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.shared.AggregationDetails;
7
import eu.dnetlib.repo.manager.shared.Timezone;
8
import org.apache.commons.codec.digest.DigestUtils;
9
import org.apache.log4j.Logger;
10
import org.json.JSONArray;
11
import org.json.JSONException;
12
import org.json.JSONObject;
13

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

    
22
public class Converter {
23

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

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

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

    
32
        if( datasource.equals(null))
33
            return null;
34

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

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

    
42
        repository.setWebsiteUrl(datasource.get("websiteurl").toString());
43
        repository.setLogoUrl(datasource.get("logourl").toString());
44
        if(repository.getLogoUrl().equals("null"))
45
            repository.setLogoUrl("");
46

    
47
        repository.setContactEmail(datasource.get("contactemail").toString());
48
        repository.setLatitude( toDouble(datasource.get("latitude").toString()));
49
        repository.setLongitude(toDouble(datasource.get("longitude").toString()));
50
        Double timezone = toDouble(datasource.get("timezone").toString());
51
        repository.setTimezone(timezone!=null?timezone:0.0);
52
        repository.setNamespacePrefix(datasource.get("namespaceprefix").toString());
53
        repository.setOdLanguages(datasource.get("languages").toString());
54
        repository.setDateOfValidation(convertStringToDate( datasource.get("dateofvalidation").toString()));
55

    
56
        /*  typology -> platform
57
         *  datasource class -> typology */
58
        repository.setTypology(datasource.get("platform").toString());
59
        if(repository.getTypology().equals("null"))
60
            repository.setTypology("");
61
        repository.setDatasourceClass(datasource.get("typology").toString());
62

    
63
        repository.setDateOfCollection(convertStringToDate( datasource.get("dateofcollection").toString()));
64
        repository.setActivationId(datasource.get("activationId").toString());
65

    
66
        repository.setDescription(datasource.get("description").toString());
67
        if(repository.getDescription().equals("null"))
68
            repository.setDescription("");
69

    
70
        repository.setIssn(datasource.get("issn").toString());
71
        repository.setLissn(datasource.get("lissn").toString());
72
        repository.setEissn(datasource.get("eissn").toString());
73
        repository.setRegisteredBy(datasource.get("registeredby").toString());
74

    
75
        /* managed field */
76
        repository.setRegistered(Boolean.parseBoolean(datasource.get("managed").toString()));
77

    
78
        //subjects
79
        repository.setAggregator(datasource.get("aggregator").toString());
80

    
81
        String collectedFrom = datasource.get("collectedfrom").toString();
82
        //TODO check data consistency
83
        String type = "UNKNOWN";
84
        if (collectedFrom.equalsIgnoreCase("openaire____::opendoar")) {
85
            type = "opendoar";
86
        } else if (collectedFrom.equalsIgnoreCase("openaire____::re3data")) {
87
            type = "re3data";
88
        } else if (collectedFrom.equalsIgnoreCase("infrastruct_::openaire")) {
89
            type = "journal";
90
        }
91
        /* collected from field  */
92
        repository.setDatasourceType(type);
93
        repository.setCollectedFrom(collectedFrom);
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<Repository> jsonToRepositoryList(JSONObject json) throws JSONException {
139

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

    
147
    public static List<RepositoryInterface> jsonToRepositoryInterfaceList(JSONObject json) throws JSONException {
148

    
149
        List<RepositoryInterface> resultSet = new ArrayList<>();
150
        JSONArray rs = json.getJSONArray("api");
151
        for(int i=0;i<rs.length();i++)
152
            resultSet.add(jsonToRepositoryInterfaceObject( rs.getJSONObject(i)) );
153
        return resultSet;
154
    }
155

    
156
    public static RepositoryInterface jsonToRepositoryInterfaceObject(JSONObject repositoryInterfaceObject) throws JSONException {
157

    
158
        RepositoryInterface repositoryInterface = new RepositoryInterface();
159

    
160
        repositoryInterface.setId(repositoryInterfaceObject.get("id").toString());
161
        repositoryInterface.setAccessProtocol(repositoryInterfaceObject.get("protocol").toString());
162
        repositoryInterface.setContentDescription(repositoryInterfaceObject.get("contentdescription").toString());
163
        repositoryInterface.setTypology(repositoryInterfaceObject.get("typology").toString());
164
        repositoryInterface.setCompliance(repositoryInterfaceObject.get("compatibility").toString());
165
        repositoryInterface.setLastCollectionDate(repositoryInterfaceObject.get("lastCollectionDate").toString());
166

    
167
        repositoryInterface.setBaseUrl(repositoryInterfaceObject.get("baseurl").toString());
168
        repositoryInterface.setRemovable(Boolean.parseBoolean(repositoryInterfaceObject.get("removable").toString()));
169

    
170

    
171
       // repositoryInterface.setMetadataIdentifierPath(repositoryInterfaceObject.get("metadataIdentifierPath").toString());
172
        repositoryInterface.setDesiredCompatibilityLevel(repositoryInterfaceObject.get("compatibility").toString());
173
        //repositoryInterface.setActive(Boolean.parseBoolean(repositoryInterfaceObject.get("active").toString()));
174

    
175

    
176
        Map<String, String> accessParams = new HashMap<>();
177
        Map<String, String> extraFields = new HashMap<>();
178

    
179
        ObjectMapper mapper = new ObjectMapper();
180
        JSONArray apiparams = repositoryInterfaceObject.getJSONArray("apiParams");
181

    
182
        for(int i=0;i<apiparams.length();i++)
183
            accessParams.put(apiparams.getJSONObject(i).getString("param"),apiparams.getJSONObject(i).getString("value"));
184

    
185
        repositoryInterface.setAccessParams(accessParams);
186

    
187
        return repositoryInterface;
188
    }
189

    
190
    public static String repositoryObjectToJson(Repository repository) throws JSONException {
191

    
192
        JSONObject jsonObject = new JSONObject();
193

    
194
        jsonObject.put("id",repository.getId());
195
        jsonObject.put("openaireId",getOpenaireId(repository.getId()));
196
        jsonObject.put("officialname",repository.getOfficialName());
197
        jsonObject.put("englishname",repository.getEnglishName());
198
        jsonObject.put("websiteurl",repository.getWebsiteUrl());
199
        jsonObject.put("logourl",repository.getLogoUrl());
200
        jsonObject.put("contactemail",repository.getContactEmail());
201
        jsonObject.put("longitude",repository.getLongitude().toString());
202
        jsonObject.put("latitude",repository.getLatitude().toString());
203
        jsonObject.put("timezone",repository.getTimezone());
204
        jsonObject.put("namespaceprefix",repository.getNamespacePrefix());
205
        jsonObject.put("languages",repository.getOdLanguages());
206
        jsonObject.put("dateofvalidation",convertDateToString(repository.getDateOfValidation()));
207

    
208
        /*
209
        * typology -> platform
210
        * datasource class -> typology
211
        * */
212
        jsonObject.put("typology",repository.getDatasourceClass());
213
        jsonObject.put("platform",repository.getTypology());
214

    
215
        jsonObject.put("dateofcollection",convertDateToString(repository.getDateOfCollection()));
216
        jsonObject.put("activationId",repository.getActivationId());
217
        jsonObject.put("description",repository.getDescription());
218
        jsonObject.put("eissn",repository.getEissn());
219
        jsonObject.put("issn",repository.getIssn());
220
        jsonObject.put("lissn",repository.getLissn());
221
        jsonObject.put("registeredby",repository.getRegisteredBy());
222

    
223
        jsonObject.put("aggregator",repository.getAggregator());
224
        jsonObject.put("collectedfrom",repository.getCollectedFrom());
225

    
226
        jsonObject.put("managed",repository.isRegistered());
227

    
228
        JSONObject organization = new JSONObject();
229
        organization.put("legalname",repository.getOrganization());
230
        organization.put("country",repository.getCountryCode());
231
        organization.put("legalshortname","");
232
        organization.put("websiteurl","");
233
        organization.put("logourl","");
234

    
235
        JSONArray organizations = new JSONArray();
236
        organizations.put(organization);
237
        jsonObject.put("organizations",organizations);
238

    
239

    
240

    
241

    
242
        //TODO check fields
243
       /* jsonObject.put("certificates",repository.getCertificates());
244
        jsonObject.put("citationguidelineurl",repository.getCitationGuidelineUrl());
245
        jsonObject.put("databaseaccessrestriction",repository.getDatabaseAccessRestriction());
246
        jsonObject.put("databaseaccesstype",repository.getDatabaseAccessType());
247
        jsonObject.put("datauploadrestriction",repository.getDataUploadRestriction());
248
        jsonObject.put("datauploadtype",repository.getDataUploadType());
249
        jsonObject.put("missionstatementurl",repository.getMissionStatementUrl());
250
        jsonObject.put("od_contenttypes",repository.getOdContentTypes());
251
        jsonObject.put("officialname",repository.getOfficialName());
252
        jsonObject.put("pidsystems",repository.getPidSystems());
253
        jsonObject.put("provenanceaction",repository.getProvenanceActionClass());
254
        jsonObject.put("qualitymanagementkind",repository.getQualityManagementKind());
255
        jsonObject.put("releaseenddate",convertDateToString(repository.getReleaseEndDate()));
256
        jsonObject.put("releasestartdate",convertDateToString(repository.getReleaseStartDate()));
257
        jsonObject.put("serviceprovider",repository.getServiceProvider());
258
        jsonObject.put("versioning",repository.getVersioning());
259
        //datasource.get("platform");
260
        //datasource.get("subjects");*/
261
        return jsonObject.toString();
262
    }
263

    
264
    public static String repositoryInterfaceObjectToJson(Repository repository,RepositoryInterface repositoryInterface) throws JSONException {
265

    
266
        JSONObject jsonObject = new JSONObject();
267

    
268
        jsonObject.put("id",repositoryInterface.getId());
269
        jsonObject.put("protocol",repositoryInterface.getAccessProtocol());
270
        jsonObject.put("datasource",repository.getId());
271
        jsonObject.put("contentdescription",repositoryInterface.getContentDescription());
272
        jsonObject.put("typology",repositoryInterface.getTypology());
273
        jsonObject.put("compatibility",repositoryInterface.getDesiredCompatibilityLevel());
274
        jsonObject.put("compatibilityOverride",repositoryInterface.getDesiredCompatibilityLevel());
275

    
276
        jsonObject.put("lastCollectionTotal","");
277

    
278
        jsonObject.put("lastCollectionDate",repositoryInterface.getLastCollectionDate());
279
        jsonObject.put("lastAggregationTotal","");
280
        jsonObject.put("lastAggregationDate","");
281
        jsonObject.put("lastDownloadTotal","");
282
        jsonObject.put("lastDownloadDate","");
283

    
284
        jsonObject.put("baseurl",repositoryInterface.getBaseUrl());
285
        jsonObject.put("removable",repositoryInterface.isRemovable());
286

    
287
        
288
        JSONArray apiparams = new JSONArray();
289
        for(String param: repositoryInterface.getAccessParams().keySet()){
290
            JSONObject jo = new JSONObject();
291
            jo.put("param",param);
292
            jo.put("value",repositoryInterface.getAccessParams().get(param));
293
            apiparams.put(jo);
294
        }
295
        jsonObject.put("apiParams",apiparams);
296

    
297

    
298
//        jsonObject.put("metadataIdentifierPath",repositoryInterface.getMetadataIdentifierPath());
299

    
300

    
301
        return jsonObject.toString();
302
    }
303

    
304
    public static ArrayList<String> readFile(String filename) {
305
        String line;
306
        ArrayList<String> list = new ArrayList<String>();
307
        try {
308
            //InputStream in = Converter.class.getResourceAsStream("resources/eu/dnetlib/repo/manager/service/utils/"+filename);
309
            InputStream in = Converter.class.getClass().getResourceAsStream("/eu/**/" + filename);
310
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
311
            while((line = br.readLine()) != null) {
312
                list.add(line.trim());
313
            }
314
            br.close();
315
        } catch (IOException e) {
316
            LOGGER.debug("Error opening file!");
317
            e.printStackTrace();
318
        }
319
        return list;
320
    }
321

    
322
    public static List<AggregationDetails> getAggregationHistoryFromJson(JSONObject datasourceInfo) throws JSONException {
323

    
324

    
325
       if(datasourceInfo.get("aggregationHistory").toString().equals("[]"))
326
           return null;
327

    
328
        JSONArray rs = new JSONArray(datasourceInfo.get("aggregationHistory").toString());
329
        List<AggregationDetails> aggregationDetailsList = new ArrayList<>();
330
        for(int i=0;i<rs.length();i++)
331
            aggregationDetailsList.add(jsonToAggregationDetails(rs.getJSONObject(i)));
332
        return aggregationDetailsList;
333
    }
334

    
335
    private static AggregationDetails jsonToAggregationDetails(JSONObject aggregationObject) throws JSONException {
336

    
337
        AggregationDetails aggregationDetails = new AggregationDetails();
338

    
339
        aggregationDetails.setAggregationStage(aggregationObject.get("aggregationStage").toString());
340
        if(aggregationObject.has("collectionMode"))
341
            aggregationDetails.setCollectionMode(aggregationObject.get("collectionMode").toString());
342
        aggregationDetails.setDate(convertStringToDate(aggregationObject.get("date").toString()));
343
        aggregationDetails.setNumberOfRecords(Integer.parseInt(aggregationObject.get("numberOfRecords").toString()));
344
        return aggregationDetails;
345
    }
346

    
347
    public static AggregationDetails getLastCollectionFromJson(JSONObject datasourceInfo) throws JSONException {
348

    
349
        if( datasourceInfo.get("lastCollection").equals(null))
350
            return null;
351

    
352
        return jsonToAggregationDetails(datasourceInfo.getJSONObject("lastCollection"));
353
    }
354

    
355
    public static AggregationDetails getLastTransformationFromJson(JSONObject datasourceInfo) throws JSONException {
356

    
357
        if( datasourceInfo.get("lastTransformation").equals(null))
358
            return null;
359

    
360
        return jsonToAggregationDetails(datasourceInfo.getJSONObject("lastTransformation"));
361
    }
362

    
363
    public static List<Timezone> toTimezones(List<String> timezones) {
364

    
365
        List<Timezone> tmz = new ArrayList<>();
366
        for(String t : timezones){
367
            String[] s = t.split("\t");
368
            tmz.add(new Timezone(s[1],Double.parseDouble(s[0])));
369
        }
370
        return tmz;
371
    }
372

    
373
    public static String getOpenaireId(String repositoryId) {
374
        if (repositoryId != null && repositoryId.contains("::"))
375
            return repositoryId.split("::")[0] + "::" + DigestUtils.md5Hex(repositoryId.split("::")[1]);
376
        return null;
377
    }
378
}
(1-1/2)