Project

General

Profile

1
import {Injectable} from '@angular/core';
2
import {Http, Response} from '@angular/http';
3
import {Observable}     from 'rxjs/Observable';
4
import {AutoCompleteValue} from '../../searchPages/searchUtils/searchHelperClasses.class';
5
import {OpenaireProperties} from '../properties/openaireProperties';
6
import 'rxjs/add/observable/of';
7
import 'rxjs/add/operator/do';
8
import 'rxjs/add/operator/share';
9

    
10
import {StringUtils} from '../string-utils.class';
11
@Injectable()
12
export class EntitiesSearchService {
13
    public ready:boolean = false;
14
    constructor(private http: Http ) {}
15

    
16
    searchProjectsByFunder(keyword:string, funderId:string):any {
17
      this.ready = false;
18
      let url =  OpenaireProperties. getSearchAPIURLLast()+"projects?"+((keyword && keyword.length > 0)?("q=" +keyword):"")+((funderId && funderId.length > 0 )?"&fq=funder exact " + '"'+funderId+ '"':"")+"&size=10&page=0&format=json";
19
      return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url).toPromise()
20
      .then(request =>
21
        {
22
          request = request.json().results;
23
          this.ready = true;
24
          return this.parse(request,"oaf:project","project");
25
        }).catch((ex) => {
26
          console.error('An error occured', ex);
27
          return  [{id:'-2',label:'Error'}];;
28
        });
29
      }
30
      searchByDepositType(keyword:string, DepositType:string):any {
31
        this.ready = false;
32
        console.info("In searchOrganizationsforDeposit");
33

    
34
        let link = OpenaireProperties.getSearchResourcesAPIURL();
35

    
36
        let url = link+"?query=";
37
        if(keyword!= null && keyword != ''  ) {
38
          url += "((oaftype exact organization and deletedbyinference=false and "+
39
            "(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=*))"+
40
            " and ((organizationlegalname all "+'"'+keyword+'"'+") or (organizationlegalshortname all "+'"'+keyword+'"'+")) " +
41
            // "and " + this.quote(params) + " " +
42
            "and (collectedfrom exact "+StringUtils.quote(StringUtils.URIEncode(DepositType))+")) "
43

    
44
        }
45

    
46
        url += "&page=0&size=10";
47
        url += "&format=json";
48

    
49
        // let url =  OpenaireProperties. getSearchAPIURLLast()+"projects?"+((keyword && keyword.length > 0)?("q=" +keyword):"")+((funderId && funderId.length > 0 )?"&fq=funderid exact " + '"'+funderId+ '"':"")+"&size=10&page=0&format=json";
50
        return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url).toPromise()
51
        .then(request =>
52
          {
53
            request = request.json().results;
54
            console.log(request);
55
            this.ready = true;
56
            return this.parse(request,"oaf:organization","organization");
57
          }).catch((ex) => {
58
            console.error('An error occured', ex);
59
            return  [{id:'-2',label:'Error'}];;
60
          });
61
        }
62

    
63
    searchByType(keyword:string,type:string){
64
       if (type == "project"){
65
         return  this.searchEntity(keyword,"projects","oaf:project","project");
66
      }else if (type == "dataset"){
67
        return  this.searchEntity(keyword,"datasets","oaf:result","dataset");
68
      }else if (type == "datasource" || type == "hostedBy" || type== "collectedFrom"){
69
        return  this.searchEntity(keyword,"datasources","oaf:datasource","datasource");
70
      }else if (type == "publication"){
71
        return  this.searchEntity(keyword,"publications","oaf:result","publication");
72
      }else if (type == "organization"){
73
        return  this.searchEntity(keyword,"organizations","oaf:organization","organization");
74

    
75
      }
76

    
77
    }
78
    fetchByType(id:string,type:string){
79
       if (type == "project"){
80
         return  this.fetchEntity(id,"projects","oaf:project","project");
81
      }else if (type == "dataset"){
82
        return  this.fetchEntity(id,"datasets","oaf:result","dataset");
83
      }else if (type == "datasource"  || type == "hostedBy" || type== "collectedFrom"){
84
        return  this.fetchEntity(id,"datasources","oaf:datasource","datasource");
85
      }else if (type == "publication"){
86
        return  this.fetchEntity(id,"publications","oaf:result","publication");
87
      }else if (type == "organization"){
88
        return  this.fetchEntity(id,"organizations","oaf:organization","organization");
89

    
90
      }
91

    
92
    }
93
private searchEntity (keyword: string,APIname:string,oafEntityType:string, type:string):any {
94
      let link = OpenaireProperties. getSearchAPIURLLast()+APIname;
95
      return this.search(link,keyword,oafEntityType,type)
96

    
97
}
98
private fetchEntity (id: string,APIname:string,oafEntityType:string, type:string):any {
99
    let link = OpenaireProperties. getSearchAPIURLLast()+APIname;
100
    return this.fetch(link,id,oafEntityType,type)
101
}
102
private fetch (link,id,oafEntityType,type){
103
  this.ready = false;
104
  let url = link+"/"+id+"?format=json";
105
  return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url)
106
    .map(request => <any> request.json())
107
    // .do(res => console.info(res))
