Skip to Content.
Sympa Menu

perfsonar-dev - [pS-dev] [GEANT/SA2/ps-java-services] r6138 - in trunk/psBase3/perfsonar-base: . src/main/java/net/geant/perfsonar src/main/java/net/geant/perfsonar/base src/main/java/net/geant/perfsonar/xpath src/test/java/net/geant/perfsonar src/test/java/net/geant/perfsonar/helpers src/test/java/net/geant/perfsonar/mp/sshtelnet src/test/resources

Subject: perfsonar development work

List archive

[pS-dev] [GEANT/SA2/ps-java-services] r6138 - in trunk/psBase3/perfsonar-base: . src/main/java/net/geant/perfsonar src/main/java/net/geant/perfsonar/base src/main/java/net/geant/perfsonar/xpath src/test/java/net/geant/perfsonar src/test/java/net/geant/perfsonar/helpers src/test/java/net/geant/perfsonar/mp/sshtelnet src/test/resources


Chronological Thread 
  • From:
  • To:
  • Subject: [pS-dev] [GEANT/SA2/ps-java-services] r6138 - in trunk/psBase3/perfsonar-base: . src/main/java/net/geant/perfsonar src/main/java/net/geant/perfsonar/base src/main/java/net/geant/perfsonar/xpath src/test/java/net/geant/perfsonar src/test/java/net/geant/perfsonar/helpers src/test/java/net/geant/perfsonar/mp/sshtelnet src/test/resources
  • Date: Thu, 14 Feb 2013 15:16:46 +0000 (GMT)
  • Authentication-results: sfpop-ironport01.merit.edu; dkim=neutral (message not signed) header.i=none

Author: psnc.pietrzak
Date: 2013-02-14 15:16:46 +0000 (Thu, 14 Feb 2013)
New Revision: 6138

Added:

trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/LSRegistrationTask.java
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/Logger.java

trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/LSRegistrationTest.java

trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/helpers/MockLSService.java

trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/mp/sshtelnet/ConfigurationFileChecker.java
Modified:
trunk/psBase3/perfsonar-base/pom.xml

trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/Configuration.java

trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/PerfSONAR.java

trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/base/Scheduler.java

trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/xpath/Helper.java

trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/xpath/XPathConfiguration.java

trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/xpath/XPathDeserializer.java

trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/PerfSONARTest.java

trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/SSHTelnetMPWebServiceTest.java

trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/mp/sshtelnet/SSHTelnetMPService.java
trunk/psBase3/perfsonar-base/src/test/resources/configuration.xml
Log:
Extracted LS registration from PerfSONAR class to separate classes.

Modified: trunk/psBase3/perfsonar-base/pom.xml
===================================================================
--- trunk/psBase3/perfsonar-base/pom.xml 2013-02-13 13:53:57 UTC (rev
6137)
+++ trunk/psBase3/perfsonar-base/pom.xml 2013-02-14 15:16:46 UTC (rev
6138)
@@ -135,19 +135,4 @@
</plugin>
</plugins>
</build>
-
- <distributionManagement>
- <repository>
- <id>geant-developers-repository</id>
- <name>perfSONAR repository</name>
-
<url>scpexe:///repo</url>
- <uniqueVersion>false</uniqueVersion>
- </repository>
- <snapshotRepository>
- <id>geant-developers-repository</id>
- <name>perfSONAR snapshots repository</name>
-
<url>scpexe:///snapshots-repo</url>
- <uniqueVersion>false</uniqueVersion>
- </snapshotRepository>
- </distributionManagement>
</project>

Modified:
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/Configuration.java
===================================================================
---
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/Configuration.java
2013-02-13 13:53:57 UTC (rev 6137)
+++
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/Configuration.java
2013-02-14 15:16:46 UTC (rev 6138)
@@ -1,16 +1,11 @@
package net.geant.perfsonar;

import java.lang.reflect.Method;
-import java.util.ArrayList;
import java.util.Hashtable;
-import java.util.List;
import java.util.Map;

-import net.geant.perfsonar.xpath.Helper;
-
/**
- * Represents configuration necessary for handling requests and registering
to
- * Lookup Service.
+ * Represents configuration necessary for handling requests.
*
* It consists of a set of static methods to improve the readability of the
code.
* Please static import all the methods from the class.
@@ -32,19 +27,12 @@
* Controller methods may contain zero or one parameters. If they contain a
parameter then
* in order to compile an argument must be passed. Method any provide
compiler friendly
* implementation. As an argument one provide type of the argument.
- *
- * In order to configure the handler for the Lookup Service registration the
following
- * code snippet must be used:
- *
<code>configure(registerToLookupService(ServiceController.class).details())</code>
- *
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
public class Configuration {
private static Method method;
private static String type;
private static Map<String, Method> handlers = new Hashtable<String,
Method>();
- private static int lsInterval = 60 * 60;
- private static List<String> lsAddresses = new ArrayList<String>();

/**
* Method used for configuration of handlers. It ensures on the
compile time phase
@@ -89,32 +77,4 @@
method = null;
handlers.clear();
}
-
- /**
- * Sets timeout between subsequent registrations/keepalives to Lookup
Service.
- */
- public void setLookupServiceInterval(String interval) {
- Configuration.lsInterval = Integer.parseInt(interval);
- }
-
- /**
- * Returns timeout between subsequent registrations/keepalives to
Lookup Service.
- */
- public static int getLSInterval() {
- return Configuration.lsInterval;
- }
-
- public static <T> T registerToLookupService(Class<T> controller) {
- return Helper.createMock(controller, new HandlerConfiguration(
- "LSRegister"));
- }
-
- public static List<String> getLSAddresses() {
- return lsAddresses;
- }
-
- public static void addLSAddress(String address) {
- if (!lsAddresses.contains(address))
- lsAddresses.add(address);
- }
}

Added:
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/LSRegistrationTask.java
===================================================================
---
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/LSRegistrationTask.java
(rev 0)
+++
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/LSRegistrationTask.java
2013-02-14 15:16:46 UTC (rev 6138)
@@ -0,0 +1,150 @@
+package net.geant.perfsonar;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.io.Writer;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.namespace.QName;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.ws.Dispatch;
+import javax.xml.ws.Service;
+import javax.xml.ws.soap.SOAPBinding;
+
+import net.geant.perfsonar.nmwg.response.TemplateEngine;
+import net.geant.perfsonar.xpath.Helper;
+import net.geant.perfsonar.xpath.XPathDeserializer;
+
+import org.xml.sax.InputSource;
+
+/**
+ * Registers a service to Lookup Service.
+ * If the service is already registered (key was returned from LS
successfully) it sends keepalive messages.
+ * It uses LSRegister.template template found in the directory where the
controller method that provides data for registration is defined.
+ *
+ * In order to configure the handler for the Lookup Service registration the
following
+ * code snippet must be used:
+ *
<code>configure(registerToLookupService(ServiceController.class).details())</code>
+ * where configure method belongs to Configuration class.
+ *
+ * @author <a
href="mailto:">Blazej
Pietrzak</a>
+ */
+public class LSRegistrationTask implements Runnable {
+
+ private static List<String> lsAddresses = new ArrayList<String>();
+
+ public List<String> getLSAddresses() {
+ return lsAddresses;
+ }
+
+ public void addLSAddress(String address) {
+ if (address == null)
+ return;
+
+ if (!lsAddresses.contains(address))
+ lsAddresses.add(address);
+ }
+
+ public static <T> T registerToLookupService(Class<T> controller) {
+ return Helper.createMock(controller, new HandlerConfiguration(
+ "LSRegister"));
+ }
+
+ private Map<String, String> keys = new Hashtable<String, String>();
+ private Logger logger;
+ private PerfSONAR service;
+
+ public LSRegistrationTask(Logger logger, PerfSONAR service) {
+ this.logger = logger;
+ this.service = service;
+ }
+
+ public LSRegistrationTask() {
+ this(null, null);
+ }
+
+ public void run() {
+ for (String address : getLSAddresses()) {
+ try {
+ registerToLookupService(address);
+ } catch (Exception ex) {
+ logger.error("Could not register to Lookup
Service at: " + address, ex);
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ protected synchronized void registerToLookupService(final String
address) throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, InstantiationException, IOException {
+ final Method m = Configuration.getHandler("LSRegister");
+ if (m == null)
+ return;
+
+ final PipedInputStream in = new PipedInputStream();
+ final PipedOutputStream out = new PipedOutputStream(in);
+
service.getScheduler().runInParallel(createLSMessageTask(address, m, out));
+
+ if (keys.get(address) == null) {
+ final XPathDeserializer deserializer = new
XPathDeserializer();
+ final NMWGMessage msg;
+ try {
+ msg =
deserializer.getObjects(NMWGMessage.class, (List<Object>)
deserializer.deserialize(new InputSource(getLSClient(address).invoke(new
StreamSource(in)).getInputStream()))).get(0);
+ if (msg.getKey() != null) {
+ keys.put(address, msg.getKey());
+ }
+ } catch (Exception e) {
+ logger.error("Could not deserialize key from
Lookup Service response.", e);
+ }
+ } else
+ getLSClient(address).invoke(new StreamSource(in));
+ }
+
+ private Runnable createLSMessageTask(final String address, final
Method m, final OutputStream out) {
+ return new Runnable() {
+
+ private final Writer writer = new
OutputStreamWriter(out);
+
+ public void run() {
+ try {
+ if (keys.get(address) == null) {
+
TemplateEngine.put("requestId", "request1");
+ TemplateEngine.put("result",
m.invoke(m.getDeclaringClass().newInstance()));
+ TemplateEngine.put("service",
service);
+
TemplateEngine.evaluate(writer, m.getDeclaringClass(), "LSRegister.template");
+ } else {
+
writer.write(getKeepAliveMessage(keys.get(address)));
+ }
+ writer.flush();
+ writer.close();
+ out.close();
+ } catch (Exception ex) {
+ logger.error("Could not register in
LookupService.", ex);
+ }
+ }
+
+ private String getKeepAliveMessage(String key) {
+ return "<?xml version='1.0'
encoding='UTF-8'?>"
+ + "<nmwg:message id='request1'
type='LSKeepaliveRequest' xmlns:nmwg='http://ggf.org/ns/nmwg/base/2.0/'>"
+ + "<nmwg:metadata
id='key_to_keepalive'><nmwg:key>" + key + "</nmwg:key></nmwg:metadata>"
+ + "<nmwg:data id='d1'
metadataIdRef='key_to_keepalive' />"
+ + "</nmwg:message>\n";
+ }
+ };
+ }
+
+ private Dispatch<StreamSource> getLSClient(final String address) {
+ final String NAMESPACE = "http://base3.perfsonar.geant.net/";;
+ final QName PORT = new QName(NAMESPACE, "PerfSONARPort");
+ final Service service = Service.create(new QName(NAMESPACE,
"PerfSONARService"));
+ service.addPort(PORT, SOAPBinding.SOAP11HTTP_BINDING,
address);
+ final Dispatch<StreamSource> client =
service.createDispatch(PORT, StreamSource.class, Service.Mode.PAYLOAD);
+ return client;
+ }
+}

Added:
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/Logger.java
===================================================================
---
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/Logger.java
(rev 0)
+++
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/Logger.java
2013-02-14 15:16:46 UTC (rev 6138)
@@ -0,0 +1,6 @@
+package net.geant.perfsonar;
+
+public interface Logger {
+
+ void error(String message, Throwable ex);
+}

Modified:
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/PerfSONAR.java
===================================================================
---
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/PerfSONAR.java
2013-02-13 13:53:57 UTC (rev 6137)
+++
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/PerfSONAR.java
2013-02-14 15:16:46 UTC (rev 6138)
@@ -5,29 +5,20 @@
import static net.geant.perfsonar.xpath.XPathDeserializer.whenXPath;

import java.io.IOException;
-import java.io.OutputStreamWriter;
-import java.io.PipedInputStream;
-import java.io.PipedOutputStream;
import java.io.StringReader;
import java.io.StringWriter;
-import java.io.Writer;
-import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;

-import javax.xml.namespace.QName;
import javax.xml.transform.stream.StreamSource;
-import javax.xml.ws.Dispatch;
import javax.xml.ws.Provider;
-import javax.xml.ws.Service;
-import javax.xml.ws.soap.SOAPBinding;

import net.geant.perfsonar.base.Scheduler;
import net.geant.perfsonar.nmwg.response.EchoResponse;
@@ -36,7 +27,6 @@
import net.geant.perfsonar.selftest.SelfTestRunner;
import net.geant.perfsonar.xpath.XPathDeserializer;

-import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;

@@ -50,7 +40,12 @@

private static int defaultThreadPoolSize = 10;

- private static Logger logger =
LoggerFactory.getLogger(PerfSONAR.class);
+ protected static final net.geant.perfsonar.Logger logger =
+ new net.geant.perfsonar.Logger() {
+ public void error(String msg, Throwable ex) {
+
LoggerFactory.getLogger(PerfSONAR.class).error(msg, ex);
+ }
+ };

static {
try {
@@ -66,27 +61,11 @@

private static SelfTestResponse response;

- private Scheduler scheduler = createThreadPool();
- private Map<String, String> keys = new Hashtable<String, String>();
+ protected Scheduler scheduler = createThreadPool();

public PerfSONAR() {
loadConfiguration();
- getScheduler().runEvery(Configuration.getLSInterval(),
registerToLSServices());
}
-
- private Runnable registerToLSServices() {
- return new Runnable() {
- public void run() {
- for (String address :
Configuration.getLSAddresses()) {
- try {
-
registerToLookupService(address);
- } catch (Exception ex) {
- logger.error("Could not
register to Lookup Service.", ex);
- }
- }
- }
- };
- }

/**
* It creates an instance of net.geant.perfsonar.SelfTestRunnerImpl.
@@ -102,29 +81,44 @@
private void loadConfiguration() {
try {

Class.forName("net.geant.perfsonar.XPaths").newInstance();
+ } catch (Exception ex) { }
+ try {

Class.forName("net.geant.perfsonar.Handlers").newInstance();
+ } catch (Exception ex) { }
+ try {

Class.forName("net.geant.perfsonar.LookupServiceRegister").newInstance();
} catch (Exception ex) { }
}

private static Scheduler createThreadPool() {
return new Scheduler() {
- private ExecutorService pool =
Executors.newFixedThreadPool(defaultThreadPoolSize);
- private Timer timer = new Timer();
+ private ScheduledExecutorService pool =
Executors.newScheduledThreadPool(defaultThreadPoolSize);
+ private Map<Runnable, ScheduledFuture<?>> tasks = new
Hashtable<Runnable, ScheduledFuture<?>>();

public void runInParallel(Runnable task) {
pool.execute(task);
}

public void runEvery(int seconds, final Runnable
task) {
- timer.scheduleAtFixedRate(new TimerTask() {
- @Override
- public void run() {
- task.run();
- }
- }, 0, seconds * 1000);
+ tasks.put(task,
pool.scheduleAtFixedRate(task, 0, seconds, TimeUnit.SECONDS));
}

+ public void stop(Runnable task) {
+ if (tasks.get(task) == null)
+ return;
+ tasks.get(task).cancel(false);
+ tasks.remove(task);
+ }
+
+ public void stopAll() {
+ for (ScheduledFuture<?> task :
tasks.values()) {
+ if (task.cancel(false) == false)
+ System.out.println("Task: " +
task + " did not stop.");
+ }
+ pool.shutdownNow();
+ tasks.clear();
+ }
+
};
}

@@ -148,10 +142,10 @@
return null;
}

- if (getObjects(NMWGMessage.class, objects).size() <= 0)
+ if (deserializer.getObjects(NMWGMessage.class,
objects).size() <= 0)
throw new RuntimeException("NMWG message was not
found in the payload.");

- final NMWGMessage msg = getObjects(NMWGMessage.class,
objects).get(0);
+ final NMWGMessage msg =
deserializer.getObjects(NMWGMessage.class, objects).get(0);

final StringWriter writer = new StringWriter();
if (msg.isEchoRequest()) {
@@ -170,7 +164,7 @@
TemplateEngine.put("result",
m.invoke(m.getDeclaringClass().newInstance()));
} else {
final List<Object> result = new
ArrayList<Object>();
- for (Object obj :
getObjects(m.getParameterTypes()[0], objects)) {
+ for (Object obj :
deserializer.getObjects(m.getParameterTypes()[0], objects)) {

result.add(m.invoke(m.getDeclaringClass().newInstance(), obj));
}
TemplateEngine.put("result", result);
@@ -226,17 +220,6 @@
return new StreamSource(new StringReader(writer.toString()));
}

- @SuppressWarnings("unchecked")
- private <T> List<T> getObjects(Class<T> type, List<Object> objects) {
- final List<T> result = new ArrayList<T>();
- for (Object obj : objects) {
- if (obj.getClass().equals(type)) {
- result.add((T) obj);
- }
- }
- return result;
- }
-
/**
* @return scheduler that uses thread pool.
*/
@@ -253,65 +236,7 @@
scheduler = createThreadPool();
}

- /**
- * Registers a service to Lookup Service.
- * If the service is already registered (key was returned from LS
successfully) it sends keepalive messages.
- * It uses LSRegister.template template found in the directory where
the controller method that provides data for registration is defined.
- *
- */
- @SuppressWarnings("unchecked")
- protected void registerToLookupService(final String address) throws
IllegalArgumentException, IllegalAccessException, InvocationTargetException,
InstantiationException, IOException {
- final Method m = Configuration.getHandler("LSRegister");
- if (m == null)
- return;
-
- TemplateEngine.put("requestId", "request1");
- TemplateEngine.put("result",
m.invoke(m.getDeclaringClass().newInstance()));
- TemplateEngine.put("service", this);
-
- final String NAMESPACE = "http://base3.perfsonar.geant.net/";;
- final QName PORT = new QName(NAMESPACE, "PerfSONARPort");
- final Service service = Service.create(new QName(NAMESPACE,
"PerfSONARService"));
- service.addPort(PORT, SOAPBinding.SOAP11HTTP_BINDING,
address);
- Dispatch<StreamSource> client = service.createDispatch(PORT,
StreamSource.class, Service.Mode.PAYLOAD);
- final PipedInputStream in = new PipedInputStream();
- final PipedOutputStream out = new PipedOutputStream(in);
- final Writer writer = new OutputStreamWriter(out);
- getScheduler().runInParallel(new Runnable() {
-
- public void run() {
- try {
- if (keys.get(address) == null)
-
TemplateEngine.evaluate(writer, m.getDeclaringClass(), "LSRegister.template");
- else
-
writer.write(getKeepAliveMessage(keys.get(address)));
- writer.flush();
- out.close();
- } catch (IOException ex) {
- logger.error("Could not register in
LookupService.", ex);
- }
- }
-
- private String getKeepAliveMessage(String key) {
- return "<?xml version='1.0'
encoding='UTF-8'?>"
- + "<nmwg:message id='request1'
type='LSKeepaliveRequest' xmlns:nmwg='http://ggf.org/ns/nmwg/base/2.0/'>"
- + "<nmwg:metadata
id='key_to_keepalive'><nmwg:key>" + key + "</nmwg:key></nmwg:metadata>"
- + "<nmwg:data id='d1'
metadataIdRef='key_to_keepalive' />"
- + "</nmwg:message>\n";
- }
- });
-
- if (keys.get(address) == null) {
- final XPathDeserializer deserializer = new
XPathDeserializer();
- final NMWGMessage msg;
- try {
- msg = getObjects(NMWGMessage.class,
(List<Object>) deserializer.deserialize(new InputSource(client.invoke(new
StreamSource(in)).getInputStream()))).get(0);
- if (msg.getKey() != null)
- keys.put(address, msg.getKey());
- } catch (Exception e) {
- logger.error("Could not deserialize key from
Lookup Service response.", e);
- }
- } else
- client.invoke(new StreamSource(in));
+ public void stop() {
+ scheduler.stopAll();
}
}

Modified:
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/base/Scheduler.java
===================================================================
---
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/base/Scheduler.java
2013-02-13 13:53:57 UTC (rev 6137)
+++
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/base/Scheduler.java
2013-02-14 15:16:46 UTC (rev 6138)
@@ -5,4 +5,8 @@
void runInParallel(Runnable task);

void runEvery(int seconds, Runnable task);
+
+ void stop(Runnable task);
+
+ void stopAll();
}
\ No newline at end of file

Modified:
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/xpath/Helper.java
===================================================================
---
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/xpath/Helper.java
2013-02-13 13:53:57 UTC (rev 6137)
+++
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/xpath/Helper.java
2013-02-14 15:16:46 UTC (rev 6138)
@@ -13,4 +13,8 @@
T result = (T) e.create();
return result;
}
+
+ public static boolean isConfigurationInstance(Object object) {
+ return
object.getClass().getName().contains("EnhancerByCGLIB");
+ }
}

Modified:
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/xpath/XPathConfiguration.java
===================================================================
---
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/xpath/XPathConfiguration.java
2013-02-13 13:53:57 UTC (rev 6137)
+++
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/xpath/XPathConfiguration.java
2013-02-14 15:16:46 UTC (rev 6138)
@@ -1,6 +1,8 @@
package net.geant.perfsonar.xpath;

import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.List;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
@@ -8,6 +10,9 @@
public class XPathConfiguration implements MethodInterceptor {

private String xpath;
+ private Object object;
+
+ private static final List<String> restrictedMethodNames =
Arrays.asList("toString", "hashCode", "finalize");

public XPathConfiguration(String xpath) {
this.xpath = xpath;
@@ -16,18 +21,27 @@
public <T> T then(Class<T> controller) throws InstantiationException,
IllegalAccessException {
return Helper.createMock(controller, this);
}
+
+ public <T> T then(Class<T> clazz, T object) throws
InstantiationException, IllegalAccessException {
+ this.object = object;
+ return Helper.createMock(clazz, this);
+ }

public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {

- if (method.getName().equals("toString") ||
method.getName().equals("hashCode") || method.getName().equals("finalize")) {
+ if (restrictedMethodNames.contains(method.getName())) {
return proxy.invokeSuper(obj, args);
}

if (args.length != 1)
throw new IllegalArgumentException("Setter method
must have exactly one argument of type String.");

- XPathDeserializer.putXPath(xpath, method);
+ if (this.object != null)
+ XPathDeserializer.putXPath(xpath, object, method);
+ else
+ XPathDeserializer.putXPath(xpath, method);
+
return null;
}
}

Modified:
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/xpath/XPathDeserializer.java
===================================================================
---
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/xpath/XPathDeserializer.java
2013-02-13 13:53:57 UTC (rev 6137)
+++
trunk/psBase3/perfsonar-base/src/main/java/net/geant/perfsonar/xpath/XPathDeserializer.java
2013-02-14 15:16:46 UTC (rev 6138)
@@ -2,6 +2,7 @@

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
@@ -65,6 +66,7 @@
private final static DefaultNamespaceContext context = new
DefaultNamespaceContext();
private Map<Class<?>, List<Object>> instances = new
Hashtable<Class<?>, List<Object>>();

+ private static Map<Method, Object> objects = new Hashtable<Method,
Object>();
private static Map<String, Method> xpaths = new Hashtable<String,
Method>();
private static Map<Class<?>, Method> identifiers = new
Hashtable<Class<?>, Method>();

@@ -88,6 +90,11 @@
return null;
}

+ public static void putXPath(String xpath, Object object, Method
method) {
+ objects.put(method, object);
+ xpaths.put(xpath, method);
+ }
+
public static void putXPath(String xpath, Method method) {
xpaths.put(xpath, method);
}
@@ -145,6 +152,17 @@

}

+ @SuppressWarnings("unchecked")
+ public <T> List<T> getObjects(Class<T> type, List<Object> objects) {
+ final List<T> result = new ArrayList<T>();
+ for (Object obj : objects) {
+ if (obj.getClass().equals(type)) {
+ result.add((T) obj);
+ }
+ }
+ return result;
+ }
+
private List<Expression> sort(List<Expression> expressions) {
final List<Expression> result = new ArrayList<Expression>();
final Iterator<Expression> iter = expressions.iterator();
@@ -195,6 +213,10 @@
}

private Object getInstance(Method method) throws
InstantiationException, IllegalAccessException {
+ if (Modifier.isStatic(method.getModifiers()))
+ return null;
+ if (objects.get(method) != null)
+ return objects.get(method);
if (instances.get(method.getDeclaringClass()) == null) {
instances.put(method.getDeclaringClass(), new
ArrayList<Object>());
}

Added:
trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/LSRegistrationTest.java
===================================================================
---
trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/LSRegistrationTest.java
(rev 0)
+++
trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/LSRegistrationTest.java
2013-02-14 15:16:46 UTC (rev 6138)
@@ -0,0 +1,53 @@
+package net.geant.perfsonar;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+import net.geant.perfsonar.helpers.MockLSService;
+import net.geant.perfsonar.mp.sshtelnet.SSHTelnetMPService;
+import net.geant.perfsonar.mp.sshtelnet.ServiceController;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+public class LSRegistrationTest {
+ private static final String LS_URL =
"http://localhost:9000/perfsonar-ls";;
+
+ private PerfSONAR service = new SSHTelnetMPService();
+
+ private LSRegistrationTask task = new LSRegistrationTask(getLogger(),
service);
+
+ private MockLSService ls;
+
+ @Before
+ public void givenLookupService() {
+ ls = new MockLSService();
+ ls.publish(LS_URL);
+ }
+
+ private Logger getLogger() {
+ return new Logger() {
+ public void error(String message, Throwable ex) {
+ fail(message + " " + ex);
+ }
+ };
+ }
+
+ @After
+ public void stopLookupService() {
+ ls.stop();
+ }
+
+ @Test
+ public void registerToLookupService() throws Exception {
+
Configuration.configure(LSRegistrationTask.registerToLookupService(
+
ServiceController.class).listAvailableRoutersAndCommands());
+
+ task.registerToLookupService(LS_URL);
+ task.registerToLookupService(LS_URL);
+ task.registerToLookupService(LS_URL);
+
+ assertEquals(2, ls.getKeepAliveCount());
+ assertEquals(1, ls.getRegisterCount());
+ }
+}

Modified:
trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/PerfSONARTest.java
===================================================================
---
trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/PerfSONARTest.java
2013-02-13 13:53:57 UTC (rev 6137)
+++
trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/PerfSONARTest.java
2013-02-14 15:16:46 UTC (rev 6138)
@@ -6,26 +6,15 @@

import java.io.IOException;
import java.io.Reader;
-import java.util.ArrayList;
-import java.util.List;

-import javax.xml.transform.stream.StreamSource;
-import javax.xml.ws.Endpoint;
-import javax.xml.ws.Provider;
-import javax.xml.ws.WebServiceProvider;
-
import net.geant.perfsonar.helpers.NMWG;
import net.geant.perfsonar.helpers.PerfSONARClient;
import net.geant.perfsonar.helpers.SelfTestResult;
import net.geant.perfsonar.mp.sshtelnet.Command;
import net.geant.perfsonar.mp.sshtelnet.SSHTelnetMPService;
-import net.geant.perfsonar.mp.sshtelnet.ServiceController;
-import net.geant.perfsonar.xpath.XPathDeserializer;

-import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class PerfSONARTest {
@@ -35,49 +24,13 @@
private PerfSONARClient client;

private SSHTelnetMPService service = new SSHTelnetMPService();
- private Endpoint ls;

- private int lsKeepAliveCount;
-
- private int lsRegisterCount;
-
@Before
public void givenPerfSONARClient() {
client = new PerfSONARClient(service);
- ls = Endpoint.publish("http://localhost:9000/perfsonar-ls";,
- new LSService());
}

- @After
- public void destroy() {
- ls.stop();
- }

- @WebServiceProvider
- class LSService implements Provider<StreamSource> {
-
- @SuppressWarnings("unchecked")
- public StreamSource invoke(StreamSource input) {
- final XPathDeserializer deserializer = new
XPathDeserializer();
- NMWGMessage msg;
- try {
- msg = getObjects(
- NMWGMessage.class,
- (List<Object>) deserializer
-
.deserialize(new InputSource(input
-
.getInputStream()))).get(0);
- if
(msg.getType().equals("LSKeepaliveRequest"))
- lsKeepAliveCount++;
- else if
(msg.getType().equals("LSRegisterRequest"))
- lsRegisterCount++;
- return new
StreamSource(NMWG.toLSResponse(msg.getId()));
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- return null;
- }
- }
-
@Test
public void checkEcho() throws SAXException {
assertEquals(NMWG.toEchoResponse(REQUEST_ID),
client.echo(REQUEST_ID));
@@ -114,30 +67,4 @@
for (int i = reader.read(); i != -1; i = reader.read())
System.out.print((char) i);
}
-
- @Test
- public void registerToLookupService() throws Exception {
- Configuration.configure(Configuration.registerToLookupService(
-
ServiceController.class).listAvailableRoutersAndCommands());
-
-
service.registerToLookupService("http://localhost:9000/perfsonar-ls";);
-
service.registerToLookupService("http://localhost:9000/perfsonar-ls";);
-
service.registerToLookupService("http://localhost:9000/perfsonar-ls";);
-
- Thread.sleep(5 * 1000);
-
- assertEquals(2, lsKeepAliveCount);
- assertEquals(1, lsRegisterCount);
- }
-
- @SuppressWarnings("unchecked")
- private <T> List<T> getObjects(Class<T> type, List<Object> objects) {
- final List<T> result = new ArrayList<T>();
- for (Object obj : objects) {
- if (obj.getClass().equals(type)) {
- result.add((T) obj);
- }
- }
- return result;
- }
}

Modified:
trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/SSHTelnetMPWebServiceTest.java
===================================================================
---
trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/SSHTelnetMPWebServiceTest.java
2013-02-13 13:53:57 UTC (rev 6137)
+++
trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/SSHTelnetMPWebServiceTest.java
2013-02-14 15:16:46 UTC (rev 6138)
@@ -6,6 +6,7 @@

import javax.xml.ws.Endpoint;

+import net.geant.perfsonar.helpers.MockLSService;
import net.geant.perfsonar.helpers.NMWG;
import net.geant.perfsonar.helpers.PerfSONARServiceClient;
import net.geant.perfsonar.mp.sshtelnet.SSHTelnetMPService;
@@ -16,30 +17,42 @@
import org.xml.sax.SAXException;

public class SSHTelnetMPWebServiceTest {
+ private static final int TWO_SECONDS = 2000;
+ private static final String REQUEST_ID = "request1";
private static final String SERVICE_URL =
"http://localhost:9000/perfsonar-java-sshtelnet-mp";;
- private static final String REQUEST_ID = "request1";
+ private static final String LS_URL =
"http://localhost:9000/perfsonar-ls";;

+ private MockLSService ls = new MockLSService();
+
+ private SSHTelnetMPService service = new SSHTelnetMPService();
private Endpoint endpoint;

@Before
- public void givenSSHTelnetMPWebService() throws InterruptedException,
IOException {
- endpoint = Endpoint.publish(SERVICE_URL, new
SSHTelnetMPService());
+ public void givenLSandSSHTelnetMPWebService() throws
InterruptedException, IOException {
+ ls.publish(LS_URL);
+ endpoint = Endpoint.publish(SERVICE_URL, service);
}
-
+
@After
- public void destroy() {
+ public void stopServices() {
endpoint.stop();
+ service.stop();
+ ls.stop();
+ endpoint = null;
+ ls = null;
+ service = null;
}
+
+ @Test
+ public void shouldRegisterToLookupService() throws Exception {
+ Thread.sleep(TWO_SECONDS * 3 + 500);
+ assertEquals(3, ls.getKeepAliveCount());
+ assertEquals(1, ls.getRegisterCount());
+ }

@Test
public void shouldSayEcho() throws SAXException, InterruptedException
{
final PerfSONARServiceClient client = new
PerfSONARServiceClient(SERVICE_URL);
assertEquals(NMWG.toEchoResponse(REQUEST_ID),
client.echo(REQUEST_ID));
}
-
- @Test
- public void shouldSetLSInterval() {
- assertEquals(600, Configuration.getLSInterval());
- }
-
}

Added:
trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/helpers/MockLSService.java
===================================================================
---
trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/helpers/MockLSService.java
(rev 0)
+++
trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/helpers/MockLSService.java
2013-02-14 15:16:46 UTC (rev 6138)
@@ -0,0 +1,55 @@
+package net.geant.perfsonar.helpers;
+
+import static org.junit.Assert.fail;
+
+import java.util.List;
+
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.ws.Endpoint;
+import javax.xml.ws.Provider;
+import javax.xml.ws.WebServiceProvider;
+
+import net.geant.perfsonar.NMWGMessage;
+import net.geant.perfsonar.xpath.XPathDeserializer;
+
+import org.xml.sax.InputSource;
+
+@WebServiceProvider
+public class MockLSService implements Provider<StreamSource> {
+ private int lsKeepAliveCount = 0;
+ private int lsRegisterCount = 0;
+ private Endpoint endpoint;
+
+ @SuppressWarnings("unchecked")
+ public StreamSource invoke(StreamSource input) {
+ final XPathDeserializer deserializer = new
XPathDeserializer();
+ NMWGMessage msg;
+ try {
+ msg = deserializer.getObjects(NMWGMessage.class,
(List<Object>) deserializer.deserialize(new
InputSource(input.getInputStream()))).get(0);
+ if (msg.getType().equals("LSKeepaliveRequest"))
+ lsKeepAliveCount++;
+ else if (msg.getType().equals("LSRegisterRequest"))
+ lsRegisterCount++;
+ return new
StreamSource(NMWG.toLSResponse(msg.getId()));
+ } catch (Exception ex) {
+ fail(ex.toString());
+ }
+ return null;
+ }
+
+ public int getKeepAliveCount() {
+ return lsKeepAliveCount;
+ }
+
+ public int getRegisterCount() {
+ return lsRegisterCount;
+ }
+
+ public void publish(String url) {
+ endpoint = Endpoint.publish(url, this);
+ }
+
+ public void stop() {
+ endpoint.stop();
+ }
+}

Added:
trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/mp/sshtelnet/ConfigurationFileChecker.java
===================================================================
---
trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/mp/sshtelnet/ConfigurationFileChecker.java
(rev 0)
+++
trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/mp/sshtelnet/ConfigurationFileChecker.java
2013-02-14 15:16:46 UTC (rev 6138)
@@ -0,0 +1,64 @@
+package net.geant.perfsonar.mp.sshtelnet;
+
+import java.io.File;
+import java.io.FileInputStream;
+
+import net.geant.perfsonar.LSRegistrationTask;
+import net.geant.perfsonar.xpath.Helper;
+import net.geant.perfsonar.xpath.XPathDeserializer;
+
+import org.xml.sax.InputSource;
+
+import static net.geant.perfsonar.xpath.XPathDeserializer.any;
+import static net.geant.perfsonar.xpath.XPathDeserializer.declarePrefix;
+import static net.geant.perfsonar.xpath.XPathDeserializer.whenXPath;
+
+public class ConfigurationFileChecker implements Runnable {
+
+ private File file = new File("src/test/resources/configuration.xml");
+ private long lastModified = 0;
+ private final SSHTelnetMPService service;
+
+ public ConfigurationFileChecker(SSHTelnetMPService service) {
+ this.service = service;
+ }
+
+ public void run() {
+ if (!file.exists()) {
+ System.err.println("Configuration file: " +
file.getAbsolutePath()
+ + " is missing");
+ return;
+ }
+
+ if (file.lastModified() > lastModified) {
+ lastModified = file.lastModified();
+ configureDeserialization();
+ XPathDeserializer deserializer = new
XPathDeserializer();
+ try {
+ deserializer.deserialize(new InputSource(new
FileInputStream(file)));
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
+ }
+ }
+
+ private void configureDeserialization() {
+ //When configuring XPath the configurator creates a subclass
of SSHTelnetMPService that registers method invocations.
+ //The instance executes base class constructor of
SSHTelnetMPService which creates this task.
+ //This guard prevents calls from subclass instances forever
when configuring XPath.
+ if (Helper.isConfigurationInstance(service))
+ return;
+
+ declarePrefix("ns",
"http://service.perfsonar.org/ns/config/base/0.9/";);
+
+ try {
+ whenXPath(
+
"ns:configuration/ns:service/ns:auxiliaryComponents/ns:component[@name='scheduling']/ns:actions/ns:action[@name='registration']/ns:option[@name='interval']/@value")
+ .then(SSHTelnetMPService.class,
service).setLookupServiceInterval(any(String.class));
+
+ whenXPath(
+
"ns:configuration/ns:service/ns:auxiliaryComponents/ns:component[@name='scheduling']/ns:actions/ns:action[@name='registration']/ns:option[starts-with(@name,
'lsAddress')]/@value")
+
.then(LSRegistrationTask.class).addLSAddress(any(String.class));
+ } catch (Exception ex) { }
+ }
+}

Modified:
trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/mp/sshtelnet/SSHTelnetMPService.java
===================================================================
---
trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/mp/sshtelnet/SSHTelnetMPService.java
2013-02-13 13:53:57 UTC (rev 6137)
+++
trunk/psBase3/perfsonar-base/src/test/java/net/geant/perfsonar/mp/sshtelnet/SSHTelnetMPService.java
2013-02-14 15:16:46 UTC (rev 6138)
@@ -2,30 +2,31 @@

import static net.geant.perfsonar.Configuration.configure;
import static net.geant.perfsonar.Configuration.when;
+import static net.geant.perfsonar.LSRegistrationTask.registerToLookupService;
import static net.geant.perfsonar.xpath.XPathDeserializer.any;
-import static net.geant.perfsonar.xpath.XPathDeserializer.declarePrefix;
import static net.geant.perfsonar.xpath.XPathDeserializer.whenXPath;

-import java.io.File;
-import java.io.FileInputStream;
-
import javax.xml.ws.WebServiceProvider;

-import net.geant.perfsonar.Configuration;
+import net.geant.perfsonar.LSRegistrationTask;
import net.geant.perfsonar.PerfSONAR;
import net.geant.perfsonar.ServiceType;
-import net.geant.perfsonar.xpath.XPathDeserializer;

-import org.xml.sax.InputSource;
-
@WebServiceProvider
public class SSHTelnetMPService extends PerfSONAR {

+ private static final int HOUR = 60 * 60;
+
private static final int SECOND = 1;

+ private final LSRegistrationTask lsRegistrationTask = new
LSRegistrationTask(logger, this);
+ private int lsInterval = HOUR;
+
public SSHTelnetMPService() {
super();
- getScheduler().runEvery(SECOND,
checkWhetherConfigurationFileChanged());
+
+ scheduler.runEvery(HOUR, lsRegistrationTask);
+ scheduler.runEvery(SECOND, new
ConfigurationFileChecker(this));
}

@Override
@@ -38,29 +39,6 @@
return "SSHTELNET";
}

- private Runnable checkWhetherConfigurationFileChanged() {
- return new Runnable() {
- private File file = new
File("src/test/resources/configuration.xml");
- private long lastModified = 0;
-
- public void run() {
- if (!file.exists()) {
- System.err.println("Configuration
file: " + file.getAbsolutePath() + " is missing");
- return;
- }
-
- if (file.lastModified() > lastModified) {
- lastModified = file.lastModified();
- XPathDeserializer deserializer = new
XPathDeserializer();
- try {
- deserializer.deserialize(new
InputSource(new FileInputStream(file)));
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- }};
- }
-
static {
try {

configure(when("MetadataKeyRequest").then(ServiceController.class)
@@ -69,6 +47,9 @@

configure(when("SetupDataRequest").then(ServiceController.class)
.execute(any(Command.class)));

+
configure(registerToLookupService(ServiceController.class)
+ .listAvailableRoutersAndCommands());
+
whenXPath(

"nmwg:message/nmwg:metadata/nmwg:subject/nmwgtopo:endPoint/text()")

.then(Command.class).setRouterName(any(String.class));
@@ -87,13 +68,25 @@
whenXPath(

"nmwg:message/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='syntax']/@value")

.then(Command.class).setSyntax(any(String.class));
-
- declarePrefix("ns",
"http://service.perfsonar.org/ns/config/base/0.9/";);
-
- whenXPath(
-
"ns:configuration/ns:service/ns:auxiliaryComponents/ns:component[@name='scheduling']/ns:actions/ns:action[@name='registration']/ns:option[@name='interval']/@value")
-
.then(Configuration.class).setLookupServiceInterval(any(String.class));
} catch (Exception ex) {
}
}
+
+ /**
+ * Sets timeout in seconds between subsequent
registrations/keepalives to Lookup
+ * Service.
+ */
+ public synchronized void setLookupServiceInterval(String interval) {
+ lsInterval = Integer.parseInt(interval);
+ scheduler.stop(lsRegistrationTask);
+ scheduler.runEvery(lsInterval, lsRegistrationTask);
+ }
+
+ /**
+ * Returns timeout in seconds between subsequent
registrations/keepalives to Lookup
+ * Service.
+ */
+ public synchronized int getLookupServiceInterval() {
+ return lsInterval;
+ }
}

Modified: trunk/psBase3/perfsonar-base/src/test/resources/configuration.xml
===================================================================
--- trunk/psBase3/perfsonar-base/src/test/resources/configuration.xml
2013-02-13 13:53:57 UTC (rev 6137)
+++ trunk/psBase3/perfsonar-base/src/test/resources/configuration.xml
2013-02-14 15:16:46 UTC (rev 6138)
@@ -67,12 +67,11 @@
<actions>
<action name="registration"
className="org.perfsonar.base2.service.registration.LSRegistrationAction">
<option name="status" value="on" />
- <option name="interval" value="600" />
+ <option name="interval" value="2" />
<option name="registerDataSource"
value="org.perfsonar.base2.service.registration.MetadataExistDBRegisterDataSource"/>

<option name="registerEventType"
value="http://ogf.org/ns/nmwg/tools/org/perfsonar/service/lookup/registration/summary/2.0"/>
<option name="registrator"
value="org.perfsonar.base2.service.registration.GenericLSRegistrator"/>
- <option name="lsAddress-1"
value="http://localhost:8080/geant2-java-xml-ls/services/LookupService"/>
- <option name="lsAddress-2"
value="http://localhost:8380/perfsonar-java-xml-ls/services/LookupService"/>
+ <option name="lsAddress-1"
value="http://localhost:9000/perfsonar-ls"/>
</action>

<!-- Checks whether a given metadata file has changed and updates
it in the database.



  • [pS-dev] [GEANT/SA2/ps-java-services] r6138 - in trunk/psBase3/perfsonar-base: . src/main/java/net/geant/perfsonar src/main/java/net/geant/perfsonar/base src/main/java/net/geant/perfsonar/xpath src/test/java/net/geant/perfsonar src/test/java/net/geant/perfsonar/helpers src/test/java/net/geant/perfsonar/mp/sshtelnet src/test/resources, svn-noreply, 02/14/2013

Archive powered by MHonArc 2.6.16.

Top of Page