Project

General

Profile

« Previous | Next » 

Revision 37588

[maven-release-plugin] copy for tag dnet-download-service-2.1.7

View differences:

modules/dnet-download-service/tags/dnet-download-service-2.1.7/deploy.info
1
{"type_source": "SVN", "goal": "package -U -T 4C source:jar", "url": "http://svn-public.driver.research-infrastructures.eu/driver/dnet40/modules/dnet-download-service/trunk/", "deploy_repository": "dnet4-snapshots", "version": "4", "mail": "sandro.labruzzo@isti.cnr.it,michele.artini@isti.cnr.it, claudio.atzori@isti.cnr.it, alessia.bardi@isti.cnr.it", "deploy_repository_url": "http://maven.research-infrastructures.eu/nexus/content/repositories/dnet4-snapshots", "name": "dnet-download-service"}
modules/dnet-download-service/tags/dnet-download-service-2.1.7/src/main/java/eu/dnetlib/data/download/DownloadReportMap.java
1
package eu.dnetlib.data.download;
2

  
3
import java.util.HashMap;
4

  
5
import com.google.gson.Gson;
6

  
7
/**
8
 * Created by sandro on 06/11/14.
9
 */
10
public class DownloadReportMap extends HashMap<String, DownloadReport> {
11

  
12
	/**
13
	 *
14
	 */
15
	private static final long serialVersionUID = -8881211500697708728L;
16

  
17
	private boolean status;
18

  
19
	private int totalDownloaded;
20

  
21
	public DownloadReportMap() {
22
		this.totalDownloaded = 0;
23
	}
24

  
25
	public void addDowload() {
26
		this.totalDownloaded++;
27
	}
28

  
29
	public boolean getStatus() {
30
		return status;
31
	}
32

  
33
	public void setStatus(final boolean status) {
34
		this.status = status;
35
	}
36

  
37
	public int getTotalDownloaded() {
38
		return totalDownloaded;
39
	}
40

  
41
	public void setTotalDownloaded(final int totalDownloaded) {
42
		this.totalDownloaded = totalDownloaded;
43
	}
44

  
45
	@Override
46
	public String toString() {
47
		Gson g = new Gson();
48
		return g.toJson(this);
49
	}
50
}
modules/dnet-download-service/tags/dnet-download-service-2.1.7/src/main/java/eu/dnetlib/data/download/plugins/DummyPlugin.java
1
package eu.dnetlib.data.download.plugins;
2

  
3
import java.util.ArrayList;
4
import java.util.List;
5

  
6
import com.google.common.base.Function;
7
import com.google.common.collect.Iterables;
8
import com.google.gson.Gson;
9

  
10
import eu.dnetlib.data.download.rmi.DownloadItem;
11
import eu.dnetlib.data.download.rmi.DownloadPlugin;
12

  
13
public class DummyPlugin implements DownloadPlugin {
14

  
15
	@Override
16
	public DownloadItem retrieveUrl(final DownloadItem item) {
17
		String url = item.getUrl();
18

  
19
		if ((url == null) || (url.trim().length() == 0)) return null;
20
		@SuppressWarnings("unchecked")
21
		List<String> urls = new Gson().fromJson(url, ArrayList.class);
22
		if ((urls == null) || (urls.size() == 0)) {
23
			item.setOriginalUrl(null);
24
			item.setUrl(null);
25
			return item;
26
		}
27
		item.setOriginalUrl(urls.get(0));
28
		item.setUrl(urls.get(0));
29
		return item;
30
	}
31

  
32
	@Override
33
	public Iterable<DownloadItem> retireveUrls(final Iterable<DownloadItem> items) {
34

  
35
		return Iterables.transform(items, new Function<DownloadItem, DownloadItem>() {
36

  
37
			@Override
38
			public DownloadItem apply(final DownloadItem input) {
39
				return retrieveUrl(input);
40
			}
41
		});
42
	}
43

  
44
	@Override
45
	public String getPluginName() {
46
		return "DummyPlugin";
47
	}
48

  
49
	@Override
50
	public void setBasePath(final String basePath) {
51
		// TODO Auto-generated method stub
52

  
53
	}
54

  
55
	/**
56
	 * {@inheritDoc}
57
	 * @see eu.dnetlib.data.download.rmi.DownloadPlugin#getRegularExpression()
58
	 */
59
	@Override
60
	public List<String> getRegularExpression() {
61
		// TODO Auto-generated method stub
62
		return null;
63
	}
64

  
65
	/**
66
	 * {@inheritDoc}
67
	 * @see eu.dnetlib.data.download.rmi.DownloadPlugin#setRegularExpression(java.util.List)
68
	 */
69
	@Override
70
	public void setRegularExpression(final List<String> regularExpression) {
71
		// TODO Auto-generated method stub
72

  
73
	}
74

  
75
}
modules/dnet-download-service/tags/dnet-download-service-2.1.7/src/main/java/eu/dnetlib/data/download/DownloadReport.java
1
package eu.dnetlib.data.download;
2

  
3
/**
4
 * Created by sandro on 06/11/14.
5
 */
