Project

General

Profile

« Previous | Next » 

Revision 45308

codebase used to migrate to java8 the production system

View differences:

modules/dnet-actionmanager-service/releases/1.0.3/src/test/java/eu/dnetlib/actionmanager/hbase/HBaseActionManagerTest.java
1
package eu.dnetlib.actionmanager.hbase;
2

  
3
import static org.junit.Assert.assertNotNull;
4
import static org.junit.Assert.assertTrue;
5

  
6
import java.io.StringReader;
7
import java.io.StringWriter;
8

  
9
import javax.annotation.Resource;
10
import javax.xml.transform.Transformer;
11

  
12
import org.apache.commons.io.IOUtils;
13
import org.dom4j.Document;
14
import org.dom4j.io.DocumentResult;
15
import org.dom4j.io.DocumentSource;
16
import org.dom4j.io.SAXReader;
17
import org.junit.Before;
18
import org.junit.Ignore;
19
import org.junit.Test;
20
import org.junit.runner.RunWith;
21
import org.springframework.test.context.ContextConfiguration;
22
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
23

  
24
import eu.dnetlib.actionmanager.ActionManagerConstants.ACTION_TYPE;
25
import eu.dnetlib.actionmanager.common.Agent;
26
import eu.dnetlib.actionmanager.common.Agent.AGENT_TYPE;
27
import eu.dnetlib.actionmanager.common.Operation;
28
import eu.dnetlib.actionmanager.common.Provenance;
29
import eu.dnetlib.actionmanager.rmi.ActionManagerException;
30

  
31
@Ignore
32
@RunWith(SpringJUnit4ClassRunner.class)
33
@ContextConfiguration(locations = { "/eu/dnetlib/actionmanager/test/applicationContext-actionmanager-test.xml" })
34
public class HBaseActionManagerTest {
35

  
36
	@Resource
37
	private HBaseActionManagerCore core;
38

  
39
	private String dmfInfoPackage;
40

  
41
	private static final String SET = "acus";
42

  
43
	@Before
44
	public void setUp() throws Exception {
45
		StringWriter sw = new StringWriter();
46
		IOUtils.copy(getClass().getResourceAsStream("/eu/dnetlib/actionmanager/test/record.xml"), sw);
47
		dmfInfoPackage = sw.toString();
48
	}
49

  
50
	@Test
51
	public void testBeans() {
52
		assertNotNull(core);
53
		assertNotNull(core.getActionFactory());
54
		assertNotNull(core.getHbaseClient());
55
	}
56

  
57
	@Test
58
	public void testXSLT() throws Exception {
59
		Transformer transformer = core.getActionFactory().prepareXsltTransformer("dmf2actions");
60
		assertNotNull(transformer);
61

  
62
		Document doc = (new SAXReader()).read(new StringReader(dmfInfoPackage));
63

  
64
		final DocumentResult result = new DocumentResult();
65
		transformer.transform(new DocumentSource(doc), result);
66

  
67
		int count = result.getDocument().selectNodes("//ACTION").size();
68
		System.out.println("******************************************");
69
		System.out.println("N. Actions: " + count);
70
		System.out.println(result.getDocument().asXML());
71
		System.out.println("******************************************");
72

  
73
		assertTrue(count > 0);
74
	}
75

  
76
	@Test
77
	public void testInfoPackage() throws ActionManagerException {
78
		Agent a = new Agent("test", "test", AGENT_TYPE.algo);
79

  
80
		core.applyInfoPackageAction("dmf2actions", SET, a, Operation.INSERT, dmfInfoPackage, Provenance.user_claim_search, "0.5", "acus");
81
	}
82

  
83
	@Test
84
	public void testRetrieveActions() throws ActionManagerException {
85
		core.getHbaseClient().retrieveRows(ACTION_TYPE.aac + "|", null, 10);
86
	}
87

  
88
}
modules/dnet-actionmanager-service/releases/1.0.3/src/test/java/eu/dnetlib/actionmanager/xslt/RelationXsltFunctionsTest.java
1
package eu.dnetlib.actionmanager.xslt;
2

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

  
6
import javax.xml.transform.Source;
7
import javax.xml.transform.Transformer;
8
import javax.xml.transform.TransformerFactory;
9
import javax.xml.transform.stream.StreamResult;
10
import javax.xml.transform.stream.StreamSource;
11

  
12
import org.junit.Before;
13
import org.junit.Test;
14

  
15
public class RelationXsltFunctionsTest {
16
	private Transformer transformer;
17

  
18
	@Before
19
	public void setUp() throws Exception {
20
		Source source = new StreamSource(getClass().getResourceAsStream("/eu/dnetlib/actionmanager/xslt/rels2actions.xslt"));
21
		transformer = TransformerFactory.newInstance().newTransformer(source);
22
	}
23

  
24
	@Test
25
	public void test_01() throws Exception {
26
		StringBuffer xml = new StringBuffer();
27
		xml.append("<RELATIONS>");
28
		xml.append("</RELATIONS>");
29

  
30
		applyXslt(xml.toString());
31
	}
32

  
33
	@Test
34
	public void test_02() throws Exception {
35
		StringBuffer xml = new StringBuffer();
36
		xml.append("<RELATIONS>");
37
		xml.append("<RELATION type='resultProject' source='50|crossref____::7fb616c8cdd08f0f12a04ac0f18edf80' target='corda_______::281877' />");
38
		xml.append("<RELATION type='resultProject' source='50|crossref____::7fb616c8cdd08f0f12a04ac0f18edf80' target='40|corda_______::0001fc1603869410927ddbde3afb2403' />");
39
		xml.append("<RELATION type='personResult' source='30|crossref____::000178abc5a314472603976a1be68927' target='50|crossref____::7fb616c8cdd08f0f12a04ac0f18edf80' />");
40
		xml.append("</RELATIONS>");
41

  
42
		applyXslt(xml.toString());
43
	}
44

  
45
	public String applyXslt(String xml) throws Exception {
46
		final Source xmlSource = new StreamSource(new StringReader(xml));
47
		final StringWriter output = new StringWriter();
48

  
49
		transformer.transform(xmlSource, new StreamResult(output));
50

  
51
		System.out.println(output.toString());
52

  
53
		return output.toString();
54
	}
55

  
56
}
modules/dnet-actionmanager-service/releases/1.0.3/src/test/resources/eu/dnetlib/actionmanager/test/applicationContext-actionmanager-test.xml
1
<?xml version="1.0" encoding="UTF-8"?>
2
<beans xmlns="http://www.springframework.org/schema/beans"
3
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
4
	xmlns:sec="http://cxf.apache.org/configuration/security" xmlns:wsa="http://cxf.apache.org/ws/addressing"
5
	xmlns:p="http://www.springframework.org/schema/p" xmlns:http="http://cxf.apache.org/transports/http/configuration"
6
	xmlns:t="http://dnetlib.eu/springbeans/t" xmlns:template="http://dnetlib.eu/springbeans/template"
7
	xmlns:util="http://www.springframework.org/schema/util"
8
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
9
                                    http://cxf.apache.org/ws/addressing http://cxf.apache.org/schemas/ws-addr-conf.xsd
10
                                    http://cxf.apache.org/configuration/security http://cxf.apache.org/schemas/configuration/security.xsd
11
                                    http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd
12
                            http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
13
                            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
