Project

General

Profile

1
package eu.dnetlib.repo.manager.service.utils;
2

    
3
import com.fasterxml.jackson.databind.ObjectMapper;
4
import eu.dnetlib.domain.data.Repository;
5
import eu.dnetlib.domain.data.RepositoryInterface;
6
import eu.dnetlib.repo.manager.service.domain.RepositorySnippet;
7
import eu.dnetlib.repo.manager.shared.AggregationDetails;
8
import eu.dnetlib.repo.manager.shared.Timezone;
9
import org.apache.commons.codec.digest.DigestUtils;
10
import org.apache.log4j.Logger;
11
import org.json.JSONArray;
12
import org.json.JSONException;
13
import org.json.JSONObject;
14

    
15
import java.io.BufferedReader;
16
import java.io.IOException;
17
import java.io.InputStream;
18
import java.io.InputStreamReader;
19
import java.text.ParseException;
20
import java.text.SimpleDateFormat;
21
import java.util.*;
22

    
23
public class Converter {
24

    
25
    private static final Logger LOGGER = Logger.getLogger(Converter.class);
26

    
27
    public static Repository jsonToRepositoryObject(JSONObject repositoryObject) throws JSONException {
28

    
29
        Repository repository = new Repository();
30
        
31
        JSONObject datasource = repositoryObject.getJSONObject("datasource");
32

    
33
        //if( datasource.equals(null))
34
        //    return null;
35

    
36
        repository.setId(datasource.get("id").toString());
37
        repository.setOfficialName(datasource.get("officialname").toString());
38

    
39
        repository.setEnglishName( datasource.get("englishname").toString());
40
        if(repository.getEnglishName().equals("null"))
41
            repository.setEnglishName("");
42

    
43
        repository.setWebsiteUrl(datasource.get("websiteurl").toString());
44
        if(repository.getWebsiteUrl().equals("null"))
45
            repository.setWebsiteUrl("");
46

    
47
        repository.setLogoUrl(datasource.get("logourl").toString());
48
        if(repository.getLogoUrl().equals("null"))
49
            repository.setLogoUrl("");
50

    
51
        repository.setContactEmail(datasource.get("contactemail").toString());
52
        if(repository.getContactEmail().equals("null"))
53
            repository.setContactEmail("");
54

    
55

    
56
        repository.setLatitude( toDouble(datasource.get("latitude").toString()));
57
        repository.setLongitude(toDouble(datasource.get("longitude").toString()));
58
        Double timezone = toDouble(datasource.get("timezone").toString());
59
        repository.setTimezone(timezone!=null?timezone:0.0);
60
        repository.setNamespacePrefix(datasource.get("namespaceprefix").toString());
61
        repository.setOdLanguages(datasource.get("languages").toString());
62
        repository.setDateOfValidation(convertStringToDate( datasource.get("dateofvalidation").toString()));
63

    
64
        /*  typology -> platform
65
         *  datasource class -> typology */
66
        repository.setTypology(datasource.get("platform").toString());
67
        if(repository.getTypology().equals("null"))
68
            repository.setTypology("");
69
        repository.setDatasourceClass(datasource.get("typology").toString());
70

    
71
        repository.setDateOfCollection(convertStringToDate( datasource.get("dateofcollection").toString()));
72
        repository.setActivationId(datasource.get("activationId").toString());
73

    
74
        repository.setDescription(datasource.get("description").toString());
75
        if(repository.getDescription().equals("null"))
76
            repository.setDescription("");
77

    
78
        repository.setIssn(datasource.get("issn").toString());
79
        repository.setLissn(datasource.get("lissn").toString());
80
        if(repository.getLissn().equals("null"))
81
            repository.setLissn("");
82
        repository.setEissn(datasource.get("eissn").toString());
83
        if(repository.getEissn().equals("null"))
84
            repository.setEissn("");
85
        repository.setRegisteredBy(datasource.get("registeredby").toString());
86

    
87
        /* managed field */
88
        repository.setRegistered(Boolean.parseBoolean(datasource.get("managed").toString()));
89

    
90
        //subjects
91

    
92
        repository.setAggregator(datasource.get("aggregator").toString());
93
        repository.setCollectedFrom(datasource.get("collectedfrom").toString());
94

    
95
        //TODO change organization to list
96
        JSONArray organizations = ((JSONArray)datasource.get("organizations"));
97
        if(organizations.length() != 0) {
98
            repository.setOrganization(((JSONArray) datasource.get("organizations")).getJSONObject(0).get("legalname").toString());
99
            String countryCode = ((JSONArray) datasource.get("organizations")).getJSONObject(0).get("country").toString();
100
            repository.setCountryCode(countryCode);
101
        }
102

    
103
        /* identities field  */
104

    
105
        return repository;
106
    }
107

    
108
    public static Date convertStringToDate(String date){
109

    
110
        if(Objects.equals(date, "null"))
111
            return null;
112

    
113
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
114
        try {
115
            return formatter.parse(date);
116
        } catch (ParseException e) {
117
            e.printStackTrace();
118
        }
119
        return null;
120
    }
121

    
122
    public static String convertDateToString(Date date){
123

    
124
        if(Objects.equals(date, null))
125
            return null;
126

    
127
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
128
        return formatter.format(date);
129
    }
130

    
131
    public static Double toDouble(String number){
132
        if(Objects.equals(number, "null"))
133
            return 0.0;
134
        else
135
            return Double.valueOf(number);
136
    }
137

    
138
    public static List<RepositorySnippet> jsonToRepositorySnippetList(JSONObject json) throws JSONException {
139

    
140
        List<RepositorySnippet> resultSet = new ArrayList<>();
141
        JSONArray rs = json.getJSONArray("datasourceInfo");
142
        for(int i=0;i<rs.length();i++)
143
            resultSet.add(jsonToRepositorySnippetObject( rs.getJSONObject(i)) );
144
        return resultSet;
145
    }
146

    
147
    private static RepositorySnippet jsonToRepositorySnippetObject(JSONObject repositorySnippetObject) throws JSONException {
148

    
149

    
150
        RepositorySnippet repositorySnippet = new RepositorySnippet();
151

    
152
//        JSONObject datasource = repositorySnippetObject.getJSONObject("datasource");
153

    
154

    
155
        repositorySnippet.setId(repositorySnippetObject.get("id").toString());
156
        repositorySnippet.setOfficialname(repositorySnippetObject.get("officialname").toString());
157

    
158
        repositorySnippet.setEnglishname( repositorySnippetObject.get("englishname").toString());
159
        if(repositorySnippet.getEnglishname().equals("null"))
160
            repositorySnippet.setEnglishname("");
161

    
162
        repositorySnippet.setWebsiteurl(repositorySnippetObject.get("websiteurl").toString());
163
        if(repositorySnippet.getWebsiteurl().equals("null"))
164
            repositorySnippet.setWebsiteurl("");
165

    
166
        repositorySnippet.setRegisteredby(repositorySnippetObject.get("registeredby").toString());
167
        if(repositorySnippet.getRegisteredby().equals("null"))
168
            repositorySnippet.setRegisteredby("");
169
        return repositorySnippet;
170

    
171
    }
172

    
173
    public static List<Repository> jsonToRepositoryList(JSONObject json) throws JSONException {
174

    
175
        List<Repository> resultSet = new ArrayList<>();
176
        JSONArray rs = json.getJSONArray("datasourceInfo");
177
        for(int i=0;i<rs.length();i++)
178
            resultSet.add(jsonToRepositoryObject( rs.getJSONObject(i)) );
179
        return resultSet;
180
    }
181

    
182
    public static List<RepositoryInterface> jsonToRepositoryInterfaceList(JSONObject json) throws JSONException {
183

    
184
        List<RepositoryInterface> resultSet = new ArrayList<>();
185
        JSONArray rs = json.getJSONArray("api");
186
        for(int i=0;i<rs.length();i++)
187
            resultSet.add(jsonToRepositoryInterfaceObject( rs.getJSONObject(i)) );
188
        return resultSet;
189
    }
190

    
191
    public static RepositoryInterface jsonToRepositoryInterfaceObject(JSONObject repositoryInterfaceObject) throws JSONException {
192

    
193
        RepositoryInterface repositoryInterface = new RepositoryInterface();
194

    
195
        repositoryInterface.setId(repositoryInterfaceObject.get("id").toString());
196
        repositoryInterface.setAccessProtocol(repositoryInterfaceObject.get("protocol").toString());
197
        repositoryInterface.setContentDescription(repositoryInterfaceObject.get("contentdescription").toString());
198
        repositoryInterface.setTypology(repositoryInterfaceObject.get("typology").toString());
199
        repositoryInterface.setCompliance(repositoryInterfaceObject.get("compatibility").toString());
200
        repositoryInterface.setLastCollectionDate(repositoryInterfaceObject.get("lastCollectionDate").toString());
201

    
202
        repositoryInterface.setBaseUrl(repositoryInterfaceObject.get("baseurl").toString());
203
        repositoryInterface.setRemovable(Boolean.parseBoolean(repositoryInterfaceObject.get("removable").toString()));
204

    
205

    
206
       // repositoryInterface.setMetadataIdentifierPath(repositoryInterfaceObject.get("metadataIdentifierPath").toString());
207
        repositoryInterface.setDesiredCompatibilityLevel(repositoryInterfaceObject.get("compatibility").toString());
208
        //repositoryInterface.setActive(Boolean.parseBoolean(repositoryInterfaceObject.get("active").toString()));
209

    
210

    
211
        Map<String, String> accessParams = new HashMap<>();
212
        Map<String, String> extraFields = new HashMap<>();
213

    
214
        ObjectMapper mapper = new ObjectMapper();
215
        JSONArray apiparams = repositoryInterfaceObject.getJSONArray("apiParams");
216

    
217
        for(int i=0;i<apiparams.length();i++)
218
            accessParams.put(apiparams.getJSONObject(i).getString("param"),apiparams.getJSONObject(i).getString("value"));
219

    
220
        repositoryInterface.setAccessParams(accessParams);
221

    
222
        return repositoryInterface;
223
    }
224

    
225
    public static String repositoryObjectToJson(Repository repository) throws JSONException {
226

    
227
        JSONObject jsonObject = new JSONObject();
228

    
229
        jsonObject.put("id",repository.getId());
230
        jsonObject.put("openaireId",getOpenaireId(repository.getId()));
231
        jsonObject.put("officialname",repository.getOfficialName());
232
        jsonObject.put("englishname",repository.getEnglishName());
233
        jsonObject.put("websiteurl",repository.getWebsiteUrl());
234
        jsonObject.put("logourl",repository.getLogoUrl());
235
        jsonObject.put("contactemail",repository.getContactEmail());
236
        jsonObject.put("longitude",repository.getLongitude().toString());
237
        jsonObject.put("latitude",repository.getLatitude().toString());
238
        jsonObject.put("timezone",repository.getTimezone());
239
        jsonObject.put("namespaceprefix",repository.getNamespacePrefix());
240
        jsonObject.put("languages",repository.getOdLanguages());
241
        jsonObject.put("dateofvalidation",convertDateToString(repository.getDateOfValidation()));
242

    
243
        /*
244
        * typology -> platform
245
        * datasource class -> typology
246
        * */
247
        jsonObject.put("typology",repository.getDatasourceClass());
248
        jsonObject.put("platform",repository.getTypology());
249

    
250
        jsonObject.put("dateofcollection",convertDateToString(repository.getDateOfCollection()));
251
        jsonObject.put("activationId",repository.getActivationId());
252
        jsonObject.put("description",repository.getDescription());
253
        jsonObject.put("eissn",repository.getEissn());
254
        jsonObject.put("issn",repository.getIssn());
255
        jsonObject.put("lissn",repository.getLissn());
256
        jsonObject.put("registeredby",repository.getRegisteredBy());
257

    
258
        jsonObject.put("aggregator",repository.getAggregator());
259
        jsonObject.put("collectedfrom",repository.getCollectedFrom());
260

    
261
        jsonObject.put("managed",repository.isRegistered());
262

    
263
        JSONObject organization = new JSONObject();
264
        organization.put("legalname",repository.getOrganization());
265
        organization.put("country",repository.getCountryCode());
266
        organization.put("legalshortname","");
267
        organization.put("websiteurl","");
268
        organization.put("logourl","");
269

    
270
        JSONArray organizations = new JSONArray();
271
        organizations.put(organization);
272
        jsonObject.put("organizations",organizations);
273

    
274

    
275

    
276

    
277
        //TODO check fields
278
       /* jsonObject.put("certificates",repository.getCertificates());
279
        jsonObject.put("citationguidelineurl",repository.getCitationGuidelineUrl());
280
        jsonObject.put("databaseaccessrestriction",repository.getDatabaseAccessRestriction());
281
        jsonObject.put("databaseaccesstype",repository.getDatabaseAccessType());
282
        jsonObject.put("datauploadrestriction",repository.getDataUploadRestriction());
283
        jsonObject.put("datauploadtype",repository.getDataUploadType());
284
        jsonObject.put("missionstatementurl",repository.getMissionStatementUrl());
285
        jsonObject.put("od_contenttypes",repository.getOdContentTypes());
286
        jsonObject.put("officialname",repository.getOfficialname());
287
        jsonObject.put("pidsystems",repository.getPidSystems());
288
        jsonObject.put("provenanceaction",repository.getProvenanceActionClass());
289
        jsonObject.put("qualitymanagementkind",repository.getQualityManagementKind());
290
        jsonObject.put("releaseenddate",convertDateToString(repository.getReleaseEndDate()));
291
        jsonObject.put("releasestartdate",convertDateToString(repository.getReleaseStartDate()));
292
        jsonObject.put("serviceprovider",repository.getServiceProvider());
293
        jsonObject.put("versioning",repository.getVersioning());
294
        //datasource.get("platform");
295
        //datasource.get("subjects");*/
296
        return jsonObject.toString();
297
    }
298

    
299
    public static String repositoryInterfaceObjectToJson(Repository repository,RepositoryInterface repositoryInterface) throws JSONException {
300

    
301
        JSONObject jsonObject = new JSONObject();
302

    
303
        jsonObject.put("id",repositoryInterface.getId());
304
        jsonObject.put("protocol",repositoryInterface.getAccessProtocol());
305
        jsonObject.put("datasource",repository.getId());
306
        jsonObject.put("contentdescription",repositoryInterface.getContentDescription());
307
        jsonObject.put("typology",repositoryInterface.getTypology());
308
        jsonObject.put("compatibility",repositoryInterface.getDesiredCompatibilityLevel());
309
        jsonObject.put("compatibilityOverride",repositoryInterface.getDesiredCompatibilityLevel());
310

    
311
        jsonObject.put("lastCollectionTotal","");
312

    
313
        jsonObject.put("lastCollectionDate",repositoryInterface.getLastCollectionDate());
314
        jsonObject.put("lastAggregationTotal","");
315
        jsonObject.put("lastAggregationDate","");
316
        jsonObject.put("lastDownloadTotal","");
317
        jsonObject.put("lastDownloadDate","");
318

    
319
        jsonObject.put("baseurl",repositoryInterface.getBaseUrl());
320
        jsonObject.put("removable",repositoryInterface.isRemovable());
321

    
322
        
323
        JSONArray apiparams = new JSONArray();
324
        for(String param: repositoryInterface.getAccessParams().keySet()){
325
            JSONObject jo = new JSONObject();
326
            jo.put("param",param);
327
            jo.put("value",repositoryInterface.getAccessParams().get(param));
328
            apiparams.put(jo);
329
        }
330
        jsonObject.put("apiParams",apiparams);
331

    
332

    
333
//        jsonObject.put("metadataIdentifierPath",repositoryInterface.getMetadataIdentifierPath());
334

    
335

    
336
        return jsonObject.toString();
337
    }
338

    
339
    public static ArrayList<String> readFile(String filename) {
340
        String line;
341
        ArrayList<String> list = new ArrayList<String>();
342
        try {
343
            //InputStream in = Converter.class.getResourceAsStream("resources/eu/dnetlib/repo/manager/service/utils/"+filename);
344
            InputStream in = Converter.class.getClass().getResourceAsStream("/eu/**/" + filename);
345
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
346
            while((line = br.readLine()) != null) {
347
                list.add(line.trim());
348
            }
349
            br.close();
350
        } catch (IOException e) {
351
            LOGGER.debug("Error opening file!");
352
            e.printStackTrace();
353
        }
354
        return list;
355
    }
356

    
357
    public static List<AggregationDetails> getAggregationHistoryFromJson(JSONObject datasourceInfo) throws JSONException {
358

    
359

    
360
      // if(datasourceInfo.get("aggregationHistory").toString().equals("[]"))
361
       //    return null;
362

    
363
        JSONArray rs = new JSONArray(datasourceInfo.get("aggregationHistory").toString());
364
        List<AggregationDetails> aggregationDetailsList = new ArrayList<>();
365
        for(int i=0;i<rs.length();i++)
366
            aggregationDetailsList.add(jsonToAggregationDetails(rs.getJSONObject(i)));
367
        return aggregationDetailsList;
368
    }
369

    
370
    private static AggregationDetails jsonToAggregationDetails(JSONObject aggregationObject) throws JSONException {
371

    
372
        AggregationDetails aggregationDetails = new AggregationDetails();
373

    
374
        aggregationDetails.setAggregationStage(aggregationObject.get("aggregationStage").toString());
375
        if(aggregationObject.has("collectionMode"))
376
            aggregationDetails.setCollectionMode(aggregationObject.get("collectionMode").toString());
377
        aggregationDetails.setDate(convertStringToDate(aggregationObject.get("date").toString()));
378
        aggregationDetails.setNumberOfRecords(Integer.parseInt(aggregationObject.get("numberOfRecords").toString()));
379
        return aggregationDetails;
380
    }
381

    
382
    public static AggregationDetails getLastCollectionFromJson(JSONObject datasourceInfo) throws JSONException {
383

    
384
        if( datasourceInfo.get("lastCollection").equals(null))
385
            return null;
386

    
387
        return jsonToAggregationDetails(datasourceInfo.getJSONObject("lastCollection"));
388
    }
389

    
390
    public static AggregationDetails getLastTransformationFromJson(JSONObject datasourceInfo) throws JSONException {
391

    
392
        if( datasourceInfo.get("lastTransformation").equals(null))
393
            return null;
394

    
395
        return jsonToAggregationDetails(datasourceInfo.getJSONObject("lastTransformation"));
396
    }
397

    
398
    public static List<Timezone> toTimezones(List<String> timezones) {
399

    
400
        List<Timezone> tmz = new ArrayList<>();
401
        for(String t : timezones){
402
            String[] s = t.split("\t");
403
            tmz.add(new Timezone(s[1],Double.parseDouble(s[0])));
404
        }
405
        return tmz;
406
    }
407

    
408
    public static String getOpenaireId(String repositoryId) {
409
        if (repositoryId != null && repositoryId.contains("::"))
410
            return repositoryId.split("::")[0] + "::" + DigestUtils.md5Hex(repositoryId.split("::")[1]);
411
        return null;
412
    }
413

    
414
}
(1-1/2)