Project

General

Profile

« Previous | Next » 

Revision 32977

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

View differences:

modules/dnet-msro-service/tags/dnet-msro-service-2.1.1/src/main/java/eu/dnetlib/msro/workflows/nodes/collect/CollectRecordsJobNode.java
1
package eu.dnetlib.msro.workflows.nodes.collect;
2

  
3
import java.io.StringReader;
4

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

  
8
import org.dom4j.Document;
9
import org.dom4j.Node;
10
import org.dom4j.io.SAXReader;
11

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

  
15
import eu.dnetlib.data.collector.rmi.CollectorService;
16
import eu.dnetlib.data.collector.rmi.InterfaceDescriptor;
17
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
18
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
19
import eu.dnetlib.msro.workflows.nodes.SimpleJobNode;
20

  
21
public class CollectRecordsJobNode extends SimpleJobNode {
22

  
23
	@Resource
24
	private UniqueServiceLocator serviceLocator;
25

  
26
	private String datasourceId;
27
	private String datasourceInterface;
28
	private String eprParam;
29

  
30
	@Override
31
	protected String execute(final NodeToken token) throws Exception {
32
		final String profile = serviceLocator.getService(ISLookUpService.class).getResourceProfile(datasourceId);
33
		final Document doc = new SAXReader().read(new StringReader(profile));
34
		final Node ifcNode = doc.selectSingleNode("//INTERFACE[@id='" + datasourceInterface + "']");
35

  
36
		final InterfaceDescriptor interfaceDescriptor = InterfaceDescriptor.newInstance(ifcNode);
37

  
38
		final W3CEndpointReference epr = serviceLocator.getService(CollectorService.class).collect(interfaceDescriptor);
39

  
40
		token.getEnv().setAttribute(getEprParam(), epr.toString());
41

  
42
		return Arc.DEFAULT_ARC;
43
	}
44

  
45
	public String getDatasourceId() {
46
		return datasourceId;
47
	}
48

  
49
	public void setDatasourceId(final String datasourceId) {
50
		this.datasourceId = datasourceId;
51
	}
52

  
53
	public String getDatasourceInterface() {
54
		return datasourceInterface;
55
	}
56

  
57
	public void setDatasourceInterface(final String datasourceInterface) {
58
		this.datasourceInterface = datasourceInterface;
59
	}
60

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

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

  
69
}
modules/dnet-msro-service/tags/dnet-msro-service-2.1.1/src/main/java/eu/dnetlib/msro/workflows/nodes/info/RemoveApiExtraFieldsJobNode.java
1
package eu.dnetlib.msro.workflows.nodes.info;
2

  
3
import java.io.StringReader;
4
import java.util.Map;
5
import java.util.Set;
6

  
7
import javax.annotation.Resource;
8

  
9
import org.apache.cxf.common.util.StringUtils;
10
import org.dom4j.Document;
11
import org.dom4j.Node;
12
import org.dom4j.io.SAXReader;
13
import org.springframework.beans.factory.annotation.Required;
14

  
15
import com.google.common.base.Splitter;
16
import com.google.common.collect.Maps;
17
import com.google.common.collect.Sets;
18
import com.googlecode.sarasvati.Arc;
19
import com.googlecode.sarasvati.NodeToken;
20

  
21
import eu.dnetlib.datasource.common.utils.DatasourceUpdater;
22
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
23
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
24
import eu.dnetlib.msro.workflows.nodes.SimpleJobNode;
25

  
26
public class RemoveApiExtraFieldsJobNode extends SimpleJobNode {
27

  
28
	private String datasourceId;
29
	private String datasourceInterface;
30
	private String fields;
31

  
32
	@Resource
33
	private UniqueServiceLocator serviceLocator;
34

  
35
	private DatasourceUpdater datasourceUpdater;
36

  
37
	@Override
38
	protected String execute(final NodeToken token) throws Exception {
39
		if (!StringUtils.isEmpty(fields)) {
40
			final Set<String> invalidFields = Sets.newHashSet(Splitter.on(",").omitEmptyStrings().trimResults().split(fields.toLowerCase()));
41
			final Map<String, String> map = calculateValidExtraFields(datasourceId, datasourceInterface, invalidFields);
42
			datasourceUpdater.updateApiExtraFields(datasourceId, datasourceInterface, map);
43
		}
44
		return Arc.DEFAULT_ARC;
45
	}
46

  
47
	private Map<String, String> calculateValidExtraFields(final String repoId, final String ifaceId, final Set<String> invalidFields) throws Exception {
48
		final Map<String, String> res = Maps.newHashMap();
49

  
50
		final String profile = serviceLocator.getService(ISLookUpService.class).getResourceProfile(repoId);
51

  
52
		final SAXReader reader = new SAXReader();
53
		final Document doc = reader.read(new StringReader(profile));
54

  
55
		final Node ifcNode = doc.selectSingleNode("//INTERFACE[@id='" + ifaceId + "']");
56
		if (ifcNode != null) {
57
			for (Object o : ifcNode.selectNodes("./INTERFACE_EXTRA_FIELD")) {
58
				final String name = ((Node) o).valueOf("@name");
59
				if (!invalidFields.contains(name.toLowerCase())) {
60
					res.put(name, ((Node) o).getText());
61
				}
62
			}
63
		}
64

  
65
		return res;
66
	}
67

  
68
	public String getFields() {
69
		return fields;
70
	}
71

  
72
	public void setFields(final String fields) {
73
		this.fields = fields;
74
	}
75

  
76
	public String getDatasourceId() {
77
		return datasourceId;
78
	}
79

  
80
	public void setDatasourceId(final String datasourceId) {
81
		this.datasourceId = datasourceId;
82
	}
83

  
84
	public String getDatasourceInterface() {
85
		return datasourceInterface;
86
	}
87

  
88
	public void setDatasourceInterface(final String datasourceInterface) {
89
		this.datasourceInterface = datasourceInterface;
90
	}
91

  
92
	public DatasourceUpdater getDatasourceUpdater() {
93
		return datasourceUpdater;
94
	}
95

  
96
	@Required
97
	public void setDatasourceUpdater(final DatasourceUpdater datasourceUpdater) {
98
		this.datasourceUpdater = datasourceUpdater;
99
	}
100
}
modules/dnet-msro-service/tags/dnet-msro-service-2.1.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>2.1.1</version>
14
	<scm>
15
		<developerConnection>scm:svn:https://svn.driver.research-infrastructures.eu/driver/dnet40/modules/dnet-msro-service/tags/dnet-msro-service-2.1.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.0.0,2.0.0)</version>
47
		</dependency>
48

  
49
		<dependency>
50
			<groupId>eu.dnetlib</groupId>
51
			<artifactId>cnr-blackboard-common</artifactId>
52
			<version>[2.1.0,3.0.0)</version>
53
		</dependency>
54
		<dependency>
55
			<groupId>eu.dnetlib</groupId>
56
			<artifactId>dnet-mongo-logging</artifactId>
57
			<version>[1.0.0,2.0.0)</version>
58
		</dependency>
59
		<dependency>
60
			<groupId>eu.dnetlib</groupId>
61
			<artifactId>dnet-datasource-common</artifactId>
62
			<version>[3.0.0,4.0.0)</version>
63
		</dependency>
64
		<dependency>
65
			<groupId>com.googlecode</groupId>
66
			<artifactId>sarasvati</artifactId>
67
			<version>1.0.3</version>
68
		</dependency>
69
		<dependency>
70
			<groupId>com.googlecode</groupId>
71
			<artifactId>sarasvati-visual</artifactId>
72
			<version>1.0.3</version>
73
		</dependency>
74
		<dependency>
75
			<groupId>eu.dnetlib</groupId>
76
			<artifactId>dnet-modular-collector-service-rmi</artifactId>
77
			<version>[1.2.0,2.0.0)</version>
78
		</dependency>
79
		<dependency>
80
			<groupId>eu.dnetlib</groupId>
81
			<artifactId>cnr-enabling-database-api</artifactId>
82
			<version>[1.0.0,2.0.0)</version>
83
		</dependency>
84
		<dependency>
85
			<groupId>eu.dnetlib</groupId>
86
			<artifactId>dnet-objectstore-rmi</artifactId>
87
			<version>[2.0.0,3.0.0)</version>
88
		</dependency>
89
		<dependency>
90
			<groupId>eu.dnetlib</groupId>
91
			<artifactId>dnet-data-transformation-service-rmi</artifactId>
92
			<version>[1.0.0,2.0.0)</version>
93
		</dependency>
94
		<dependency>
95
			<groupId>eu.dnetlib</groupId>
96
			<artifactId>dnet-data-provision-rmi</artifactId>
97
			<version>[1.0.0,2.0.0)</version>
98
		</dependency>
99
		<dependency>
100
			<groupId>eu.dnetlib</groupId>
101
			<artifactId>dnet-runtime</artifactId>
102
			<version>[1.0.0,2.0.0)</version>
103
		</dependency>
104
		<dependency>
105
			<groupId>javax.mail</groupId>
106
			<artifactId>mail</artifactId>
107
			<version>1.4</version>
108
		</dependency>
109
		<dependency>
110
			<groupId>org.codehaus.groovy</groupId>
111
			<artifactId>groovy-all</artifactId>
112
			<version>2.1.6</version>
113
		</dependency>
114
		<dependency>
115
			<groupId>junit</groupId>
116
			<artifactId>junit</artifactId>
117
			<version>${junit.version}</version>
118
			<scope>test</scope>
119
		</dependency>
120
		<dependency>
121
			<groupId>joda-time</groupId>
122
			<artifactId>joda-time</artifactId>
123
			<version>2.3</version>
124
		</dependency>
125
	</dependencies>