14
                            http://dnetlib.eu/springbeans/template http://dnetlib.eu/springbeans/template.xsd">
15

  
16
	<bean id="hbaseActionManagerCore" class="eu.dnetlib.actionmanager.hbase.HBaseActionManagerCore"
17
		p:actionFactory-ref="actionFactory"
18
		p:hbaseClient-ref="hbaseClient" />
19
		
20
	<bean id="hbaseClient" class="eu.dnetlib.actionmanager.hbase.HBaseClient"
21
		p:tableName="db_actions_michele"
22
		p:hbaseConf="${services.data.hbase.dm.properties}" 
23
		init-method="initWithEmptyTable" />		
24
		<!-- p:hbaseConf="classpath:/eu/dnetlib/actionmanager/test/hbase.properties" -->
25
		
26
	<bean id="actionFactory" class="eu.dnetlib.actionmanager.actions.ActionFactory">
27
		<property name="xslts">
28
			<util:map>
29
				<entry key="dmf2actions" value="classpath:/eu/dnetlib/actionmanager/xslt/dmf2actions.xslt" />
30
			</util:map>
31
		</property>
32
	</bean>
33

  
34

  
35
</beans>
modules/dnet-actionmanager-service/releases/1.0.3/src/test/resources/eu/dnetlib/actionmanager/test/hbase.properties
1
#COMMON
2
hadoop.entry.node                               =       node1.hadoop.research-infrastructures.eu
3

  
4
#CORE-SITE
5
fs.defaultFS                                    =       hdfs://${hadoop.entry.node}:8020
6
io.file.buffer.size                     =       65536
7
io.compression.codecs                   =       org.apache.hadoop.io.compress.DefaultCodec,org.apache.hadoop.io.compress.GzipCodec,org.apache.hadoop.io.compress.BZip2Codec,org.apache.hadoop.io.compress.DeflateCodec,org.apache.hadoop.io.compress.SnappyCodec
8
hadoop.security.authentication  =       simple
9
hadoop.security.auth_to_local   =       DEFAULT
10

  
11
#HBASE-SITE
12
hbase.rootdir                                   =       ${fs.defaultFS}/hbase
13
hbase.client.write.buffer               =       2097152
14
hbase.client.pause                              =       1000
15
hbase.client.retries.number             =       10
16
hbase.client.scanner.caching    =       1
17
hbase.client.keyvalue.maxsize   =       10485760
18
hbase.security.authentication   =       simple
19
zookeeper.session.timeout               =       60000
20
zookeeper.znode.parent                  =       /hbase
21
zookeeper.znode.rootserver              =       root-region-server
22
hbase.zookeeper.quorum                  =       ${hadoop.entry.node}
23
hbase.zookeeper.property.clientPort     =       2182
24

  
25
#HDFS-SITE
26
dfs.https.port                                  =       50470
27
dfs.namenode.https-address              =       ${hadoop.entry.node}:${dfs.https.port}
28
dfs.namenode.http-address               =       ${hadoop.entry.node}:50070
29
dfs.replication                                 =       3
30
dfs.blocksize                                   =       134217728
31
dfs.client.use.datanode.hostname=       false
32

  
33
#MAPRED-SITE
34
mapreduce.jobtracker.address    =       ${hadoop.entry.node}:8021
35
mapred.job.tracker                              =       ${hadoop.entry.node}:8021
36
mapred.mapper.new-api                   =       true
37
mapred.reducer.new-api                  =       true
38
mapred.output.compress                  =       false
39
mapred.output.compression.type  =       BLOCK
40
mapred.output.compression.codec =       org.apache.hadoop.io.compress.DefaultCodec
41
#mapred.map.output.compression.codec    =       org.apache.hadoop.io.compress.SnappyCodec
42
mapred.compress.map.output              =       true
43
#io.sort.factor                                 =       64
44
#io.sort.record.percent                 =       0.05
45
#io.sort.spill.percent                  =       0.8
46
#mapred.reduce.parallel.copies  =       10
47
#mapred.submit.replication              =       1
48
#mapred.reduce.tasks                            =       8
49
#io.sort.mb                                             =       56
50
#mapred.child.java.opts                 =        -Xmx238449165
51
#mapred.job.reuse.jvm.num.tasks =       1
52
#mapred.map.tasks                               =       6
53
#mapred.map.tasks.speculative.execution =       false
54
#mapred.reduce.tasks.speculative.execution      =       false
55
#mapred.reduce.slowstart.completed.maps =       0.8
56
##mapred.local.dir                              = /data/mapred/local,/data/mapred/jt
57
mapred.local.dir                                = /tmp
58
mapred.child.java.opts                  = -Xmx512973352
59

  
60
#dfs.client.use.legacy.blockreader=true
61
 
