Project

General

Profile

« Previous | Next » 

Revision 34727

[maven-release-plugin] copy for tag dnet-msro-service-3.0.1

View differences:

modules/dnet-msro-service/tags/dnet-msro-service-3.0.1/src/main/java/eu/dnetlib/msro/workflows/nodes/BlackboardJobNode.java
1
package eu.dnetlib.msro.workflows.nodes;
2

  
3
import javax.annotation.Resource;
4

  
5
import org.apache.commons.lang.StringUtils;
6
import org.apache.commons.logging.Log;
7
import org.apache.commons.logging.LogFactory;
8

  
9
import com.googlecode.sarasvati.Engine;
10
import com.googlecode.sarasvati.NodeToken;
11

  
12
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
13
import eu.dnetlib.enabling.tools.blackboard.BlackboardClientHandler;
14
import eu.dnetlib.enabling.tools.blackboard.BlackboardJob;
15
import eu.dnetlib.enabling.tools.blackboard.BlackboardJobImpl;
16
import eu.dnetlib.enabling.tools.blackboard.BlackboardJobRegistry;
17
import eu.dnetlib.msro.workflows.nodes.blackboard.BlackboardWorkflowJobListener;
18
import eu.dnetlib.msro.workflows.util.WorkflowsConstants;
19

  
20
public abstract class BlackboardJobNode extends SarasvatiJobNode {
21

  
22
	@Resource
23
	private UniqueServiceLocator serviceLocator;
24

  
25
	/**
26
	 * logger.
27
	 */
28
	private static final Log log = LogFactory.getLog(BlackboardJobNode.class); // NOPMD by marko on 11/24/08 5:02 PM
29

  
30
	/**
31
	 * blackboard handler.
32
	 */
33
	@Resource
34
	private BlackboardClientHandler blackboardClientHandler;
35

  
36
	/**
37
	 * blackboard job registry.
38
	 */
39
	@Resource
40
	private BlackboardJobRegistry jobRegistry;
41

  
42
	@Override
43
	public void execute(final Engine engine, final NodeToken token) {
44
		super.execute(engine, token);
45

  
46
		log.info("executing blackboard node");
47

  
48
		try {
49
			token.getEnv().setAttribute(WorkflowsConstants.BLACKBOARD_IS_BLACKBOARD, true);
50

  
51
			final String serviceId = obtainServiceId(token);
52
			if (StringUtils.isBlank(serviceId)) {
53
				token.getEnv().setAttribute(WorkflowsConstants.SYSTEM_HAS_FAILED, true);
54
				final String msg = "cannot locate target service profile: " + serviceId;
55
				token.getEnv().setAttribute(WorkflowsConstants.SYSTEM_ERROR, msg);
56
				log.error(msg);
57
				engine.complete(token, "failed");
58
				return;
59
			}
60

  
61
			final BlackboardJob job = blackboardClientHandler.newJob(serviceId);
62

  
63
			token.getEnv().setTransientAttribute(WorkflowsConstants.BLACKBOARD_JOB, job);
64
			token.getEnv().setAttribute(WorkflowsConstants.BLACKBOARD_SERVICE_ID, ((BlackboardJobImpl) job).getServiceId());
65
			prepareJob(job, token);
66

  
67
			jobRegistry.registerJobListener(job, generateBlackboardListener(engine, token));
68

  
69
			blackboardClientHandler.assign(job);
70

  
71
		} catch (final Throwable e) {
72
			token.getEnv().setAttribute(WorkflowsConstants.SYSTEM_HAS_FAILED, true);
73
			token.getEnv().setAttribute(WorkflowsConstants.SYSTEM_ERROR, "cannot prepare blackboard job: " + e);
74
			engine.complete(token, "failed");
75
			log.error("cannot prepare blackboard job", e);
76
		}
77
	}
78

  
79
	abstract protected String obtainServiceId(NodeToken token);
80

  
81
	abstract protected void prepareJob(final BlackboardJob job, final NodeToken token) throws Exception;
82

  
83
	protected BlackboardWorkflowJobListener generateBlackboardListener(final Engine engine, final NodeToken token) {
84
		return new BlackboardWorkflowJobListener(engine, token);
85
	}
86

  
87
	public UniqueServiceLocator getServiceLocator() {
88
		return serviceLocator;
89
	}
90

  
91
}
modules/dnet-msro-service/tags/dnet-msro-service-3.0.1/src/main/java/eu/dnetlib/msro/workflows/nodes/repobye/DeleteMetaWfJobNode.java
1
package eu.dnetlib.msro.workflows.nodes.repobye;
2

  
3
import java.io.StringReader;
4
import java.io.StringWriter;
5

  
6
import javax.annotation.Resource;
7

  
8
import org.apache.commons.logging.Log;
9
import org.apache.commons.logging.LogFactory;
10
import org.dom4j.Document;
11
import org.dom4j.Node;
12
import org.dom4j.io.SAXReader;
13

  
14
import com.googlecode.sarasvati.Arc;
15
import com.googlecode.sarasvati.NodeToken;
16

  
17
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
18
import eu.dnetlib.enabling.is.registry.rmi.ISRegistryService;
19
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
20
import eu.dnetlib.msro.workflows.nodes.SimpleJobNode;
21
import eu.dnetlib.msro.workflows.util.WorkflowsConstants;
22

  
23
public class DeleteMetaWfJobNode extends SimpleJobNode {
24

  
25
	private String metaWfId;
26

  
27
	@Resource
28
	private UniqueServiceLocator serviceLocator;
29

  
30
	private static final Log log = LogFactory.getLog(DeleteMetaWfJobNode.class);
31

  
32
	@Override
33
	protected String execute(final NodeToken token) throws Exception {
34
		final String profile = serviceLocator.getService(ISLookUpService.class).getResourceProfile(metaWfId);
35
		final Document doc = new SAXReader().read(new StringReader(profile));
36

  
37
		final String dsId = doc.valueOf("//DATAPROVIDER/@id");
38
		final String dsName = doc.valueOf("//DATAPROVIDER/text()");
39
		final String ifaceId = doc.valueOf("//DATAPROVIDER/@interface");
40
		final String destroyWfId = doc.valueOf("//CONFIGURATION/@destroyWorkflow");
41

  
42
		log.info("Removing a MetaWf of dataprovider: " + dsId);
43

  
44
		token.getEnv().setAttribute(WorkflowsConstants.DATAPROVIDER_ID, dsId);
45
		token.getEnv().setAttribute(WorkflowsConstants.DATAPROVIDER_NAME, dsName);
46
		token.getEnv().setAttribute(WorkflowsConstants.DATAPROVIDER_INTERFACE, ifaceId);
47

  
48
		final ISRegistryService registry = serviceLocator.getService(ISRegistryService.class);
49

  
50
		for (Object o : doc.selectNodes("//WORKFLOW")) {
51
			final String wfId = ((Node) o).valueOf("@id");
52
			try {
53
				registry.deleteProfile(wfId);
54
				log.info(" - Deleted Workflow: " + wfId);
55
			} catch (Exception e) {
56
				log.error(" - (ERR) Error deleting profile " + wfId);
57
			}
58
		}
59
		registry.deleteProfile(metaWfId);
60
		log.info(" - Deleted MetaWorkflow: " + metaWfId);
61

  
62
		registry.deleteProfile(destroyWfId);
63
		log.info(" - Deleted destroy workflow: " + destroyWfId);
64

  
65
		verifyDatasource(dsId, ifaceId);
66

  
67
		return Arc.DEFAULT_ARC;
68
	}
69

  
70
	private void verifyDatasource(final String dsId, final String ifaceId) throws Exception {
71
		final StringWriter sw = new StringWriter();
72

  
73
		sw.append("for $x in collection('/db/DRIVER/MetaWorkflowDSResources/MetaWorkflowDSResourceType') where");
74
		sw.append("  $x//DATAPROVIDER/@id = '" + dsId + "' and ");
75
		sw.append("  $x//DATAPROVIDER/@interface = '" + ifaceId + "' and ");
76
		sw.append("  $x//RESOURCE_IDENTIFIER/@value != '" + metaWfId + "' ");
77
		sw.append("return $x//RESOURCE_IDENTIFIER/@value/string()");
78

  
79
		final boolean active = !serviceLocator.getService(ISLookUpService.class).quickSearchProfile(sw.toString()).isEmpty();
80

  
81
		log.info(" - Updating iface, active status: " + active);
82

  
83
		updateIfaceActivationStatus(dsId, ifaceId, active);
84
	}
85

  
86
	protected void updateIfaceActivationStatus(final String dsId, final String ifaceId, final boolean active) throws Exception {
87
		serviceLocator.getService(ISRegistryService.class).updateProfileNode(dsId, "//INTERFACE[@id = '" + ifaceId + "']/@active", "'" + active + "'");
88
	}
89

  
90
	public String getMetaWfId() {
91
		return metaWfId;
92
	}
93

  
94
	public void setMetaWfId(final String metaWfId) {
95
		this.metaWfId = metaWfId;
96
	}
97

  
98
}
modules/dnet-msro-service/tags/dnet-msro-service-3.0.1/src/main/java/eu/dnetlib/msro/workflows/nodes/download/UrlExtractor.java
1
package eu.dnetlib.msro.workflows.nodes.download;
2

  
3
import java.io.ByteArrayInputStream;
4
import java.util.ArrayList;
5
import java.util.List;
6

  
7
import javax.xml.parsers.DocumentBuilder;
8
import javax.xml.parsers.DocumentBuilderFactory;
9
import javax.xml.xpath.XPath;
10
import javax.xml.xpath.XPathConstants;
11
import javax.xml.xpath.XPathExpression;
12
import javax.xml.xpath.XPathFactory;
13

  
14
import org.apache.commons.lang.StringUtils;
15
import org.apache.commons.logging.Log;
16
import org.apache.commons.logging.LogFactory;
17
import org.joda.time.DateTime;
18
import org.joda.time.format.DateTimeFormat;
19
import org.joda.time.format.DateTimeFormatter;
20
import org.w3c.dom.Document;
21
import org.w3c.dom.NodeList;
22

  
23
import com.google.common.base.Function;
24
import com.google.gson.Gson;
25

  
26
import eu.dnetlib.data.download.rmi.DownloadItem;
27

  
28
// TODO: Auto-generated Javadoc
29
/**
30
 * The Class UrlExtractor.
31
 */
