CommonLibrary(util/rest-client) code upload.
authortian.ming@huawei.com <tian.ming@huawei.com>
Thu, 25 Aug 2016 03:54:47 +0000 (11:54 +0800)
committertian.ming@huawei.com <tian.ming@huawei.com>
Thu, 25 Aug 2016 04:10:24 +0000 (12:10 +0800)
Change-Id: I46c9c2ef19e43ebc7f61d8c1b5972c362e7f2d2a
Signed-off-by: tian.ming@huawei.com <tian.ming@huawei.com>
55 files changed:
CommonLibrary/.gitignore [new file with mode: 0644]
CommonLibrary/common-util/.gitignore [new file with mode: 0644]
CommonLibrary/common-util/pom.xml [new file with mode: 0644]
CommonLibrary/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/CipherCreator.java [new file with mode: 0644]
CommonLibrary/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/impl/AesCipher.java [new file with mode: 0644]
CommonLibrary/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/impl/AesCipherFactory.java [new file with mode: 0644]
CommonLibrary/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/inf/AbstractCipher.java [new file with mode: 0644]
CommonLibrary/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/inf/AbstractCipherFactory.java [new file with mode: 0644]
CommonLibrary/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/sha/Sha256.java [new file with mode: 0644]
CommonLibrary/common-util/src/main/java/org/openo/baseservice/util/RestUtils.java [new file with mode: 0644]
CommonLibrary/common-util/src/main/java/org/openo/baseservice/util/impl/SystemEnvVariablesDefImpl.java [new file with mode: 0644]
CommonLibrary/common-util/src/main/java/org/openo/baseservice/util/impl/SystemEnvVariablesFactory.java [new file with mode: 0644]
CommonLibrary/common-util/src/main/java/org/openo/baseservice/util/inf/SystemEnvVariables.java [new file with mode: 0644]
CommonLibrary/common-util/src/test/java/org/openo/baseservice/encrypt/cbb/impl/AesCipherTest.java [new file with mode: 0644]
CommonLibrary/common-util/src/test/java/org/openo/baseservice/encrypt/cbb/sha/Sha256Test.java [new file with mode: 0644]
CommonLibrary/common-util/src/test/java/org/openo/baseservice/util/RestUtilsTest.java [new file with mode: 0644]
CommonLibrary/common-util/src/test/java/org/openo/baseservice/util/impl/SystemEnvVariablesDefImplTest.java [new file with mode: 0644]
CommonLibrary/pom.xml [new file with mode: 0644]
CommonLibrary/rest-client/.gitignore [new file with mode: 0644]
CommonLibrary/rest-client/pom.xml [new file with mode: 0644]
CommonLibrary/rest-client/src/main/java/org/openo/baseservice/remoteservice/exception/ExceptionArgs.java [new file with mode: 0644]
CommonLibrary/rest-client/src/main/java/org/openo/baseservice/remoteservice/exception/ServiceException.java [new file with mode: 0644]
CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/ReaderHelper.java [new file with mode: 0644]
CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/ServiceUtil.java [new file with mode: 0644]
CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/clientsdk/HttpUtil.java [new file with mode: 0644]
CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/clientsdk/JsonUtil.java [new file with mode: 0644]
CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/clientsdk/RestClientUtil.java [new file with mode: 0644]
CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/DefaultAsyncCallback.java [new file with mode: 0644]
CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/HttpBaseRest.java [new file with mode: 0644]
CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/HttpRest.java [new file with mode: 0644]
CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestHttpContentExchange.java [new file with mode: 0644]
CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/Restful.java [new file with mode: 0644]
CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulAsyncCallback.java [new file with mode: 0644]
CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulClientConst.java [new file with mode: 0644]
CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulConfigure.java [new file with mode: 0644]
CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulFactory.java [new file with mode: 0644]
CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulOptions.java [new file with mode: 0644]
CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulParametes.java [new file with mode: 0644]
CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulResponse.java [new file with mode: 0644]
CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/ReaderHelperTest.java [new file with mode: 0644]
CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/TestServiceUtil.java [new file with mode: 0644]
CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/clientsdk/TestHttpUtil.java [new file with mode: 0644]
CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/clientsdk/TestJsonUtil.java [new file with mode: 0644]
CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/clientsdk/TestRestClientUtil.java [new file with mode: 0644]
CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/clientsdk/demo/JsonTestClass.java [new file with mode: 0644]
CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestHttpRest.java [new file with mode: 0644]
CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestHttpContentExchange.java [new file with mode: 0644]
CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulConfigure.java [new file with mode: 0644]
CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulFactory.java [new file with mode: 0644]
CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulOptions.java [new file with mode: 0644]
CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulParametes.java [new file with mode: 0644]
CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulResponse.java [new file with mode: 0644]
CommonLibrary/rest-client/src/test/resources/etc/conf/restclient.json [new file with mode: 0644]
CommonLibrary/rest-client/src/test/resources/rest-client-test.json [new file with mode: 0644]
CommonLibrary/rest-client/src/test/resources/sample.txt.gz [new file with mode: 0644]

diff --git a/CommonLibrary/.gitignore b/CommonLibrary/.gitignore
new file mode 100644 (file)
index 0000000..be68b59
--- /dev/null
@@ -0,0 +1,5 @@
+/target/
+# Eclipse
+.settings/
+.classpath
+.project
diff --git a/CommonLibrary/common-util/.gitignore b/CommonLibrary/common-util/.gitignore
new file mode 100644 (file)
index 0000000..be68b59
--- /dev/null
@@ -0,0 +1,5 @@
+/target/
+# Eclipse
+.settings/
+.classpath
+.project
diff --git a/CommonLibrary/common-util/pom.xml b/CommonLibrary/common-util/pom.xml
new file mode 100644 (file)
index 0000000..b4245d0
--- /dev/null
@@ -0,0 +1,122 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Copyright (c) 2016, Huawei Technologies Co., Ltd.
+  Licensed under the Apache License, Version 2.0 (the "License");
+  you may not use this file except in compliance with the License.
+  You may obtain a copy of the License at
+  http://www.apache.org/licenses/LICENSE-2.0
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+-->
+<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>org.openo.baseservice</groupId>
+          <artifactId>common-setting</artifactId>
+          <version>1.0.1-SNAPSHOT</version>
+    </parent>
+    <artifactId>commonlib-cbb</artifactId>
+    <packaging>jar</packaging>
+    <properties>
+    </properties>
+    <dependencies>
+        <dependency>
+            <groupId>com.googlecode.jmockit</groupId>
+            <artifactId>jmockit</artifactId>
+            <scope>test</scope>
+            <version>1.1</version>
+        </dependency>
+
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <scope>test</scope>
+            <version>4.8.2</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-lang3</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>commons-io</groupId>
+            <artifactId>commons-io</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>com.springsource.slf4j.log4j</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.codehaus.jackson</groupId>
+            <artifactId>jackson-mapper-asl</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>net.sf.json-lib</groupId>
+            <artifactId>json-lib</artifactId>
+            <classifier>jdk15</classifier>
+        </dependency>
+        <dependency>
+            <groupId>javax.servlet</groupId>
+            <artifactId>servlet-api</artifactId>
+            <version>2.5</version>
+        </dependency>
+        <dependency>
+            <groupId>com.github.stephenc.jcip</groupId>
+            <artifactId>jcip-annotations</artifactId>
+            <version>1.0-1</version>
+             <scope>test</scope>
+        </dependency>
+    </dependencies>
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-release-plugin</artifactId>
+                <version>2.5.2</version>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-surefire-plugin</artifactId>
+                <configuration>
+                    <argLine>-XX:-UseSplitVerifier</argLine>
+                    <skip>${maven.test.skip}</skip>
+                    <testFailureIgnore>${maven.test.failure.ignore}</testFailureIgnore>
+                    <excludes>
+                        <exclude>${excludesFile}</exclude>
+                    </excludes>
+                </configuration>
+            </plugin>
+            <plugin>
+                <groupId>org.codehaus.mojo</groupId>
+                <artifactId>cobertura-maven-plugin</artifactId>
+                <version>2.6</version>
+                <configuration>
+                    <formats>
+                        <format>xml</format>
+                        <format>html</format>
+                    </formats>
+                </configuration>
+                <executions>
+                    <execution>
+                        <phase>package</phase>
+                        <goals>
+                            <goal>cobertura</goal>
+                        </goals>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+    </build>
+
+
+</project>
+
diff --git a/CommonLibrary/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/CipherCreator.java b/CommonLibrary/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/CipherCreator.java
new file mode 100644 (file)
index 0000000..c3e59b9
--- /dev/null
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.encrypt.cbb;
+
+import org.openo.baseservice.encrypt.cbb.impl.AesCipherFactory;
+import org.openo.baseservice.encrypt.cbb.inf.AbstractCipher;
+import org.openo.baseservice.encrypt.cbb.inf.AbstractCipherFactory;
+
+/**
+ * Helps create cipher instances from factory.<br/>
+ * <p>
+ * Creates the cipher instances using cipher factory. By default it uses AesCipherFactory.
+ * Can be changed through spring.
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 08-Jun-2016
+ */
+public final class CipherCreator {
+
+    private static CipherCreator instance = new CipherCreator();
+
+    private AbstractCipherFactory factory = new AesCipherFactory();
+
+    /**
+     * Constructor<br/>
+     * <p>
+     * private
+     * </p>
+     * 
+     * @since SDNO 0.5
+     */
+    private CipherCreator() {
+
+    }
+
+    /**
+     * Singleton instance.
+     * <br/>
+     * 
+     * @return
+     * @since SDNO 0.5
+     */
+    public static CipherCreator instance() {
+        return instance;
+    }
+
+    /**
+     * Creates cipher with default key.
+     * <br/>
+     * 
+     * @return cipher instance with default key.
+     * @since SDNO 0.5
+     */
+    public AbstractCipher create() {
+        return factory.createCipherManager();
+    }
+
+    /**
+     * Creates cipher instance with a key.
+     * <br/>
+     * 
+     * @param key the key to be used for encryption and decryption.
+     * @return cipher instance with specified key.
+     * @since SDNO 0.5
+     */
+    public AbstractCipher create(final String key) {
+        return factory.createCipherManager(key);
+    }
+
+    /**
+     * Sets the cipher factory instance.
+     * <br/>
+     * 
+     * @param factory cipher factory.
+     * @since SDNO 0.5
+     */
+    public void setFactory(final AbstractCipherFactory factory) {
+        this.factory = factory;
+    }
+
+}
diff --git a/CommonLibrary/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/impl/AesCipher.java b/CommonLibrary/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/impl/AesCipher.java
new file mode 100644 (file)
index 0000000..c9d7123
--- /dev/null
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openo.baseservice.encrypt.cbb.impl;
+
+import java.security.NoSuchAlgorithmException;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.KeySpec;
+
+import javax.crypto.Cipher;
+import javax.crypto.SecretKey;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.PBEKeySpec;
+import javax.crypto.spec.SecretKeySpec;
+import javax.xml.bind.DatatypeConverter;
+
+import org.openo.baseservice.encrypt.cbb.inf.AbstractCipher;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * CipherManager implement<br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 31-May-2016
+ */
+public class AesCipher implements AbstractCipher {
+
+    private static final Logger LOG = LoggerFactory.getLogger(AesCipher.class);
+    
+    private static final byte[] DEFAULT_IV = {2, 1, 4, 8, 0, 3, 2, 0, 7, 9, 2, 8, 5, 11, 6, 1};
+
+    private static final IvParameterSpec IV_PARAMETER_SPEC = new IvParameterSpec(DEFAULT_IV);
+
+    protected final SecretKey secretKey;
+
+    /**
+     * Constructor<br/>
+     * <p>
+     * Creates default key.
+     * </p>
+     * 
+     * @since SDNO 0.5
+     */
+    public AesCipher() {
+        super();
+        secretKey = createSecretKey("default");
+    }
+
+    /**
+     * Constructor<br/>
+     * <p>
+     * </p>
+     * 
+     * @since SDNO 0.5
+     * @param ckey: key.
+     */
+    public AesCipher(final String key) {
+        super();
+        secretKey = createSecretKey(key);
+    }
+
+    private SecretKey createSecretKey(final String key) {
+        SecretKey secretKey = null;
+        try {
+            final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
+            final KeySpec keySpec = new PBEKeySpec(key.toCharArray(), DEFAULT_IV, 30000, 128);
+
+            secretKey = keyFactory.generateSecret(keySpec);
+            return new SecretKeySpec(secretKey.getEncoded(), "AES");
+        } catch(InvalidKeySpecException e) {
+            LOG.error("Invalid KeySpec ", e);
+        } catch(NoSuchAlgorithmException e) {
+            LOG.error("Algorithm do not support: ", e);
+        }
+        return null;
+    }
+
+    @Override
+    public String encrypt(final String plain) {
+        try {
+            final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+            cipher.init(Cipher.ENCRYPT_MODE, secretKey, IV_PARAMETER_SPEC);
+            final byte[] encryptToBytes = cipher.doFinal(plain.getBytes());
+            return DatatypeConverter.printBase64Binary(encryptToBytes);
+        } catch(final Exception e) {
+            LOG.error("Encrypt the plain error:", e);
+            return null;
+        }
+    }
+
+    @Override
+    public String decrypt(final String encrypted) {
+
+        if(encrypted == null || encrypted.length() == 0) {
+            return null;
+        }
+
+        if(secretKey == null) {
+            return null;
+        }
+
+        try {
+            final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+            cipher.init(Cipher.DECRYPT_MODE, secretKey, IV_PARAMETER_SPEC);
+            final byte[] tempBytes = DatatypeConverter.parseBase64Binary(encrypted);
+            final byte[] decrypTobytes = cipher.doFinal(tempBytes);
+            return new String(decrypTobytes);
+        } catch(final Exception e) {
+            LOG.error("decrypt the plain error:", e);
+            return null;
+        }
+    }
+
+}
diff --git a/CommonLibrary/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/impl/AesCipherFactory.java b/CommonLibrary/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/impl/AesCipherFactory.java
new file mode 100644 (file)
index 0000000..39fe605
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.encrypt.cbb.impl;
+
+import org.openo.baseservice.encrypt.cbb.inf.AbstractCipher;
+import org.openo.baseservice.encrypt.cbb.inf.AbstractCipherFactory;
+
+/**
+ * Factory class to create CipherManager instances.<br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 03-Jun-2016
+ */
+public class AesCipherFactory implements AbstractCipherFactory {
+
+    /**
+     * Creates new CipherManager instance.<br/>
+     * 
+     * @return new cipher manager instance.
+     * @since SDNO 0.5
+     */
+    @Override
+    public AbstractCipher createCipherManager() {
+        return new AesCipher();
+    }
+
+    /**
+     * Creates new CipherManager instance.<br/>
+     * 
+     * @param key new cipher manager instance.
+     * @return
+     * @since SDNO 0.5
+     */
+    @Override
+    public AbstractCipher createCipherManager(final String key) {
+        return new AesCipher(key);
+    }
+
+}
diff --git a/CommonLibrary/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/inf/AbstractCipher.java b/CommonLibrary/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/inf/AbstractCipher.java
new file mode 100644 (file)
index 0000000..4357d86
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.encrypt.cbb.inf;
+
+/**
+ * Cipher Manager, provides the encrypt/decrypt interface
+ * <br/>
+ * <p>
+ * It provides bi-directional encryption api.
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 31-May-2016
+ */
+public interface AbstractCipher {
+
+    /**
+     * Encrypt a string.
+     * <br/>
+     * 
+     * @param plain string to be encrypted.
+     * @return encrypted string.
+     * @since SDNO 0.5
+     */
+    String encrypt(String plain);
+
+    /**
+     * Decrypt a string.
+     * <br/>
+     * 
+     * @param encrypted String is encrypted by AES 128
+     * @return plain after decrypt
+     * @since SDNO 0.5
+     */
+    String decrypt(String encrypted);
+
+}
diff --git a/CommonLibrary/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/inf/AbstractCipherFactory.java b/CommonLibrary/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/inf/AbstractCipherFactory.java
new file mode 100644 (file)
index 0000000..2d6f2ad
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.encrypt.cbb.inf;
+
+/**
+ * Factory class to create CipherManager instances.<br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 03-Jun-2016
+ */
+public interface AbstractCipherFactory {
+
+    /**
+     * Creates new CipherManager instance.<br/>
+     * 
+     * @return new cipher manager instance.
+     * @since SDNO 0.5
+     */
+    AbstractCipher createCipherManager();
+
+    /**
+     * Creates new CipherManager instance.<br/>
+     * 
+     * @param key new cipher manager instance.
+     * @return
+     * @since SDNO 0.5
+     */
+    AbstractCipher createCipherManager(final String key);
+
+}
diff --git a/CommonLibrary/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/sha/Sha256.java b/CommonLibrary/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/sha/Sha256.java
new file mode 100644 (file)
index 0000000..74cc2bb
--- /dev/null
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.encrypt.cbb.sha;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.nio.charset.StandardCharsets;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+import javax.xml.bind.DatatypeConverter;
+
+/**
+ * Utility to generate SHA256 digest and HMAC.<br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 03-Jun-2016
+ */
+public final class Sha256 {
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(Sha256.class);
+
+    private Sha256() {
+
+    }
+
+    /**
+     * Generates SHA256 digest.<br/>
+     * 
+     * @param data: The data to be digested.
+     * @return Hex encoded digested data.
+     * @since SDNO 0.5
+     */
+    public static String digest(final String data) {
+        final byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
+        MessageDigest md = null;
+        try {
+            md = MessageDigest.getInstance("SHA-256");
+        } catch(final NoSuchAlgorithmException e) {
+            LOGGER.error("No SHA-256 support ", e);
+            return "";
+        }
+        final byte[] digest = md.digest(dataBytes);
+        return DatatypeConverter.printHexBinary(digest);
+    }
+
+    /**
+     * Generates hmac signature using data and key.<br/>
+     * 
+     * @param data: The data to be signed.
+     * @param key: The signing key.
+     * @return Hex encoded HMAC signature.
+     * @throws InvalidKeyException if the key is invalid.
+     * @since SDNO 0.5
+     */
+    public static String mac(final String data, final Key key) throws InvalidKeyException {
+        final byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
+        Mac mac = null;
+        try {
+            mac = Mac.getInstance("HmacSHA256");
+            mac.init(key);
+        } catch(final NoSuchAlgorithmException e) {
+            LOGGER.error("SHA mac not supported", e);
+            return "";
+        }
+        final byte[] digest = mac.doFinal(dataBytes);
+        return DatatypeConverter.printHexBinary(digest);
+
+    }
+
+    /**
+     * Generates hmac with data and secret.
+     * <br/>
+     * 
+     * @param data: The data to be signed.
+     * @param secret: The signing key.
+     * @return Hex encoded HMAC signature.
+     * @since SDNO 0.5
+     */
+    public static String mac(final String data, final byte[] secret) {
+        final Key key = new SecretKeySpec(secret, "HmacSHA256");
+        try {
+            return mac(data, key);
+        } catch(final InvalidKeyException e) {
+            LOGGER.error("Invalid key: ", e);
+            return "";
+        }
+    }
+
+}
diff --git a/CommonLibrary/common-util/src/main/java/org/openo/baseservice/util/RestUtils.java b/CommonLibrary/common-util/src/main/java/org/openo/baseservice/util/RestUtils.java
new file mode 100644 (file)
index 0000000..ee250b1
--- /dev/null
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.util;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+
+import javax.servlet.http.HttpServletRequest;
+
+/**
+ * Utility functions for ROA.<br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 31-May-2016
+ */
+public final class RestUtils {
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(RestUtils.class);
+
+    private RestUtils() {
+
+    }
+
+    /**
+     * To get body from http request<br/>
+     * 
+     * @param request : request object.
+     * @return Request body as string.
+     * @since SDNO 0.5
+     */
+    public static String getRequestBody(final HttpServletRequest request) {
+        String body = null;
+        final StringBuilder stringBuilder = new StringBuilder();
+        BufferedReader bufferedReader = null;
+
+        try {
+            final InputStream inputStream = request.getInputStream();
+            if(inputStream != null) {
+                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
+                final char[] charBuffer = new char[128];
+                int bytesRead = -1;
+                while((bytesRead = bufferedReader.read(charBuffer)) > 0) {
+                    stringBuilder.append(charBuffer, 0, bytesRead);
+                }
+            }
+        } catch(final IOException ex) {
+            LOGGER.error("read inputStream buffer catch exception:", ex);
+        } finally {
+            if(bufferedReader != null) {
+                try {
+                    bufferedReader.close();
+                } catch(final IOException ex) {
+                    LOGGER.error("close buffer catch exception:", ex);
+                }
+            }
+        }
+
+        body = stringBuilder.toString();
+        return body;
+    }
+
+}
diff --git a/CommonLibrary/common-util/src/main/java/org/openo/baseservice/util/impl/SystemEnvVariablesDefImpl.java b/CommonLibrary/common-util/src/main/java/org/openo/baseservice/util/impl/SystemEnvVariablesDefImpl.java
new file mode 100644 (file)
index 0000000..bd98fb9
--- /dev/null
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.util.impl;
+
+import org.openo.baseservice.util.inf.SystemEnvVariables;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.IOException;
+
+/**
+ * System environment variable helper implementation.<br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 24-Jun-2016
+ */
+public class SystemEnvVariablesDefImpl extends SystemEnvVariables {
+
+    private static final Logger LOG = LoggerFactory.getLogger(SystemEnvVariablesDefImpl.class);
+
+    @Override
+    public String getAppRoot() {
+        String appRoot = null;
+        appRoot = System.getProperty("catalina.base");
+        if(appRoot != null) {
+            appRoot = getCanonicalPath(appRoot);
+        }
+        return appRoot;
+    }
+
+    /**
+     * Gets the canonical path<br/>
+     * 
+     * @param inPath input path
+     * @return the canonical path.
+     * @since SDNO 0.5
+     */
+    private String getCanonicalPath(final String inPath) {
+        String path = null;
+        try {
+            if(inPath != null) {
+                final File file = new File(inPath);
+                path = file.getCanonicalPath();
+            }
+        } catch(final IOException e) {
+            LOG.error("file.getCanonicalPath() IOException:", e);
+        }
+        return path;
+    }
+
+}
diff --git a/CommonLibrary/common-util/src/main/java/org/openo/baseservice/util/impl/SystemEnvVariablesFactory.java b/CommonLibrary/common-util/src/main/java/org/openo/baseservice/util/impl/SystemEnvVariablesFactory.java
new file mode 100644 (file)
index 0000000..e40ab53
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openo.baseservice.util.impl;
+
+import org.openo.baseservice.util.inf.SystemEnvVariables;
+
+/**
+ * SystemEnvVariables factory class
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 2016å¹´8月13æ—¥
+ */
+public class SystemEnvVariablesFactory {
+
+    private static SystemEnvVariables systemEnvVariablesInstance = new SystemEnvVariablesDefImpl();
+
+    /**
+     * get the SystemEnvVariables instance
+     * <br/>
+     * 
+     * @return SystemEnvVariables instance
+     * @since SDNO 0.5
+     */
+    public static SystemEnvVariables getInstance() {
+        return systemEnvVariablesInstance;
+    }
+}
diff --git a/CommonLibrary/common-util/src/main/java/org/openo/baseservice/util/inf/SystemEnvVariables.java b/CommonLibrary/common-util/src/main/java/org/openo/baseservice/util/inf/SystemEnvVariables.java
new file mode 100644 (file)
index 0000000..014cdbd
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.util.inf;
+
+/**
+ * Dependency the system env<br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 31-May-2016
+ */
+public abstract class SystemEnvVariables {
+
+    /**
+     * Get application root path <br/>
+     * 
+     * @return application root path.
+     * @since SDNO 0.5
+     */
+    public abstract String getAppRoot();
+}
diff --git a/CommonLibrary/common-util/src/test/java/org/openo/baseservice/encrypt/cbb/impl/AesCipherTest.java b/CommonLibrary/common-util/src/test/java/org/openo/baseservice/encrypt/cbb/impl/AesCipherTest.java
new file mode 100644 (file)
index 0000000..3241b14
--- /dev/null
@@ -0,0 +1,210 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.encrypt.cbb.impl;
+
+import java.security.NoSuchAlgorithmException;
+import java.security.spec.InvalidKeySpecException;
+
+import javax.crypto.Cipher;
+import javax.crypto.SecretKeyFactory;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.openo.baseservice.encrypt.cbb.CipherCreator;
+import org.openo.baseservice.encrypt.cbb.inf.AbstractCipher;
+
+import junit.framework.Assert;
+import mockit.Mocked;
+import mockit.NonStrictExpectations;
+
+/**
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 02-Jun-2016
+ */
+public class AesCipherTest {
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @BeforeClass
+    public static void setUpBeforeClass() throws Exception {
+        CipherCreator.instance().setFactory(new AesCipherFactory());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @AfterClass
+    public static void tearDownAfterClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @Before
+    public void setUp() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @After
+    public void tearDown() throws Exception {
+    }
+
+    /**
+     * Test method for
+     * {@link org.openo.baseservice.encrypt.cbb.impl.AesCipher#encrypt(java.lang.String)}.
+     */
+    @Test
+    public void testEncrypt() {
+        final AbstractCipher cipherManager = CipherCreator.instance().create();
+        final String encrypted = cipherManager.encrypt("test-encrypt");
+        final String decrypted = cipherManager.decrypt(encrypted);
+
+        Assert.assertEquals("test-encrypt", decrypted);
+    }
+
+    @Test
+    public void testEncryptException() throws Exception {
+        new NonStrictExpectations() {
+
+            @Mocked
+            Cipher cipher;
+
+            {
+                cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+                result = new InvalidKeySpecException();
+            }
+        };
+        final AbstractCipher cipherManager = CipherCreator.instance().create();
+        final String encrypted = cipherManager.encrypt("test-encrypt");
+
+        Assert.assertEquals(null, encrypted);
+    }
+
+    /**
+     * Test method for
+     * {@link org.openo.baseservice.encrypt.cbb.impl.AesCipher#decrypt(java.lang.String)}.
+     */
+    @Test
+    public void testDecrypt() {
+        final AbstractCipher cipherManager = CipherCreator.instance().create();
+        final String encrypted = cipherManager.encrypt("test-encrypt");
+        final String decrypted = cipherManager.decrypt(encrypted);
+
+        Assert.assertEquals("test-encrypt", decrypted);
+    }
+
+    @Test
+    public void testDecryptNull() {
+        final AbstractCipher cipherManager = CipherCreator.instance().create();
+        String decrypted = cipherManager.decrypt(null);
+        Assert.assertEquals(null, decrypted);
+
+        decrypted = cipherManager.decrypt("");
+
+        Assert.assertEquals(null, decrypted);
+    }
+
+    /**
+     * Test method for
+     * {@link
+     * org.openo.baseservice.encrypt.cbb.impl.AesCipher#CipherManagerImpl(java.lang.String)}
+     * .
+     */
+    @Test
+    public void testCipherManagerImplString() {
+        final AbstractCipher cipherManager = CipherCreator.instance().create("secret-key");
+        final String encrypted = cipherManager.encrypt("test-encrypt");
+        final String decrypted = cipherManager.decrypt(encrypted);
+
+        Assert.assertEquals("test-encrypt", decrypted);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testCipherManagerImplStringDiffKey() {
+        final String encrypted = CipherCreator.instance().create("secret-key").encrypt("test-encrypt");
+        final String decrypted = CipherCreator.instance().create("wrong-key").decrypt(encrypted);
+
+        Assert.assertNotSame("test-encrypt", decrypted);
+
+        final String decrypt = CipherCreator.instance().create("secret-key").decrypt(encrypted);
+        Assert.assertEquals("test-encrypt", decrypt);
+    }
+    
+    @Test
+    public void testCreateSecretKeyNoSuchAlgorithmException() throws Exception {
+        new NonStrictExpectations() {
+
+            @Mocked
+            SecretKeyFactory keyFactory;
+
+            {
+                keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
+                result = new NoSuchAlgorithmException();
+            }
+        };
+
+        final AbstractCipher cipherManager = CipherCreator.instance().create("secret-key");
+        final String encrypted = cipherManager.encrypt("test-encrypt");
+        Assert.assertEquals(encrypted, encrypted);
+
+    }
+
+    @Test
+    public void testCreateSecretKeyInvalidKeySpecException() throws Exception {
+        new NonStrictExpectations() {
+
+            @Mocked
+            SecretKeyFactory keyFactory;
+
+            {
+                keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
+                result = new InvalidKeySpecException();
+            }
+        };
+
+        final AbstractCipher cipherManager = CipherCreator.instance().create("secret-key");
+        final String decrypted = cipherManager.decrypt("test-encrypt");
+        Assert.assertEquals(decrypted, null);
+
+    }
+}
diff --git a/CommonLibrary/common-util/src/test/java/org/openo/baseservice/encrypt/cbb/sha/Sha256Test.java b/CommonLibrary/common-util/src/test/java/org/openo/baseservice/encrypt/cbb/sha/Sha256Test.java
new file mode 100644 (file)
index 0000000..30a640e
--- /dev/null
@@ -0,0 +1,193 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.encrypt.cbb.sha;
+
+import static org.junit.Assert.fail;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.security.InvalidKeyException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+
+import mockit.Mocked;
+import mockit.NonStrictExpectations;
+import mockit.integration.junit4.JMockit;
+
+/**
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 03-Jun-2016
+ */
+@RunWith(JMockit.class)
+public class Sha256Test {
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @BeforeClass
+    public static void setUpBeforeClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @AfterClass
+    public static void tearDownAfterClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @Before
+    public void setUp() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @After
+    public void tearDown() throws Exception {
+    }
+
+    /**
+     * Test method for {@link org.openo.baseservice.encrypt.cbb.sha.Sha256#digest(java.lang.String)}
+     * .
+     */
+    @Test
+    public void testDigest() {
+        String plain = "";
+        String expected = "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855";
+        Assert.assertEquals(expected, Sha256.digest(plain));
+
+        expected = "D7A8FBB307D7809469CA9ABCB0082E4F8D5651E46D3CDB762D02D0BF37C9E592";
+        plain = "The quick brown fox jumps over the lazy dog";
+        Assert.assertEquals(expected, Sha256.digest(plain));
+    }
+
+    @Test
+    public void testDigestException() throws Exception {
+        new NonStrictExpectations() {
+
+            @Mocked
+            MessageDigest md;
+
+            {
+                md = MessageDigest.getInstance("SHA-256");
+                result = new NoSuchAlgorithmException();
+            }
+        };
+        final String plain = "";
+        final String expected = "";
+        Assert.assertEquals(expected, Sha256.digest(plain));
+
+    }
+
+    /**
+     * Test method for
+     * {@link org.openo.baseservice.encrypt.cbb.sha.Sha256#mac(java.lang.String, java.security.Key)}
+     * .
+     * 
+     * @throws InvalidKeyException
+     */
+    @Test
+    public void testMacStringKey() {
+        final String expected = "F7BC83F430538424B13298E6AA6FB143EF4D59A14946175997479DBC2D1A3CD8";
+        final String plain = "The quick brown fox jumps over the lazy dog";
+        try {
+            Assert.assertEquals(expected, Sha256.mac(plain, new SecretKeySpec("key".getBytes(), "HmacSHA256")));
+        } catch(final InvalidKeyException e) {
+            e.printStackTrace();
+            fail("testMacStringKey failed" + e.getMessage());
+        }
+        try {
+            Assert.assertEquals(expected, Sha256.mac(plain, new SecretKeySpec("key".getBytes(), "AES")));
+        } catch(final InvalidKeyException e) {
+            e.printStackTrace();
+            fail("testMacStringKey failed" + e.getMessage());
+        }
+
+    }
+
+    @Test
+    public void testMacStringKeyException() throws Exception {
+        new NonStrictExpectations() {
+
+            @Mocked
+            Mac mac;
+
+            {
+                mac = Mac.getInstance("HmacSHA256");
+                result = new NoSuchAlgorithmException();
+            }
+        };
+        Sha256.mac("dummy", new SecretKeySpec("key".getBytes(), "AES"));
+    }
+
+    /**
+     * Test method for
+     * {@link org.openo.baseservice.encrypt.cbb.sha.Sha256#mac(java.lang.String, byte[])}.
+     */
+    @Test
+    public void testMacStringByteArray() {
+        final String expected = "F7BC83F430538424B13298E6AA6FB143EF4D59A14946175997479DBC2D1A3CD8";
+        final String plain = "The quick brown fox jumps over the lazy dog";
+        Assert.assertEquals(expected, Sha256.mac(plain, "key".getBytes()));
+    }
+
+    @Test
+    public void testMacStringByteArrayInvalidKeyException() throws Exception {
+        final String key = "key";
+        new NonStrictExpectations() {
+
+            @Mocked
+            Mac mac;
+
+            {
+                mac = Mac.getInstance("HmacSHA256");
+                result = new InvalidKeyException();
+            }
+        };
+        final String expected = "";
+        final String plain = "The quick brown fox jumps over the lazy dog";
+        Assert.assertEquals(expected, Sha256.mac(plain, key.getBytes()));
+    }
+
+}
diff --git a/CommonLibrary/common-util/src/test/java/org/openo/baseservice/util/RestUtilsTest.java b/CommonLibrary/common-util/src/test/java/org/openo/baseservice/util/RestUtilsTest.java
new file mode 100644 (file)
index 0000000..2cf0589
--- /dev/null
@@ -0,0 +1,190 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.util;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+
+import javax.servlet.ServletInputStream;
+import javax.servlet.http.HttpServletRequest;
+
+import junit.framework.Assert;
+import mockit.Expectations;
+import mockit.Mocked;
+import mockit.integration.junit4.JMockit;
+
+/**
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 08-Jun-2016
+ */
+@RunWith(JMockit.class)
+public class RestUtilsTest {
+
+    @Mocked
+    HttpServletRequest mockHttpServletRequest;
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @BeforeClass
+    public static void setUpBeforeClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @AfterClass
+    public static void tearDownAfterClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @Before
+    public void setUp() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @After
+    public void tearDown() throws Exception {
+    }
+
+    /**
+     * Test method for
+     * {@link org.openo.baseservice.util.RestUtils#getRequestBody(javax.servlet.http.HttpServletRequest)}
+     * .
+     * 
+     * @throws IOException
+     */
+    @Test
+    public void testGetRequestBody() throws IOException {
+        final String dummy = "this is a dummy data to test request body";
+        final ServletInputStream inputStream = new ServletInputStream() {
+
+            final ByteArrayInputStream stream = new ByteArrayInputStream(dummy.getBytes());
+
+            @Override
+            public int read() throws IOException {
+                return stream.read();
+            }
+
+        };
+
+        new Expectations() {
+
+            {
+                mockHttpServletRequest.getInputStream();
+                returns(inputStream);
+            }
+        };
+        final String body = RestUtils.getRequestBody(mockHttpServletRequest);
+
+        Assert.assertEquals(dummy, body);
+    }
+
+    @Test
+    public void testGetRequestBodyNull() throws IOException {
+        final ServletInputStream inputStream = null;
+        new Expectations() {
+
+            {
+                mockHttpServletRequest.getInputStream();
+                returns(inputStream);
+            }
+        };
+        final String body = RestUtils.getRequestBody(mockHttpServletRequest);
+
+        Assert.assertEquals("", body);
+    }
+
+    @Test
+    public void testGetRequestBodyIOException() throws IOException {
+        final ServletInputStream inputStream = new ServletInputStream() {
+
+            @Override
+            public int read() throws IOException {
+                throw new IOException();
+            }
+
+        };
+
+        new Expectations() {
+
+            {
+                mockHttpServletRequest.getInputStream();
+                returns(inputStream);
+            }
+        };
+        final String body = RestUtils.getRequestBody(mockHttpServletRequest);
+
+        Assert.assertEquals("", body);
+    }
+
+    @Test
+    public void testGetRequestBodyCloseIOException() throws IOException {
+        final ServletInputStream inputStream = new ServletInputStream() {
+
+            final ByteArrayInputStream stream = new ByteArrayInputStream("dummy".getBytes());
+
+            @Override
+            public int read() throws IOException {
+                return stream.read();
+            }
+
+            @Override
+            public void close() throws IOException {
+                throw new IOException();
+            }
+        };
+
+        new Expectations() {
+
+            {
+                mockHttpServletRequest.getInputStream();
+                returns(inputStream);
+            }
+        };
+        final String body = RestUtils.getRequestBody(mockHttpServletRequest);
+
+        Assert.assertEquals("dummy", body);
+    }
+
+}
diff --git a/CommonLibrary/common-util/src/test/java/org/openo/baseservice/util/impl/SystemEnvVariablesDefImplTest.java b/CommonLibrary/common-util/src/test/java/org/openo/baseservice/util/impl/SystemEnvVariablesDefImplTest.java
new file mode 100644 (file)
index 0000000..97a8d11
--- /dev/null
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.util.impl;
+
+import java.io.File;
+import java.io.IOException;
+
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openo.baseservice.util.inf.SystemEnvVariables;
+
+import junit.framework.Assert;
+import mockit.Mocked;
+import mockit.NonStrictExpectations;
+import mockit.integration.junit4.JMockit;
+import net.jcip.annotations.NotThreadSafe;
+
+/**
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 08-Jun-2016
+ */
+@RunWith(JMockit.class)
+@NotThreadSafe
+public class SystemEnvVariablesDefImplTest {
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @BeforeClass
+    public static void setUpBeforeClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @AfterClass
+    public static void tearDownAfterClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @Before
+    public void setUp() throws Exception {
+    }
+
+    @Test
+    public void testGetAppRootException() throws Exception {
+        new NonStrictExpectations() {
+
+            @Mocked
+            File file;
+
+            {
+                file = new File(".");
+                file.getCanonicalPath();
+                result = new IOException();
+            }
+
+        };
+        final SystemEnvVariables envVars =new SystemEnvVariablesDefImpl();
+        System.setProperty("catalina.base", ".");
+        final String actual = envVars.getAppRoot();
+        Assert.assertEquals(null, actual);
+    }
+
+
+    /**
+     * Test method for
+     * {@link org.openo.baseservice.util.impl.SystemEnvVariablesDefImpl#getAppRoot()}.
+     * 
+     * @throws Exception
+     */
+    @Test
+    public void testGetAppRoot() throws Exception {
+        final SystemEnvVariables envVars = new SystemEnvVariablesDefImpl();
+        final File file = new File(".");
+        final String expected = file.getCanonicalPath();
+        System.setProperty("catalina.base", ".");
+        final String actual = envVars.getAppRoot();
+        Assert.assertEquals(expected, actual);
+    }
+
+}
diff --git a/CommonLibrary/pom.xml b/CommonLibrary/pom.xml
new file mode 100644 (file)
index 0000000..2ff9e92
--- /dev/null
@@ -0,0 +1,319 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Copyright (c) 2016, Huawei Technologies Co., Ltd.
+  Licensed under the Apache License, Version 2.0 (the "License");
+  you may not use this file except in compliance with the License.
+  You may obtain a copy of the License at
+  http://www.apache.org/licenses/LICENSE-2.0
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+       <modelVersion>4.0.0</modelVersion>
+       <groupId>org.openo.baseservice</groupId>
+       <artifactId>common-setting</artifactId>
+       <version>1.0.1-SNAPSHOT</version>
+       <packaging>pom</packaging>
+       <name>common-setting</name>
+
+       <properties>
+               <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+               <maven.test.skip>false</maven.test.skip>
+               <maven.test.failure.ignore>false</maven.test.failure.ignore>
+               <finalName>${project.artifactId}-${project.version}</finalName>
+               <release.dir>${basedir}/target</release.dir>
+               <slf4j.version>1.6.1</slf4j.version>
+
+
+               <bundle.name>${project.artifactId}-${project.version}</bundle.name>
+               <pkgzip.dir>${basedir}/../release/pkgzip</pkgzip.dir>
+               <excludesFile>**/*$*</excludesFile>
+       </properties>
+    <modules>
+        <module>common-util</module>
+        <module>rest-client</module>
+    </modules>
+
+       <distributionManagement>
+               <repository>
+                       <id>releases</id>
+                       <url>http://113.200.115.170:4096/nexus/content/repositories/OPEN-O_Release</url>
+               </repository>
+               <snapshotRepository>
+                       <id>snapshots</id>
+                       <url>http://113.200.115.170:4096/nexus/content/repositories/OPEN-O_SnapShots</url>
+               </snapshotRepository>
+       </distributionManagement>
+       <dependencyManagement>
+               <dependencies>
+                       <dependency>
+                               <groupId>commons-io</groupId>
+                               <artifactId>commons-io</artifactId>
+                               <version>2.4</version>
+                       </dependency>
+                       <dependency>
+                               <groupId>org.apache.commons</groupId>
+                               <artifactId>com.springsource.org.apache.commons.lang</artifactId>
+                               <version>2.6.0</version>
+                       </dependency>
+                       <dependency>
+                               <groupId>org.apache.commons</groupId>
+                               <artifactId>com.springsource.org.apache.commons.logging</artifactId>
+                               <version>1.1.1</version>
+                       </dependency>
+                       <dependency>
+                               <groupId>org.apache.commons</groupId>
+                               <artifactId>com.springsource.org.apache.commons.codec</artifactId>
+                               <version>1.9.0</version>
+                       </dependency>
+
+                       <dependency>
+                               <groupId>org.slf4j</groupId>
+                               <artifactId>slf4j-api</artifactId>
+                               <version>${slf4j.version}</version>
+                       </dependency>
+                       <dependency>
+                               <groupId>org.slf4j</groupId>
+                               <artifactId>com.springsource.slf4j.log4j</artifactId>
+                               <version>${slf4j.version}</version>
+                       </dependency>
+                       <dependency>
+                               <groupId>org.apache.log4j</groupId>
+                               <artifactId>com.springsource.org.apache.log4j</artifactId>
+                               <version>1.2.16</version>
+                       </dependency>
+                       <dependency>
+                               <groupId>org.mybatis</groupId>
+                               <artifactId>mybatis-spring</artifactId>
+                               <version>1.2.0</version>
+                       </dependency>
+                       <dependency>
+                               <groupId>org.mybatis</groupId>
+                               <artifactId>mybatis</artifactId>
+                               <version>3.2.7</version>
+                       </dependency>
+                       <dependency>
+                               <groupId>org.apache.commons</groupId>
+                               <artifactId>commons-lang3</artifactId>
+                               <version>3.1</version>
+                       </dependency>
+                       <dependency>
+                               <groupId>org.codehaus.jackson</groupId>
+                               <artifactId>jackson-mapper-asl</artifactId>
+                               <version>1.9.2</version>
+                       </dependency>
+                       <dependency>
+                               <groupId>net.sf.json-lib</groupId>
+                               <artifactId>json-lib</artifactId>
+                               <version>2.4</version>
+                               <classifier>jdk15</classifier>
+                       </dependency>
+                       <dependency>
+                               <groupId>org.eclipse.jetty.aggregate</groupId>
+                           <artifactId>jetty-all</artifactId>
+                           <version>8.1.16.v20140903</version>
+                       </dependency>
+                       <dependency>
+                               <groupId>org.eclipse.jetty.orbit</groupId>
+                               <artifactId>javax.servlet</artifactId>
+                               <version>3.0.0.v201112011016</version>
+                               <scope>provided</scope>
+                       </dependency>
+                       <dependency>
+                               <groupId>redis.clients</groupId>
+                               <artifactId>jedis</artifactId>
+                               <version>2.8.0</version>
+                       </dependency>
+                       <dependency>
+                               <groupId>org.apache.commons</groupId>
+                               <artifactId>commons-dbcp2</artifactId>
+                               <version>2.0.1</version>
+                       </dependency>
+                       <dependency>
+                               <groupId>org.codehaus.jackson</groupId>
+                               <artifactId>jackson-mapper-asl</artifactId>
+                               <version>1.9.2</version>
+                       </dependency>
+               </dependencies>
+       </dependencyManagement>
+
+       <build>
+               <resources>
+                       <resource>
+                               <directory>${resources.dir}</directory>
+                       </resource>
+                       <resource>
+                               <directory>${project.build.directory}/generated-resources</directory>
+                       </resource>
+                       <resource>
+                               <directory>${basedir}/src/main/java</directory>
+                               <excludes>
+                                       <exclude>**/*.java</exclude>
+                               </excludes>
+                       </resource>
+                       <resource>
+                               <directory>${basedir}/src/main/resources</directory>
+                       </resource>
+               </resources>
+               <testResources>
+                       <testResource>
+                               <directory>${basedir}/src/test/java</directory>
+                               <excludes>
+                                       <exclude>**/*.java</exclude>
+                               </excludes>
+                       </testResource>
+                       <testResource>
+                               <directory>${basedir}/src/test/resources</directory>
+                       </testResource>
+               </testResources>
+               <pluginManagement>
+                       <plugins>
+                               <plugin>
+                                       <groupId>org.apache.maven.plugins</groupId>
+                                       <artifactId>maven-antrun-plugin</artifactId>
+                                       <version>1.6</version>
+                                       <dependencies>
+                                               <dependency>
+                                                       <groupId>ant-contrib</groupId>
+                                                       <artifactId>ant-contrib</artifactId>
+                                                       <version>1.0b3</version>
+                                                       <exclusions>
+                                                               <exclusion>
+                                                                       <groupId>ant</groupId>
+                                                                       <artifactId>ant</artifactId>
+                                                               </exclusion>
+                                                       </exclusions>
+                                               </dependency>
+                                               <dependency>
+                                                       <groupId>com.google.js</groupId>
+                                                       <artifactId>closure-compiler</artifactId>
+                                                       <version>1.0.0</version>
+                                               </dependency>
+                                               <dependency>
+                                                       <groupId>com.google.closure-stylesheets</groupId>
+                                                       <artifactId>closure-stylesheets</artifactId>
+                                                       <version>20140426</version>
+                                               </dependency>
+                                       </dependencies>
+                               </plugin>
+                               <plugin>
+                                       <groupId>org.apache.maven.plugins</groupId>
+                                       <artifactId>maven-clean-plugin</artifactId>
+                                       <version>2.4.1</version>
+                               </plugin>
+                               <plugin>
+                                       <groupId>org.apache.maven.plugins</groupId>
+                                       <artifactId>maven-release-plugin</artifactId>
+                                       <version>2.5.2</version>
+                                       <configuration>
+                                               <checkModificationExcludes>
+                                                       <checkModificationExclude>**/*.java</checkModificationExclude>
+                                               </checkModificationExcludes>
+                                               <allowTimestampedSnapshots>true</allowTimestampedSnapshots>
+                                       </configuration>
+                               </plugin>
+
+                       </plugins>
+               </pluginManagement>
+               <plugins>
+                       <!--Release -->
+                       <plugin>
+                               <groupId>org.apache.maven.plugins</groupId>
+                               <artifactId>maven-release-plugin</artifactId>
+                       </plugin>
+
+                       <!--plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> 
+                               <version>2.4-fixed</version> <configuration> <srcLocation>${srcLocation}</srcLocation> 
+                               <classOutputDir>${classOutputDir}</classOutputDir> </configuration> </plugin -->
+
+                       <plugin>
+                               <groupId>org.apache.maven.plugins</groupId>
+                               <artifactId>maven-deploy-plugin</artifactId>
+                               <version>2.7</version>
+                               <configuration>
+                                       <retryFailedDeploymentCount>2</retryFailedDeploymentCount>
+                               </configuration>
+                       </plugin>
+
+
+                       <!-- javadoc -->
+                       <plugin>
+                               <groupId>org.apache.maven.plugins</groupId>
+                               <artifactId>maven-javadoc-plugin</artifactId>
+                               <version>2.6.1</version>
+                               <configuration>
+                                       <aggregate>true</aggregate>
+                                       <stylesheetfile>${javadoc.loc}/javadoc.css</stylesheetfile>
+                                       <overview>${javadoc.loc}/overview.html</overview>
+                                       <excludePackageNames>org.apache.*,*.impl</excludePackageNames>
+                                       <breakiterator>true</breakiterator>
+                                       <quiet>true</quiet>
+                                       <failOnError>false</failOnError>
+                                       <verbose>false</verbose>
+                                       <show>protected</show>
+                                       <source>1.5</source>
+                                       <charset>gb2312</charset>
+                                       <encoding>UTF-8</encoding>
+                                       <docencoding>gb2312</docencoding>
+                                       <maxmemory>256M</maxmemory>
+                               </configuration>
+                       </plugin>
+                       <plugin>
+                               <groupId>org.apache.maven.plugins</groupId>
+                               <artifactId>maven-compiler-plugin</artifactId>
+                               <version>3.3</version>
+                               <configuration>
+                                       <source>1.7</source>
+                                       <target>1.7</target>
+                               </configuration>
+                       </plugin>
+                       <plugin>
+                               <groupId>org.apache.maven.plugins</groupId>
+                               <artifactId>maven-jar-plugin</artifactId>
+                               <version>2.3.1</version>
+                               <configuration>
+                                       <finalName>${bundle.name}</finalName>
+                                       <outputDirectory>${release.dir}</outputDirectory>
+                               </configuration>
+                       </plugin>
+                       <!-- clean -->
+                       <plugin>
+                               <artifactId>maven-clean-plugin</artifactId>
+                               <configuration>
+                                       <failOnError>false</failOnError>
+                                       <filesets>
+                                               <fileset>
+                                                       <directory>${release.dir}</directory>
+                                                       <includes>
+                                                               <include>${bundle.name}.${project.packaging}</include>
+                                                       </includes>
+                                               </fileset>
+                                       </filesets>
+                               </configuration>
+                       </plugin>
+
+               </plugins>
+       </build>
+       <reporting>
+               <plugins>
+                       <plugin>
+                               <groupId>org.apache.maven.plugins</groupId>
+                               <artifactId>maven-javadoc-plugin</artifactId>
+                               <version>2.6.1</version>
+                               <configuration>
+                                       <aggregate>true</aggregate>
+                                       <quiet>true</quiet>
+                                       <show>public</show>
+                               </configuration>
+                       </plugin>
+               </plugins>
+       </reporting>
+
+</project>
diff --git a/CommonLibrary/rest-client/.gitignore b/CommonLibrary/rest-client/.gitignore
new file mode 100644 (file)
index 0000000..b83d222
--- /dev/null
@@ -0,0 +1 @@
+/target/
diff --git a/CommonLibrary/rest-client/pom.xml b/CommonLibrary/rest-client/pom.xml
new file mode 100644 (file)
index 0000000..33f24c3
--- /dev/null
@@ -0,0 +1,89 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Copyright (c) 2016, Huawei Technologies Co., Ltd.
+  Licensed under the Apache License, Version 2.0 (the "License");
+  you may not use this file except in compliance with the License.
+  You may obtain a copy of the License at
+  http://www.apache.org/licenses/LICENSE-2.0
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+-->
+<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>org.openo.baseservice</groupId>
+       <artifactId>common-setting</artifactId>
+       <version>1.0.1-SNAPSHOT</version>
+    </parent>
+    <artifactId>commonlib-restclient</artifactId>
+    <properties>
+    </properties>
+    <dependencies>
+        <dependency>
+            <groupId>org.openo.baseservice</groupId>
+            <artifactId>commonlib-cbb</artifactId>
+            <version>1.0.1-SNAPSHOT</version>
+        </dependency>
+        <dependency>
+            <groupId>org.eclipse.jetty.aggregate</groupId>
+            <artifactId>jetty-all</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <scope>test</scope>
+            <version>4.8.2</version>
+        </dependency>
+        <dependency>
+            <groupId>org.jmockit</groupId>
+            <artifactId>jmockit</artifactId>
+            <scope>test</scope>
+            <version>1.18</version>
+        </dependency>
+
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-surefire-plugin</artifactId>
+                <configuration>
+                       <forkMode>always</forkMode>
+                    <argLine>-XX:-UseSplitVerifier</argLine>
+                    <skip>${maven.test.skip}</skip>
+                    <testFailureIgnore>${maven.test.failure.ignore}</testFailureIgnore>
+                    <excludes>
+                        <exclude>${excludesFile}</exclude>
+                    </excludes>
+                </configuration>
+            </plugin>
+            <plugin>
+                <groupId>org.codehaus.mojo</groupId>
+                <artifactId>cobertura-maven-plugin</artifactId>
+                <version>2.6</version>
+                <configuration>
+                    <formats>
+                        <format>xml</format>
+                        <format>html</format>
+                    </formats>
+                </configuration>
+                <executions>
+                    <execution>
+                        <phase>package</phase>
+                        <goals>
+                            <goal>cobertura</goal>
+                        </goals>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+    </build>
+</project>
diff --git a/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/remoteservice/exception/ExceptionArgs.java b/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/remoteservice/exception/ExceptionArgs.java
new file mode 100644 (file)
index 0000000..40dd2b1
--- /dev/null
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.remoteservice.exception;
+
+/**
+ * ROA exception handling parameters.
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 28-May-2016
+ */
+public class ExceptionArgs {
+
+    /**
+     * Exception descriptions.
+     */
+    private String[] descArgs = null;
+
+    /**
+     * Exception reasons.
+     */
+    private String[] reasonArgs = null;
+
+    /**
+     * Exception detals.
+     */
+    private String[] detailArgs = null;
+
+    /**
+     * Exception advices.
+     */
+    private String[] adviceArgs = null;
+
+    /**
+     * Constructor<br/>
+     * <p>
+     * </p>
+     * 
+     * @since SDNO 0.5
+     */
+    public ExceptionArgs() {
+        // default constructor.
+    }
+
+    /**
+     * Constructor<br/>
+     * <p>
+     * </p>
+     * 
+     * @since SDNO 0.5
+     * @param descArgs: descriptions.
+     * @param reasonArgs: reasons.
+     * @param detailArgs: details.
+     * @param adviceArgs: advices.
+     */
+    public ExceptionArgs(final String[] descArgs, final String[] reasonArgs, final String[] detailArgs,
+            final String[] adviceArgs) {
+        this.descArgs = descArgs;
+        this.reasonArgs = reasonArgs;
+        this.detailArgs = detailArgs;
+        this.adviceArgs = adviceArgs;
+    }
+
+    public String[] getDescArgs() {
+        return descArgs;
+    }
+
+    public void setDescArgs(final String[] descArgs) {
+        this.descArgs = descArgs;
+    }
+
+    public String[] getReasonArgs() {
+        return reasonArgs;
+    }
+
+    public void setReasonArgs(final String[] reasonArgs) {
+        this.reasonArgs = reasonArgs;
+    }
+
+    public String[] getDetailArgs() {
+        return detailArgs;
+    }
+
+    public void setDetailArgs(final String[] detailArgs) {
+        this.detailArgs = detailArgs;
+    }
+
+    public String[] getAdviceArgs() {
+        return adviceArgs;
+    }
+
+    public void setAdviceArgs(final String[] adviceArgs) {
+        this.adviceArgs = adviceArgs;
+    }
+}
diff --git a/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/remoteservice/exception/ServiceException.java b/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/remoteservice/exception/ServiceException.java
new file mode 100644 (file)
index 0000000..e64d914
--- /dev/null
@@ -0,0 +1,254 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.remoteservice.exception;
+
+import java.text.MessageFormat;
+
+/**
+ * The base class for all common exception.<br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 28-May-2016
+ */
+public class ServiceException extends Exception {
+
+    /**
+     * default exception id.
+     */
+    public static final String DEFAULT_ID = "framwork.remote.SystemError";
+
+    /**
+     * Serial number.
+     */
+    private static final long serialVersionUID = 5703294364555144738L;
+
+    /**
+     * Exception id.
+     */
+    private String id = DEFAULT_ID;
+
+    private Object[] args = null;
+
+    private int httpCode = 500;
+
+    private ExceptionArgs exceptionArgs = null;
+
+    /**
+     * The default constructor<br/>
+     * <p>
+     * This method is only used as deserialized, in other cases, use parameterized constructor.
+     * </p>
+     * 
+     * @since SDNO 0.5
+     */
+    public ServiceException() {
+        super("");
+    }
+
+    /**
+     * Constructor<br/>
+     * <p>
+     * </p>
+     * 
+     * @since SDNO 0.5
+     * @param id: details.
+     * @param cause: reason.
+     */
+    public ServiceException(final String id, final Throwable cause) {
+        super(cause);
+        this.setId(id);
+    }
+
+    /**
+     * Constructor<br/>
+     * <p>
+     * </p>
+     * 
+     * @since SDNO 0.5
+     * @param message: details.
+     */
+    public ServiceException(final String message) {
+        super(message);
+    }
+
+    /**
+     * Constructor<br/>
+     * <p>
+     * </p>
+     * 
+     * @since SDNO 0.5
+     * @param id: exception id.
+     * @param message: details.
+     */
+    public ServiceException(final String id, final String message) {
+        super(message);
+        this.setId(id);
+    }
+
+    /**
+     * Constructor<br/>
+     * <p>
+     * </p>
+     * 
+     * @since SDNO 0.5
+     * @param id: exception id.
+     * @param httpCode: http status code.
+     */
+    public ServiceException(final String id, final int httpCode) {
+        super();
+        this.setId(id);
+        this.setHttpCode(httpCode);
+    }
+
+    /**
+     * Constructor<br/>
+     * <p>
+     * </p>
+     * 
+     * @since SDNO 0.5
+     * @param id: exception id.
+     * @param httpCode: http code.
+     * @param exceptionArgs: Exception handling frame parameters.
+     */
+    public ServiceException(final String id, final int httpCode, final ExceptionArgs exceptionArgs) {
+        super();
+        this.setId(id);
+        this.setHttpCode(httpCode);
+        this.setExceptionArgs(exceptionArgs);
+    }
+
+    /**
+     * Constructor<br/>
+     * <p>
+     * Have a placeholder exception, use args formatted message.
+     * </p>
+     * 
+     * @since SDNO 0.5
+     * @param id: exception id.
+     * @param message: details.
+     * @param args: Placeholders for parameters
+     */
+    public ServiceException(final String id, final String message, final Object... args) {
+        super(MessageFormat.format(message, args));
+        this.setId(id);
+        this.args = args;
+    }
+
+    /**
+     * Constructor<br/>
+     * <p>
+     * Have a placeholder exception, use args formatted message
+     * </p>
+     * 
+     * @since SDNO 0.5
+     * @param id: exception id.
+     * @param message: details.
+     * @param cause: reason.
+     * @param args: placeholder for parameters
+     */
+    public ServiceException(final String id, final String message, final Throwable cause, final Object... args) {
+        super(MessageFormat.format(message, args), cause);
+        this.setId(id);
+        this.args = args;
+    }
+
+    /**
+     * Constructor<br/>
+     * <p>
+     * </p>
+     * 
+     * @since SDNO 0.5
+     * @param id: exception id.
+     * @param message: details.
+     * @param cause: reason.
+     */
+    public ServiceException(final String id, final String message, final Throwable cause) {
+        super(message, cause);
+        this.setId(id);
+    }
+
+    /**
+     * Constructor<br/>
+     * <p>
+     * </p>
+     * 
+     * @since SDNO 0.5
+     * @param cause: reason.
+     */
+    public ServiceException(final Throwable cause) {
+        super(cause);
+    }
+
+    /**
+     * Get exceptoin id.<br/>
+     * 
+     * @return
+     * @since SDNO 0.5
+     */
+    public String getId() {
+        if(id == null || id.isEmpty()) {
+            return DEFAULT_ID;
+        }
+        return id;
+    }
+
+    public void setId(final String id) {
+        this.id = id;
+    }
+
+    public int getHttpCode() {
+        return this.httpCode;
+    }
+
+    public void setHttpCode(final int httpCode) {
+        this.httpCode = httpCode;
+    }
+
+    /**
+     * Obtain the ROA exception handling framework parameters<br/>
+     * 
+     * @return exception args.
+     * @since SDNO 0.5
+     */
+    public ExceptionArgs getExceptionArgs() {
+        return exceptionArgs;
+    }
+
+    public void setExceptionArgs(final ExceptionArgs exceptionArgs) {
+        this.exceptionArgs = exceptionArgs;
+    }
+
+    /**
+     * Gets the parameter information<br/>
+     * 
+     * @return parameter list.
+     * @since SDNO 0.5
+     */
+    protected Object[] getArgs() {
+        if(args == null || args.length == 0 || DEFAULT_ID.equals(getId())) {
+            return new Object[] {};
+        }
+        return args;
+    }
+
+    @Override
+    public String toString() {
+        return "exception.id: " + getId() + "; " + super.toString();
+    }
+
+}
diff --git a/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/ReaderHelper.java b/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/ReaderHelper.java
new file mode 100644 (file)
index 0000000..86124cf
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.roa.util;
+
+import org.apache.commons.io.LineIterator;
+
+import java.io.Reader;
+
+/**
+ * Helper for read line.<br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 31-May-2016
+ */
+public class ReaderHelper {
+
+    private LineIterator ite = null;
+
+    /**
+     * Constructor<br/>
+     * <p>
+     * </p>
+     * 
+     * @since SDNO 0.5
+     * @param reader
+     */
+    public ReaderHelper(final Reader reader) {
+        if(reader != null) {
+            ite = new LineIterator(reader);
+        }
+
+    }
+
+    /**
+     * Gets the next line.<br/>
+     * 
+     * @return line if present else null.
+     * @since SDNO 0.5
+     */
+    public String getLine() {
+        if(ite != null && ite.hasNext()) {
+            return ite.nextLine();
+        }
+        return null;
+    }
+}
diff --git a/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/ServiceUtil.java b/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/ServiceUtil.java
new file mode 100644 (file)
index 0000000..aca60c0
--- /dev/null
@@ -0,0 +1,177 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.roa.util;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Enumeration;
+import java.util.Properties;
+
+/**
+ * Service connection configuration util.<br/>
+ * <p>
+ * Get host and port from the Client Configure the connection environment and service Configure
+ * profile
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 28-May-2016
+ */
+public class ServiceUtil {
+
+    private static final Logger LOG = LoggerFactory.getLogger(ServiceUtil.class);
+
+    private final Properties allConfigure = new Properties();
+
+    private final Properties serviceConfigure;
+
+    private String serviceStage;
+
+    private String serviceName;
+
+    /**
+     * Constructor<br/>
+     * <p>
+     * Load profile information.
+     * </p>
+     * 
+     * @since SDNO 0.5
+     * @param serviceName user-specified service name.
+     * @param url invoked service url.
+     */
+    public ServiceUtil(final String serviceName, final String url) {
+        final String fomattedUrl = formatUrl(url);
+        serviceConfigure = loadProperties("service-configure.properties");
+        if(null == serviceName || serviceName.isEmpty()) {
+            this.serviceName = getServiceNameWhitUrl(fomattedUrl);
+        } else {
+            this.serviceName = serviceName;
+        }
+        loadPropertyFile();
+    }
+
+    /**
+     * Get the service user-specified host.
+     * <br/>
+     * 
+     * @return host
+     * @since SDNO 0.5
+     */
+    public String getServiceHost() {
+        final String host = allConfigure.getProperty(serviceName + "." + serviceStage + ".host");
+        if(null == host) {
+            return "";
+        }
+        return host;
+    }
+
+    /**
+     * Get the service user-specified port.
+     * <br/>
+     * 
+     * @return port
+     * @since SDNO 0.5
+     */
+    public int getServicePort() {
+        final String portStr = allConfigure.getProperty(serviceName + "." + serviceStage + ".port");
+        if(null == portStr) {
+            return -1;
+        }
+        return Integer.parseInt(portStr);
+    }
+
+    private String getServiceNameWhitUrl(final String url) {
+        final Enumeration<?> keys = serviceConfigure.propertyNames();
+        while(keys.hasMoreElements()) {
+            final String key = (String)keys.nextElement();
+            if(key.endsWith("urls")) {
+                final String urls = serviceConfigure.getProperty(key);
+                for(String tempUrl : urls.split(",")) {
+                    tempUrl = formatUrl(tempUrl);
+                    if(url.startsWith(tempUrl)) {
+                        return key.split("\\.")[0];
+                    }
+                }
+
+            }
+        }
+        return "";
+    }
+
+    private static String formatUrl(final String url) {
+        String outUrl = url;
+        if(outUrl.contains("?")) {
+            outUrl = outUrl.split("\\?")[0];
+        }
+        outUrl = outUrl.replace("\\", "/");
+        outUrl = outUrl.replaceAll("[/]{2,}", "/");
+        outUrl = outUrl.endsWith("/") ? outUrl.substring(0, outUrl.length() - 1) : outUrl;
+        outUrl = outUrl.endsWith("/*") ? outUrl.substring(0, outUrl.length() - 2) : outUrl;
+        return outUrl;
+    }
+
+    /**
+     * Loads the client and service configuration files.
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    private void loadPropertyFile() {
+        final Properties clientConfigure = loadProperties(serviceName + "-client-configure.properties");
+        allConfigure.putAll(clientConfigure);
+        allConfigure.putAll(serviceConfigure);
+        serviceStage = allConfigure.getProperty(serviceName + ".stage");
+    }
+
+    /**
+     * Loads the client and service configuration files.
+     * <br/>
+     * 
+     * @param classProperties: service profile file name.
+     * @return Service configuration.
+     * @since SDNO 0.5
+     */
+    private Properties loadProperties(final String classProperties) {
+        final Properties properties = new Properties();
+        InputStream inputStream = null;
+        ClassLoader classloader = null;
+        try {
+            classloader = this.getClass().getClassLoader();
+            if(classloader != null) {
+                inputStream = classloader.getResourceAsStream(classProperties);
+            }
+            if(inputStream != null) {
+                properties.load(inputStream);
+                inputStream.close();
+            }
+        } catch(final IOException e) {
+            LOG.error("load file error: ", e);
+        } finally {
+            if(inputStream != null) {
+                try {
+                    inputStream.close();
+                } catch(final IOException ee) {
+                    LOG.error("close inputStream  error: ", ee);
+                }
+                inputStream = null;
+            }
+        }
+        return properties;
+    }
+}
diff --git a/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/clientsdk/HttpUtil.java b/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/clientsdk/HttpUtil.java
new file mode 100644 (file)
index 0000000..3c6493c
--- /dev/null
@@ -0,0 +1,169 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.roa.util.clientsdk;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.Collection;
+import java.util.Date;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Http utilities.
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 28-May-2016
+ */
+public class HttpUtil {
+
+    /**
+     * 
+     */
+    private static final String APPLICATION_JSON = "application/json";
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);
+
+    private HttpUtil() {
+
+    }
+
+    /**
+     * Check if the given array contains the given value (with case-insensitive comparison).
+     * <br/>
+     * 
+     * @param array The array
+     * @param value The value to search
+     * @return true if the array contains the value
+     * @since SDNO 0.5
+     */
+    public static boolean containsIgnoreCase(final String[] array, final String value) {
+        for(final String str : array) {
+            if(value == null && str == null) {
+                return true;
+            }
+            if(value != null && value.equalsIgnoreCase(str)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Join an array of strings with the given separator.
+     * <br/>
+     * 
+     * @param array The array of strings
+     * @param separator The separator
+     * @return the resulting string
+     * @since SDNO 0.5
+     */
+    public static String join(final String[] array, final String separator) {
+        final int len = array.length;
+        if(len == 0) {
+            return "";
+        }
+        final StringBuilder out = new StringBuilder();
+        out.append(array[0]);
+        for(int i = 1; i < len; i++) {
+            out.append(separator).append(array[i]);
+        }
+        return out.toString();
+    }
+
+    /**
+     * Format the given parameter object into string.
+     * <br/>
+     * 
+     * @param param param input
+     * @return query param string
+     * @since SDNO 0.5
+     */
+    public static String parameterToString(final Object param) {
+        if(param == null) {
+            return "";
+        } else if(param instanceof Date) {
+            return Long.toString(((Date)param).getTime());
+        } else if(param instanceof Collection) {
+            final StringBuilder b = new StringBuilder();
+            for(final Object o : (Collection)param) {
+                if(b.length() > 0) {
+                    b.append(',');
+                }
+                b.append(String.valueOf(o));
+            }
+            return b.toString();
+        } else {
+            return String.valueOf(param);
+        }
+    }
+
+    /**
+     * get accept header
+     * <br/>
+     * 
+     * @param accepts accepts accept types
+     * @return the accepts string
+     * @since SDNO 0.5
+     */
+    public static String selectHeaderAccept(final String[] accepts) {
+        if(accepts.length == 0) {
+            return null;
+        }
+        if(HttpUtil.containsIgnoreCase(accepts, APPLICATION_JSON)) {
+            return APPLICATION_JSON;
+        }
+        return HttpUtil.join(accepts, ",");
+    }
+
+    /**
+     * select head content type
+     * <br/>
+     * 
+     * @param contentTypes contentTypes content types
+     * @return the json string or the first content type
+     * @since SDNO 0.5
+     */
+    public static String selectHeaderContentType(final String[] contentTypes) {
+        if(contentTypes.length == 0) {
+            return APPLICATION_JSON;
+        }
+        if(HttpUtil.containsIgnoreCase(contentTypes, APPLICATION_JSON)) {
+            return APPLICATION_JSON;
+        }
+        return contentTypes[0];
+    }
+
+    /**
+     * Escape the given string to be used as URL query value.<br/>
+     * 
+     * @param str str param str
+     * @return escape string
+     * @since SDNO 0.5
+     */
+    public static String escapeString(final String str) {
+        try {
+            return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20");
+        } catch(final UnsupportedEncodingException e) {
+            LOGGER.info("UTF8 is not supported", e);
+            return str;
+        }
+    }
+}
diff --git a/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/clientsdk/JsonUtil.java b/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/clientsdk/JsonUtil.java
new file mode 100644 (file)
index 0000000..2234e19
--- /dev/null
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.roa.util.clientsdk;
+
+import org.codehaus.jackson.map.ObjectMapper;
+import org.codehaus.jackson.type.TypeReference;
+
+import net.sf.json.JSON;
+
+import java.io.IOException;
+
+/**
+ * JSON parse utilities.
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 28-May-2016
+ */
+public final class JsonUtil {
+
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    static {
+        MAPPER.setDeserializationConfig(MAPPER.getDeserializationConfig()
+                .without(org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES));
+    }
+
+    private JsonUtil() {
+    }
+
+    /**
+     * Parse JSON formated string.<br/>
+     * 
+     * @param jsonstr: JSON formated string.
+     * @param type: result type.
+     * @return parsed object.
+     * @throws IOException incase error.
+     * @since SDNO 0.5
+     */
+    public static <T> T unMarshal(final String jsonstr, final Class<T> type) throws IOException {
+        return MAPPER.readValue(jsonstr, type);
+    }
+
+    /**
+     * Parse JSON formatted string (for a generic target type).
+     * <br/>
+     * 
+     * @param jsonstr request data.
+     * @param type target type.
+     * @return result object.
+     * @throws IOException incase error.
+     * @since SDNO 0.5
+     */
+    public static <T> T unMarshal(final String jsonstr, final TypeReference<T> type) throws IOException {
+        return MAPPER.readValue(jsonstr, type);
+    }
+
+    /**
+     * Convert object to JSON format string.
+     * <br/>
+     * 
+     * @param srcObj source object.
+     * @return JSON format string.
+     * @throws IOException incase of error.
+     * @since SDNO 0.5
+     */
+    public static String marshal(final Object srcObj) throws IOException {
+        if(srcObj instanceof JSON) {
+            return srcObj.toString();
+        }
+        return MAPPER.writeValueAsString(srcObj);
+    }
+
+    /**
+     * Get parsing mapper
+     * <br/>
+     * 
+     * @return parsing mapper
+     * @since SDNO 0.5
+     */
+    public static ObjectMapper getMapper() {
+        return MAPPER;
+    }
+}
diff --git a/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/clientsdk/RestClientUtil.java b/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/clientsdk/RestClientUtil.java
new file mode 100644 (file)
index 0000000..b769f0a
--- /dev/null
@@ -0,0 +1,133 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.roa.util.clientsdk;
+
+import org.openo.baseservice.remoteservice.exception.ServiceException;
+import org.openo.baseservice.roa.util.restclient.Restful;
+import org.openo.baseservice.roa.util.restclient.RestfulAsyncCallback;
+import org.openo.baseservice.roa.util.restclient.RestfulParametes;
+import org.openo.baseservice.roa.util.restclient.RestfulResponse;
+
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * Rest Client Tools.
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 28-May-2016
+ */
+public class RestClientUtil {
+
+    private static Set<Class<?>> ret = new HashSet<>();
+
+    static {
+        ret.add(Boolean.class);
+        ret.add(Character.class);
+        ret.add(Byte.class);
+        ret.add(Short.class);
+        ret.add(Integer.class);
+        ret.add(Long.class);
+        ret.add(Float.class);
+        ret.add(Double.class);
+        ret.add(Void.class);
+        ret.add(String.class);
+    }
+
+    private RestClientUtil() {
+
+    }
+
+    /**
+     * Processing HTTP requests.
+     * <br/>
+     * 
+     * @param method method name.
+     * @param path request path.
+     * @param parameters parameters.
+     * @param restFull ReST request instance
+     * @return The ReST response.
+     * @throws ServiceException Exception information.
+     * @since SDNO 0.5
+     */
+    public static RestfulResponse invokeMethod(final String method, final String path,
+            final RestfulParametes parameters, final Restful restFull) throws ServiceException {
+        RestfulResponse response;
+        if("get".equalsIgnoreCase(method)) {
+            response = restFull.get(path, parameters);
+        } else if("put".equalsIgnoreCase(method)) {
+            response = restFull.put(path, parameters);
+        } else if("post".equalsIgnoreCase(method)) {
+            response = restFull.post(path, parameters);
+        } else if("delete".equalsIgnoreCase(method)) {
+            response = restFull.delete(path, parameters);
+        } else if("patch".equalsIgnoreCase(method)) {
+            response = restFull.patch(path, parameters);
+        } else {
+            throw new ServiceException("NotSuppertMethod", 400);
+        }
+        return response;
+    }
+
+    /**
+     * An asynchronous HTTP request.
+     * <br/>
+     * 
+     * @param method http method.
+     * @param path request path.
+     * @param parameters request parameters.
+     * @param restFull restFull instance.
+     * @param callback callback function.
+     * @throws ServiceException in case error.
+     * @since SDNO 0.5
+     */
+    public static void invokeAsyncMethod(final String method, final String path, final RestfulParametes parameters,
+            final Restful restFull, final RestfulAsyncCallback callback) throws ServiceException {
+        if("get".equalsIgnoreCase(method)) {
+            restFull.asyncGet(path, parameters, callback);
+        } else if("put".equalsIgnoreCase(method)) {
+            restFull.asyncPut(path, parameters, callback);
+        } else if("post".equalsIgnoreCase(method)) {
+            restFull.asyncPost(path, parameters, callback);
+        } else if("delete".equalsIgnoreCase(method)) {
+            restFull.asyncDelete(path, parameters, callback);
+        } else if("patch".equalsIgnoreCase(method)) {
+            restFull.asyncPatch(path, parameters, callback);
+        } else {
+            throw new ServiceException("NotSuppertMethod", 400);
+        }
+    }
+
+    /**
+     * Determine whether a class is a native.<br/>
+     * 
+     * @param clazz: class type.
+     * @return whether primitive or not.
+     * @since SDNO 0.5
+     */
+    public static boolean isPrimitive(final Class<?> clazz) {
+        if(clazz.isPrimitive()) {
+            return true;
+        }
+        if(ret.contains(clazz)) {
+            return true;
+        }
+        return false;
+    }
+}
diff --git a/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/DefaultAsyncCallback.java b/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/DefaultAsyncCallback.java
new file mode 100644 (file)
index 0000000..8195b0d
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.roa.util.restclient;
+
+/**
+ * Restful Asynchronous call back implentation.<br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 28-May-2016
+ */
+public class DefaultAsyncCallback implements RestfulAsyncCallback {
+
+    @Override
+    public void callback(final RestfulResponse response) {
+        // default implementation.
+    }
+
+    @Override
+    public void handleExcepion(final Throwable e) {
+        // default implementation
+    }
+}
diff --git a/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/HttpBaseRest.java b/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/HttpBaseRest.java
new file mode 100644 (file)
index 0000000..4f58778
--- /dev/null
@@ -0,0 +1,291 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openo.baseservice.roa.util.restclient;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.eclipse.jetty.client.Address;
+import org.eclipse.jetty.client.HttpClient;
+import org.eclipse.jetty.client.HttpExchange;
+import org.eclipse.jetty.http.HttpMethods;
+import org.openo.baseservice.remoteservice.exception.ServiceException;
+import org.openo.baseservice.roa.util.ServiceUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 Aug 9, 2016
+ */
+public abstract class HttpBaseRest implements Restful {
+
+    private static final Logger LOG = LoggerFactory.getLogger(HttpRest.class);
+
+    final AtomicInteger requestId = new AtomicInteger(0);
+
+    protected HttpClient client = null;
+
+    private static final String LOCAL_HOST = "127.0.0.1";
+
+    static final String HTTP_PATCH = "PATCH";
+
+    String defaultIP = LOCAL_HOST;
+
+    int defaultPort = -10000;
+
+    int defaultTimeout = 30000;
+
+    final String procenameRouteID = "RouteID-" + System.currentTimeMillis() + "-";
+
+    /**
+     * Constructor<br/>
+     * <p>
+     * </p>
+     * 
+     * @since SDNO 0.5
+     */
+    public HttpBaseRest() {
+        super();
+    }
+
+    protected void createHttpClient() {
+        client = new HttpClient();
+    }
+
+    protected RestHttpContentExchange createRestHttpContentExchange(final RestfulAsyncCallback callback) {
+        final RestHttpContentExchange exchange = new RestHttpContentExchange(true, callback);
+        exchange.setScheme("http");
+        return exchange;
+    }
+
+    private String encodeParams(final RestfulParametes restParametes) throws ServiceException {
+        final Map<String, String> parm = restParametes.getParamMap();
+        String value = null;
+        boolean bHasParma = false;
+        final StringBuilder builder = new StringBuilder();
+        try {
+            for(final String key : parm.keySet()) {
+                value = parm.get(key);
+                if(value == null) {
+                    value = "";
+                }
+                String str;
+                if(bHasParma) {
+                    str = String.format("&%s=%s", URLEncoder.encode(key, RestfulClientConst.ENCODING),
+                            URLEncoder.encode(value, RestfulClientConst.ENCODING));
+                } else {
+                    bHasParma = true;
+                    str = String.format("%s=%s", URLEncoder.encode(key, RestfulClientConst.ENCODING),
+                            URLEncoder.encode(value, RestfulClientConst.ENCODING));
+                }
+                builder.append(str);
+            }
+        } catch(final UnsupportedEncodingException ex) {
+            LOG.error("unsupported encoding: ", ex);
+            throw new ServiceException("Broken VM does not support UTF-8");
+        }
+        return builder.toString();
+    }
+
+    private void processHeader(final RestHttpContentExchange contentExchange, final Map<String, String> headerMap) {
+        for(final String key : headerMap.keySet()) {
+            final String value = headerMap.get(key);
+            contentExchange.addRequestHeader(key, value);
+        }
+
+    }
+
+    private void setContentExchangeParams(final RestHttpContentExchange contentExchange) {
+        final String contentType = contentExchange.getRequestFields().getStringField("Content-Type");
+        if(null == contentType || contentType.isEmpty()) {
+            // application/json;charset=utf-8
+            contentExchange.setRequestContentType(RestfulClientConst.APPLICATION_FORM_URLENCODED);
+        }
+        final String encoding = contentExchange.getRequestFields().getStringField("Accept-Encoding");
+        if(null == encoding || encoding.isEmpty()) {
+            // compress,gzip
+            contentExchange.setRequestHeader("Accept-Encoding", "*/*");
+        }
+        contentExchange.setVersion(11);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @param method
+     * @param servicePath
+     * @param restParametes
+     * @param options
+     * @param callback
+     * @return
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    protected RestfulResponse sendHttpRequest(final String method, final String servicePath,
+            final RestfulParametes restParametes, final RestfulOptions options, final RestfulAsyncCallback callback)
+            throws ServiceException {
+        final RestHttpContentExchange contentExchange = createRestHttpContentExchange(callback);
+        if(null == restParametes) {
+            return new RestfulResponse();
+        }
+        final String requestTrace = this.getReuqestIdString();
+        restParametes.putHttpContextHeader(RestfulClientConst.REQUEST_ID, requestTrace);
+
+        RestfulResponse rsp = null;
+        try {
+            contentExchange.setMethod(method);
+            final String str = encodeParams(restParametes);
+            final StringBuilder builder = new StringBuilder();
+            builder.append(servicePath);
+            if(str.length() > 0 && (method.equals(HttpMethods.GET) || method.equals(HttpMethods.DELETE)
+                    || method.equals(HttpMethods.HEAD))) {
+                builder.append('?');
+                builder.append(str);
+            }
+            setDefaultUrl(contentExchange, options, builder);
+            processHeader(contentExchange, restParametes.getHeaderMap());
+            setContentExchangeParams(contentExchange);
+
+            setPostPutParam(method, restParametes, contentExchange, str);
+            setTimeout(options, contentExchange);
+
+            client.send(contentExchange);
+            rsp = callbackExecute(callback, contentExchange);
+        } catch(final Exception e) {
+            LOG.error("request reply message have exception:status is "
+                    + RestHttpContentExchange.toState(contentExchange.getStatus()));
+            throw new ServiceException(e);
+        }
+        return rsp;
+    }
+
+    private void setDefaultUrl(final RestHttpContentExchange contentExchange, final RestfulOptions options,
+            final StringBuilder url) {
+        // server
+        if(url.toString().startsWith("http")) {
+            contentExchange.setURL(url.toString());
+        } else {
+            String host = defaultIP;
+            int iPort = defaultPort;
+            String calledServiceName = null;
+            if(options != null) {
+                calledServiceName = options.getCalledServicName();
+            }
+            final ServiceUtil serviceUtil = new ServiceUtil(calledServiceName, url.toString());
+            final String configHost = serviceUtil.getServiceHost();
+            final int configPort = serviceUtil.getServicePort();
+            if(!configHost.isEmpty() && configPort > 0) {
+                if(options != null) {
+                    options.setHost(configHost);
+                    options.setPort(configPort);
+                } else {
+                    host = configHost;
+
+                    iPort = configPort;
+                }
+            }
+            if(options != null) {
+                host = options.getHost();
+                if(host.isEmpty()) {
+                    host = defaultIP;
+                }
+                iPort = options.getPort();
+                if(iPort == 0) {
+                    iPort = defaultPort;
+                }
+            }
+            // Integer.getInteger(".http.client.maxThread",30)
+            contentExchange.setAddress(new Address(host, iPort));
+            contentExchange.setRequestURI(url.toString());
+        }
+    }
+
+    private String getReuqestIdString() {
+        if(this.requestId.get() == 0x7FFFFFFF) {
+            this.requestId.set(1);
+        }
+        final int reqId = this.requestId.getAndIncrement();
+        final StringBuilder builder = new StringBuilder(this.procenameRouteID);
+        // time
+        final SimpleDateFormat dateFormate = new SimpleDateFormat("yyMMdd");
+        final SimpleDateFormat timeFormate = new SimpleDateFormat("HHmmss");
+        final Date date = Calendar.getInstance().getTime();
+        builder.append(dateFormate.format(date) + timeFormate.format(date));
+        builder.append('-');
+        builder.append(reqId);
+        return builder.toString();
+    }
+
+    private void setPostPutParam(final String method, final RestfulParametes restParametes,
+            final RestHttpContentExchange contentExchange, final String str) throws UnsupportedEncodingException {
+        if(HttpMethods.POST.equals(method) || HttpMethods.PUT.equals(method) || HTTP_PATCH.equals(method)) {
+            ByteArrayInputStream buff;
+            final String tmpRaw = restParametes.getRawData();
+            if(tmpRaw == null) {
+                buff = new ByteArrayInputStream(str.getBytes(RestfulClientConst.ENCODING));
+            } else {
+                buff = new ByteArrayInputStream(tmpRaw.getBytes(RestfulClientConst.ENCODING));
+            }
+            final int len = buff.available();
+            contentExchange.setRequestContentSource(buff);
+            contentExchange.setRequestHeader("content-length", String.valueOf(len));
+        }
+    }
+
+    private void setTimeout(final RestfulOptions options, final RestHttpContentExchange contentExchange) {
+        if(options != null) {
+            final long timeout = options.getRestTimeout();
+            if(timeout != 0) {
+                contentExchange.setTimeout(timeout);
+            } else {
+                contentExchange.setTimeout(defaultTimeout);
+            }
+        } else {
+            contentExchange.setTimeout(defaultTimeout);
+        }
+    }
+
+    private RestfulResponse callbackExecute(final RestfulAsyncCallback callback,
+            final RestHttpContentExchange contentExchange) throws InterruptedException, IOException, ServiceException {
+        if(callback == null) {
+            final int exchangeState = contentExchange.waitForDone();
+            if(exchangeState == HttpExchange.STATUS_COMPLETED) {
+                return contentExchange.getResponse();
+            } else if(exchangeState == HttpExchange.STATUS_EXCEPTED) {
+                throw new ServiceException(
+                        "request is exception: " + RestHttpContentExchange.toState(HttpExchange.STATUS_EXCEPTED));
+            } else if(exchangeState == HttpExchange.STATUS_EXPIRED) {
+                throw new ServiceException(
+                        "request is expierd: " + RestHttpContentExchange.toState(HttpExchange.STATUS_EXPIRED));
+            }
+        }
+        return null;
+    }
+
+}
diff --git a/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/HttpRest.java b/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/HttpRest.java
new file mode 100644 (file)
index 0000000..50a3538
--- /dev/null
@@ -0,0 +1,254 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openo.baseservice.roa.util.restclient;
+
+import org.eclipse.jetty.client.HttpClient;
+import org.eclipse.jetty.http.HttpMethods;
+import org.eclipse.jetty.util.thread.QueuedThreadPool;
+import org.openo.baseservice.remoteservice.exception.ServiceException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 Aug 9, 2016
+ */
+public class HttpRest extends HttpBaseRest {
+
+    private static final Logger LOG = LoggerFactory.getLogger(HttpRest.class);
+
+    /**
+     * Initializing Rest options.<br/>
+     * 
+     * @param options: rest options.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    public void initHttpRest(final RestfulOptions option) throws ServiceException {
+        if(option == null) {
+            client = null;
+            throw new ServiceException("option is null.");
+        }
+        createHttpClient();
+        try {
+            int iValue;
+            iValue = option.getIntOption(RestfulClientConst.MAX_CONN_PER_ADDR_KEY_NAME);
+            // max 200 concurrent,connections to every address
+            client.setMaxConnectionsPerAddress(iValue);
+
+            iValue = option.getIntOption(RestfulClientConst.THREAD_KEY_NAME);
+            // max threads
+            client.setThreadPool(new QueuedThreadPool(iValue));
+            iValue = option.getIntOption(RestfulClientConst.CONN_TIMEOUT_KEY_NAME);
+            client.setConnectTimeout(iValue);
+            iValue = option.getRestTimeout();
+            defaultTimeout = iValue;
+            client.setTimeout(iValue);
+
+            iValue = option.getIntOption(RestfulClientConst.IDLE_TIMEOUT_KEY_NAME);
+            client.setIdleTimeout(iValue);
+            iValue = option.getIntOption(RestfulClientConst.MAX_RESPONSE_HEADER_SIZE);
+            client.setResponseHeaderSize(iValue);
+            iValue = option.getIntOption(RestfulClientConst.MAX_REQUEST_HEADER_SIZE);
+            client.setRequestHeaderSize(iValue);
+            // HttpClient.CONNECTOR_SOCKET
+            client.setConnectorType(HttpClient.CONNECTOR_SELECT_CHANNEL);
+            client.start();
+            defaultIP = option.getStringOption(RestfulClientConst.HOST_KEY_NAME);
+            defaultPort = option.getIntOption(RestfulClientConst.PORT_KEY_NAME);
+        } catch(final Exception e) {
+            LOG.error("start httpclient error", e);
+            client = null;
+            throw new ServiceException("http client init failed.");
+        }
+    }
+
+    @Override
+    public RestfulResponse get(final String servicePath, final RestfulParametes restParametes) throws ServiceException {
+        return this.sendHttpRequest(HttpMethods.GET, servicePath, restParametes, null, null);
+    }
+
+    @Override
+    public RestfulResponse get(final String servicePath, final RestfulParametes restParametes,
+            final RestfulOptions option) throws ServiceException {
+        return this.sendHttpRequest(HttpMethods.GET, servicePath, restParametes, option, null);
+    }
+
+    @Override
+    public RestfulResponse head(final String servicePath, final RestfulParametes restParametes)
+            throws ServiceException {
+        return this.sendHttpRequest(HttpMethods.HEAD, servicePath, restParametes, null, null);
+    }
+
+    @Override
+    public RestfulResponse head(final String servicePath, final RestfulParametes restParametes,
+            final RestfulOptions option) throws ServiceException {
+        return this.sendHttpRequest(HttpMethods.HEAD, servicePath, restParametes, option, null);
+    }
+
+    @Override
+    public void asyncGet(final String servicePath, final RestfulParametes restParametes,
+            final RestfulAsyncCallback callback) throws ServiceException {
+        if(callback == null) {
+            this.sendHttpRequest(HttpMethods.GET, servicePath, restParametes, null, new DefaultAsyncCallback());
+        } else {
+            this.sendHttpRequest(HttpMethods.GET, servicePath, restParametes, null, callback);
+        }
+    }
+
+    @Override
+    public void asyncGet(final String servicePath, final RestfulParametes restParametes, final RestfulOptions option,
+            final RestfulAsyncCallback callback) throws ServiceException {
+        if(callback == null) {
+            this.sendHttpRequest(HttpMethods.GET, servicePath, restParametes, option, new DefaultAsyncCallback());
+        } else {
+            this.sendHttpRequest(HttpMethods.GET, servicePath, restParametes, option, callback);
+        }
+    }
+
+    @Override
+    public RestfulResponse put(final String servicePath, final RestfulParametes restParametes) throws ServiceException {
+        return this.sendHttpRequest(HttpMethods.PUT, servicePath, restParametes, null, null);
+    }
+
+    @Override
+    public RestfulResponse put(final String servicePath, final RestfulParametes restParametes,
+            final RestfulOptions option) throws ServiceException {
+        return this.sendHttpRequest(HttpMethods.PUT, servicePath, restParametes, option, null);
+    }
+
+    @Override
+    public void asyncPut(final String servicePath, final RestfulParametes restParametes,
+            final RestfulAsyncCallback callback) throws ServiceException {
+        if(callback == null) {
+            this.sendHttpRequest(HttpMethods.PUT, servicePath, restParametes, null, new DefaultAsyncCallback());
+        } else {
+            this.sendHttpRequest(HttpMethods.PUT, servicePath, restParametes, null, callback);
+        }
+    }
+
+    @Override
+    public void asyncPut(final String servicePath, final RestfulParametes restParametes, final RestfulOptions option,
+            final RestfulAsyncCallback callback) throws ServiceException {
+        if(callback == null) {
+            this.sendHttpRequest(HttpMethods.PUT, servicePath, restParametes, option, new DefaultAsyncCallback());
+        } else {
+            this.sendHttpRequest(HttpMethods.PUT, servicePath, restParametes, option, callback);
+        }
+    }
+
+    @Override
+    public RestfulResponse post(final String servicePath, final RestfulParametes restParametes)
+            throws ServiceException {
+        return this.sendHttpRequest(HttpMethods.POST, servicePath, restParametes, null, null);
+    }
+
+    @Override
+    public RestfulResponse post(final String servicePath, final RestfulParametes restParametes,
+            final RestfulOptions option) throws ServiceException {
+        return this.sendHttpRequest(HttpMethods.POST, servicePath, restParametes, option, null);
+    }
+
+    @Override
+    public void asyncPost(final String servicePath, final RestfulParametes restParametes,
+            final RestfulAsyncCallback callback) throws ServiceException {
+        if(callback == null) {
+            this.sendHttpRequest(HttpMethods.POST, servicePath, restParametes, null, new DefaultAsyncCallback());
+        } else {
+            this.sendHttpRequest(HttpMethods.POST, servicePath, restParametes, null, callback);
+        }
+    }
+
+    @Override
+    public void asyncPost(final String servicePath, final RestfulParametes restParametes, final RestfulOptions option,
+            final RestfulAsyncCallback callback) throws ServiceException {
+        if(callback == null) {
+            this.sendHttpRequest(HttpMethods.POST, servicePath, restParametes, option, new DefaultAsyncCallback());
+        } else {
+            this.sendHttpRequest(HttpMethods.POST, servicePath, restParametes, option, callback);
+        }
+    }
+
+    @Override
+    public RestfulResponse delete(final String servicePath, final RestfulParametes restParametes)
+            throws ServiceException {
+        return this.sendHttpRequest(HttpMethods.DELETE, servicePath, restParametes, null, null);
+    }
+
+    @Override
+    public RestfulResponse delete(final String servicePath, final RestfulParametes restParametes,
+            final RestfulOptions option) throws ServiceException {
+        return this.sendHttpRequest(HttpMethods.DELETE, servicePath, restParametes, option, null);
+    }
+
+    @Override
+    public void asyncDelete(final String servicePath, final RestfulParametes restParametes,
+            final RestfulAsyncCallback callback) throws ServiceException {
+        if(callback == null) {
+            this.sendHttpRequest(HttpMethods.DELETE, servicePath, restParametes, null, new DefaultAsyncCallback());
+        } else {
+            this.sendHttpRequest(HttpMethods.DELETE, servicePath, restParametes, null, callback);
+        }
+    }
+
+    @Override
+    public void asyncDelete(final String servicePath, final RestfulParametes restParametes, final RestfulOptions option,
+            final RestfulAsyncCallback callback) throws ServiceException {
+        if(callback == null) {
+            this.sendHttpRequest(HttpMethods.DELETE, servicePath, restParametes, option, new DefaultAsyncCallback());
+        } else {
+            this.sendHttpRequest(HttpMethods.DELETE, servicePath, restParametes, option, callback);
+        }
+    }
+
+    @Override
+    public RestfulResponse patch(final String servicePath, final RestfulParametes restParametes)
+            throws ServiceException {
+        return this.sendHttpRequest(HTTP_PATCH, servicePath, restParametes, null, null);
+    }
+
+    @Override
+    public RestfulResponse patch(final String servicePath, final RestfulParametes restParametes,
+            final RestfulOptions option) throws ServiceException {
+        return this.sendHttpRequest(HTTP_PATCH, servicePath, restParametes, option, null);
+    }
+
+    @Override
+    public void asyncPatch(final String servicePath, final RestfulParametes restParametes,
+            final RestfulAsyncCallback callback) throws ServiceException {
+        if(callback == null) {
+            this.sendHttpRequest(HTTP_PATCH, servicePath, restParametes, null, new DefaultAsyncCallback());
+        } else {
+            this.sendHttpRequest(HTTP_PATCH, servicePath, restParametes, null, callback);
+        }
+    }
+
+    @Override
+    public void asyncPatch(final String servicePath, final RestfulParametes restParametes, final RestfulOptions option,
+            final RestfulAsyncCallback callback) throws ServiceException {
+        if(callback == null) {
+            this.sendHttpRequest(HTTP_PATCH, servicePath, restParametes, option, new DefaultAsyncCallback());
+        } else {
+            this.sendHttpRequest(HTTP_PATCH, servicePath, restParametes, option, callback);
+        }
+    }
+
+}
diff --git a/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestHttpContentExchange.java b/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestHttpContentExchange.java
new file mode 100644 (file)
index 0000000..85118ce
--- /dev/null
@@ -0,0 +1,234 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.roa.util.restclient;
+
+import org.openo.baseservice.remoteservice.exception.ServiceException;
+
+import org.apache.commons.lang.StringUtils;
+import org.eclipse.jetty.client.ContentExchange;
+import org.eclipse.jetty.client.HttpDestination;
+import org.eclipse.jetty.http.HttpFields;
+import org.eclipse.jetty.http.HttpHeaders;
+import org.eclipse.jetty.io.Buffer;
+import org.eclipse.jetty.util.StringUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.nio.charset.Charset;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.zip.GZIPInputStream;
+
+/**
+ * ContentExchange implementation classe to provide access to response.
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 28-May-2016
+ */
+public class RestHttpContentExchange extends ContentExchange {
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(RestHttpContentExchange.class);
+
+    private boolean gzip = false;
+
+    private RestfulAsyncCallback callback = null;
+
+    /**
+     * Constructor<br/>
+     * <p>
+     * </p>
+     * 
+     * @since SDNO 0.5
+     * @param cacheFields whether to cache response header.
+     * @param asyncCallback callback method.
+     */
+    RestHttpContentExchange(final boolean cacheFields, final RestfulAsyncCallback asyncCallback) {
+        super(cacheFields);
+        this.callback = asyncCallback;
+    }
+
+    /**
+     * Extract message.
+     * <br/>
+     * 
+     * @param data GZipped data.
+     * @return Uncompressed data.
+     * @throws IOException
+     * @since SDNO 0.5
+     */
+    public String decompressGzipToStr(final byte[] data) throws IOException {
+        if(data == null) {
+            return "";
+        }
+        ByteArrayInputStream input = null;
+        GZIPInputStream gzis = null;
+        InputStreamReader reader = null;
+        final StringBuilder out = new StringBuilder();
+        try {
+            input = new ByteArrayInputStream(data);
+            gzis = new GZIPInputStream(input);
+            reader = new InputStreamReader(gzis, Charset.forName(RestfulClientConst.ENCODING));
+            final char[] buff = new char[1024];
+            for(int n; (n = reader.read(buff)) != -1;) {
+                out.append(new String(buff, 0, n));
+            }
+        } finally {
+            if(reader != null) {
+                try {
+                    reader.close();
+                } catch(final IOException e) {
+                    LOGGER.error("decompress Gzip reader exception:", e);
+                }
+            }
+            if(gzis != null) {
+                try {
+                    gzis.close();
+                } catch(final IOException e) {
+                    LOGGER.error("decompress Gzip exception:", e);
+                }
+            }
+            if(input != null) {
+                try {
+                    input.close();
+                } catch(final IOException e) {
+                    LOGGER.error("decompress Gzip input exception:", e);
+                }
+            }
+        }
+        return out.toString();
+
+    }
+
+    /**
+     * View response headers Content-Encoding values if you need to extract data.<br/>
+     * 
+     * @param name buffer
+     * @param value value
+     * @throws IOException
+     * @since SDNO 0.5
+     */
+    @Override
+    protected synchronized void onResponseHeader(final Buffer name, final Buffer value) throws IOException {
+        super.onResponseHeader(name, value);
+        final int header = HttpHeaders.CACHE.getOrdinal(name);
+        if(header == HttpHeaders.CONTENT_ENCODING_ORDINAL) {
+            final String encoding = StringUtil.asciiToLowerCase(value.toString());
+            gzip = encoding != null && StringUtils.contains(encoding, "gzip");
+        }
+
+    }
+
+    @Override
+    protected void onResponseComplete() throws IOException {
+        if(LOGGER.isInfoEnabled()) {
+            LOGGER.info("Response has Complete:" + "path:" + this.getRequestURI().replace("\n", "0x0A"));
+        }
+        super.onResponseComplete();
+        if(callback != null) {
+            final RestfulResponse rsp = getResponse();
+            callback.callback(rsp);
+        }
+    }
+
+    @Override
+    protected void onRequestCommitted() throws IOException {
+        if(LOGGER.isInfoEnabled()) {
+            LOGGER.info("Request Header has been send:" + "path:" + this.getRequestURI().replace("\n", "0x0A"));
+        }
+        super.onRequestCommitted();
+    }
+
+    @Override
+    protected void onRequestComplete() throws IOException {
+        if(LOGGER.isInfoEnabled()) {
+            LOGGER.info("Request has bend send complete:" + "path:" + this.getRequestURI().replace("\n", "0x0A"));
+        }
+        super.onRequestComplete();
+    }
+
+    @Override
+    protected void onException(final Throwable x) {
+        LOGGER.warn("onException:", x);
+        super.onException(x);
+        if(callback != null) {
+            callback.handleExcepion(x);
+        }
+    }
+
+    @Override
+    protected void onConnectionFailed(final Throwable x) {
+        LOGGER.warn("onConnectionFailed:", x);
+        super.onConnectionFailed(x);
+        if(callback != null) {
+            callback.handleExcepion(x);
+        }
+
+    }
+
+    @Override
+    protected void expire(final HttpDestination destination) {
+        super.expire(destination);
+        if(callback != null) {
+            callback.handleExcepion(new ServiceException("request is expired, status:" + toState(getStatus())));
+        }
+    }
+
+    public boolean isGzip() {
+        return gzip;
+    }
+
+    /**
+     * Get the response as RestfulResponse.
+     * <br/>
+     * 
+     * @return response object.
+     * @throws IOException
+     * @since SDNO 0.5
+     */
+    public RestfulResponse getResponse() throws IOException {
+        final RestfulResponse rsp = new RestfulResponse();
+        rsp.setStatus(this.getResponseStatus());
+        if(isGzip()) {
+            final String responseString = decompressGzipToStr(getResponseContentBytes());
+            rsp.setResponseJson(responseString);
+        } else {
+            rsp.setResponseJson(this.getResponseContent());
+        }
+
+        final HttpFields field = this.getResponseFields();
+        if(field != null) {
+            final Map<String, String> header = new HashMap<>();
+
+            final Enumeration<String> names = field.getFieldNames();
+            for(final Enumeration<String> e = names; e.hasMoreElements();) {
+                final String fieldName = e.nextElement();
+                final String fieldValue = field.getStringField(fieldName);
+                header.put(fieldName, fieldValue);
+            }
+
+            rsp.setRespHeaderMap(header);
+        }
+        return rsp;
+    }
+
+}
diff --git a/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/Restful.java b/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/Restful.java
new file mode 100644 (file)
index 0000000..7a7c11e
--- /dev/null
@@ -0,0 +1,298 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.roa.util.restclient;
+
+import org.openo.baseservice.remoteservice.exception.ServiceException;
+
+/**
+ * ReSTful method interface.<br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 28-May-2016
+ */
+public interface Restful {
+
+    /**
+     * Http GET method.<br/>
+     * 
+     * @param servicePath: request path.
+     * @param restParametes: query parameters.
+     * @return response.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    RestfulResponse get(String servicePath, RestfulParametes restParametes) throws ServiceException;
+
+    /**
+     * Http HEAD method.<br/>
+     * 
+     * @param servicePath: request path.
+     * @param restParametes: request parameters.
+     * @param options: request options.
+     * @return response.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    RestfulResponse head(String servicePath, RestfulParametes restParametes, RestfulOptions options)
+            throws ServiceException;
+
+    /**
+     * Http HEAD method.<br/>
+     * 
+     * @param servicePath: request path.
+     * @param restParametes: request parameters.
+     * @return response.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    RestfulResponse head(String servicePath, RestfulParametes restParametes) throws ServiceException;
+
+    /**
+     * Http GET method.<br/>
+     * 
+     * @param servicePath: request path.
+     * @param restParametes: request parameters.
+     * @param options: request options.
+     * @return response.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    RestfulResponse get(String servicePath, RestfulParametes restParametes, RestfulOptions options)
+            throws ServiceException;
+
+    /**
+     * Asynchronouse GET request.<br/>
+     * 
+     * @param servicePath: request path.
+     * @param restParametes: request parameters.
+     * @param callback: response callback method.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    void asyncGet(String servicePath, RestfulParametes restParametes, RestfulAsyncCallback callback)
+            throws ServiceException;
+
+    /**
+     * Asynchronouse GET request.<br/>
+     * 
+     * @param servicePath: request path.
+     * @param restParametes: request parameters.
+     * @param options: request options.
+     * @param callback: response callback method.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    void asyncGet(String servicePath, RestfulParametes restParametes, RestfulOptions options,
+            RestfulAsyncCallback callback) throws ServiceException;
+
+    /**
+     * Http PUT method.<br/>
+     * 
+     * @param servicePath: request path.
+     * @param restParametes: request parameters.
+     * @return response.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    RestfulResponse put(String servicePath, RestfulParametes restParametes) throws ServiceException;
+
+    /**
+     * Http PUT method.<br/>
+     * 
+     * @param servicePath: request path.
+     * @param restParametes: request parameters.
+     * @param options: request options.
+     * @return response.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    RestfulResponse put(String servicePath, RestfulParametes restParametes, RestfulOptions options)
+            throws ServiceException;
+
+    /**
+     * Asynchronouse PUT request.<br/>
+     * 
+     * @param servicePath: request path.
+     * @param restParametes: request parameters.
+     * @param callback: response callback method.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    void asyncPut(String servicePath, RestfulParametes restParametes, RestfulAsyncCallback callback)
+            throws ServiceException;
+
+    /**
+     * Asynchronouse PUT request.<br/>
+     * 
+     * @param servicePath: request path.
+     * @param restParametes: request parameters.
+     * @param options: request options.
+     * @param callback: response callback method.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    void asyncPut(String servicePath, RestfulParametes restParametes, RestfulOptions options,
+            RestfulAsyncCallback callback) throws ServiceException;
+
+    /**
+     * Http POST method.<br/>
+     * 
+     * @param servicePath: request path.
+     * @param restParametes: request parameters.
+     * @return response.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    RestfulResponse post(String servicePath, RestfulParametes restParametes) throws ServiceException;
+
+    /**
+     * Http POST method.<br/>
+     * 
+     * @param servicePath: request path.
+     * @param restParametes: request parameters.
+     * @param options: request options.
+     * @return response.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    RestfulResponse post(String servicePath, RestfulParametes restParametes, RestfulOptions options)
+            throws ServiceException;
+
+    /**
+     * Asynchronouse POST request.<br/>
+     * 
+     * @param servicePath: request path.
+     * @param restParametes: request parameters.
+     * @param callback: response callback method.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    void asyncPost(String servicePath, RestfulParametes restParametes, RestfulAsyncCallback callback)
+            throws ServiceException;
+
+    /**
+     * Asynchronouse POST request.<br/>
+     * 
+     * @param servicePath: request path.
+     * @param restParametes: request parameters.
+     * @param options: request options.
+     * @param callback: response callback method.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    void asyncPost(String servicePath, RestfulParametes restParametes, RestfulOptions options,
+            RestfulAsyncCallback callback) throws ServiceException;
+
+    /**
+     * Http DELETE method.<br/>
+     * 
+     * @param servicePath: request path.
+     * @param restParametes: request parameters.
+     * @return response.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    RestfulResponse delete(String servicePath, RestfulParametes restParametes) throws ServiceException;
+
+    /**
+     * Http DELETE method.<br/>
+     * 
+     * @param servicePath: request path.
+     * @param restParametes: request parameters.
+     * @param options: request options.
+     * @return response.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    RestfulResponse delete(String servicePath, RestfulParametes restParametes, RestfulOptions options)
+            throws ServiceException;
+
+    /**
+     * Asynchronouse DELETE request.<br/>
+     * 
+     * @param servicePath: request path.
+     * @param restParametes: request parameters.
+     * @param callback: response callback method.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    void asyncDelete(String servicePath, RestfulParametes restParametes, RestfulAsyncCallback callback)
+            throws ServiceException;
+
+    /**
+     * Asynchronouse DELETE request.<br/>
+     * 
+     * @param servicePath: request path.
+     * @param restParametes: request parameters.
+     * @param options: request options.
+     * @param callback: response callback method.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    void asyncDelete(String servicePath, RestfulParametes restParametes, RestfulOptions options,
+            RestfulAsyncCallback callback) throws ServiceException;
+
+    /**
+     * Http PATCH method.<br/>
+     * 
+     * @param servicePath: request path.
+     * @param restParametes: request parameters.
+     * @return response.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    RestfulResponse patch(String servicePath, RestfulParametes restParametes) throws ServiceException;
+
+    /**
+     * Http PATCH method.<br/>
+     * 
+     * @param servicePath: request path.
+     * @param restParametes: request parameters.
+     * @param options: request options.
+     * @return response.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    RestfulResponse patch(String servicePath, RestfulParametes restParametes, RestfulOptions options)
+            throws ServiceException;
+
+    /**
+     * Asynchronouse PATCH request.<br/>
+     * 
+     * @param servicePath: request path.
+     * @param restParametes: request parameters.
+     * @param callback: response callback method.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    void asyncPatch(String servicePath, RestfulParametes restParametes, RestfulAsyncCallback callback)
+            throws ServiceException;
+
+    /**
+     * Asynchronouse PATCH request.<br/>
+     * 
+     * @param servicePath: request path.
+     * @param restParametes: request parameters.
+     * @param options: request options.
+     * @param callback: response callback method.
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    void asyncPatch(String servicePath, RestfulParametes restParametes, RestfulOptions options,
+            RestfulAsyncCallback callback) throws ServiceException;
+}
diff --git a/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulAsyncCallback.java b/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulAsyncCallback.java
new file mode 100644 (file)
index 0000000..bf11c16
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.roa.util.restclient;
+
+/**
+ * Callback interface for ReST calls.<br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 28-May-2016
+ */
+public interface RestfulAsyncCallback {
+
+    /**
+     * Response callback.<br/>
+     * 
+     * @param response: response of ReST call.
+     * @since SDNO 0.5
+     */
+    void callback(RestfulResponse response);
+
+    /**
+     * Exceptoin callback.<br/>
+     * 
+     * @param e: ReST call exception.
+     * @since SDNO 0.5
+     */
+    void handleExcepion(Throwable e);
+}
diff --git a/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulClientConst.java b/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulClientConst.java
new file mode 100644 (file)
index 0000000..ef02b7d
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.roa.util.restclient;
+
+/**
+ * Constants for ReST client.<br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 28-May-2016
+ */
+public class RestfulClientConst {
+
+    /** -- json Ecode -- **/
+    public static final String APPLICATION_FORM_JSON_EBCIDED = "application/json";
+
+    /**
+     * urlencode
+     */
+    public static final String APPLICATION_FORM_URLENCODED = "application/x-www-form-urlencoded; charset=UTF-8";
+
+    public static final String ENCODING = "UTF-8";
+
+    public static final String SERVER_KEY_NAME = "defaulServer";
+
+    public static final String CALLED_SERVICE_NAME = "serviceName";
+
+    public static final String HOST_KEY_NAME = "host";
+
+    public static final String PORT_KEY_NAME = "port";
+
+    public static final String CONN_TIMEOUT_KEY_NAME = "ConnectTimeout";
+
+    public static final String THREAD_KEY_NAME = "thread";
+
+    public static final String IDLE_TIMEOUT_KEY_NAME = "idletimeout";
+
+    public static final String TIMEOUT_KEY_NAME = "timeout";
+
+    public static final String MAX_CONN_PER_ADDR_KEY_NAME = "maxConnectionPerAddr";
+
+    public static final String REQUEST_ID = "x-request-id";
+
+    public static final String MAX_RESPONSE_HEADER_SIZE = "responseHeaderSize";
+
+    public static final String MAX_REQUEST_HEADER_SIZE = "requestHeaderSize";
+
+    private RestfulClientConst() {
+
+    }
+}
diff --git a/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulConfigure.java b/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulConfigure.java
new file mode 100644 (file)
index 0000000..3d0a0ff
--- /dev/null
@@ -0,0 +1,162 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.roa.util.restclient;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+
+import org.openo.baseservice.roa.util.ReaderHelper;
+import org.openo.baseservice.util.impl.SystemEnvVariablesFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import net.sf.json.JSONObject;
+
+/**
+ * Rest client options.<br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 28-May-2016
+ */
+public class RestfulConfigure {
+
+    private static final Logger LOG = LoggerFactory.getLogger(RestfulConfigure.class);
+
+    private RestfulOptions options = null;
+
+    /**
+     * Constructor<br/>
+     * <p>
+     * Use the default path initialization http Rest options.
+     * </p>
+     * 
+     * @since SDNO 0.5
+     */
+    public RestfulConfigure() {
+        final String config = "/etc/conf/restclient.json";
+        final String approot = SystemEnvVariablesFactory.getInstance().getAppRoot();
+        final StringBuilder extendSetting = new StringBuilder();
+
+        if(approot != null) {
+            extendSetting.append(approot);
+            extendSetting.append(config);
+        } else {
+            extendSetting.append(System.getProperty("user.dir"));
+            extendSetting.append(config);
+        }
+
+        final String configfile = extendSetting.toString();
+        initRestConf(configfile);
+    }
+
+    /**
+     * Constructor<br/>
+     * <p>
+     * Use the specified file to initialize http Rest options.
+     * </p>
+     * 
+     * @since SDNO 0.5
+     * @param configfile
+     */
+    public RestfulConfigure(final String configfile) {
+        initRestConf(configfile);
+    }
+
+    public RestfulOptions getOptions() {
+        return options;
+    }
+
+    private void initRestConf(final String configfile) {
+        options = getDefaultOptions();
+
+        final JSONObject obj = loadJsonFromFile(configfile);
+        if(obj != null) {
+            if(obj.has(RestfulClientConst.SERVER_KEY_NAME)) {
+                final JSONObject server = obj.getJSONObject(RestfulClientConst.SERVER_KEY_NAME);
+                setStringOption(server, RestfulClientConst.HOST_KEY_NAME);
+                setIntOption(server, RestfulClientConst.PORT_KEY_NAME);
+            }
+            setIntOption(obj, RestfulClientConst.CONN_TIMEOUT_KEY_NAME);
+            setIntOption(obj, RestfulClientConst.THREAD_KEY_NAME);
+            setIntOption(obj, RestfulClientConst.IDLE_TIMEOUT_KEY_NAME);
+            setIntOption(obj, RestfulClientConst.TIMEOUT_KEY_NAME);
+            setIntOption(obj, RestfulClientConst.MAX_CONN_PER_ADDR_KEY_NAME);
+            setIntOption(obj, RestfulClientConst.MAX_RESPONSE_HEADER_SIZE);
+            setIntOption(obj, RestfulClientConst.MAX_REQUEST_HEADER_SIZE);
+        } else {
+            LOG.error("failed to load json from " + configfile);
+        }
+    }
+
+    private void setStringOption(final JSONObject json, final String key) {
+        if(json.has(key)) {
+            options.setOption(key, json.getString(key));
+        }
+    }
+
+    private void setIntOption(final JSONObject json, final String key) {
+        if(json.has(key)) {
+            options.setOption(key, json.getInt(key));
+        }
+    }
+
+    private RestfulOptions getDefaultOptions() {
+        options = new RestfulOptions();
+        options.setOption(RestfulClientConst.CONN_TIMEOUT_KEY_NAME, 3000);
+        options.setOption(RestfulClientConst.THREAD_KEY_NAME, 200);
+        options.setOption(RestfulClientConst.IDLE_TIMEOUT_KEY_NAME, 30000);
+        options.setOption(RestfulClientConst.TIMEOUT_KEY_NAME, 30000);
+        options.setOption(RestfulClientConst.MAX_CONN_PER_ADDR_KEY_NAME, 50);
+        options.setOption(RestfulClientConst.MAX_RESPONSE_HEADER_SIZE, 20 * 1024);
+        options.setOption(RestfulClientConst.MAX_REQUEST_HEADER_SIZE, 20 * 1024);
+        return options;
+    }
+
+    private JSONObject loadJsonFromFile(final String filePath) {
+        final File file = new File(filePath);
+        if((!file.exists()) || (!file.isFile())) {
+            LOG.error(filePath + "isn't exist.");
+            return null;
+        }
+        BufferedReader reader = null;
+        final StringBuilder jsonstr = new StringBuilder();
+        JSONObject jo = null;
+        try {
+            reader = new BufferedReader(new FileReader(file));
+            final ReaderHelper rHelpper = new ReaderHelper(reader);
+            String tempString = null;
+            while((tempString = rHelpper.getLine()) != null) {
+                jsonstr.append(tempString);
+            }
+            jo = JSONObject.fromObject(jsonstr.toString());
+        } catch(final IOException e) {
+            LOG.error("load file exception:" + e);
+        } finally {
+            if(reader != null) {
+                try {
+                    reader.close();
+                } catch(final IOException e) {
+                    LOG.error("close error.", e);
+                }
+            }
+        }
+        return jo;
+    }
+}
diff --git a/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulFactory.java b/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulFactory.java
new file mode 100644 (file)
index 0000000..e53bab1
--- /dev/null
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.roa.util.restclient;
+
+import org.openo.baseservice.remoteservice.exception.ServiceException;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * RestFul instance factory. <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 28-May-2016
+ */
+public class RestfulFactory {
+
+    /**
+     * https protocol.
+     */
+    public static final String PROTO_HTTPS = "https";
+
+    /**
+     * http protocol.
+     */
+    public static final String PROTO_HTTP = "http";
+
+    private static final Logger LOG = LoggerFactory.getLogger(RestfulFactory.class);
+
+    private static final Map<String, Restful> INSTANCES = new HashMap<>(2);
+
+    private RestfulFactory() {
+
+    }
+
+    /**
+     * Get RESTful instance. This method returns a singleton instance.
+     * <br/>
+     * 
+     * @param protocol protocol. currently only support 'http'.
+     * @return restful instance.
+     * @since SDNO 0.5
+     */
+    public static synchronized Restful getRestInstance(final String protocol) {
+        Restful rest = INSTANCES.get(protocol);
+        if(rest != null) {
+            return rest;
+        }
+        if(PROTO_HTTP.equals(protocol)) {
+            rest = createHttpRest();
+            INSTANCES.put(protocol, rest);
+        }
+        return rest;
+    }
+
+    private static Restful createHttpRest() {
+        final HttpRest rest = new HttpRest();
+        setRestOption(rest, null);
+        return rest;
+    }
+
+    private static void setRestOption(final HttpRest rest, final String restoptionfile) {
+        try {
+            RestfulConfigure config;
+            if(restoptionfile == null || restoptionfile.isEmpty()) {
+                config = new RestfulConfigure();
+            } else {
+                config = new RestfulConfigure(restoptionfile);
+            }
+
+            final RestfulOptions option = config.getOptions();
+            rest.initHttpRest(option);
+        } catch(final ServiceException e) {
+            LOG.error("init http client exception: ", e);
+        }
+    }
+}
diff --git a/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulOptions.java b/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulOptions.java
new file mode 100644 (file)
index 0000000..912abf5
--- /dev/null
@@ -0,0 +1,196 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.roa.util.restclient;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Options for Rest communication.<br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 28-May-2016
+ */
+public class RestfulOptions {
+
+    public static final String REST_OPTIONS_NAME_TIMEOUT = "timeout";
+
+    public static final int REST_OPTIONS_TIMEOUT_MAXTIMEOUT = 1800000;
+
+    private final Map<String, Object> optionsMap = new HashMap<>();
+
+    /**
+     * Set called service name.<br/>
+     * 
+     * @param serviceName service name.
+     * @return true.
+     * @since SDNO 0.5
+     */
+    public boolean setCalledServiceName(final String serviceName) {
+        this.setOption(RestfulClientConst.CALLED_SERVICE_NAME, serviceName);
+        return true;
+    }
+
+    /**
+     * Get called service name.<br/>
+     * 
+     * @return
+     * @since SDNO 0.5
+     */
+    public String getCalledServicName() {
+        final Object obj = this.getOption(RestfulClientConst.CALLED_SERVICE_NAME);
+        if(null == obj) {
+            return "";
+        }
+        return (String)obj;
+    }
+
+    /**
+     * Get port.<br/>
+     * 
+     * @return port.
+     * @since SDNO 0.5
+     */
+    public int getPort() {
+        final Object obj = this.getOption(RestfulClientConst.PORT_KEY_NAME);
+        if(null == obj) {
+            return 0;
+        }
+        return ((Integer)obj).intValue();
+    }
+
+    /**
+     * Set port.<br/>
+     * 
+     * @param port port to set.
+     * @return
+     * @since SDNO 0.5
+     */
+    public boolean setPort(final int port) {
+        this.setOption(RestfulClientConst.PORT_KEY_NAME, port);
+        return true;
+    }
+
+    /**
+     * Get host.<br/>
+     * 
+     * @return the host.
+     * @since SDNO 0.5
+     */
+    public String getHost() {
+        final Object obj = this.getOption(RestfulClientConst.HOST_KEY_NAME);
+        if(null == obj) {
+            return "";
+        }
+        return (String)obj;
+    }
+
+    /**
+     * Set host.<br/>
+     * 
+     * @param host host to set.
+     * @return
+     * @since SDNO 0.5
+     */
+    public boolean setHost(final String host) {
+        this.setOption(RestfulClientConst.HOST_KEY_NAME, host);
+        return true;
+    }
+
+    /**
+     * Set rest time-out.<br/>
+     * 
+     * @param timeout time-out to set in seconds.
+     * @return
+     * @since SDNO 0.5
+     */
+    public boolean setRestTimeout(final int timeout) {
+        if(0 < timeout && REST_OPTIONS_TIMEOUT_MAXTIMEOUT >= timeout) {
+            this.setOption(REST_OPTIONS_NAME_TIMEOUT, timeout);
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Get time-out.<br/>
+     * 
+     * @return time-out in seconds.
+     * @since SDNO 0.5
+     */
+    public int getRestTimeout() {
+        final Object obj = this.getOption(REST_OPTIONS_NAME_TIMEOUT);
+        if(null == obj) {
+            return 0;
+        }
+        return ((Integer)obj).intValue();
+    }
+
+    /**
+     * Get specified option.<br/>
+     * 
+     * @param optionName option name.
+     * @return option
+     * @since SDNO 0.5
+     */
+    public Object getOption(final String optionName) {
+        return optionsMap.get(optionName);
+    }
+
+    /**
+     * Get option value as integer.<br/>
+     * 
+     * @param optionName option name.
+     * @return option value as int.
+     * @since SDNO 0.5
+     */
+    public int getIntOption(final String optionName) {
+        final Object obj = this.getOption(optionName);
+        if(null == obj) {
+            return 0;
+        }
+        return ((Integer)obj).intValue();
+    }
+
+    /**
+     * Get option value as string.<br/>
+     * 
+     * @param optionName option name.
+     * @return option value as string.
+     * @since SDNO 0.5
+     */
+    public String getStringOption(final String optionName) {
+        final Object obj = this.getOption(optionName);
+        if(null == obj) {
+            return "";
+        }
+        return (String)obj;
+    }
+
+    /**
+     * Set option.<br/>
+     * 
+     * @param option option name.
+     * @param optionsValue option value.
+     * @return
+     * @since SDNO 0.5
+     */
+    public Object setOption(final String option, final Object optionsValue) {
+        return optionsMap.put(option, optionsValue);
+    }
+}
diff --git a/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulParametes.java b/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulParametes.java
new file mode 100644 (file)
index 0000000..c6c5933
--- /dev/null
@@ -0,0 +1,155 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openo.baseservice.roa.util.restclient;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 Aug 9, 2016
+ */
+public class RestfulParametes {
+
+    private Map<String, String> paramMap = new HashMap<>();
+
+    private Map<String, String> headerMap = new HashMap<>();
+
+    private String rawData = null;
+
+    /**
+     * <br/>
+     * 
+     * @param key
+     * @return
+     * @since SDNO 0.5
+     */
+    public String get(final String key) {
+        return paramMap.get(key);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @param data
+     * @since SDNO 0.5
+     */
+    public void setRawData(final String data) {
+        this.rawData = data;
+    }
+
+    /**
+     * <br/>
+     * 
+     * @return
+     * @since SDNO 0.5
+     */
+    public String getRawData() {
+        return this.rawData;
+    }
+
+    /**
+     * <br/>
+     * 
+     * @param key
+     * @param value
+     * @return
+     * @since SDNO 0.5
+     */
+    public String put(final String key, final String value) {
+        return paramMap.put(key, value);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @param key
+     * @param value
+     * @return
+     * @since SDNO 0.5
+     */
+    public String putHttpContextHeader(final String key, final String value) {
+        return headerMap.put(key, value);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @param key
+     * @param value
+     * @return
+     * @since SDNO 0.5
+     */
+    public String putHttpContextHeader(final String key, final int value) {
+        return this.putHttpContextHeader(key, String.valueOf(value));
+    }
+
+    /**
+     * <br/>
+     * 
+     * @param key
+     * @return
+     * @since SDNO 0.5
+     */
+    public String getHttpContextHeader(final String key) {
+        return headerMap.get(key);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @return
+     * @since SDNO 0.5
+     */
+    public Map<String, String> getParamMap() {
+        return paramMap;
+    }
+
+    /**
+     * <br/>
+     * 
+     * @param paramMap
+     * @since SDNO 0.5
+     */
+    public void setParamMap(final Map<String, String> paramMap) {
+        this.paramMap = paramMap;
+    }
+
+    /**
+     * <br/>
+     * 
+     * @return
+     * @since SDNO 0.5
+     */
+    public Map<String, String> getHeaderMap() {
+        return this.headerMap;
+    }
+
+    /**
+     * <br/>
+     * 
+     * @param headerMap
+     * @since SDNO 0.5
+     */
+    public void setHeaderMap(final Map<String, String> headerMap) {
+        this.headerMap = headerMap;
+    }
+}
diff --git a/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulResponse.java b/CommonLibrary/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulResponse.java
new file mode 100644 (file)
index 0000000..28a0c6d
--- /dev/null
@@ -0,0 +1,144 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openo.baseservice.roa.util.restclient;
+
+import java.util.Map;
+
+/**
+ * Response for RestFul requests.<br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 28-May-2016
+ */
+public class RestfulResponse {
+
+    private String responseContent;
+
+    private int status = -1;
+
+    private Map<String, String> respHeaderMap = null;
+
+    /**
+     * <br/>
+     * 
+     * @return
+     * @since SDNO 0.5
+     */
+    public int getStatus() {
+        return status;
+    }
+
+    /**
+     * <br/>
+     * 
+     * @param status
+     * @since SDNO 0.5
+     */
+    public void setStatus(final int status) {
+        this.status = status;
+    }
+
+    /**
+     * <br/>
+     * 
+     * @return
+     * @since SDNO 0.5
+     */
+    public Map<String, String> getRespHeaderMap() {
+        return respHeaderMap;
+    }
+
+    /**
+     * <br/>
+     * 
+     * @param header
+     * @since SDNO 0.5
+     */
+    public void setRespHeaderMap(final Map<String, String> header) {
+        this.respHeaderMap = header;
+    }
+
+    /**
+     * Get response header value as integer.<br/>
+     * 
+     * @param key header param name.
+     * @return header param value as integer. (-1 if error)
+     * @since SDNO 0.5
+     */
+    public int getRespHeaderInt(final String key) {
+        if(respHeaderMap != null) {
+            final String result = respHeaderMap.get(key);
+            if(result != null) {
+                return Integer.parseInt(result);
+            }
+        }
+        return -1;
+    }
+
+    /**
+     * Get response header value as long.<br/>
+     * 
+     * @param key header param name.
+     * @return value as long. -1 if no value.
+     * @since SDNO 0.5
+     */
+    public long getRespHeaderLong(final String key) {
+        if(respHeaderMap != null) {
+            final String result = respHeaderMap.get(key);
+            if(result != null) {
+                return Long.parseLong(result);
+            }
+        }
+        return -1;
+    }
+
+    /**
+     * Get http header as string.<br/>
+     * 
+     * @param key header name.
+     * @return header value.
+     * @since SDNO 0.5
+     */
+    public String getRespHeaderStr(final String key) {
+        if(respHeaderMap != null) {
+            return respHeaderMap.get(key);
+        }
+        return null;
+    }
+
+    /**
+     * <br/>
+     * 
+     * @return
+     * @since SDNO 0.5
+     */
+    public String getResponseContent() {
+        return responseContent;
+    }
+
+    /**
+     * <br/>
+     * 
+     * @param responseString
+     * @since SDNO 0.5
+     */
+    public void setResponseJson(final String responseString) {
+        this.responseContent = responseString;
+    }
+}
diff --git a/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/ReaderHelperTest.java b/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/ReaderHelperTest.java
new file mode 100644 (file)
index 0000000..78f08da
--- /dev/null
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.openo.baseservice.roa.util;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.io.Reader;
+import java.io.StringReader;
+
+import junit.framework.Assert;
+
+/**
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 12-Jun-2016
+ */
+public class ReaderHelperTest {
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @BeforeClass
+    public static void setUpBeforeClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @AfterClass
+    public static void tearDownAfterClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @Before
+    public void setUp() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @After
+    public void tearDown() throws Exception {
+    }
+
+    /**
+     * Test method for {@link org.openo.baseservice.util.inf.ReaderHelper#getLine()}.
+     */
+    @Test
+    public void testGetLine() {
+        final String message = "hello.. how are you?";
+        final Reader reader = new StringReader(message);
+        final ReaderHelper helper = new ReaderHelper(reader);
+        final String actual = helper.getLine();
+        Assert.assertEquals(message, actual);
+    }
+
+    /**
+     * Test method for {@link org.openo.baseservice.util.inf.ReaderHelper#getLine()}.
+     */
+    @Test
+    public void testGetLineMultiLine() {
+        final String line1 = "hello.. how are you?";
+        final String line2 = "I am fine.";
+        final Reader reader = new StringReader(line1 + System.lineSeparator() + line2);
+        final ReaderHelper helper = new ReaderHelper(reader);
+        String actual = helper.getLine();
+        Assert.assertEquals(line1, actual);
+        actual = helper.getLine();
+        Assert.assertEquals(line2, actual);
+        actual = helper.getLine();
+        Assert.assertEquals(null, actual);
+    }
+
+    @Test
+    public void testGetLineNull() {
+        final ReaderHelper helper = new ReaderHelper(null);
+        final String actual = helper.getLine();
+        Assert.assertEquals(null, actual);
+
+    }
+
+}
diff --git a/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/TestServiceUtil.java b/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/TestServiceUtil.java
new file mode 100644 (file)
index 0000000..f4f93e4
--- /dev/null
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openo.baseservice.roa.util;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+/**
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 13-Jun-2016
+ */
+public class TestServiceUtil {
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @BeforeClass
+    public static void setUpBeforeClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @AfterClass
+    public static void tearDownAfterClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @Before
+    public void setUp() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @After
+    public void tearDown() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetServiceHost() {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetServicePort() {
+    }
+}
diff --git a/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/clientsdk/TestHttpUtil.java b/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/clientsdk/TestHttpUtil.java
new file mode 100644 (file)
index 0000000..419d4d0
--- /dev/null
@@ -0,0 +1,266 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openo.baseservice.roa.util.clientsdk;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.Arrays;
+import java.util.Date;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import mockit.Mocked;
+import mockit.NonStrictExpectations;
+
+/**
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 13-Jun-2016
+ */
+public class TestHttpUtil {
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @BeforeClass
+    public static void setUpBeforeClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @AfterClass
+    public static void tearDownAfterClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @Before
+    public void setUp() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @After
+    public void tearDown() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testContainsIgnoreCase() {
+        final String[] array = {"hello", "how", "are", "you", "?"};
+        final String toFind = "Hello";
+        Assert.assertTrue(HttpUtil.containsIgnoreCase(array, toFind));
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testContainsIgnoreCaseNull() {
+        final String[] array = {"hello", "how", "are", "you", "?"};
+        final String toFind = "Hello";
+        Assert.assertFalse(HttpUtil.containsIgnoreCase(array, null));
+
+        array[0] = null;
+        Assert.assertFalse(HttpUtil.containsIgnoreCase(array, toFind));
+
+        Assert.assertTrue(HttpUtil.containsIgnoreCase(array, null));
+        array[0] = "hello";
+        array[array.length - 1] = null;
+        Assert.assertTrue(HttpUtil.containsIgnoreCase(array, null));
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testJoin() {
+        final String[] array = {"hello", "how", "are", "you", "?"};
+        String actual = HttpUtil.join(array, ",");
+        String expected = "hello,how,are,you,?";
+        Assert.assertEquals(actual, expected);
+
+        actual = HttpUtil.join(array, "#");
+        expected = expected.replaceAll(",", "#");
+        Assert.assertEquals(actual, expected);
+        actual = HttpUtil.join(new String[] {}, ",");
+        Assert.assertEquals(actual, "");
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testParameterToString() {
+        // with param string.
+        Object param = new String("String Param");
+        String actual = HttpUtil.parameterToString(param);
+        String expected = "String Param";
+        Assert.assertEquals(expected, actual);
+
+        // with param date.
+        final Date date = new Date();
+        param = date;
+        expected = "" + date.getTime();
+        actual = HttpUtil.parameterToString(param);
+        Assert.assertEquals(expected, actual);
+
+        // with param collection.
+        final String[] array = {"hello", "how", "are", "you", "?"};
+        param = Arrays.asList(array);
+        expected = HttpUtil.join(array, ",");
+        actual = HttpUtil.parameterToString(param);
+        Assert.assertEquals(expected, actual);
+
+        // with param any
+        param = new Object() {
+
+            @Override
+            public String toString() {
+                return "test object";
+            }
+        };
+        expected = "test object";
+        actual = HttpUtil.parameterToString(param);
+        Assert.assertEquals(expected, actual);
+
+        // with param null.
+        expected = "";
+        actual = HttpUtil.parameterToString(null);
+        Assert.assertEquals(expected, actual);
+
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testSelectHeaderAccept() {
+        final String[] accepts = {"application/json", "text/plain", "application/xml"};
+        String expected = "application/json";
+        String actual = HttpUtil.selectHeaderAccept(accepts);
+        Assert.assertEquals(expected, actual);
+
+        accepts[0] = "application/x-www-form-urlencoded";
+        expected = HttpUtil.join(accepts, ",");
+        actual = HttpUtil.selectHeaderAccept(accepts);
+        Assert.assertEquals(expected, actual);
+
+        expected = null;
+        actual = HttpUtil.selectHeaderAccept(new String[] {});
+        Assert.assertEquals(expected, actual);
+
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testSelectHeaderContentType() {
+        final String[] accepts = {"application/json", "text/plain", "application/xml"};
+        String expected = "application/json";
+        String actual = HttpUtil.selectHeaderContentType(accepts);
+        Assert.assertEquals(expected, actual);
+
+        accepts[0] = "application/x-www-form-urlencoded";
+        expected = "application/x-www-form-urlencoded";
+        actual = HttpUtil.selectHeaderContentType(accepts);
+        Assert.assertEquals(expected, actual);
+
+        expected = "application/json";
+        actual = HttpUtil.selectHeaderContentType(new String[] {});
+        Assert.assertEquals(expected, actual);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testEscapeString() throws Exception {
+        final String str = "/this/url/to be encoded";
+        final String actual = HttpUtil.escapeString(str);
+        final String expected = "%2Fthis%2Furl%2Fto%20be%20encoded";
+        Assert.assertEquals(expected, actual);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Ignore
+    @Test
+    public void testEscapeStringException() throws Exception {
+
+        final String str = "/this/url/to be encoded";
+        new NonStrictExpectations() {
+
+            @Mocked
+            URLEncoder encoder;
+
+            {
+                URLEncoder.encode(str, "utf8");
+                result = new UnsupportedEncodingException();
+            }
+        };
+
+        final String actual = HttpUtil.escapeString(str);
+        Assert.assertEquals(str, actual);
+    }
+}
diff --git a/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/clientsdk/TestJsonUtil.java b/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/clientsdk/TestJsonUtil.java
new file mode 100644 (file)
index 0000000..d532b94
--- /dev/null
@@ -0,0 +1,184 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openo.baseservice.roa.util.clientsdk;
+
+import org.openo.baseservice.roa.util.clientsdk.demo.JsonTestClass;
+
+import org.codehaus.jackson.JsonParseException;
+import org.codehaus.jackson.map.JsonMappingException;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.codehaus.jackson.type.TypeReference;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import net.sf.json.JSONObject;
+
+import junit.framework.Assert;
+
+/**
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 13-Jun-2016
+ */
+public class TestJsonUtil {
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @BeforeClass
+    public static void setUpBeforeClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @AfterClass
+    public static void tearDownAfterClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @Before
+    public void setUp() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @After
+    public void tearDown() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testUnMarshalStringClassOfT() throws Exception {
+        final String name = "myname";
+        final int id = 25;
+        final String jsonstr = "{\"name\": \"" + name + "\", \"id\": " + id + "}";
+
+        final JsonTestClass jsonObj = JsonUtil.unMarshal(jsonstr, JsonTestClass.class);
+
+        Assert.assertNotNull(jsonObj);
+        Assert.assertEquals(name, jsonObj.getName());
+        Assert.assertEquals(id, jsonObj.getId());
+
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testUnMarshalStringTypeReferenceOfT() throws Exception {
+        final String name = "myname";
+        final int id = 25;
+        final String jsonstr = "{\"name\": \"" + name + "\", \"id\": " + id + "}";
+
+        final JsonTestClass jsonObj = JsonUtil.unMarshal(jsonstr, new TypeReference<JsonTestClass>() {});
+
+        Assert.assertNotNull(jsonObj);
+        Assert.assertEquals(name, jsonObj.getName());
+        Assert.assertEquals(id, jsonObj.getId());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testMarshal() throws Exception {
+        final JsonTestClass jsonObj = new JsonTestClass();
+        jsonObj.setId(1);
+        jsonObj.setName("somename");
+        final String str = JsonUtil.marshal(jsonObj);
+        final JSONObject json = JSONObject.fromObject(str);
+        Assert.assertNotNull(json);
+        Assert.assertEquals(json.getString("name"), jsonObj.getName());
+        Assert.assertEquals(json.getInt("id"), jsonObj.getId());
+
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testMarshalJsonObj() throws Exception {
+        final JSONObject jsonObj = new JSONObject();
+        jsonObj.put("id", 10);
+        jsonObj.put("name", "some-name");
+        final String str = JsonUtil.marshal(jsonObj);
+        final JSONObject json = JSONObject.fromObject(str);
+        Assert.assertNotNull(json);
+        Assert.assertEquals(json.getString("name"), "some-name");
+        Assert.assertEquals(json.getInt("id"), 10);
+
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws JsonParseException
+     * @throws JsonMappingException
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetMapper() throws JsonParseException, JsonMappingException, Exception {
+        final String name = "myname";
+        final int id = 25;
+        final ObjectMapper mapper = JsonUtil.getMapper();
+        Assert.assertNotNull(mapper);
+        final JSONObject json = new JSONObject();
+        json.put("name", name);
+        json.put("id", id);
+        final JsonTestClass jsonObj = mapper.readValue(json.toString(), JsonTestClass.class);
+        Assert.assertNotNull(jsonObj);
+        Assert.assertEquals(name, jsonObj.getName());
+        Assert.assertEquals(id, jsonObj.getId());
+    }
+}
diff --git a/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/clientsdk/TestRestClientUtil.java b/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/clientsdk/TestRestClientUtil.java
new file mode 100644 (file)
index 0000000..0fcaf40
--- /dev/null
@@ -0,0 +1,210 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openo.baseservice.roa.util.clientsdk;
+
+import org.openo.baseservice.remoteservice.exception.ServiceException;
+import org.openo.baseservice.roa.util.restclient.Restful;
+import org.openo.baseservice.roa.util.restclient.RestfulAsyncCallback;
+import org.openo.baseservice.roa.util.restclient.RestfulParametes;
+import org.openo.baseservice.roa.util.restclient.RestfulResponse;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+
+import java.util.Arrays;
+import java.util.Date;
+
+import junit.framework.Assert;
+import mockit.Expectations;
+import mockit.Mocked;
+
+/**
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 13-Jun-2016
+ */
+public class TestRestClientUtil {
+
+    @Mocked
+    Restful restFullMock;
+
+    ExpectedException thrown = ExpectedException.none();;
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @BeforeClass
+    public static void setUpBeforeClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @AfterClass
+    public static void tearDownAfterClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @Before
+    public void setUp() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @After
+    public void tearDown() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    @Ignore
+    @Test
+    public void testInvokeMethod() throws ServiceException {
+        final String path = "test/path";
+        final RestfulParametes parameters = null;
+        final RestfulResponse expected = new RestfulResponse();
+        expected.setStatus(200);
+
+        new Expectations() {
+
+            {
+                restFullMock.get(path, parameters);
+                returns(expected);
+
+                restFullMock.post(path, parameters);
+                returns(expected);
+
+                restFullMock.patch(path, parameters);
+                returns(expected);
+
+                restFullMock.delete(path, parameters);
+                returns(expected);
+
+                restFullMock.put(path, parameters);
+                returns(expected);
+            }
+        };
+        RestfulResponse actual = RestClientUtil.invokeMethod("GET", path, parameters, restFullMock);
+        Assert.assertEquals(200, actual.getStatus());
+
+        actual = RestClientUtil.invokeMethod("POST", path, parameters, restFullMock);
+        Assert.assertEquals(200, actual.getStatus());
+
+        actual = RestClientUtil.invokeMethod("PATCH", path, parameters, restFullMock);
+        Assert.assertEquals(200, actual.getStatus());
+
+        actual = RestClientUtil.invokeMethod("DELETE", path, parameters, restFullMock);
+        Assert.assertEquals(200, actual.getStatus());
+
+        actual = RestClientUtil.invokeMethod("PUT", path, parameters, restFullMock);
+        Assert.assertEquals(200, actual.getStatus());
+    }
+
+    @Ignore
+    @Test(expected = ServiceException.class)
+    public void testInvokeMethodException() throws ServiceException {
+        RestClientUtil.invokeMethod("UNKNOWN-METHOD", "some/path", null, restFullMock);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    @Ignore
+    @Test(expected = ServiceException.class)
+    public void testInvokeAsyncMethod() throws ServiceException {
+        final String path = "test/path";
+        final RestfulParametes parameters = null;
+        final RestfulAsyncCallback callback = null;
+
+        RestClientUtil.invokeAsyncMethod("GET", path, parameters, restFullMock, callback);
+
+        RestClientUtil.invokeAsyncMethod("POST", path, parameters, restFullMock, callback);
+
+        RestClientUtil.invokeAsyncMethod("PATCH", path, parameters, restFullMock, callback);
+
+        RestClientUtil.invokeAsyncMethod("DELETE", path, parameters, restFullMock, callback);
+
+        RestClientUtil.invokeAsyncMethod("PUT", path, parameters, restFullMock, callback);
+
+        RestClientUtil.invokeAsyncMethod("UNKNOWN", path, parameters, restFullMock, callback);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Ignore
+    @Test
+    public void testIsPrimitive() {
+
+        Assert.assertTrue(RestClientUtil.isPrimitive(Integer.class));
+        Assert.assertTrue(RestClientUtil.isPrimitive(Long.class));
+        Assert.assertTrue(RestClientUtil.isPrimitive(Double.class));
+        Assert.assertTrue(RestClientUtil.isPrimitive(Void.class));
+        Assert.assertTrue(RestClientUtil.isPrimitive(String.class));
+        Assert.assertTrue(RestClientUtil.isPrimitive(Boolean.class));
+        Assert.assertTrue(RestClientUtil.isPrimitive(Byte.class));
+        Assert.assertTrue(RestClientUtil.isPrimitive(Character.class));
+        Assert.assertTrue(RestClientUtil.isPrimitive(Short.class));
+        Assert.assertTrue(RestClientUtil.isPrimitive(Float.class));
+
+        Assert.assertTrue(RestClientUtil.isPrimitive(int.class));
+        Assert.assertTrue(RestClientUtil.isPrimitive(long.class));
+        Assert.assertTrue(RestClientUtil.isPrimitive(double.class));
+        Assert.assertTrue(RestClientUtil.isPrimitive(void.class));
+        Assert.assertTrue(RestClientUtil.isPrimitive(boolean.class));
+        Assert.assertTrue(RestClientUtil.isPrimitive(byte.class));
+        Assert.assertTrue(RestClientUtil.isPrimitive(char.class));
+        Assert.assertTrue(RestClientUtil.isPrimitive(short.class));
+        Assert.assertTrue(RestClientUtil.isPrimitive(float.class));
+
+        Assert.assertFalse(RestClientUtil.isPrimitive(Object.class));
+        Assert.assertFalse(RestClientUtil.isPrimitive(Date.class));
+        Assert.assertFalse(RestClientUtil.isPrimitive(Arrays.class));
+    }
+}
diff --git a/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/clientsdk/demo/JsonTestClass.java b/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/clientsdk/demo/JsonTestClass.java
new file mode 100644 (file)
index 0000000..5833bca
--- /dev/null
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openo.baseservice.roa.util.clientsdk.demo;
+
+/**
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 13-Jun-2016
+ */
+public class JsonTestClass {
+
+    /**
+     * 
+     */
+    private String name;
+
+    /**
+     * 
+     */
+    private int id;
+
+    /**
+     * Constructor<br/>
+     * <p>
+     * </p>
+     * 
+     * @since SDNO 0.5
+     */
+    public JsonTestClass() {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @return
+     * @since SDNO 0.5
+     */
+    public String getName() {
+        return name;
+    }
+
+    /**
+     * <br/>
+     * 
+     * @param name
+     * @since SDNO 0.5
+     */
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    /**
+     * <br/>
+     * 
+     * @return
+     * @since SDNO 0.5
+     */
+    public int getId() {
+        return id;
+    }
+
+    /**
+     * <br/>
+     * 
+     * @param id
+     * @since SDNO 0.5
+     */
+    public void setId(int id) {
+        this.id = id;
+    }
+}
diff --git a/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestHttpRest.java b/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestHttpRest.java
new file mode 100644 (file)
index 0000000..ac8b4a8
--- /dev/null
@@ -0,0 +1,1289 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openo.baseservice.roa.util.restclient;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import org.openo.baseservice.remoteservice.exception.ServiceException;
+import org.openo.baseservice.roa.util.ServiceUtil;
+
+import org.eclipse.jetty.client.HttpClient;
+import org.eclipse.jetty.client.HttpExchange;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.lang.reflect.Field;
+import java.net.URLEncoder;
+
+import mockit.Expectations;
+import mockit.Mock;
+import mockit.MockUp;
+import mockit.Mocked;
+import mockit.NonStrictExpectations;
+import mockit.integration.junit4.JMockit;
+
+/**
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 13-Jun-2016
+ */
+@RunWith(JMockit.class)
+public class TestHttpRest {
+
+    @Rule
+    public ExpectedException thrown = ExpectedException.none();
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @BeforeClass
+    public static void setUpBeforeClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @AfterClass
+    public static void tearDownAfterClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @Before
+    public void setUp() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @After
+    public void tearDown() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testInitHttpRest() throws Exception {
+        final RestfulOptions options = new RestfulOptions();
+        new MockUp<HttpClient>() {
+
+            @Mock
+            public void doStart() {
+                System.out.println("started");
+            }
+        };
+        final HttpRest httpRest = new HttpRest();
+        httpRest.initHttpRest(options);
+        final Field httpClient = HttpBaseRest.class.getDeclaredField("client");
+        httpClient.setAccessible(true);
+        Assert.assertNotNull(httpClient.get(httpRest));
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testInitHttpRestExcpetion() throws Exception {
+        final RestfulOptions options = new RestfulOptions();
+        new MockUp<HttpClient>() {
+
+            @Mock
+            public void doStart() throws Exception {
+                throw new Exception();
+            }
+        };
+        final HttpRest httpRest = new HttpRest();
+        thrown.expect(ServiceException.class);
+        thrown.expectMessage("http client init failed.");
+        httpRest.initHttpRest(options);
+        final Field httpClient = HttpRest.class.getDeclaredField("client");
+        httpClient.setAccessible(true);
+        Assert.assertNull(httpClient.get(httpRest));
+        System.out.println("finished");
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testInitHttpRestNull() throws Exception {
+        final HttpRest httpRest = new HttpRest();
+        thrown.expect(ServiceException.class);
+        thrown.expectMessage("option is null.");
+        httpRest.initHttpRest(null);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws NoSuchFieldException
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testCreateRestHttpContentExchange() throws NoSuchFieldException, Exception {
+        final HttpBaseRest httpRest = new HttpRest();
+        final RestfulAsyncCallback callback = new RestfulAsyncCallback() {
+
+            @Override
+            public void callback(final RestfulResponse response) {
+
+            }
+
+            @Override
+            public void handleExcepion(final Throwable e) {
+
+            }
+
+        };
+        final RestHttpContentExchange exchange = httpRest.createRestHttpContentExchange(callback);
+        assertNotNull(exchange);
+        final Field callbackField = RestHttpContentExchange.class.getDeclaredField("callback");
+        assertNotNull(callbackField);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetStringRestfulParametes() throws Exception {
+        final RestfulOptions options = new RestfulOptions();
+
+        final HttpRest httpRest = getHttpRest(options);
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public int waitForDone() {
+                System.out.println("waitForDone");
+                return HttpExchange.STATUS_COMPLETED;
+            }
+
+            @Mock
+            public RestfulResponse getResponse() throws IOException {
+                final RestfulResponse response = new RestfulResponse();
+                response.setStatus(HttpExchange.STATUS_COMPLETED);
+                return response;
+            }
+
+        };
+        final RestfulParametes parametes = new RestfulParametes();
+        parametes.put("id", "1234");
+        parametes.put("name", "some-name");
+        parametes.put("address", null);
+        parametes.putHttpContextHeader("Content-Type", "application/json");
+        parametes.putHttpContextHeader("Accept-Encoding", "*/*");
+        final RestfulResponse response = httpRest.get("path/to/service", parametes);
+        assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus());
+
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetStringRestfulParametesRestfulOptions() throws Exception {
+        final RestfulOptions options = new RestfulOptions();
+
+        final HttpRest httpRest = getHttpRest(options);
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public int waitForDone() {
+                System.out.println("waitForDone");
+                return HttpExchange.STATUS_COMPLETED;
+            }
+
+            @Mock
+            public RestfulResponse getResponse() throws IOException {
+                final RestfulResponse response = new RestfulResponse();
+                response.setStatus(HttpExchange.STATUS_COMPLETED);
+                return response;
+            }
+
+        };
+        final RestfulResponse response = httpRest.get("path/to/service", new RestfulParametes(), options);
+        assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Ignore
+    @Test
+    public void testGetStringRestfulParametesEncodeError() throws Exception {
+        final RestfulOptions options = new RestfulOptions();
+
+        final HttpRest httpRest = getHttpRest(options);
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public int waitForDone() {
+                System.out.println("waitForDone");
+                return HttpExchange.STATUS_COMPLETED;
+            }
+
+            @Mock
+            public RestfulResponse getResponse() throws IOException {
+                final RestfulResponse response = new RestfulResponse();
+                response.setStatus(HttpExchange.STATUS_COMPLETED);
+                return response;
+            }
+
+        };
+
+        new NonStrictExpectations() {
+
+            @Mocked
+            URLEncoder encoder;
+
+            {
+                URLEncoder.encode(anyString, RestfulClientConst.ENCODING);
+                result = new UnsupportedEncodingException();
+            }
+
+        };
+
+        thrown.expect(ServiceException.class);
+        thrown.expectMessage("Broken VM does not support");
+
+        final RestfulParametes parametes = new RestfulParametes();
+        parametes.put("id", "1234");
+        parametes.put("name", "some-name");
+        parametes.put("address", null);
+        parametes.putHttpContextHeader("Content-Type", "application/json");
+        parametes.putHttpContextHeader("Accept-Encoding", "*/*");
+        final RestfulResponse response = httpRest.get("path/to/service", parametes);
+        assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus());
+
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testHeadStringRestfulParametes() throws Exception {
+        final RestfulOptions options = new RestfulOptions();
+
+        final HttpRest httpRest = getHttpRest(options);
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public int waitForDone() {
+                System.out.println("waitForDone");
+                return HttpExchange.STATUS_COMPLETED;
+            }
+
+            @Mock
+            public RestfulResponse getResponse() throws IOException {
+                final RestfulResponse response = new RestfulResponse();
+                response.setStatus(HttpExchange.STATUS_COMPLETED);
+                return response;
+            }
+
+        };
+        final RestfulParametes parametes = new RestfulParametes();
+        parametes.put("id", "1234");
+        parametes.put("name", "some-name");
+        parametes.put("address", null);
+        parametes.putHttpContextHeader("Content-Type", "");
+        parametes.putHttpContextHeader("Accept-Encoding", "");
+        final RestfulResponse response = httpRest.head("path/to/service", parametes);
+        assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Ignore
+    @Test
+    public void testHeadStringRestfulParametesRestfulOptions() throws Exception {
+        final RestfulOptions options = new RestfulOptions();
+
+        final HttpRest httpRest = getHttpRest(options);
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public int waitForDone() {
+                System.out.println("waitForDone");
+                return HttpExchange.STATUS_COMPLETED;
+            }
+
+            @Mock
+            public RestfulResponse getResponse() throws IOException {
+                final RestfulResponse response = new RestfulResponse();
+                response.setStatus(HttpExchange.STATUS_COMPLETED);
+                return response;
+            }
+
+        };
+        final RestfulParametes parametes = new RestfulParametes();
+        parametes.put("id", "1234");
+        parametes.put("name", "some-name");
+        parametes.put("address", null);
+        parametes.putHttpContextHeader("Content-Type", "");
+        parametes.putHttpContextHeader("Accept-Encoding", "");
+        new Expectations() {
+
+            ServiceUtil serviceUtil;
+
+            {
+                serviceUtil = new ServiceUtil(anyString, anyString);
+                serviceUtil.getServiceHost();
+                returns("127.0.0.1");
+
+                serviceUtil.getServicePort();
+                returns(10);
+            }
+
+        };
+        final RestfulResponse response = httpRest.head("path/to/service", parametes, options);
+        assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @param options
+     * @return
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    private HttpRest getHttpRest(final RestfulOptions options) throws ServiceException {
+        final HttpRest httpRest = new HttpRest();
+        {
+            new MockUp<HttpClient>() {
+
+                @Mock
+                public void doStart() {
+                    System.out.println("started");
+                }
+
+                @Mock
+                public void send(final HttpExchange exchange) throws IOException {
+                    System.out.println("send");
+                }
+            };
+            httpRest.initHttpRest(options);
+
+        }
+        return httpRest;
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testAsyncGetStringRestfulParametesRestfulAsyncCallback() throws Exception {
+        final RestfulOptions options = new RestfulOptions();
+
+        final HttpRest httpRest = getHttpRest(options);
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public int waitForDone() {
+                System.out.println("waitForDone");
+                return HttpExchange.STATUS_COMPLETED;
+            }
+
+            @Mock
+            public RestfulResponse getResponse() throws IOException {
+                final RestfulResponse response = new RestfulResponse();
+                response.setStatus(HttpExchange.STATUS_COMPLETED);
+                return response;
+            }
+
+        };
+
+        final RestfulAsyncCallback callback = new RestfulAsyncCallback() {
+
+            @Override
+            public void callback(final RestfulResponse response) {
+                System.out.println("callback called.");
+
+            }
+
+            @Override
+            public void handleExcepion(final Throwable e) {
+
+                System.out.println("handleExcepion called.");
+            }
+
+        };
+        httpRest.asyncGet("path/to/service", new RestfulParametes(), callback);
+        httpRest.asyncGet("path/to/service", new RestfulParametes(), null);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testAsyncGetStringRestfulParametesRestfulOptionsRestfulAsyncCallback() throws ServiceException {
+        final RestfulOptions options = new RestfulOptions();
+
+        final HttpRest httpRest = getHttpRest(options);
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public int waitForDone() {
+                System.out.println("waitForDone");
+                return HttpExchange.STATUS_COMPLETED;
+            }
+
+            @Mock
+            public RestfulResponse getResponse() throws IOException {
+                final RestfulResponse response = new RestfulResponse();
+                response.setStatus(HttpExchange.STATUS_COMPLETED);
+                return response;
+            }
+
+        };
+
+        final RestfulAsyncCallback callback = new RestfulAsyncCallback() {
+
+            @Override
+            public void callback(final RestfulResponse response) {
+                System.out.println("callback called.");
+
+            }
+
+            @Override
+            public void handleExcepion(final Throwable e) {
+
+                System.out.println("handleExcepion called.");
+            }
+
+        };
+        httpRest.asyncGet("path/to/service", new RestfulParametes(), new RestfulOptions(), callback);
+        httpRest.asyncGet("path/to/service", new RestfulParametes(), new RestfulOptions(), null);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    @Ignore
+    @Test
+    public void testPutStringRestfulParametes() throws ServiceException {
+        final RestfulOptions options = new RestfulOptions();
+
+        final HttpRest httpRest = getHttpRest(options);
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public int waitForDone() {
+                System.out.println("waitForDone");
+                return HttpExchange.STATUS_COMPLETED;
+            }
+
+            @Mock
+            public RestfulResponse getResponse() throws IOException {
+                final RestfulResponse response = new RestfulResponse();
+                response.setStatus(HttpExchange.STATUS_COMPLETED);
+                return response;
+            }
+
+        };
+        final RestfulParametes parametes = new RestfulParametes();
+        parametes.put("id", "1234");
+        parametes.put("name", "some-name");
+        parametes.put("address", null);
+        parametes.putHttpContextHeader("Content-Type", "");
+        parametes.putHttpContextHeader("Accept-Encoding", "");
+        new Expectations() {
+
+            ServiceUtil serviceUtil;
+
+            {
+                serviceUtil = new ServiceUtil(anyString, anyString);
+                serviceUtil.getServiceHost();
+                returns("127.0.0.1");
+
+                serviceUtil.getServicePort();
+                returns(-1);
+            }
+
+        };
+        final RestfulResponse response = httpRest.put("path/to/service", parametes);
+        assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    @Ignore
+    @Test
+    public void testPutStringRestfulParametesRestfulOptions() throws ServiceException {
+
+        final RestfulOptions options = new RestfulOptions();
+
+        final HttpRest httpRest = getHttpRest(options);
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public int waitForDone() {
+                System.out.println("waitForDone");
+                return HttpExchange.STATUS_COMPLETED;
+            }
+
+            @Mock
+            public RestfulResponse getResponse() throws IOException {
+                final RestfulResponse response = new RestfulResponse();
+                response.setStatus(HttpExchange.STATUS_COMPLETED);
+                return response;
+            }
+
+        };
+        final RestfulParametes parametes = new RestfulParametes();
+        parametes.put("id", "1234");
+        parametes.put("name", "some-name");
+        parametes.put("address", null);
+        parametes.putHttpContextHeader("Content-Type", "");
+        parametes.putHttpContextHeader("Accept-Encoding", "");
+        new Expectations() {
+
+            ServiceUtil serviceUtil;
+
+            {
+                serviceUtil = new ServiceUtil(anyString, anyString);
+                serviceUtil.getServiceHost();
+                returns("127.0.0.1");
+
+                serviceUtil.getServicePort();
+                returns(10);
+            }
+
+        };
+        final RestfulResponse response = httpRest.put("path/to/service", parametes, null);
+        assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testAsyncPutStringRestfulParametesRestfulAsyncCallback() throws ServiceException {
+        final RestfulOptions options = new RestfulOptions();
+
+        final HttpRest httpRest = getHttpRest(options);
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public int waitForDone() {
+                System.out.println("waitForDone");
+                return HttpExchange.STATUS_COMPLETED;
+            }
+
+            @Mock
+            public RestfulResponse getResponse() throws IOException {
+                final RestfulResponse response = new RestfulResponse();
+                response.setStatus(HttpExchange.STATUS_COMPLETED);
+                return response;
+            }
+
+        };
+
+        final RestfulAsyncCallback callback = new RestfulAsyncCallback() {
+
+            @Override
+            public void callback(final RestfulResponse response) {
+                System.out.println("callback called.");
+
+            }
+
+            @Override
+            public void handleExcepion(final Throwable e) {
+
+                System.out.println("handleExcepion called.");
+            }
+
+        };
+        httpRest.asyncPut("path/to/service", new RestfulParametes(), callback);
+        httpRest.asyncPut("path/to/service", new RestfulParametes(), null);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testAsyncPutStringRestfulParametesRestfulOptionsRestfulAsyncCallback() throws Exception {
+        final RestfulOptions options = new RestfulOptions();
+
+        final HttpRest httpRest = getHttpRest(options);
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public int waitForDone() {
+                System.out.println("waitForDone");
+                return HttpExchange.STATUS_COMPLETED;
+            }
+
+            @Mock
+            public RestfulResponse getResponse() throws IOException {
+                final RestfulResponse response = new RestfulResponse();
+                response.setStatus(HttpExchange.STATUS_COMPLETED);
+                return response;
+            }
+
+        };
+
+        final RestfulAsyncCallback callback = new RestfulAsyncCallback() {
+
+            @Override
+            public void callback(final RestfulResponse response) {
+                System.out.println("callback called.");
+
+            }
+
+            @Override
+            public void handleExcepion(final Throwable e) {
+
+                System.out.println("handleExcepion called.");
+            }
+
+        };
+        httpRest.asyncPut("path/to/service", new RestfulParametes(), new RestfulOptions(), callback);
+        httpRest.asyncPut("path/to/service", new RestfulParametes(), new RestfulOptions(), null);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testPostStringRestfulParametes() throws Exception {
+        final RestfulOptions options = new RestfulOptions();
+
+        final HttpBaseRest httpRest = getHttpRest(options);
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public int waitForDone() {
+                System.out.println("waitForDone");
+                return HttpExchange.STATUS_EXPIRED;
+            }
+
+            @Mock
+            public RestfulResponse getResponse() throws IOException {
+                final RestfulResponse response = new RestfulResponse();
+                response.setStatus(HttpExchange.STATUS_EXPIRED);
+                return response;
+            }
+
+        };
+        final RestfulParametes parameters = new RestfulParametes();
+        parameters.put("id", "1234");
+        parameters.put("name", "some-name");
+        parameters.put("address", null);
+        parameters.putHttpContextHeader("Content-Type", "");
+        parameters.putHttpContextHeader("Accept-Encoding", "");
+
+        thrown.expect(ServiceException.class);
+        thrown.expectMessage("request is expierd");
+        final RestfulResponse response = httpRest.post("http://localhost:80/path/to/service", parameters);
+        assertEquals(HttpExchange.STATUS_EXPIRED, response.getStatus());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    @Ignore
+    @Test
+    public void testPostStringRestfulParametesRestfulOptions() throws ServiceException {
+        final RestfulOptions options = new RestfulOptions();
+
+        final HttpBaseRest httpRest = getHttpRest(options);
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public int waitForDone() {
+                System.out.println("waitForDone" + HttpExchange.STATUS_EXCEPTED);
+                return HttpExchange.STATUS_EXCEPTED;
+            }
+
+            @Mock
+            public RestfulResponse getResponse() throws IOException {
+                final RestfulResponse response = new RestfulResponse();
+                response.setStatus(HttpExchange.STATUS_COMPLETED);
+                return response;
+            }
+
+        };
+        final RestfulParametes parameters = new RestfulParametes();
+        parameters.put("id", "1234");
+        parameters.put("name", "some-name");
+        parameters.put("address", null);
+        parameters.setRawData("{ \"data\"=\"sample JSON data\"");
+        parameters.putHttpContextHeader("Content-Type", "");
+        parameters.putHttpContextHeader("Accept-Encoding", "");
+        new Expectations() {
+
+            ServiceUtil serviceUtil;
+
+            {
+                serviceUtil = new ServiceUtil(anyString, anyString);
+                serviceUtil.getServiceHost();
+                returns("127.0.0.1");
+
+                serviceUtil.getServicePort();
+                returns(10);
+            }
+
+        };
+        thrown.expect(ServiceException.class);
+        thrown.expectMessage("request is exception");
+        final RestfulResponse response = httpRest.post("path/to/service", parameters, null);
+        assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testAsyncPostStringRestfulParametesRestfulAsyncCallback() throws Exception {
+        final RestfulOptions options = new RestfulOptions();
+        options.setRestTimeout(10);
+
+        final HttpBaseRest httpRest = getHttpRest(options);
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public int waitForDone() {
+                System.out.println("waitForDone:" + HttpExchange.STATUS_EXCEPTED);
+                return 99;
+            }
+
+            @Mock
+            public RestfulResponse getResponse() throws IOException {
+                final RestfulResponse response = new RestfulResponse();
+                response.setStatus(HttpExchange.STATUS_EXCEPTED);
+                return response;
+            }
+
+        };
+
+        final RestfulAsyncCallback callback = new RestfulAsyncCallback() {
+
+            @Override
+            public void callback(final RestfulResponse response) {
+                System.out.println("callback called.");
+
+            }
+
+            @Override
+            public void handleExcepion(final Throwable e) {
+
+                System.out.println("handleExcepion called.");
+            }
+
+        };
+        httpRest.asyncPost("path/to/service", new RestfulParametes(), options, callback);
+        httpRest.asyncPost("path/to/service", new RestfulParametes(), options, null);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testAsyncPostStringRestfulParametesRestfulOptionsRestfulAsyncCallback() throws ServiceException {
+        final RestfulOptions options = new RestfulOptions();
+        options.setRestTimeout(10);
+
+        final HttpBaseRest httpRest = getHttpRest(options);
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public int waitForDone() {
+                System.out.println("waitForDone:" + HttpExchange.STATUS_COMPLETED);
+                return HttpExchange.STATUS_COMPLETED;
+            }
+
+            @Mock
+            public RestfulResponse getResponse() throws IOException {
+                final RestfulResponse response = new RestfulResponse();
+                response.setStatus(HttpExchange.STATUS_COMPLETED);
+                return response;
+            }
+
+        };
+
+        final RestfulAsyncCallback callback = new RestfulAsyncCallback() {
+
+            @Override
+            public void callback(final RestfulResponse response) {
+                System.out.println("callback called.");
+
+            }
+
+            @Override
+            public void handleExcepion(final Throwable e) {
+
+                System.out.println("handleExcepion called.");
+            }
+
+        };
+        httpRest.asyncPost("path/to/service", new RestfulParametes(), options, callback);
+        httpRest.asyncPost("path/to/service", new RestfulParametes(), options, null);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testDeleteStringRestfulParametes() throws ServiceException {
+        final RestfulOptions options = new RestfulOptions();
+
+        final HttpBaseRest httpRest = getHttpRest(options);
+
+        final RestfulResponse response = httpRest.delete("path/to/service", null);
+        assertEquals(-1, response.getStatus());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    @Ignore
+    @Test
+    public void testDeleteStringRestfulParametesRestfulOptions() throws ServiceException {
+        final RestfulOptions options = new RestfulOptions();
+
+        final HttpBaseRest httpRest = getHttpRest(options);
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public int waitForDone() {
+                System.out.println("waitForDone" + HttpExchange.STATUS_COMPLETED);
+                return HttpExchange.STATUS_COMPLETED;
+            }
+
+            @Mock
+            public RestfulResponse getResponse() throws IOException {
+                final RestfulResponse response = new RestfulResponse();
+                response.setStatus(HttpExchange.STATUS_COMPLETED);
+                return response;
+            }
+
+        };
+        final RestfulParametes parameters = new RestfulParametes();
+        parameters.put("id", "1234");
+        parameters.put("name", "some-name");
+        parameters.put("address", null);
+        parameters.setRawData("{ \"data\"=\"sample JSON data\"");
+        parameters.putHttpContextHeader("Content-Type", "");
+        parameters.putHttpContextHeader("Accept-Encoding", "");
+        new Expectations() {
+
+            ServiceUtil serviceUtil;
+
+            {
+                serviceUtil = new ServiceUtil(anyString, anyString);
+                serviceUtil.getServiceHost();
+                returns("127.0.0.1");
+
+                serviceUtil.getServicePort();
+                returns(10);
+            }
+
+        };
+        final RestfulResponse response = httpRest.delete("path/to/service", parameters, options);
+        assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testAsyncDeleteStringRestfulParametesRestfulAsyncCallback() throws ServiceException {
+        final RestfulOptions options = new RestfulOptions();
+        options.setRestTimeout(10);
+
+        final HttpBaseRest httpRest = getHttpRest(options);
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public int waitForDone() {
+                System.out.println("waitForDone:" + HttpExchange.STATUS_COMPLETED);
+                return HttpExchange.STATUS_COMPLETED;
+            }
+
+            @Mock
+            public RestfulResponse getResponse() throws IOException {
+                final RestfulResponse response = new RestfulResponse();
+                response.setStatus(HttpExchange.STATUS_COMPLETED);
+                return response;
+            }
+
+        };
+
+        final RestfulAsyncCallback callback = new RestfulAsyncCallback() {
+
+            @Override
+            public void callback(final RestfulResponse response) {
+                System.out.println("callback called.");
+
+            }
+
+            @Override
+            public void handleExcepion(final Throwable e) {
+
+                System.out.println("handleExcepion called.");
+            }
+
+        };
+        httpRest.asyncDelete("path/to/service", new RestfulParametes(), callback);
+        httpRest.asyncDelete("path/to/service", new RestfulParametes(), null);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testAsyncDeleteStringRestfulParametesRestfulOptionsRestfulAsyncCallback() throws ServiceException {
+        final RestfulOptions options = new RestfulOptions();
+        options.setRestTimeout(10);
+
+        final HttpBaseRest httpRest = getHttpRest(options);
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public int waitForDone() {
+                System.out.println("waitForDone:" + HttpExchange.STATUS_COMPLETED);
+                return HttpExchange.STATUS_COMPLETED;
+            }
+
+            @Mock
+            public RestfulResponse getResponse() throws IOException {
+                final RestfulResponse response = new RestfulResponse();
+                response.setStatus(HttpExchange.STATUS_COMPLETED);
+                return response;
+            }
+
+        };
+
+        final RestfulAsyncCallback callback = new RestfulAsyncCallback() {
+
+            @Override
+            public void callback(final RestfulResponse response) {
+                System.out.println("callback called.");
+
+            }
+
+            @Override
+            public void handleExcepion(final Throwable e) {
+
+                System.out.println("handleExcepion called.");
+            }
+
+        };
+        httpRest.asyncDelete("path/to/service", new RestfulParametes(), options, callback);
+        httpRest.asyncDelete("path/to/service", new RestfulParametes(), options, null);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    @Ignore
+    @Test
+    public void testPatchStringRestfulParametes() throws ServiceException {
+        final RestfulOptions options = new RestfulOptions();
+
+        final HttpBaseRest httpRest = getHttpRest(options);
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public int waitForDone() {
+                System.out.println("waitForDone" + HttpExchange.STATUS_COMPLETED);
+                return HttpExchange.STATUS_COMPLETED;
+            }
+
+            @Mock
+            public RestfulResponse getResponse() throws IOException {
+                final RestfulResponse response = new RestfulResponse();
+                response.setStatus(HttpExchange.STATUS_COMPLETED);
+                return response;
+            }
+
+        };
+        final RestfulParametes parameters = new RestfulParametes();
+        parameters.put("id", "1234");
+        parameters.put("name", "some-name");
+        parameters.put("address", null);
+        parameters.setRawData("{ \"data\"=\"sample JSON data\"");
+        parameters.putHttpContextHeader("Content-Type", "");
+        parameters.putHttpContextHeader("Accept-Encoding", "");
+        new Expectations() {
+
+            ServiceUtil serviceUtil;
+
+            {
+                serviceUtil = new ServiceUtil(anyString, anyString);
+                serviceUtil.getServiceHost();
+                returns("127.0.0.1");
+
+                serviceUtil.getServicePort();
+                returns(10);
+            }
+
+        };
+        final RestfulResponse response = httpRest.patch("path/to/service", parameters);
+        assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    @Ignore
+    @Test
+    public void testPatchStringRestfulParametesRestfulOptions() throws ServiceException {
+        final RestfulOptions options = new RestfulOptions();
+
+        final HttpBaseRest httpRest = getHttpRest(options);
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public int waitForDone() {
+                System.out.println("waitForDone" + HttpExchange.STATUS_COMPLETED);
+                return HttpExchange.STATUS_COMPLETED;
+            }
+
+            @Mock
+            public RestfulResponse getResponse() throws IOException {
+                final RestfulResponse response = new RestfulResponse();
+                response.setStatus(HttpExchange.STATUS_COMPLETED);
+                return response;
+            }
+
+        };
+        final RestfulParametes parameters = new RestfulParametes();
+        parameters.put("id", "1234");
+        parameters.put("name", "some-name");
+        parameters.put("address", null);
+        parameters.setRawData("{ \"data\"=\"sample JSON data\"");
+        parameters.putHttpContextHeader("Content-Type", "");
+        parameters.putHttpContextHeader("Accept-Encoding", "");
+        new Expectations() {
+
+            ServiceUtil serviceUtil;
+
+            {
+                serviceUtil = new ServiceUtil(anyString, anyString);
+                serviceUtil.getServiceHost();
+                returns("127.0.0.1");
+
+                serviceUtil.getServicePort();
+                returns(10);
+            }
+
+        };
+        final RestfulResponse response = httpRest.patch("path/to/service", parameters, options);
+        assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testAsyncPatchStringRestfulParametesRestfulAsyncCallback() throws ServiceException {
+        final RestfulOptions options = new RestfulOptions();
+        options.setRestTimeout(10);
+
+        final HttpBaseRest httpRest = getHttpRest(options);
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public int waitForDone() {
+                System.out.println("waitForDone:" + HttpExchange.STATUS_COMPLETED);
+                return HttpExchange.STATUS_COMPLETED;
+            }
+
+            @Mock
+            public RestfulResponse getResponse() throws IOException {
+                final RestfulResponse response = new RestfulResponse();
+                response.setStatus(HttpExchange.STATUS_COMPLETED);
+                return response;
+            }
+
+        };
+
+        final RestfulAsyncCallback callback = new RestfulAsyncCallback() {
+
+            @Override
+            public void callback(final RestfulResponse response) {
+                System.out.println("callback called.");
+
+            }
+
+            @Override
+            public void handleExcepion(final Throwable e) {
+
+                System.out.println("handleExcepion called.");
+            }
+
+        };
+        httpRest.asyncPatch("path/to/service", new RestfulParametes(), callback);
+        httpRest.asyncPatch("path/to/service", new RestfulParametes(), null);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws ServiceException
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testAsyncPatchStringRestfulParametesRestfulOptionsRestfulAsyncCallback() throws ServiceException {
+        final RestfulOptions options = new RestfulOptions();
+        options.setRestTimeout(10);
+
+        final HttpBaseRest httpRest = getHttpRest(options);
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public int waitForDone() {
+                System.out.println("waitForDone:" + HttpExchange.STATUS_COMPLETED);
+                return HttpExchange.STATUS_COMPLETED;
+            }
+
+            @Mock
+            public RestfulResponse getResponse() throws IOException {
+                final RestfulResponse response = new RestfulResponse();
+                response.setStatus(HttpExchange.STATUS_COMPLETED);
+                return response;
+            }
+
+        };
+
+        final RestfulAsyncCallback callback = new RestfulAsyncCallback() {
+
+            @Override
+            public void callback(final RestfulResponse response) {
+                System.out.println("callback called.");
+
+            }
+
+            @Override
+            public void handleExcepion(final Throwable e) {
+
+                System.out.println("handleExcepion called.");
+            }
+
+        };
+        httpRest.asyncPatch("path/to/service", new RestfulParametes(), options, callback);
+        httpRest.asyncPatch("path/to/service", new RestfulParametes(), options, null);
+    }
+
+}
diff --git a/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestHttpContentExchange.java b/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestHttpContentExchange.java
new file mode 100644 (file)
index 0000000..094e43d
--- /dev/null
@@ -0,0 +1,590 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openo.baseservice.roa.util.restclient;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.openo.baseservice.remoteservice.exception.ServiceException;
+
+import org.apache.log4j.Level;
+import org.apache.log4j.LogManager;
+import org.eclipse.jetty.client.Address;
+import org.eclipse.jetty.client.CachedExchange;
+import org.eclipse.jetty.client.HttpDestination;
+import org.eclipse.jetty.client.HttpExchange;
+import org.eclipse.jetty.http.HttpFields;
+import org.eclipse.jetty.http.HttpHeaders;
+import org.eclipse.jetty.io.Buffer;
+import org.eclipse.jetty.io.ByteArrayBuffer;
+import org.eclipse.jetty.util.StringUtil;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.zip.GZIPInputStream;
+
+import mockit.Mock;
+import mockit.MockUp;
+import mockit.Mocked;
+import mockit.integration.junit4.JMockit;
+
+/**
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 20-Jun-2016
+ */
+@RunWith(JMockit.class)
+public class TestRestHttpContentExchange {
+
+    @Mocked
+    HttpDestination mockedDest;
+
+    @Rule
+    public ExpectedException thrown = ExpectedException.none();
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @BeforeClass
+    public static void setUpBeforeClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @AfterClass
+    public static void tearDownAfterClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @Before
+    public void setUp() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @After
+    public void tearDown() throws Exception {
+        LogManager.getLogger(RestHttpContentExchange.class).setLevel(Level.ERROR);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws IOException
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testOnRequestCommitted() throws IOException {
+        final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
+        final Address address = new Address("localhost", 9999);
+        exchange.setAddress(address);
+        exchange.setRequestURI("/the/request/uri");
+        exchange.onRequestCommitted();
+
+        LogManager.getLogger(RestHttpContentExchange.class).setLevel(Level.DEBUG);
+        exchange.onRequestCommitted();
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws IOException
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testOnRequestComplete() throws IOException {
+        final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
+        final Address address = new Address("localhost", 9999);
+        exchange.setAddress(address);
+        exchange.setRequestURI("/the/request/uri");
+        exchange.onRequestComplete();
+
+        LogManager.getLogger(RestHttpContentExchange.class).setLevel(Level.DEBUG);
+        exchange.onRequestComplete();
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testOnResponseComplete() throws Exception {
+        RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
+        final Address address = new Address("localhost", 9999);
+        exchange.setAddress(address);
+        exchange.setRequestURI("/the/request/uri");
+        exchange.onResponseComplete();
+
+        LogManager.getLogger(RestHttpContentExchange.class).setLevel(Level.DEBUG);
+        exchange.onResponseComplete();
+
+        final AtomicInteger isCallback = new AtomicInteger(0);
+        final AtomicInteger isException = new AtomicInteger(0);
+        final RestfulAsyncCallback callback = new RestfulAsyncCallback() {
+
+            @Override
+            public void callback(final RestfulResponse response) {
+                isCallback.set(1);
+            }
+
+            @Override
+            public void handleExcepion(final Throwable e) {
+                isException.set(1);
+            }
+
+        };
+
+        final Field statusField = HttpExchange.class.getDeclaredField("_status");
+        statusField.setAccessible(true);
+        exchange = new RestHttpContentExchange(false, callback);
+        statusField.set(exchange, new AtomicInteger(200));
+        exchange.setAddress(new Address("localhost", 9999));
+        exchange.setRequestURI("/the/request/uri");
+        exchange.onResponseComplete();
+        assertEquals(1, isCallback.get());
+        assertEquals(0, isException.get());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testDecompressGzipToStr() throws Exception {
+        final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
+        final Address address = new Address("localhost", 9999);
+        exchange.setAddress(address);
+        exchange.setRequestURI("/the/request/uri");
+
+        final InputStream stream = ClassLoader.getSystemResourceAsStream("sample.txt.gz");
+        final byte[] binaryData = new byte[1024];
+        stream.read(binaryData);
+        final String expected = "sample data.";
+
+        final String actual = exchange.decompressGzipToStr(binaryData);
+
+        System.out.println("actual: '" + actual + "'");
+        System.out.println("expected: '" + expected + "'");
+        assertEquals(actual, expected);
+
+        new MockUp<ByteArrayInputStream>() {
+
+            @Mock
+            public int read() throws Exception {
+                throw new IOException();
+            }
+
+            @Mock
+            public int read(final byte abyte0[], final int i, final int j) {
+
+                return -1;
+            }
+
+        };
+
+        thrown.expect(IOException.class);
+        exchange.decompressGzipToStr(binaryData);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testDecompressGzipToStrException() throws Exception {
+        final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
+        final Address address = new Address("localhost", 9999);
+        exchange.setAddress(address);
+        exchange.setRequestURI("/the/request/uri");
+
+        final InputStream stream = ClassLoader.getSystemResourceAsStream("sample.txt.gz");
+        final byte[] binaryData = new byte[1024];
+        stream.read(binaryData);
+        final String expected = "sample data.";
+
+        new MockUp<GZIPInputStream>() {
+
+            @Mock
+            public void close() throws IOException {
+                throw new IOException();
+            }
+
+        };
+
+        new MockUp<InputStreamReader>() {
+
+            @Mock
+            public void close() throws IOException {
+                throw new IOException();
+            }
+
+        };
+
+        new MockUp<ByteArrayInputStream>() {
+
+            @Mock
+            public void close() throws IOException {
+                throw new IOException();
+            }
+
+        };
+
+        final String actual = exchange.decompressGzipToStr(binaryData);
+
+        System.out.println("actual: '" + actual + "'");
+        System.out.println("expected: '" + expected + "'");
+        assertEquals(actual, expected);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testDecompressGzipToStrNull() throws Exception {
+        final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
+        final Address address = new Address("localhost", 9999);
+        exchange.setAddress(address);
+        exchange.setRequestURI("/the/request/uri");
+        final String expected = "";
+        final String actual = exchange.decompressGzipToStr(null);
+
+        System.out.println("actual: '" + actual + "'");
+        System.out.println("expected: '" + expected + "'");
+        assertEquals(actual, expected);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testOnResponseHeaderBufferBuffer() throws Exception {
+        final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
+        final Address address = new Address("localhost", 9999);
+        exchange.setAddress(address);
+        exchange.setRequestURI("/the/request/uri");
+
+        final Buffer name = new ByteArrayBuffer("key");
+        final Buffer value = new ByteArrayBuffer("value");
+        exchange.onResponseHeader(name, value);
+
+        new MockUp<HttpHeaders>() {
+
+            @Mock
+            public int getOrdinal(final Buffer buffer) {
+                return HttpHeaders.CONTENT_ENCODING_ORDINAL;
+            }
+
+        };
+        exchange.onResponseHeader(name, value);
+
+        new MockUp<StringUtil>() {
+
+            @Mock
+            public String asciiToLowerCase(final String s) {
+                return "gzip";
+            }
+
+        };
+        exchange.onResponseHeader(name, value);
+
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testOnExceptionThrowable() {
+        final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
+        final Address address = new Address("localhost", 9999);
+        exchange.setAddress(address);
+        exchange.setRequestURI("/the/request/uri");
+        exchange.onException(new Exception());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testOnExceptionThrowableWithCallback() {
+        final AtomicInteger isCallback = new AtomicInteger(0);
+        final AtomicInteger isException = new AtomicInteger(0);
+        final RestfulAsyncCallback callback = new RestfulAsyncCallback() {
+
+            @Override
+            public void callback(final RestfulResponse response) {
+                isCallback.set(1);
+            }
+
+            @Override
+            public void handleExcepion(final Throwable e) {
+                isException.set(1);
+            }
+
+        };
+        final RestHttpContentExchange exchange = new RestHttpContentExchange(true, callback);
+        final Address address = new Address("localhost", 9999);
+        exchange.setAddress(address);
+        exchange.setRequestURI("/the/request/uri");
+        exchange.onException(new Exception());
+        assertEquals(0, isCallback.get());
+        assertEquals(1, isException.get());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testOnConnectionFailedThrowable() {
+        final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
+        final Address address = new Address("localhost", 9999);
+        exchange.setAddress(address);
+        exchange.setRequestURI("/the/request/uri");
+        exchange.onConnectionFailed(new Exception());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testOnConnectionFailedThrowableException() {
+        final AtomicInteger isCallback = new AtomicInteger(0);
+        final AtomicInteger isException = new AtomicInteger(0);
+        final RestfulAsyncCallback callback = new RestfulAsyncCallback() {
+
+            @Override
+            public void callback(final RestfulResponse response) {
+                isCallback.set(1);
+            }
+
+            @Override
+            public void handleExcepion(final Throwable e) {
+                isException.set(1);
+            }
+
+        };
+        final RestHttpContentExchange exchange = new RestHttpContentExchange(true, callback);
+        final Address address = new Address("localhost", 9999);
+        exchange.setAddress(address);
+        exchange.setRequestURI("/the/request/uri");
+        exchange.onConnectionFailed(new Exception());
+        assertEquals(0, isCallback.get());
+        assertEquals(1, isException.get());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testExpireHttpDestination() {
+        final RestHttpContentExchange exchange = new RestHttpContentExchange(true, null);
+        final Address address = new Address("localhost", 9999);
+        exchange.setAddress(address);
+        exchange.setRequestURI("/the/request/uri");
+        exchange.expire(mockedDest);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testExpireHttpDestinationException() throws Exception {
+        final AtomicInteger isCallback = new AtomicInteger(0);
+        final AtomicInteger isException = new AtomicInteger(0);
+        final List<Throwable> thrSet = new ArrayList<Throwable>();
+        final RestfulAsyncCallback callback = new RestfulAsyncCallback() {
+
+            @Override
+            public void callback(final RestfulResponse response) {
+                isCallback.set(1);
+            }
+
+            @Override
+            public void handleExcepion(final Throwable e) {
+                isException.set(1);
+                thrSet.add(e);
+            }
+
+        };
+        final RestHttpContentExchange exchange = new RestHttpContentExchange(true, callback);
+        final Address address = new Address("localhost", 9999);
+        exchange.setAddress(address);
+        exchange.setRequestURI("/the/request/uri");
+        exchange.expire(mockedDest);
+        assertEquals(0, isCallback.get());
+        assertEquals(1, isException.get());
+        assertEquals(1, thrSet.size());
+        final Throwable t = thrSet.get(0);
+        assertEquals(ServiceException.class, t.getClass());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testIsGzip() throws Exception {
+        final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
+        final Address address = new Address("localhost", 9999);
+        exchange.setAddress(address);
+        exchange.setRequestURI("/the/request/uri");
+
+        final Buffer name = new ByteArrayBuffer("key");
+        final Buffer value = new ByteArrayBuffer("value");
+
+        new MockUp<HttpHeaders>() {
+
+            @Mock
+            public int getOrdinal(final Buffer buffer) {
+                return HttpHeaders.CONTENT_ENCODING_ORDINAL;
+            }
+
+        };
+        exchange.onResponseHeader(name, value);
+        assertFalse(exchange.isGzip());
+
+        new MockUp<StringUtil>() {
+
+            @Mock
+            public String asciiToLowerCase(final String s) {
+                return "gzip";
+            }
+
+        };
+        exchange.onResponseHeader(name, value);
+        assertTrue(exchange.isGzip());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetResponse() throws Exception {
+        final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
+        final Address address = new Address("localhost", 9999);
+        exchange.setAddress(address);
+        exchange.setRequestURI("/the/request/uri");
+
+        final Field statusField = HttpExchange.class.getDeclaredField("_status");
+        statusField.setAccessible(true);
+        statusField.set(exchange, new AtomicInteger(200));
+
+        RestfulResponse response = exchange.getResponse();
+        assertEquals(0, response.getStatus());
+
+        final HttpFields fields = new HttpFields();
+        final Field headerFields = CachedExchange.class.getDeclaredField("_responseFields");
+        headerFields.setAccessible(true);
+        headerFields.set(exchange, fields);
+        response = exchange.getResponse();
+        assertEquals(0, response.getStatus());
+        fields.add("Content-Type", "application/json");
+        fields.add("Content-Encode", "UTF-8");
+        response = exchange.getResponse();
+        assertEquals(0, response.getStatus());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetResponseGzip() throws Exception {
+        final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null);
+        final Address address = new Address("localhost", 9999);
+        exchange.setAddress(address);
+        exchange.setRequestURI("/the/request/uri");
+        new MockUp<RestHttpContentExchange>() {
+
+            @Mock
+            public boolean isGzip() {
+                return true;
+            }
+        };
+        final Field statusField = HttpExchange.class.getDeclaredField("_status");
+        statusField.setAccessible(true);
+        statusField.set(exchange, new AtomicInteger(200));
+
+        final RestfulResponse response = exchange.getResponse();
+        assertEquals(0, response.getStatus());
+    }
+}
diff --git a/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulConfigure.java b/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulConfigure.java
new file mode 100644 (file)
index 0000000..30b5620
--- /dev/null
@@ -0,0 +1,245 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openo.baseservice.roa.util.restclient;
+
+import static org.junit.Assert.assertEquals;
+
+import org.openo.baseservice.util.impl.SystemEnvVariablesDefImpl;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import net.sf.json.JSONObject;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URL;
+
+import mockit.Mock;
+import mockit.MockUp;
+
+/**
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 20-Jun-2016
+ */
+public class TestRestfulConfigure {
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @BeforeClass
+    public static void setUpBeforeClass() throws Exception {
+        setAppRoot();
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @AfterClass
+    public static void tearDownAfterClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @Before
+    public void setUp() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @After
+    public void tearDown() throws Exception {
+    }
+
+    private static void setAppRoot() {
+        final URL resource = ClassLoader.getSystemResource("etc/conf/restclient.json");
+        final String urlPath = resource.getPath().replace("etc/conf/restclient.json", "");
+
+        try {
+            final String path = new File(urlPath).getCanonicalPath();
+            System.out.println("path: " + path);
+
+            System.setProperty("catalina.base", path);
+            System.out.println("approot:" + System.getProperty("catalina.base"));
+        } catch(final IOException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Ignore
+    @Test
+    public final void testRestfulConfigure() throws Exception {
+        final RestfulConfigure configure = new RestfulConfigure();
+        final RestfulOptions options = configure.getOptions();
+        assertEquals("127.0.0.1", options.getHost());
+        assertEquals(8080, options.getPort());
+        assertEquals(1000, options.getIntOption("ConnectTimeout"));
+        assertEquals(10, options.getIntOption("thread"));
+        assertEquals(500000, options.getIntOption("idletimeout"));
+        assertEquals(10000, options.getIntOption("timeout"));
+
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Ignore
+    @Test
+    public final void testRestfulConfigureAppRootNull() throws Exception {
+        new MockUp<SystemEnvVariablesDefImpl>() {
+
+            @Mock
+            public String getAppRoot() {
+                return null;
+            }
+
+        };
+        final RestfulConfigure configure = new RestfulConfigure();
+        final RestfulOptions options = configure.getOptions();
+
+        assertEquals("", options.getHost());
+        assertEquals(0, options.getPort());
+        assertEquals(3000, options.getIntOption("ConnectTimeout"));
+        assertEquals(200, options.getIntOption("thread"));
+        assertEquals(30000, options.getIntOption("idletimeout"));
+        assertEquals(30000, options.getIntOption("timeout"));
+
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Ignore
+    @Test
+    public final void testRestfulConfigureDefault() throws Exception {
+
+        {
+
+            new MockUp<File>() {
+
+                @Mock
+                public boolean isFile() {
+                    return false;
+                }
+            };
+            final RestfulConfigure configure = new RestfulConfigure();
+            final RestfulOptions options = configure.getOptions();
+            assertEquals("", options.getHost());
+            assertEquals(0, options.getPort());
+            assertEquals(3000, options.getIntOption("ConnectTimeout"));
+            assertEquals(200, options.getIntOption("thread"));
+            assertEquals(30000, options.getIntOption("idletimeout"));
+            assertEquals(30000, options.getIntOption("timeout"));
+        }
+
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws Exception
+     * @since SDNO 0.5
+     */
+    @Ignore
+    @Test
+    public final void testRestfulConfigureException() throws Exception {
+
+        new MockUp<JSONObject>() {
+
+            @Mock
+            JSONObject fromObject(final Object object) throws IOException {
+                throw new IOException();
+            }
+        };
+
+        final RestfulConfigure configure = new RestfulConfigure();
+        final RestfulOptions options = configure.getOptions();
+        assertEquals("", options.getHost());
+        assertEquals(0, options.getPort());
+        assertEquals(3000, options.getIntOption("ConnectTimeout"));
+        assertEquals(200, options.getIntOption("thread"));
+        assertEquals(30000, options.getIntOption("idletimeout"));
+        assertEquals(30000, options.getIntOption("timeout"));
+
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Ignore
+    @Test
+    public final void testRestfulConfigureString() {
+        final String configFile = "rest-client-test.json";
+        final String appRoot = System.getProperty("catalina.base");
+        final RestfulConfigure configure = new RestfulConfigure(appRoot + File.separator + configFile);
+        final RestfulOptions options = configure.getOptions();
+        assertEquals("10.10.10.10", options.getHost());
+        assertEquals(443, options.getPort());
+        assertEquals(10, options.getIntOption("ConnectTimeout"));
+        assertEquals(100, options.getIntOption("thread"));
+        assertEquals(30, options.getIntOption("idletimeout"));
+        assertEquals(60, options.getIntOption("timeout"));
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Ignore
+    @Test
+    public final void testGetOptions() {
+    }
+}
\ No newline at end of file
diff --git a/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulFactory.java b/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulFactory.java
new file mode 100644 (file)
index 0000000..70c7dea
--- /dev/null
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openo.baseservice.roa.util.restclient;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import org.openo.baseservice.remoteservice.exception.ServiceException;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import mockit.Mock;
+import mockit.MockUp;
+
+/**
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 21-Jun-2016
+ */
+public class TestRestfulFactory {
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @BeforeClass
+    public static void setUpBeforeClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @AfterClass
+    public static void tearDownAfterClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @Before
+    public void setUp() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @After
+    public void tearDown() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetRestInstance() {
+        Restful instance = RestfulFactory.getRestInstance("https");
+        assertNull(instance);
+        new MockUp<HttpRest>() {
+
+            @Mock
+            public void initHttpRest(final RestfulOptions option) throws ServiceException {
+                throw new ServiceException();
+            }
+
+        };
+        instance = RestfulFactory.getRestInstance("http");
+        assertNotNull(instance);
+
+        instance = RestfulFactory.getRestInstance("http");
+        assertNotNull(instance);
+    }
+}
diff --git a/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulOptions.java b/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulOptions.java
new file mode 100644 (file)
index 0000000..624f54c
--- /dev/null
@@ -0,0 +1,315 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openo.baseservice.roa.util.restclient;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import mockit.integration.junit4.JMockit;
+
+/**
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 20-Jun-2016
+ */
+@RunWith(JMockit.class)
+public class TestRestfulOptions {
+
+    @Rule
+    final public ExpectedException thrown = ExpectedException.none();
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @BeforeClass
+    public static void setUpBeforeClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @AfterClass
+    public static void tearDownAfterClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @Before
+    public void setUp() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @After
+    public void tearDown() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testSetCalledServiceName() {
+        final RestfulOptions options = new RestfulOptions();
+        final String serviceName = "sample-service";
+        assertTrue(options.setCalledServiceName(serviceName));
+        assertEquals(serviceName, options.getCalledServicName());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetCalledServicName() {
+        final RestfulOptions options = new RestfulOptions();
+        final String serviceName = "sample-service";
+        assertEquals("", options.getCalledServicName());
+        options.setCalledServiceName(serviceName);
+        assertEquals(serviceName, options.getCalledServicName());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetPort() {
+        final RestfulOptions options = new RestfulOptions();
+        final int port = 9091;
+        assertEquals(0, options.getPort());
+        options.setPort(port);
+        assertEquals(port, options.getPort());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testSetPort() {
+        final RestfulOptions options = new RestfulOptions();
+        final int port = 9091;
+        assertTrue(options.setPort(port));
+        assertEquals(port, options.getPort());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetHost() {
+        final RestfulOptions options = new RestfulOptions();
+        final String host = "localhost";
+        assertEquals("", options.getHost());
+        options.setHost(host);
+        assertEquals(host, options.getHost());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testSetHost() {
+        final RestfulOptions options = new RestfulOptions();
+        final String host = "localhost";
+        assertTrue(options.setHost(host));
+        assertEquals(host, options.getHost());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testSetRestTimeout() {
+        final RestfulOptions options = new RestfulOptions();
+        int timeout = 0;
+        assertFalse(options.setRestTimeout(timeout));
+        assertEquals(0, options.getRestTimeout());
+
+        timeout = 1;
+        assertTrue(options.setRestTimeout(timeout));
+        assertEquals(timeout, options.getRestTimeout());
+
+        timeout = 10;
+        assertTrue(options.setRestTimeout(timeout));
+        assertEquals(timeout, options.getRestTimeout());
+
+        timeout = RestfulOptions.REST_OPTIONS_TIMEOUT_MAXTIMEOUT - 1;
+        assertTrue(options.setRestTimeout(timeout));
+        assertEquals(timeout, options.getRestTimeout());
+
+        timeout = RestfulOptions.REST_OPTIONS_TIMEOUT_MAXTIMEOUT;
+        assertTrue(options.setRestTimeout(timeout));
+        assertEquals(timeout, options.getRestTimeout());
+
+        timeout = RestfulOptions.REST_OPTIONS_TIMEOUT_MAXTIMEOUT + 1;
+        assertFalse(options.setRestTimeout(timeout));
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetRestTimeout() {
+        final RestfulOptions options = new RestfulOptions();
+        int timeout = 0;
+        assertEquals(0, options.getRestTimeout());
+
+        timeout = 1;
+        assertTrue(options.setRestTimeout(timeout));
+        assertEquals(timeout, options.getRestTimeout());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetOption() {
+        final RestfulOptions options = new RestfulOptions();
+        assertNull(options.getOption("invalid"));
+
+        options.setHost("localhost");
+        Object obj = options.getOption(RestfulClientConst.HOST_KEY_NAME);
+        assertNotNull(obj);
+        assertTrue(obj instanceof String);
+        assertEquals("localhost", obj);
+
+        final List<String> list = new ArrayList<String>();
+        list.add("data");
+        options.setOption("list", list);
+        obj = options.getOption("list");
+        assertNotNull(obj);
+        assertTrue(obj instanceof List);
+        assertSame(list, obj);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetIntOption() {
+        final RestfulOptions options = new RestfulOptions();
+
+        assertEquals(0, options.getIntOption("count"));
+
+        options.setOption("count", 1);
+        assertEquals(1, options.getIntOption("count"));
+
+        thrown.expect(RuntimeException.class);
+
+        options.setOption("string-count", "two");
+        final int value = options.getIntOption("string-count");
+        assertEquals(2, value);
+
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetStringOption() {
+        final RestfulOptions options = new RestfulOptions();
+
+        assertEquals("", options.getStringOption("count"));
+
+        options.setOption("string-count", "one");
+        assertEquals("one", options.getStringOption("string-count"));
+
+        thrown.expect(RuntimeException.class);
+
+        options.setOption("count", 2);
+        final String value = options.getStringOption("count");
+        assertEquals(2, value);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testSetOption() {
+        final RestfulOptions options = new RestfulOptions();
+        assertNull(options.getOption("invalid"));
+
+        options.setHost("localhost");
+        Object obj = options.getOption(RestfulClientConst.HOST_KEY_NAME);
+        assertNotNull(obj);
+        assertTrue(obj instanceof String);
+        assertEquals("localhost", obj);
+
+        final List<String> list = new ArrayList<String>();
+        list.add("data");
+        options.setOption("list", list);
+        obj = options.getOption("list");
+        assertNotNull(obj);
+        assertTrue(obj instanceof List);
+        assertSame(list, obj);
+    }
+}
diff --git a/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulParametes.java b/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulParametes.java
new file mode 100644 (file)
index 0000000..fd6fd9f
--- /dev/null
@@ -0,0 +1,229 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openo.baseservice.roa.util.restclient;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 21-Jun-2016
+ */
+public class TestRestfulParametes {
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @BeforeClass
+    public static void setUpBeforeClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @AfterClass
+    public static void tearDownAfterClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @Before
+    public void setUp() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @After
+    public void tearDown() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGet() {
+        final RestfulParametes params = new RestfulParametes();
+        assertNull(params.get("param"));
+        final Map<String, String> paramMap = new HashMap<String, String>();
+        params.setParamMap(paramMap);
+        paramMap.put("param", "value");
+        assertEquals("value", params.get("param"));
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testSetRawData() {
+        final RestfulParametes params = new RestfulParametes();
+        final String data = "Sample data.";
+        params.setRawData(data);
+        assertEquals(data, params.getRawData());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetRawData() {
+        final RestfulParametes params = new RestfulParametes();
+        assertNull(params.getRawData());
+        final String data = "Sample data.";
+        params.setRawData(data);
+        assertEquals(data, params.getRawData());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testPut() {
+        final RestfulParametes params = new RestfulParametes();
+        params.put("somekey", "somevalue");
+        params.put("otherkey", "othervalue");
+        assertEquals("somevalue", params.get("somekey"));
+        assertEquals("othervalue", params.get("otherkey"));
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testPutHttpContextHeaderStringString() {
+        final RestfulParametes params = new RestfulParametes();
+        params.putHttpContextHeader("Context-Encoding", "UTF-8");
+        assertEquals("UTF-8", params.getHttpContextHeader("Context-Encoding"));
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testPutHttpContextHeaderStringInt() {
+        final RestfulParametes params = new RestfulParametes();
+        params.putHttpContextHeader("Expire-At", 1000);
+        assertEquals("1000", params.getHttpContextHeader("Expire-At"));
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetHttpContextHeader() {
+        final RestfulParametes params = new RestfulParametes();
+        params.putHttpContextHeader("Expire-At", 1000);
+        params.putHttpContextHeader("Context-Encoding", "UTF-8");
+        assertEquals("1000", params.getHttpContextHeader("Expire-At"));
+        assertEquals("UTF-8", params.getHttpContextHeader("Context-Encoding"));
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetParamMap() {
+        final RestfulParametes params = new RestfulParametes();
+        params.put("key", "value");
+        final Map<String, String> map = params.getParamMap();
+        assertEquals("value", map.get("key"));
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testSetParamMap() {
+        final RestfulParametes params = new RestfulParametes();
+        final Map<String, String> map = new HashMap<String, String>();
+        map.put("key", "value");
+        params.setParamMap(map);
+        assertEquals("value", params.get("key"));
+
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetHeaderMap() {
+        final RestfulParametes params = new RestfulParametes();
+        params.putHttpContextHeader("key", "value");
+        final Map<String, String> map = params.getHeaderMap();
+        assertEquals("value", map.get("key"));
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testSetHeaderMap() {
+        final RestfulParametes params = new RestfulParametes();
+        final Map<String, String> map = new HashMap<String, String>();
+        map.put("key", "value");
+        params.setHeaderMap(map);
+        assertEquals("value", params.getHttpContextHeader("key"));
+    }
+}
diff --git a/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulResponse.java b/CommonLibrary/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulResponse.java
new file mode 100644 (file)
index 0000000..c837aec
--- /dev/null
@@ -0,0 +1,273 @@
+/*
+ * Copyright (c) 2016, Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openo.baseservice.roa.util.restclient;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * <br/>
+ * <p>
+ * </p>
+ * 
+ * @author
+ * @version SDNO 0.5 20-Jun-2016
+ */
+public class TestRestfulResponse {
+
+    @Rule
+    public ExpectedException thrown = ExpectedException.none();
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @BeforeClass
+    public static void setUpBeforeClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @AfterClass
+    public static void tearDownAfterClass() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @Before
+    public void setUp() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @throws java.lang.Exception
+     * @since SDNO 0.5
+     */
+    @After
+    public void tearDown() throws Exception {
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetStatus() {
+        final RestfulResponse response = new RestfulResponse();
+        int actual = response.getStatus();
+        int expected = -1;
+
+        assertEquals(expected, actual);
+        expected = 202;
+        response.setStatus(expected);
+        actual = response.getStatus();
+        assertEquals(expected, actual);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testSetStatus() {
+        final RestfulResponse response = new RestfulResponse();
+        final int expected = 10;
+        response.setStatus(expected);
+        final int actual = response.getStatus();
+        assertEquals(expected, actual);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetRespHeaderMap() {
+        final RestfulResponse response = new RestfulResponse();
+        Map<String, String> expected = response.getRespHeaderMap();
+        assertNull(expected);
+        expected = new HashMap<String, String>();
+        expected.put("key", "value");
+        response.setRespHeaderMap(expected);
+        final Map<String, String> actual = response.getRespHeaderMap();
+        assertNotNull(actual);
+        assertSame(actual, expected);
+
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testSetRespHeaderMap() {
+        final RestfulResponse response = new RestfulResponse();
+        response.setRespHeaderMap(null);
+        Map<String, String> expected = response.getRespHeaderMap();
+        assertNull(expected);
+        expected = new HashMap<String, String>();
+        expected.put("key", "value");
+        response.setRespHeaderMap(expected);
+        final Map<String, String> actual = response.getRespHeaderMap();
+        assertNotNull(actual);
+        assertSame(actual, expected);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetRespHeaderInt() {
+        final RestfulResponse response = new RestfulResponse();
+        response.setRespHeaderMap(null);
+        int actual = response.getRespHeaderInt("somekey");
+        assertEquals(-1, actual);
+        final Map<String, String> headers = new HashMap<String, String>();
+        headers.put("key", "value");
+        headers.put("count", "1");
+        response.setRespHeaderMap(headers);
+        actual = response.getRespHeaderInt("somekey");
+        assertEquals(-1, actual);
+
+        actual = response.getRespHeaderInt("count");
+        assertEquals(1, actual);
+
+        thrown.expect(RuntimeException.class);
+        actual = response.getRespHeaderInt("key");
+        assertEquals(1, actual);
+
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetRespHeaderLong() {
+        final RestfulResponse response = new RestfulResponse();
+        response.setRespHeaderMap(null);
+        long actual = response.getRespHeaderLong("somekey");
+        assertEquals(-1, actual);
+        final Map<String, String> headers = new HashMap<String, String>();
+        headers.put("key", "value");
+        headers.put("count", "1");
+        headers.put("max", "" + Long.MAX_VALUE);
+        headers.put("max++", Long.MAX_VALUE + 1 + "");
+        response.setRespHeaderMap(headers);
+        actual = response.getRespHeaderLong("somekey");
+        assertEquals(-1, actual);
+
+        actual = response.getRespHeaderLong("count");
+        assertEquals(1, actual);
+
+        actual = response.getRespHeaderLong("max");
+        assertEquals(Long.MAX_VALUE, actual);
+
+        actual = response.getRespHeaderLong("max++");
+        assertTrue(actual < 0);
+
+        thrown.expect(RuntimeException.class);
+        actual = response.getRespHeaderLong("key");
+        assertEquals(1, actual);
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetRespHeaderStr() {
+        final RestfulResponse response = new RestfulResponse();
+        response.setRespHeaderMap(null);
+        String actual = response.getRespHeaderStr("somekey");
+        assertEquals(null, actual);
+        final Map<String, String> headers = new HashMap<String, String>();
+        headers.put("key", "value");
+        headers.put("count", "1");
+        headers.put("max", "" + Long.MAX_VALUE);
+        response.setRespHeaderMap(headers);
+        actual = response.getRespHeaderStr("somekey");
+        assertEquals(null, actual);
+
+        actual = response.getRespHeaderStr("key");
+        assertEquals("value", actual);
+
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testGetResponseContent() {
+        final RestfulResponse response = new RestfulResponse();
+        assertEquals(null, response.getResponseContent());
+
+        final String content = "{ \"content\" = \"The response content\" }";
+        response.setResponseJson(content);
+        assertEquals(content, response.getResponseContent());
+    }
+
+    /**
+     * <br/>
+     * 
+     * @since SDNO 0.5
+     */
+    @Test
+    public void testSetResponseJson() {
+        final RestfulResponse response = new RestfulResponse();
+        assertEquals(null, response.getResponseContent());
+
+        final String content = "{ \"content\" = \"The response content\" }";
+        response.setResponseJson(content);
+        assertEquals(content, response.getResponseContent());
+    }
+}
diff --git a/CommonLibrary/rest-client/src/test/resources/etc/conf/restclient.json b/CommonLibrary/rest-client/src/test/resources/etc/conf/restclient.json
new file mode 100644 (file)
index 0000000..96b749a
--- /dev/null
@@ -0,0 +1,11 @@
+{
+    "defaulServer":
+    {
+        "host":"127.0.0.1",
+        "port":"8080",
+    },
+    "ConnectTimeout":"1000",
+    "thread":"10",
+    "idletimeout":"500000",
+    "timeout":"10000"
+}
\ No newline at end of file
diff --git a/CommonLibrary/rest-client/src/test/resources/rest-client-test.json b/CommonLibrary/rest-client/src/test/resources/rest-client-test.json
new file mode 100644 (file)
index 0000000..230ff36
--- /dev/null
@@ -0,0 +1,11 @@
+{
+    "defaulServer":
+    {
+        "host":"10.10.10.10",
+        "port":"443",
+    },
+    "ConnectTimeout":"10",
+    "thread":"100",
+    "idletimeout":"30",
+    "timeout":"60",
+}
\ No newline at end of file
diff --git a/CommonLibrary/rest-client/src/test/resources/sample.txt.gz b/CommonLibrary/rest-client/src/test/resources/sample.txt.gz
new file mode 100644 (file)
index 0000000..a39ad49
Binary files /dev/null and b/CommonLibrary/rest-client/src/test/resources/sample.txt.gz differ