modules/dnet-actionmanager-service/releases/1.0.3/src/main/java/eu/dnetlib/actionmanager/hbase/HBaseClient.java
1
package eu.dnetlib.actionmanager.hbase;
2

  
3
import java.io.IOException;
4
import java.util.Collections;
5
import java.util.Iterator;
6
import java.util.List;
7
import java.util.Map;
8
import java.util.Map.Entry;
9
import java.util.NavigableMap;
10
import java.util.Set;
11
import java.util.concurrent.Executor;
12
import java.util.concurrent.Executors;
13

  
14
import javax.annotation.Resource;
15

  
16
import org.apache.commons.logging.Log;
17
import org.apache.commons.logging.LogFactory;
18
import org.apache.hadoop.conf.Configuration;
19
import org.apache.hadoop.hbase.HColumnDescriptor;
20
import org.apache.hadoop.hbase.HTableDescriptor;
21
import org.apache.hadoop.hbase.client.Delete;
22
import org.apache.hadoop.hbase.client.Get;
23
import org.apache.hadoop.hbase.client.HBaseAdmin;
24
import org.apache.hadoop.hbase.client.HTable;
25
import org.apache.hadoop.hbase.client.Put;
26
import org.apache.hadoop.hbase.client.Result;
27
import org.apache.hadoop.hbase.client.ResultScanner;
28
import org.apache.hadoop.hbase.client.Scan;
29
import org.apache.hadoop.hbase.filter.Filter;
30
import org.apache.hadoop.hbase.filter.FilterList;
31
import org.apache.hadoop.hbase.filter.PageFilter;
32
import org.apache.hadoop.hbase.filter.PrefixFilter;
33
import org.apache.hadoop.hbase.util.Bytes;
34
import org.springframework.beans.factory.annotation.Required;
35

  
36
import com.google.common.base.Function;
37
import com.google.common.collect.Iterators;
38
import com.google.common.collect.Lists;
39
import com.google.common.collect.Maps;
40
import com.google.common.collect.Sets;
41
import com.google.gson.Gson;
42
import com.google.protobuf.InvalidProtocolBufferException;
43

  
44
import eu.dnetlib.actionmanager.ActionManagerConstants;
45
import eu.dnetlib.actionmanager.ActionManagerConstants.ACTION_TYPE;
46
import eu.dnetlib.actionmanager.ActionManagerConstants.COLUMN_FAMILIES;
47
import eu.dnetlib.actionmanager.rmi.ActionManagerException;
48
import eu.dnetlib.data.hadoop.config.ClusterName;
49
import eu.dnetlib.data.hadoop.config.ConfigurationEnumerator;
50
import eu.dnetlib.data.proto.OafProtos.Oaf;
51
import eu.dnetlib.miscutils.functional.hash.Hashing;
52

  
53
public class HBaseClient {
54

  
55
	private String tableName;
56

  
57
	@Resource
58
	private ConfigurationEnumerator configurationEnumerator;
59

  
60
	private Configuration config;
61

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

  
64
	private final Executor executor = Executors.newSingleThreadExecutor();
65

  
66
	private final Function<Result, Map<String, String>> transformRow = new Function<Result, Map<String, String>>() {
67

  
68
		@Override
69
		public Map<String, String> apply(Result r) {
70
			Map<String, String> map = Maps.newHashMap();
71
			map.put("rowId", Bytes.toString(r.getRow()));
72

  
73
			for (Entry<byte[], NavigableMap<byte[], NavigableMap<Long, byte[]>>> e1 : r.getMap().entrySet()) {
74
				String cf = Bytes.toString(e1.getKey());
75
				for (Entry<byte[], NavigableMap<Long, byte[]>> e2 : e1.getValue().entrySet()) {
76
					byte[] bb = e2.getValue().get(Collections.max(e2.getValue().keySet()));
77
					String key = cf + ":" + Bytes.toString(e2.getKey());
78
					String value = "";
79
					try {
80
						value = key.equals("target:content") ? Oaf.parseFrom(bb).toString() : Bytes.toString(bb);
81
					} catch (InvalidProtocolBufferException e) {
82
						log.error("Problem parsing protobuf !!!");
83
					}
84
					map.put(key, value);
85
				}
86
			}
87
			return map;
88
		}
89
	};
90

  
91
	public void init() {
92
		performInit(false);
93
	}
94

  
95
	public void initWithEmptyTable() {
96
		performInit(true);
97
	}
98

  
99
	private void performInit(final boolean delete) {
100
		executor.execute(new Runnable() {
101

  
102
			@Override
103
			public void run() {
104
				try {
105
					log.info("Initializing Action Manager");
106
					loadConfiguration();
107
					prepareTable(delete);
108
					log.info("ActionManager is ready");
109
				} catch (IOException e) {
110
					log.error("Error initializing action manager", e);
111
				}
112
			}
113
		});
114
	}
115

  
116
	private void prepareTable(boolean delete) throws IOException {
117

  
118
		final HBaseAdmin admin = new HBaseAdmin(config);
119
		try {
120
			if (delete && admin.tableExists(tableName)) {
121
				log.info("Deleting existing hbase table: " + tableName);
122
				admin.disableTable(tableName);
123
				admin.deleteTable(tableName);
124
			}
125

  
126
			if (!admin.tableExists(tableName)) {
127
				log.info("Creating missing hbase table: " + tableName);
128
				admin.createTable(new HTableDescriptor(tableName));
129
			}
130

  
131
			final HTableDescriptor desc = admin.getTableDescriptor(Bytes.toBytes(getTableName()));
132

  
133
			Set<String> currents = Sets.newHashSet();
134
			for (HColumnDescriptor hcd : desc.getColumnFamilies()) {
135
				currents.add(hcd.getNameAsString());
136
			}
137

  
138
			Set<String> missing = Sets.newHashSet();
139
			for (COLUMN_FAMILIES cf : ActionManagerConstants.COLUMN_FAMILIES.values()) {
140
				if (!currents.contains(cf.toString())) {
141
					missing.add(cf.toString());
142
				}
143
			}
144

  
145
			if (!missing.isEmpty()) {
146
				if (admin.isTableEnabled(getTableName())) {
147
					admin.disableTable(getTableName());
148
				}
149

  
150
				for (String column : missing) {
151
					log.info("hbase table: '" + getTableName() + "', adding columnFamily: " + column);
152
					admin.addColumn(getTableName(), new HColumnDescriptor(column));
153
				}
154

  
155
				admin.enableTable(getTableName());
156
			}
157
		} finally {
158
			admin.close();
159
		}
160
	}
161

  
162
	private void loadConfiguration() throws IOException {
163
		config = configurationEnumerator.get(ClusterName.DM);
164
		log.info(config.toString());
165
	}
166

  
167
	public Configuration getConfig() {
168
		return config;
169
	}
170

  
171
	public void write(List<Put> puts) throws ActionManagerException {
172
		try {
173
			final HTable table = new HTable(config, tableName);
174
			try {
175
				log.info("Adding " + puts.size() + " action(s) to " + tableName);
176
				table.put(puts);
177
			} finally {
178
				table.flushCommits();
179
				table.close();
180
			}
181
		} catch (IOException e) {
182
			throw new ActionManagerException(e);
183
		}
184
	}
185

  
186
	public void write(List<Put> puts, HTable table) throws ActionManagerException {
187
		try {
188
			log.info("Adding " + puts.size() + " action(s) to " + tableName);
189
			table.put(puts);
190
		} catch (IOException e) {
191
			throw new ActionManagerException(e);
192
		}
193
	}
194

  
195
	public void delete(List<Delete> deletes) throws ActionManagerException {
196
		try {
197
			final HTable table = new HTable(config, tableName);
198
			try {
199
				log.info("Deleting " + deletes.size() + " action(s) from " + tableName);
200
				table.delete(deletes);
201
			} finally {
202
				table.flushCommits();
203
				table.close();
204
			}
205
		} catch (IOException e) {
206
			throw new ActionManagerException(e);
207
		}
208
	}
209

  
210
	public Map<String, String> getRow(byte[] id) throws ActionManagerException {
211
		try {
212
			final HTable table = new HTable(config, tableName);
213
			try {
214
				Result result = table.get(new Get(id));
215
				return transformRow.apply(result);
216
			} finally {
217
				table.close();
218
			}
219
		} catch (IOException e) {
220
			throw new ActionManagerException(e);
221
		}
222
	}
223

  
224
	public List<Map<String, String>> retrieveRows(String prefix, String start, int limit) throws ActionManagerException {
225
		List<Map<String, String>> list = Lists.newArrayList();
226

  
227
		try {
228
			final HTable table = new HTable(config, tableName);
229
			try {
230
				Filter filter = prefix == null || prefix.isEmpty() ? new PageFilter(limit) : new FilterList(FilterList.Operator.MUST_PASS_ALL, new PageFilter(
231
						limit), new PrefixFilter(Bytes.toBytes(prefix)));
232
				Scan scan = new Scan();
233
				if (start != null) {
234
					scan.setStartRow(Bytes.toBytes(start));
235
				}
236
				scan.setFilter(filter);
237

  
238
				ResultScanner rs = table.getScanner(scan);
239
				try {
240
					Iterator<Map<String, String>> iter = Iterators.transform(rs.iterator(), transformRow);
241
					while (iter.hasNext()) {
242
						list.add(iter.next());
243
					}
244
				} finally {
245
					rs.close();
246
				}
247
			} finally {
248
				table.close();
249
			}
250
		} catch (IOException e) {
251
			throw new ActionManagerException(e);
252
		}
253
		return list;
254
	}
255

  
256
	public List<String> retrieveActionsByAgent(String agentId, int limit) throws ActionManagerException {
257
		List<String> list = Lists.newArrayList();
258

  
259
		String prefix = ACTION_TYPE.pkg + "|" + Hashing.md5(agentId) + "|";
260

  
261
		try {
262
			final HTable table = new HTable(config, tableName);
263
			try {
264

  
265
				FilterList filter = new FilterList(FilterList.Operator.MUST_PASS_ALL);
266
				filter.addFilter(new PageFilter(limit));
267
				filter.addFilter(new PrefixFilter(Bytes.toBytes(prefix)));
268

  
269
				Scan scan = new Scan();
270
				scan.setFilter(filter);
271

  
272
				ResultScanner rs = table.getScanner(scan);
273
				Iterator<Result> iter = rs.iterator();
274
				while (iter.hasNext()) {
275
					Result r = iter.next();
276
					Map<String, String> map = Maps.newHashMap();
277
					map.put("id", Bytes.toString(r.getRow()));
278
					map.put("content", Bytes.toString(r.getValue(ActionManagerConstants.ACTION_COLFAMILY, Bytes.toBytes(ACTION_TYPE.pkg.toString()))));
279
					list.add(new Gson().toJson(map));
280
				}
281
			} finally {
282
				table.close();
283
			}
284
		} catch (IOException e) {
285
			throw new ActionManagerException(e);
286
		}
287
		return list;
288
	}
289

  
290
	public String getTableName() {
291
		return tableName;
292
	}
293

  
294
	@Required
295
	public void setTableName(String tableName) {
296
		this.tableName = tableName;
297
	}
298

  
299
}
modules/dnet-actionmanager-service/releases/1.0.3/src/main/java/eu/dnetlib/actionmanager/hbase/HBaseActionManagerCore.java
1
package eu.dnetlib.actionmanager.hbase;
2

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

  
6
import org.apache.hadoop.hbase.client.Delete;
7
import org.apache.hadoop.hbase.client.HTable;
8
import org.apache.hadoop.hbase.client.Put;
9
import org.apache.hadoop.hbase.util.Bytes;
10
import org.springframework.beans.factory.annotation.Required;
11

  
12
import com.google.common.collect.Lists;
13

  
14
import eu.dnetlib.actionmanager.actions.ActionFactory;
15
import eu.dnetlib.actionmanager.actions.XsltInfoPackageAction;
16
import eu.dnetlib.actionmanager.common.Agent;
17
import eu.dnetlib.actionmanager.common.Operation;
18
import eu.dnetlib.actionmanager.common.Provenance;
19
import eu.dnetlib.actionmanager.is.ISClient;
20
import eu.dnetlib.actionmanager.rmi.ActionManagerException;
21
import eu.dnetlib.actionmanager.set.ActionManagerSet;
22

  
23
public class HBaseActionManagerCore {
24

  
25
	private ActionFactory actionFactory;
26

  
27
	private HBaseClient hbaseClient;
28

  
29
	private ISClient informationServiceClient;
30

  
31
	/*
32
	 * public void insertOrUpdateAtomicAction(AtomicAction action, String provenance, String trust) throws
33
	 * ActionManagerException { hbaseClient.write(action.asPutOperations(null, provenance, trust, null)); }
34
	 * 
35
	 * public void insertOrUpdateAtomicActions(List<AtomicAction> actions, String provenance, String trust) throws
36
	 * ActionManagerException { for (AtomicAction action : actions) { insertOrUpdateAtomicAction(action, provenance,
37
	 * trust); } }
38
	 */
39

  
40
	public int applyInfoPackageAction(
41
			String splitRuleId,
42
			String set,
43
			Agent agent,
44
			Operation operation,
45
			String infoPackage,
46
			Provenance provenance,
47
			String trust,
48
			String nsprefix) throws ActionManagerException {
49

  
50
		if (informationServiceClient.existsSet(set)) {
51
			XsltInfoPackageAction action = actionFactory.generateInfoPackageAction(splitRuleId, set, agent, operation, infoPackage);
52
			List<Put> puts = action.asPutOperations(null, provenance, trust, nsprefix);
53
			hbaseClient.write(puts);
54
			return puts.size();
55
		} else {
56
			throw new ActionManagerException("Missing set " + set);
57
		}
58
	}
59
	
60
	public int applyInfoPackageAction(			
61
			String splitRuleId,
62
			String set,
63
			Agent agent,
64
			Operation operation,
65
			String infoPackage,
66
			Provenance provenance,
67
			String trust,
68
			String nsprefix,
69
			HTable table) throws ActionManagerException {
70
		if (informationServiceClient.existsSet(set)) {
71
			XsltInfoPackageAction action = actionFactory.generateInfoPackageAction(splitRuleId, set, agent, operation, infoPackage);
72
			List<Put> puts = action.asPutOperations(null, provenance, trust, nsprefix);
73
			hbaseClient.write(puts, table);
74
			return puts.size();
75
		} else {
76
			throw new ActionManagerException("Missing set " + set);
77
		}
78
		
79
	}
80

  
81
	public void deleteInfoPackageAction(String id) throws ActionManagerException {
82
		Map<String, String> row = hbaseClient.getRow(Bytes.toBytes(id));
83
		List<Delete> deletes = Lists.newArrayList();
84
		for (String key : row.keySet()) {
85
			if (key.startsWith("rel:")) {
86
				deletes.add(new Delete(Bytes.toBytes(key.substring(4))));
87
			}
88
		}
89
		deletes.add(new Delete(Bytes.toBytes(id)));
90
		hbaseClient.delete(deletes);
91
	}
92

  
93
	public ActionFactory getActionFactory() {
94
		return actionFactory;
95
	}
96

  
97
	@Required
98
	public void setActionFactory(ActionFactory actionFactory) {
99
		this.actionFactory = actionFactory;
100
	}
101

  
102
	public HBaseClient getHbaseClient() {
103
		return hbaseClient;
104
	}
105

  
106
	@Required
107
	public void setHbaseClient(HBaseClient hbaseClient) {
108
		this.hbaseClient = hbaseClient;
109
	}
110

  
111
	public List<ActionManagerSet> listAvailableSets() {
112
		return informationServiceClient.listSets();
113
	}
114

  
115
	public ISClient getInformationServiceClient() {
116
		return informationServiceClient;
117
	}
118

  
119
	@Required
120
	public void setInformationServiceClient(ISClient informationServiceClient) {
121
		this.informationServiceClient = informationServiceClient;
122
	}
123

  
124
}
modules/dnet-actionmanager-service/releases/1.0.3/src/main/java/eu/dnetlib/actionmanager/blackboard/ActionManagerActions.java
1
package eu.dnetlib.actionmanager.blackboard;
2

  
3
public enum ActionManagerActions {
4
	FEED,
5
	PROMOTE,
6
	DELETE
7
}
modules/dnet-actionmanager-service/releases/1.0.3/src/main/java/eu/dnetlib/actionmanager/blackboard/DeleteActionManagerAction.java
1
package eu.dnetlib.actionmanager.blackboard;
2

  
3
import java.util.concurrent.Callable;
4

  
5
import eu.dnetlib.actionmanager.rmi.ActionManagerException;
6
import eu.dnetlib.actionmanager.wf.ActionManagerWorkflowLauncher;
7
import eu.dnetlib.enabling.tools.blackboard.BlackboardJob;
8
import eu.dnetlib.enabling.tools.blackboard.BlackboardServerAction;
9
import eu.dnetlib.enabling.tools.blackboard.BlackboardServerHandler;
10

  
11
public class DeleteActionManagerAction extends AbstractActionManagerAction implements BlackboardServerAction<ActionManagerActions> {
12

  
13
	//	<MESSAGE id="bb-1234" date="2012-11-06T15:10:56+01:00">
14
	//		<ACTION>DELETE</ACTION>
15
	//		<PARAMETER name="set" value=""/>
16
	//		<ACTION_STATUS>ASSIGNED</ACTION_STATUS>
17
	//	</MESSAGE>
18

  
19
	@Override
20
	public void execute(final BlackboardServerHandler handler, final BlackboardJob job) {
21

  
22
		String set = job.getParameters().get("set");
23
		if (set == null || set.isEmpty()) {
24
			set = ActionManagerWorkflowLauncher.ALL_SETS;
25
		}
26

  
27
		try {
28
			getActionManagerWorkflowLauncher().executeDelete(set, new Callable<String>() {
29
				@Override
30
				public String call() {
31
					handler.done(job);
32
					return "done";
33
				}
34
			}, new Callable<String>() {
35
				@Override
36
				public String call() {
37
					handler.failed(job, new ActionManagerException("MSRO Workwlow is failed"));
38
					return "failed";
39
				}
40
			});
41
		} catch (Exception e) {
42
			handler.failed(job, e);
43
		}
44
	}
45

  
46
}
modules/dnet-actionmanager-service/releases/1.0.3/src/main/java/eu/dnetlib/actionmanager/blackboard/AbstractActionManagerAction.java
1
package eu.dnetlib.actionmanager.blackboard;
2

  
3
import javax.annotation.Resource;
4

  
5
import eu.dnetlib.actionmanager.hbase.HBaseActionManagerCore;
6
import eu.dnetlib.actionmanager.wf.ActionManagerWorkflowLauncher;
7

  
8
public class AbstractActionManagerAction {
9

  
10
	@Resource
11
	protected HBaseActionManagerCore core;
12

  
13
	@Resource
14
	private ActionManagerWorkflowLauncher actionManagerWorkflowLauncher;
15

  
16
	public HBaseActionManagerCore getCore() {
17
		return core;
18
	}
19

  
20
	public void setCore(HBaseActionManagerCore core) {
21
		this.core = core;
22
	}
23

  
24
	public ActionManagerWorkflowLauncher getActionManagerWorkflowLauncher() {
25
		return actionManagerWorkflowLauncher;
26
	}
27

  
28
	public void setActionManagerWorkflowLauncher(ActionManagerWorkflowLauncher actionManagerWorkflowLauncher) {
29
		this.actionManagerWorkflowLauncher = actionManagerWorkflowLauncher;
30
	}
31

  
32
}
modules/dnet-actionmanager-service/releases/1.0.3/src/main/java/eu/dnetlib/actionmanager/blackboard/FeedActionManagerAction.java
1
package eu.dnetlib.actionmanager.blackboard;
2

  
3
import javax.annotation.Resource;
4

  
5
import org.apache.commons.codec.binary.Base64;
6
import org.apache.commons.logging.Log;
7
import org.apache.commons.logging.LogFactory;
8

  
9
import eu.dnetlib.actionmanager.common.Agent;
10
import eu.dnetlib.actionmanager.common.Operation;
11
import eu.dnetlib.actionmanager.common.Provenance;
12
import eu.dnetlib.actionmanager.rmi.ActionManagerException;
13
import eu.dnetlib.enabling.resultset.client.ResultSetClientFactory;
14
import eu.dnetlib.enabling.tools.blackboard.BlackboardJob;
15
import eu.dnetlib.enabling.tools.blackboard.BlackboardServerAction;
16
import eu.dnetlib.enabling.tools.blackboard.BlackboardServerHandler;
17

  
18
// TODO: Auto-generated Javadoc
19
/**
20
 * The Class FeedActionManagerAction.
21
 */
22
public class FeedActionManagerAction extends AbstractActionManagerAction implements BlackboardServerAction<ActionManagerActions> {
23

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

  
27
	/** The result set client factory. */
28
	@Resource
29
	private ResultSetClientFactory resultSetClientFactory;
30

  
31
	/**
32
	 * input parameters: epr: result-set end point reference containg the set of package info ruleId: one of the rules
33
	 * available to apply set: the destination set for the current info-packages provenance: the source of the
34
	 * info-packages fed trust: trust level nsprefix: namespace prefix agentID agentType.
35
	 * 
36
	 * @param handler
37
	 *            the handler
38
	 * @param job
39
	 *            the job
40
	 */
41
	@Override
42
	public void execute(BlackboardServerHandler handler, BlackboardJob job) {
43
		log.debug("Inside execute" + this.getClass().getSimpleName());
44

  
45
		String epr = job.getParameters().get("epr");
46
		String ruleId = job.getParameters().get("ruleId");
47
		String set = job.getParameters().get("set");
48
		Provenance provenance = Provenance.convert(job.getParameters().get("provenance"));
49
		String trust = job.getParameters().get("trust");
50
		String nsprefix = job.getParameters().get("nsprefix");
51
		String agentID = job.getParameters().get("agentId");
52
		String agentName = job.getParameters().get("agentName");
53
		String agentType = job.getParameters().get("agentType");
54

  
55
		int n = 0;
56
		try {
57
			n = feed(epr, ruleId, set, provenance, trust, nsprefix, agentID, agentName, agentType);
58
		} catch (ActionManagerException e) {
59
			handler.failed(job, e);
60
			return;
61
		}
62

  
63
		log.debug("Actions added: " + n);
64
		handler.done(job);
65
	}
66

  
67
	/**
68
	 * Feed.
69
	 * 
70
	 * @param epr
71
	 *            the epr
72
	 * @param ruleId
73
	 *            the rule id
74
	 * @param set
75
	 *            the set
76
	 * @param provenance
77
	 *            the provenance
78
	 * @param trust
79
	 *            the trust
80
	 * @param nsprefix
81
	 *            the nsprefix
82
	 * @param agentID
83
	 *            the agent id
84
	 * @param agentType
85
	 *            the agent type
86
	 * @return the int
87
	 * @throws ActionManagerException
88
	 *             the action manager exception
89
	 */
90
	private int feed(
91
			String epr,
92
			String ruleId,
93
			String set,
94
			Provenance provenance,
95
			String trust,
96
			String nsprefix,
97
			String agentID,
98
			String agentName,
99
			String agentType
100

  
101
	) throws ActionManagerException {
102
		String decodeEPR = new String(Base64.decodeBase64(epr));
103

  
104
		final Iterable<String> records = resultSetClientFactory.getClient(decodeEPR);
105
		int n = 0;
106
		Agent agent = new Agent();
107
		agent.setId(agentID);
108
		agent.setName(agentName);
109
		agent.setType(Agent.AGENT_TYPE.valueOf(agentType));
110
		for (String infoPackage : records) {
111
			if (infoPackage != null) {
112
				n += core.applyInfoPackageAction(ruleId, set, agent, Operation.INSERT, infoPackage, provenance, trust, nsprefix);
113
			}
114
		}
115
		return n;
116
	}
117
}
modules/dnet-actionmanager-service/releases/1.0.3/src/main/java/eu/dnetlib/actionmanager/blackboard/PromoteActionManagerAction.java
1
package eu.dnetlib.actionmanager.blackboard;
2

  
3
import java.util.concurrent.Callable;
4

  
5
import eu.dnetlib.actionmanager.rmi.ActionManagerException;
6
import eu.dnetlib.actionmanager.wf.ActionManagerWorkflowLauncher;
7
import eu.dnetlib.enabling.tools.blackboard.BlackboardJob;
8
import eu.dnetlib.enabling.tools.blackboard.BlackboardServerAction;
9
import eu.dnetlib.enabling.tools.blackboard.BlackboardServerHandler;
10

  
11
public class PromoteActionManagerAction extends AbstractActionManagerAction implements BlackboardServerAction<ActionManagerActions> {
12

  
13
	@Override
14
	public void execute(final BlackboardServerHandler handler, final BlackboardJob job) {
15

  
16
		String set = job.getParameters().get("set");
17
		if (set == null || set.isEmpty()) {
18
			set = ActionManagerWorkflowLauncher.ALL_SETS;
19
		}
20

  
21
		try {
22
			getActionManagerWorkflowLauncher().executeCommit(set, new Callable<String>() {
23
				@Override
24
				public String call() {
25
					handler.done(job);
26
					return "done";
27
				}
28
			}, new Callable<String>() {
29
				@Override
30
				public String call() {
31
					handler.failed(job, new ActionManagerException("MSRO Workwlow is failed"));
32
					return "failed";
33
				}
34
			});
35
		} catch (Exception e) {
36
			handler.failed(job, e);
37
		}
38

  
39
	}
40
}
modules/dnet-actionmanager-service/releases/1.0.3/src/main/java/eu/dnetlib/actionmanager/hack/StoreInfoPackageJobNode.java
1
package eu.dnetlib.actionmanager.hack;
2

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

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

  
8
import org.apache.commons.logging.Log;
9
import org.apache.commons.logging.LogFactory;
10
import org.apache.hadoop.hbase.client.HTable;
11
import org.dom4j.Document;
12
import org.dom4j.io.SAXReader;
13
import org.springframework.beans.factory.annotation.Required;
14

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

  
19
import eu.dnetlib.actionmanager.common.Agent;
20
import eu.dnetlib.actionmanager.common.Agent.AGENT_TYPE;
21
import eu.dnetlib.actionmanager.common.Operation;
22
import eu.dnetlib.actionmanager.common.Provenance;
23
import eu.dnetlib.actionmanager.hbase.HBaseActionManagerCore;
24
import eu.dnetlib.enabling.resultset.WorkflowCountingResultSetFactory;
25
import eu.dnetlib.enabling.resultset.client.ResultSetClientFactory;
26
import eu.dnetlib.workflow.AsyncJobNode;
27

  
28
public class StoreInfoPackageJobNode extends AsyncJobNode {
29

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

  
32
	private ResultSetClientFactory resultSetClientFactory;
33

  
34
	private HBaseActionManagerCore core;
35

  
36
	private String splitRuleId = "claimedMigration";
37

  
38
	private String defaultTrust;
39

  
40
	private WorkflowCountingResultSetFactory countingRSFactory;
41

  
42
	@Override
43
	protected void executeAsync(final Engine engine, final NodeToken token) {
44
		final SAXReader reader = new SAXReader();
45
		try {
46
			final HTable table = getTable();
47
			try {
48
				W3CEndpointReference epr = (W3CEndpointReference) token.getEnv().getTransientAttribute("epr");
49
				for (String record : resultSetClientFactory.getClient(getCountingRSFactory().createCountingResultSet(epr, token))) {
50
					// System.out.println("\n\nRECORD:\n\n" + record);
51

  
52
					Document doc = reader.read(new StringReader(record));
53
					String id = doc.valueOf("//*[local-name()='objIdentifier']");
54
					String user = doc.valueOf("//*[local-name()='user']");
55
					String nsprefix = doc.valueOf("//*[local-name()='datasourceprefix']");
56

  
57
					RequiredSet set = null;
58
					Provenance provenance = null;
59
					Operation operation = Operation.INSERT;
60
					Agent agent = null;
61
					if ((user != null) && !user.trim().isEmpty()) {
62
						agent = new Agent(user.trim(), user.trim(), AGENT_TYPE.human);
63
						if (id.startsWith("crossref____::")) {
64
							set = RequiredSet.userclaim_search_crossref;
65
							provenance = Provenance.user_claim_pid;
66
						} else if (id.startsWith("driver______::")) {
67
							set = RequiredSet.userclaim_search_driver;
68
							provenance = Provenance.user_claim_search;
69
						} else {
70
							log.warn("I can't assign set and provenance for id " + id);
71
							log.warn(record);
72
						}
73
					} else {
74
						log.warn("********* Missing user for record: " + id);
75
					}
76

  
77
					core.applyInfoPackageAction(splitRuleId, set.toString(), agent, operation, record, provenance, defaultTrust, nsprefix, table);
78
				}
79
				engine.complete(token, Arc.DEFAULT_ARC);
80
			} catch (Exception e) {
81
				log.error("Error storing EPR");
82
				failed(engine, token, e);
83
			} finally {
84
				table.flushCommits();
85
				table.close();
86
			}
87
		} catch (Throwable e) {
88
			log.error("Error storing EPR");
89
			failed(engine, token, e);
90
		}
91
	}
92

  
93
	private HTable getTable() throws IOException {
94
		return new HTable(core.getHbaseClient().getConfig(), core.getHbaseClient().getTableName());
95
	}
96

  
97
	public ResultSetClientFactory getResultSetClientFactory() {
98
		return resultSetClientFactory;
99
	}
100

  
101
	@Required
102
	public void setResultSetClientFactory(final ResultSetClientFactory resultSetClientFactory) {
103
		this.resultSetClientFactory = resultSetClientFactory;
104
	}
105

  
106
	public HBaseActionManagerCore getCore() {
107
		return core;
108
	}
109

  
110
	@Required
111
	public void setCore(final HBaseActionManagerCore core) {
112
		this.core = core;
113
	}
114

  
115
	public String getSplitRuleId() {
116
		return splitRuleId;
117
	}
118

  
119
	@Required
120
	public void setSplitRuleId(final String splitRuleId) {
121
		this.splitRuleId = splitRuleId;
122
	}
123

  
124
	public String getDefaultTrust() {
125
		return defaultTrust;
126
	}
127

  
128
	@Required
129
	public void setDefaultTrust(final String defaultTrust) {
130
		this.defaultTrust = defaultTrust;
131
	}
132

  
133
	public WorkflowCountingResultSetFactory getCountingRSFactory() {
134
		return countingRSFactory;
135
	}
136

  
137
	@Required
138
	public void setCountingRSFactory(final WorkflowCountingResultSetFactory countingRSFactory) {
139
		this.countingRSFactory = countingRSFactory;
140
	}
141

  
142
}
modules/dnet-actionmanager-service/releases/1.0.3/src/main/java/eu/dnetlib/actionmanager/hack/PerformSQLJobNode.java
1
package eu.dnetlib.actionmanager.hack;
2

  
3
import java.io.StringWriter;
4

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

  
7
import org.apache.commons.io.IOUtils;
8
import org.apache.commons.logging.Log;
9
import org.apache.commons.logging.LogFactory;
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.Engine;
15
import com.googlecode.sarasvati.NodeToken;
16

  
17
import eu.dnetlib.enabling.database.rmi.DatabaseService;
18
import eu.dnetlib.enabling.tools.ServiceLocator;
19
import eu.dnetlib.workflow.AsyncJobNode;
20

  
21
public class PerformSQLJobNode extends AsyncJobNode {
22

  
23
	private ServiceLocator<DatabaseService> dbServiceLocator;
24

  
25
	private String dbName;
26

  
27
	private Resource query;
28

  
29
	private Resource countQuery;
30

  
31
	private Resource xslt;
32

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

  
35
	@Override
36
	public void executeAsync(final Engine engine, final NodeToken token) {
37
		final StringWriter q = new StringWriter();
38
		final StringWriter cq = new StringWriter();
39
		final StringWriter xs = new StringWriter();
40

  
41
		try {
42
			IOUtils.copy(query.getInputStream(), q);
43
			IOUtils.copy(countQuery.getInputStream(), cq);
44
			IOUtils.copy(xslt.getInputStream(), xs);
45

  
46
			log.info("Executing query [" + q + "] on db " + dbName);
47
			W3CEndpointReference epr = getDbServiceLocator().getService().alternativeXsltSearchSQL(dbName, q.toString(), cq.toString(), xs.toString());
48
			log.info("Optained epr: " + epr);
49

  
50
			token.getEnv().setTransientAttribute("epr", epr);
51
			engine.complete(token, Arc.DEFAULT_ARC);
52
		} catch (Throwable e) {
53
			failed(engine, token, e);
54
		}
55
	}
56

  
57
	public String getDbName() {
58
		return dbName;
59
	}
60

  
61
	@Required
62
	public void setDbName(String dbName) {
63
		this.dbName = dbName;
64
	}
65

  
66
	public ServiceLocator<DatabaseService> getDbServiceLocator() {
67
		return dbServiceLocator;
68
	}
69

  
70
	@Required
71
	public void setDbServiceLocator(ServiceLocator<DatabaseService> dbServiceLocator) {
72
		this.dbServiceLocator = dbServiceLocator;
73
	}
74

  
75
	public Resource getQuery() {
76
		return query;
77
	}
78

  
79
	@Required
80
	public void setQuery(Resource query) {
81
		this.query = query;
82
	}
83

  
84
	public Resource getCountQuery() {
85
		return countQuery;
86
	}
87

  
88
	@Required
89
	public void setCountQuery(Resource countQuery) {
90
		this.countQuery = countQuery;
91
	}
92

  
93
	public Resource getXslt() {
94
		return xslt;
95
	}
96

  
97
	@Required
98
	public void setXslt(Resource xslt) {
99
		this.xslt = xslt;
100
	}
101

  
102
}
modules/dnet-actionmanager-service/releases/1.0.3/src/main/java/eu/dnetlib/actionmanager/hack/RequiredSet.java
1
package eu.dnetlib.actionmanager.hack;
2

  
3
public enum RequiredSet {
4
	userclaim_search_driver,
5
	userclaim_search_crossref,
6

  
7
	sysimport_mining_repository_pubmed,
8
	sysimport_mining_repository_arxiv,
9
	sysimport_mining_repository_isiWOS,
10
	sysimport_mining_repository_copernicus,
11
	sysimport_mining_repository_unknown
12
}
modules/dnet-actionmanager-service/releases/1.0.3/src/main/java/eu/dnetlib/actionmanager/hack/RegisterMissingSets.java
1
package eu.dnetlib.actionmanager.hack;
2

  
3
import org.springframework.beans.factory.annotation.Required;
4

  
5
import com.googlecode.sarasvati.Arc;
6
import com.googlecode.sarasvati.Engine;
7
import com.googlecode.sarasvati.NodeToken;
8

  
9
import eu.dnetlib.actionmanager.hbase.HBaseActionManagerCore;
10
import eu.dnetlib.actionmanager.set.ActionManagerSet;
11
import eu.dnetlib.workflow.AsyncJobNode;
12

  
13
public class RegisterMissingSets extends AsyncJobNode {
14

  
15
	private HBaseActionManagerCore core;
16

  
17
	@Override
18
	protected void executeAsync(Engine engine, NodeToken token) {
19
		try {
20
			for (RequiredSet rs : RequiredSet.values()) {
21
				String set = rs.toString();
22
				if (!core.getInformationServiceClient().existsSet(set.toString())) {
23
					core.getInformationServiceClient().registerSetProfile(new ActionManagerSet(set, set));
24
				}
25
			}
26
			engine.complete(token, Arc.DEFAULT_ARC);
27
		} catch (Throwable e) {
28
			failed(engine, token, e);
29
		}
30
	}
31

  
32
	public HBaseActionManagerCore getCore() {
33
		return core;
34
	}
35

  
36
	@Required
37
	public void setCore(HBaseActionManagerCore core) {
38
		this.core = core;
39
	}
40

  
41
}
modules/dnet-actionmanager-service/releases/1.0.3/src/main/java/eu/dnetlib/actionmanager/inspector/ActionManagerController.java
1
package eu.dnetlib.actionmanager.inspector;
2

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

  
7
import javax.annotation.Resource;
8

  
9
import org.springframework.stereotype.Controller;
10
import org.springframework.ui.ModelMap;
11
import org.springframework.web.bind.annotation.ModelAttribute;
12
import org.springframework.web.bind.annotation.RequestMapping;
13
import org.springframework.web.bind.annotation.RequestParam;
14

  
15
import com.google.common.base.Function;
16
import com.google.common.collect.Lists;
17
import com.google.common.collect.Maps;
18

  
19
import eu.dnetlib.actionmanager.ActionManagerConstants.ACTION_TYPE;
20
import eu.dnetlib.actionmanager.common.Agent;
21
import eu.dnetlib.actionmanager.common.Agent.AGENT_TYPE;
22
import eu.dnetlib.actionmanager.common.Operation;
23
import eu.dnetlib.actionmanager.common.Provenance;
24
import eu.dnetlib.actionmanager.hbase.HBaseActionManagerCore;
25
import eu.dnetlib.actionmanager.set.ActionManagerSet;
26
import eu.dnetlib.actionmanager.wf.ActionManagerWorkflowLauncher;
27
import eu.dnetlib.enabling.inspector.AbstractInspectorController;
28

  
29
@Controller
30
public class ActionManagerController extends AbstractInspectorController {
31

  
32
	private static final int DEFAULT_PAGE_SIZE = 10;
33

  
34
	@Resource
35
	private HBaseActionManagerCore core;
36

  
37
	@Resource
38
	private ActionManagerWorkflowLauncher actionManagerWorkflowLauncher;
39

  
40
	@ModelAttribute(value = "types")
41
	public ACTION_TYPE[] listActionTypes() {
42
		return ACTION_TYPE.values();
43
	}
44

  
45
	@ModelAttribute(value = "provenances")
46
	public Provenance[] listProvenances() {
47
		return Provenance.values();
48
	}
49

  
50
	@ModelAttribute(value = "sets")
51
	public List<ActionManagerSet> listSets() {
52
		return core.listAvailableSets();
53
	}
54

  
55
	@RequestMapping("/inspector/actions/listActions.do")
56
	public String listActions(
57
			final ModelMap map,
58
			@RequestParam(value = "type", required = false) String stype,
59
			@RequestParam(value = "start", required = false) String start) throws Exception {
60

  
61
		ACTION_TYPE type = (stype == null) ? ACTION_TYPE.all : ACTION_TYPE.valueOf(stype);
62
		String prefix = (type == ACTION_TYPE.all) ? null : type + "|";
63
		map.addAttribute("type", type);
64

  
65
		List<Map<String, String>> actions = core.getHbaseClient().retrieveRows(prefix, start, DEFAULT_PAGE_SIZE + 1);
66

  
67
		int size = actions.size();
68
		if (size > DEFAULT_PAGE_SIZE) {
69
			map.addAttribute("next", actions.remove(size - 1).get("rowId"));
70
		}
71

  
72
		map.addAttribute("actions", Lists.transform(actions, new Function<Map<String, String>, Map<String, Object>>() {
73
			@Override
74
			public Map<String, Object> apply(Map<String, String> map) {
75
				return formatAction(map);
76
			}
77
		}));
78

  
79
		String template;
80

  
81
		switch (type) {
82
		case aac:
83
			template = "listAtomicActions";
84
			break;
85
		case pkg:
86
			template = "listInfoPackages";
87
			break;
88
		default:
89
			template = "listAll";
90
			break;
91
		}
92

  
93
		return "inspector/actions/" + template;
94
	}
95

  
96
	@SuppressWarnings("unchecked")
97
	private Map<String, Object> formatAction(Map<String, String> map) {
98
		Map<String, Object> res = Maps.newHashMap();
99
		for (String key : map.keySet()) {
100
			if (key.equals("rowId")) {
101
				res.put("rowId", map.get(key));
102
			} else if (key.startsWith("date:")) {
103
				res.put("date", map.get(key));
104
			} else if (key.startsWith("set:")) {
105
				res.put("set", map.get(key));
106
			} else if (key.startsWith("operation:")) {
107
				res.put("operation", map.get(key));
108
			} else if (key.endsWith(":" + ACTION_TYPE.pkg)) {
109
				res.put("infoPackage", map.get(key).replaceAll("<", "&lt;").replaceAll(">", "&gt;"));
110
			} else if (key.startsWith("rel:")) {
111
				String nk = map.get(key).trim();
112
				if (!res.containsKey(nk)) {
113
					res.put(nk, new ArrayList<String>());
114
				}
115
				((List<String>) res.get(nk)).add(key.substring(4));
116
			} else if (key.startsWith("target:")) {
117
				res.put(key.replaceAll(":", "_"), map.get(key));
118
			} else {
119
				res.put(key, map.get(key));
120
			}
121
		}
122
		return res;
123
	}
124

  
125
	@RequestMapping("/inspector/actions/registerInfoPackage.do")
126
	public void registerInfoPackage(
127
			final ModelMap map,
128
			@RequestParam(value = "ruleId", required = false) String ruleId,
129
			@RequestParam(value = "set", required = false) String set,
130
			@RequestParam(value = "infoPackage", required = false) String infoPackage,
131
			@RequestParam(value = "provenance", required = false) String provenance,
132
			@RequestParam(value = "trust", required = false) String trust,
133
			@RequestParam(value = "nsprefix", required = false) String nsprefix) throws Exception {
134

  
135
		if (ruleId != null && !ruleId.isEmpty() && set != null && !set.isEmpty() && infoPackage != null && !infoPackage.isEmpty() && trust != null
136
				&& !trust.isEmpty() && provenance != null && !provenance.isEmpty() && nsprefix != null && !nsprefix.isEmpty()
137
				&& core.getActionFactory().getXslts().containsKey(ruleId)) {
138

  
139
			Agent agent = new Agent();
140
			agent.setId("inspector");
141
			agent.setName("inspector");
142
			agent.setType(AGENT_TYPE.human);
143

  
144
			int n = core.applyInfoPackageAction(ruleId, set, agent, Operation.INSERT, infoPackage, Provenance.convert(provenance), trust, nsprefix);
145
			map.addAttribute("message", "1 infoPackageAction + " + (n - 1) + " atomicAction(s) registered");
146
		}
147

  
148
		map.addAttribute("rules", core.getActionFactory().getXslts().keySet());
149
		map.addAttribute("ruleId", ruleId);
150
		map.addAttribute("set", set);
151
		map.addAttribute("infoPackage", infoPackage);
152
		map.addAttribute("trust", trust);
153
		map.addAttribute("nsprefix", nsprefix);
154
	}
155

  
156
	@RequestMapping("/inspector/actions/deleteInfoPackage.do")
157
	public String deleteInfoPackage(final ModelMap map, @RequestParam(value = "id", required = false) String id) throws Exception {
158
		core.deleteInfoPackageAction(id);
159
		return "redirect:listActions.do?type=" + ACTION_TYPE.pkg;
160
	}
161

  
162
	@RequestMapping("/inspector/actions/bulkdelete.do")
163
	public void clear(final ModelMap map, @RequestParam(value = "set", required = false) String set) throws Exception {
164
		map.addAttribute("allSets", ActionManagerWorkflowLauncher.ALL_SETS);
165
		if (set != null && !set.isEmpty()) {
166
			actionManagerWorkflowLauncher.executeDelete(set, null, null);
167
			map.addAttribute("message", "Workflow started !!!");
168
		}
169
	}
170

  
171
	@RequestMapping("/inspector/actions/commit.do")
172
	public void commit(final ModelMap map, @RequestParam(value = "set", required = false) String set) throws Exception {
173
		map.addAttribute("allSets", ActionManagerWorkflowLauncher.ALL_SETS);
174
		if (set != null && !set.isEmpty()) {
175
			actionManagerWorkflowLauncher.executeCommit(set, null, null);
176
			map.addAttribute("message", "Workflow started !!!");
177
		}
178
	}
179

  
180
	@RequestMapping("/inspector/actions/createSet.do")
181
	public void createSet(
182
			final ModelMap map,
183
			@RequestParam(value = "id", required = false) String id,
184
			@RequestParam(value = "name", required = false) String name) throws Exception {
185
		if (id != null && name != null && !id.isEmpty() && !name.isEmpty()) {
186
			core.getInformationServiceClient().registerSetProfile(new ActionManagerSet(id, name));
187
		}
188
		map.addAttribute("sets", core.listAvailableSets());
189
	}
190
}
modules/dnet-actionmanager-service/releases/1.0.3/src/main/java/eu/dnetlib/actionmanager/ActionManagerServiceImpl.java
1
package eu.dnetlib.actionmanager;
2

  
3
import java.util.List;
4

  
5
import javax.jws.WebParam;
6

  
7
import org.springframework.beans.factory.annotation.Required;
8

  
9
import eu.dnetlib.actionmanager.common.Agent;
10
import eu.dnetlib.actionmanager.common.Operation;
11
import eu.dnetlib.actionmanager.common.Provenance;
12
import eu.dnetlib.actionmanager.hbase.HBaseActionManagerCore;
13
import eu.dnetlib.actionmanager.rmi.ActionManagerException;
14
import eu.dnetlib.actionmanager.rmi.ActionManagerService;
15
import eu.dnetlib.actionmanager.set.ActionManagerSet;
16
import eu.dnetlib.enabling.tools.AbstractBaseService;
17
import eu.dnetlib.enabling.tools.blackboard.NotificationHandler;
18

  
19
public class ActionManagerServiceImpl extends AbstractBaseService implements ActionManagerService {
20

  
21
	private HBaseActionManagerCore core;
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff