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.getSearchResourcesAPIURL();
19
      console.log("Funder is " + funderId);
20
      url = url+"?query=(oaftype exact project and deletedbyinference=false) ";
21
      if(keyword!= null && keyword != ''  ) {
22
        url +=  'and ((projectcode_nt exact "'+keyword+'" )or('+keyword+')) ' ;
23
        url+=((funderId && funderId.length > 0 )?("&fq=funder exact " + '"'+funderId+ '"'):"");
24
      }
25

    
26
      url += "&page=0&size=10";
27
      url += "&format=json";
28
      console.log("URL " + url);
29
      // 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";
30
      return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url).toPromise()
31
      .then(request =>
32
        {
33
          request = request.json().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):any {
42
        this.ready = false;
43
        console.info("In searchOrganizationsforDeposit");
44

    
45
        let link = OpenaireProperties.getSearchResourcesAPIURL();
46

    
47
        let url = link+"?query=";
48
        if(keyword!= null && keyword != ''  ) {
49
          url += "((oaftype exact organization and deletedbyinference=false and "+
50
            "(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=*))"+
51
            " and ((organizationlegalname all "+'"'+keyword+'"'+") or (organizationlegalshortname all "+'"'+keyword+'"'+")) " +
52
            // "and " + this.quote(params) + " " +
53
            "and (collectedfrom exact "+StringUtils.quote(StringUtils.URIEncode(DepositType))+")) "
54

    
55
        }
56

    
57
        url += "&page=0&size=10";
58
        url += "&format=json";
59

    
60
        // 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";
61
        return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url).toPromise()
62
        .then(request =>
63
          {
64
            request = request.json().results;
65
            console.log(request);
66
            this.ready = true;
67
            return this.parse(request,"oaf:organization","organization");
68
          }).catch((ex) => {
69
            console.error('An error occured', ex);
70
            return  [{id:'-2',label:'Error'}];;
71
          });
72
        }
73

    
74
    searchByType(keyword:string,type:string){
75
       if (type == "project"){
76
         return  this.searchEntity(keyword,"projects","oaf:project","project");
77
      }else if (type == "dataset"){
78
        return  this.searchEntity(keyword,"datasets","oaf:result","dataset");
79
      }else if (type == "datasource" || type == "hostedBy" || type== "collectedFrom"){
80
        return  this.searchEntity(keyword,"datasources","oaf:datasource","datasource");
81
      }else if (type == "publication"){
82
        return  this.searchEntity(keyword,"publications","oaf:result","publication");
83
      }else if (type == "organization"){
84
        return  this.searchEntity(keyword,"organizations","oaf:organization","organization");
85

    
86
      }
87

    
88
    }
89
    fetchByType(id:string,type:string){
90
       if (type == "project"){
91
         return  this.fetchEntity(id,"projects","oaf:project","project");
92
      }else if (type == "dataset"){
93
        return  this.fetchEntity(id,"datasets","oaf:result","dataset");
94
      }else if (type == "datasource"  || type == "hostedBy" || type== "collectedFrom"){
95
        return  this.fetchEntity(id,"datasources","oaf:datasource","datasource");
96
      }else if (type == "publication"){
97
        return  this.fetchEntity(id,"publications","oaf:result","publication");
98
      }else if (type == "organization"){
99
        return  this.fetchEntity(id,"organizations","oaf:organization","organization");
100

    
101
      }
102

    
103
    }
104
private searchEntity (keyword: string,APIname:string,oafEntityType:string, type:string):any {
105
      let link = OpenaireProperties. getSearchAPIURLLast()+APIname;
106
      return this.search(link,keyword,oafEntityType,type)
107

    
108
}
109
private fetchEntity (id: string,APIname:string,oafEntityType:string, type:string):any {
110
    let link = OpenaireProperties. getSearchAPIURLLast()+APIname;
111
    return this.fetch(link,id,oafEntityType,type)
112
}
113
private fetch (link,id,oafEntityType,type){
114
  this.ready = false;
115
  let url = link+"/"+id+"?format=json";
116
  return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url)
117
    .map(request => <any> request.json())
118
    // .do(res => console.info(res))
119
    .map(request => {
120
      this.ready = true;
121
      return this.parse(request,oafEntityType,type);
122
    }).catch((ex) => {
123
      console.error('An error occured', ex);
124
      return  [{id:'-2',label:'Error'}];;
125
    });
126

    
127
}
128
    private search (link,keyword,oafEntityType,type){
129
      this.ready = false;
130
      let url = link+"?";
131
      if(keyword!= null && keyword != ''  ) {
132
          url += "q="+ keyword;
133
      }
134

    
135
      url += "&page=0&size="+10+"&format=json";
136
      return this.http.get((OpenaireProperties.isCacheEnabled())? (OpenaireProperties.getCacheUrl()+encodeURIComponent(url)): url).toPromise()
137
                 .then(request =>
138
                   {
139
                     request = request.json().results;
140
                     this.ready = true;
141
                     return this.parse(request,oafEntityType,type);
142
                   }).catch((ex) => {
143
                     console.error('An error occured', ex);
144
                     return [{id:'-2',label:'Error'}];
145
                   });
146

    
147

    
148
    }
