/**
     * Finds entities that match given conditions.
     */
    findAndCount(conditionsOrFindOptions?: Object|FindOptions, options?: FindOptions): Rx.Observable<[ Entity[], number ]> {
        if (conditionsOrFindOptions && options) {
            return Rx.Observable.fromPromise(this.repository.findAndCount(conditionsOrFindOptions, options));

        } else if (conditionsOrFindOptions) {
            return Rx.Observable.fromPromise(this.repository.findAndCount(conditionsOrFindOptions));

        } else {
            return Rx.Observable.fromPromise(this.repository.findAndCount());
        }
    }
    /**
     * Finds first entity that matches given conditions.
     */
    findOne(conditionsOrFindOptions?: Object|FindOptions, options?: FindOptions): Rx.Observable<Entity> {
        if (conditionsOrFindOptions && options) {
            return Rx.Observable.fromPromise(this.repository.findOne(conditionsOrFindOptions, options));

        } else if (conditionsOrFindOptions) {
            return Rx.Observable.fromPromise(this.repository.findOne(conditionsOrFindOptions));

        } else {
            return Rx.Observable.fromPromise(this.repository.findOne());
        }
    }
 /**
  * Return the total number of the tasks by filter
  * @param requestNode - TaskFilterRepresentationModel
  * @returns {any}
  */
 public getTotalTasks(requestNode: TaskQueryRequestRepresentationModel): Observable<any> {
     requestNode.size = 0;
     return Observable.fromPromise(this.callApiTasksFiltered(requestNode))
         .map((res: any) => {
             return res;
         }).catch(this.handleError);
 }
Example #4
0
export function validateTextDocumentAsync(textDocument: TextDocument, options: CSpellUserSettings): Rx.Observable<Diagnostic> {
    const limit = (options.checkLimit || defaultCheckLimit) * 1024;
    const text = textDocument.getText().slice(0, limit);
    return Rx.Observable.fromPromise<cspell.TextOffset[]>(validateText(text, options))
        .flatMap(a => a)
        .filter(a => !!a)
        .map(a => a!)
        // Convert the offset into a position
        .map(offsetWord => ({...offsetWord, position: textDocument.positionAt(offsetWord.offset) }))
        // Calculate the range
        .map(word => ({
            ...word,
            range: {
                start: word.position,
                end: ({...word.position, character: word.position.character + word.text.length })
            }
        }))
        // Convert it to a Diagnostic
        .map(({text, range}) => ({
            severity: DiagnosticSeverity.Information,
            range: range,
            message: `Unknown word: "${text}"`,
            source: diagSource
        }))
    ;
}
 .catch(error => {
     if (error.status === 401) {
         this.authService.unauthenticated();     // 401 means authentication required
         let message = this.authService.isOrgApiKeySet ? 'Incorrect organization API key' : 'Authentication is required';
         return Observable.fromPromise(this.authService.login(message))
             .mergeMap(confirmed => {
                 if (confirmed) { // logged in again, or updated api key
                     this.authService.authenticationMayChange();
                     switch (params.length) {
                         case 1:
                             return func(params[0]);
                         case 2:
                             return func(params[0], params[1]);
                         case 3:
                             return func(params[0], params[1], params[2]);
                         default:
                             return Observable.throw(new Error('Wrong number of parameters: ' + params));
                     }
                 }else {      // canceled
                     return Observable.throw(new Error('User cancelled authentication'));
                 }
             });
     }else {
         let errorDetail = error.json();
         if (errorDetail) {
             this.authService.authenticated();  // a valid API response received
             return Observable.throw(new Error(errorDetail.type + ': ' + errorDetail.message));
         }
         console.log('API call failed: ' + JSON.stringify(error));
         return Observable.throw(error);
     }
 });
 /**
  * Add a filter
  * @param filter - FilterRepresentationModel
  * @returns {FilterRepresentationModel}
  */
 addFilter(filter: FilterRepresentationModel): Observable<FilterRepresentationModel> {
     return Observable.fromPromise(this.callApiAddFilter(filter))
         .map(res => res)
         .map((response: FilterRepresentationModel) => {
             return response;
         }).catch(this.handleError);
 }
 ngOnInit() {
   // Don't process restart for Rudi ("Rudi Rule")
   let user = this.session.get().user;
   if ( user && user.id == 10 ) {
     this.router.navigate(['upload']);
     return;
   }
   
   Observable.fromPromise(this.resume.resumeIsDone())
   .ignoreElements() // make sure this doesn't emit values
   .do(() => console.log('restarting session...'))
   .concat(this.backend.resetSession())
   .subscribe({
     next: (res) => {
       console.info('success restarting session', res.json());
       let session = this.session.get();
       // keep user and token data
       this.session.reset( {user:session.user, token:session.token} ); 
       this.router.navigate(['upload']);
     },
     error: (err) => {
       console.log('error restarting session', err.json());
       this.router.navigate(['upload']);
     }
   });
 }
 exportReportToCsv(reportId: string, paramsQuery: any): Observable<any> {
     return Observable.fromPromise(this.apiService.getInstance().activiti.reportApi.exportToCsv(reportId, paramsQuery))
         .map((res: any) => {
             this.logService.info('export');
             return res;
         }).catch(err => this.handleError(err));
 }
 /**
  * Retrive all the task details
  * @param id - taskId
  * @returns {<TaskDetailsModel>}
  */
 getTaskDetails(id: string): Observable<TaskDetailsModel> {
     return Observable.fromPromise(this.callApiTaskDetails(id))
         .map(res => res)
         .map((details: any) => {
             return new TaskDetailsModel(details);
         }).catch(this.handleError);
 }
 /**
  * Create a new standalone task
  * @param task - TaskDetailsModel
  * @returns {TaskDetailsModel}
  */
 createNewTask(task: TaskDetailsModel): Observable<TaskDetailsModel> {
     return Observable.fromPromise(this.callApiCreateTask(task))
         .map(res => res)
         .map((response: TaskDetailsModel) => {
             return new TaskDetailsModel(response);
         }).catch(this.handleError);
 }