6
public class DownloadReport {
7

  
8
    private int numberOfOccurrences;
9
    private String stackTrace;
10
    private String recordId;
11

  
12

  
13
    public DownloadReport() {
14
        this.numberOfOccurrences =1;
15

  
16
    }
17

  
18
    public DownloadReport(int numberOfOccurrences, String stackTrace, String recordId) {
19
        this.numberOfOccurrences = numberOfOccurrences;
20
        this.stackTrace = stackTrace;
21
        this.recordId = recordId;
22
    }
23

  
24
    public void incrementError(){
25
        this.numberOfOccurrences ++;
26
    }
27

  
28
    public void incrementError(int numberOfOccurrences){
29
        this.numberOfOccurrences += numberOfOccurrences;
30
    }
31

  
32
    /**
33
     * Getter for property 'numberOfOccurrences'.
34
     *
35
     * @return Value for property 'numberOfOccurrences'.
36
     */
37
    public int getNumberOfOccurrences() {
38

  
39
        return numberOfOccurrences;
40
    }
41

  
42
    /**
43
     * Setter for property 'numberOfOccurrences'.
44
     *
45
     * @param numberOfOccurrences Value to set for property 'numberOfOccurrences'.
46
     */
47
    public void setNumberOfOccurrences(int numberOfOccurrences) {
48
        this.numberOfOccurrences = numberOfOccurrences;
49
    }
50

  
51
    /**
52
     * Getter for property 'stackTrace'.
53
     *
54
     * @return Value for property 'stackTrace'.
55
     */
56
    public String getStackTrace() {
57
        return stackTrace;
58
    }
59

  
60
    /**
61
     * Setter for property 'stackTrace'.
62
     *
63
     * @param stackTrace Value to set for property 'stackTrace'.
64
     */
65
    public void setStackTrace(String stackTrace) {
66
        this.stackTrace = stackTrace;
67
    }
68

  
69
    /**
70
     * Getter for property 'recordId'.
71
     *
72
     * @return Value for property 'recordId'.
73
     */
74
    public String getRecordId() {
75
        return recordId;
76
    }
77

  
78
    /**
79
     * Setter for property 'recordId'.
80
     *
81
     * @param recordId Value to set for property 'recordId'.
82
     */
83
    public void setRecordId(String recordId) {
84
        this.recordId = recordId;
85
    }
86
}
modules/dnet-download-service/tags/dnet-download-service-2.1.7/src/main/java/eu/dnetlib/data/download/DownloadAction.java
1
package eu.dnetlib.data.download;
2

  
3
import java.lang.reflect.Type;
4
import java.util.List;
5

  
6
import javax.annotation.Resource;
7

  
8
import org.apache.commons.lang.StringUtils;
9
import org.apache.commons.logging.Log;
10
import org.apache.commons.logging.LogFactory;
11

  
12
import com.google.common.reflect.TypeToken;
13
import com.google.gson.Gson;
14

  
15
import eu.dnetlib.data.download.rmi.DownloadServiceActions;
16
import eu.dnetlib.data.download.rmi.DownloadServiceException;
17
import eu.dnetlib.data.download.rmi.DownloadServiceFeeder;
18
import eu.dnetlib.enabling.tools.blackboard.BlackboardJob;
19
import eu.dnetlib.enabling.tools.blackboard.BlackboardServerAction;
20
import eu.dnetlib.enabling.tools.blackboard.BlackboardServerHandler;
21

  
22
public class DownloadAction implements BlackboardServerAction<DownloadServiceActions> {
23

  
24
	/** The Constant log. */
25
	private static final Log log = LogFactory.getLog(DownloadAction.class);
26

  
27
	@Resource
28
	DownloadServiceFeeder downloadServiceFeeder;
29

  
30
	private static String DEFAULT_NUMBER_OF_THREAD = "5";
31

  
32
	private Type typeToken = new TypeToken<List<String>>() {
33
		/**
34
		 *
35
		 */
36
		private static final long serialVersionUID = 5683238626707746063L;
37
	}.getType();
38

  
39
	@Override
40
	public void execute(final BlackboardServerHandler handler, final BlackboardJob job) throws Exception {
41
		try {
42
			String epr = job.getParameters().get("epr");
43
			String plugin = job.getParameters().get("plugin");
44
			String objectStoreID = job.getParameters().get("objectStoreID");
45
			String protocol = job.getParameters().get("protocol");
46
			String mimeType = job.getParameters().get("mimeType");
47
			String numberOfThreads = job.getParameters().get("thread");
48
			String basePath = job.getParameters().get("basePath");
49
			String regularExpression = job.getParameters().get("regularExpressions");
50
			log.debug("regular Expression: "+regularExpression);
51

  
52
			List<String> expressions = null;
53

  
54
			if (!StringUtils.isBlank(regularExpression)) {
55
				expressions =new Gson().fromJson(regularExpression, typeToken);
56
			}
57

  
58
			if ((numberOfThreads == "") || (numberOfThreads == null)) {
59
				log.warn("Cannot find numberOfThread, using default value " + DEFAULT_NUMBER_OF_THREAD);
60
				numberOfThreads = DEFAULT_NUMBER_OF_THREAD;
61
			}
62
			log.info(String.format("downloading using plugin %s , protocol : %s into ObjectStore id %s  ", plugin, protocol, objectStoreID));
63
			handler.ongoing(job);
64
			DownloadReportMap response = downloadServiceFeeder.download(epr, plugin, objectStoreID, protocol, mimeType, Integer.parseInt(numberOfThreads),
65
					basePath, expressions);
66
			job.getParameters().put("downloadReport", "" + response.getTotalDownloaded());
67
			if (response.getStatus()) {
68
				log.info(String.format("Completed Download", plugin, protocol, objectStoreID));
69
				handler.done(job);
70
			} else {
71
				log.error("response is false" + response);
72

  
73
				handler.failed(job, new DownloadServiceException("Opps something bad happen to our download hamsters" + response.toString()));
74
			}
75
		} catch (Exception e) {
76
			log.error("An error occur while starting download",e);
77
			handler.failed(job, new DownloadServiceException(e));
78
		}
79
	}
80

  
81
}
modules/dnet-download-service/tags/dnet-download-service-2.1.7/src/main/java/eu/dnetlib/data/download/rmi/DownloadServiceFeeder.java
1
package eu.dnetlib.data.download.rmi;
2

  
3
import java.util.List;
4
import java.util.concurrent.ArrayBlockingQueue;
5
import java.util.concurrent.BlockingQueue;
6
import java.util.concurrent.ExecutorService;
7
import java.util.concurrent.Executors;
8
import java.util.concurrent.Future;
9

  
10
import javax.annotation.Resource;
11

  
12
import org.apache.commons.logging.Log;
13
import org.apache.commons.logging.LogFactory;
14
import org.springframework.beans.factory.annotation.Autowired;
15

  
16
import com.google.common.base.Function;
17
import com.google.common.base.Joiner;
18
import com.google.common.collect.Lists;
19

  
20
import eu.dnetlib.data.download.DownloadPluginEnumeratorImpl;
21
import eu.dnetlib.data.download.DownloadReport;
22
import eu.dnetlib.data.download.DownloadReportMap;
23
import eu.dnetlib.data.download.DownloadServiceImpl;
24
import eu.dnetlib.data.download.worker.DownloadWorker;
25
import eu.dnetlib.data.objectstore.modular.connector.ObjectStore;
26
import eu.dnetlib.data.objectstore.modular.connector.ObjectStoreDao;
27
import eu.dnetlib.data.objectstore.rmi.ObjectStoreServiceException;
28
import eu.dnetlib.data.objectstore.rmi.Protocols;
29
import eu.dnetlib.enabling.resultset.client.ResultSetClientFactory;
30

  
31
/**
32
 * The Class DownloadServiceFeeder.
33
 */
