Project

General

Profile

Download (15.2 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
 * Copyright (C) 2007 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.print;
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.URISyntaxException;
16
import java.net.URL;
17
import java.util.ArrayList;
18
import java.util.Arrays;
19
import java.util.HashMap;
20
import java.util.List;
21
import java.util.Map;
22
import java.util.UUID;
23

    
24
import org.apache.http.HttpResponse;
25
import org.apache.http.NameValuePair;
26
import org.apache.http.message.BasicNameValuePair;
27
import org.apache.logging.log4j.LogManager;
28
import org.apache.logging.log4j.Logger;
29
import org.jdom.Document;
30
import org.jdom.Element;
31
import org.jdom.JDOMException;
32
import org.jdom.xpath.XPath;
33

    
34
import eu.etaxonomy.cdm.common.URI;
35
import eu.etaxonomy.cdm.common.UriUtils;
36
import eu.etaxonomy.cdm.common.monitor.IProgressMonitor;
37
import eu.etaxonomy.cdm.print.XMLHelper.EntityType;
38

    
39
/**
40
 * Implementation of an IXMLEntityFactory that is connected to a CDM Community
41
 * Server on a remote machine. API call will be executed by accessing the
42
 * servers REST API.
43
 *
44
 * @author n.hoffmann
45
 * @author l.morris
46
 * @since Apr 6, 2010
47
 */
48
public class RemoteXMLEntityFactory extends XmlEntityFactoryBase {
49

    
50
	private static final Logger logger = LogManager.getLogger(RemoteXMLEntityFactory.class);
51

    
52
	private URL serviceUrl;
53

    
54
	private IProgressMonitor monitor;
55

    
56
	private static final List<NameValuePair> UNLIMITED_RESULTS = Arrays
57
			.asList(new NameValuePair[] { new BasicNameValuePair("start", "0"),
58
					new BasicNameValuePair("limit", "-1") });
59

    
60
	private static final String UUID = "{uuid}";
61

    
62
	private static final String CLASSIFICATIONS = "classification";
63
	private static final String CLASSIFICATION_CHILD_NODES = "classification/"
64
			+ UUID + "/childNodes/";
65
	private static final String TAXONNODE_CHILD_NODES = "taxonNode/" + UUID
66
			+ "/childNodes/";
67
	private static final String TAXONNODE = "taxonNode/" + UUID;
68
	private static final String TAXONNODE_TAXON = TAXONNODE + "/taxon";
69
	// private static final String TAXONNODES = TAXONNODE + "/taxon";
70
	private static final String TAXA_AND_NAMES = "taxon/findTaxaAndNames";
71
	private static final String TAXONNODES = "taxon/" + UUID + "/taxonNodes";
72
	// http://dev.e-taxonomy.eu/cdmserver/palmae/portal/taxon/d58c0b44-29f8-4071-aa49-32baa185296f/taxonNodes
73

    
74
	private static final String FEATURETREES = "featureTree";
75
	private static final String FEATURETREE = "featureTree/" + UUID;
76
	private static final String FEATURENODE = "featurenode/" + UUID;
77
	// private static final String FEATURENODE = "featureNode/" + UUID +
78
	// "/childNodes";
79
	private static final String FEATURENODE_FEATURE = FEATURENODE + "/feature";
80

    
81
	private static final String NAME_TYPE_DESIGNATIONS = "name/" + UUID
82
			+ "/typeDesignations";
83

    
84
	// TAXON_ACCEPTED should populate references but authorship is not always
85
	// populated so call the reference controller directly
86
	private static final String REFERENCES = "portal/reference/" + UUID;
87

    
88
	private static final String TAXON_ACCEPTED = "portal/taxon/" + UUID;
89
	private static final String TAXON_SYNONYMY = "portal/taxon/" + UUID
90
			+ "/synonymy";
91
	private static final String TAXON_DESCRIPTIONS = "portal/taxon/" + UUID
92
			+ "/descriptions";
93

    
94
	private static final String POLYTOMOUS_KEY = "dto/polytomousKey/linkedStyle?findByTaxonomicScope="
95
			+ UUID;
96
	// dto/polytomousKey/linkedStyle.json?findByTaxonomicScope=f820f533-06f2-4116-87e9-c9319c0c1cbf
97

    
98
	// images /portal/taxon/{uuid}
99
	private static final String TAXON_MEDIA = "portal/taxon/" + UUID + "/media";
100

    
101
	// http://test.e-taxonomy.eu/cdmserver/palmae/portal/media/bb49e8f0-49bc-41f7-9674-1cb36eb716fb
102

    
103
	/**
104
	 * Creates new instance of this factory and connects it to the given CDM
105
	 * Community Stores access point.
106
	 *
107
	 * Typically, there is no need to instantiate this class.
108
	 *
109
	 * @param monitor
110
	 */
111
	protected RemoteXMLEntityFactory(URL webserviceUrl, IProgressMonitor monitor) {
112
		this.serviceUrl = webserviceUrl;
113
		this.monitor = monitor;
114
	}
115

    
116
	/*
117
	 * (non-Javadoc)
118
	 *
119
	 * @see eu.etaxonomy.printpublisher.IXMLEntityFactory#getClassifications()
120
	 */
121
	@Override
122
    public List<Element> getClassifications() {
123
		Element result = queryServiceWithParameters(CLASSIFICATIONS,
124
				UNLIMITED_RESULTS);
125
		return processElementList(result);
126
	}
127

    
128
	/*
129
	 * (non-Javadoc)
130
	 *
131
	 * @see
132
	 * eu.etaxonomy.printpublisher.IXMLEntityFactory#getChildNodes(org.jdom.
133
	 * Element)
134
	 */
135
	@Override
136
    public List<Element> getChildNodes(Element treeNode) {
137
		EntityType entityType = XMLHelper.getEntityType(treeNode);
138

    
139
		Element result = null;
140

    
141
		if (EntityType.CLASSIFICATION.equals(entityType)) {
142
			result = queryService(treeNode, CLASSIFICATION_CHILD_NODES);
143
		} else if (EntityType.TAXON_NODE.equals(entityType)) {
144
			result = queryService(treeNode, TAXONNODE_CHILD_NODES);
145
		}
146

    
147
		return processElementList(result);
148
	}
149

    
150
	/*
151
	 * (non-Javadoc)
152
	 *
153
	 * @see
154
	 * eu.etaxonomy.printpublisher.IXMLEntityFactory#getTaxonNode(java.util.
155
	 * UUID)
156
	 */
157
	@Override
158
    public Element getTaxonNode(UUID taxonNodeUuid) {
159
		return queryService(taxonNodeUuid, TAXONNODE);
160
	}
161

    
162
	/*
163
	 * Returns the taxonNode for a specific taxon name string.
164
	 */
165
	@Override
166
    public Element getTaxonNodesByName(String taxonName, String classification) {
167

    
168
		// 1-To find the uuid of a Taxon name:
169
		// http://dev.e-taxonomy.eu/cdmserver/palmae/taxon/findTaxaAndNames.json?doTaxa=1&matchMode=EXACT&query=Acrocomia
170
		// 2-Then get the taxonNodes for this name:
171
		// http://dev.e-taxonomy.eu/cdmserver/palmae/portal/taxon/d58c0b44-29f8-4071-aa49-32baa185296f/taxonNodes
172
		Element taxonNodes = null;
173

    
174
		List <NameValuePair> params = new ArrayList<NameValuePair>();
175
		params.add(new BasicNameValuePair("doTaxa", "1"));
176
		params.add(new BasicNameValuePair("matchMode", "EXACT"));
177
		params.add(new BasicNameValuePair("query", taxonName));
178

    
179
		if (classification != null) {
180
			List<Element> classifications = getClassifications();
181
			String classificationUuid = "";
182

    
183
			// String xPathString="//titleCache[.='" +
184
			// classification+"']/../uuid";
185

    
186
			for (Element element : classifications) {
187
				if (element.getChild("titleCache").getValue()
188
						.equals(classification)) {
189
					System.out.println(element.getChild("uuid").getValue());
190
					classificationUuid = element.getChild("uuid").getValue();
191
				}
192
			}
193
			params.add(new BasicNameValuePair("tree", classificationUuid));
194
		}
195

    
196
		Element element = queryServiceWithParameters(TAXA_AND_NAMES, params);
197

    
198
		Element taxonNodeString = null;
199
		UUID taxonNodeUuid = null;
200

    
201
		try {
202

    
203
			// TODO: we only get the first Taxon to match this name - we should
204
			// get all Taxons to match the name
205
			Element taxonUuid = (Element) XPath.selectSingleNode(element,
206
					"//records/e[1]");
207

    
208
			taxonNodes = queryService(taxonUuid, TAXONNODES);
209

    
210
			taxonNodeString = (Element) XPath.selectSingleNode(taxonNodes,
211
					"//PersistentSet/e[1]/uuid");
212
			String val = taxonNodeString.getValue();
213
			taxonNodeUuid = java.util.UUID.fromString(taxonNodeString
214
					.getValue());
215

    
216
		} catch (JDOMException e) {
217
			// TODO Auto-generated catch block
218
			e.printStackTrace();
219
		}
220
		return getTaxonNode(taxonNodeUuid);
221
		// TODO: Should be return a set of taxonNodes if there is more than one
222
		// for the name
223
		// public List<Element> getTaxonNodesByName(String taxonName) {
224
		// return taxonNodes;
225
	}
226

    
227
	/*
228
	 * (non-Javadoc)
229
	 *
230
	 * @see
231
	 * eu.etaxonomy.printpublisher.IXMLEntityFactory#getFeatureTree(java.util
232
	 * .UUID)
233
	 */
234
	@Override
235
    public Element getFeatureTree(UUID featureTreeUuid) {
236
		return queryService(featureTreeUuid, FEATURETREE);
237
	}
238

    
239
	/*
240
	 * (non-Javadoc)
241
	 *
242
	 * @see eu.etaxonomy.printpublisher.IXMLEntityFactory#getFeatureTrees()
243
	 */
244
	@Override
245
    public List<Element> getFeatureTrees() {
246
		Element result = queryServiceWithParameters(FEATURETREES,
247
				UNLIMITED_RESULTS);
248
		return processElementList(result);
249
	}
250

    
251
	@Override
252
    public Element getTermNode(UUID featureNodeUuid) {
253
		Element result = queryService(featureNodeUuid, FEATURENODE);
254
		return result;
255
	}
256

    
257
	@Override
258
    public Element getFeatureForTermNode(UUID featureNodeUuid) {
259
		Element result = queryService(featureNodeUuid, FEATURENODE_FEATURE);
260
		return result;
261
	}
262

    
263
	/*
264
	 * (non-Javadoc)
265
	 *
266
	 * @see
267
	 * eu.etaxonomy.printpublisher.IXMLEntityFactory#getTaxonFromTaxonNode(org
268
	 * .jdom.Element)
269
	 */
270
	@Override
271
    public Element getTaxonForTaxonNode(Element taxonNodeElement) {
272
		return queryService(taxonNodeElement, TAXONNODE_TAXON);
273
	}
274

    
275
	/*
276
	 *
277
	 */
278
	/*
279
	 * public List<Element> getReferences(Element taxonElement) throws
280
	 * JDOMException {
281
	 *
282
	 * //get the references from the taxonElement String referencePattern =
283
	 * "//name/nomenclaturalSource.citation";
284
	 *
285
	 * //but there could be many references Element referenceElement = (Element)
286
	 * XPath.selectSingleNode(taxonElement, referencePattern); //List<Element>
287
	 * descriptionElementElements = XPath.selectNodes(context, featurePattern +
288
	 * "/..");
289
	 *
290
	 * List<Element> elementList = null;
291
	 *
292
	 * if(referenceElement != null){ //the referencePattern was found in the
293
	 * taxonElement
294
	 *
295
	 * Element result = queryService(referenceElement, REFERENCES);
296
	 *
297
	 * elementList = new ArrayList<Element>();
298
	 *
299
	 * for(Object child : result.getChildren()){ if(child instanceof Element){
300
	 * Element childElement = (Element) ((Element)child).clone();
301
	 *
302
	 * childElement.detach();
303
	 *
304
	 * elementList.add(childElement); } } }
305
	 *
306
	 * return elementList; }
307
	 */
308

    
309
	@Override
310
    public List<Element> getReferences(Element referenceElement) {
311

    
312
		Element result = queryService(referenceElement, REFERENCES);
313

    
314
		List<Element> elementList = new ArrayList<Element>();
315

    
316
		for (Object child : result.getChildren()) {
317
			if (child instanceof Element) {
318
				Element childElement = (Element) ((Element) child).clone();
319

    
320
				childElement.detach();
321

    
322
				elementList.add(childElement);
323
			}
324
		}
325

    
326
		return elementList;
327
	}
328

    
329
	/*
330
	 * (non-Javadoc)
331
	 *
332
	 * @see
333
	 * eu.etaxonomy.printpublisher.IXMLEntityFactory#getAcceptedTaxonElement
334
	 * (org.jdom.Element)
335
	 */
336
	@Override
337
    public Element getAcceptedTaxonElement(Element taxonElement) {
338
		Element result = queryService(taxonElement, TAXON_ACCEPTED);
339
		return result;
340
	}
341

    
342
	/*
343
	 * (non-Javadoc)
344
	 *
345
	 * @see
346
	 * eu.etaxonomy.printpublisher.IXMLEntityFactory#getSynonymy(org.jdom.Element
347
	 * )
348
	 */
349
	@Override
350
    public List<Element> getSynonymy(Element taxonElement) {
351
		Element result = queryService(taxonElement, TAXON_SYNONYMY);
352

    
353
		List<Element> elementList = new ArrayList<Element>();
354

    
355
		for (Object child : result.getChildren()) {
356
			if (child instanceof Element) {
357
				Element childElement = (Element) ((Element) child).clone();
358

    
359
				childElement.detach();
360

    
361
				elementList.add(childElement);
362
			}
363
		}
364

    
365
		return elementList;
366
	}
367

    
368
	/*
369
	 *
370
	 */
371
	@Override
372
    public List<Element> getMedia(Element taxonElement) {
373

    
374
		List<NameValuePair> params = Arrays
375
				.asList(new NameValuePair[] {
376
						new BasicNameValuePair("includeTaxonDescriptions",
377
								"true"),
378
						new BasicNameValuePair("includeOccurrences", "false"),
379
						new BasicNameValuePair("includeTaxonNameDescriptions",
380
								"false") });
381

    
382
		UUID uuid = XMLHelper.getUuid(taxonElement);
383

    
384
		Element result = queryServiceWithParameters(
385
				TAXON_MEDIA.replace(UUID, uuid.toString()), params);
386

    
387
		// Element result = queryService(taxonElement, TAXON_MEDIA);
388

    
389
		List<Element> elementList = new ArrayList<Element>();
390

    
391
		for (Object child : result.getChildren()) {
392
			if (child instanceof Element) {
393
				Element childElement = (Element) ((Element) child).clone();
394

    
395
				childElement.detach();
396

    
397
				elementList.add(childElement);
398
			}
399
		}
400

    
401
		return elementList;
402
	}
403

    
404
	/*
405
	 * (non-Javadoc)
406
	 *
407
	 * @see
408
	 * eu.etaxonomy.printpublisher.IXMLEntityFactory#getTypeDesignations(org
409
	 * .jdom.Element)
410
	 */
411
	@Override
412
    public List<Element> getTypeDesignations(Element nameElement) {
413
		Element result = queryService(nameElement, NAME_TYPE_DESIGNATIONS);
414
		return processElementList(result);
415
	}
416

    
417
	/*
418
	 * (non-Javadoc)
419
	 *
420
	 * @see
421
	 * eu.etaxonomy.printpublisher.IXMLEntityFactory#getDescriptions(org.jdom
422
	 * .Element)
423
	 */
424
	@Override
425
    public Element getDescriptions(Element taxonElement) {
426
		Element result = queryService(taxonElement, TAXON_DESCRIPTIONS);
427
		return result;
428
	}
429

    
430
	/**
431
	 * Queries the service with the uuid of the given element
432
	 *
433
	 * @param element
434
	 * @param restRequest
435
	 * @return
436
	 */
437
	private Element queryService(Element element, String restRequest) {
438
		UUID uuid = XMLHelper.getUuid(element);
439
		return queryService(uuid, restRequest);
440
	}
441

    
442
	/**
443
	 * Queries the service with the given uuid
444
	 *
445
	 * @param uuid
446
	 * @param restRequest
447
	 * @return
448
	 */
449
	private Element queryService(UUID uuid, String restRequest) {
450
		String request = restRequest.replace(UUID, uuid.toString());
451
		return queryServiceWithParameters(request, null);
452
	}
453

    
454
	/**
455
	 *
456
	 * @param restRequest
457
	 * @return
458
	 * @throws URISyntaxException
459
	 */
460
	private Element queryServiceWithParameters(String restRequest,
461
			List<NameValuePair> queryParameters) {
462

    
463
		try {
464
			URI newUri = UriUtils.createUri(serviceUrl, restRequest,
465
					queryParameters, null);
466

    
467
			Map<String, String> requestHeaders = new HashMap<String, String>();
468
			requestHeaders.put("Accept", "application/xml");
469
			// requestHeaders.put("Accept", "application/json");
470
			requestHeaders.put("Accept-Charset", "UTF-8");
471

    
472
			HttpResponse response = UriUtils
473
					.getResponse(newUri, requestHeaders);
474

    
475
			logger.info("Firing request for URI: " + newUri);
476

    
477
			if (UriUtils.isOk(response)) {
478

    
479
				// get the content at the resource
480
				InputStream content = UriUtils.getContent(response);
481

    
482
				// specify encoding in the reader
483
				BufferedReader in = new BufferedReader(new InputStreamReader(
484
						content, "UTF-8"));
485

    
486
				// build the jdom document
487
				Document document = builder.build(in);
488
				// Document document = builder.build(content);
489

    
490
				return document.getRootElement();
491
			} else {
492
				monitor.warning(UriUtils.getStatus(response));
493
				logger.error(UriUtils.getStatus(response));
494
			}
495

    
496
		} catch (IOException e) {
497
			monitor.warning("No content for request: " + restRequest, e);
498
			logger.error("No content for request: " + restRequest);
499
		} catch (JDOMException e) {
500
			monitor.warning("Error building the document.", e);
501
			logger.error("Error building the document.", e);
502
		} catch (URISyntaxException e) {
503
			monitor.warning("Error building URI", e);
504
			logger.error("Error building URI", e);
505
		}
506

    
507
		// error
508
		return null;
509
	}
510

    
511
	/**
512
	 * The access point of a CDM Community Server
513
	 *
514
	 * @return the serviceUrl
515
	 */
516
	public URL getServiceUrl() {
517
		return serviceUrl;
518
	}
519

    
520
	/**
521
	 * The CDM Community Servers access point
522
	 *
523
	 * @param serviceUrl
524
	 */
525
	public void setServiceUrl(URL serviceUrl) {
526
		this.serviceUrl = serviceUrl;
527
	}
528

    
529
	// dto/polytomousKey/linkedStyle.json?findByTaxonomicScope=f820f533-06f2-4116-87e9-c9319c0c1cbf
530
	/*
531
	 * (non-Javadoc) TODO: Implement this method.
532
	 *
533
	 * @see
534
	 * eu.etaxonomy.cdm.print.IXMLEntityFactory#getPolytomousKey(org.jdom.Element
535
	 * )
536
	 */
537
	@Override
538
	// public List<Element> getPolytomousKey(Element taxonElement) {
539
	public Element getPolytomousKey(Element taxonElement) {
540

    
541
		Element result = queryService(taxonElement, POLYTOMOUS_KEY);
542
		return result;
543
		// TODO Auto-generated method stub
544
		// return null;
545
	}
546
}
(6-6/10)