126

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

  
131
</project>
modules/dnet-msro-service/tags/dnet-msro-service-2.1.1/src/main/java/eu/dnetlib/msro/workflows/nodes/SuccessFailureNode.java
1
package eu.dnetlib.msro.workflows.nodes;
2

  
3
import java.util.Map;
4

  
5
import javax.annotation.Resource;
6

  
7
import org.antlr.stringtemplate.StringTemplate;
8
import org.apache.commons.io.IOUtils;
9
import org.apache.commons.lang.StringEscapeUtils;
10
import org.apache.commons.lang.StringUtils;
11
import org.apache.commons.logging.Log;
12
import org.apache.commons.logging.LogFactory;
13
import org.springframework.beans.factory.annotation.Required;
14

  
15
import com.google.common.collect.Maps;
16
import com.googlecode.sarasvati.Arc;
17
import com.googlecode.sarasvati.NodeToken;
18

  
19
import eu.dnetlib.common.logging.DnetLogger;
20
import eu.dnetlib.common.logging.LogMessage;
21
import eu.dnetlib.enabling.is.registry.rmi.ISRegistryService;
22
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
23
import eu.dnetlib.miscutils.datetime.DateUtils;
24
import eu.dnetlib.msro.workflows.util.WorkflowsConstants;
25

  
26
/**
27
 * The success node sets the "isCompletedSuccessfully" env var.
28
 * 
29
 */
30
public class SuccessFailureNode extends SimpleJobNode {
31

  
32
	/**
33
	 * is completed successfully.
34
	 */
35
	private boolean success;
36

  
37
	@Resource
38
	private UniqueServiceLocator serviceLocator;
39

  
40
	@Resource(name = "msroWorkflowLogger")
41
	private DnetLogger dnetLogger;
42

  
43
	private static final Log log = LogFactory.getLog(SuccessFailureNode.class);
44

  
45
	@Override
46
	protected String execute(final NodeToken token) {
47
		final String profileId = token.getFullEnv().getAttribute(WorkflowsConstants.SYSTEM_WF_PROFILE_ID).trim();
48

  
49
		final long now = DateUtils.now();
50
		final String date = DateUtils.calculate_ISO8601(now);
51

  
52
		token.getProcess().getEnv().setAttribute(WorkflowsConstants.SYSTEM_END_DATE, now);
53
		token.getProcess().getEnv().setAttribute(WorkflowsConstants.SYSTEM_END_HUMAN_DATE, date);
54

  
55
		final Map<String, String> params = mergeEnvAttributes(token);
56
		final LogMessage logMessage = dnetLogger.newLogMessage().addDetails(params);
57

  
58
		try {
59
			final String template = IOUtils.toString(getClass().getResourceAsStream("/eu/dnetlib/msro/workflows/templates/workflow_status.xml.st"));
60
			final StringTemplate st = new StringTemplate(template);
61
			st.setAttribute("procId", StringEscapeUtils.escapeXml(params.get(WorkflowsConstants.SYSTEM_WF_PROCESS_ID)));
62
			st.setAttribute("date", StringEscapeUtils.escapeXml(date));
63
			st.setAttribute("params", filterOutputParams(params));
64
			if (!isSuccess()) {
65
				st.setAttribute("error", StringEscapeUtils.escapeXml(params.get(WorkflowsConstants.SYSTEM_ERROR)));
66
			}
67

  
68
			serviceLocator.getService(ISRegistryService.class).updateProfileNode(profileId, "//STATUS", st.toString());
69

  
70
			token.getProcess().getEnv().setAttribute(WorkflowsConstants.SYSTEM_COMPLETED_SUCCESSFULLY, isSuccess());
71

  
72
			logMessage.addDetail(WorkflowsConstants.SYSTEM_COMPLETED_SUCCESSFULLY, Boolean.toString(isSuccess()));
73
		} catch (Exception e) {
74
			log.error("Error updating workflow profile: " + profileId, e);
75
			token.getProcess().getEnv().setAttribute(WorkflowsConstants.SYSTEM_COMPLETED_SUCCESSFULLY, false);
76
			logMessage.addDetail(WorkflowsConstants.SYSTEM_COMPLETED_SUCCESSFULLY, Boolean.toString(false));
77
		}
78

  
79
		logMessage.flush();
80

  
81
		return Arc.DEFAULT_ARC;
82
	}
83

  
84
	private Map<String, String> filterOutputParams(final Map<String, String> map) {
85
		final Map<String, String> res = Maps.newHashMap();
86

  
87
		if (map != null) {
88
			for (String k : map.keySet()) {
89
				if (!StringUtils.isBlank(k) && (k.startsWith(WorkflowsConstants.DATAPROVIDER_PREFIX) || k.startsWith(WorkflowsConstants.MAIN_LOG_PREFIX))) {
90
					final String key = StringEscapeUtils.escapeXml(k);
91
					final String v = map.get(k);
92
					res.put(key, v != null ? StringEscapeUtils.escapeXml(v) : "null");
93
				}
94
			}
95
		}
96

  
97
		return res;
98
	}
99

  
100
	private Map<String, String> mergeEnvAttributes(final NodeToken token) {
101
		final Map<String, String> map = Maps.newHashMap();
102

  
103
		for (String s : token.getEnv().getAttributeNames()) {
104
			map.put(s, token.getEnv().getAttribute(s));
105
		}
106
		for (String s : token.getFullEnv().getAttributeNames()) {
107
			map.put(s, token.getFullEnv().getAttribute(s));
108
		}
109
		return map;
110
	}
111

  
112
	public boolean isSuccess() {
113
		return success;
114
	}
115

  
116
	@Required
117
	public void setSuccess(final boolean success) {
118
		this.success = success;
119
	}
120

  
121
}
modules/dnet-msro-service/tags/dnet-msro-service-2.1.1/src/main/java/eu/dnetlib/msro/workflows/nodes/transform/MdBuilderJobNode.java
1
package eu.dnetlib.msro.workflows.nodes.transform;
2

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

  
6
import javax.xml.ws.wsaddressing.W3CEndpointReference;
7

  
8
import org.antlr.stringtemplate.StringTemplate;
9
import org.apache.commons.io.IOUtils;
10
import org.springframework.beans.factory.annotation.Required;
11
import org.springframework.core.io.Resource;
12

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

  
16
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpDocumentNotFoundException;
17
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;
18
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
19
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
20
import eu.dnetlib.enabling.resultset.XSLTMappedResultSetFactory;
21
import eu.dnetlib.enabling.resultset.client.utils.EPRUtils;
22
import eu.dnetlib.msro.rmi.MSROException;
23
import eu.dnetlib.msro.workflows.nodes.SimpleJobNode;
24

  
25
public class MdBuilderJobNode extends SimpleJobNode {
26

  
27
	private Resource mdBuilderTemplateXslt;
28

  
29
	private String inputEprParam;
30
	private String outputEprParam;
31
	private String datasourceId;
32
	private String datasourceInterface;
33

  
34
	private XSLTMappedResultSetFactory xsltMappedResultSetFactory;
35

  
36
	@javax.annotation.Resource
37
	private UniqueServiceLocator serviceLocator;
38

  
39
	@Override
40
	protected String execute(final NodeToken token) throws MSROException {
41
		final String inputEpr = token.getEnv().getAttribute(inputEprParam);
42

  
43
		if (inputEpr == null || inputEpr.isEmpty()) { throw new MSROException("InputEprParam (" + inputEprParam + ") not found in ENV"); }
44

  
45
		String xQuery = "for $x in collection('/db/DRIVER/RepositoryServiceResources/RepositoryServiceResourceType') "
46
				+ "return $x//INTERFACE[@id='{interfaceId}']/INTERFACE_EXTRA_FIELD[@name='metadata_identifier_path']/string()";
47
		xQuery = xQuery.replace("{interfaceId}", datasourceInterface);
48

  
49
		final ISLookUpService lookupService = serviceLocator.getService(ISLookUpService.class);
50

  
51
		try {
52
			final StringTemplate st = new StringTemplate(IOUtils.toString(getMdBuilderTemplateXslt().getInputStream()));
53
			st.setAttribute("xpath", lookupService.getResourceProfileByQuery(xQuery));
54
			st.setAttribute("datasourceId", datasourceId);
55

  
56
			/*
57
			 * If namespacePrefix has been already pushed to env by some custom JobNode e.g. ObtainOpenaireDataSourceParamsJobNode then push
58
			 * it to ST. Else: a) try to get it from EXTRAFIELDS of the datasource b) try to get it from DATASOURCE_ORIGINAL_ID of the
59
			 * datasource c) if any of the is present, then push to ST the datasourceId
60
			 */
61
			if (token.getEnv().hasAttribute("namespacePrefix")) {
62
				st.setAttribute("namespacePrefix", token.getEnv().getAttribute("namespacePrefix"));
63
			} else {
64
				List<String> namespacePrefix;
65
				xQuery = "/*[.//RESOURCE_IDENTIFIER/@value='" + datasourceId + "']//EXTRA_FIELDS/FIELD/value[../key='NamespacePrefix']/string()";
66
				namespacePrefix = lookupService.quickSearchProfile(xQuery);
67
				if (namespacePrefix.size() != 0) {
68
					st.setAttribute("namespacePrefix", namespacePrefix.get(0));
69
				} else {
70
					xQuery = "/*[.//RESOURCE_IDENTIFIER/@value='" + datasourceId + "']//DATASOURCE_ORIGINAL_ID/string()";
71
					namespacePrefix = lookupService.quickSearchProfile(xQuery);
72
					if (namespacePrefix.size() != 0) {
73
						st.setAttribute("namespacePrefix", namespacePrefix.get(0));
74
					} else {
75
						st.setAttribute("namespacePrefix", datasourceId);
76
					}
77
				}
78
			}
79
			final W3CEndpointReference epr = xsltMappedResultSetFactory.createMappedResultSet(new EPRUtils().getEpr(inputEpr), st.toString());
80

  
81
			token.getEnv().setAttribute(outputEprParam, epr.toString());
82

  
83
			return Arc.DEFAULT_ARC;
84
		} catch (ISLookUpDocumentNotFoundException e) {
85
			throw new MSROException("Missing metadata_identifier_path extra field for ds: " + datasourceId, e);
86
		} catch (ISLookUpException e) {
87
			throw new MSROException("Error searching metadata_identifier_path extra field for ds: " + datasourceId, e);
88
		} catch (IOException e) {
89
			throw new MSROException("Error parsing template: " + getMdBuilderTemplateXslt().getFilename(), e);
90
		}
91
	}
92

  
93
	public String getInputEprParam() {
94
		return inputEprParam;
95
	}
96

  
97
	public void setInputEprParam(final String inputEprParam) {
98
		this.inputEprParam = inputEprParam;
99
	}
100

  
101
	public String getOutputEprParam() {
102
		return outputEprParam;
103
	}
104

  
105
	public void setOutputEprParam(final String outputEprParam) {
106
		this.outputEprParam = outputEprParam;
107
	}
108

  
109
	public XSLTMappedResultSetFactory getXsltMappedResultSetFactory() {
110
		return xsltMappedResultSetFactory;
111
	}
112

  
113
	public String getDatasourceId() {
114
		return datasourceId;
115
	}
116

  
117
	public void setDatasourceId(final String datasourceId) {
118
		this.datasourceId = datasourceId;
119
	}
120

  
121
	public String getDatasourceInterface() {
122
		return datasourceInterface;
123
	}
124

  
125
	public void setDatasourceInterface(final String datasourceInterface) {
126
		this.datasourceInterface = datasourceInterface;
127
	}
128

  
129
	@Required
130
	public void setXsltMappedResultSetFactory(final XSLTMappedResultSetFactory xsltMappedResultSetFactory) {
131
		this.xsltMappedResultSetFactory = xsltMappedResultSetFactory;
132
	}
133

  
134
	public Resource getMdBuilderTemplateXslt() {
135
		return mdBuilderTemplateXslt;
136
	}
137

  
138
	@Required
139
	public void setMdBuilderTemplateXslt(final Resource mdBuilderTemplateXslt) {
140
		this.mdBuilderTemplateXslt = mdBuilderTemplateXslt;
141
	}
142

  
143
}
modules/dnet-msro-service/tags/dnet-msro-service-2.1.1/src/main/java/eu/dnetlib/msro/workflows/nodes/transform/GroovyUnaryFunction.java
1
package eu.dnetlib.msro.workflows.nodes.transform;
2

  
3
import java.util.Map;
4

  
5
import eu.dnetlib.miscutils.functional.UnaryFunction;
6

  
7
public abstract class GroovyUnaryFunction implements UnaryFunction<String, String> {
8

  
9
	private Map<String, String> params;
10

  
11
	@Override
12
	abstract public String evaluate(String input);
13

  
14
	public Map<String, String> getParams() {
15
		return params;
16
	}
17

  
18
	public void setParams(final Map<String, String> params) {
19
		this.params = params;
20
	}
21

  
22
}
modules/dnet-msro-service/tags/dnet-msro-service-2.1.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 ? "Workflow '" + wfName + "' has been completed successfully" : "Workflow '" + wfName + "' is failed";
124
			subject += " 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
	}
194

  
195
	public String getCc() {
196
		return cc;
197
	}
198

  
199
	@Required
200
	public void setCc(final String cc) {
201
		this.cc = cc;
202
	}
203

  
204
	public String getSmtpHost() {
205
		return smtpHost;
206
	}
207

  
208
	@Required
209
	public void setSmtpHost(final String smtpHost) {
210
		this.smtpHost = smtpHost;
211
	}
212

  
213
	public int getSmtpPort() {
214
		return smtpPort;
215
	}
216

  
217
	public void setSmtpPort(final int smtpPort) {
218
		this.smtpPort = smtpPort;
219
	}
220

  
221
	public String getSmtpUser() {
222
		return smtpUser;
223
	}
224

  
225
	public void setSmtpUser(final String smtpUser) {
226
		this.smtpUser = smtpUser;
227
	}
228

  
229
	public String getSmtpPassword() {
230
		return smtpPassword;
231
	}
232

  
233
	public void setSmtpPassword(final String smtpPassword) {
234
		this.smtpPassword = smtpPassword;
235
	}
236

  
237
	public String getBaseUrl() {
238
		return baseUrl;
239
	}
240

  
241
	@Required
242
	public void setBaseUrl(final String baseUrl) {
243
		this.baseUrl = baseUrl;
244
	}
245

  
246
	public String getInfrastructure() {
247
		return infrastructure;
248
	}
249

  
250
	@Required
251
	public void setInfrastructure(final String infrastructure) {
252
		this.infrastructure = infrastructure;
253
	}
254

  
255
}
modules/dnet-msro-service/tags/dnet-msro-service-2.1.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
			Document doc = builder.parse(new ByteArrayInputStream(input.getBytes()));
77
			XPathFactory xPathFactory = XPathFactory.newInstance();
78
			XPath myXpath = xPathFactory.newXPath();
79
			XPathExpression expression = myXpath.compile(xpathURL);
80
			Object values = expression.evaluate(doc, XPathConstants.NODESET);
81
			di.setUrl(getNodes((NodeList) values));
82
			di.setOriginalUrl(getNodes((NodeList) values));
83

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

  
107
	}
108

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

  
126
	/**
127
	 * Gets the xpath metadata id.
128
	 *
129
	 * @return the xpathMetadataID
130
	 */
131
	public String getXpathMetadataID() {
132
		return xpathMetadataID;
133
	}
134

  
135
	/**
136
	 * Sets the xpath metadata id.
137
	 *
138
	 * @param xpathMetadataID
139
	 *            the xpathMetadataID to set
140
	 */
141
	public void setXpathMetadataID(final String xpathMetadataID) {
142
		this.xpathMetadataID = xpathMetadataID;
143
	}
144

  
145
	/**
146
	 * Gets the xpath url.
147
	 *
148
	 * @return the xpath url
149
	 */
150
	public String getXpathURL() {
151
		return xpathURL;
152
	}
153

  
154
	/**
155
	 * Sets the xpath url.
156
	 *
157
	 * @param xpathURL
158
	 *            the new xpath url
159
	 */
160
	public void setXpathURL(final String xpathURL) {
161
		this.xpathURL = xpathURL;
162
	}
163

  
164
	/**
165
	 * Gets the xpath open access.
166
	 *
167
	 * @return the xpath open access
168
	 */
169
	public String getXpathOpenAccess() {
170
		return xpathOpenAccess;
171
	}
172

  
173
	/**
174
	 * Sets the xpath open access.
175
	 *
176
	 * @param xpathOpenAccess
177
	 *            the new xpath open access
178
	 */
179
	public void setXpathOpenAccess(final String xpathOpenAccess) {
180
		this.xpathOpenAccess = xpathOpenAccess;
181
	}
182

  
183
	/**
184
	 * Gets the xpath embargo date.
185
	 *
186
	 * @return the xpath embargo date
187
	 */
188
	public String getXpathEmbargoDate() {
189
		return xpathEmbargoDate;
190
	}
191

  
192
	/**
193
	 * Sets the xpath embargo date.
194
	 *
195
	 * @param xpathEmbargoDate
196
	 *            the new xpath embargo date
197
	 */
198
	public void setXpathEmbargoDate(final String xpathEmbargoDate) {
199
		this.xpathEmbargoDate = xpathEmbargoDate;
200
	}
201

  
202
}
modules/dnet-msro-service/tags/dnet-msro-service-2.1.1/src/main/java/eu/dnetlib/msro/notification/WfDependencyLauncherNotificationHandler.java
1
package eu.dnetlib.msro.notification;
2

  
3
import java.io.StringReader;
4
import java.util.Map;
5
import java.util.Set;
6

  
7
import javax.annotation.Resource;
8

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

  
16
import com.google.common.base.Splitter;
17
import com.google.common.collect.Maps;
18
import com.google.common.collect.Sets;
19

  
20
import eu.dnetlib.enabling.actions.AbstractSubscriptionAction;
21
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;
22
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
23
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
24
import eu.dnetlib.msro.workflows.sarasvati.loader.WorkflowExecutor;
25

  
26
public class WfDependencyLauncherNotificationHandler extends AbstractSubscriptionAction {
27

  
28
	@Resource
29
	private UniqueServiceLocator serviceLocator;
30

  
31
	@Resource
32
	private WorkflowExecutor workflowExecutor;
33

  
34
	@Resource
35
	private EmailDispatcher emailDispatcher;
36

  
37
	private static final Log log = LogFactory.getLog(WorkflowExecutor.class);
38

  
39
	@Override
40
	public void notified(final String subscrId, final String topic, final String rsId, final String profile) {
41

  
42
		final SAXReader reader = new SAXReader();
43
		try {
44
			final Document doc = reader.read(new StringReader(profile));
45

  
46
			final Set<String> emails = calculateEmails(rsId);
47
			final String procId = doc.valueOf("//LAST_EXECUTION_ID");
48
			final String wfName = doc.valueOf("//WORKFLOW_NAME");
49
			final boolean success = doc.valueOf("//LAST_EXECUTION_STATUS").equals("SUCCESS");
50
			final Map<String, String> responses = Maps.newHashMap();
51

  
52
			for (Object o : doc.selectNodes("//LAST_EXECUTION_OUTPUT")) {
53
				Node n = (Node) o;
54
				responses.put(n.valueOf("@name"), n.getText());
55
			}
56

  
57
			if (!success) {
58
				log.info("Last execution of " + rsId + " failed, dependencies NOT STARTED");
59
			}
60

  
61
			final String query = "for $x in collection('/db/DRIVER/MetaWorkflowDSResources/MetaWorkflowDSResourceType')//WORKFLOW[@id='" + rsId
62
					+ "']/WORKFLOW let $y := /RESOURCE_PROFILE[.//RESOURCE_IDENTIFIER/@value = $x/@id] "
63
					+ "where $y//CONFIGURATION/@start != 'disabled' return concat ($x/@id , ' @@@ ', $x/@name , ' @@@ ', $y//CONFIGURATION/@start)";
64

  
65
			try {
66
				final Map<String, String> pendingWfs = Maps.newHashMap();
67

  
68
				for (String s : serviceLocator.getService(ISLookUpService.class).quickSearchProfile(query)) {
69
					final String[] arr = s.split("@@@");
70
					final String id = arr[0].trim();
71
					final String name = arr[1].trim();
72
					final boolean manual = arr[2].trim().toLowerCase().equals("manual");
73
					if (success && !manual) {
74
						try {
75
							String pid = workflowExecutor.startProcess(id);
76
							log.info("PROC " + pid + " of WF " + id + " STARTED AS CHILD OF " + rsId);
77
						} catch (Exception e) {
78
							log.error("Error starting wf: " + id);
79
						}
80
					} else {
81
						pendingWfs.put(id, name);
82
					}
83
				}
84

  
85
				if (!emails.isEmpty()) {
86
					if (success) {
87
						emailDispatcher.sendSuccessMail(emails, rsId, procId, wfName, pendingWfs, responses);
88
					} else {
89
						final String error = doc.valueOf("//LAST_EXECUTION_ERROR");
90
						emailDispatcher.sendFailedMail(emails, rsId, procId, wfName, pendingWfs, responses, error);
91
					}
92
				}
93
			} catch (ISLookUpException e) {
94
				log.error("Error executing xquery: " + query, e);
95
			}
96
		} catch (DocumentException e) {
97
			log.error("Error parsing profile with id " + rsId + ": " + profile);
98
		}
99
	}
100

  
101
	private Set<String> calculateEmails(final String id) {
102
		final Set<String> list = Sets.newHashSet();
103
		try {
104
			for (String val : serviceLocator.getService(ISLookUpService.class).quickSearchProfile("//ADMIN_EMAIL[..//WORKFLOW/@id='" + id + "']/text()")) {
105
				for (String s : Splitter.on(",").trimResults().omitEmptyStrings().split(val)) {
106
					list.add(s);
107
				}
108
			}
109
		} catch (Exception e) {
110
			log.error("Error searching email adresses", e);
111
		}
112
		return list;
113
	}
114
}
modules/dnet-msro-service/tags/dnet-msro-service-2.1.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-2.1.1/src/main/java/eu/dnetlib/msro/workflows/nodes/mdstore/FetchMultipleMDStores.java
1
package eu.dnetlib.msro.workflows.nodes.mdstore;
2

  
3
import java.util.List;
4

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

  
8
import org.springframework.beans.factory.annotation.Autowired;
9

  
10
import com.google.gson.Gson;
11
import com.googlecode.sarasvati.Arc;
12
import com.googlecode.sarasvati.NodeToken;
13

  
14
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
15
import eu.dnetlib.enabling.resultset.IterableResultSetFactory;
16
import eu.dnetlib.enabling.resultset.client.ResultSetClientFactory;
17
import eu.dnetlib.msro.workflows.nodes.SimpleJobNode;
18

  
19
public class FetchMultipleMDStores extends SimpleJobNode {
20

  
21
	@Resource
22
	private UniqueServiceLocator serviceLocator;
23

  
24
	private List<String> mdId;
25
	private String mdFormat;
26

  
27
	private String eprParam;
28

  
29
	/** The result set factory. */
30
	@Resource(name = "iterableResultSetFactory")
31
	private IterableResultSetFactory resultSetFactory;
32

  
33
	/** The result set client factory. */
34
	@Autowired
35
	private ResultSetClientFactory resultSetClientFactory;
36

  
37
	@Override
38
	protected String execute(final NodeToken token) throws Exception {
39

  
40
		if (getMdId() == null) {
41
			@SuppressWarnings("unchecked")
42
			List<String> mdIds = new Gson().fromJson(token.getEnv().getAttribute("mdId"), List.class);
43

  
44
			setMdId(mdIds);
45
		}
46
		if (getMdFormat() == null) {
47
			setMdFormat(token.getEnv().getAttribute("mdFormat"));
48
		}
49
		MultipleMdStoreIterator iterators = new MultipleMdStoreIterator(serviceLocator, getMdId(), resultSetClientFactory);
50
		W3CEndpointReference eprUrls = resultSetFactory.createIterableResultSet(iterators);
51
		token.getEnv().setAttribute(getEprParam(), eprUrls.toString());
52
		return Arc.DEFAULT_ARC;
53
	}
54

  
55
	public List<String> getMdId() {
56
		return mdId;
57
	}
58

  
59
	public void setMdId(final List<String> mdId) {
60
		this.mdId = mdId;
61
	}
62

  
63
	public String getMdFormat() {
64
		return mdFormat;
65
	}
66

  
67
	public void setMdFormat(final String mdFormat) {
68
		this.mdFormat = mdFormat;
69
	}
70

  
71
	public String getEprParam() {
72
		return eprParam;
73
	}
74

  
75
	public void setEprParam(final String eprParam) {
76
		this.eprParam = eprParam;
77
	}
78

  
79
}
modules/dnet-msro-service/tags/dnet-msro-service-2.1.1/src/main/java/eu/dnetlib/msro/workflows/nodes/objectStore/DownloadIntoObjectStoreJobNode.java
1
package eu.dnetlib.msro.workflows.nodes.objectStore;
2

  
3
import java.io.StringReader;
4
import java.util.Iterator;
5
import java.util.Map;
6

  
7
import javax.xml.ws.wsaddressing.W3CEndpointReference;
8
import javax.xml.xpath.XPath;
9
import javax.xml.xpath.XPathFactory;
10

  
11
import org.apache.commons.logging.Log;
12
import org.apache.commons.logging.LogFactory;
13
import org.xml.sax.InputSource;
14

  
15
import com.googlecode.sarasvati.Engine;
16
import com.googlecode.sarasvati.NodeToken;
17
import com.googlecode.sarasvati.env.Env;
18

  
19
import eu.dnetlib.data.objectstore.rmi.MetadataObjectRecord;
20
import eu.dnetlib.data.objectstore.rmi.ObjectStoreService;
21
import eu.dnetlib.enabling.resultset.IterableResultSetFactory;
22
import eu.dnetlib.enabling.resultset.client.ResultSetClientFactory;
23
import eu.dnetlib.enabling.tools.blackboard.BlackboardJob;
24
import eu.dnetlib.msro.workflows.nodes.BlackboardJobNode;
25
import eu.dnetlib.msro.workflows.nodes.ProgressJobNode;
26
import eu.dnetlib.msro.workflows.nodes.blackboard.BlackboardWorkflowJobListener;
27
import eu.dnetlib.msro.workflows.resultset.ProcessCountingResultSetFactory;
28
import eu.dnetlib.msro.workflows.util.ProgressProvider;
29
import eu.dnetlib.msro.workflows.util.ResultsetProgressProvider;
30
import eu.dnetlib.msro.workflows.util.WorkflowsConstants;
31

  
32
public class DownloadIntoObjectStoreJobNode extends BlackboardJobNode implements ProgressJobNode {
33

  
34
	private static final Log log = LogFactory.getLog(DownloadIntoObjectStoreJobNode.class);
35

  
36
	class MetadataObjectIterator implements Iterator<String> {
37

  
38
		private Iterator<String> inputIterator;
39

  
40
		private String mime;
41

  
42
		public MetadataObjectIterator(final Iterator<String> inputIterator, final String xpath, final String mime) {
43
			this.inputIterator = inputIterator;
44
		}
45

  
46
		@Override
47
		public boolean hasNext() {
48
			return inputIterator.hasNext();
49
		}
50

  
51
		@Override
52
		public String next() {
53
			try {
54
				String record = inputIterator.next();
55
				XPath xpath = XPathFactory.newInstance().newXPath();
56
				InputSource doc = new InputSource(new StringReader(record));
57
				String identifier = xpath.evaluate(getIdXpath(), doc);
58
				MetadataObjectRecord objectrecord = new MetadataObjectRecord(identifier, record, mime);
59
				return objectrecord.toJSON();
60
			} catch (Exception e) {
61
				return null;
62
			}
63
		}
64

  
65
		@Override
66
		public void remove() {
67

  
68
		}
69

  
70
	}
71

  
72
	private String eprParam;
73

  
74
	private String objectStoreId;
75

  
76
	private String idXpath; // "//*[local-name()='objIdentifier']
77

  
78
	private String contentDescription;
79

  
80
	private String objectIsInsideEpr;
81

  
82
	private IterableResultSetFactory iterableResultSetFactory;
83
	private ResultSetClientFactory resultSetClientFactory;
84

  
85
	private ResultsetProgressProvider progressProvider;
86
	private ProcessCountingResultSetFactory processCountingResultSetFactory;
87

  
88
	@Override
89
	protected String obtainServiceId(final NodeToken token) {
90
		return getServiceLocator().getServiceId(ObjectStoreService.class);
91
	}
92

  
93
	public String getEprParam() {
94
		return eprParam;
95
	}
96

  
97
	public void setEprParam(final String eprParam) {
98
		this.eprParam = eprParam;
99
	}
100

  
101
	public String getObjectStoreId() {
102
		return objectStoreId;
103
	}
104

  
105
	public void setObjectStoreId(final String objectStoreId) {
106
		this.objectStoreId = objectStoreId;
107
	}
108

  
109
	public ProgressProvider getProgressProvider(final NodeToken token) {
110

  
111
		return progressProvider;
112
	}
113

  
114
	@Override
115
	protected void prepareJob(final BlackboardJob job, final NodeToken token) throws Exception {
116

  
117
		job.setAction("FEEDOBJECT");
118
		final String eprS = token.getEnv().getAttribute(getEprParam());
119
		job.getParameters().put("obsID", getObjectStoreId());
120
		job.getParameters().put("mime", getContentDescription());
121
		final Iterator<String> client = resultSetClientFactory.getClient(eprS).iterator();
122

  
123
		final W3CEndpointReference epr = iterableResultSetFactory.createIterableResultSet(new Iterable<String>() {
124

  
125
			@Override
126
			public Iterator<String> iterator() {
127
				return new MetadataObjectIterator(client, "//*[local-name()='objIdentifier']", "xml");
128
			}
129
		});
130
		this.progressProvider = processCountingResultSetFactory.createProgressProvider(token.getProcess(), epr);
131
		job.getParameters().put("epr", progressProvider.getEpr().toString());
132

  
133
	}
134

  
135
	@Override
136
	protected BlackboardWorkflowJobListener generateBlackboardListener(final Engine engine, final NodeToken token) {
137
		return new BlackboardWorkflowJobListener(engine, token) {
138

  
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff