Project

General

Profile

1
package eu.dnetlib.data.actionmanager.is;
2

    
3
import java.io.StringReader;
4
import java.util.List;
5
import java.util.NoSuchElementException;
6
import java.util.Set;
7
import javax.annotation.Resource;
8
import javax.xml.ws.Endpoint;
9

    
10
import com.google.common.collect.Iterables;
11
import com.google.common.collect.Lists;
12
import com.google.common.collect.Sets;
13

    
14
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
15
import eu.dnetlib.miscutils.datetime.DateUtils;
16
import eu.dnetlib.rmi.data.actionmanager.ActionManagerException;
17
import eu.dnetlib.rmi.data.actionmanager.ActionManagerSet;
18
import eu.dnetlib.rmi.data.actionmanager.ActionManagerSet.ImpactTypes;
19
import eu.dnetlib.rmi.data.actionmanager.RawSet;
20
import eu.dnetlib.rmi.enabling.ISLookUpException;
21
import eu.dnetlib.rmi.enabling.ISLookUpService;
22
import eu.dnetlib.rmi.enabling.ISRegistryException;
23
import eu.dnetlib.rmi.enabling.ISRegistryService;
24
import eu.dnetlib.soap.EndpointReferenceBuilder;
25
import org.antlr.stringtemplate.StringTemplate;
26
import org.apache.commons.logging.Log;
27
import org.apache.commons.logging.LogFactory;
28
import org.dom4j.Attribute;
29
import org.dom4j.Document;
30
import org.dom4j.Element;
31
import org.dom4j.io.SAXReader;
32
import org.springframework.beans.factory.annotation.Required;
33

    
34
public class ISClient {
35

    
36
	private static final Log log = LogFactory.getLog(ISClient.class); // NOPMD by marko on 11/24/08 5:02 PM
37
	@Resource
38
	private UniqueServiceLocator serviceLocator;
39
	/**
40
	 * Template for ActionManagerSet profiles
41
	 */
42
	private StringTemplate actionManagerSetDsTemplate;
43
	/**
44
	 * service endpoint.
45
	 */
46
	private Endpoint endpoint;
47
	/**
48
	 * endpoint builder.
49
	 */
50
	private EndpointReferenceBuilder<Endpoint> eprBuilder;
51

    
52
	public String registerSetProfile(final ActionManagerSet set) throws ActionManagerException {
53
		if (existsSet(set.getId())) { throw new ActionManagerException("Set " + set.getId() + " already registered"); }
54
		try {
55
			StringTemplate template = new StringTemplate(actionManagerSetDsTemplate.getTemplate());
56
			template.setAttribute("serviceUri", eprBuilder.getAddress(endpoint));
57
			template.setAttribute("set", set);
58
			template.setAttribute("latest", RawSet.newInstance());
59
			return serviceLocator.getService(ISRegistryService.class).registerProfile(template.toString());
60
		} catch (ISRegistryException e) {
61
			throw new ActionManagerException("Error registering set " + set, e);
62
		}
63
	}
64

    
65
	public List<ActionManagerSet> listSets() throws ActionManagerException {
66
		final String q = "for $x in collection('/db/DRIVER/ActionManagerSetDSResources/ActionManagerSetDSResourceType') return $x";
67
		return getActionManagerSets(q);
68
	}
69

    
70
	public List<ActionManagerSet> listValidSets() throws ActionManagerException {
71
		final String q = "for $x in collection('/db/DRIVER/ActionManagerSetDSResources/ActionManagerSetDSResourceType') \n"
72
				+ "where string-length($x//RAW_SETS/LATEST/@id/string()) > 0\n"
73
				+ "return $x";
74

    
75
		return getActionManagerSets(q);
76
	}
77

    
78
	private List<ActionManagerSet> getActionManagerSets(final String q) throws ActionManagerException {
79
		final List<ActionManagerSet> list = Lists.newArrayList();
80

    
81
		try {
82
			final String basePath = getBasePathHDFS();
83
			for (String s : serviceLocator.getService(ISLookUpService.class).quickSearchProfile(q)) {
84
				list.add(getActionManagerSet(basePath, s));
85
			}
86
		} catch (ISLookUpException e) {
87
			log.error("Error accessing Sets, using query: " + q);
88
		}
89
		return list;
90
	}
91

    
92
	public ActionManagerSet getSet(final String setId) throws ActionManagerException, ISLookUpException {
93
		final String q = "for $x in collection('/db/DRIVER/ActionManagerSetDSResources/ActionManagerSetDSResourceType') "
94
				+ "where $x//SET/@id = '" + setId + "' return $x";
95

    
96
		try {
97
			final String basePath = getBasePathHDFS();
98
			final String setProfile = serviceLocator.getService(ISLookUpService.class).getResourceProfileByQuery(q);
99
			return getActionManagerSet(basePath, setProfile);
100
		} catch (ISLookUpException e) {
101
			throw new ActionManagerException("Error accessing Sets, using query: " + q);
102
		}
103
	}
104

    
105
	private ActionManagerSet getActionManagerSet(final String basePath, final String profile) throws ActionManagerException {
106
		final SAXReader reader = new SAXReader();
107
		final ActionManagerSet set = new ActionManagerSet();
108

    
109
		try {
110
			final Document doc = reader.read(new StringReader(profile));
111

    
112
			set.setId(doc.valueOf("//SET/@id").trim());
113
			set.setName(doc.valueOf("//SET").trim());
114
			set.setImpact(ImpactTypes.valueOf(doc.valueOf("//IMPACT").trim()));
115
			set.setLatest(doc.valueOf("//RAW_SETS/LATEST/@id"), doc.valueOf("//RAW_SETS/LATEST/@creationDate"), doc.valueOf("//RAW_SETS/LATEST/@lastUpdate"));
116
			set.setDirectory(doc.valueOf("//SET/@directory"));
117
			final List expiredNodes = doc.selectNodes("//RAW_SETS/EXPIRED");
118
			if (expiredNodes != null) {
119
				for (int i = 0; i < expiredNodes.size(); i++) {
120
					Element ex = (Element) expiredNodes.get(i);
121
					set.addExpired(ex.attributeValue("id"), ex.attributeValue("creationDate"), ex.attributeValue("lastUpdate"));
122
				}
123
			}
124

    
125
			final StringBuilder sb = new StringBuilder();
126
			sb.append(basePath);
127
			sb.append("/");
128
			sb.append(doc.valueOf("//SET/@directory"));
129
			sb.append("/");
130
			sb.append(doc.valueOf("//RAW_SETS/LATEST/@id"));
131
			set.setPathToLatest(sb.toString());
132

    
133
			return set;
134
		} catch (Exception e) {
135
			throw new ActionManagerException("Error creating set from profile: " + profile, e);
136
		}
137
	}
138

    
139
	public boolean deleteSetProfile(final String setId) throws ActionManagerException {
140
		final String q = "for $x in collection('/db/DRIVER/ActionManagerSetDSResources/ActionManagerSetDSResourceType') where $x//SET/@id = '" + setId
141
				+ "' return $x//RESOURCE_IDENTIFIER/@value/string()";
142

    
143
		try {
144
			final String profId = serviceLocator.getService(ISLookUpService.class).getResourceProfileByQuery(q);
145
			return serviceLocator.getService(ISRegistryService.class).deleteProfile(profId);
146
		} catch (Exception e) {
147
			log.error("Error deleting set " + setId, e);
148
			throw new ActionManagerException("Error deleting set " + setId, e);
149
		}
150
	}
151

    
152
	public boolean existsSet(final String id) throws ActionManagerException {
153
		final String q = "for $x in collection('/db/DRIVER/ActionManagerSetDSResources/ActionManagerSetDSResourceType') where $x//SET/@id = '" + id
154
				+ "' return $x";
155
		try {
156
			return !serviceLocator.getService(ISLookUpService.class).quickSearchProfile(q).isEmpty();
157
		} catch (ISLookUpException e) {
158
			log.error("Error accessing Sets, using query: " + q, e);
159
			throw new ActionManagerException("Error running xquery: " + q, e);
160
		}
161
	}
162

    
163
	public boolean existsRawSet(final String id) throws ActionManagerException {
164
		final String q = "for $x in collection('/db/DRIVER/ActionManagerSetDSResources/ActionManagerSetDSResourceType') where $x//RAW_SETS/*/@id = '" + id
165
				+ "' return $x";
166
		try {
167
			return !serviceLocator.getService(ISLookUpService.class).quickSearchProfile(q).isEmpty();
168
		} catch (ISLookUpException e) {
169
			log.error("Error accessing RawSets, using query: " + q, e);
170
			throw new ActionManagerException("Error running xquery: " + q, e);
171
		}
172
	}
173

    
174
	public Set<String> listValidRawSets() throws ActionManagerException {
175
		final String q = "for $x in collection('/db/DRIVER/ActionManagerSetDSResources/ActionManagerSetDSResourceType') return $x//RAW_SETS/LATEST/@id/string()";
176
		try {
177
			final List<String> list = serviceLocator.getService(ISLookUpService.class).quickSearchProfile(q);
178
			return Sets.newHashSet(list);
179
		} catch (Exception e) {
180
			log.error("Error running xquery: " + q, e);
181
			throw new ActionManagerException("Error running xquery: " + q, e);
182
		}
183
	}
184

    
185
	public RawSet geLatestRawSet(final String set) throws ActionManagerException {
186
		final String q = "for $x in collection('/db/DRIVER/ActionManagerSetDSResources/ActionManagerSetDSResourceType') where $x//SET/@id = '" + set
187
				+ "' return concat(' ' , $x//RAW_SETS/LATEST/@id, ' @@@ ', $x//RAW_SETS/LATEST/@creationDate, ' @@@ ', $x//RAW_SETS/LATEST/@lastUpdate, ' ')";
188
		try {
189
			String[] arr = serviceLocator.getService(ISLookUpService.class).getResourceProfileByQuery(q).split("@@@");
190
			return RawSet.newInstance(arr[0].trim(), arr[1].trim(), arr[2].trim());
191
		} catch (ISLookUpException e) {
192
			log.error("Error accessing Sets, using query: " + q, e);
193
			throw new ActionManagerException("Error running xquery: " + q, e);
194
		}
195
	}
196

    
197
	public String getGarbageTimeMargin() throws ActionManagerException {
198
		return queryServiceProperty("garbageTimeMargin");
199
	}
200

    
201
	public String getBasePathHDFS() throws ActionManagerException {
202
		return queryServiceProperty("basePath");
203
	}
204

    
205
	public String getGarbageRetainThreshold() throws ActionManagerException {
206
		return queryServiceProperty("garbageRetainThreshold");
207
	}
208

    
209
	private String queryServiceProperty(final String propertyName) throws ActionManagerException {
210
		final String q = "for $x in /RESOURCE_PROFILE[.//RESOURCE_TYPE/@value='ActionManagerServiceResourceType'] return $x//SERVICE_PROPERTIES/PROPERTY[./@ key='"
211
				+ propertyName + "']/@value/string()";
212
		log.debug("quering for service property: " + q);
213
		try {
214
			final List<String> value = serviceLocator.getService(ISLookUpService.class).quickSearchProfile(q);
215
			return Iterables.getOnlyElement(value);
216
		} catch (ISLookUpException e) {
217
			String msg = "Error accessing service profile, using query: " + q;
218
			log.error(msg, e);
219
			throw new ActionManagerException(msg, e);
220
		} catch (NoSuchElementException e) {
221
			String msg = "missing service property: " + propertyName;
222
			log.error(msg, e);
223
			throw new ActionManagerException(msg, e);
224
		} catch (IllegalArgumentException e) {
225
			String msg = "found more than one service property: " + propertyName;
226
			log.error(msg, e);
227
			throw new ActionManagerException(msg, e);
228
		}
229
	}
230

    
231
	public void addLatestRawSet(final String set, final RawSet rawSet) throws ActionManagerException {
232
		final String q = "for $x in collection('/db/DRIVER/ActionManagerSetDSResources/ActionManagerSetDSResourceType') where $x//SET/@id = '" + set
233
				+ "' return $x";
234
		try {
235
			final String profile = serviceLocator.getService(ISLookUpService.class).getResourceProfileByQuery(q);
236
			final Document doc = new SAXReader().read(new StringReader(profile));
237
			final String profId = doc.valueOf("//RESOURCE_IDENTIFIER/@value");
238
			final Element latest = (Element) doc.selectSingleNode("//RAW_SETS/LATEST");
239
			final Element expired = ((Element) doc.selectSingleNode("//RAW_SETS")).addElement("EXPIRED");
240

    
241
			for (Object o : latest.attributes()) {
242
				final Attribute a = (Attribute) o;
243
				expired.addAttribute(a.getName(), a.getValue());
244
			}
245

    
246
			latest.addAttribute("id", rawSet.getId());
247
			latest.addAttribute("creationDate", rawSet.getCreationDate());
248
			latest.addAttribute("lastUpdate", rawSet.getLastUpdate());
249

    
250
			serviceLocator.getService(ISRegistryService.class).updateProfile(profId, doc.asXML(), "ActionManagerSetDSResourceType");
251
		} catch (Exception e) {
252
			log.error("Error updating profile of set: " + set);
253
			throw new ActionManagerException("Error running xquery: " + q, e);
254
		}
255
	}
256

    
257
	public void updateLastUpdate(final String rawSet) throws ActionManagerException {
258
		final String q = "for $x in collection('/db/DRIVER/ActionManagerSetDSResources/ActionManagerSetDSResourceType')//RAW_SETS/*[@id='" + rawSet
259
				+ "']/@lastUpdate return update replace $x with '" + DateUtils.now_ISO8601() + "'";
260

    
261
		try {
262
			serviceLocator.getService(ISRegistryService.class).executeXUpdate(q);
263
		} catch (Exception e) {
264
			log.error("Error updating lastUpdate using query: " + q, e);
265
			throw new ActionManagerException("Error updating lastUpdate using query: " + q, e);
266
		}
267
	}
268

    
269
	public StringTemplate getActionManagerSetDsTemplate() {
270
		return actionManagerSetDsTemplate;
271
	}
272

    
273
	@Required
274
	public void setActionManagerSetDsTemplate(final StringTemplate actionManagerSetDsTemplate) {
275
		this.actionManagerSetDsTemplate = actionManagerSetDsTemplate;
276
	}
277

    
278
	public Endpoint getEndpoint() {
279
		return endpoint;
280
	}
281

    
282
	@Required
283
	public void setEndpoint(final Endpoint endpoint) {
284
		this.endpoint = endpoint;
285
	}
286

    
287
	public EndpointReferenceBuilder<Endpoint> getEprBuilder() {
288
		return eprBuilder;
289
	}
290

    
291
	@Required
292
	public void setEprBuilder(final EndpointReferenceBuilder<Endpoint> eprBuilder) {
293
		this.eprBuilder = eprBuilder;
294
	}
295

    
296
}
    (1-1/1)