Example #11
0
  deleteData(endpoint) {
    let promise = new Promise((resolve, reject) => {
      this.user.getSettings().then((set:Settings) => {
        if (set != null) {
          this.settings = set;
        } else {
          this.settings = new Settings("", "");
        }

        let finalUrl = this.settings.url + endpoint;
        this.headers = new Headers({'Authorization': "Token " + this.settings.token});

        this.http.delete(finalUrl, {headers: this.headers}).subscribe(
          data => {
            resolve(data.json());
          },
          err => {
            reject(err);
          }
        );
      });
    });

    return Observable.fromPromise(promise);
  }
    /**
     * Add a comment to a task
     * @param id - taskId
     * @param message - content of the comment
     * @returns {Comment}
     */
    addTaskComment(id: string, message: string): Observable<Comment> {
        return Observable.fromPromise(this.callApiAddTaskComment(id, message))
            .map(res => res)
            .map((response: Comment) => {
                return new Comment(response.id, response.message, response.created, response.createdBy);
            }).catch(this.handleError);

    }
Example #13
0
 canActivate(route:ActivatedRouteSnapshot, state:RouterStateSnapshot):Observable<any> {
     return Observable.fromPromise(this.auth.check())
         .map(authState => {
             console.log(authState, '-------------------');
             if (authState) this.router.navigate(['/dashboard']);
             return !authState
         }).take(1)
 }
    addTag(nodeId: string, tagName: string): any {
        let alfrescoApi: any = this.apiService.getInstance();
        let tagBody = new alfrescoApi.core.TagBody();
        tagBody.tag = tagName;

        return Observable.fromPromise(this.apiService.getInstance().core.tagsApi.addTag(nodeId, tagBody))
            .catch(this.handleError);
    }
 //MOCK...maybe this information will simply be in getPractices?!?
 getPracticeGeneralInformation(id) {
   for (var practice of PRACTICE_GENERAL_INFO) {
     if (practice.id === id) {
       var promise = Promise.resolve(practice);
       return Observable.fromPromise(promise);
     }
   }
 }
Example #16
0
 init(rootComponent:Function):Rx.Observable<void> {
   const promise = this._tcb.createAsync(rootComponent)
     .then(fixture => {
       this._fixture = fixture;
       fixture.detectChanges();
     });
   return Rx.Observable.fromPromise(promise);
 }
    updateNode(nodeId: string, nodeBody: any, options: any = {}): Observable<MinimalNodeEntryEntity> {
        const { nodesApi, handleError, getEntryFromEntity } = this;
        const promise = nodesApi
            .updateNode(nodeId, nodeBody, options)
            .then(getEntryFromEntity);

        return Observable.fromPromise(promise).catch(handleError);
    }
    getPerson(personId: string): Observable<any> {
        const { peopleApi, handleError } = this;
        const promise = peopleApi.getPerson(personId);

        return Observable
            .fromPromise(promise)
            .catch(handleError);
    }
    deleteNode(nodeId: string, options: any = {}): Observable<void> {
        const { nodesApi, handleError } = this;
        const promise = nodesApi
            .deleteNode(nodeId, options);

        return Observable
            .fromPromise(promise)
            .catch(handleError);
    }
 postRating(nodeId: string, ratingType: any, vote: any): any {
     let ratingBody: RatingBody = {
         'id': ratingType,
         'myRating': vote
     };
     return Observable.fromPromise(this.apiService.getInstance().core.ratingsApi.rate(nodeId, ratingBody))
         .map(res => res)
         .catch(this.handleError);
 }
    search(query: any): Observable<NodePaging> {
        const { searchApi, handleError } = this;
        const searchQuery = Object.assign(query);
        const promise = searchApi.search(searchQuery);

        return Observable
            .fromPromise(promise)
            .catch(handleError);
    }
    restoreNode(nodeId: string): Observable<MinimalNodeEntryEntity> {
        const { nodesApi, handleError, getEntryFromEntity } = this;
        const promise = nodesApi
            .restoreNode(nodeId)
            .then(getEntryFromEntity);

        return Observable
            .fromPromise(promise)
            .catch(handleError);
    }
 getTasksByProcessDefinitionId(reportId: string, processDefinitionId: string): Observable<any> {
     return Observable.fromPromise(this.apiService.getInstance().activiti.reportApi.getTasksByProcessDefinitionId(reportId, processDefinitionId))
         .map((res: any) => {
             let paramOptions: ParameterValueModel[] = [];
             res.forEach((opt) => {
                 paramOptions.push(new ParameterValueModel({ id: opt, name: opt }));
             });
             return paramOptions;
         }).catch(this.handleError);
 }
 getProcessDefinitionsValues(appId: string): Observable<any> {
     return Observable.fromPromise(this.apiService.getInstance().activiti.processDefinitionsApi.getProcessDefinitions(appId))
         .map((res: any) => {
             let paramOptions: ParameterValueModel[] = [];
             res.data.forEach((opt) => {
                 paramOptions.push(new ParameterValueModel(opt));
             });
             return paramOptions;
         }).catch(this.handleError);
 }
 getProcessDefinitionsValuesNoApp(): Observable<any> {
     return Observable.fromPromise(this.apiService.getInstance().activiti.reportApi.getProcessDefinitions())
         .map((res: any) => {
             let paramOptions: ParameterValueModel[] = [];
             res.forEach((opt) => {
                 paramOptions.push(new ParameterValueModel(opt));
             });
             return paramOptions;
         }).catch(err => this.handleError(err));
 }
 /**
  * Retrive all the tasks filtered by filterModel
  * @param filter - TaskFilterRepresentationModel
  * @returns {any}
  */
 getTasks(requestNode: TaskQueryRequestRepresentationModel): Observable<TaskDetailsModel[]> {
     return Observable.fromPromise(this.callApiTasksFiltered(requestNode))
         .map((res: any) => {
             if (requestNode.processDefinitionKey) {
                 return res.data.filter(p => p.processDefinitionKey === requestNode.processDefinitionKey);
             } else {
                 return res.data;
             }
         }).catch(this.handleError);
 }
 /**
  * Retrive all the Deployed app
  * @returns {Observable<any>}
  */
 getDeployedApplications(name?: string): Observable<any> {
     return Observable.fromPromise(this.apiService.getInstance().activiti.appsApi.getAppDefinitions())
         .map((response: any) => {
             if (name) {
                 return response.data.find(p => p.name === name);
             }
             return response.data;
         })
         .catch(this.handleError);
 }
Example #28
0
export function getCurrentLocation(): Observable<any> {

  return Observable.fromPromise(Geolocation.getCurrentPosition({
    timeout: 10000, enableHighAccuracy: true, maximumAge: 10
  })).map(pos => {
    return {
      lat: pos.coords.latitude,
      lng: pos.coords.longitude
    };
  })
}
    public getPhoto(): Observable<string> {
        return Observable.fromPromise(
            this.getMediaDevices().getUserMedia({ video: true, audio: false })
                .then((stream: any) => {
                        return new Promise((resolve, reject) => {
                            try {
                                var vendorURL = window.URL || window.webkitURL;
                                var doc = document;
                                var videoElement = doc.createElement('video');
                                videoElement.src = vendorURL.createObjectURL(stream);
                                videoElement.play();

                                videoElement.addEventListener('canplay', () => {
                                    var canvasElement = doc.createElement('canvas');
                                    canvasElement.setAttribute('width', videoElement.videoWidth.toString());
                                    canvasElement.setAttribute('height', videoElement.videoHeight.toString());

                                    // Wait a bit before taking a screenshot so the camera has time to adjust lights
                                    setTimeout(() => {
                                        var context = canvasElement.getContext('2d');
                                        context.drawImage(videoElement, 0, 0, videoElement.videoWidth, videoElement.videoHeight);

                                        var url = canvasElement.toDataURL('image/png');

                                        videoElement.pause();

                                        if (stream.stop) {
                                            stream.stop();
                                        }

                                        if (stream.getAudioTracks) {
                                            stream.getAudioTracks().forEach((track: any) => {
                                                track.stop();
                                            });
                                        }

                                        if (stream.getVideoTracks) {
                                            stream.getVideoTracks().forEach((track: any) => {
                                                track.stop();
                                            });
                                        }

                                        resolve(url);
                                    }, 500);
                                });
                            }
                            catch (e) {
                                reject(e);
                            }
                        });

                    }
                ));
    }
 /**
  * Retrive all the Deployed app
  * @returns {Observable<any>}
  */
 getReportList(): Observable<any> {
     return Observable.fromPromise(this.apiService.getInstance().activiti.reportApi.getReportList())
         .map((res: any) => {
             let reports: ReportParametersModel[] = [];
             res.forEach((report: ReportParametersModel) => {
                 let reportModel = new ReportParametersModel(report);
                 reports.push(reportModel);
             });
             return reports;
         }).catch(this.handleError);
 }