32
public class UrlExtractor implements Function<String, String> {
33

  
34
	/** The Constant log. */
35
	private static final Log log = LogFactory.getLog(UrlExtractor.class);
36

  
37
	/** The xpath url. */
38
	private String xpathURL;
39

  
40
	/** The xpath. */
41
	private String xpathMetadataID;
42

  
43
	/** The xpath open access. */
44
	private String xpathOpenAccess;
45

  
46
	/** The xpath embargo date. */
47
	private String xpathEmbargoDate;
48

  
49
	/**
50
	 * Instantiates a new url extractor.
51
	 *
52
	 * @param xpath
53
	 *            the xpath
54
	 * @param xpathMetadataID
55
	 *            the xpath metadata id
56
	 */
57
	public UrlExtractor(final String xpath, final String xpathMetadataID, final String xpathOpenAccess, final String xpathEmbargoDate) {
58
		this.xpathURL = xpath;
59
		this.xpathMetadataID = xpathMetadataID;
60
		this.xpathOpenAccess = xpathOpenAccess;
61
		this.xpathEmbargoDate = xpathEmbargoDate;
62
	}
63

  
64
	/*
65
	 * (non-Javadoc)
66
	 *
67
	 * @see com.google.common.base.Function#apply(java.lang.Object)
68
	 */
69
	@Override
70
	public String apply(final String input) {
71
		try {
72
			DownloadItem di = new DownloadItem();
73
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
74
			DocumentBuilder builder;
75
			builder = factory.newDocumentBuilder();
76
			if (input == null) {
77
				log.error("Metadata input is null");
78
				return null;
79
			}
80
			Document doc = builder.parse(new ByteArrayInputStream(input.getBytes()));
81
			XPathFactory xPathFactory = XPathFactory.newInstance();
82
			XPath myXpath = xPathFactory.newXPath();
83
			XPathExpression expression = myXpath.compile(xpathURL);
84
			Object values = expression.evaluate(doc, XPathConstants.NODESET);
85
			di.setUrl(getNodes((NodeList) values));
86
			di.setOriginalUrl(getNodes((NodeList) values));
87

  
88
			if (xpathOpenAccess != null) {
89
				expression = myXpath.compile(xpathOpenAccess);
90
				String openAccess = expression.evaluate(doc);
91
				di.setOpenAccess(openAccess);
92
			}
93
			if (xpathEmbargoDate != null) {
94
				expression = myXpath.compile(xpathEmbargoDate);
95
				String embargoDate = expression.evaluate(doc);
96
				if (!StringUtils.isEmpty(embargoDate)) {
97
					try {
98
						DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");
99
						DateTime dt = fmt.parseDateTime(embargoDate);
100
						di.setEmbargoDate(dt.toDate());
101
					} catch (Exception pe) {}
102
				}
103
			}
104
			expression = myXpath.compile(xpathMetadataID);
105
			String extracted_metadataId = expression.evaluate(doc);
106
			di.setIdItemMetadata(extracted_metadataId);
107
			return di.toJSON();
108
		} catch (Exception e) {
109
			log.error("OPSSS... Something bad happen on evaluating ", e);
110
			return null;
111
		}
112

  
113
	}
114

  
115
	/**
116
	 * Gets the nodes.
117
	 *
118
	 * @param nodes
119
	 *            the nodes
120
	 * @return the nodes
121
	 */
122
	private String getNodes(final NodeList nodes) {
123
		List<String> extracted_Url = new ArrayList<String>();
124
		if (nodes != null) {
125
			for (int i = 0; i < nodes.getLength(); i++) {
126
				extracted_Url.add(nodes.item(i).getNodeValue());
127
			}
128
		}
129
		return new Gson().toJson(extracted_Url);
130
	}
131

  
132
	/**
133
	 * Gets the xpath metadata id.
134
	 *
135
	 * @return the xpathMetadataID
136
	 */
137
	public String getXpathMetadataID() {
138
		return xpathMetadataID;
139
	}
140

  
141
	/**
142
	 * Sets the xpath metadata id.
143
	 *
144
	 * @param xpathMetadataID
145
	 *            the xpathMetadataID to set
146
	 */
147
	public void setXpathMetadataID(final String xpathMetadataID) {
148
		this.xpathMetadataID = xpathMetadataID;
149
	}
150

  
151
	/**
152
	 * Gets the xpath url.
153
	 *
154
	 * @return the xpath url
155
	 */
156
	public String getXpathURL() {
157
		return xpathURL;
158
	}
159

  
160
	/**
161
	 * Sets the xpath url.
162
	 *
163
	 * @param xpathURL
164
	 *            the new xpath url
165
	 */
166
	public void setXpathURL(final String xpathURL) {
167
		this.xpathURL = xpathURL;
168
	}
169

  
170
	/**
171
	 * Gets the xpath open access.
172
	 *
173
	 * @return the xpath open access
174
	 */
175
	public String getXpathOpenAccess() {
176
		return xpathOpenAccess;
177
	}
178

  
179
	/**
180
	 * Sets the xpath open access.
181
	 *
182
	 * @param xpathOpenAccess
183
	 *            the new xpath open access
184
	 */
185
	public void setXpathOpenAccess(final String xpathOpenAccess) {
186
		this.xpathOpenAccess = xpathOpenAccess;
187
	}
188

  
189
	/**
190
	 * Gets the xpath embargo date.
191
	 *
192
	 * @return the xpath embargo date
193
	 */
194
	public String getXpathEmbargoDate() {
195
		return xpathEmbargoDate;
196
	}
197

  
198
	/**
199
	 * Sets the xpath embargo date.
200
	 *
201
	 * @param xpathEmbargoDate
202
	 *            the new xpath embargo date
203
	 */
204
	public void setXpathEmbargoDate(final String xpathEmbargoDate) {
205
		this.xpathEmbargoDate = xpathEmbargoDate;
206
	}
207

  
208
}
modules/dnet-msro-service/tags/dnet-msro-service-3.0.1/src/main/java/eu/dnetlib/msro/workflows/nodes/blackboard/OngoingBlackboardWorkflowJobListener.java
1
package eu.dnetlib.msro.workflows.nodes.blackboard;
2

  
3
import com.googlecode.sarasvati.Arc;
4
import com.googlecode.sarasvati.Engine;
5
import com.googlecode.sarasvati.NodeToken;
6

  
7
import eu.dnetlib.enabling.tools.blackboard.BlackboardJob;
8

  
9
public class OngoingBlackboardWorkflowJobListener extends BlackboardWorkflowJobListener {
10

  
11
	public OngoingBlackboardWorkflowJobListener(Engine engine, NodeToken token) {
12
		super(engine, token);
13
	}
14

  
15
	@Override
16
	protected void onOngoing(BlackboardJob job) {
17
		super.onOngoing(job);
18
		complete(job, Arc.DEFAULT_ARC);
19
	}
20

  
21
}
modules/dnet-msro-service/tags/dnet-msro-service-3.0.1/src/main/java/eu/dnetlib/msro/workflows/nodes/mdstore/MultipleMdStoreIterator.java
1
package eu.dnetlib.msro.workflows.nodes.mdstore;
2

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

  
6
import javax.annotation.Resource;
7
import javax.xml.ws.wsaddressing.W3CEndpointReference;
8

  
9
import org.apache.commons.logging.Log;
10
import org.apache.commons.logging.LogFactory;
11
import org.springframework.beans.factory.annotation.Autowired;
12

  
13
import eu.dnetlib.data.mdstore.MDStoreService;
14
import eu.dnetlib.data.mdstore.MDStoreServiceException;
15
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
16
import eu.dnetlib.enabling.resultset.client.ResultSetClientFactory;
17

  
18
// TODO: Auto-generated Javadoc
19
/**
20
 * The Class MultipleMdStoreIterator.
21
 */
