<repo_name>apastorini/SDAP-GUI<file_sep>/src/app/components/files/files.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Constants } from '../../utils/Constants';
import { FileService } from '../../services/file.service';
import { HttpClient, HttpEventType, HttpHeaders } from '@angular/common/http';
import { Session } from '../../auth/loginData';
import { NgbModal, NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from '../../utils/modal/modal.component';
import 'rxjs/add/observable/interval';
import { Subscription } from 'rxjs';
import { Observable } from "rxjs";


@Component({
  selector: 'app-files',
  templateUrl: './files.component.html',
  styleUrls: []
})

export class FilesComponent implements OnInit, OnDestroy {
  fileList = [];
  porcentaje = '';
  public uploadFile = Constants.BASE_URL +  'documentController/addFileToUser';
  selectedFile: File = null;
  buttonDisabled: boolean = false;
  fileID = null;
  public sub:Subscription;




  constructor(
    private http: HttpClient,
    private fileService: FileService,
    private modalService: NgbModal
  ){

    this.sub = Observable.interval(10000)

      .subscribe((val) => {
        this.getAllUserFiles();

        console.log('TIMER FILES'); });
  }

  onFileSelected(event){
    this.porcentaje='';
    this.selectedFile = <File> event.target.files[0];

  }




  upload(){
    this.buttonDisabled=true;
    const fd = new FormData();
    console.log("ULPLOAD()")
    fd.append('file',this.selectedFile, this.selectedFile.name)
    this.http.post(this.uploadFile + "?email=" + sessionStorage.email + "&token=" + sessionStorage.token ,fd,{
      reportProgress: true,
      observe:'events'
    })
      .subscribe(event => {
        if(event.type === HttpEventType.UploadProgress){
          this.porcentaje = Math.round(event.loaded / event.total * 100) + "%";
          console.log('Upload Progress: '+ this.porcentaje)

        }else if(event.type === HttpEventType.Response){
          this.buttonDisabled = false;
            this.getAllUserFiles();

            console.log("EVENT " + JSON.stringify(event));
            console.log("EVENT " + JSON.stringify(HttpEventType.Response));

            console.log("EVENT  CODE" + JSON.stringify(event['body']['code']));

            if(JSON.stringify(event['body']['code']) == '1'){
              this.openModal(JSON.stringify(event['body']['message']),'El archivo ya existe en el sistem o fue eliminado. Cambie el nombre del archivo y vuelva a intentarlo.',"error","error");

            }
            if(JSON.stringify(event['body']['code']) == '0'){
              this.openModal(JSON.stringify(event['body']['message']),'' ,"success","success");

            }

        }

      });
  }

  uploadFlow(){
    console.log("hola "+ this.selectedFile)
    if(this.selectedFile == null){
      this.openModal("Archivo no seleccionado", "Seleccione archivo a subir e intentelo nuevamente","error","error");
    }
    else
      this.openModal("Esta seguro de subir el documento?", "Haga click en 'Confirmar' para subir el documento o en 'Cerrar' para cancelar la accion","confirm",'upload');
  }

  ngOnInit() {
    this.getAllUserFiles();
  }

  ngOnDestroy(){
    this.sub.unsubscribe();
  }

  getAllUserFiles(){
    this.fileService.userFilesList(sessionStorage.getItem('email'),sessionStorage.getItem('token'))
    .subscribe(res => {
      console.log("solucion: " + JSON.stringify(res['result']))
      if(JSON.stringify(res['result'])!="[]"){
        console.log("Entra");

        this.fileList = res['result'];

        console.log("fileList length:  " + this.fileList.length  );
      }else
      {
        this.fileList = [];
      }


    });
  }

deleteFileFlow(fileID: string){
  this.fileID=fileID;
  this.openModal("¿Esta seguro de eliminar el archivo?", "Haga click en 'Confirmar' para eliminar el archivo o en 'Cerrar' para cancelar la accion","confirm",'delete')

}

  downloadFile(fileID: string ){
    console.log("entro!!!  " + fileID)
    this.fileService.downloadFile(sessionStorage.getItem('email'),sessionStorage.getItem('token'), fileID)
    .subscribe(res => {
      console.log("entro!!!  " + res);
      console.log("entro string Importante !!!  " + JSON.stringify(res));

      var file = new Blob([res], {type: 'application/pdf'});

      this.showFile(file)
    });
  }


  deleteFile(fileID: string){
    this.fileService.deleteFile(sessionStorage.getItem('email'),sessionStorage.getItem('token'), fileID)
    .subscribe(res =>{
      this.getAllUserFiles();
      console.log("OT " + JSON.stringify(res));
      //this.openModal("NO SE ELIMINO", "FUNCION NO IMPLEMENTADA,","assets/img/red.png");
    });
  }

  showFile(blob){
    console.log("size!!!  " + blob.size);

    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blob);
      return;
    }

    // For other browsers:
    // Create a link pointing to the ObjectURL containing the blob.
    const data = window.URL.createObjectURL(blob);
    console.log("data windows url !!!  " + JSON.stringify(data));
    var link = document.createElement('a');
    link.href = data;
    link.download="file.pdf";
    console.log("data file url !!!  " + JSON.stringify(link));
    link.click();
  }



  openModal(title,text,type,action) {
    let ngbModalOptions: NgbModalOptions = {
          backdrop : 'static',
          keyboard : false
    };
    const modalRef = this.modalService.open(ModalComponent,ngbModalOptions);
    modalRef.componentInstance.title = title;
    modalRef.componentInstance.text = text;
    modalRef.componentInstance.type = type;
    modalRef.componentInstance.action = action;


    modalRef.result.then((result) => {

      console.log("resultados del modal  "+result);
      if(result=='delete'){
        this.deleteFile(this.fileID)
      }
      if(result=='upload'){
        this.upload();

      }

    }).catch((error) => {
      console.log(error);
    });
  }


  }
<file_sep>/src/app/components/home/home.component.ts
import { Component, OnInit } from '@angular/core';
import {HomeService} from '../../services/home.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: []
})
export class HomeComponent implements OnInit {
  role: string;
  cantArchivos;
  cantAnalisis;
  cantAnalisisTerminados;
  cantUsuariosDelSistema;
  cantArchivosCarpetaCompartida;
  cantArchivosEnElSistema;

  constructor(
  private homeService: HomeService

  ) { }

  ngOnInit() {
    console.log("role Nuevo " + this.role );
    this.role = sessionStorage.getItem('role');
    console.log("role Nuevo2 " + this.role );
    this.getDashBoard();

  }

  private getDashBoard(){

    this.homeService.getDashBoard(sessionStorage.getItem('email'),sessionStorage.getItem('token')).subscribe(res => {
    console.log(" cantArchivos: " + JSON.stringify(res)  );
    console.log('%c getDashBoard', 'color: orange;');

    this.cantArchivos = res['result'][0].cantArchivos;
    this.cantAnalisis = res['result'][0].cantAnalisis;
    this.cantAnalisisTerminados = res['result'][0].cantAnalisisTerminados;
    this.cantUsuariosDelSistema = res['result'][0].cantUsuariosDelSistema;
    this.cantArchivosCarpetaCompartida = res['result'][0].cantArchivosCarpetaCompartida;
    this.cantArchivosEnElSistema = res['result'][0].cantArchivosEnElSistema;
    });

  }

}
<file_sep>/src/app/services/payload/PasswordPayload.ts
export class PasswordPayload{
    userEmail: string;
}
<file_sep>/src/app/auth/loginData.ts
export interface Login {
  mail: string;
  password: string;
}
export interface Logout {
  mail: string;
  password: string;
  token:string;
}

export interface Session {
  email:string;
  token:string;
  role:string;
}
<file_sep>/src/app/components/password/password.component.ts
import { Component, OnInit, Inject } from '@angular/core';
import { Router,Routes, RouterModule} from '@angular/router';
import { PasswordPayload } from '../../services/payload/PasswordPayload';
import { LoginService } from '../../services/login.service';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NgbModal,NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from '../../utils/modal/modal.component';





@Component({
  selector: 'app-password',
  templateUrl: './password.component.html',
  styleUrls: []
})
export class PasswordComponent implements OnInit {

  userEmail:string;
  form: FormGroup;


  constructor(
    private router: Router,
    private loginService: LoginService,
    private fb: FormBuilder,
    private modalService: NgbModal
  ) { }

  ngOnInit() {
    this.form = this.fb.group({
      userEmail: ['', Validators.required]
    });
  }

  onSubmitClicked() {
    const payload = new PasswordPayload();
    payload.userEmail = this.userEmail;
    console.log("email." + this.form.get("userEmail").value);

    if (this.form.valid) {
      this.loginService.recuperarPassword(this.form.get("userEmail").value)
      .subscribe(res => {

        if(res['code']===1){

          this.openModal(res["message"], "","error","error")

        }else
          this.openModal("Email enviado", "","success","success")

  console.log("asdasdsa" + JSON.stringify(res))
  //this.openModal("Email enviado", "","success","success")

      });







    }
  }
  goToLogin(){
    this.router.navigate(['login']);
  }


  openModal(title,text,type,action) {
    let ngbModalOptions: NgbModalOptions = {
          backdrop : 'static',
          keyboard : false
    };
    const modalRef = this.modalService.open(ModalComponent,ngbModalOptions);
    modalRef.componentInstance.title = title;
    modalRef.componentInstance.text = text;
    modalRef.componentInstance.type = type;
    modalRef.componentInstance.type = action;

    modalRef.result.then((result) => {
      console.log("resultados del modal  "+result);
      if(result=='edit'){

      }
    }).catch((error) => {
      console.log(error);
    });
  }

}
<file_sep>/src/app/components/help/help.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-help',
  templateUrl: './help.component.html',
  styleUrls: []
})
export class HelpComponent implements OnInit {

  role: string;
  email: string;

  constructor() { }


  ngOnInit() {
      this.role = sessionStorage.getItem('role');
      this.email = sessionStorage.getItem('email');

  }

}
<file_sep>/src/app/components/shared/navbar/navbar.component.ts
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../../auth/auth.service';
import { StorageService } from '../../../auth/storageService';
import { Session } from '../../../auth/loginData';
import { Observable } from 'rxjs/Observable';
import {HttpClientModule} from '@angular/common/http';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: []
})

export class NavbarComponent implements OnInit {

  isLoggedIn$: Observable<boolean>;
  email: string;
  role: string;
  name: string;


  constructor(
    private authService: AuthService,
    private storageService: StorageService
  ) { }


  ngOnInit() {
    this.isLoggedIn$ = this.authService.isLoggedIn; // {2}
    console.log("si funciona bien "+ this.isLoggedIn$);

    this.email = sessionStorage.getItem('email');
    this.role = sessionStorage.getItem('role');
    this.name = sessionStorage.getItem('name');


    this.storageService.watchStorage().subscribe((data:string) => {

      console.log("soy Data "+ data);

      this.email = sessionStorage.getItem('email');
      this.role = sessionStorage.getItem('role');

    //this will call whenever your localStorage data changes


    // use localStorage code here and set your data here for ngFor
    })

  }

  onLogout(){
    this.authService.logout();                      // {3}
  }
}
<file_sep>/src/app/components/login/login.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { AuthService } from '../../auth/auth.service';
import { Router,Routes, RouterModule} from '@angular/router';
import { Constants } from '../../utils/Constants';
import { HttpClient, HttpEventType, HttpHeaders } from '@angular/common/http';
import { NgbModal,NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from '../../utils/modal/modal.component';


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: []
})
export class LoginComponent implements OnInit {
  registerForm: FormGroup;                    // {1}
  private formSubmitAttempt: boolean; // {2}

  submitted = false;
  emailExists:boolean;      // {1}


  constructor(
    private http: HttpClient,
    private fb: FormBuilder,         // {3}
    private authService: AuthService, // {4}
    private router: Router,
    private modalService: NgbModal
  ) {}

  ngOnInit() {
    this.authService.logout()
    this.registerForm = this.fb.group({     // {5}
      mail: ['', Validators.required],
      password: ['', Validators.required]
    });
  }

  isFieldInvalid(field: string) { // {6}
    return (
      (!this.registerForm.get(field).valid && this.registerForm.get(field).touched) ||
      (this.registerForm.get(field).untouched && this.formSubmitAttempt)
    );
  }

  onSubmit() {
    if (this.registerForm.valid) {

      this.authService.login(this.registerForm.value);
       // {7}
    }else{
      this.openModal("Error en login","Los campos Email y Contraseña deben tener informacion.","error","error");
    }
    this.formSubmitAttempt = true;             // {8}
  }

  goToPassword(){
    this.router.navigate(['password']);
  }

   goToSignin(){
     this.router.navigate(['signin']);
  }

  // convenience getter for easy access to form fields
 get f() { return this.registerForm.controls; }

   openModal(title,text,type,action) {
     let ngbModalOptions: NgbModalOptions = {
           backdrop : 'static',
           keyboard : false
     };
     const modalRef = this.modalService.open(ModalComponent,ngbModalOptions);
     modalRef.componentInstance.title = title;
     modalRef.componentInstance.text = text;
     modalRef.componentInstance.type = type;
     modalRef.componentInstance.action = action;

     modalRef.result.then((result) => {
       console.log("resultados del modal  "+result);
       if(result=='edit'){

       }
     }).catch((error) => {
       console.log(error);
     });
   }
  }
<file_sep>/src/app/app.module.ts
//Modulos
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { FormsModule } from '@angular/forms';
// import { AppMaterialModule } from './app-material/app-material.module';
import { HttpClient } from 'selenium-webdriver/http';
import { HttpClientModule } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ReactiveFormsModule } from '@angular/forms';
//import { FileSelectDirective } from 'ng2-file-upload';
// import { FileUploadModule} from 'ng2-file-upload';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

//Components
import { NavbarComponent } from './components/shared/navbar/navbar.component';
import { AppComponent } from './app.component';
import { LoginComponent } from './components/login/login.component';
import { FilesComponent } from './components/files/files.component';
import { PasswordComponent } from './components/password/password.component';
import { CreateUserComponent } from './components/create-user/create-user.component';
import { EditUserComponent } from './components/edit-user/edit-user.component';
import { HomeComponent } from './components/home/home.component';
//import { WebmasterValidationComponent } from './webmaster-validation/webmaster-validation.component';
//import { ConfirmationDialogComponent } from './components/shared/confirmation-dialog/confirmation-dialog.component';

//Servicios
import { LoginService } from './services/login.service';
import { AuthService } from './auth/auth.service';
import { AnalyzeService } from './services/analyze.service';
import { UserService } from './services/user.service';
import { FileService } from './services/file.service';
import { StorageService } from './auth/storageService';
import { HomeService } from './services/home.service';
//import { DriveResource } from './services/drive-resource.service';

//Routing
import { APP_ROUTING } from './app.routes'
import { AuthGuard } from './auth/auth.guard';
import { FooterComponent } from './components/shared/footer/footer.component';
import { AnalyzeComponent } from './components/analyze/analyze.component';
import { UniqueEmailValidatorDirective } from './validators/unique-email-validator.directive';
import { ReportsComponent } from './components/reports/reports.component';
import { GoogleDriveComponent } from './components/google-drive/google-drive.component';
import { EditProfileComponent } from './components/edit-profile/edit-profile.component';
import { ModalComponent } from './utils/modal/modal.component';
import { GapiSession } from '../infrastructure/sessions/gapi.session';
import { AppRepository } from '../infrastructure/repositories/app.repository';
import { FileRepository } from '../infrastructure/repositories/file.repository';
import { UserRepository } from '../infrastructure/repositories/user.repository';
import { AppContext } from '../infrastructure/app.context';
import { AppSession } from '../infrastructure/sessions/app.session';
import { UserSession } from '../infrastructure/sessions/user.session';
import { FileSession } from '../infrastructure/sessions/file.session';
import { BreadCrumbSession } from '../infrastructure/sessions/breadcrumb.session';
import { DialogOneInputComponent } from './components/dialogoneinput/dialogoneinput.component';
import { BreadCrumbComponent } from './components/breadcrumb/breadcrumb.component';
import { BreadCrumbItemComponent } from './components/breadcrumb/breadcrumbitem/breadcrumbitem.component';
import { MatButtonModule, MatIconModule, MatMenuModule, MatTableModule, MatBottomSheetModule, MatDialogModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatToolbarModule, MatProgressSpinnerModule, MatListModule } from '@angular/material';
import { PageNotFoundComponent } from './components/page-not-found/page-not-found.component';
import { HelpComponent } from './components/help/help.component';
import { NewPasswordComponent } from './components/new-password/new-password.component';
import { ChangePasswordComponent } from './components/change-password/change-password.component';




export function initGapi(gapiSession: GapiSession) {
  return () => gapiSession.initClient();
}

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    NavbarComponent,
    FilesComponent,
    PasswordComponent,
    CreateUserComponent,
    EditUserComponent,
    HomeComponent,
    FooterComponent,
    AnalyzeComponent,
    UniqueEmailValidatorDirective,
    ReportsComponent,
    GoogleDriveComponent,
    EditProfileComponent,
    ModalComponent,
    DialogOneInputComponent,
    BreadCrumbComponent,
    BreadCrumbItemComponent,
    PageNotFoundComponent,
    HelpComponent,
    NewPasswordComponent,
    ChangePasswordComponent

  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule,
    BrowserAnimationsModule,
    FormsModule,
    APP_ROUTING,
    HttpClientModule,
    NgbModule.forRoot(),
    MatBottomSheetModule,
    MatButtonModule,
    MatDialogModule,
    MatFormFieldModule,
    MatIconModule,
    MatInputModule,
    MatMenuModule,
    MatProgressSpinnerModule,
    MatSelectModule,
    MatTableModule,
    MatToolbarModule,
    MatListModule,
  ],
  providers: [
    AuthService,
    AuthGuard,
    LoginService,
    UserService,
    FileService,
    AnalyzeService,
    StorageService,
    HomeService,
    { provide: APP_INITIALIZER, useFactory: initGapi, deps: [GapiSession], multi: true },
    AppContext,
    AppSession,
    FileSession,
    GapiSession,
    UserSession,
    BreadCrumbSession,
    AppRepository,
    FileRepository,
    UserRepository,

  ],
  bootstrap: [AppComponent],
  entryComponents: [
  ModalComponent
]
})
export class AppModule { }
<file_sep>/src/app/components/reports/reports.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import {AnalyzeService} from '../../services/analyze.service';
import { HttpClient, HttpEventType, HttpHeaders } from '@angular/common/http';
import 'rxjs/add/observable/interval';
import { Subscription, Observable } from 'rxjs';

@Component({
  selector: 'app-reports',
  templateUrl: './reports.component.html',
  styleUrls: []
})
export class ReportsComponent implements OnInit, OnDestroy {
  reportsList = [];
  public sub:Subscription;

  constructor(
  private analyzeService: AnalyzeService,
  private http: HttpClient
  ) {

    this.sub = Observable.interval(10000)
      .subscribe((val) => {
        this.getReportList()
        console.log('TIMER!'); });
  }

  ngOnInit() {
    this.getReportList()
  }

  ngOnDestroy(){
    this.sub.unsubscribe();
  }

  getReportList(){

    this.analyzeService.listarAnalisisPorUsuario().subscribe(res=>{
      console.log("FLSG")

      if(JSON.stringify(res['result']) != "[]"){
        this.reportsList = res['result'];
          console.log("entro11111!!!  " + JSON.stringify(res['result']))
          console.log("entro!!!  " + JSON.stringify(res['result'][2]))

      }
  });


  }

  downloadReport(idAnalisis: string ){
    console.log("idAnalisis!!!  " + idAnalisis)
    this.analyzeService.reporteAnalisis(sessionStorage.getItem('email'),sessionStorage.getItem('token'), idAnalisis)
    .subscribe(res => {
      console.log("entro!!!  " + res);
      console.log("entro string !!!  " + JSON.stringify(res));

      var file = new Blob([res], {type: 'application/pdf'});

      this.showFile(file)

    });

  }

  showFile(blob){
    console.log("size!!!  " + blob.size);

    // IE doesn't allow using a blob object directly as link href
    // instead it is necessary to use msSaveOrOpenBlob
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blob);
      return;
    }

    // For other browsers:
    // Create a link pointing to the ObjectURL containing the blob.
    const data = window.URL.createObjectURL(blob);
    console.log("data windows url !!!  " + JSON.stringify(data));
    var link = document.createElement('a');
    link.href = data;
    link.download="file.pdf";
    console.log("data file url !!!  " + JSON.stringify(link));
    link.click();


  }

}
<file_sep>/src/app/services/user.service.ts
import { Injectable } from '@angular/core';
import { Constants } from '../utils/Constants';
import { HttpClient, HttpHeaders,HttpParams } from '@angular/common/http';
import { LoginPayload } from './payload/LoginPayload';
import { ErrorHandler } from '../utils/ErrorHandler';
import { RequestOptions } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
import { User } from '../models/User';
import { URLSearchParams } from '@angular/http';

@Injectable()
export class UserService {

  private isUsedId = Constants.BASE_URL +  'loginController/isUsedId';
  private passwordByEmail = Constants.BASE_URL + 'loginController/sendPasswordByMail';
  private checkUserUrl = Constants.BASE_URL + 'loginController/isUsedId';
  private createUserUrl = Constants.BASE_URL + 'systemController/createUser';
  private modifyUserUrl = Constants.BASE_URL + 'systemController/modifyUser';
  private secureEchoUrl = Constants.BASE_URL + 'Sdp/api/secure/echo/andrei';
  private allUsersUrl = Constants.BASE_URL + 'systemController/listarUsuarios';
  private recuperarContraseniaUrl = Constants.BASE_URL + 'systemController/recuperarContrasenia';
  private changePasswordURL = Constants.BASE_URL + 'systemController/changePassword';
  constructor(private http: HttpClient, private router: Router) { }

  public doLogin(payload: LoginPayload): Observable<any>{
    return this.http.post(this.checkUserUrl, payload, {responseType: 'text'}).pipe(
      catchError(new ErrorHandler().handleError('LoginService', null))
    );
  }

  public createUser(user: User){

    if (user.name !== '' && user.password !== '') { // {3}

        let headers = new HttpHeaders();
        headers = headers.set('Content-Type', 'application/json; charset=utf-8');
        headers.append('Access-Control-Allow-Origin','*');
        console.log('headers' + headers.get('Content-Type'));
        console.log('User los datos del usuairooooooooo  ::::::::::::::: ' + JSON.stringify(user));
        console.log('headers' + user.roles);

        return this.http.post(this.createUserUrl+"?email=" + sessionStorage.getItem('email') + "&token=" + sessionStorage.getItem('token'), user, {headers: headers})
        //this.http.post(this.createUserUrl, user, {headers: headers})
           //.subscribe(respuesta =>JSON.stringify(console.log(respuesta)))
    }
  }

  public getAllUsers(){

    let skeleton = {
      "mail": "string",
      "password": "<PASSWORD>",
      "roleDTOs": [
        {
          "desc": "string",
          "id": 0,
          "name": "string"
        }
      ],
      "token": "string"
    }

    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/json; charset=utf-8');
    headers.append('Access-Control-Allow-Origin','*');
    console.log('headers' + headers.get('Content-Type'));
    return  this.http.post(this.allUsersUrl, skeleton, {headers: headers})
    //this.http.post(this.createUserUrl, user, {headers: headers})
       //.subscribe(respuesta =>JSON.stringify(console.log(respuesta))
  }



public recuperarContrasenia(email:string , token :string , password :string){
  console.log("EMAIL, TOKEN, PASSWORD:     " + email + "   " + token + "   " + password)

  let skeleton = {
    "email": email,
    "enable": true,
    "name": "string",
    "password": <PASSWORD>,
    "passwordExpiredDate": "string",
    "passwordToken": token,
    "roles": [
      {
        "desc": "string",
        "id": 0,
        "name": "string"
      }
    ],
    "secondName": "string",
    "token": "string"
  }
  console.log("IMPORTANTE    TOKEN     " + skeleton.token)

  let headers = new HttpHeaders();
  headers = headers.set('Content-Type', 'application/json; charset=utf-8');
  headers.append('Access-Control-Allow-Origin','*');
  console.log('headers' + headers.get('Content-Type'));
  return  this.http.post(this.recuperarContraseniaUrl, skeleton, {headers: headers})

}

  public modifyUser(user: User){
    console.log('1');
    if (user.name !== '' && user.password !== '') { // {3}

        console.log('2');
        let headers = new HttpHeaders();
        headers = headers.set('Content-Type', 'application/json; charset=utf-8');
        headers.append('Access-Control-Allow-Origin','*');
        console.log('headers' + headers.get('Content-Type'));
        return  this.http.post(this.modifyUserUrl+"?email=" + sessionStorage.getItem('email') + "&token=" + sessionStorage.getItem('token'), user, {headers: headers})
        //this.http.post(this.createUserUrl, user, {headers: headers})
           //.subscribe(respuesta =>JSON.stringify(console.log(respuesta)))
    }
  }

  public changePassword(password){
    if (password !== '') { // {3}

        let headers = new HttpHeaders();
        headers = headers.set('Content-Type', 'application/json; charset=utf-8');
        headers.append('Access-Control-Allow-Origin','*');
        console.log('headers' + headers.get('Content-Type'));
        return  this.http.post(this.changePasswordURL+"?email=" + sessionStorage.getItem('email') + "&token=" + sessionStorage.getItem('token') + "&password=" + password, {headers: headers})
        //this.http.post(this.createUserUrl, user, {headers: headers})
           //.subscribe(respuesta =>JSON.stringify(console.log(respuesta)))
    }
  }



  public exist(email: string){
    let params = new HttpParams().set('email', email);
    params.append('email', email);
    return this.http.get(this.checkUserUrl, {params:params})
      .map(res =>{console.log("exist----> "+res)});
      //.map(res =>{return res});
      //.subscribe(res =>{console.log(res)});
      //.subscribe(res =>{return res});
  }

  public doSecureEcho(authToken: string): Observable<any>{
    let httpParams = new HttpParams()
        .append("mail", "<EMAIL>")
        .append("password", "<PASSWORD>")
    let headers = new HttpHeaders();
    headers = headers.set('x-auth-token', authToken);
    headers = headers.append('Content-Type', 'text/xml');
    return this.http.get(this.secureEchoUrl, {headers: headers,responseType: 'text'}).pipe(
      catchError(new ErrorHandler().handleError('LoginService', null))
    );
  }


}
<file_sep>/src/app/validators/async-email.validator.ts
  import { AbstractControl } from '@angular/forms';
  import { UserService } from '../services/user.service';

  export class ValidateEmailNotTaken {
    public createValidator(userService: UserService) {
      return (control: AbstractControl) => {
        return userService.exist(control.value).map(res => {
          return res ? true : { emailTaken: true };
        });
      };
    }
  }
<file_sep>/src/app/services/login.service.ts
import { Injectable } from '@angular/core';
import { Constants } from '../utils/Constants';
import { HttpClient, HttpHeaders,HttpParams } from '@angular/common/http';
import { LoginPayload } from './payload/LoginPayload';
import { ErrorHandler } from '../utils/ErrorHandler';
import { RequestOptions } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
import { User } from '../models/User';
import { URLSearchParams } from '@angular/http';

@Injectable()
export class LoginService {
  private isUsedId = Constants.BASE_URL +  'loginController/isUsedId';
  private passwordByEmail = Constants.BASE_URL + 'loginController/sendPasswordByMail';
  private checkUserUrl = Constants.BASE_URL + 'loginController/isUsedId';
  private createUserUrl = Constants.BASE_URL + 'systemController/createUser';
  private secureEchoUrl = Constants.BASE_URL + 'Sdp/api/secure/echo/andrei';
  constructor(private http: HttpClient, private router: Router) { }

  public doLogin(payload: LoginPayload): Observable<any>{
    return this.http.post(this.checkUserUrl, payload, {responseType: 'text'}).pipe(
      catchError(new ErrorHandler().handleError('LoginService', null))
    );
  }

//<EMAIL>
  public signin(user: User){

    if (user.name !== '' && user.password !== '') { // {3}
      console.log("ENTRO"+ user.name);

        let bool=  this.exist(user.email);

          if (!this.exist(user.email)){
            console.log("ENTRO"+ user);
            //<EMAIL>

            //this.http.post(this.checkUserUrl, user, {responseType: 'text'}).subscribe(respuesta =>this.manageLoginResponse(respuesta));
            this.http.post(this.createUserUrl, user, {responseType: 'text'})
              .subscribe(respuesta =>localStorage.setItem('currentUser', JSON.stringify({ token: respuesta })))

            let currentUser = JSON.parse(localStorage.getItem('currentUser'));
            localStorage.setItem('token',currentUser.token);
            localStorage.setItem('userName',currentUser.name);
            //localStorage.setItem('userID',currentUser.userID);

            this.router.navigate(['/home']);
          }
          else{
              console.log("NO EXISTIO: "+user.email);
          }
    }
  }




  public exist(email: string){
    console.log(this.checkUserUrl);
    let params = new HttpParams().set('email', email);
    params.append('email', email);
    console.log("paramsssss= " + params);

    return this.http.get(this.checkUserUrl, {params:params})
      .subscribe(respuesta =>{return respuesta});
  }

  public doSecureEcho(authToken: string): Observable<any>{
    let headers = new HttpHeaders();
    headers = headers.set('x-auth-token', authToken);
    headers = headers.append('Content-Type', 'text/xml');
    return this.http.get(this.secureEchoUrl, {headers: headers,responseType: 'text'}).pipe(
      catchError(new ErrorHandler().handleError('LoginService', null))
    );
  }



getIsUsedId(eMail: string): boolean{
  if (eMail!== '') { // {3}

        console.log("email: "+ eMail);
        this.http.post(this.passwordByEmail, eMail, {responseType: 'text'})
          .subscribe(respuesta =>localStorage.setItem('currentUser', JSON.stringify({ token: respuesta })))
        return true;
  }
}


recuperarPassword(eMail: string): Observable<any>{
  if (eMail!== '') { // {3}

        console.log("email!!!!!  : "+ eMail);

        let headers = new HttpHeaders();
        headers = headers.append('Content-Type', 'text/xml');
        //this.http.post(this.checkUserUrl, user, {responseType: 'text'}).subscribe(respuesta =>this.manageLoginResponse(respuesta));
        return this.http.get(this.passwordByEmail + "?email=" + eMail)
        //localStorage.setItem('userID',currentUser.userID);
  }
}


 getPasswordByEmail(eMail: string ){
    if (eMail!== '') { // {3}

          console.log("email: "+ eMail);
          //this.http.post(this.checkUserUrl, user, {responseType: 'text'}).subscribe(respuesta =>this.manageLoginResponse(respuesta));
          this.http.post(this.passwordByEmail, eMail, {responseType: 'text'})
            .subscribe(respuesta =>localStorage.setItem('currentUser', JSON.stringify({ token: respuesta })))
          //localStorage.setItem('userID',currentUser.userID);

          this.router.navigate(['/home']);

    }
  }

}
<file_sep>/src/app/services/payload/TokenParams.ts
export class TokenParams{
  token_type: string;
  token: string;
}
<file_sep>/src/app/services/home.service.ts
import { Injectable } from '@angular/core';
import { Constants } from '../utils/Constants';
import { HttpClient, HttpHeaders,HttpParams} from '@angular/common/http';
import { ErrorHandler } from '../utils/ErrorHandler';
import { RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { catchError } from 'rxjs/operators';

@Injectable()
export class HomeService {

  private dashBoardUrl = Constants.BASE_URL + 'systemController/getDashBoard';

  constructor(
    private http: HttpClient
  ) { }


getDashBoard(email: string, token: string): Observable<any>{
  return this.http.post(this.dashBoardUrl + "?email=" + email + "&token=" + token , {responseType: 'text'})
  //.pipe(catchError(new ErrorHandler().handleError('LoginService', null)));
}

}
<file_sep>/src/app/components/create-user/create-user.component.ts
import { Component, OnInit } from '@angular/core';
import { UserService} from '../../services/user.service';
//import { AuthService, GoogleLoginProvider } from "angular5-social-login";
import { HttpClient} from '@angular/common/http'
import { Router,Routes, RouterModule} from '@angular/router';
import { FormGroup, FormBuilder, Validators, FormControl, AsyncValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms';
import { AuthService } from '../../auth/auth.service';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';
import { NgbModal,NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from '../../utils/modal/modal.component';



 //[ existingMobileNumberValidator(this.userService),
@Component({
  selector: 'app-create-user',
  templateUrl: './create-user.component.html',
  styleUrls: []
})

export class CreateUserComponent implements OnInit {
  registerForm: FormGroup;
  // role: FormGroup;
  submitted = false;
  emailExists:boolean;
  successfullySaved = false;
  errorSaved = false;
  buttonDisabled: boolean = false;
  private formSubmitAttempt: boolean; // {2}

  rolesList = [{'name':'ADMIN'},{'name':'TUTOR'}]

  constructor(
    private userService: UserService,
    private http: HttpClient,
    private router: Router,
    private fb: FormBuilder,
    private authService: AuthService,
    private modalService: NgbModal
  )
    { }

  ngOnInit() {
    this.registerForm = this.fb.group({     // {5}
      name: ['', Validators.required],
      secondName: ['', Validators.required],
      email: ['',
      [Validators.required,Validators.email]],
      roles: ['',Validators.required]
      // roles: this.fb.group({
      //    rolname:['']
      //  })
    });
  }

  // convenience getter for easy access to form fields
 get f() { return this.registerForm.controls; }

 onSubmit() {
        this.submitted = true;
        // stop here if form is invalid
        if (this.registerForm.invalid) {
            return;
        }
        else{

        if(this.registerForm.value.roles == "TUTOR"){
          this.registerForm.value.roles= [{'name':'TUTOR'}]
        }else{
          this.registerForm.value.roles= [{'name':'ADMIN'}]
        }

          this.userService.createUser(this.registerForm.value).subscribe(res =>{
            console.log("DATOOOOS   " + JSON.stringify(res) + " +++++++");
            console.log("DATOOOOS   " + JSON.stringify(res['code']));
            console.log(typeof res['code']);


            if(res['code']==0){
              this.successfullySaved = true;
                this.openModal("Usuario creado", "","success","success");
                this.submitted = false;
                this.registerForm.reset();
              //alert("")
            }
            else{
              this.errorSaved = true;
              this.openModal("Error al crear usuario", "","success","success");
            //  alert("Error al crear usuario")
            }
          })
    }
}

  goToLogin(){
    this.router.navigate(['login']);
  }

  isFieldInvalid(field: string) { // {6}
    return (
      (!this.registerForm.get(field).valid && this.registerForm.get(field).touched) ||
      (this.registerForm.get(field).untouched && this.formSubmitAttempt)
    );
  }

  userExist(){
    let value = this.userService.exist(this.registerForm.controls['email'].value);
    //console.log(value);
    this.registerForm.controls['email'].setErrors({'incorrect': value});
  }

  openModal(title,text,type,action) {
    let ngbModalOptions: NgbModalOptions = {
          backdrop : 'static',
          keyboard : false
    };
    const modalRef = this.modalService.open(ModalComponent,ngbModalOptions);
    modalRef.componentInstance.title = title;
    modalRef.componentInstance.text = text;
    modalRef.componentInstance.type = type;
    modalRef.componentInstance.type = action;


    modalRef.result.then((result) => {
      console.log("resultados del modal  "+result);
    }).catch((error) => {
      console.log(error);
    });
  }




}
<file_sep>/src/app/models/User.ts

export class Role{
  "desc":string;
  "id":string;
  "name":string

}


export class User {
    name: string;
    secondName: string;
    Name: string;
    email: string;
    googleMail: string;
    password: string;
    passwordGoogle: string;
    roles:Role;
    
}
<file_sep>/src/app/components/change-password/change-password.component.ts
import { Component, OnInit } from '@angular/core';
import { UserService} from '../../services/user.service';
//import { AuthService, GoogleLoginProvider } from "angular5-social-login";
import { HttpClient} from '@angular/common/http'
import { Router,Routes, RouterModule,ActivatedRoute} from '@angular/router';
import { FormGroup, FormBuilder, Validators, FormControl, AsyncValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';
import { NgbModal,NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from '../../utils/modal/modal.component';


@Component({
  selector: 'app-change-password',
  templateUrl: './change-password.component.html',
  styleUrls: []
})
export class ChangePasswordComponent implements OnInit {

  registerForm: FormGroup;
  submitted = false;


  constructor(

    private userService: UserService,
    private http: HttpClient,
    private router: Router,
    private fb: FormBuilder,
    private modalService: NgbModal,
    private route: ActivatedRoute
  ) {}

    // convenience getter for easy access to form fields
   get f() { return this.registerForm.controls; }

  ngOnInit() {

    this.registerForm = this.fb.group({     // {5}
    password: ['', [Validators.required,Validators.minLength(6)]],
    confirmation: ['', Validators.required]
    });
  }

  onSubmit() {
    this.submitted = true;
    if (this.registerForm.invalid) {
      return;
    }

    if(this.registerForm.value.password==this.registerForm.value.confirmation){

      this.openModal("¿Esta seguro de querer reestablecer la contraseña?","Haga click en 'Confirmar' para reestablecer su contraseña o en 'Cerrar' para cancelar la accion","confirm","modificar")

    }
    else
    {
      this.openModal("Error: Las contraseñas no coinciden","Los campos 'Password' y 'Confirmacion' deben coincidir, modifiquielo e intentelo otra vez","error","error")

    }
  }


  changePassword(){
    this.userService.changePassword(this.registerForm.get("password").value).subscribe((res)=>{
      this.openModal("Contraseña modificada","","success","success")

       console.log("recuperarContrasena     "+ JSON.stringify(res));

    })
  }


    openModal(title,text,type,action) {
      let ngbModalOptions: NgbModalOptions = {
            backdrop : 'static',
            keyboard : false
      };
      const modalRef = this.modalService.open(ModalComponent,ngbModalOptions);
      modalRef.componentInstance.title = title;
      modalRef.componentInstance.text = text;
      modalRef.componentInstance.type = type;
      modalRef.componentInstance.action = action;


      modalRef.result.then((result) => {
        console.log("resultados del modal  "+result);

        if(result=="modificar"){
          this.changePassword()

        }
        if(result=="exito"){

        }

      }).catch((error) => {
        console.log(error);
      });
    }


  }
<file_sep>/src/app/components/edit-profile/edit-profile.component.ts
import { Component, OnInit } from '@angular/core';
import { UserService} from '../../services/user.service';
import { HttpClient} from '@angular/common/http'
import { Router,Routes, RouterModule} from '@angular/router';
import { FormGroup, FormBuilder, Validators, FormControl, AsyncValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms';
import { AuthService } from '../../auth/auth.service';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';
import { NgbModal,NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from '../../utils/modal/modal.component';


@Component({
  selector: 'app-edit-profile',
  templateUrl: './edit-profile.component.html',
  styleUrls: []
})
export class EditProfileComponent implements OnInit {
  registerForm: FormGroup;
  submitted = false;
  emailExists:boolean;      // {1}
  private formSubmitAttempt: boolean; // {2}
  role= "";

  constructor(
    private userService: UserService,
    private http: HttpClient,
    private router: Router,
    private fb: FormBuilder,
    private authService: AuthService,
    private modalService: NgbModal,
    //private user: User
  )
    { }

  ngOnInit() {
    this.getAllUsers();

    this.registerForm = this.fb.group({     // {5}
      name: ['', Validators.required],
      secondName: ['', Validators.required],
      email: [sessionStorage.getItem('email'),
      [Validators.required,Validators.email]]
    });
  }

  // convenience getter for easy access to form fields
  get f() { return this.registerForm.controls; }

  onSubmit() {
          this.submitted = true;
   
          // stop here if form is invalid
          if (this.registerForm.invalid) {
            this.openModal("Error al editar perfil", "Uno o mas campos son incorrectos, complete los campos correctamente y vuelva a intentarlo","error","error");
              return;
          }
        else{

          this.openModal("¿Esta seguro de modificar su perfil?", "Haga click en 'Confirmar' para modificar el perfil o en 'Cerrar' para cancelar la accion",'confirm',"edit")


      }
  }


editarPerfil(){
  console.log("MIS DATOS  "+ this.registerForm.value)

  this.userService.modifyUser(this.registerForm.value).subscribe(res =>{

      this.openModal("Perfil modificado", "","success","success");

  })
}


  goToLogin(){
    this.router.navigate(['login']);
  }

  isFieldInvalid(field: string) { // {6}
    return (
      (!this.registerForm.get(field).valid && this.registerForm.get(field).touched) ||
      (this.registerForm.get(field).untouched && this.formSubmitAttempt)
    );
  }

  userExist(){
    let value = this.userService.exist(this.registerForm.controls['email'].value);
    console.log(value);
    this.registerForm.controls['email'].setErrors({'incorrect': value});
  }

  getAllUsers(){
    this.userService.getAllUsers().subscribe(res=>{
      res['result'].forEach(variable => {

        if(variable.email==sessionStorage.getItem('email')){
        //  this.user = variable;
        this.registerForm.setValue({
           name: variable.name,
           secondName: variable.secondName,
           email:sessionStorage.getItem('email')

           //enablecheck: this.fileList[event.target.value].enable
        });

        this.role=variable.roles[0].name;

        }

      });

      //this.user = res['result'];



    })
  }

  goToChangePassword(){
    this.router.navigate(['change-password']);
  }


  openModal(title,text,type,action) {
    let ngbModalOptions: NgbModalOptions = {
          backdrop : 'static',
          keyboard : false
    };
    const modalRef = this.modalService.open(ModalComponent,ngbModalOptions);
    modalRef.componentInstance.title = title;
    modalRef.componentInstance.text = text;
    modalRef.componentInstance.type = type;
    modalRef.componentInstance.action = action;

    modalRef.result.then((result) => {
      console.log("resultados del modal  "+result);
      if(result=='edit'){
        this.editarPerfil();

      }
    }).catch((error) => {
      console.log(error);
    });
  }



  }
<file_sep>/src/app/utils/Constants.ts
export class Constants{
  static BASE_URL:string = "http://ec2-18-215-158-201.compute-1.amazonaws.com:8888/";
  //static BASE_URL:string = "http://localhost:8080/";
}
<file_sep>/src/app/utils/modal/modal.component.ts
import { Component, Input, OnInit } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: []
})
export class ModalComponent implements OnInit {
  @Input() text = ``;
  @Input() type = ``;
  @Input() title = ``;
  @Input() action = ``;


  constructor(
    public activeModal: NgbActiveModal,
  )
   {
     console.log("DATA MODAL>  "+ this.text + "   " +this.type + "   " +this.title + "   " +this.action)
   }

  closeModal() {
  this.activeModal.close('Modal Closed');
}

  ngOnInit() {
    console.log("TEXT:   "+ this.text + "   TYPE:    " +this.type + "    TITLE:   " +this.title + "     ACTION:   " +this.action)
  }


}
<file_sep>/src/app/validators/unique-email-validator.directive.ts
import { Directive } from '@angular/core';
import { NG_ASYNC_VALIDATORS, AsyncValidator, AbstractControl, ValidationErrors } from '@angular/forms';
import { UserService } from '../services/user.service';
import { Observable} from 'rxjs';
import { map} from 'rxjs/operators';

@Directive({
  selector: '[uniqueEmail]',
  providers:[
    {
      provide: NG_ASYNC_VALIDATORS,
      useExisting:UniqueEmailValidatorDirective,
      multi: true
    }
  ]
})

export class UniqueEmailValidatorDirective implements AsyncValidator {

  constructor(private userService:UserService) { }

  validate(c:AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null >{
    return this.userService.exist(c.value).pipe(
      map(res =>{
        return (res) ? {'uniqueEmail': true} : null;
      })
    );

  }

}
<file_sep>/src/app/components/analyze/analyze.component.ts
import { Component, OnInit } from '@angular/core';
import { FileService } from '../../services/file.service';
import { AnalyzeService } from '../../services/analyze.service';
import { HttpClient} from '@angular/common/http'
import { Router,Routes, RouterModule} from '@angular/router';
import { FormGroup, FormBuilder, Validators, FormControl, AsyncValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms';
import { AuthService } from '../../auth/auth.service';
import { Observable } from "rxjs";
import 'rxjs/add/operator/map';
import { NgbModal,NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from '../../utils/modal/modal.component';

@Component({
  selector: 'app-analyze',
  templateUrl: './analyze.component.html',
  styleUrls: []
})
export class AnalyzeComponent implements OnInit {
   fileToAnalize:string;
   fileList = [];
   filesToCompare = [];
   sharedFileList = [];
   filesToCompareShared = [];
   allFilesToCompare = [];
   buttonDisabled : boolean = false;
   selectedAll: boolean = false;
   selectedAllShared: boolean = false;


   constructor(
    private analyzeService: AnalyzeService,
    private fileService: FileService,
    private http: HttpClient,
    private router: Router,
    private fb: FormBuilder,
    private authService: AuthService,
    private modalService: NgbModal

  ) {

    this.fileToAnalize = '-1';
    this.getAllUserFiles();
    this.getSharedFiles();


  }

  doAnalysis(){
          this.analyzeService.iniciarAnalisis(this.fileToAnalize,this.allFilesToCompare).subscribe(res=>{
            console.log("ANALISIS   " + JSON.stringify(res));
            this.openModal("Analisis Iniciado","Podes ver el estado de este y otros analisis en la pestaña Reportes.","success","success")
            this.uncheckAll();
          });
  }

  onSubmit(){
    // console.log("polo   " + this.fileToAnalize);
    this.allFilesToCompare= this.filesToCompare.concat(this.filesToCompareShared);
    console.log("ARRAY A ANALIZAR  " +   this.allFilesToCompare);



    if(this.fileToAnalize=="-1"){
      this.openModal("No se inició el analisis","Seleccione documento a analizar y vuelva a intentarlo.","error","error")
    }else
    {
      console.log("polo 2  " + this.allFilesToCompare.length);
      if(this.allFilesToCompare.length == 0){
        this.openModal("No se inició el analisis","Seleccione 1 o mas archivos de la lista para comparar y vuelva a intentarlo.","error","error")

      }else{
        this.openModal("¿Esta seguro de querer iniciar el analisis?","Haga click en 'Confirmar' para iniciar el analisis o en 'Cerrar' para cancelar la accion","confirm","analyze")


      }
    }
  }

  ngOnInit() {
    // this.fileToAnalize = '-1';
    // this.getAllUserFiles();
    // this.getSharedFiles();
  }


  uncheckAll(){
    for (var i = 0; i < this.fileList.length; i++) {
        this.fileList[i].selected = this.selectedAll;
    }

    this.filesToCompare =[];
  }

  uncheckAllShared(){
    for (var i = 0; i < this.sharedFileList.length; i++) {
        this.sharedFileList[i].selected = this.selectedAllShared;
    }

    this.filesToCompareShared =[];
  }


  onSelectAll(isChecked: boolean){
    this.selectedAll = !this.selectedAll;

    if(isChecked) {
      let aux1 = <any>this.fileList;
      this.filesToCompare = aux1.map(a => a.idFile);

      for (var i = 0; i < this.fileList.length; i++) {
        console.log("  el chekbox ANTES "+  JSON.stringify( this.fileList[i]))
        console.log(" this.selectedA "+   this.selectedAll)
          this.fileList[i].selected = this.selectedAll;
          console.log("  el chekbox DESPUES "+  JSON.stringify( this.fileList[i]))
      }

    } else {
      this.uncheckAll();

    //   for (var i = 0; i < this.fileList.length; i++) {
    //       this.fileList[i].selected = this.selectedAll;
    //   }
    //
    //   this.filesToCompare =[];
     }
    console.log(this.filesToCompare)
  }
  onSelectAllShared(isChecked: boolean){
    this.selectedAllShared = !this.selectedAllShared;
    console.log("selectedAllShared   "+ this.selectedAllShared)

    if(isChecked) {
      console.log("ENTRO AL IF   "+ this.selectedAllShared)
      let aux = <any>this.sharedFileList;
      this.filesToCompareShared = aux.map(a => a.idFile);

        console.log("selectedAllShared   "+ this.selectedAllShared)

      for (var i = 0; i < this.sharedFileList.length; i++) {
        console.log("  el chekbox ANTES "+  JSON.stringify( this.sharedFileList[i]))
        console.log(" this.selectedAllShared "+   this.selectedAllShared)

          this.sharedFileList[i].selected = this.selectedAllShared;
          console.log("  el chekbox DESPUES "+  JSON.stringify( this.sharedFileList[i]))
      }

    } else {
      this.uncheckAllShared();

    //   for (var i = 0; i < this.fileList.length; i++) {
    //       this.fileList[i].selected = this.selectedAll;
    //   }
    //
    //   this.filesToCompare =[];
     }
    console.log(this.filesToCompareShared)
  }

  checkIfAllSelected(){
    if (this.fileList.length == this.filesToCompare.length){
      this.selectedAll = true;
    }
    this.selectedAll = false;
  }
  checkIfAllSelectedShared(){
    console.log("all selected shared???")
    if (this.sharedFileList.length == this.filesToCompareShared.length){
      this.selectedAllShared = true;
      console.log("YES")
    }
    this.selectedAllShared = false;
    console.log("NO")
  }

  onChangeShared(id: string, isChecked: boolean) {

        if(isChecked) {
          this.filesToCompareShared.push(id);
          console.log(JSON.stringify(this.sharedFileList.length) +  "    "  + JSON.stringify(this.filesToCompareShared.length))

          if (this.sharedFileList.length == this.filesToCompareShared.length){
            console.log("SI!!! SELECCIONASTE TODOS LOS ELEMENTOS De la tabla shared")
            this.selectedAllShared = true;
          }else{
          console.log("NO!!! SELECCIONASTE TODOS LOS ELEMENTOS De la tabla shared")
          this.selectedAllShared = false;
          }

        } else {
          let index = this.filesToCompareShared.indexOf(id);
          this.filesToCompareShared.splice(index,1);
          if(this.selectedAllShared){
            this.selectedAllShared = false;
          }



        }
        console.log(this.filesToCompareShared)
    }


    onChange(id: string, isChecked: boolean) {

      //Check if all is Selected


          if(isChecked) {
            this.filesToCompare.push(id);
            console.log(JSON.stringify(this.fileList.length) +  "    "  + JSON.stringify(this.filesToCompare.length))

            if (this.fileList.length == this.filesToCompare.length){
              console.log("SI!!! SELECCIONASTE TODOS LOS ELEMENTOS")
              this.selectedAll = true;
            }else{
            console.log("NO!!! SELECCIONASTE TODOS LOS ELEMENTOS")
            this.selectedAll = false;
            }

          } else {
            let index = this.filesToCompare.indexOf(id);
            this.filesToCompare.splice(index,1);
            if(this.selectedAll){
              this.selectedAll = false;
            }



          }
          console.log(this.filesToCompare)
      }

   onOptionSelected(event){
     console.log(event.target.value);
     this.fileToAnalize = event.target.value;
   }

  getAllUserFiles(){
    this.fileService.userFilesList(sessionStorage.getItem('email'),sessionStorage.getItem('token'))
    .subscribe(res => {
      if (JSON.stringify(res['result'])!= "[]"){
        this.fileList =  res['result'];
         console.log("PROBANDO!" + JSON.stringify(res['result']));
         console.log("PROBANDO!" + res['result'].length);

        this.fileList.forEach(function(obj) { obj.selected = false });


        // for(let i = 0 ;i < res['result'].length;i++){
        //   this.names.push({ name : JSON.stringify(res['result'][i].idFile), selected : false })
        // }
        // console.log("testeo    " + JSON.stringify(this.names));


      }
      console.log("lista files " + JSON.stringify(this.fileList));
    });
  }

  getSharedFiles(){
    this.fileService.getSharedFiles(sessionStorage.getItem('email'),sessionStorage.getItem('token'))
    .subscribe(res => {

      if (JSON.stringify(res['result'])!= "[]"){
        this.sharedFileList =  res['result'];
      }
      console.log("lista shared" + this.sharedFileList);
    });
  }

  openModal(title,text,type,action) {
    let ngbModalOptions: NgbModalOptions = {
          backdrop : 'static',
          keyboard : false
    };
    const modalRef = this.modalService.open(ModalComponent,ngbModalOptions);
    modalRef.componentInstance.title = title;
    modalRef.componentInstance.text = text;
    modalRef.componentInstance.type = type;
    modalRef.componentInstance.action = action;

    modalRef.result.then((result) => {
      console.log("resultados del modal  "+ result);
      if(result=="analyze"){
        this.doAnalysis()

      }
    }).catch((error) => {
      console.log(error);
    });
  }

}
<file_sep>/src/app/services/analyze.service.ts
import { Injectable } from '@angular/core';
import { Constants } from '../utils/Constants';
import { HttpClient, HttpHeaders,HttpParams } from '@angular/common/http';
import { ErrorHandler } from '../utils/ErrorHandler';
import { RequestOptions } from '@angular/http';
import { Session } from '../auth/loginData';
import { Observable } from 'rxjs/Observable';
import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
import { User } from '../models/User';
import {URLSearchParams} from '@angular/http';

@Injectable()
export class AnalyzeService {

  private iniciarAnalisisUrl = Constants.BASE_URL +  'systemController/iniciarAnalisis/';
  private analisisListUrl = Constants.BASE_URL +  'systemController/listarAnalisisPorUsuario/';
  private obtenerResultadoAnalisisUrl = Constants.BASE_URL +  'systemController/reporteAnalisis';


  constructor(private http:HttpClient) { }

  public iniciarAnalisis(fileToAnalize, corpus): Observable<any>{
    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/json; charset=utf-8');
    let body = {
      "credentials": {
        "mail": sessionStorage.getItem('email'),
        "password": "<PASSWORD>",
        "roleDTOs": [
          {
            "desc": "string",
            "id": 0,
            "name": "string"
          }
        ],
        "token": sessionStorage.getItem('token')
      },
      "fileToAnalyze": fileToAnalize,
      "filesToCompare": corpus,
      "finishDate": "2018-09-04T18:33:45.716Z",
      "idAnalize": 0,
      "initialDate": "2018-09-04T18:33:45.716Z",
      "terminado": true
    }
      return this.http.post(this.iniciarAnalisisUrl,body,{headers: headers});

  }

  // public getReportList(): Observable<any>{
  //   return this.http.post(this.obtenerResultadoAnalisisUrl + "?email=" + sessionStorage.getItem('email') + "&token=" + sessionStorage.getItem('token') , {responseType: 'text'}).pipe(
  //     catchError(new ErrorHandler().handleError('LoginService', null))
  //   );
  // }

  public listarAnalisisPorUsuario(): Observable<any>{
    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/json; charset=utf-8');
    let body = {
      "mail": sessionStorage.getItem('email'),
      "password": "<PASSWORD>",
      "roleDTOs": [
        {
          "desc": "string",
          "id": 0,
          "name": "string"
        }
      ],
      "token": sessionStorage.getItem('token')
    }
      return this.http.post(this.analisisListUrl,body,{headers: headers});

  }

  reporteAnalisis(email: string, token: string, idAnalisis: string) { //get file from service
    let headers = new HttpHeaders();
    headers = headers.set('Accept', 'application/pdf');
    let url = this.obtenerResultadoAnalisisUrl + "?email=" + email + "&token=" + token + "&idAnalisis=" + idAnalisis
    return this.http.get(url,{ headers: headers, responseType: 'blob' })
  }


}
<file_sep>/src/app/services/file.service.ts
import { Injectable } from '@angular/core';
import { Constants } from '../utils/Constants';
import { HttpClient, HttpHeaders,HttpParams} from '@angular/common/http';
import { ErrorHandler } from '../utils/ErrorHandler';
import { RequestOptions } from '@angular/http';
import { Session } from '../auth/loginData';
import { ResponseContentType,RequestMethod } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
import { User } from '../models/User';
import { URLSearchParams } from '@angular/http';

@Injectable()
export class FileService {

  private fileListUrl = Constants.BASE_URL +  'documentController/listUserFiles';
  private sharedFilesUrl = Constants.BASE_URL + 'documentController/listSharedFiles/';
  private downloadFileUrl = Constants.BASE_URL + 'documentController/downloadUserFiles/';
  private downloadFileGoogleUrl = 'https://www.googleapis.com/drive/v3/files/';
  private removeFileFromUserUrl = Constants.BASE_URL +'/documentController/removeFileFromUser';

  //documentController/download/{fileID}/{email}/{token}
  //documentController//downloadUserFiles/{email}/{token}/{fileID}/
  constructor(private http:HttpClient) { }


  public userFilesList(email: string, token: string): Observable<any>{
    console.log("console log: " + this.fileListUrl);
    return this.http.post(this.fileListUrl + "?email=" + email + "&token=" + token , {responseType: 'text'})
    //.pipe(catchError(new ErrorHandler().handleError('LoginService', null)));
  }
  public getSharedFiles(email: string, token: string): Observable<any>{
    return this.http.post(this.sharedFilesUrl + "?email=" + email + "&token=" + token , {responseType: 'text'})
    //.pipe(catchError(new ErrorHandler().handleError('LoginService', null)));
  }

  downloadFile(email: string, token: string, fileId: string) { //get file from service
    let headers = new HttpHeaders();
    headers = headers.set('Accept', 'application/pdf');
    let url = this.downloadFileUrl + "?email=" + email + "&token=" + token + "&fileID=" + fileId
    return this.http.get(url,{ headers: headers, responseType: 'blob' })
  }


  deleteFile(email: string, token: string, fileId: string) { //get file from service
    let headers = new HttpHeaders();
    headers = headers.set('Accept', 'application/pdf');
    let url = this.removeFileFromUserUrl + "?email=" + email + "&token=" + token + "&fileID=" + fileId
    return this.http.post(url,{ headers: headers, responseType: 'text' })
  }





//  http://localhost:8888/documentController/listUserFiles?email=<EMAIL>&token=<PASSWORD>

}
<file_sep>/src/app/components/edit-user/edit-user.component.ts
import { Component, OnInit } from '@angular/core';
import { UserService} from '../../services/user.service';
//import { AuthService, GoogleLoginProvider } from "angular5-social-login";
import { HttpClient} from '@angular/common/http'
import { Router,Routes, RouterModule} from '@angular/router';
import { FormGroup, FormBuilder, Validators, FormControl, AsyncValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms';
import { AuthService } from '../../auth/auth.service';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';
import { NgbModal,NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from '../../utils/modal/modal.component';

@Component({
  selector: 'app-edit-user',
  templateUrl: './edit-user.component.html',
  styles: []
})
export class EditUserComponent implements OnInit {
  registerForm: FormGroup;
  submitted = false;
  emailExists:boolean;      // {1}
  fileList = [];
  optionSelected: any;
  enable:boolean;
  private formSubmitAttempt: boolean; // {2}
  private isChecked: boolean
  rolesList = [{'name':'ADMIN'},{'name':'TUTOR'}]

  constructor(
    private userService: UserService,
    private http: HttpClient,
    private router: Router,
    private fb: FormBuilder,
    private authService: AuthService,
    private modalService: NgbModal
  ) {}

    // convenience getter for easy access to form fields
   get f() { return this.registerForm.controls; }

  ngOnInit() {
    this.getAllUsers();
    this.registerForm = this.fb.group({     // {5}
    name: ['', Validators.required],
    secondName: ['', Validators.required],
    email: ['',
    [Validators.required,Validators.email]],
    roles: ['',Validators.required]
    //passwordGoogle:['<PASSWORD>', Validators.required],
    });

  }


onSubmit(){
  this.submitted = true;
   
        // stop here if form is invalid
 if (this.registerForm.invalid) {
    this.openModal("Error al editar perfil", "Uno o mas campos son incorrectos, complete los campos correctamente y vuelva a intentarlo","error","error");
      return;
 }
 else{
   if(this.registerForm.value.roles == "TUTOR"){
     this.registerForm.value.roles= [{'name':'TUTOR'}]
   }else{
     this.registerForm.value.roles= [{'name':'ADMIN'}]
   }

    this.openModal("¿Esta seguro de modificar su Usuario?", "Haga click en 'Confirmar' para modificar el usuario o en 'Cerrar' para cancelar la accion",'confirm',"edit")

 }

}

editUser() {
 

      console.log("valores para Edit usuer:   "+ JSON.stringify(this.registerForm.value))
    this.userService.modifyUser(this.registerForm.value).subscribe(res =>{
     if(true){
       this.getAllUsers();
        this.openModal("Usuario modificado", "","success","success");
     }
     else{
       //  alert("Error al crear usuario")
       }
     })

}

getAllUsers(){
  this.userService.getAllUsers().subscribe(res=>{
    console.log('RES!!!'+JSON.stringify(res['result']) );
    this.fileList = res['result'];
  })
}

  onOptionSelected(event){
    console.log("cheked :  "+ this.isChecked);
     console.log(event); //option value will be sent as event
     this.optionSelected = event.target.value;
     console.log("REtencion "+ event.target.value.enable);
    //this.isChecked=this.fileList[event.target.value].enable

    console.log("cheked :  "+ this.isChecked);

     this.registerForm.setValue({
        name: this.fileList[event.target.value].name,
        secondName: this.fileList[event.target.value].secondName,
        email: this.fileList[event.target.value].email,
        roles: this.fileList[event.target.value].roles[0].name
        //enablecheck: this.fileList[event.target.value].enable
     });

  }

  openModal(title,text,type,action) {
    let ngbModalOptions: NgbModalOptions = {
          backdrop : 'static',
          keyboard : false
    };
    const modalRef = this.modalService.open(ModalComponent,ngbModalOptions);
    modalRef.componentInstance.title = title;
    modalRef.componentInstance.text = text;
    modalRef.componentInstance.type = type;
    modalRef.componentInstance.action = action;


    modalRef.result.then((result) => {
      console.log("resultados del modal  "+result);
      console.log("resultados del modal  "+result);
      if(result=='edit'){
       this.editUser()

      }


    }).catch((error) => {
      console.log(error);
    });
  }


}
<file_sep>/src/app/auth/storageService.ts
import {Injectable} from '@angular/core';
import {Router, CanActivate, RouterStateSnapshot, ActivatedRouteSnapshot} from '@angular/router';
import {AuthService} from './auth.service';
import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';


@Injectable()
export class StorageService {

 private storageSub = new Subject<boolean>();

 watchStorage(): Observable<any> {
   return this.storageSub.asObservable();
 }

 setItem(key: string, data: any) {
   sessionStorage.setItem(key, data);
   this.storageSub.next(data);
 }

 removeItem(key) {
   sessionStorage.removeItem(key);
   this.storageSub.next(null);
 }
}
<file_sep>/src/app/validators/emailTaken.validator.ts
import { AsyncValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';
import {UserService} from '../services/user.service';

export function emailTaken(userService: UserService): AsyncValidatorFn {
  return (control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> => {
    return userService.exist(control.value).map(
      res => {
        return (res) ? {"emailExists": true} : null;
      }
    );
  };
}
<file_sep>/src/app/components/google-drive/google-drive.component.ts
import { Component, NgZone, OnInit } from "@angular/core";
import { AppContext } from "../../../infrastructure/app.context";
import { FileInfo, MIME_TYPE_FOLDER } from "../../../model/fileInfo"
import { BreadCrumbItem } from "../../../model/breadCrumbItem";
import { MatTableDataSource } from "@angular/material/table";
import { BreadCrumbItemOption, OPTION_NEW_FOLDER, OPTION_UPLOAD_FILES } from "../../../model/breadCrumbItemOption";
import { MatDialog } from "@angular/material/dialog";
import { DialogOneInputComponent } from "../dialogoneinput/dialogoneinput.component"
import { DialogOneInputData } from "../../../model/dialogOneInputData"
import { MatBottomSheet } from '@angular/material';
import { HttpClient, HttpEventType, HttpHeaders } from '@angular/common/http';
import { Constants } from '../../utils/Constants';
import { NgbModal, NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from '../../utils/modal/modal.component';




import { Router } from "@angular/router";

@Component({
    selector: "google-drive",
    templateUrl: "./google-drive.component.html",
    styleUrls: []
})
export class GoogleDriveComponent implements OnInit{
   breadCrumbItems: BreadCrumbItem[] = [];
   dataSource: MatTableDataSource<FileInfo>;
   //displayedColumns: string[] = ["icon", "name", "modifiedTime", "size", "delete"];
   displayedColumns: string[] = ["icon", "name", "modifiedTime", "size"];
   files: FileInfo[] = [];
   isSignedIn: boolean = this.appContext.Session.Gapi.isSignedIn;
   email: string;
   public uploadFile = Constants.BASE_URL +  'documentController/addFileToUser';
   public buttonDisabled: boolean = false;
   public porcentaje=''


    constructor(
        private appContext: AppContext,
        private router: Router,
        private zone: NgZone,
        public dialog: MatDialog,
        private bottomSheet: MatBottomSheet,
        private http: HttpClient,
        private modalService: NgbModal


    ) {

      console.log("TEST FILES   "+ JSON.stringify(this.files))
      this.dataSource = new MatTableDataSource(this.files);


    }

onRefresh(){
    this.refresh("root");
}

signIn(){
  this.appContext.Session.Gapi.signIn().then(() => {
    if(this.appContext.Session.Gapi.isSignedIn){
      this.isSignedIn = this.appContext.Session.Gapi.isSignedIn;

      console.log("ESTAS LOGUEADO")
      this.appContext.Session.BreadCrumb.init();
      this.breadCrumbItems = this.appContext.Session.BreadCrumb.items;
      this.refresh("root");

    }
    else
      console.log("NO ESTAS LOGUEADO")
  });

}

singOut(){
  this.appContext.Session.Gapi.signOut();
  this.refresh("root");

}

browse(file: FileInfo) {
       if (file.IsFolder) {
           this.appContext.Repository.File.getFiles(file.Id)
               .then((res) => {
                   this.zone.run(() => {

                       this.files = res;
                       this.dataSource.data = this.files;
                       this.appContext.Session.BreadCrumb.navigateTo(file.Id, file.Name);
                       this.breadCrumbItems = this.appContext.Session.BreadCrumb.items;
                   });
               });
       }
   }

   createNewFolder() {
          var data: DialogOneInputData = new DialogOneInputData();
          data.DefaultInputText = "Untitled folder";
          data.Title = "New folder"
          const dialogRef = this.dialog.open(DialogOneInputComponent, {
              width: '250px',
              data: data
          });

          dialogRef.afterClosed().subscribe(result => {
              if (result) {
                  this.appContext.Repository.File.create(
                      this.appContext.Session.BreadCrumb.currentItem.Id,
                      result)
                      .then(() => {
                          this.refresh(this.appContext.Session.BreadCrumb.currentItem.Id);
                      });
              }

          });
      }

      delete(file: FileInfo) {
          var index = this.files.indexOf(file);
          if (index > -1) {
              this.files.splice(index, 1);
              this.appContext.Repository.File.delete(file.Id)
                  .then(() => {
                      this.zone.run(() => {
                          this.dataSource.data = this.files;
                          console.log("Delete successfully");
                      });
                  });
          }
      }


      ngOnInit(): void {
        console.log("isSignedIn 1  " +this.isSignedIn);
          this.isSignedIn = this.appContext.Session.Gapi.isSignedIn;
          this.appContext.Session.BreadCrumb.init();
          this.breadCrumbItems = this.appContext.Session.BreadCrumb.items;
          this.refresh("root");
          console.log("isSignedIn 2   " +this.isSignedIn);

      }

      logout(): void{

      }

      onSelectedItemChanged($event: BreadCrumbItem) {
          let fileInfo: FileInfo = new FileInfo();
          fileInfo.Id = $event.Id;
          fileInfo.Name = $event.Name;
          fileInfo.MimeType = MIME_TYPE_FOLDER;
          this.browse(fileInfo);
      }

      // onSelectedOptionChanged($event: BreadCrumbItemOption) {
      //     if ($event.Option === OPTION_NEW_FOLDER) {
      //         this.createNewFolder();
      //     }
      //     else if ($event.Option === OPTION_UPLOAD_FILES) {
      //         // this.importByUrl();
      //         this.bottomSheet.open(FilesUploadComponent, { data: $event.Data });
      //     }
      // }

      refresh(fileId: string) {
          this.appContext.Repository.File.getFiles(fileId)
              .then((res) => {
                  this.zone.run(() => {
                      this.files = res;
                      console.log('files: ' + JSON.stringify(res))
                      this.dataSource.data = this.files;
                  });
              });
      }



      downloadFile(fileID: string,name:string ){
        console.log("downloadFile");
        console.log("entro!!!  " + fileID)
        console.log("%c entro!!!, {color= orange}  " + fileID);
        //console.log("GOOGLE AUTH:   " + JSON.stringify(this.appContext.Session.Gapi.googleAuth));


        this.appContext.Repository.File.downloadFileGoogle(fileID)
        .subscribe(res => {
          console.log("ENTRO AL BLOB!!!!!! " + res);
          console.log("entro string !!!  " + JSON.stringify(res));

          var file = new Blob([res], {type: 'application/pdf'});

          let fd=new FormData();
          fd.append("blob",file, name);
          this.upload(file,name)

          //this.showFile(file)
        });
      }



      upload(file:Blob, name:string){
        this.buttonDisabled=true;
        const fd = new FormData();
        console.log("ULPLOAD()")
        fd.append('file',file, name )
        console.log("Archivo a subir" + file)
        console.log("Archivo a subir" + JSON.stringify(file) )
        this.http.post(this.uploadFile + "?email=" + sessionStorage.email + "&token=" + sessionStorage.token ,fd,{
          reportProgress: true,
          observe:'events'
        })
          .subscribe(event => {
            if(event.type === HttpEventType.UploadProgress){
              this.porcentaje = Math.round(event.loaded / event.total * 100) + "%";
              //console.log('Upload Progress: '+ this.porcentaje)

            }else if(event.type === HttpEventType.Response){
              this.buttonDisabled = false;
                //this.getAllUserFiles();

                console.log("EVENT " + JSON.stringify(event));
                console.log("EVENT " + JSON.stringify(HttpEventType.Response));

                console.log("EVENT  CODE" + JSON.stringify(event['body']['code']));

                if(JSON.stringify(event['body']['code']) == '1'){
                  this.openModal(JSON.stringify(event['body']['message']),'El archivo ya existe en el sistem o fue eliminado.',"error","error");

                }
                if(JSON.stringify(event['body']['code']) == '0'){
                  this.openModal(JSON.stringify(event['body']['message']),'' ,"success","success");

                }

            }

          });
      }

        showFile(blob){
          console.log("size!!!  " + blob.size);

          // IE doesn't allow using a blob object directly as link href
          // instead it is necessary to use msSaveOrOpenBlob
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveOrOpenBlob(blob);
            return;
          }

          // For other browsers:
          // Create a link pointing to the ObjectURL containing the blob.
          const data = window.URL.createObjectURL(blob);
          console.log("data windows url !!!  " + JSON.stringify(data));
          var link = document.createElement('a');
          link.href = data;
          link.download="file.pdf";
          console.log("data file url !!!  " + JSON.stringify(link));
          link.click();
        }








          openModal(title,text,type,action) {
            let ngbModalOptions: NgbModalOptions = {
                  backdrop : 'static',
                  keyboard : false
            };
            const modalRef = this.modalService.open(ModalComponent,ngbModalOptions);
            modalRef.componentInstance.title = title;
            modalRef.componentInstance.text = text;
            modalRef.componentInstance.type = type;
            modalRef.componentInstance.action = action;


            modalRef.result.then((result) => {

              console.log("resultados del modal  "+result);


            }).catch((error) => {
              console.log(error);
            });
          }





}
<file_sep>/src/app/auth/auth.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { BehaviorSubject } from 'rxjs';
import { Login, Logout, Session} from './loginData';
import { Constants } from '../utils/Constants';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ErrorHandler } from '../utils/ErrorHandler';
import { RequestOptions, Headers } from '@angular/http';
import { catchError } from 'rxjs/operators';
import { StorageService } from './storageService';
import { NgbModal, NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from '../utils/modal/modal.component';
  //import {Headers, RequestOptions} from 'angular2/http';


@Injectable()
export class AuthService {
  private loggedIn = new BehaviorSubject<boolean>(false); // {1}
  private loginUrl = Constants.BASE_URL + 'loginController/login';
  private logoutUrl = Constants.BASE_URL + 'loginController/logout/';
  private secureEchoUrl = Constants.BASE_URL + 'Sdp/api/secure/echo/andrei';
  private isLoggedInUrl = Constants.BASE_URL + 'loginController/isLoggedIn';



  get isLoggedIn() {
    console.log("TOKEN:  " + this.getToken())

    if(this.getToken()){
      this.loggedIn.next(true);
    }
      return this.loggedIn.asObservable(); // {2}

  }

  public getToken(): string {
    return sessionStorage.getItem('token');
  }

  constructor(
    private router: Router,
    private http: HttpClient,
    private storageService: StorageService,
    private modalService: NgbModal
  ) {}


  logout() {
    let email = sessionStorage.getItem('email');
    let token =  sessionStorage.getItem('token');


    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/json; charset=utf-8');
    console.log('headers' + headers.get('Content-Type'));
    this.http.post(this.logoutUrl, {email: email, token: token},  {headers: headers})
                    .subscribe(res =>  {
                    sessionStorage.setItem('token','');
                    sessionStorage.setItem('email','');
                    sessionStorage.setItem('role','');
                    this.loggedIn.next(false);
                    this.router.navigate(['/login']);
                });
  }

login(login: Login){

  console.log("User and password: "+ login);

  let headers = new HttpHeaders();
  headers = headers.set('Content-Type', 'application/json; charset=utf-8');
  this.http.post(this.loginUrl, login,  {headers: headers})
                  .subscribe(res =>  {

                    console.log(JSON.stringify("jjjjjjj" + JSON.stringify(res)));

                  if (JSON.stringify(res['code'])=="0"|| JSON.stringify(res['code'])=="2"){
                    console.log('SESION    ' + JSON.stringify(res['result']));


                    this.storageService.setItem('token', res['result'][0].token)
                    this.storageService.setItem('email', res['result'][0].email)
                    this.storageService.setItem('role', res['result'][0].roles[0].id)
                    this.loggedIn.next(true);
                    this.router.navigate(['/home']);



                  }
                  else {
                    this.openModal(res['message'],"","error","error");

                  }

              });
}



openModal(title,text,type,action) {
  let ngbModalOptions: NgbModalOptions = {
        backdrop : 'static',
        keyboard : false
  };
  const modalRef = this.modalService.open(ModalComponent,ngbModalOptions);
  modalRef.componentInstance.title = title;
  modalRef.componentInstance.text = text;
  modalRef.componentInstance.type = type;
  modalRef.componentInstance.action = action;

  modalRef.result.then((result) => {
    console.log("resultados del modal  "+result);
    if(result=='edit'){

    }
  }).catch((error) => {
    console.log(error);
  });
}

// isLoggedIn(){
//
// let skeleton = {
//   "mail": "string",
//   "password": "<PASSWORD>",
//   "roleDTOs": [
//     {
//       "desc": "string",
//       "id": 0,
//       "name": "string"
//     }
//   ],
//   "token": "<PASSWORD>"
// }
//
// let headers = new HttpHeaders();
// headers = headers.set('Content-Type', 'application/json; charset=utf-8');
// headers.append('Access-Control-Allow-Origin','*');
// console.log('headers' + headers.get('Content-Type'));
// return  this.http.post(this.allUsersUrl, skeleton, {headers: headers})
// //this.http.post(this.createUserUrl, user, {headers: headers})
//    //.subscribe(respuesta =>JSON.stringify(console.log(respuesta))
//
// }




}
<file_sep>/src/app/app.routes.ts
import { RouterModule, Routes } from '@angular/router';
import { FilesComponent } from './components/files/files.component';
import { LoginComponent } from './components/login/login.component';
import { PasswordComponent } from './components/password/password.component';
import { CreateUserComponent } from './components/create-user/create-user.component';
import { EditUserComponent } from './components/edit-user/edit-user.component';
import { EditProfileComponent } from './components/edit-profile/edit-profile.component';
import { HomeComponent } from './components/home/home.component';
import { AnalyzeComponent } from './components/analyze/analyze.component';
import { ReportsComponent } from './components/reports/reports.component';
import { PageNotFoundComponent } from './components/page-not-found/page-not-found.component';
import { GoogleDriveComponent } from './components/google-drive/google-drive.component';
import { AuthGuard } from './auth/auth.guard';
import { HelpComponent } from './components/help/help.component';
import { NewPasswordComponent } from './components/new-password/new-password.component';
import { ChangePasswordComponent } from './components/change-password/change-password.component';

const APP_ROUTES: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full', canActivate: [AuthGuard]},
  { path: 'files', component: FilesComponent, canActivate: [AuthGuard]},
  { path: 'login', component: LoginComponent },
  { path: 'home', component: HomeComponent, canActivate: [AuthGuard]},
  { path: 'password', component: PasswordComponent },
  { path: 'analyze', component: AnalyzeComponent, canActivate: [AuthGuard]},
  { path: 'create-user', component: CreateUserComponent,  canActivate: [AuthGuard],data: {
        roles: {
            only: ['1'],
            redirectTo: 'password'
        }
    }},
  { path: 'edit-user', component: EditUserComponent, canActivate: [AuthGuard]},
  { path: 'edit-profile', component: EditProfileComponent, canActivate: [AuthGuard]},
  { path: 'reports', component: ReportsComponent, canActivate: [AuthGuard]},
  { path: 'google-drive', component: GoogleDriveComponent, canActivate: [AuthGuard]},
  { path: 'help', component: HelpComponent, canActivate: [AuthGuard]},
  { path: 'change-password', component: ChangePasswordComponent, canActivate: [AuthGuard]},
  { path: 'new-password', component: NewPasswordComponent},
  //{ path: '**', pathMatch: 'full', redirectTo: '' },
  { path: '**', component: PageNotFoundComponent},
];

export const APP_ROUTING = RouterModule.forRoot(APP_ROUTES);