34
public class DownloadServiceFeeder {
35

  
36
	/** The Constant log. */
37
	private static final Log log = LogFactory.getLog(DownloadServiceFeeder.class);
38

  
39
	/** The download plugin enumerator. */
40
	@Resource
41
	DownloadPluginEnumeratorImpl downloadPluginEnumerator;
42

  
43
	/** The result set client factory. */
44
	@Resource
45
	private ResultSetClientFactory resultSetClientFactory;
46

  
47
	/** The object store dao. */
48
	@Autowired
49
	private ObjectStoreDao objectStoreDao;
50

  
51
	/**
52
	 * Download and feed file into the objectStore .
53
	 *
54
	 * @param epr
55
	 *            the end-point reference of the result-set of Serialized DownloadItem
56
	 * @param plugin
57
	 *            the plugin used to retrieve the correct URL
58
	 * @param objectStoreID
59
	 *            the object store id to store the data
60
	 * @param protocol
61
	 *            the protocol used to download the file
62
	 * @param mimeType
63
	 *            the mime type of the Files
64
	 * @param numberOfThreads
65
	 *            the number of threads to use for download at the same time
66
	 * @throws DownloadServiceException
67
	 *             the download service exception
68
	 * @throws ObjectStoreServiceException
69
	 */
70
	public DownloadReportMap download(final String epr,
71
			final String plugin,
72
			final String objectStoreID,
73
			final String protocol,
74
			final String mimeType,
75
			final int numberOfThreads,
76
			final String basePath,
77
			final List<String> regularExpression
78
			) throws DownloadServiceException, ObjectStoreServiceException {
79
		final DownloadPlugin downloadPlugin = downloadPluginEnumerator.get(plugin);
80
		if ((basePath != null) && (basePath.isEmpty() == false)) {
81
			downloadPlugin.setBasePath(basePath);
82
		}
83

  
84
		final Iterable<String> urlInfo = resultSetClientFactory.getClient(epr);
85
		final BlockingQueue<String> itemsQueue = new ArrayBlockingQueue<String>(1024);
86
		final ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
87
		final ObjectStore objStore = objectStoreDao.getObjectStore(objectStoreID);
88

  
89
		final List<Future<DownloadReportMap>> responses = Lists.newArrayList();
90

  
91
		if (regularExpression!= null) {
92
			downloadPlugin.setRegularExpression(regularExpression);
93
		}
94

  
95
		for (int i = 0; i < numberOfThreads; i++) {
96
			responses.add(executor.submit(new DownloadWorker(itemsQueue, objStore, Protocols.valueOf(protocol), mimeType, new Function<String, DownloadItem>() {
97

  
98
				@Override
99
				public DownloadItem apply(final String input) {
100
					if (input == null) {
101
						log.error("Input is null");
102
						return null;
103
					}
104
					if (input.equals(DownloadServiceImpl.END_QUEUE_STRING)) return DownloadServiceImpl.END_QUEUE;
105
					try {
106
						final DownloadItem di = DownloadItem.newObjectfromJSON(input);
107

  
108

  
109
						if (downloadPlugin.retrieveUrl(di) == null) {
110
							di.setUrl(null);
111
							di.setOriginalUrl(null);
112
						}
113
						return di;
114
					} catch (Exception e) {
115
						log.error("Exception on trasform item :"+input,e);
116
						return null;
117
					}
118
				}
119
			})));
120
		}
121

  
122
		int i = 0;
123
		if(urlInfo!= null) {
124
			for (final String downloadItem : urlInfo) {
125
				if (downloadItem != null) {
126
					if ((i++ % 1000) == 0) {
127
						log.debug("Read " + i);
128
					}
129
					try {
130
						itemsQueue.put(downloadItem);
131
					} catch (final Exception e) {
132
						log.error("An error occurred while populating the download items queue: " + Joiner.on("\tat ").join(e.getStackTrace()));
133
					}
134
				}
135
			}
136
		}
137

  
138
		try {
139
			itemsQueue.put(DownloadServiceImpl.END_QUEUE_STRING);
140
		} catch (final InterruptedException e) {
141
			log.error("An error occurred adding the loop terminator: " + Joiner.on("\tat ").join(e.getStackTrace()));
142
		}
143

  
144
		final DownloadReportMap resultMap = new DownloadReportMap();
145
		resultMap.setStatus(true);
146

  
147
		for (final Future<DownloadReportMap> currentResponses : responses) {
148
			try {
149
				final DownloadReportMap currentMap = currentResponses.get();
150
				for (final String key : currentMap.keySet()) {
151
					if (!resultMap.containsKey(key)) {
152
						resultMap.put(key, currentMap.get(key));
153
						resultMap.setTotalDownloaded(currentMap.getTotalDownloaded());
154
						resultMap.setStatus(currentMap.getStatus());
155
					} else {
156
						final DownloadReport currentReport = currentMap.get(key);
157
						resultMap.get(key).incrementError(currentReport.getNumberOfOccurrences());
158
					}
159
				}
160
				log.info("Status " + currentMap.getStatus());
161
				resultMap.setStatus(resultMap.getStatus() && currentMap.getStatus());
162
				resultMap.setTotalDownloaded(currentMap.getTotalDownloaded() + resultMap.getTotalDownloaded());
163

  
164
			} catch (final Exception e) {
165
				log.error(e);
166
				resultMap.setStatus(false);
167
			}
168
		}
169

  
170
		executor.shutdown();
171
		return resultMap;
172

  
173
	}
174
}
modules/dnet-download-service/tags/dnet-download-service-2.1.7/src/main/java/eu/dnetlib/data/download/rmi/DownloadServiceActions.java
1
package eu.dnetlib.data.download.rmi;
2

  
3
public enum DownloadServiceActions {
4
	DOWNLOAD,
5

  
6
}
modules/dnet-download-service/tags/dnet-download-service-2.1.7/src/main/java/eu/dnetlib/data/download/worker/DownloadWorker.java
1
package eu.dnetlib.data.download.worker;
2

  
3
import java.io.IOException;
4
import java.net.HttpURLConnection;
5
import java.net.URL;
6
import java.util.concurrent.BlockingQueue;
7
import java.util.concurrent.Callable;
8

  
9
import org.apache.commons.logging.Log;
10
import org.apache.commons.logging.LogFactory;
11

  
12
import com.google.common.base.Function;
13
import com.google.common.base.Joiner;
14

  
15
import eu.dnetlib.data.download.DownloadReport;
16
import eu.dnetlib.data.download.DownloadReportMap;
17
import eu.dnetlib.data.download.DownloadServiceImpl;
18
import eu.dnetlib.data.download.rmi.DownloadItem;
19
import eu.dnetlib.data.objectstore.modular.ObjectStoreRecord;
20
import eu.dnetlib.data.objectstore.modular.connector.ObjectStore;
21
import eu.dnetlib.data.objectstore.rmi.ObjectStoreFile;
22
import eu.dnetlib.data.objectstore.rmi.ObjectStoreServiceException;
23
import eu.dnetlib.data.objectstore.rmi.Protocols;
24

  
25
/**
26
 * The Class DownloadWorker is a worker responsible to download the data into the object store.
27
 */
28
public class DownloadWorker implements Callable<DownloadReportMap> {
29

  
30
	/**
31
	 * The Constant log.
32
	 */
33
	private static final Log log = LogFactory.getLog(DownloadWorker.class);
34

  
35
	/**
36
	 * The queue.
37
	 */
38
	private BlockingQueue<String> queue = null;
39

  
40
	/**
41
	 * The object store.
42
	 */
43
	private ObjectStore objectStore = null;
44

  
45
	/**
46
	 * The protocol.
47
	 */
48
	private Protocols protocol;
49

  
50
	/**
51
	 * The mime type.
52
	 */
53
	private String mimeType;
54

  
55
	private Function<String, DownloadItem> converter;
56

  
57
	/**
58
	 * Instantiates a new download worker.
59
	 *
60
	 * @param queue
61
	 *            the queue
62
	 * @param objectStore
63
	 *            the object store
64
	 * @param protocol
65
	 *            the protocol
66
	 * @param mimeType
67
	 *            the mime type
68
	 */
69
	public DownloadWorker(final BlockingQueue<String> queue, final ObjectStore objectStore, final Protocols protocol, final String mimeType,
70
			final Function<String, DownloadItem> converter) {
71
		this.setConverter(converter);
72
		this.setQueue(queue);
73
		this.setObjectStore(objectStore);
74
		this.setMimeType(mimeType);
75
		this.setProtocol(protocol);
76
	}
77

  
78
	/*
79
	 * (non-Javadoc)
80
	 *
81
	 * @see java.lang.Runnable#run()
82
	 */
83
	@Override
84
	public DownloadReportMap call() throws Exception {
85
		final DownloadReportMap report = new DownloadReportMap();
86
		try {
87

  
88
			String takedObject = queue.take();
89
			DownloadItem di = getConverter().apply(takedObject);
90
			if (log.isDebugEnabled()) {
91
				log.debug(takedObject);
92
			}
93

  
94
			while (DownloadServiceImpl.END_QUEUE != di) {
95

  
96
				log.debug(Thread.currentThread().getId()+": Reading  "+takedObject);
97

  
98
				if (di == null) {
99
					log.info("the current download item is Null, skipping");
100
				}
101
				if ((di != null) && (di.getUrl() != null) && (di.getUrl().length() != 0) && !checkIfExists(di)) {
102
					try {
103
						final URL toDownload = followURL(new URL(di.getUrl()), report, di);
104
						final ObjectStoreRecord record = new ObjectStoreRecord();
105
						final ObjectStoreFile metadata = new ObjectStoreFile();
106
						metadata.setObjectID(di.getFileName());
107
						metadata.setMetadataRelatedID(di.getIdItemMetadata());
108
						metadata.setAccessProtocol(this.protocol);
109
						metadata.setMimeType(this.mimeType);
110
						metadata.setDownloadedURL(di.getOriginalUrl());
111
						record.setFileMetadata(metadata);
112
						record.setInputStream(toDownload.openStream());
113
						objectStore.feedObjectRecord(record);
114
						report.addDowload();
115
						log.debug("Saved object " + metadata.toJSON());
116
					} catch (final Throwable e) {
117
						log.error("An error occur inside the loop: ",e);
118
						// reportException(report, di, e);
119
					}
120
				}
121
				takedObject = queue.take();
122
				log.debug(Thread.currentThread().getId()+": Next Object From Queue  "+takedObject);
123
				di = getConverter().apply(takedObject);
124
				if (log.isDebugEnabled()) {
125
					log.debug(takedObject);
126
				}
127
			}
128
			queue.put(DownloadServiceImpl.END_QUEUE_STRING);
129
		} catch (final Exception e) {
130
			log.error("An error occured : " + Joiner.on("\tat ").join(e.getStackTrace()));
131
			report.setStatus(false);
132
			return report;
133
		}
134

  
135
		log.info("CLOSED THREAD " + Thread.currentThread().getId());
136
		report.setStatus(true);
137
		return report;
138

  
139
	}
140

  
141
	private void reportException(final DownloadReportMap report, final DownloadItem di, final Exception e) {
142
		final String className = e.getClass().getName();
143
		if (!report.containsKey(className)) {
144
			final DownloadReport dr = new DownloadReport();
145
			dr.setStackTrace(Joiner.on("\tat ").join(e.getStackTrace()));
146
			dr.setRecordId(di.getIdItemMetadata());
147
			report.put(className, dr);
148
		} else {
149
			report.get(className).incrementError();
150
		}
151
	}
152

  
153
	private URL followURL(final URL inputURL, final DownloadReportMap report, final DownloadItem di) throws IOException {
154

  
155
		final String ptrcl = inputURL.getProtocol();
156
		if (ptrcl.startsWith("file")) {
157
			log.debug("the protocol is File, returning " + inputURL);
158
			return inputURL;
159
		}
160

  
161
		HttpURLConnection conn;
162

  
163
		conn = (HttpURLConnection) inputURL.openConnection();
164
		conn.setInstanceFollowRedirects(true);  // you still need to handle redirect manully.
165
		HttpURLConnection.setFollowRedirects(true);
166
		String location = inputURL.toString();
167
		if ((conn.getResponseCode() >= 300) && (conn.getResponseCode() < 400)) {
168
			location = conn.getHeaderFields().get("Location").get(0);
169
			conn.disconnect();
170
		}
171

  
172
		if (!location.equals(inputURL.toString())) return new URL(location);
173
		return inputURL;
174

  
175

  
176
	}
177

  
178
	private boolean checkIfExists(final DownloadItem di) {
179
		try {
180
			return objectStore.deliverObject(di.getFileName()) != null;
181
		} catch (final ObjectStoreServiceException e) {
182
			log.debug(e.getMessage());
183
			return false;
184
		}
185
	}
186

  
187
	/**
188
	 * Sets the object store.
189
	 *
190
	 * @param objectStore
191
	 *            the objectStore to set
192
	 */
193
	public void setObjectStore(final ObjectStore objectStore) {
194
		this.objectStore = objectStore;
195
	}
196

  
197
	/**
198
	 * Sets the queue.
199
	 *
200
	 * @param queue
201
	 *            the queue to set
202
	 */
203
	public void setQueue(final BlockingQueue<String> queue) {
204
		this.queue = queue;
205
	}
206

  
207
	/**
208
	 * Sets the protocol.
209
	 *
210
	 * @param protocol
211
	 *            the protocol to set
212
	 */
213
	public void setProtocol(final Protocols protocol) {
214
		this.protocol = protocol;
215
	}
216

  
217
	/**
218
	 * Sets the mime type.
219
	 *
220
	 * @param mimeType
221
	 *            the mimeType to set
222
	 */
223
	public void setMimeType(final String mimeType) {
224
		this.mimeType = mimeType;
225
	}
226

  
227
	public Function<String, DownloadItem> getConverter() {
228
		return converter;
229
	}
230

  
231
	public void setConverter(final Function<String, DownloadItem> converter) {
232
		this.converter = converter;
233
	}
234
}
modules/dnet-download-service/tags/dnet-download-service-2.1.7/src/main/java/eu/dnetlib/data/download/DownloadPluginEnumeratorImpl.java
1
package eu.dnetlib.data.download;
2

  
3
import java.util.Map;
4

  
5
import org.springframework.beans.BeansException;
6
import org.springframework.beans.factory.BeanFactory;
7
import org.springframework.beans.factory.ListableBeanFactory;
8

  
9
import com.google.common.collect.Maps;
10

  
11
import eu.dnetlib.data.download.rmi.DownloadPlugin;
12
import eu.dnetlib.data.download.rmi.DownloadPluginEnumerator;
13
import eu.dnetlib.data.download.rmi.DownloadServiceException;
14

  
15
/**
16
 * The Class DownloadPluginEnumeratorImpl.
17
 */
18
public class DownloadPluginEnumeratorImpl implements DownloadPluginEnumerator {
19

  
20
	/**
21
	 * bean factory.
22
	 */
23
	private ListableBeanFactory beanFactory;
24

  
25
	/*
26
	 * (non-Javadoc)
27
	 *
28
	 * @see eu.dnetlib.data.download.rmi.DownloadPluginEnumerator#getAll()
29
	 */
30
	@Override
31
	public Map<String, DownloadPlugin> getAll() {
32
		return beanFactory.getBeansOfType(DownloadPlugin.class);
33
	}
34

  
35
	/*
36
	 * (non-Javadoc)
37
	 *
38
	 * @see eu.dnetlib.data.download.rmi.DownloadPluginEnumerator#getByProtocols()
39
	 */
40
	@Override
41
	public Map<String, DownloadPlugin> getByProtocols() {
42
		final Map<String, DownloadPlugin> res = Maps.newHashMap();
43
		for (DownloadPlugin cp : getAll().values()) {
44
			res.put(cp.getPluginName().toLowerCase(), cp);
45
		}
46
		return res;
47
	}
48

  
49
	/*
50
	 * (non-Javadoc)
51
	 *
52
	 * @see org.springframework.beans.factory.BeanFactoryAware#setBeanFactory(org.springframework.beans.factory.BeanFactory)
53
	 */
54
	@Override
55
	public void setBeanFactory(final BeanFactory beanFactory) throws BeansException {
56
		this.beanFactory = (ListableBeanFactory) beanFactory;
57
	}
58

  
59
	/**
60
	 * Gets the bean factory.
61
	 *
62
	 * @return the bean factory
63
	 */
64
	public ListableBeanFactory getBeanFactory() {
65
		return beanFactory;
66
	}
67

  
68
	/**
69
	 * Get given DownloadPlugin or throws exception.
70
	 *
71
	 * @param protocol
72
	 *            the protocol
73
	 * @return the download plugin
74
	 * @throws eu.dnetlib.data.download.rmi.DownloadServiceException
75
	 *             the download service exception
76
	 */
77
	public DownloadPlugin get(final String protocol) throws DownloadServiceException {
78
		final DownloadPlugin plugin = getByProtocols().get(protocol.toLowerCase());
79
		if (plugin == null) throw new DownloadServiceException("plugin not found for name: " + protocol);
80
		return plugin;
81
	}
82

  
83
}
modules/dnet-download-service/tags/dnet-download-service-2.1.7/src/main/java/eu/dnetlib/data/download/DownloadServiceImpl.java
1
package eu.dnetlib.data.download;
2

  
3
import java.security.KeyManagementException;
4
import java.security.NoSuchAlgorithmException;
5
import java.security.cert.CertificateException;
6
import java.util.ArrayList;
7
import java.util.List;
8

  
9
import javax.annotation.Resource;
10
import javax.net.ssl.HostnameVerifier;
11
import javax.net.ssl.HttpsURLConnection;
12
import javax.net.ssl.SSLContext;
13
import javax.net.ssl.SSLSession;
14
import javax.net.ssl.TrustManager;
15
import javax.net.ssl.X509TrustManager;
16
import javax.xml.ws.wsaddressing.W3CEndpointReference;
17

  
18
import org.apache.commons.logging.Log;
19
import org.apache.commons.logging.LogFactory;
20
import org.springframework.beans.factory.annotation.Required;
21
import org.springframework.beans.factory.annotation.Value;
22

  
23
import eu.dnetlib.data.download.rmi.DownloadItem;
24
import eu.dnetlib.data.download.rmi.DownloadService;
25
import eu.dnetlib.data.download.rmi.DownloadServiceException;
26
import eu.dnetlib.data.download.rmi.DownloadServiceFeeder;
27
import eu.dnetlib.data.objectstore.rmi.ObjectStoreServiceException;
28
import eu.dnetlib.enabling.tools.AbstractBaseService;
29
import eu.dnetlib.enabling.tools.blackboard.NotificationHandler;
30

  
31
/**
32
 * The Class DownloadServiceImpl.
33
 */
34
public class DownloadServiceImpl extends AbstractBaseService implements DownloadService {
35

  
36
	/** The Constant log. */
37
	private static final Log log = LogFactory.getLog(DownloadServiceImpl.class);
38

  
39
	/** The Constant END_QUEUE. */
40
	public static final DownloadItem END_QUEUE = new DownloadItem();
41

  
42
	public static final String END_QUEUE_STRING = "END_DOWNLOAD";
43

  
44
	@Resource
45
	private DownloadServiceFeeder downloadfeeder;
46

  
47
	/** The download plugin enumerator. */
48
	@Resource
49
	DownloadPluginEnumeratorImpl downloadPluginEnumerator;
50

  
51
	/** The notification handler. */
52
	private NotificationHandler notificationHandler;
53

  
54
	@Value("${services.download.http.sslcheck}")
55
	private boolean checkCerts;
56

  
57
	/*
58
	 * (non-Javadoc)
59
	 *
60
	 * @see eu.dnetlib.data.download.rmi.DownloadService#downloadFromResultSet(javax.xml.ws.wsaddressing.W3CEndpointReference,
61
	 * java.lang.String, java.lang.String, java.lang.String, java.lang.String)
62
	 */
63
	@Override
64
	public void downloadFromResultSet(final W3CEndpointReference resultSet,
65
			final String plugin,
66
			final String objectStoreID,
67
			final String protocol,
68
			final String mimeType) throws DownloadServiceException {
69

  
70
		log.info(String.format("Try to download using plugin '%s' , protocol '%s' into ObjectStore '%s'", plugin, protocol, objectStoreID));
71
		try {
72
			downloadfeeder.download(resultSet.toString(), plugin, objectStoreID, protocol, mimeType, 5, null, null);
73
		} catch (ObjectStoreServiceException e) {
74
			log.error(e);
75
		}
76
		log.info(String.format("download completed using plugin '%s' , protocol '%s' into ObjectStore '%s'", plugin, protocol, objectStoreID));
77
	}
78

  
79
	/**
80
	 * {@inheritDoc}
81
	 *
82
	 * @see eu.dnetlib.enabling.tools.AbstractBaseService#notify(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
83
	 */
84
	@Override
85
	public void notify(final String subscriptionId, final String topic, final String isId, final String message) {
86
		getNotificationHandler().notified(subscriptionId, topic, isId, message);
87
	}
88

  
89
	@Override
90
	public void start() {
91
		if (!checkCerts) {
92
			log.info("diabling SSL check ...");
93
			new Thread(new Runnable() {
94

  
95
				@Override
96
				public void run() {
97
					disableSslVerification();
98
				}
99
			}).start();
100
		}
101
	}
102

  
103
	private void disableSslVerification() {
104
		try {
105
			// Create a trust manager that does not validate certificate chains
106
			TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
107

  
108
				@Override
109
				public void checkClientTrusted(final java.security.cert.X509Certificate[] x509Certificates, final String s) throws CertificateException {
110

  
111
				}
112

  
113
				@Override
114
				public void checkServerTrusted(final java.security.cert.X509Certificate[] x509Certificates, final String s) throws CertificateException {
115

  
116
				}
117

  
118
				@Override
119
				public java.security.cert.X509Certificate[] getAcceptedIssuers() {
120
					return null;
121
				}
122
			} };
123

  
124
			// Install the all-trusting trust manager
125
			SSLContext sc = SSLContext.getInstance("SSL");
126
			sc.init(null, trustAllCerts, new java.security.SecureRandom());
127
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
128

  
129
			// Create all-trusting host name verifier
130
			HostnameVerifier allHostsValid = new HostnameVerifier() {
131

  
132
				@Override
133
				public boolean verify(final String hostname, final SSLSession session) {
134
					return true;
135
				}
136
			};
137

  
138
			// Install the all-trusting host verifier
139
			HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
140
			log.info("disabled SSL check");
141
		} catch (NoSuchAlgorithmException e) {
142
			log.error(e.getMessage(), e);
143
		} catch (KeyManagementException e) {
144
			log.error(e.getMessage(), e);
145
		}
146
	}
147

  
148
	/**
149
	 * @return the downloadfeeder
150
	 */
151
	public DownloadServiceFeeder getDownloadfeeder() {
152
		return downloadfeeder;
153
	}
154

  
155
	/**
156
	 * @param downloadfeeder
157
	 *            the downloadfeeder to set
158
	 */
159
	public void setDownloadfeeder(final DownloadServiceFeeder downloadfeeder) {
160
		this.downloadfeeder = downloadfeeder;
161
	}
162

  
163
	/**
164
	 * @return the notificationHandler
165
	 */
166
	public NotificationHandler getNotificationHandler() {
167
		return notificationHandler;
168
	}
169

  
170
	/**
171
	 * @param notificationHandler
172
	 *            the notificationHandler to set
173
	 */
174
	@Required
175
	public void setNotificationHandler(final NotificationHandler notificationHandler) {
176
		this.notificationHandler = notificationHandler;
177
	}
178

  
179
	@Override
180
	public List<String> listPlugins() throws DownloadServiceException {
181

  
182
		List<String> result = new ArrayList<String>();
183
		result.addAll(downloadPluginEnumerator.getAll().keySet());
184
		return result;
185
	}
186

  
187
}
modules/dnet-download-service/tags/dnet-download-service-2.1.7/src/main/resources/eu/dnetlib/data/download/applicationContext-dnet-downloadService.properties
1
services.download.http.sslcheck=false
modules/dnet-download-service/tags/dnet-download-service-2.1.7/src/main/resources/eu/dnetlib/data/download/applicationContext-dnet-downloadService.xml
1
<?xml version="1.0" encoding="UTF-8"?>
2
<beans xmlns="http://www.springframework.org/schema/beans"
3
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
4
	xmlns:sec="http://cxf.apache.org/configuration/security" xmlns:wsa="http://cxf.apache.org/ws/addressing"
5
	xmlns:p="http://www.springframework.org/schema/p" xmlns:http="http://cxf.apache.org/transports/http/configuration"
6
	xmlns:t="http://dnetlib.eu/springbeans/t" xmlns:template="http://dnetlib.eu/springbeans/template"
7
	xmlns:util="http://www.springframework.org/schema/util"
8
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
9
                                    http://cxf.apache.org/ws/addressing http://cxf.apache.org/schemas/ws-addr-conf.xsd
10
                                    http://cxf.apache.org/configuration/security http://cxf.apache.org/schemas/configuration/security.xsd
11
                                    http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd
12
                            http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
13
                            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
14
                            http://dnetlib.eu/springbeans/template http://dnetlib.eu/springbeans/template.xsd">
15
                            
16
    <bean id="downloadNotificationHandler"
17
		class="eu.dnetlib.enabling.tools.blackboard.BlackboardServerExecutorNotificationHandler"
18
		p:blackboardExecutor-ref="downloadBlackboardExecutor" />
19
		
20
	<bean id = "DownloadServiceFeeder" class ="eu.dnetlib.data.download.rmi.DownloadServiceFeeder" />
21

  
22
	<bean id="downloadBlackboardExecutor"
23
		class="eu.dnetlib.enabling.tools.blackboard.BlackboardServerActionExecutor"
24
		p:blackboardHandler-ref="blackboardHandler"
25
		p:actionType="eu.dnetlib.data.download.rmi.DownloadServiceActions"
26
		p:incomplete="false">
27
		<property name="actionMap">
28
			<map>
29
				<entry key="DOWNLOAD">
30
					<bean class="eu.dnetlib.data.download.DownloadAction"/>
31
				</entry>				
32
			</map>
33
		</property>
34
	</bean>		
35
                            
36
                            
37
    <bean id="DummyPlugin" class="eu.dnetlib.data.download.plugins.DummyPlugin" />
38

  
39
	<bean id="downloadSerive" class="eu.dnetlib.data.download.DownloadServiceImpl"
40
		init-method="start" p:notificationHandler-ref="downloadNotificationHandler" />
41

  
42
	<bean id="downloadPluginEnumerator" class="eu.dnetlib.data.download.DownloadPluginEnumeratorImpl" />
43

  
44
	<jaxws:endpoint id="downloadServiceEndpoint"
45
		implementor="#downloadSerive" implementorClass="eu.dnetlib.data.download.rmi.DownloadService"
46
		address="/downloadService" />
47

  
48
	<template:instance name="serviceRegistrationManager"
49
		t:serviceRegistrationManagerClass="eu.dnetlib.enabling.tools.registration.ValidatingServiceRegistrationManagerImpl"
50
		t:name="downloadServiceRegistrationManager" t:service="downloadSerive"
51
		t:endpoint="downloadServiceEndpoint" t:jobScheduler="jobScheduler"
52
		t:serviceRegistrator="blackboardServiceRegistrator" />
53

  
54

  
55
</beans>
modules/dnet-download-service/tags/dnet-download-service-2.1.7/pom.xml
1
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
2
	<parent>
3
		<groupId>eu.dnetlib</groupId>
4
		<artifactId>dnet-parent</artifactId>
5
		<version>1.0.0</version>
6
		<relativePath />
7
	</parent>
8
	<modelVersion>4.0.0</modelVersion>
9
	<groupId>eu.dnetlib</groupId>
10
	<artifactId>dnet-download-service</artifactId>
11
	<version>2.1.7</version>
12
	<scm>
13
	  <developerConnection>scm:svn:https://svn.driver.research-infrastructures.eu/driver/dnet40/modules/dnet-download-service/tags/dnet-download-service-2.1.7</developerConnection>
14
	</scm>
15
	<dependencies>
16
		<dependency>
17
			<groupId>eu.dnetlib</groupId>
18
			<artifactId>dnet-download-service-rmi</artifactId>
19
			<version>[1.0.0,2.0.0)</version>
20
		</dependency>		
21
		<dependency>
22
			<groupId>eu.dnetlib</groupId>
23
			<artifactId>cnr-service-common</artifactId>
24
			<version>[2.1.0,3.0.0)</version>
25
		</dependency>
26
		<dependency>
27
			<groupId>eu.dnetlib</groupId>
28
			<artifactId>dnet-modular-objectstore-service</artifactId>
29
			<version>[4.0.0,5.0.0)</version>
30
		</dependency>		
31
	</dependencies>
32
</project>

Also available in: Unified diff