22
public class MultipleMdStoreIterator implements Iterator<String> {
23

  
24
	private static final Log log = LogFactory.getLog(MultipleMdStoreIterator.class); // NOPMD by marko on 11/24/08 5:02 PM
25

  
26
	/** The service locator. */
27
	@Resource
28
	private UniqueServiceLocator serviceLocator;
29

  
30
	/** The md i ds. */
31
	private List<String> mdIDs;
32

  
33
	/** The current id. */
34
	private String currentId = null;
35

  
36
	/** The current iterator. */
37
	private Iterator<String> currentIterator;
38

  
39
	/** The result set client factory. */
40
	@Autowired
41
	private ResultSetClientFactory resultSetClientFactory;
42

  
43
	/**
44
	 * Instantiates a new multiple md store iterator.
45
	 *
46
	 * @param mdstoreLocator
47
	 *            the mdstore locator
48
	 * @param mdIds
49
	 *            the md ids
50
	 */
51
	public MultipleMdStoreIterator(final UniqueServiceLocator serviceLocator, final List<String> mdIds, final ResultSetClientFactory resultSetClientFactory) {
52
		this.serviceLocator = serviceLocator;
53
		this.mdIDs = mdIds;
54
		this.resultSetClientFactory = resultSetClientFactory;
55
		getNextMDStoreRecords();
56

  
57
	}
58

  
59
	/*
60
	 * (non-Javadoc)
61
	 * 
62
	 * @see java.util.Iterator#hasNext()
63
	 */
64
	@Override
65
	public boolean hasNext() {
66
		if (currentId == null || currentIterator == null) { return false; }
67
		return currentIterator.hasNext();
68
	}
69

  
70
	/*
71
	 * (non-Javadoc)
72
	 * 
73
	 * @see java.util.Iterator#next()
74
	 */
75
	@Override
76
	public String next() {
77
		String nextElement = currentIterator.next();
78
		if (!currentIterator.hasNext()) {
79
			getNextMDStoreRecords();
80
		}
81
		return nextElement;
82
	}
83

  
84
	/*
85
	 * (non-Javadoc)
86
	 * 
87
	 * @see java.util.Iterator#remove()
88
	 */
89
	@Override
90
	public void remove() {
91
		currentIterator.remove();
92
	}
93

  
94
	/**
95
	 * Gets the next md store records.
96
	 *
97
	 * @return the next md store records
98
	 */
99
	private void getNextMDStoreRecords() {
100
		if (mdIDs.size() > 0) {
101
			currentId = mdIDs.remove(0);
102
			currentIterator = getIterableResultset(currentId);
103
		}
104
	}
105

  
106
	/**
107
	 * Gets the iterable resultset.
108
	 *
109
	 * @param id
110
	 *            the id
111
	 * @return the iterable resultset
112
	 */
113
	private Iterator<String> getIterableResultset(final String id) {
114
		try {
115
			W3CEndpointReference epr = serviceLocator.getService(MDStoreService.class, id).deliverMDRecords(id, "", "", "");
116
			Iterable<String> input = resultSetClientFactory.getClient(epr);
117
			return input.iterator();
118
		} catch (MDStoreServiceException e) {
119
			log.error(e);
120
			return null;
121
		}
122
	}
123
}
modules/dnet-msro-service/tags/dnet-msro-service-3.0.1/src/main/java/eu/dnetlib/msro/workflows/nodes/collect/FindDateRangeForIncrementalHarvestingJobNode.java
1
package eu.dnetlib.msro.workflows.nodes.collect;
2

  
3
import java.text.SimpleDateFormat;
4
import java.util.Date;
5
import java.util.Iterator;
6
import java.util.Map;
7

  
8
import javax.annotation.Resource;
9

  
10
import org.apache.commons.lang.math.NumberUtils;
11
import org.apache.commons.logging.Log;
12
import org.apache.commons.logging.LogFactory;
13

  
14
import com.googlecode.sarasvati.Arc;
15
import com.googlecode.sarasvati.NodeToken;
16

  
17
import eu.dnetlib.common.logging.DnetLogger;
18
import eu.dnetlib.msro.rmi.MSROException;
19
import eu.dnetlib.msro.workflows.nodes.SimpleJobNode;
20
import eu.dnetlib.msro.workflows.util.WorkflowsConstants;
21

  
22
public class FindDateRangeForIncrementalHarvestingJobNode extends SimpleJobNode {
23
	
24
	private String fromDateParam;
25
	private String untilDateParam;
26
	private long ONE_DAY = 1000 * 60 * 60 * 24;	
27
	
28
	@Resource(name = "msroWorkflowLogger")
29
	private DnetLogger dnetLogger;
30
	
31
	private static final Log log = LogFactory.getLog(FindDateRangeForIncrementalHarvestingJobNode.class);
32
	
33
	@Override
34
	protected String execute(NodeToken token) throws Exception {
35
		final String profId = findCurrentWfProfileId(token);
36
		final String fromDate = calculateFromDate(profId); 
37
		final String untilDate = null;
38
		
39
		log.info("Incremental Harv Details - profId: " + profId + " - from: " + fromDate + " - until: " + untilDate);
40
		
41
		if (fromDate != null) {
42
			token.getEnv().setAttribute(getFromDateParam(), fromDate);
43
		}
44
		
45
		//if (untilDate != null) {
46
		//	token.getEnv().setAttribute(getUntilDateParam(), untilDate);
47
		//}
48
		
49
		return Arc.DEFAULT_ARC;
50
	}	
51
	
52
	private String calculateFromDate(final String profId) {
53
		final long d = findLastSuccessStartDate(profId);
54
		return (d > 0) ? (new SimpleDateFormat("yyyy-MM-dd")).format(new Date(d - ONE_DAY)) : null;
55
	}
56

  
57
	private long findLastSuccessStartDate(String profId) {
58
		long res = -1;
59
		
60
		final Iterator<Map<String, String>> iter = dnetLogger.find(WorkflowsConstants.SYSTEM_WF_PROFILE_ID, profId);
61
		while (iter.hasNext()) {
62
			final Map<String, String> map = iter.next();
63
			if ("true".equalsIgnoreCase(map.get(WorkflowsConstants.SYSTEM_COMPLETED_SUCCESSFULLY))) {
64
				final long curr = NumberUtils.toLong(map.get(WorkflowsConstants.SYSTEM_START_DATE), -1);
65
				if (curr > res) {
66
					res = curr;
67
				}
68
			}
69
		}
70
		return res;
71
	}
72

  
73
	private String findCurrentWfProfileId(NodeToken token) throws MSROException {
74
		final String p1 = token.getEnv().getAttribute(WorkflowsConstants.SYSTEM_WF_PROFILE_ID);
75
		if (p1 != null && !p1.isEmpty()) {
76
			return p1;
77
		}
78
		final String p2 = token.getFullEnv().getAttribute(WorkflowsConstants.SYSTEM_WF_PROFILE_ID);
79
		if (p2 != null && !p2.isEmpty()) {
80
			return p2;
81
		}
82
		final String p3 = token.getProcess().getEnv().getAttribute(WorkflowsConstants.SYSTEM_WF_PROFILE_ID);
83
		if (p3 != null && !p3.isEmpty()) {
84
			return p3;
85
		}
86
		throw new MSROException("Missing property in env: " + WorkflowsConstants.SYSTEM_WF_PROFILE_ID);
87
	}
88

  
89
	public String getFromDateParam() {
90
		return fromDateParam;
91
	}
92
	public void setFromDateParam(String fromDateParam) {
93
		this.fromDateParam = fromDateParam;
94
	}
95
	public String getUntilDateParam() {
96
		return untilDateParam;
97
	}
98
	public void setUntilDateParam(String untilDateParam) {
99
		this.untilDateParam = untilDateParam;
100
	}
101
	
102
}
modules/dnet-msro-service/tags/dnet-msro-service-3.0.1/src/main/java/eu/dnetlib/msro/workflows/nodes/mdstore/FetchMDStoreRecordsJobNode.java
1
package eu.dnetlib.msro.workflows.nodes.mdstore;
2

  
3
import javax.annotation.Resource;
4
import javax.xml.ws.wsaddressing.W3CEndpointReference;
5

  
6
import org.apache.commons.logging.Log;
7
import org.apache.commons.logging.LogFactory;
8

  
9
import com.googlecode.sarasvati.Arc;
10
import com.googlecode.sarasvati.NodeToken;
11

  
12
import eu.dnetlib.data.mdstore.MDStoreService;
13
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
14
import eu.dnetlib.msro.rmi.MSROException;
15
import eu.dnetlib.msro.workflows.nodes.SimpleJobNode;
16

  
17
public class FetchMDStoreRecordsJobNode extends SimpleJobNode {
18

  
19
	private static final Log log = LogFactory.getLog(FetchMDStoreRecordsJobNode.class); // NOPMD by marko on 11/24/08 5:02 PM
20

  
21
	@Resource
22
	private UniqueServiceLocator serviceLocator;
23

  
24
	private String mdId;
25
	private String mdFormat;
26
	private String eprParam;
27

  
28
	@Override
29
	protected String execute(final NodeToken token) throws Exception {
30
		if (getMdId() == null) {
31
			setMdId(token.getEnv().getAttribute("mdId"));
32
		}
33
		if (getMdFormat() == null) {
34
			setMdFormat(token.getEnv().getAttribute("mdFormat"));
35
		}
36

  
37
		log.info("getting MDRecords from: " + getMdId());
38
		final W3CEndpointReference epr = serviceLocator.getService(MDStoreService.class, getMdId()).deliverMDRecords(getMdId(), "", "", "");
39
		if (epr == null) { throw new MSROException("unable to read MDRecords from: " + getMdId()); }
40
		token.getEnv().setAttribute(getEprParam(), epr.toString());
41
		return Arc.DEFAULT_ARC;
42
	}
43

  
44
	public String getMdId() {
45
		return mdId;
46
	}
47

  
48
	public void setMdId(final String mdId) {
49
		this.mdId = mdId;
50
	}
51

  
52
	public String getMdFormat() {
53
		return mdFormat;
54
	}
55

  
56
	public void setMdFormat(final String mdFormat) {
57
		this.mdFormat = mdFormat;
58
	}
59

  
60
	public String getEprParam() {
61
		return eprParam;
62
	}
63

  
64
	public void setEprParam(final String eprParam) {
65
		this.eprParam = eprParam;
66
	}
67
}
modules/dnet-msro-service/tags/dnet-msro-service-3.0.1/src/main/java/eu/dnetlib/msro/workflows/nodes/transform/GroovyJobNode.java
1
package eu.dnetlib.msro.workflows.nodes.transform;
2

  
3
import java.io.IOException;
4
import java.util.Map;
5

  
6
import javax.annotation.Resource;
7
import javax.xml.ws.wsaddressing.W3CEndpointReference;
8

  
9
import org.apache.commons.logging.Log;
10
import org.apache.commons.logging.LogFactory;
11
import org.springframework.beans.factory.annotation.Required;
12

  
13
import com.google.common.collect.Maps;
14
import com.googlecode.sarasvati.Arc;
15
import com.googlecode.sarasvati.NodeToken;
16

  
17
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
18
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
19
import eu.dnetlib.enabling.resultset.MappedResultSetFactory;
20
import eu.dnetlib.enabling.resultset.client.utils.EPRUtils;
21
import eu.dnetlib.msro.rmi.MSROException;
22
import eu.dnetlib.msro.workflows.nodes.SimpleJobNode;
23
import groovy.lang.GroovyShell;
24
import groovy.util.GroovyScriptEngine;
25

  
26
public class GroovyJobNode extends SimpleJobNode {
27

  
28
	private static final Log log = LogFactory.getLog(GroovyJobNode.class);
29

  
30
	/**
31
	 * used to transform the records using Groovy.
32
	 */
33

  
34
	private MappedResultSetFactory mappedResultSetFactory;
35

  
36
	private String inputEprParam;
37
	private String outputEprParam;
38
	private String transformationRuleId;
39
	// private String groovyParams;
40

  
41
	@Resource
42
	private UniqueServiceLocator serviceLocator;
43

  
44
	private Map<String, String> retrieveGroovyParameter() {
45
		Map<String, String> out = Maps.newHashMap();
46

  
47
		String query = "for $x in collection('/db/DRIVER/GroovyProcessingDSResource/GroovyProcessingDSResourceType')"
48
				+ "where $x[.//RESOURCE_IDENTIFIER/@value='" + transformationRuleId + "']"
49
				+ "return concat($x//GROOVY_CLASSPATH/text(),':::',$x//GROOVY_DNETCLASS/text())";
50
		try {
51
			String result = serviceLocator.getService(ISLookUpService.class).quickSearchProfile(query).get(0);
52
			if (result == null) { return null; }
53
			String[] data = result.trim().split(":::");
54
			if (data.length == 2) {
55
				out.put("classpath", data[0]);
56
				out.put("mainClass", data[1]);
57
			}
58

  
59
			return out;
60
		} catch (Exception e) {
61
			log.error(e);
62
			return null;
63
		}
64
	}
65

  
66
	@Override
67
	protected String execute(final NodeToken token) throws Exception {
68
		final String inputEprString = token.getEnv().getAttribute(inputEprParam);
69
		if (inputEprString == null || inputEprString.isEmpty()) { throw new MSROException("InputEprParam (" + inputEprParam + ") not found in ENV"); }
70
		final W3CEndpointReference inputEpr = new EPRUtils().getEpr(inputEprString);
71
		String groovyClasspath, groovyDnetClass;
72
		Map<String, String> prop = retrieveGroovyParameter();
73
		groovyClasspath = prop.get("classpath");
74
		groovyDnetClass = prop.get("mainClass");
75
		W3CEndpointReference epr = transformGroovy(inputEpr, groovyClasspath, groovyDnetClass, parseJsonParameters(token));
76
		token.getEnv().setAttribute(outputEprParam, epr.toString());
77
		return Arc.DEFAULT_ARC;
78
	}
79

  
80
	private W3CEndpointReference transformGroovy(final W3CEndpointReference source,
81
			final String groovyClasspath,
82
			final String groovyDnetClass,
83
			final Map<String, String> params) throws ClassNotFoundException, IOException {
84

  
85
		GroovyScriptEngine gse = new GroovyScriptEngine(groovyClasspath);
86
		gse.getGroovyClassLoader().loadClass(groovyDnetClass);
87
		log.info("***********************************************");
88
		log.info("Loaded Groovy classes:");
89
		for (Class<?> c : gse.getGroovyClassLoader().getLoadedClasses()) {
90
			log.info(c.getCanonicalName());
91
		}
92
		log.info("***********************************************");
93
		GroovyShell groovyShell = new GroovyShell(gse.getGroovyClassLoader());
94

  
95
		Object go = groovyShell.evaluate("new " + groovyDnetClass + "()");
96
		if (go instanceof GroovyUnaryFunction) {
97
			GroovyUnaryFunction groovyUnaryFunction = (GroovyUnaryFunction) go;
98
			if (params != null) {
99
				groovyUnaryFunction.setParams(params);
100
			}
101
			return mappedResultSetFactory.createMappedResultSet(source, groovyUnaryFunction);
102
		} else {
103
			throw new RuntimeException("Groovy object " + go + " is not supported");
104
		}
105
	}
106

  
107
	public MappedResultSetFactory getMappedResultSetFactory() {
108
		return mappedResultSetFactory;
109
	}
110

  
111
	@Required
112
	public void setMappedResultSetFactory(final MappedResultSetFactory mappedResultSetFactory) {
113
		this.mappedResultSetFactory = mappedResultSetFactory;
114
	}
115

  
116
	public String getInputEprParam() {
117
		return inputEprParam;
118
	}
119

  
120
	public void setInputEprParam(final String inputEprParam) {
121
		this.inputEprParam = inputEprParam;
122
	}
123

  
124
	public String getOutputEprParam() {
125
		return outputEprParam;
126
	}
127

  
128
	public void setOutputEprParam(final String outputEprParam) {
129
		this.outputEprParam = outputEprParam;
130
	}
131

  
132
	public String getTransformationRuleId() {
133
		return transformationRuleId;
134
	}
135

  
136
	public void setTransformationRuleId(final String transformationRuleId) {
137
		this.transformationRuleId = transformationRuleId;
138
	}
139

  
140
}
modules/dnet-msro-service/tags/dnet-msro-service-3.0.1/src/main/java/eu/dnetlib/msro/workflows/nodes/db/UpdateDbJobNode.java
1
package eu.dnetlib.msro.workflows.nodes.db;
2

  
3
import org.apache.commons.logging.Log;
4
import org.apache.commons.logging.LogFactory;
5
import org.springframework.beans.factory.annotation.Required;
6

  
7
import com.googlecode.sarasvati.NodeToken;
8

  
9
import eu.dnetlib.enabling.database.rmi.DatabaseService;
10
import eu.dnetlib.enabling.tools.blackboard.BlackboardJob;
11
import eu.dnetlib.msro.workflows.nodes.BlackboardJobNode;
12
import eu.dnetlib.msro.workflows.nodes.ProgressJobNode;
13
import eu.dnetlib.msro.workflows.resultset.ProcessCountingResultSetFactory;
14
import eu.dnetlib.msro.workflows.util.ProgressProvider;
15
import eu.dnetlib.msro.workflows.util.ResultsetProgressProvider;
16

  
17
public class UpdateDbJobNode extends BlackboardJobNode implements ProgressJobNode {
18

  
19
	private String db;
20
	private String dbParam;
21
	private String eprParam;
22
	private ProcessCountingResultSetFactory processCountingResultSetFactory;
23
	private ResultsetProgressProvider progressProvider;
24

  
25
	private static final Log log = LogFactory.getLog(UpdateDbJobNode.class);
26

  
27
	@Override
28
	protected String obtainServiceId(final NodeToken token) {
29
		return getServiceLocator().getServiceId(DatabaseService.class);
30
	}
31

  
32
	@Override
33
	protected void prepareJob(final BlackboardJob job, final NodeToken token) throws Exception {
34
		if (db == null || db.isEmpty()) {
35
			db = token.getEnv().getAttribute(getDbParam());
36
		}
37

  
38
		log.info("preparing blackboard job to update DB: " + db);
39

  
40
		final String epr = token.getEnv().getAttribute(getEprParam());
41

  
42
		this.progressProvider = processCountingResultSetFactory.createProgressProvider(token.getProcess(), epr);
43

  
44
		job.setAction("IMPORT");
45
		job.getParameters().put("db", db);
46
		job.getParameters().put("epr", this.progressProvider.getEpr().toString());
47
	}
48

  
49
	@Override
50
	public ProgressProvider getProgressProvider() {
51
		return progressProvider;
52
	}
53

  
54
	public String getDb() {
55
		return db;
56
	}
57

  
58
	public void setDb(final String db) {
59
		this.db = db;
60
	}
61

  
62
	public String getEprParam() {
63
		return eprParam;
64
	}
65

  
66
	public void setEprParam(final String eprParam) {
67
		this.eprParam = eprParam;
68
	}
69

  
70
	public ProcessCountingResultSetFactory getProcessCountingResultSetFactory() {
71
		return processCountingResultSetFactory;
72
	}
73

  
74
	@Required
75
	public void setProcessCountingResultSetFactory(final ProcessCountingResultSetFactory processCountingResultSetFactory) {
76
		this.processCountingResultSetFactory = processCountingResultSetFactory;
77
	}
78

  
79
	public String getDbParam() {
80
		return dbParam;
81
	}
82

  
83
	public void setDbParam(final String dbParam) {
84
		this.dbParam = dbParam;
85
	}
86

  
87
}
modules/dnet-msro-service/tags/dnet-msro-service-3.0.1/src/main/java/eu/dnetlib/msro/workflows/nodes/db/QueryDbJobNode.java
1
package eu.dnetlib.msro.workflows.nodes.db;
2

  
3
import java.io.IOException;
4

  
5
import javax.annotation.Resource;
6
import javax.xml.ws.wsaddressing.W3CEndpointReference;
7

  
8
import org.apache.commons.io.IOUtils;
9
import org.apache.commons.lang.StringUtils;
10

  
11
import com.googlecode.sarasvati.Arc;
12
import com.googlecode.sarasvati.NodeToken;
13

  
14
import eu.dnetlib.enabling.database.rmi.DatabaseService;
15
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
16
import eu.dnetlib.msro.workflows.nodes.AsyncJobNode;
17

  
18
public class QueryDbJobNode extends AsyncJobNode {
19

  
20
	private String db;
21
	private String dbParam;
22
	private String dbProperty;
23

  
24
	private String sql;
25
	private String sqlForSize;
26
	private String xslt;
27
	private String outputEprParam;
28

  
29
	@Resource
30
	private UniqueServiceLocator serviceLocator;
31

  
32
	@Override
33
	protected String execute(final NodeToken token) throws Exception {
34
		final String sqlText = fetchSqlAsText(sql);
35

  
36
		W3CEndpointReference epr = null;
37

  
38
		final DatabaseService dbService = serviceLocator.getService(DatabaseService.class);
39

  
40
		if (StringUtils.isNotBlank(xslt)) {
41
			final String xsltText = IOUtils.toString(getClass().getResourceAsStream(xslt));
42

  
43
			if (StringUtils.isBlank(sqlForSize)) {
44
				epr = dbService.xsltSearchSQL(findDb(token), sqlText, xsltText);
45
			} else {
46
				epr = dbService.alternativeXsltSearchSQL(findDb(token), sqlText, fetchSqlAsText(sqlForSize), xsltText);
47
			}
48
		} else {
49
			if (StringUtils.isBlank(sqlForSize)) {
50
				epr = dbService.searchSQL(findDb(token), sqlText);
51
			} else {
52
				epr = dbService.alternativeSearchSQL(findDb(token), sqlText, fetchSqlAsText(sqlForSize));
53
			}
54
		}
55

  
56
		token.getEnv().setAttribute(outputEprParam, epr.toString());
57

  
58
		return Arc.DEFAULT_ARC;
59
	}
60

  
61
	private String fetchSqlAsText(final String path) throws IOException {
62
		return IOUtils.toString(getClass().getResourceAsStream(path));
63
	}
64

  
65
	private String findDb(final NodeToken token) {
66
		if (dbParam != null && !dbParam.isEmpty()) {
67
			return token.getEnv().getAttribute(dbParam);
68
		} else if (dbProperty != null && !dbProperty.isEmpty()) {
69
			return getPropertyFetcher().getProperty(dbProperty);
70
		} else {
71
			return db;
72
		}
73
	}
74

  
75
	public String getDb() {
76
		return db;
77
	}
78

  
79
	public void setDb(final String db) {
80
		this.db = db;
81
	}
82

  
83
	public String getDbParam() {
84
		return dbParam;
85
	}
86

  
87
	public void setDbParam(final String dbParam) {
88
		this.dbParam = dbParam;
89
	}
90

  
91
	public String getSql() {
92
		return sql;
93
	}
94

  
95
	public void setSql(final String sql) {
96
		this.sql = sql;
97
	}
98

  
99
	public String getXslt() {
100
		return xslt;
101
	}
102

  
103
	public void setXslt(final String xslt) {
104
		this.xslt = xslt;
105
	}
106

  
107
	public String getOutputEprParam() {
108
		return outputEprParam;
109
	}
110

  
111
	public void setOutputEprParam(final String outputEprParam) {
112
		this.outputEprParam = outputEprParam;
113
	}
114

  
115
	public String getDbProperty() {
116
		return dbProperty;
117
	}
118

  
119
	public void setDbProperty(final String dbProperty) {
120
		this.dbProperty = dbProperty;
121
	}
122

  
123
	public String getSqlForSize() {
124
		return sqlForSize;
125
	}
126

  
127
	public void setSqlForSize(final String sqlForSize) {
128
		this.sqlForSize = sqlForSize;
129
	}
130

  
131
}
modules/dnet-msro-service/tags/dnet-msro-service-3.0.1/pom.xml
1
<?xml version="1.0" encoding="UTF-8"?>
2
<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/maven-v4_0_0.xsd">
3
	<parent>
