Project

General

Profile

1
import {Injectable} from '@angular/core';
2
import {HttpClient, HttpErrorResponse} from "@angular/common/http";
3
import {throwError} from 'rxjs';
4

    
5

    
6

    
7
import{EnvProperties} from '../properties/env-properties';
8

    
9
import {catchError, map} from "rxjs/operators";
10
@Injectable()
11
export class EntitiesSearchService {
12
    public ready:boolean = false;
13
    constructor(private http: HttpClient ) {}
14

    
15
    /*searchProjectsByFunder(keyword:string, funderId:string, properties:EnvProperties ):any {
16
      this.ready = false;
17
      let url = properties.searchResourcesAPIURL;
18
      //console.log("Funder is " + funderId);
19
      url = url+"?query=(oaftype exact project and deletedbyinference=false) ";
20
      if(keyword!= null && keyword != ''  ) {
21
        url +=  'and ((projectcode_nt exact "'+keyword+'" )or('+keyword+')) ' ;
22
        url+=((funderId && funderId.length > 0 )?("&fq=funder exact " + '"'+funderId+ '"'):"");
23
      }
24

    
25
      url += "&page=0&size=10";
26
      url += "&format=json";
27
      //console.log("URL " + url);
28
      // let url =  properties.searchAPIURLLAst+"projects?"+((keyword && keyword.length > 0)?("q=" +keyword):"")+((funderId && funderId.length > 0 )?"&fq=funder exact " + '"'+funderId+ '"':"")+"&size=10&page=0&format=json";
29
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url).toPromise()
30
      .then(request =>
31
        {
32
          //request = request.json().results;
33
          request = request['results'];
34
          this.ready = true;
35
          return this.parse(request,"oaf:project","project");
36
        }).catch((ex) => {
37
          console.error('An error occured', ex);
38
          return  [{id:'-2',label:'Error'}];
39
        });
40
      }*/
41
      searchByDepositType(keyword:string, DepositType:string, properties:EnvProperties ):any {
42
        this.ready = false;
43

    
44
        let link = properties.searchResourcesAPIURL;
45

    
46
        let url = link+"?query=";
47
        if(keyword!= null && keyword != ''  ) {
48
          /*url += "((oaftype exact organization and deletedbyinference=false and "+
49
            "(reldatasourcecompatibilityid=driver or reldatasourcecompatibilityid=driver-openaire2.0 or reldatasourcecompatibilityid=openaire2.0 or reldatasourcecompatibilityid=openaire3.0 or reldatasourcecompatibilityid=openaire2.0_data or reldatasourcecompatibilityid=hostedBy or relprojectid=* or reldatasourcecompatibilityid = native))"+
50
            " and ((organizationlegalname all "+'"'+keyword+'"'+") or (organizationlegalshortname all "+'"'+keyword+'"'+")) " +
51
            // "and " + this.quote(params) + " " +
52
            "and (collectedfrom exact "+StringUtils.quote(StringUtils.URIEncode(DepositType))+")) "*/
53

    
54
            // in search there is this filter:
55
            //reldatasourcecompatibilityid exact driver or reldatasourcecompatibilityid exact driver-openaire2.0 or reldatasourcecompatibilityid exact openaire2.0 or reldatasourcecompatibilityid exact openaire3.0 or reldatasourcecompatibilityid exact openaire2.0_data or reldatasourcecompatibilityid exact hostedBy or relproject=*
56

    
57

    
58
          //url += "((oaftype exact organization and deletedbyinference=false )"+
59
          url += "((oaftype exact organization and deletedbyinference=false and"+
60
            "(reldatasourcecompatibilityid=driver or reldatasourcecompatibilityid=driver-openaire2.0 or reldatasourcecompatibilityid=openaire2.0 or reldatasourcecompatibilityid=openaire3.0 or reldatasourcecompatibilityid=openaire4.0 or reldatasourcecompatibilityid=openaire2.0_data or reldatasourcecompatibilityid=hostedBy or relprojectid=* or reldatasourcecompatibilityid = native))"+
61
            " and ((organizationlegalname all "+'"'+keyword+'"'+") or (organizationlegalshortname all "+'"'+keyword+'"'+")) " +
62
            // "and " + this.quote(params) + " " +
63
            //"and (collectedfrom exact "+StringUtils.quote(StringUtils.URIEncode(DepositType))+")) "
64
            ")";
65
        }
66

    
67
        url += "&page=0&size=10";
68
        url += "&format=json";
69

    
70
        // let url =  properties.searchAPIURLLAst+"projects?"+((keyword && keyword.length > 0)?("q=" +keyword):"")+((funderId && funderId.length > 0 )?"&fq=funderid exact " + '"'+funderId+ '"':"")+"&size=10&page=0&format=json";
71
        return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url).toPromise()
72
        .then(request =>
73
          {
74
            //request = request.json().results;
75
            request = request['results'];
76
            //console.log(request);
77
            this.ready = true;
78
            return this.parse(request,"oaf:organization","organization");
79
          }).catch((ex) => {
80
            console.error('An error occured', ex);
81
            return  [{id:'-2',label:'Error'}];
82
          });
83
        }
84

    
85
    searchByType(keyword:string,type:string, properties:EnvProperties ){
86
       if (type == "project"){
87
         return  this.searchEntity(keyword,"projects","oaf:project","project", properties);
88
      }else if (type == "dataset"){
89
        return  this.searchEntity(keyword,"datasets","oaf:result","dataset", properties);
90
      }else if (type == "datasource" || type == "hostedBy" || type== "collectedFrom"){
91
        return  this.searchEntity(keyword,"datasources","oaf:datasource","datasource", properties);
92
      }else if (type == "publication"){
93
        return  this.searchEntity(keyword,"publications","oaf:result","publication", properties);
94
      }else if (type == "organization"){
95
        return  this.searchEntity(keyword,"organizations","oaf:organization","organization", properties);
96

    
97
      }
98

    
99
    }
100
    fetchByType(id:string,type:string, properties:EnvProperties ){
101
       if (type == "project"){
102
         return  this.fetchEntity(id,"projects","oaf:project","project", properties);
103
      }else if (type == "dataset"){
104
        return  this.fetchEntity(id,"datasets","oaf:result","dataset", properties);
105
      }else if (type == "datasource"  || type == "hostedBy" || type== "collectedFrom"){
106
        return  this.fetchEntity(id,"datasources","oaf:datasource","datasource", properties);
107
      }else if (type == "publication"){
108
        return  this.fetchEntity(id,"publications","oaf:result","publication", properties);
109
      }else if (type == "organization"){
110
        return  this.fetchEntity(id,"organizations","oaf:organization","organization", properties);
111

    
112
      }
113

    
114
    }
115
private searchEntity (keyword: string,APIname:string,oafEntityType:string, type:string, properties:EnvProperties ):any {
116
      let link = properties.searchAPIURLLAst+APIname;
117
      return this.search(link,keyword,oafEntityType,type, properties)
118

    
119
}
120
private fetchEntity (id: string,APIname:string,oafEntityType:string, type:string, properties:EnvProperties ):any {
121
    let link = properties.searchAPIURLLAst+APIname;
122
    return this.fetch(link,id,oafEntityType,type, properties)
123
}
124
private fetch (link,id,oafEntityType,type, properties:EnvProperties ){
125
  this.ready = false;
126
  let url = link+"/"+id+"?format=json";
127
  return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url)
128
    //.map(request => <any> request.json())
129
    // .do(res => console.info(res))
130
    .pipe(map(request => {
131
      this.ready = true;
132
      return this.parse(request,oafEntityType,type);
133
    }))
134
    .pipe(catchError((ex) => {
135
      console.error('An error occured', ex);
136
      return  [{id:'-2',label:'Error'}];
137
    }));
138

    
139
}
140
    private search (link,keyword,oafEntityType,type, properties:EnvProperties ){
141
      this.ready = false;
142
      let url = link+"?";
143
      if(keyword!= null && keyword != ''  ) {
144
          if(type=="project") {
145
            //name, title, acronym, grantid
146
            url += "fq="+'(projectcode_nt="'+keyword+'" ) or (fundershortname='+'"'+keyword+ '"'+') or (projectacronym="'+keyword+'" ) or (projecttitle="'+keyword+'")';
147
          } else if(type=="organization") {
148
            //name fields
149
            url += "fq="+'(organizationlegalname="'+keyword+'" ) or (organizationlegalshortname='+'"'+keyword+ '")';
150
          } else {
151
            url += "q="+ keyword;
152
          }
153
      }
154

    
155
      url += "&page=0&size="+10+"&format=json";
156
      return this.http.get((properties.useCache)? (properties.cacheUrl+encodeURIComponent(url)): url).toPromise()
157
                 .then(request =>
158
                   {
159
                     //request = request.json().results;
160
                     request = request['results'];
161
                     this.ready = true;
162
                     return this.parse(request,oafEntityType,type);
163
                   }).catch((ex) => {
164
                     console.error('An error occured', ex);
165
                     return [{id:'-2',label:'Error'}];
166
                   });
167

    
168

    
169
    }
