Project

General

Profile

Download (8.13 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2009 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9
package eu.etaxonomy.cdm.ext.bci;
10

    
11
import java.io.BufferedReader;
12
import java.io.IOException;
13
import java.io.InputStream;
14
import java.io.InputStreamReader;
15
import java.net.HttpURLConnection;
16
import java.net.MalformedURLException;
17
import java.net.URI;
18
import java.net.URISyntaxException;
19
import java.net.URL;
20
import java.util.ArrayList;
21
import java.util.HashMap;
22
import java.util.List;
23
import java.util.Map;
24

    
25
import org.apache.commons.lang.StringUtils;
26
import org.apache.http.NameValuePair;
27
import org.apache.http.message.BasicNameValuePair;
28
import org.apache.log4j.Logger;
29
import org.springframework.stereotype.Component;
30

    
31
import com.ibm.lsid.MalformedLSIDException;
32

    
33
import eu.etaxonomy.cdm.api.application.ICdmRepository;
34
import eu.etaxonomy.cdm.common.CdmUtils;
35
import eu.etaxonomy.cdm.ext.common.SchemaAdapterBase;
36
import eu.etaxonomy.cdm.ext.common.ServiceWrapperBase;
37
import eu.etaxonomy.cdm.model.common.IdentifiableEntity;
38
import eu.etaxonomy.cdm.model.common.LSID;
39
import eu.etaxonomy.cdm.model.occurrence.Collection;
40
import eu.etaxonomy.cdm.model.reference.OriginalSourceType;
41
import eu.etaxonomy.cdm.model.reference.Reference;
42
import eu.etaxonomy.cdm.model.reference.ReferenceFactory;
43

    
44
/**
45
* This service allows to query the Biodiversity collection index {@link http://www.biodiversitycollectionsindex.org}
46
* @author a.mueller
47
* @since Aug 16, 2010
48
 */
49
@Component
50
public class BciServiceWrapper
51
        extends ServiceWrapperBase<Collection>
52
        implements IBciServiceWrapper{
53

    
54
    private static final Logger logger = Logger.getLogger(BciServiceWrapper.class);
55

    
56
	 private enum ServiceType{
57
		 AUTHOR,
58
		 NAME,
59
		 PUBLICATION,
60
	 }
61

    
62
//	private URL serviceUrl;
63

    
64
// ******************************** CONSTRUCTOR **************************************
65

    
66

    
67
//	/**
68
//	 * Creates new instance of this factory and connects it to the given
69
//	 * CDM Community Stores access point.
70
//	 *
71
//	 * Typically, there is no need to instantiate this class.
72
//	 */
73
//	protected IpniService(URL webserviceUrl){
74
//		this.serviceUrl = webserviceUrl;
75
//	}
76

    
77
// ****************************** METHODS ****************************************************/
78

    
79
	@Override
80
    public List<Collection> getCollectionsByCode(String code, ICdmRepository appConfig){
81

    
82
		SchemaAdapterBase<Collection> schemaAdapter = schemaAdapterMap.get("recordSchema");
83
		if(schemaAdapter == null){
84
			throw new RuntimeException("No SchemaAdapter found for " + "recordSchema");
85
		}
86

    
87
		String SruOperation = "searchRetrieve";
88

    
89
		List<NameValuePair> pairs = new ArrayList<>();
90
		pairs.add(new BasicNameValuePair("code", SruOperation));
91

    
92
		Map<String, String> requestHeaders = new HashMap<>();
93
		requestHeaders.put("Accept-Charset", "UTF-8");
94

    
95
		try {
96
			URI requestUri = createUri(null, pairs);
97
			InputStream stream = executeHttpGet(requestUri, requestHeaders);
98
			return schemaAdapter.getCmdEntities(stream);
99
		} catch (IOException e) {
100
			// thrown by doHttpGet
101
			logger.error(e);
102
		} catch (URISyntaxException e) {
103
			// thrown by createUri
104
			logger.error(e);
105
		}
106

    
107
		code = normalizeParameter(code);
108
		String request = code;
109

    
110
		@SuppressWarnings("unchecked")
111
        List<Collection> result = (List<Collection>)queryService(request, appConfig, getServiceUrl(IBciServiceWrapper.LOOKUP_CODE_REST), ServiceType.AUTHOR);
112
		return result;
113
	}
114

    
115
	private List<? extends IdentifiableEntity> queryService(String request, ICdmRepository appConfig, URL serviceUrl, ServiceType serviceType){
116
		try {
117
            // create the request url
118
            URL newUrl = new URL(serviceUrl.getProtocol(),
119
                                                     serviceUrl.getHost(),
120
                                                     serviceUrl.getPort(),
121
                                                     serviceUrl.getPath()
122
                                                     + "" + request);
123
            // open a connection
124
            HttpURLConnection connection = (HttpURLConnection) newUrl.openConnection();
125
            // set the accept property to XML so we can use jdom to handle the content
126
            //connection.setRequestProperty("Accept", "text/xml");
127

    
128
            logger.info("Firing request for URL: " + newUrl);
129

    
130
            int responseCode = connection.getResponseCode();
131

    
132
            // get the content at the resource
133
            InputStream content = (InputStream) connection.getContent();
134

    
135
            // build the result
136
            List<? extends IdentifiableEntity<?>> result;
137
            if (serviceType.equals(ServiceType.AUTHOR)){
138
            	result = buildCollectionList(content, appConfig);
139
            }else if (serviceType.equals(ServiceType.NAME)){
140
            	//
141
            	result = null;
142
            }else{
143
            	//
144
            	result = null;
145
            }
146
            if(responseCode == HttpURLConnection.HTTP_OK){
147
                    return result;
148
            }else if(responseCode == HttpURLConnection.HTTP_MULT_CHOICE){
149
                    return result;
150
            }else{
151
                //TODO error handling
152
            	logger.error("No Http_OK");
153
            }
154

    
155
        } catch (IOException e) {
156
                logger.error("No content for request: " + request);
157
        }
158

    
159
        // error
160
        return null;
161
    }
162

    
163

    
164
	private List<Collection> buildCollectionList(InputStream content, ICdmRepository appConfig) throws IOException {
165
		List<Collection> result = new ArrayList<Collection>();
166
		BufferedReader reader = new BufferedReader (new InputStreamReader(content));
167

    
168
		String headerLine = reader.readLine();
169

    
170
		String line = reader.readLine();
171
		while (StringUtils.isNotBlank(line)){
172
			Collection collection = getCollectionFromLine(line, appConfig);
173
			result.add(collection);
174
			line = reader.readLine();
175
		}
176

    
177
		return result;
178
	}
179

    
180
	private Collection getCollectionFromLine(String line, ICdmRepository appConfig) {
181
		//urn:lsid:biocol.org:col:15727	http://biocol.org/urn:lsid:biocol.org:col:15727	University of Bergen Herbarium
182
		String[] splits = line.split("\t");
183
		if (splits.length != 3){
184
			logger.warn("Unknwon BCI line format: " + line);
185
			return null;
186
		}
187
		String lsidString = splits[0];
188
		String urlString = splits[1];
189
		String collectionName = splits[2];
190

    
191
		Collection result = Collection.NewInstance();
192

    
193
		//LSID
194
		LSID lsid = null;
195
		try {
196
			lsid = new LSID(lsidString);
197
		} catch (MalformedLSIDException e) {
198
			logger.warn("Malformed LSID " + lsidString, e);
199
		}
200

    
201
		result.setLsid(lsid);
202
		String id = getCollectionId(lsid);
203

    
204
		result.setName(collectionName);
205

    
206
		//id, citation
207
		Reference citation = getBciCitation(appConfig);
208
		result.addSource(OriginalSourceType.Lineage, id, null, citation, null);
209

    
210

    
211
		return result;
212
	}
213

    
214

    
215
	private String getCollectionId(LSID lsid) {
216
		String result = lsid == null? null : lsid.getObject();
217
		return result;
218
	}
219

    
220

    
221
	private Reference getBciCitation(ICdmRepository appConfig) {
222
		Reference bciReference;
223
		if (appConfig != null){
224
			bciReference = appConfig.getReferenceService().find(uuidBci);
225
			if (bciReference == null){
226
				bciReference = getNewBciReference();
227
				bciReference.setUuid(uuidBci);
228
				appConfig.getReferenceService().save(bciReference);
229
			}
230
		}else{
231
			bciReference = getNewBciReference();
232
		}
233
		return bciReference;
234
	}
235

    
236
	private Reference getNewBciReference() {
237
		Reference bciReference;
238
		bciReference = ReferenceFactory.newDatabase();
239
		bciReference.setTitleCache("Biodiversity Collection Index (BCI))", true);
240
		return bciReference;
241
	}
242

    
243
	private String normalizeParameter(String parameter) {
244
		String result = CdmUtils.Nz(parameter).replace(" ", "+");
245
		return result;
246
	}
247

    
248
	@Override
249
    public URL getServiceUrl(String url) {
250
		URL serviceUrl;
251
		try {
252
			serviceUrl = new URL(url);
253
		} catch (MalformedURLException e) {
254
			throw new RuntimeException("This should not happen", e);
255
		}
256
		return serviceUrl;
257
	}
258
}
(2-2/3)