4
		<groupId>eu.dnetlib</groupId>
5
		<artifactId>dnet-parent</artifactId>
6
		<version>1.0.0</version>
7
		<relativePath />
8
	</parent>
9
	<modelVersion>4.0.0</modelVersion>
10
	<groupId>eu.dnetlib</groupId>
11
	<artifactId>dnet-msro-service</artifactId>
12
	<packaging>jar</packaging>
13
	<version>3.0.1</version>
14
	<scm>
15
		<developerConnection>scm:svn:https://svn.driver.research-infrastructures.eu/driver/dnet40/modules/dnet-msro-service/tags/dnet-msro-service-3.0.1</developerConnection>
16
	</scm>
17
	<dependencies>
18
		<dependency>
19
			<groupId>opensymphony</groupId>
20
			<artifactId>quartz</artifactId>
21
			<version>1.6.6</version>
22
		</dependency>
23
		<dependency>
24
			<groupId>eu.dnetlib</groupId>
25
			<artifactId>dnet-msro-service-api</artifactId>
26
			<version>[2.0.0,3.0.0)</version>
27
		</dependency>
28
		<dependency>
29
			<groupId>eu.dnetlib</groupId>
30
			<artifactId>cnr-resultset-service</artifactId>
31
			<version>[2.0.0,3.0.0)</version>
32
		</dependency>
33
		<dependency>
34
			<groupId>eu.dnetlib</groupId>
35
			<artifactId>cnr-data-utility-cleaner-rmi</artifactId>
36
			<version>[2.0.0,3.0.0)</version>
37
		</dependency>
38
		<dependency>
39
			<groupId>eu.dnetlib</groupId>
40
			<artifactId>cnr-resultset-client</artifactId>
41
			<version>[2.0.0,3.0.0)</version>
42
		</dependency>
43
		<dependency>
44
			<groupId>eu.dnetlib</groupId>
45
			<artifactId>dnet-download-service-rmi</artifactId>
46
			<version>[1.1.0,2.0.0)</version>
47
		</dependency>
48
		<dependency>
49
			<groupId>eu.dnetlib</groupId>
50
			<artifactId>dnet-datasource-manager-rmi</artifactId>
51
			<version>[4.0.0,5.0.0)</version>
52
		</dependency>
53
		<dependency>
54
			<groupId>eu.dnetlib</groupId>
55
			<artifactId>cnr-blackboard-common</artifactId>
56
			<version>[2.1.0,3.0.0)</version>
57
		</dependency>
58
		<dependency>
59
			<groupId>eu.dnetlib</groupId>
60
			<artifactId>dnet-mongo-logging</artifactId>
61
			<version>[1.0.0,2.0.0)</version>
62
		</dependency>
63
		<dependency>
64
			<groupId>com.googlecode</groupId>
65
			<artifactId>sarasvati</artifactId>
66
			<version>1.0.3</version>
67
		</dependency>
68
		<dependency>
69
			<groupId>com.googlecode</groupId>
70
			<artifactId>sarasvati-visual</artifactId>
71
			<version>1.0.3</version>
72
		</dependency>
73
		<dependency>
74
			<groupId>eu.dnetlib</groupId>
75
			<artifactId>dnet-modular-collector-service-rmi</artifactId>
76
			<version>[1.3.0,2.0.0)</version>
77
		</dependency>
78
		<dependency>
79
			<groupId>eu.dnetlib</groupId>
80
			<artifactId>cnr-enabling-database-api</artifactId>
81
			<version>[1.0.0,2.0.0)</version>
82
		</dependency>
83
		<dependency>
84
			<groupId>eu.dnetlib</groupId>
85
			<artifactId>dnet-objectstore-rmi</artifactId>
86
			<version>[2.0.0,3.0.0)</version>
87
		</dependency>
88
		<dependency>
89
			<groupId>eu.dnetlib</groupId>
90
			<artifactId>dnet-data-transformation-service-rmi</artifactId>
91
			<version>[1.0.0,2.0.0)</version>
92
		</dependency>
93
		<dependency>
94
			<groupId>eu.dnetlib</groupId>
95
			<artifactId>dnet-data-provision-rmi</artifactId>
96
			<version>[1.0.0,2.0.0)</version>
97
		</dependency>
98
		<dependency>
99
			<groupId>eu.dnetlib</groupId>
100
			<artifactId>dnet-runtime</artifactId>
101
			<version>[1.0.0,2.0.0)</version>
102
		</dependency>
103
		<dependency>
104
			<groupId>javax.mail</groupId>
105
			<artifactId>mail</artifactId>
106
			<version>1.4</version>
107
		</dependency>
108
		<dependency>
109
			<groupId>org.codehaus.groovy</groupId>
110
			<artifactId>groovy-all</artifactId>
111
			<version>2.1.6</version>
112
		</dependency>
113
		<dependency>
114
			<groupId>junit</groupId>
115
			<artifactId>junit</artifactId>
116
			<version>${junit.version}</version>
117
			<scope>test</scope>
118
		</dependency>
119
		<dependency>
120
			<groupId>joda-time</groupId>
121
			<artifactId>joda-time</artifactId>
122
			<version>2.3</version>
123
		</dependency>
124
	</dependencies>
125

  
126
	<properties>
127
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
128
	</properties>
129

  
130
</project>
modules/dnet-msro-service/tags/dnet-msro-service-3.0.1/src/main/java/eu/dnetlib/msro/workflows/nodes/repobye/DeleteObjectStoreJobNode.java
1
package eu.dnetlib.msro.workflows.nodes.repobye;
2

  
3
import org.apache.commons.logging.Log;
4
import org.apache.commons.logging.LogFactory;
5

  
6
import com.googlecode.sarasvati.NodeToken;
7

  
8
import eu.dnetlib.data.objectstore.rmi.ObjectStoreService;
9
import eu.dnetlib.enabling.tools.blackboard.BlackboardJob;
10
import eu.dnetlib.msro.workflows.nodes.BlackboardJobNode;
11

  
12
public class DeleteObjectStoreJobNode extends BlackboardJobNode {
13

  
14
	private static final Log log = LogFactory.getLog(DeleteObjectStoreJobNode.class);
15

  
16
	private String objectstoreId;
17

  
18
	@Override
19
	protected String obtainServiceId(final NodeToken token) {
20
		return getServiceLocator().getServiceId(ObjectStoreService.class);
21
	}
22

  
23
	@Override
24
	protected void prepareJob(final BlackboardJob job, final NodeToken token) throws Exception {
25
		log.info("preparing blackboard job: delete of mdstore " + getObjectstoreId());
26
		job.setAction("DELETE");
27
		job.getParameters().put("obsID", getObjectstoreId());
28
	}
29

  
30
	/**
31
	 * @return the objectstoreId
32
	 */
33
	public String getObjectstoreId() {
34
		return objectstoreId;
35
	}
36

  
37
	/**
38
	 * @param objectstoreId
39
	 *            the objectstoreId to set
40
	 */
41
	public void setObjectstoreId(final String objectstoreId) {
42
		this.objectstoreId = objectstoreId;
43
	}
44

  
45
}
modules/dnet-msro-service/tags/dnet-msro-service-3.0.1/src/main/java/eu/dnetlib/msro/notification/EmailDispatcher.java
1
package eu.dnetlib.msro.notification;
2

  
3
import java.util.Arrays;
4
import java.util.Date;
5
import java.util.Map;
6
import java.util.Properties;
7
import java.util.Set;
8
import java.util.concurrent.BlockingQueue;
9
import java.util.concurrent.LinkedBlockingQueue;
10

  
11
import javax.mail.Authenticator;
12
import javax.mail.Message;
13
import javax.mail.MessagingException;
14
import javax.mail.PasswordAuthentication;
15
import javax.mail.Session;
16
import javax.mail.Transport;
17
import javax.mail.internet.InternetAddress;
18
import javax.mail.internet.MimeMessage;
19

  
20
import org.antlr.stringtemplate.StringTemplate;
21
import org.apache.commons.io.IOUtils;
22
import org.apache.commons.logging.Log;
23
import org.apache.commons.logging.LogFactory;
24
import org.springframework.beans.factory.annotation.Required;
25

  
26
import com.google.common.base.Splitter;
27
import com.google.common.collect.Maps;
28

  
29
public class EmailDispatcher {
30

  
31
	private String from;
32
	private String fromName;
33
	private String cc;
34
	private String smtpHost;
35
	private int smtpPort = 587;
36
	private String smtpUser;
37
	private String smtpPassword;
38
	private String baseUrl;
39
	private String infrastructure;
40

  
41
	private static final Log log = LogFactory.getLog(EmailDispatcher.class);
42

  
43
	private final BlockingQueue<Message> queue = new LinkedBlockingQueue<Message>();
44

  
45
	public StringTemplate prepareMessage(final String template, final Map<String, Object> tmplParams) {
46
		final StringTemplate st = new StringTemplate(template);
47
		st.setAttributes(tmplParams);
48
		st.setAttribute("baseUrl", baseUrl);
49
		st.setAttribute("infrastructure", infrastructure);
50
		return st;
51
	}
52

  
53
	public void sendMail(final Set<String> to, final String subject, final String template, final Map<String, Object> tmplParams) {
54
		try {
55
			final StringTemplate st = prepareMessage(template, tmplParams);
56

  
57
			final Session session = Session.getInstance(obtainProperties(), obtainAuthenticator());
58

  
59
			final MimeMessage message = new MimeMessage(session);
60
			message.setFrom(new InternetAddress(from, fromName));
61
			message.setSubject(subject);
62
			message.setContent(st.toString(), "text/html; charset=utf-8");
63
			message.setSentDate(new Date());
64

  
65
			for (String s : to) {
66
				message.addRecipient(Message.RecipientType.TO, new InternetAddress(s));
67
			}
68
			if ((cc != null) && !cc.isEmpty()) {
69
				for (String aCC : Splitter.on(",").omitEmptyStrings().trimResults().split(getCc())) {
70
					message.addRecipient(Message.RecipientType.CC, new InternetAddress(aCC));
71
				}
72
			}
73

  
74
			queue.add(message);
75

  
76
			log.info("Mail to " + Arrays.toString(to.toArray()) + " in queue");
77
		} catch (Exception e) {
78
			log.error("Error sending mail", e);
79
		}
80
	}
81

  
82
	public void processMailQueue() {
83
		while (true) {
84
			final Message message = queue.poll();
85
			if (message == null) return;
86
			else {
87
				try {
88
					log.info("Sending mail...");
89
					Transport.send(message);
90
					log.info("...sent");
91
				} catch (MessagingException e) {
92
					log.error("Error sending email", e);
93
					queue.add(message);
94
					return;
95
				}
96
			}
97
		}
98
	}
99

  
100
	private void sendWfStatusMail(final boolean success,
101
			final Set<String> to,
102
			final String wfId,
103
			final String procId,
104
			final String wfName,
105
			final Map<String, String> pendingWfs,
106
			final Map<String, String> responses,
107
			final String error) {
108
		try {
109
			final Map<String, Object> map = Maps.newHashMap();
110
			map.put("wfId", wfId);
111
			map.put("wfName", wfName);
112
			map.put("procId", procId);
113
			if ((pendingWfs != null) && !pendingWfs.isEmpty()) {
114
				map.put("pendingWfs", pendingWfs);
115
			}
116
			if ((responses != null) && !responses.isEmpty()) {
117
				map.put("responses", responses);
118
			}
119
			if ((error != null) && !error.isEmpty()) {
120
				map.put("error", error);
121
			}
122

  
123
			String subject = success ? "[D-NET WORKFLOW] -- SUCCESS: " : "WF FAILURE: ";
124
			subject += wfName + " on " + infrastructure;
125
			final String tmplName = success ? "wf_success.mail.st" : "wf_failed.mail.st";
126
			final String template = IOUtils.toString(getClass().getResourceAsStream("/eu/dnetlib/msro/mail/" + tmplName));
127

  
128
			sendMail(to, subject, template, map);
129
		} catch (Exception e) {
130
			log.error("Error generating success-mail", e);
131
		}
132
	}
133

  
134
	public void sendSuccessMail(final Set<String> to,
135
			final String wfId,
136
			final String procId,
137
			final String wfName,
138
			final Map<String, String> pendingWfs,
139
			final Map<String, String> responses) {
140
		sendWfStatusMail(true, to, wfId, procId, wfName, pendingWfs, responses, "");
141
	}
142

  
143
	public void sendFailedMail(final Set<String> to,
144
			final String wfId,
145
			final String procId,
146
			final String wfName,
147
			final Map<String, String> pendingWfs,
148
			final Map<String, String> responses,
149
			final String error) {
150
		sendWfStatusMail(false, to, wfId, procId, wfName, pendingWfs, responses, error);
151
	}
152

  
153
	private Properties obtainProperties() {
154
		final Properties props = new Properties();
155
		props.put("mail.transport.protocol", "smtp");
156
		props.put("mail.smtp.host", smtpHost);
157
		props.put("mail.smtp.port", smtpPort);
158
		props.put("mail.smtp.auth", Boolean.toString((smtpUser != null) && !smtpUser.isEmpty()));
159
		return props;
160
	}
161

  
162
	private Authenticator obtainAuthenticator() {
163
		if ((smtpUser == null) || smtpUser.isEmpty()) return null;
164

  
165
		return new Authenticator() {
166

  
167
			private final PasswordAuthentication authentication = new PasswordAuthentication(smtpUser, smtpPassword);
168

  
169
			@Override
170
			protected PasswordAuthentication getPasswordAuthentication() {
171
				return authentication;
172
			}
173

  
174
		};
175
	}
176

  
177
	public String getFrom() {
178
		return from;
179
	}
180

  
181
	@Required
182
	public void setFrom(final String from) {
183
		this.from = from;
184
	}
185

  
186
	public String getFromName() {
187
		return fromName;
188
	}
189

  
190
	@Required
191
	public void setFromName(final String fromName) {
192
		this.fromName = fromName;
193
	}
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff