summaryrefslogtreecommitdiffstats
path: root/communications
diff options
context:
space:
mode:
Diffstat (limited to 'communications')
-rw-r--r--communications/pom.xml65
-rw-r--r--communications/src/main/java/eu/novi/connection/RESTCommunication.java84
-rw-r--r--communications/src/main/java/eu/novi/connection/SSHConnection.java172
3 files changed, 321 insertions, 0 deletions
diff --git a/communications/pom.xml b/communications/pom.xml
new file mode 100644
index 0000000..c42445b
--- /dev/null
+++ b/communications/pom.xml
@@ -0,0 +1,65 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>eu.novi</groupId>
+ <artifactId>parent</artifactId>
+ <version>0.1.0-SNAPSHOT</version>
+ <relativePath>../parent/</relativePath>
+ </parent>
+ <artifactId>communications</artifactId>
+ <packaging>bundle</packaging>
+ <name>Helper methods for communications</name>
+
+ <developers>
+ <developer>
+ <id>pikusa</id>
+ <name>Piotr Pikusa</name>
+ <email>pikusa@man.poznan.pl</email>
+ <organization>PSNC</organization>
+ <organizationUrl>http://www.man.poznan.pl/</organizationUrl>
+ <roles>
+ <role>architect</role>
+ <role>developer</role>
+ </roles>
+ <timezone>+1</timezone>
+ </developer>
+ </developers>
+
+ <dependencies>
+ <dependency>
+ <groupId>eu.novi</groupId>
+ <artifactId>information-model</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.servicemix.bundles</groupId>
+ <artifactId>org.apache.servicemix.bundles.commons-httpclient</artifactId>
+ <version>3.1_1</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.servicemix.bundles</groupId>
+ <artifactId>org.apache.servicemix.bundles.jsch</artifactId>
+ <version>0.1.43_1</version>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <configuration>
+ <instructions>
+ <Export-Package>eu.novi.connection</Export-Package>
+ <Import-Package>
+ *
+ </Import-Package>
+ </instructions>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+</project>
diff --git a/communications/src/main/java/eu/novi/connection/RESTCommunication.java b/communications/src/main/java/eu/novi/connection/RESTCommunication.java
new file mode 100644
index 0000000..48d5868
--- /dev/null
+++ b/communications/src/main/java/eu/novi/connection/RESTCommunication.java
@@ -0,0 +1,84 @@
+package eu.novi.connection;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpException;
+import org.apache.commons.httpclient.methods.PostMethod;
+import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
+import org.apache.commons.httpclient.methods.multipart.Part;
+import org.apache.commons.httpclient.methods.multipart.StringPart;
+
+public class RESTCommunication {
+
+ private String response = "";
+
+
+ /**
+ * Methods executes POST communication on the given address where REST service is running.
+ * @param restAddress URL address of the REST service to call. For example http://planetlab:8080/request/handler/delete
+ * @param requestParameters The pairs contains keys and values of the request parameters. For example for POST message in URL "http://planetlab:8080/request/handler/delete?sliceId=1234" the key is "sliceId" and
+ * @throws HttpException
+ * @throws IOException
+ */
+ public void executePostMethod(String restAddress, Map<String, String> requestParameters) throws HttpException, IOException {
+ PostMethod postMethod = preparePostMethod(restAddress, requestParameters);
+ response = getResponseFromService(postMethod);
+ }
+
+ /**
+ * Prepare POST method with the given parameters
+ * @param restAddress
+ * @param key
+ * @param value
+ * @return
+ */
+ private PostMethod preparePostMethod(String restAddress, Map<String, String> requestParameters) {
+ Part[] parts = generateParts(requestParameters);
+ PostMethod postMethod = new PostMethod(restAddress);
+ postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
+
+ return postMethod;
+ }
+
+ private Part[] generateParts(Map<String, String> keyValuePairs) {
+ Part[] parts = new Part[keyValuePairs.size()];
+ int i = 0;
+ for(String key : keyValuePairs.keySet()){
+ parts[i++] = new StringPart(key, keyValuePairs.get(key));
+ }
+ return parts;
+ }
+
+ private String getResponseFromService(PostMethod postMethod) throws HttpException, IOException {
+ String resp = "";
+ final HttpClient client = new HttpClient();
+ if (client.executeMethod(postMethod) != -1) {
+ resp = getResponseFromStream(postMethod.getResponseBodyAsStream());
+ postMethod.releaseConnection();
+ }
+ return resp;
+ }
+
+
+ public String getResponseFromStream(InputStream responseBodyAsStream) throws IOException{
+ BufferedReader reader = new BufferedReader(new InputStreamReader(responseBodyAsStream));
+ StringBuilder responseBuilder = new StringBuilder();
+ String line;
+ while ((line = reader.readLine()) != null) {
+ responseBuilder.append(line);
+ }
+ return responseBuilder.toString();
+ }
+
+
+ public String getResponse() {
+ return response;
+ }
+
+}
diff --git a/communications/src/main/java/eu/novi/connection/SSHConnection.java b/communications/src/main/java/eu/novi/connection/SSHConnection.java
new file mode 100644
index 0000000..caf93a1
--- /dev/null
+++ b/communications/src/main/java/eu/novi/connection/SSHConnection.java
@@ -0,0 +1,172 @@
+package eu.novi.connection;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.jcraft.jsch.Channel;
+import com.jcraft.jsch.ChannelExec;
+import com.jcraft.jsch.JSch;
+import com.jcraft.jsch.JSchException;
+import com.jcraft.jsch.Session;
+
+
+public class SSHConnection {
+
+ private static final Logger logger = LoggerFactory.getLogger(SSHConnection.class);
+
+ private BufferedReader br;
+ private InputStream in;
+ private Session session;
+ private Channel channel;
+ private boolean connectedStatus = false;
+ private static final int SSHPORT = 22;
+ private static final int TIMEOUT = 30000;
+ private static final int AVAILABLE_BYTES = 1024;
+
+ /**
+ *
+ * @return
+ */
+ public boolean connected() {
+ return connectedStatus;
+ }
+
+ /**
+ *
+ * @param user
+ * @param host
+ * @param password
+ * @param command
+ * @throws JSchException
+ * @throws Exception
+ */
+ public void executeCommandOnHostWithPassword(String user, String host, String password, String command)
+ throws JSchException, Exception {
+
+ JSch jsch = new JSch();
+ session = jsch.getSession(user, host, SSHPORT);
+ session.setPassword(password);
+ session.setConfig("StrictHostKeyChecking", "no");
+ session.connect(TIMEOUT);
+ executeCommandInSession(session, command);
+ }
+
+ /**
+ *
+ * @param user
+ * @param host
+ * @param sshKeyLocation
+ * @param command
+ * @param
+ * @throws JSchException
+ * @throws Exception
+ */
+ public void executeCommandOnHostWithKey(String user, String host, String sshKeyLocation, String command)
+ throws JSchException, Exception {
+ JSch jsch = new JSch();
+ jsch.addIdentity(sshKeyLocation);
+ session = jsch.getSession(user, host, SSHPORT);
+ session.setConfig("StrictHostKeyChecking", "no");
+ session.connect(TIMEOUT);
+ executeCommandInSession(session, command);
+ }
+
+ private void executeCommandInSession(Session session, String command) throws JSchException, Exception {
+ channel = session.openChannel("exec");
+ ((ChannelExec) channel).setCommand(command);
+ ((ChannelExec) channel).setErrStream(System.out);
+ in = channel.getInputStream();
+ br = new BufferedReader(new InputStreamReader(in));
+ channel.connect();
+ connectedStatus = true;
+ }
+
+ /**
+ * Reads the output stream that. It always reads the InputStream.available() amount of bytes. If there is expected more
+ * (for example when "tail -f" command is executed, than this method should be called many times.
+ *
+ *
+ * @param bytes
+ * = number of bytes to read. If bytes<0, then default value is
+ * InputStream.available()
+ * @return output If there is no mroe bytes that can be read the output=""
+ */
+ public String readOutput(int bytes) throws IOException {
+ String result = "";
+ if (in.available() > 0) {
+ byte[] tmp = new byte[AVAILABLE_BYTES];
+ int i = in.read(tmp, 0, AVAILABLE_BYTES);
+ if (i > 0){
+ result = (new String(tmp, 0, i));
+ }
+ }
+ if (channel.isClosed() || !channel.isConnected()) {
+ disconnect();
+ }
+ return result;
+
+ }
+
+
+ public String readOutputLine() throws IOException {
+ String result = "";
+ try{
+ result = br.readLine();
+ if (result == null) {
+ disconnect();
+ return "";
+ }
+ } catch (IOException e) {
+ //disconnect();
+ throw e;
+ }
+ if (channel.isClosed()) {
+ logger.info("exit-status: " + channel.getExitStatus());
+ disconnect();
+ }
+
+ return result;
+ }
+
+ public String readOutputLineWhenBufferReady() throws IOException {
+ String result = "";
+ try{
+ if(!br.ready()){
+ disconnect();
+ return "";
+ }
+ result = br.readLine();
+ if (result == null) {
+ disconnect();
+ return "";
+ }
+ } catch (IOException e) {
+ disconnect();
+ throw e;
+ }
+ if (channel.isClosed()) {
+ logger.info("exit-status: " + channel.getExitStatus());
+ disconnect();
+ }
+
+ return result;
+ }
+
+ /**
+ * Close the connection that is hosted by the object of this class.
+ * @throws IOException
+ */
+ public void disconnect() throws IOException {
+ in.close();
+ br.close();
+ channel.disconnect();
+ session.disconnect();
+ connectedStatus = false;
+ }
+}