170

    
171
    private parse(data: any,oafEntityType:string, type:string){
172
      var array:any =[]
173
      let length = Array.isArray(data) ? data.length : 1;
174

    
175
      for(let i=0; i<length; i++) {
176
            let resData = Array.isArray(data) ? data[i]['result']['metadata']['oaf:entity'][oafEntityType] : data['result']['metadata']['oaf:entity'][oafEntityType];
177

    
178
            var value:any={} ;
179
            if(resData['title']){
180
              if(Array.isArray(resData['title'])) {
181
                    value.label = resData['title'][0];
182
              } else {
183
                    value.label = resData['title'];
184
              }
185
              if(oafEntityType=="oaf:result"){
186
                value.label = value.label.content;
187
                value.result = resData;
188
              }
189
            }else if(resData["fullname"]){
190
              if(Array.isArray(resData["fullname"])) {
191
                    value.label = resData["fullname"][0];
192
              } else {
193
                    value.label = resData["fullname"];
194
              }
195
            }else if(resData["legalname"]){
196

    
197
              if(Array.isArray(resData["legalname"])) {
198
                    value.label = resData["legalname"][0];
199
              } else {
200
                    value.label = resData["legalname"];
201
              }
202
              if(resData["legalshortname"]){
203

    
204
                if(Array.isArray(resData["legalshortname"])) {
205
                      value.label += " (" + resData["legalshortname"][0] +")";
206
                } else {
207
                      value.label += " (" +  resData["legalshortname"] +")";
208
                }
209
              }
210

    
211
            }else if(resData["officialname"]){
212

    
213
              if(Array.isArray(resData["officialname"])) {
214
                    value.label = resData["officialname"][0];
215
              } else {
216
                    value.label = resData["officialname"];
217
              }
218
            }
219

    
220
           value.id = Array.isArray(data) ? data[i]['result']['header']['dri:objIdentifier'] : data['result']['header']['dri:objIdentifier'];
221

    
222
             if(type=="project"){
223
                  value.projectAcronym = resData['acronym'];
224
                  value.projectName = value.label;
225
                  value.endDate = null;
226
                  value.startDate = null;
227
                  value.funderId = "";
228
                  value.funderName = "";
229
                  value.jurisdiction = "";
230
                  value.fundingLevel0 = "";
231
                  value.code =  resData['code'];
232

    
233
                  if(resData['fundingtree'] && resData['fundingtree']['funder']){
234
                    value.funderId = (resData['fundingtree']['funder']['id'] )?resData['fundingtree']['funder']['id']:"";
235
                    value.funderName = (resData['fundingtree']['funder']['shortname'] )?resData['fundingtree']['funder']['shortname']:"";
236
                    value.jurisdiction = (resData['fundingtree']['funder']['jurisdiction'] )?resData['fundingtree']['funder']['jurisdiction']:"";
237
                    if(resData['fundingtree']['funding_level_2']){
238
                      value.fundingLevel0 = (resData['fundingtree']['funding_level_2'] && resData['fundingtree']['funding_level_2']['parent'] &&
239
                       resData['fundingtree']['funding_level_2']['parent']['funding_level_1'] && resData['fundingtree']['funding_level_2']['parent']['funding_level_1']['parent']
240
                     && resData['fundingtree']['funding_level_2']['parent']['funding_level_1']['parent']['funding_level_0'])?
241
                      resData['fundingtree']['funding_level_2']['parent']['funding_level_1']['parent']['funding_level_0']['name']:"";
242
                    }else if(resData['fundingtree']['funding_level_1']){
243
                      value.fundingLevel0 = (resData['fundingtree']['funding_level_1'] && resData['fundingtree']['funding_level_1']['parent'] && resData['fundingtree']['funding_level_1']['parent']['funding_level_0'])?
244
                      resData['fundingtree']['funding_level_1']['parent']['funding_level_0']['name']:"";
245
                    }else if(resData['fundingtree']['funding_level_0']){
246
                      value.fundingLevel0 = (resData['fundingtree']['funding_level_0']  )?resData['fundingtree']['funding_level_0']['name']:"";
247
                    }else {
248
                      value.fundingLevel0="";
249
                    }
250
                  }
251

    
252
                  if(resData.hasOwnProperty("startdate")) {
253
                    value.startDate = resData.startdate.split('-')[0];
254
                  }
255
                  if(resData.hasOwnProperty("enddate")) {
256
                    value.endDate = resData.enddate.split('-')[0];
257
                  }
258

    
259
             }
260
            //  console.info("add:"+value.label+"   "+value.id);
261

    
262
              array.push(value);
263
        }
264
        if(array.length == 0){
265
          array.push({id:'-1',label:'No results found'});
266
        }
267
        //console.info("Parsing results.... Size:"+array.length);
268

    
269
        return array;
270
    }
271

    
272
    private handleError (error: HttpErrorResponse) {
273
      // in a real world app, we may send the error to some remote logging infrastructure
274
      // instead of just logging it to the console
275
      console.log(error);
276
      return throwError(error  || 'Server error');
277
    }
278
}
(3-3/4)