108
    .map(request => {
109
      this.ready = true;
110
      return this.parse(request,oafEntityType,type);
111
    }).catch((ex) => {
112
      console.error('An error occured', ex);
113
      return  [{id:'-2',label:'Error'}];;
114
    });
115

    
116
}
117
    private search (link,keyword,oafEntityType,type){
118
      this.ready = false;
119
      let url = link+"?";
120
      if(keyword!= null && keyword != ''  ) {
121
          url += "q="+ keyword;
122
      }
123

    
124
      url += "&page=0&size="+10+"&format=json";
125
      return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url).toPromise()
126
                 .then(request =>
127
                   {
128
                     request = request.json().results;
129
                     this.ready = true;
130
                     return this.parse(request,oafEntityType,type);
131
                   }).catch((ex) => {
132
                     console.error('An error occured', ex);
133
                     return [{id:'-2',label:'Error'}];
134
                   });
135

    
136

    
137
    }
138

    
139
    private parse(data: any,oafEntityType:string, type:string){
140
      var array:any =[]
141
      let length = Array.isArray(data) ? data.length : 1;
142

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

    
146
            var value:any={} ;
147
            if(resData['title']){
148
              if(Array.isArray(resData['title'])) {
149
                    value.label = resData['title'][0];
150
              } else {
151
                    value.label = resData['title'];
152
              }
153
              if(oafEntityType=="oaf:result"){
154
                value.label = value.label.content;
155
                value.result = resData;
156
              }
157
            }else if(resData["fullname"]){
158
              if(Array.isArray(resData["fullname"])) {
159
                    value.label = resData["fullname"][0];
160
              } else {
161
                    value.label = resData["fullname"];
162
              }
163
            }else if(resData["legalname"]){
164

    
165
              if(Array.isArray(resData["legalname"])) {
166
                    value.label = resData["legalname"][0];
167
              } else {
168
                    value.label = resData["legalname"];
169
              }
170

    
171
            }else if(resData["officialname"]){
172

    
173
              if(Array.isArray(resData["officialname"])) {
174
                    value.label = resData["officialname"][0];
175
              } else {
176
                    value.label = resData["officialname"];
177
              }
178
            }
179

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

    
182
             if(type=="project"){
183
                  value.projectAcronym = resData['acronym'];
184
                  value.projectName = value.label;
185
                  value.endDate = null;
186
                  value.startDate = null;
187
                  value.funderId = "";
188
                  value.funderName = "";
189
                  value.jurisdiction = "";
190
                  value.fundingLevel0 = "";
191
                  value.code =  resData['code'];
192

    
193
                  if(resData['fundingtree'] && resData['fundingtree']['funder']){
194
                    value.funderId = (resData['fundingtree']['funder']['id'] )?resData['fundingtree']['funder']['id']:"";
195
                    value.funderName = (resData['fundingtree']['funder']['shortname'] )?resData['fundingtree']['funder']['shortname']:"";
196
                    value.jurisdiction = (resData['fundingtree']['funder']['jurisdiction'] )?resData['fundingtree']['funder']['jurisdiction']:"";
197
                    if(resData['fundingtree']['funding_level_2']){
198
                      value.fundingLevel0 = (resData['fundingtree']['funding_level_2'] && resData['fundingtree']['funding_level_2']['parent'] &&
199
                       resData['fundingtree']['funding_level_2']['parent']['funding_level_1'] && resData['fundingtree']['funding_level_2']['parent']['funding_level_1']['parent']
200
                     && resData['fundingtree']['funding_level_2']['parent']['funding_level_1']['parent']['funding_level_0'])?
201
                      resData['fundingtree']['funding_level_2']['parent']['funding_level_1']['parent']['funding_level_0']['name']:"";
202
                    }else if(resData['fundingtree']['funding_level_1']){
203
                      value.fundingLevel0 = (resData['fundingtree']['funding_level_1'] && resData['fundingtree']['funding_level_1']['parent'] && resData['fundingtree']['funding_level_1']['parent']['funding_level_0'])?
204
                      resData['fundingtree']['funding_level_1']['parent']['funding_level_0']['name']:"";
205
                    }else if(resData['fundingtree']['funding_level_0']){
206
                      value.fundingLevel0 = (resData['fundingtree']['funding_level_0']  )?resData['fundingtree']['funding_level_0']['name']:"";
207
                    }else {
208
                      value.fundingLevel0="";
209
                    }
210
                  }
211

    
212
                  if(resData.hasOwnProperty("startdate")) {
213
                    value.startDate = resData.startdate.split('-')[0];
214
                  }
215
                  if(resData.hasOwnProperty("enddate")) {
216
                    value.endDate = resData.enddate.split('-')[0];
217
                  }
218

    
219
             }
220
            //  console.info("add:"+value.label+"   "+value.id);
221

    
222
              array.push(value);
223
        }
224
        if(array.length == 0){
225
          array.push({id:'-1',label:'No results found'});
226
        }
227
        console.info("Parsing results.... Size:"+array.length);
228

    
229
        return array;
230
    }
231

    
232
    private handleError (error: Response) {
233
      // in a real world app, we may send the error to some remote logging infrastructure
234
      // instead of just logging it to the console
235
      console.log(error);
236
      return Observable.throw(error  || 'Server error');
237
    }
238
}
(3-3/4)