149

    
150
    private parse(data: any,oafEntityType:string, type:string){
151
      var array:any =[]
152
      let length = Array.isArray(data) ? data.length : 1;
153

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

    
157
            var value:any={} ;
158
            if(resData['title']){
159
              if(Array.isArray(resData['title'])) {
160
                    value.label = resData['title'][0];
161
              } else {
162
                    value.label = resData['title'];
163
              }
164
              if(oafEntityType=="oaf:result"){
165
                value.label = value.label.content;
166
                value.result = resData;
167
              }
168
            }else if(resData["fullname"]){
169
              if(Array.isArray(resData["fullname"])) {
170
                    value.label = resData["fullname"][0];
171
              } else {
172
                    value.label = resData["fullname"];
173
              }
174
            }else if(resData["legalname"]){
175

    
176
              if(Array.isArray(resData["legalname"])) {
177
                    value.label = resData["legalname"][0];
178
              } else {
179
                    value.label = resData["legalname"];
180
              }
181

    
182
            }else if(resData["officialname"]){
183

    
184
              if(Array.isArray(resData["officialname"])) {
185
                    value.label = resData["officialname"][0];
186
              } else {
187
                    value.label = resData["officialname"];
188
              }
189
            }
190

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

    
193
             if(type=="project"){
194
                  value.projectAcronym = resData['acronym'];
195
                  value.projectName = value.label;
196
                  value.endDate = null;
197
                  value.startDate = null;
198
                  value.funderId = "";
199
                  value.funderName = "";
200
                  value.jurisdiction = "";
201
                  value.fundingLevel0 = "";
202
                  value.code =  resData['code'];
203

    
204
                  if(resData['fundingtree'] && resData['fundingtree']['funder']){
205
                    value.funderId = (resData['fundingtree']['funder']['id'] )?resData['fundingtree']['funder']['id']:"";
206
                    value.funderName = (resData['fundingtree']['funder']['shortname'] )?resData['fundingtree']['funder']['shortname']:"";
207
                    value.jurisdiction = (resData['fundingtree']['funder']['jurisdiction'] )?resData['fundingtree']['funder']['jurisdiction']:"";
208
                    if(resData['fundingtree']['funding_level_2']){
209
                      value.fundingLevel0 = (resData['fundingtree']['funding_level_2'] && resData['fundingtree']['funding_level_2']['parent'] &&
210
                       resData['fundingtree']['funding_level_2']['parent']['funding_level_1'] && resData['fundingtree']['funding_level_2']['parent']['funding_level_1']['parent']
211
                     && resData['fundingtree']['funding_level_2']['parent']['funding_level_1']['parent']['funding_level_0'])?
212
                      resData['fundingtree']['funding_level_2']['parent']['funding_level_1']['parent']['funding_level_0']['name']:"";
213
                    }else if(resData['fundingtree']['funding_level_1']){
214
                      value.fundingLevel0 = (resData['fundingtree']['funding_level_1'] && resData['fundingtree']['funding_level_1']['parent'] && resData['fundingtree']['funding_level_1']['parent']['funding_level_0'])?
215
                      resData['fundingtree']['funding_level_1']['parent']['funding_level_0']['name']:"";
216
                    }else if(resData['fundingtree']['funding_level_0']){
217
                      value.fundingLevel0 = (resData['fundingtree']['funding_level_0']  )?resData['fundingtree']['funding_level_0']['name']:"";
218
                    }else {
219
                      value.fundingLevel0="";
220
                    }
221
                  }
222

    
223
                  if(resData.hasOwnProperty("startdate")) {
224
                    value.startDate = resData.startdate.split('-')[0];
225
                  }
226
                  if(resData.hasOwnProperty("enddate")) {
227
                    value.endDate = resData.enddate.split('-')[0];
228
                  }
229

    
230
             }
231
            //  console.info("add:"+value.label+"   "+value.id);
232

    
233
              array.push(value);
234
        }
235
        if(array.length == 0){
236
          array.push({id:'-1',label:'No results found'});
237
        }
238
        console.info("Parsing results.... Size:"+array.length);
239

    
240
        return array;
241
    }
242

    
243
    private handleError (error: Response) {
244
      // in a real world app, we may send the error to some remote logging infrastructure
245
      // instead of just logging it to the console
246
      console.log(error);
247
      return Observable.throw(error  || 'Server error');
248
    }
249
}
(3-3/4)