diff options
Diffstat (limited to 'huawei/vnfmadapter/VnfmadapterService/service')
140 files changed, 15138 insertions, 0 deletions
diff --git a/huawei/vnfmadapter/VnfmadapterService/service/pom.xml b/huawei/vnfmadapter/VnfmadapterService/service/pom.xml new file mode 100644 index 00000000..8fc9f512 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/pom.xml @@ -0,0 +1,217 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Copyright 2016-2017, 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.nfvo</groupId> + <artifactId>vnfmadapter-service-root</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + + <artifactId>vnfmadapter-service</artifactId> + <name>nfvo/drivers/vnfm/svnfm/huawei/vnfmadapter/VnfmadapterService/service</name> + <packaging>war</packaging> + + <dependencies> + <dependency> + <groupId>org.powermock</groupId> + <artifactId>powermock-core</artifactId> + <version>1.5.4</version> +</dependency> + <dependency> + <groupId>org.powermock</groupId> + <artifactId>powermock-api-mockito</artifactId> + <version>1.5.4</version> +</dependency> +<dependency> + <groupId>org.powermock</groupId> + <artifactId>powermock-module-junit4</artifactId> + <version>1.5.4</version> +</dependency> + <dependency> + <groupId>mysql</groupId> + <artifactId>mysql-connector-java</artifactId> + <version>5.1.36</version> + </dependency> + <dependency> + <groupId>org.apache.cxf</groupId> + <artifactId>cxf-rt-frontend-jaxrs</artifactId> + <version>3.1.6</version> + </dependency> + <dependency> + <groupId>org.openo.common-services.common-utilities</groupId> + <artifactId>commonlib-cbb</artifactId> + <version>1.1.0-SNAPSHOT</version> + </dependency> + <dependency> + <groupId>org.openo.common-services.common-utilities</groupId> + <artifactId>commonlib-restclient</artifactId> + <version>1.1.0-SNAPSHOT</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.springframework</groupId> + <artifactId>spring-beans</artifactId> + <version>3.1.0.RELEASE</version> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-context</artifactId> + <version>3.1.0.RELEASE</version> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-core</artifactId> + <version>3.1.0.RELEASE</version> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-web</artifactId> + <version>3.1.0.RELEASE</version> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-asm</artifactId> + <version>3.1.0.RELEASE</version> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-expression</artifactId> + <version>3.1.0.RELEASE</version> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-aop</artifactId> + <version>3.1.0.RELEASE</version> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-jdbc</artifactId> + <version>3.1.0.RELEASE</version> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-test</artifactId> + <version>3.1.0.RELEASE</version> + </dependency> + <dependency> + <groupId>org.codehaus.jackson</groupId> + <artifactId>jackson-jaxrs</artifactId> + <version>1.9.2</version> + </dependency> + <dependency> + <groupId>javax.ws.rs</groupId> + <artifactId>jsr311-api</artifactId> + <version>1.1.1</version> + </dependency> + <dependency> + <groupId>com.sun.jersey</groupId> + <artifactId>jersey-client</artifactId> + <version>1.12</version> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-tx</artifactId> + <version>3.1.2.RELEASE</version> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + <version>4.3.5</version> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient-cache</artifactId> + <version>4.3.5</version> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpmime</artifactId> + <version>4.3.5</version> + </dependency> + + <!--dependency> + <groupId>org.apache.commons</groupId> + <artifactId>com.springsource.org.apache.commons.httpclient</artifactId> + <version>3.1.0</version> + </dependency--> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + </dependency> + <dependency> + <groupId>commons-httpclient</groupId> + <artifactId>commons-httpclient</artifactId> + <version>3.1</version> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + <version>4.3.5</version> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient-cache</artifactId> + <version>4.3.5</version> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpmime</artifactId> + <version>4.3.5</version> + </dependency> + <dependency> + <groupId>org.apache.cxf</groupId> + <artifactId>cxf-rt-frontend-jaxrs</artifactId> + <version>3.1.6</version> + </dependency> + + <!-- UT coverage dependency start --> + <dependency> + <groupId>org.jmockit</groupId> + <artifactId>jmockit</artifactId> + <version>1.19</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.jmockit</groupId> + <artifactId>jmockit-coverage</artifactId> + <version>1.18</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.8.1</version> + <scope>test</scope> + </dependency> + <!-- UT coverage dependency end --> + + + + + </dependencies> +</project> diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/mocoserver/VnfmAdapterSuccessServer.java b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/mocoserver/VnfmAdapterSuccessServer.java new file mode 100644 index 00000000..8554f7ae --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/mocoserver/VnfmAdapterSuccessServer.java @@ -0,0 +1,103 @@ +/* + * 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.nfvo.vnfmadapter.mocoserver; + +import org.openo.sdno.testframework.http.model.HttpRequest; +import org.openo.sdno.testframework.http.model.HttpResponse; +import org.openo.sdno.testframework.http.model.HttpRquestResponse; +import org.openo.sdno.testframework.moco.MocoHttpServer; +import org.openo.sdno.testframework.moco.responsehandler.MocoResponseHandler; + +/** + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 2, 2016 + */ +public class VnfmAdapterSuccessServer extends MocoHttpServer { + + private static final String GET_ALL_CLOUD_FILE = + "src/integration-test/resources/vnfmadapter/mocoserver/getallcloudinfo.json"; + + private static final String ADD_AUTH_INFO_FILE = + "src/integration-test/resources/vnfmadapter/mocoserver/addauthinfo.json"; + + private static final String GRANT_VNF_RES_FILE = + "src/integration-test/resources/vnfmadapter/mocoserver/grantvnfresource.json"; + + private static final String GET_CSAR_INFO_FILE = + "src/integration-test/resources/vnfmadapter/mocoserver/getcsarinfo.json"; + + private static final String GET_VNFM_INFO_FILE = + "src/integration-test/resources/vnfmadapter/mocoserver/getvnfminfo.json"; + + private static final String UPLOAD_VNF_INFO_FILE = + "src/integration-test/resources/vnfmadapter/mocoserver/uploadvnfpackage.json"; + + private static final String GET_VNFD_VER_FILE = + "src/integration-test/resources/vnfmadapter/mocoserver/getvnfdversion.json"; + + private static final String GET_VNFD_PLAN_FILE = + "src/integration-test/resources/vnfmadapter/mocoserver/getvnfdplaninfo.json"; + + private static final String REMOVE_VNF_FILE = + "src/integration-test/resources/vnfmadapter/mocoserver/removevnf.json"; + + private static final String GET_VNF_FILE = + "src/integration-test/resources/vnfmadapter/mocoserver/getvnf.json"; + + private static final String GET_AUTH_INFO_FILE = + "src/integration-test/resources/vnfmadapter/mocoserver/getauthinfo.json"; + + public VnfmAdapterSuccessServer() { + super(); + } + + public VnfmAdapterSuccessServer(int port) { + super(port); + } + + @Override + public void addRequestResponsePairs() { + this.addRequestResponsePair(GET_ALL_CLOUD_FILE); + this.addRequestResponsePair(ADD_AUTH_INFO_FILE); + this.addRequestResponsePair(GRANT_VNF_RES_FILE); + this.addRequestResponsePair(GET_CSAR_INFO_FILE); + this.addRequestResponsePair(GET_VNFM_INFO_FILE); + this.addRequestResponsePair(UPLOAD_VNF_INFO_FILE); + this.addRequestResponsePair(GET_VNFD_VER_FILE); + this.addRequestResponsePair(GET_VNFD_PLAN_FILE); + this.addRequestResponsePair(REMOVE_VNF_FILE); + this.addRequestResponsePair(GET_VNF_FILE); + this.addRequestResponsePair(GET_AUTH_INFO_FILE); + } + + private class CreateVimResponseHandler extends MocoResponseHandler { + + @Override + public void processRequestandResponse(HttpRquestResponse httpObject) { + System.out.println("***********************"); + System.out.println(httpObject); + System.out.println("***********************"); + HttpRequest httpRequest = httpObject.getRequest(); + HttpResponse httpResponse = httpObject.getResponse(); + } + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITAuthRoaFail.java b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITAuthRoaFail.java new file mode 100644 index 00000000..14469b29 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITAuthRoaFail.java @@ -0,0 +1,61 @@ +/* + * Copyright 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.nfvo.vnfmadapter.test; + +import java.io.File; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.nfvo.vnfmadapter.mocoserver.VnfmAdapterSuccessServer; +import org.openo.nfvo.vnfmadapter.util.AddSuccessChecker; +import org.openo.nfvo.vnfmadapter.util.FailureChecker; +import org.openo.nfvo.vnfmadapter.util.GetSuccessChecker; +import org.openo.nfvo.vnfmadapter.util.MyTestManager; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 20, 2016 + */ +public class ITAuthRoaFail extends MyTestManager { + + private static final String POST_PATH = "src/integration-test/resources/vnfmadapter/testcase/authroa/addauthinfofail.json"; + + private VnfmAdapterSuccessServer vnfmAdapterServer = new VnfmAdapterSuccessServer(); + + + @Before + public void setup() throws ServiceException, InterruptedException { + vnfmAdapterServer.start(); +// Thread.sleep(1000*30); + } + + @After + public void tearDown() throws ServiceException { + vnfmAdapterServer.stop(); + } + + @Test + public void testOperateSuccess1() throws ServiceException { + execTestCase(new File(POST_PATH),new FailureChecker()); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITAuthRoaSuccess.java b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITAuthRoaSuccess.java new file mode 100644 index 00000000..0393571e --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITAuthRoaSuccess.java @@ -0,0 +1,60 @@ +/* + * Copyright 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.nfvo.vnfmadapter.test; + +import java.io.File; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.nfvo.vnfmadapter.mocoserver.VnfmAdapterSuccessServer; +import org.openo.nfvo.vnfmadapter.util.AddSuccessChecker; +import org.openo.nfvo.vnfmadapter.util.GetSuccessChecker; +import org.openo.nfvo.vnfmadapter.util.MyTestManager; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 20, 2016 + */ +public class ITAuthRoaSuccess extends MyTestManager { + + private static final String POST_PATH = "src/integration-test/resources/vnfmadapter/testcase/authroa/addauthinfosuccess.json"; + + private VnfmAdapterSuccessServer vnfmAdapterServer = new VnfmAdapterSuccessServer(); + + + @Before + public void setup() throws ServiceException, InterruptedException { + vnfmAdapterServer.start(); +// Thread.sleep(1000*30); + } + + @After + public void tearDown() throws ServiceException { + vnfmAdapterServer.stop(); + } + + @Test + public void testOperateSuccess1() throws ServiceException { + execTestCase(new File(POST_PATH)); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITVnfAdapterResourceRoaFail.java b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITVnfAdapterResourceRoaFail.java new file mode 100644 index 00000000..8ef66b03 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITVnfAdapterResourceRoaFail.java @@ -0,0 +1,61 @@ +/* + * Copyright 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.nfvo.vnfmadapter.test; + +import java.io.File; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.nfvo.vnfmadapter.mocoserver.VnfmAdapterSuccessServer; +import org.openo.nfvo.vnfmadapter.util.FailureChecker; +import org.openo.nfvo.vnfmadapter.util.GetSuccessChecker; +import org.openo.nfvo.vnfmadapter.util.MyTestManager; +import org.openo.nfvo.vnfmadapter.util.SuccessChecker; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 24, 2016 + */ +public class ITVnfAdapterResourceRoaFail extends MyTestManager { + + private static final String GET_PATH = "src/integration-test/resources/vnfmadapter/testcase/vnfadapterresourceroa/querygetallcloudinfofail.json"; + + private VnfmAdapterSuccessServer vnfmAdapterServer = new VnfmAdapterSuccessServer(31943); + + + @Before + public void setup() throws ServiceException, InterruptedException { + vnfmAdapterServer.start(); +// Thread.sleep(1000*30); + } + + @After + public void tearDown() throws ServiceException { + vnfmAdapterServer.stop(); + } + + @Test + public void testOperateSuccess() throws ServiceException { + execTestCase(new File(GET_PATH),new FailureChecker()); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITVnfAdapterResourceRoaSuccess.java b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITVnfAdapterResourceRoaSuccess.java new file mode 100644 index 00000000..64ad1275 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITVnfAdapterResourceRoaSuccess.java @@ -0,0 +1,60 @@ +/* + * Copyright 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.nfvo.vnfmadapter.test; + +import java.io.File; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.nfvo.vnfmadapter.mocoserver.VnfmAdapterSuccessServer; +import org.openo.nfvo.vnfmadapter.util.GetSuccessChecker; +import org.openo.nfvo.vnfmadapter.util.MyTestManager; +import org.openo.nfvo.vnfmadapter.util.SuccessChecker; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 24, 2016 + */ +public class ITVnfAdapterResourceRoaSuccess extends MyTestManager { + + private static final String GET_PATH = "src/integration-test/resources/vnfmadapter/testcase/vnfadapterresourceroa/querygetallcloudinfosuccess.json"; + + private VnfmAdapterSuccessServer vnfmAdapterServer = new VnfmAdapterSuccessServer(31943); + + + @Before + public void setup() throws ServiceException, InterruptedException { + vnfmAdapterServer.start(); +// Thread.sleep(1000*30); + } + + @After + public void tearDown() throws ServiceException { + vnfmAdapterServer.stop(); + } + + @Test + public void testOperateSuccess() throws ServiceException { + execTestCase(new File(GET_PATH),new GetSuccessChecker()); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITVnfResourceRoaFail.java b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITVnfResourceRoaFail.java new file mode 100644 index 00000000..25aeaa67 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITVnfResourceRoaFail.java @@ -0,0 +1,61 @@ +/* + * Copyright 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.nfvo.vnfmadapter.test; + +import java.io.File; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.nfvo.vnfmadapter.mocoserver.VnfmAdapterSuccessServer; +import org.openo.nfvo.vnfmadapter.util.FailureChecker; +import org.openo.nfvo.vnfmadapter.util.GetSuccessChecker; +import org.openo.nfvo.vnfmadapter.util.MyTestManager; +import org.openo.nfvo.vnfmadapter.util.SuccessChecker; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 24, 2016 + */ +public class ITVnfResourceRoaFail extends MyTestManager { + + private static final String GET_PATH = "src/integration-test/resources/vnfmadapter/testcase/vnfresourceroa/grantvnfresourcefail.json"; + + private VnfmAdapterSuccessServer vnfmAdapterServer = new VnfmAdapterSuccessServer(); + + + @Before + public void setup() throws ServiceException, InterruptedException { + vnfmAdapterServer.start(); +// Thread.sleep(1000*60); + } + + @After + public void tearDown() throws ServiceException { + vnfmAdapterServer.stop(); + } + + @Test + public void testOperateSuccess() throws ServiceException { + execTestCase(new File(GET_PATH),new FailureChecker()); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITVnfResourceRoaSuccess.java b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITVnfResourceRoaSuccess.java new file mode 100644 index 00000000..549ae1ca --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITVnfResourceRoaSuccess.java @@ -0,0 +1,60 @@ +/* + * Copyright 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.nfvo.vnfmadapter.test; + +import java.io.File; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.nfvo.vnfmadapter.mocoserver.VnfmAdapterSuccessServer; +import org.openo.nfvo.vnfmadapter.util.GetSuccessChecker; +import org.openo.nfvo.vnfmadapter.util.MyTestManager; +import org.openo.nfvo.vnfmadapter.util.SuccessChecker; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 24, 2016 + */ +public class ITVnfResourceRoaSuccess extends MyTestManager { + + private static final String GET_PATH = "src/integration-test/resources/vnfmadapter/testcase/vnfresourceroa/grantvnfresourcesuccess.json"; + + private VnfmAdapterSuccessServer vnfmAdapterServer = new VnfmAdapterSuccessServer(); + + + @Before + public void setup() throws ServiceException, InterruptedException { + vnfmAdapterServer.start(); +// Thread.sleep(1000*60); + } + + @After + public void tearDown() throws ServiceException { + vnfmAdapterServer.stop(); + } + + @Test + public void testOperateSuccess() throws ServiceException { + execTestCase(new File(GET_PATH),new GetSuccessChecker()); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITVnfRoaFail.java b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITVnfRoaFail.java new file mode 100644 index 00000000..784aa9df --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITVnfRoaFail.java @@ -0,0 +1,68 @@ +/* + * Copyright 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.nfvo.vnfmadapter.test; + +import java.io.File; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.nfvo.vnfmadapter.mocoserver.VnfmAdapterSuccessServer; +import org.openo.nfvo.vnfmadapter.util.FailureChecker; +import org.openo.nfvo.vnfmadapter.util.MyTestManager; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 24, 2016 + */ +public class ITVnfRoaFail extends MyTestManager { + + private static final String POST_PATH = "src/integration-test/resources/vnfmadapter/testcase/vnfroa/addvnffail.json"; + + private static final String DEL_PATH = "src/integration-test/resources/vnfmadapter/testcase/vnfroa/deletevnffail.json"; + + private static final String GET_VNF_PATH = "src/integration-test/resources/vnfmadapter/testcase/vnfroa/getvnffail.json"; + + private static final String GET_JOB_PATH = "src/integration-test/resources/vnfmadapter/testcase/vnfroa/getjobfail.json"; + + private VnfmAdapterSuccessServer vnfmAdapterServer = new VnfmAdapterSuccessServer(); + + + @Before + public void setup() throws ServiceException, InterruptedException { + vnfmAdapterServer.start(); +// Thread.sleep(1000*30); + } + + @After + public void tearDown() throws ServiceException { + vnfmAdapterServer.stop(); + } + + @Test + public void testOperateSuccess() throws ServiceException { + execTestCase(new File(GET_VNF_PATH),new FailureChecker()); + execTestCase(new File(POST_PATH),new FailureChecker()); + execTestCase(new File(GET_JOB_PATH),new FailureChecker()); + execTestCase(new File(DEL_PATH),new FailureChecker()); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITVnfRoaSuccess.java b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITVnfRoaSuccess.java new file mode 100644 index 00000000..b2109e1f --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/test/ITVnfRoaSuccess.java @@ -0,0 +1,69 @@ +/* + * Copyright 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.nfvo.vnfmadapter.test; + +import java.io.File; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.nfvo.vnfmadapter.mocoserver.VnfmAdapterSuccessServer; +import org.openo.nfvo.vnfmadapter.util.GetSuccessChecker; +import org.openo.nfvo.vnfmadapter.util.MyTestManager; +import org.openo.nfvo.vnfmadapter.util.SuccessChecker; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 24, 2016 + */ +public class ITVnfRoaSuccess extends MyTestManager { + + private static final String POST_PATH = "src/integration-test/resources/vnfmadapter/testcase/vnfroa/addvnfsuccess.json"; + + private static final String DEL_PATH = "src/integration-test/resources/vnfmadapter/testcase/vnfroa/deletevnfsuccess.json"; + + private static final String GET_VNF_PATH = "src/integration-test/resources/vnfmadapter/testcase/vnfroa/getvnfsuccess.json"; + + private static final String GET_JOB_PATH = "src/integration-test/resources/vnfmadapter/testcase/vnfroa/getjobsuccess.json"; + + private VnfmAdapterSuccessServer vnfmAdapterServer = new VnfmAdapterSuccessServer(); + + + @Before + public void setup() throws ServiceException, InterruptedException { + vnfmAdapterServer.start(); +// Thread.sleep(1000*60); + } + + @After + public void tearDown() throws ServiceException { + vnfmAdapterServer.stop(); + } + + @Test + public void testOperateSuccess() throws ServiceException { + execTestCase(new File(GET_VNF_PATH),new GetSuccessChecker()); +// execTestCase(new File(POST_PATH),new GetSuccessChecker()); + execTestCase(new File(GET_JOB_PATH),new GetSuccessChecker()); + execTestCase(new File(DEL_PATH),new GetSuccessChecker()); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/util/AddSuccessChecker.java b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/util/AddSuccessChecker.java new file mode 100644 index 00000000..ea0dc396 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/util/AddSuccessChecker.java @@ -0,0 +1,49 @@ +/* + * Copyright 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.nfvo.vnfmadapter.util; + +import org.openo.sdno.testframework.checker.IChecker; +import org.openo.sdno.testframework.http.model.HttpResponse; + +import net.sf.json.JSONObject; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 21, 2016 + */ +public class AddSuccessChecker implements IChecker { + + String addMsg = "org.openo.nfvo.resmanage.common.update.success"; + + @Override + public boolean check(HttpResponse response) { + System.out.println("===================="); + System.out.println(response); + String data = response.getData(); + System.out.println("********************"); + System.out.println(data); +// JSONObject dataObj = JSONObject.fromObject(data); + if(response.getStatus() == 201 && data != null && !data.isEmpty()) { + return true; + } + return false; + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/util/FailureChecker.java b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/util/FailureChecker.java new file mode 100644 index 00000000..f1b8f248 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/util/FailureChecker.java @@ -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.nfvo.vnfmadapter.util; + +import org.openo.sdno.testframework.checker.IChecker; +import org.openo.sdno.testframework.http.model.HttpResponse; + +import net.sf.json.JSONObject; + +/** + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 16, 2016 + */ +public class FailureChecker implements IChecker { + + @Override + public boolean check(HttpResponse response) { + String data = response.getData(); + if(response.getStatus() != 200) { + return true; + } + JSONObject dataObj = JSONObject.fromObject(data); + int retCode = (int)dataObj.get("retCode"); + return retCode == -1; + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/util/GetSuccessChecker.java b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/util/GetSuccessChecker.java new file mode 100644 index 00000000..37856822 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/util/GetSuccessChecker.java @@ -0,0 +1,53 @@ +/* + * Copyright 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.nfvo.vnfmadapter.util; + +import org.openo.sdno.testframework.checker.IChecker; +import org.openo.sdno.testframework.http.model.HttpResponse; + +import net.sf.json.JSONObject; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 21, 2016 + */ +public class GetSuccessChecker implements IChecker { + + String addMsg = "org.openo.nfvo.resmanage.common.add.success"; + + @Override + public boolean check(HttpResponse response) { + System.out.println("===================="); + System.out.println(response); + String data = response.getData(); + System.out.println("********************"); + System.out.println(data); +// JSONObject dataObj = JSONObject.fromObject(data); +// if(response.getStatus() == 200 && !dataObj.isEmpty()) { +// System.out.println(dataObj.isEmpty()); +// return true; +// } + if(response.getStatus() == 200 && data != null && !data.isEmpty()) { + return true; + } + return false; + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/util/MyChecker.java b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/util/MyChecker.java new file mode 100644 index 00000000..6ff60919 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/util/MyChecker.java @@ -0,0 +1,65 @@ +/* + * Copyright 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.nfvo.vnfmadapter.util; + +import org.openo.sdno.testframework.checker.DefaultChecker; +import org.openo.sdno.testframework.http.model.HttpResponse; + +import net.sf.json.JSONObject; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 21, 2016 + */ +public class MyChecker extends DefaultChecker { + + private HttpResponse expectedResponse; + + /** + * Constructor<br> + * <p> + * </p> + * + * @param expectedResponse + * @since NFVO 0.5 + */ + public MyChecker(HttpResponse expectedResponse) { + super(expectedResponse); + this.expectedResponse = expectedResponse; + } + + /** + * <br> + * + * @param response + * @return + * @since NFVO 0.5 + */ + @Override + public boolean check(HttpResponse response) { + System.out.println("expectedResponse:"); + System.out.println(expectedResponse.getData()); + System.out.println("response:"); + System.out.println(JSONObject.fromObject(response.getData())); + return (JSONObject.fromObject(expectedResponse.getData())).equals(JSONObject.fromObject(response.getData())); + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/util/MyTestManager.java b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/util/MyTestManager.java new file mode 100644 index 00000000..aa866bb3 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/util/MyTestManager.java @@ -0,0 +1,163 @@ +/* + * Copyright 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.nfvo.vnfmadapter.util; + +import java.io.File; +import java.util.Iterator; +import java.util.Map; + +import org.junit.Assert; +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.baseservice.roa.util.restclient.RestfulParametes; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.sdno.testframework.checker.DefaultChecker; +import org.openo.sdno.testframework.http.model.HttpModelUtils; +import org.openo.sdno.testframework.http.model.HttpRequest; +import org.openo.sdno.testframework.http.model.HttpResponse; +import org.openo.sdno.testframework.http.model.HttpRquestResponse; +import org.openo.sdno.testframework.restclient.HttpRestClient; +import org.openo.sdno.testframework.testmanager.TestManager; +import org.openo.sdno.testframework.util.file.FileUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 21, 2016 + */ +public class MyTestManager extends TestManager { + + private HttpRestClient restClient; + + public MyTestManager() { + restClient = new HttpRestClient(); + } + + private static final Logger LOGGER = LoggerFactory.getLogger(MyTestManager.class); + + /** + * <br> + * + * @param file + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + @Override + public HttpResponse execTestCase(File file) throws ServiceException { + String content = FileUtils.readFromJson(file); + HttpRquestResponse httpObject = HttpModelUtils.praseHttpRquestResponse(content); + return send(httpObject.getRequest(), httpObject.getResponse()); + } + + private HttpResponse send(HttpRequest request, HttpResponse response) { + try { + RestfulResponse responseResult = doSend(request); + DefaultChecker checker = new MyChecker(response); + HttpResponse httpResponse = HttpModelUtils.convertResponse(responseResult); + Assert.assertEquals(Boolean.valueOf(checker.check(httpResponse)), Boolean.valueOf(true)); + return httpResponse; + } catch(ServiceException e) { + LOGGER.error("call the restful interface failed.", e); + } + return null; + } + + private RestfulResponse doSend(HttpRequest request) throws ServiceException { + String url = request.getUri(); + String method = request.getMethod(); + String body = request.getData(); + RestfulParametes restfulParametes = new RestfulParametes(); + Map requestHeaders = request.getHeaders(); + if(null != requestHeaders) { + java.util.Map.Entry curEntity; + for(Iterator iterator = requestHeaders.entrySet().iterator(); iterator.hasNext(); restfulParametes + .putHttpContextHeader((String)curEntity.getKey(), (String)curEntity.getValue())) + curEntity = (java.util.Map.Entry)iterator.next(); + + } + Map paramMap = request.getQueries(); + if(null != paramMap) + restfulParametes.setParamMap(paramMap); + if(null != body) + restfulParametes.setRawData(body); + return callRestfulMotheds(url, method, restfulParametes); + } + + private RestfulResponse callRestfulMotheds(String url, String method, RestfulParametes restfulParametes) + throws ServiceException { + String s = method; + byte byte0 = -1; + switch(s.hashCode()) { + case 3446944: + if(s.equals("post")) + byte0 = 0; + break; + + case 102230: + if(s.equals("get")) + byte0 = 1; + break; + + case 111375: + if(s.equals("put")) + byte0 = 2; + break; + + case -1335458389: + if(s.equals("delete")) + byte0 = 3; + break; + + case 3198432: + if(s.equals("head")) + byte0 = 4; + break; + + case 106438728: + if(s.equals("patch")) + byte0 = 5; + break; + } + switch(byte0) { + case 0: // '\0' + return restClient.post(url, restfulParametes); + + case 1: // '\001' + return restClient.get(url, restfulParametes); + + case 2: // '\002' + return restClient.put(url, restfulParametes); + + case 3: // '\003' + return restClient.delete(url, restfulParametes); + + case 4: // '\004' + return restClient.head(url, restfulParametes); + + case 5: // '\005' + return restClient.patch(url, restfulParametes); + } + LOGGER.error("The method is unsupported."); + throw new ServiceException("The method is unsupported."); + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/util/SuccessChecker.java b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/util/SuccessChecker.java new file mode 100644 index 00000000..dcb40c8a --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/java/org/openo/nfvo/vnfmadapter/util/SuccessChecker.java @@ -0,0 +1,46 @@ +/* + * 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.nfvo.vnfmadapter.util; + +import org.openo.sdno.testframework.checker.IChecker; +import org.openo.sdno.testframework.http.model.HttpResponse; + +import net.sf.json.JSONObject; + +/** + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 16, 2016 + */ +public class SuccessChecker implements IChecker { + + String addMsg = "org.openo.nfvo.resmanage.common.add.success"; + + @Override + public boolean check(HttpResponse response) { + String data = response.getData(); + System.out.println(data); + JSONObject dataObj = JSONObject.fromObject(data); + if(response.getStatus() == 200 && addMsg.equals(dataObj.getString("msg"))) { + return true; + } + return false; + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/server.properties b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/server.properties new file mode 100644 index 00000000..44f3fdf6 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/server.properties @@ -0,0 +1,14 @@ + +## Integration Test Server Configuration File + +## Server IpAddress +serverip=127.0.0.1 + +## Server Port +serverport=8080 + +## Http Moco Server Port +mocohttpport=12306 + +## Https Moco Server Port +mocohttpsport=12307
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/urlconfig.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/urlconfig.json new file mode 100644 index 00000000..9d07650e --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/urlconfig.json @@ -0,0 +1,18 @@ +[ + { + "url": "/svc/ipsec/v1", + "prefix": "/org.openo.sdno.ipsecservice" + }, + { + "url": "/v2.0/tokens", + "prefix": "" + }, + { + "url": "/v2.0/networks", + "prefix": "" + }, + { + "url": "/rest/v1/resmanage/virtualnetworks", + "prefix": "" + } +]
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/addauthinfo.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/addauthinfo.json new file mode 100644 index 00000000..cd4398bd --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/addauthinfo.json @@ -0,0 +1,36 @@ +{ + "request": { + "uri": "/rest/vnfmmed/v2/auth/tokens", + "method": "post", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + "auth": { + "identity": { + "methods": ["password"], + "password": { + "user": { + "name": "admin", + "password": "User@123" + } + } + } + } + } + }, + "response": { + "status": 201, + "json": { + "token": { + "methods": ["password"], + "expires_at": "", + "user": { + "id": "admin", + "name": "admin" + }, + "roa_rand": "RoaRand" + } + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getallcloudinfo.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getallcloudinfo.json new file mode 100644 index 00000000..ab9d35ce --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getallcloudinfo.json @@ -0,0 +1,18 @@ +{ + "request": { + "uri": "/rest/vnfm/vnfmvim/v2/computeservice/getAllCloud", + "method": "get", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + + } + }, + "response": { + "status": 200, + "json": [{ + "dn": "NE=34603007" + }] + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getauthinfo.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getauthinfo.json new file mode 100644 index 00000000..39a7caf7 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getauthinfo.json @@ -0,0 +1,36 @@ +{ + "request": { + "uri": "/v2/auth/tokens", + "method": "post", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + "auth": { + "identity": { + "methods": "password", + "password": { + "user": { + "name": "admin", + "password": "User@123" + } + } + } + } + } + }, + "response": { + "status": 201, + "json": { + "token": { + "methods": ["password"], + "expires_at": "", + "user": { + "id": "admin", + "name": "admin" + }, + "roa_rand": "RoaRand" + } + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getcsarinfo.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getcsarinfo.json new file mode 100644 index 00000000..86d2650b --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getcsarinfo.json @@ -0,0 +1,32 @@ +{ + "request": { + "uri": "/openoapi/catalog/v1/csars/12345", + "method": "get", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + + } + }, + "response": { + "status": 200, + "json": { + "csarId":"78ede6f3-66cc-46ab-b748-38a6c010d272", + "name":"NanocellGateway", + "provider":"ZTE", + "version":"V1.0", + "deletionPending":"false", + "createTime":"2016-06-29 03:33:15", + "modifyTime":"2016-06-29 09:33:15", + "size":"0.93M", + "operationalState":"Disabled", + "usageState":"InUse", + "onBoardState":"non-onBoarded", + "processState":"normal", + "format":"yml", + "downloadUri":"http://msb_ip:msb_port/files/catalog-http/NSAR/ZTE/NanocellGW/v1.0/NanocellGateway.csar", + "type":"NSAR" + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getjob.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getjob.json new file mode 100644 index 00000000..6dbc30e9 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getjob.json @@ -0,0 +1,16 @@ +{ + "request": { + "uri": "/v2/vapps/instances/12345?roarand=123456&type=status", + "method": "get", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + } + }, + "response": { + "status": 200, + "json": { + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getvnf.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getvnf.json new file mode 100644 index 00000000..6dbc30e9 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getvnf.json @@ -0,0 +1,16 @@ +{ + "request": { + "uri": "/v2/vapps/instances/12345?roarand=123456&type=status", + "method": "get", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + } + }, + "response": { + "status": 200, + "json": { + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getvnfdplaninfo.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getvnfdplaninfo.json new file mode 100644 index 00000000..db1d0e0e --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getvnfdplaninfo.json @@ -0,0 +1,29 @@ +{ + "request": { + "uri": "/v2/vapps/templates/12345/plans", + "method": "post", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + "template": { + "name": "MME", + "catalog": "huawei/epc/mme" + } + } + }, + "response": { + "status": 200, + "json": { + "template": { + "id": "000000001", + "name": "MME", + "vnfd_catalog": "huawei/epc/mme", + "description": "", + "vnfd_format": "tosca", + "vnfd_file_status": "queued", + "image_file_status": "queued" + } + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getvnfdversion.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getvnfdversion.json new file mode 100644 index 00000000..4c4ccf34 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getvnfdversion.json @@ -0,0 +1,29 @@ +{ + "request": { + "uri": "/v2/vapps/templates/12345", + "method": "post", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + "template": { + "name": "MME", + "catalog": "huawei/epc/mme" + } + } + }, + "response": { + "status": 200, + "json": { + "template": { + "id": "000000001", + "name": "MME", + "vnfd_catalog": "huawei/epc/mme", + "description": "", + "vnfd_format": "tosca", + "vnfd_file_status": "queued", + "image_file_status": "queued" + } + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getvnfminfo.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getvnfminfo.json new file mode 100644 index 00000000..c2bb60f3 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/getvnfminfo.json @@ -0,0 +1,29 @@ +{ + "request": { + "uri": "/openoapi/extsys/v1/vnfms/12345", + "method": "get", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + + } + }, + "response": { + "status": 200, + "json": { + "vnfmId":"19ecbb3a-3242-4fa3-9926-8dfb7ddc29ee", + "name":"vnfm", + "type":"Tacker", + "vimId":"", + "vendor":"ZTE", + "version":"v1.0", + "description":"vnfm", + "certificateUrl":"", + "url":"http://127.0.0.1:12306", + "userName":"admin", + "password":"admin", + "createTime":"2016-07-06 15:33:18" + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/grantvnfresource.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/grantvnfresource.json new file mode 100644 index 00000000..0d729e2a --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/grantvnfresource.json @@ -0,0 +1,31 @@ +{ + "request": { + "uri": "/rest/v1/resmanage/vappvm", + "method": "post", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + "vapp": { + "id": "", + "name": "", + "action": "", + "used": { + "vcpus": "", + "memory": "", + "disk": "" + }, + "drTotal": { + "vcpus": "0", + "memory": "0", + "disk": "0" + } + } + } + }, + "response": { + "status": 200, + "json": { + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/removevnf.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/removevnf.json new file mode 100644 index 00000000..339419ca --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/removevnf.json @@ -0,0 +1,16 @@ +{ + "request": { + "uri": "/v2/vapps/instances/12345?roarand=123456", + "method": "delete", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + } + }, + "response": { + "status": 200, + "json": { + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/uploadvnfpackage.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/uploadvnfpackage.json new file mode 100644 index 00000000..342c64db --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/mocoserver/uploadvnfpackage.json @@ -0,0 +1,29 @@ +{ + "request": { + "uri": "/v2/vapps/templates", + "method": "post", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + "template": { + "name": "MME", + "catalog": "huawei/epc/mme" + } + } + }, + "response": { + "status": 201, + "json": { + "template": { + "id": "000000001", + "name": "MME", + "vnfd_catalog": "huawei/epc/mme", + "description": "", + "vnfd_format": "tosca", + "vnfd_file_status": "queued", + "image_file_status": "queued" + } + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/authroa/addauthinfofail.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/authroa/addauthinfofail.json new file mode 100644 index 00000000..fa85f832 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/authroa/addauthinfofail.json @@ -0,0 +1,28 @@ +{ + "request": { + "uri": "/rest/vnfmmed/v2/auth/tokens", + "method": "post", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + "auth": { + "identity": { + "methods": ["password"], + "password": { + "user": { + "name": "admin", + "password": "User@123" + } + } + } + } + } + }, + "response": { + "status": 500, + "json": { + + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/authroa/addauthinfosuccess.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/authroa/addauthinfosuccess.json new file mode 100644 index 00000000..cd4398bd --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/authroa/addauthinfosuccess.json @@ -0,0 +1,36 @@ +{ + "request": { + "uri": "/rest/vnfmmed/v2/auth/tokens", + "method": "post", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + "auth": { + "identity": { + "methods": ["password"], + "password": { + "user": { + "name": "admin", + "password": "User@123" + } + } + } + } + } + }, + "response": { + "status": 201, + "json": { + "token": { + "methods": ["password"], + "expires_at": "", + "user": { + "id": "admin", + "name": "admin" + }, + "roa_rand": "RoaRand" + } + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfadapterresourceroa/querygetallcloudinfofail.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfadapterresourceroa/querygetallcloudinfofail.json new file mode 100644 index 00000000..c38949c8 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfadapterresourceroa/querygetallcloudinfofail.json @@ -0,0 +1,15 @@ +{ + "request": { + "uri": "/rest/rest/vnfm/vnfmvim/v2/computeservice/getAllCloud", + "method": "get", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + } + }, + "response": { + "status": 404, + "json": { + + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfadapterresourceroa/querygetallcloudinfosuccess.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfadapterresourceroa/querygetallcloudinfosuccess.json new file mode 100644 index 00000000..33beb0ca --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfadapterresourceroa/querygetallcloudinfosuccess.json @@ -0,0 +1,17 @@ +{ + "request": { + "uri": "/rest/rest/vnfm/vnfmvim/v2/computeservice/getAllCloud", + "method": "get", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + } + }, + "response": { + "status": 200, + "json": [ + { + "dn": "NE=34603007" + } + ] + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfresourceroa/grantvnfresourcefail.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfresourceroa/grantvnfresourcefail.json new file mode 100644 index 00000000..bc17edea --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfresourceroa/grantvnfresourcefail.json @@ -0,0 +1,39 @@ +{ + "request": { + "uri": "/rest/vnfmmed/csm/v2/vapps/instances/123456/grant", + "method": "put", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + "grant": { + "vnf_id":"", + "project_id": "", + "type": "instantiation", + "oparetion_right": "increase", + "vnf_name": "", + "vm_list": [{ + "vm_flavor": { + "vdu_name": "OMU_VDU", + "location": "", + "num_cpus": "", + "mem_size": "", + "proirity": "", + "storage": [{ + "vol_type": "network_storage", + "vol_size": "512" + }] + }, + "init_number": "" + }] + } + } + }, + "response": { + "status": 400, + "json": { + "grant": { + } + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfresourceroa/grantvnfresourcesuccess.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfresourceroa/grantvnfresourcesuccess.json new file mode 100644 index 00000000..4e2c3cef --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfresourceroa/grantvnfresourcesuccess.json @@ -0,0 +1,41 @@ +{ + "request": { + "uri": "/rest/vnfmmed/csm/v2/vapps/instances/123456/grant", + "method": "put", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + "grant": { + "vnf_id":"", + "project_id": "", + "type": "instantiation", + "oparetion_right": "increase", + "vnf_name": "", + "vm_list": [{ + "vm_flavor": { + "vdu_name": "OMU_VDU", + "location": "", + "num_cpus": "", + "mem_size": "", + "proirity": "", + "storage": [{ + "vol_type": "network_storage", + "vol_size": "512" + }] + }, + "init_number": "" + }] + } + } + }, + "response": { + "status": 200, + "json": { + "grant": { + "vim_id": "", + "vnf_id": "" + } + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/addvnffail.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/addvnffail.json new file mode 100644 index 00000000..de6fbfb5 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/addvnffail.json @@ -0,0 +1,45 @@ +{ + "request": { + "uri": "/rest/openoapi/hw-vnfm/v1/12345/vnfs", + "method": "post", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + "VNFM": { + "name":"vsnfm1", + "url": "https://188.100.100.86:30001", + "type": "csm", + "version": "v1", + "userName": "manoadmin", + "sites": ["Miano","Roma"], + "pwd": "User@12345", + "extro_info": { + + } + } + } + }, + "response": { + "status": 400, + "json": { + "retCode": 1, + "data": { + "name":"vsnfm1", + "updateAt": "2016-09-30 16:03:15", + "createAt": "2016-09-30 16:10:15", + "id": "fj392842fj32jf392fj392f", + "url": "https://188.100.100.86:30001", + "type": "csm", + "version": "v1", + "userName": "manoadmin", + "sites": ["Miano","Roma"], + "pwd": "User@12345", + "extro_info": { + + }, + "status": "active" + } + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/addvnfsuccess.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/addvnfsuccess.json new file mode 100644 index 00000000..646d04b6 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/addvnfsuccess.json @@ -0,0 +1,44 @@ +{ + "request": { + "uri": "/rest/openoapi/hw-vnfm/v1/12345/vnfs", + "method": "post", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + "name":"vsnfm1", + "url": "https://188.100.100.86:30001", + "type": "csm", + "version": "v1", + "userName": "manoadmin", + "sites": ["Miano","Roma"], + "pwd": "User@12345", + "vnfPackageId": "12345", + "extro_info": { + + } + } + }, + "response": { + "status": 200, + "json": { + "retCode": 1, + "data": { + "name":"vsnfm1", + "updateAt": "2016-09-30 16:03:15", + "createAt": "2016-09-30 16:10:15", + "id": "fj392842fj32jf392fj392f", + "url": "https://188.100.100.86:30001", + "type": "csm", + "version": "v1", + "userName": "manoadmin", + "sites": ["Miano","Roma"], + "pwd": "User@12345", + "extro_info": { + + }, + "status": "active" + } + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/deletevnffail.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/deletevnffail.json new file mode 100644 index 00000000..e2105a9b --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/deletevnffail.json @@ -0,0 +1,18 @@ +{ + "request": { + "uri": "/rest/openoapi/hw-vnfm/v1/12345/vnfs/54321/terminate", + "method": "post", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + } + }, + "response": { + "status": 400, + "json": { + "retCode": 1, + "data": "delete vnf success" + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/deletevnfsuccess.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/deletevnfsuccess.json new file mode 100644 index 00000000..dce221ac --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/deletevnfsuccess.json @@ -0,0 +1,18 @@ +{ + "request": { + "uri": "/rest/openoapi/hw-vnfm/v1/12345/vnfs/54321/terminate", + "method": "post", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + } + }, + "response": { + "status": 200, + "json": { + "retCode": 1, + "data": "delete vnf success" + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/getjobfail.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/getjobfail.json new file mode 100644 index 00000000..fe0937cd --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/getjobfail.json @@ -0,0 +1,33 @@ +{ + "request": { + "uri": "/rest/openoapi/hw-vnfm/v1/12345/jobs/54321", + "method": "get", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + } + }, + "response": { + "status": 400, + "json": { + "retCode": 1, + "data": { + "name":"vsnfm1", + "updateAt": "2016-09-30 16:03:15", + "createAt": "2016-09-30 16:10:15", + "id": "fj392842fj32jf392fj392f", + "url": "https://188.100.100.86:30001", + "type": "csm", + "version": "v1", + "userName": "manoadmin", + "sites": ["Miano","Roma"], + "pwd": "User@12345", + "extro_info": { + + }, + "status": "active" + } + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/getjobsuccess.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/getjobsuccess.json new file mode 100644 index 00000000..1aa63ca8 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/getjobsuccess.json @@ -0,0 +1,33 @@ +{ + "request": { + "uri": "/rest/openoapi/hw-vnfm/v1/12345/jobs/54321", + "method": "get", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + } + }, + "response": { + "status": 200, + "json": { + "retCode": 1, + "data": { + "name":"vsnfm1", + "updateAt": "2016-09-30 16:03:15", + "createAt": "2016-09-30 16:10:15", + "id": "fj392842fj32jf392fj392f", + "url": "https://188.100.100.86:30001", + "type": "csm", + "version": "v1", + "userName": "manoadmin", + "sites": ["Miano","Roma"], + "pwd": "User@12345", + "extro_info": { + + }, + "status": "active" + } + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/getvnffail.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/getvnffail.json new file mode 100644 index 00000000..1b0349e9 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/getvnffail.json @@ -0,0 +1,33 @@ +{ + "request": { + "uri": "/rest/openoapi/hw-vnfm/v1/12345/vnfs/54321", + "method": "get", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + } + }, + "response": { + "status": 400, + "json": { + "retCode": 1, + "data": { + "name":"vsnfm1", + "updateAt": "2016-09-30 16:03:15", + "createAt": "2016-09-30 16:10:15", + "id": "fj392842fj32jf392fj392f", + "url": "https://188.100.100.86:30001", + "type": "csm", + "version": "v1", + "userName": "manoadmin", + "sites": ["Miano","Roma"], + "pwd": "User@12345", + "extro_info": { + + }, + "status": "active" + } + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/getvnfsuccess.json b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/getvnfsuccess.json new file mode 100644 index 00000000..0b6525a6 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/integration-test/resources/vnfmadapter/testcase/vnfroa/getvnfsuccess.json @@ -0,0 +1,33 @@ +{ + "request": { + "uri": "/rest/openoapi/hw-vnfm/v1/12345/vnfs/54321", + "method": "get", + "headers": { + "Content-Type": "application/json;charset=UTF-8" + }, + "json": { + } + }, + "response": { + "status": 200, + "json": { + "retCode": 1, + "data": { + "name":"vsnfm1", + "updateAt": "2016-09-30 16:03:15", + "createAt": "2016-09-30 16:10:15", + "id": "fj392842fj32jf392fj392f", + "url": "https://188.100.100.86:30001", + "type": "csm", + "version": "v1", + "userName": "manoadmin", + "sites": ["Miano","Roma"], + "pwd": "User@12345", + "extro_info": { + + }, + "status": "active" + } + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/AsyncCallback.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/AsyncCallback.java new file mode 100644 index 00000000..3d2043de --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/AsyncCallback.java @@ -0,0 +1,44 @@ +/* + * Copyright 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.nfvo.vnfmadapter.common; + +import org.openo.baseservice.roa.util.restclient.RestfulAsyncCallback; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Async call back. + * .</br> + * + * @author + * @version NFVO 0.5 Sep 10, 2016 + */ +public class AsyncCallback implements RestfulAsyncCallback { + + private static final Logger LOGGER = LoggerFactory.getLogger(AsyncCallback.class); + + @Override + public void callback(RestfulResponse response) { + LOGGER.warn("function=callback, msg=status={}, content={}.", response.getStatus(), response.getResponseContent()); + } + + @Override + public void handleExcepion(Throwable e) { + LOGGER.error("function=callback, msg= e is {}.", e); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/DownloadCsarManager.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/DownloadCsarManager.java new file mode 100644 index 00000000..8d512e1a --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/DownloadCsarManager.java @@ -0,0 +1,212 @@ +/* + * Copyright 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.nfvo.vnfmadapter.common; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Enumeration; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import org.apache.http.Header; +import org.apache.http.HeaderElement; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; + +/** + * Utility class to download CSAR + * + * @author + * @version NFVO 0.5 Sep 5, 2016 + * + */ +public class DownloadCsarManager { + + private static final Logger LOG = LoggerFactory.getLogger(DownloadCsarManager.class); + + public static final int CACHE = 100 * 1024; + + private DownloadCsarManager(){ + //private constructor + } + + /** + * Download from given URL. + * @param url String + * @return + */ + public static String download(String url) { + return download(url, null); + } + + /** + * Download from given URL to given file location. + * @param url String + * @param filepath String + * @return + */ + public static String download(String url, String filepath) { + String status = ""; + try { + CloseableHttpClient client = HttpClients.createDefault(); + HttpGet httpget = new HttpGet(url); + CloseableHttpResponse response = client.execute(httpget); + + HttpEntity entity = response.getEntity(); + InputStream is = entity.getContent(); + if (filepath == null){ + filepath = getFilePath(response); //NOSONAR + } + + File file = new File(filepath); + file.getParentFile().mkdirs(); + FileOutputStream fileout = new FileOutputStream(file); + + byte[] buffer = new byte[CACHE]; + int ch; + while ((ch = is.read(buffer)) != -1) { + fileout.write(buffer,0,ch); + } + is.close(); + fileout.flush(); + fileout.close(); + status = Constant.DOWNLOADCSAR_SUCCESS; + + } catch (Exception e) { + status = Constant.DOWNLOADCSAR_FAIL; + LOG.error("Download csar file failed! "+ e.getMessage(), e); + } + return status; + } + + /** + * Retrieve file path from given response. + * @param response HttpResponse + * @return + */ + public static String getFilePath(HttpResponse response) { + String filepath = System.getProperty("java.home"); + String filename = getFileName(response); + + if (filename != null) { + filepath += filename; + } else { + filepath += getRandomFileName(); + } + return filepath; + } + + /** + * Retrieve file name from given response. + * @param response HttpResponse + * @return + */ + public static String getFileName(HttpResponse response) { + Header contentHeader = response.getFirstHeader("Content-Disposition"); + String filename = null; + if (contentHeader != null) { + HeaderElement[] values = contentHeader.getElements(); + if (values.length == 1) { + NameValuePair param = values[0].getParameterByName("filename"); + if (param != null) { + try { + filename = param.getValue(); + } catch (Exception e) { + LOG.error("getting filename failed! "+ e.getMessage(), e); + } + } + } + } + return filename; + } + + /** + * Provides random file name. + * @return + */ + public static String getRandomFileName() { + return String.valueOf(System.currentTimeMillis()); + } + + /** + * unzip CSAR packge + * @param fileName filePath + * @return + */ + public static int unzipCSAR(String fileName,String filePath){ + final int BUFFER = 2048; + int status=0; + + try { + ZipFile zipFile = new ZipFile(fileName); + Enumeration emu = zipFile.entries(); + int i=0; + while(emu.hasMoreElements()){ + ZipEntry entry = (ZipEntry)emu.nextElement(); + //read directory as file first,so only need to create directory + if (entry.isDirectory()) + { + new File(filePath + entry.getName()).mkdirs(); + continue; + } + BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); + File file = new File(filePath + entry.getName()); + //Because that is random to read zipfile,maybe the file is read first + //before the directory is read,so we need to create directory first. + File parent = file.getParentFile(); + if(parent != null && (!parent.exists())){ + parent.mkdirs(); + } + FileOutputStream fos = new FileOutputStream(file); + BufferedOutputStream bos = new BufferedOutputStream(fos,BUFFER); + + int count; + byte data[] = new byte[BUFFER]; + while ((count = bis.read(data, 0, BUFFER)) != -1) + { + bos.write(data, 0, count); + } + bos.flush(); + bos.close(); + bis.close(); + } + status=Constant.UNZIP_SUCCESS; + zipFile.close(); + } catch (Exception e) { + status=Constant.UNZIP_FAIL; + e.printStackTrace(); + } + return status; + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/RegisterConfigInfo.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/RegisterConfigInfo.java new file mode 100644 index 00000000..126af305 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/RegisterConfigInfo.java @@ -0,0 +1,96 @@ +/* + * Copyright 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.nfvo.vnfmadapter.common; + +import java.util.Locale; +import java.util.ResourceBundle; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Provide function for reading register parameter. + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 25, 2016 + */ +public class RegisterConfigInfo { + + private static final Logger LOGGER = LoggerFactory.getLogger(RegisterConfigInfo.class); + + private String serviceName; + + private String version; + + private String url; + + private String protocol; + + private String ip; + + private String port; + + private String ttl; + + private static RegisterConfigInfo regConfig = new RegisterConfigInfo(); + + private RegisterConfigInfo() { + ResourceBundle rb = ResourceBundle.getBundle("registerService", Locale.getDefault()); + serviceName = rb.getString("serviceName"); + version = rb.getString("version"); + url = rb.getString("url"); + protocol = rb.getString("protocol"); + ip = rb.getString("ip"); + port = rb.getString("port"); + ttl = rb.getString("ttl"); + } + + public static RegisterConfigInfo getInstance() { + return regConfig; + } + + public String getServiceName() { + return serviceName; + } + + public String getVersion() { + return version; + } + + public String getUrl() { + return url; + } + + public String getProtocol() { + return protocol; + } + + public String getIp() { + return ip; + } + + public String getPort() { + return port; + } + + public String getTtl() { + return ttl; + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/ResultRequestUtil.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/ResultRequestUtil.java new file mode 100644 index 00000000..c47ad64c --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/ResultRequestUtil.java @@ -0,0 +1,216 @@ +/* + * Copyright 2016-2017 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.nfvo.vnfmadapter.common; + +import java.io.IOException; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; + +import org.apache.commons.httpclient.HttpMethod; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.constant.ParamConstants; +import org.openo.nfvo.vnfmadapter.service.csm.connect.ConnectMgrVnfm; +import org.openo.nfvo.vnfmadapter.service.csm.connect.HttpRequests; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 25, 2016 + */ +public final class ResultRequestUtil { + + private static final Logger LOG = LoggerFactory.getLogger(ResultRequestUtil.class); + + private ResultRequestUtil() throws VnfmException { + throw new VnfmException("can't be instanced."); + } + + /** + * common method + * <br/> + * + * @param vnfmObject + * @param path + * url defined + * @param methodName + * [get, put, delete, post] + * @param paramsJson + * raw data with json format, if <code>methodName</code> is get + * or delete, fill it with null + * @return + * @since NFVO 0.5 + */ + public static JSONObject call(JSONObject vnfmObject, String path, String methodName, String paramsJson) { + JSONObject resultJson = new JSONObject(); + + ConnectMgrVnfm mgrVcmm = new ConnectMgrVnfm(); + + if(Constant.HTTP_OK != mgrVcmm.connect(vnfmObject)) { + resultJson.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultJson.put("data", "connect fail."); + return resultJson; + } + + HttpMethod httpMethod = null; + try { + + String result = null; + String vnfPath = path.contains("%s") ? String.format(path, mgrVcmm.getRoaRand()) : path; + LOG.info("function=call, msg=url is {}, session is {}", vnfmObject.getString("url") + vnfPath, + mgrVcmm.getAccessSession()); + HttpRequests.Builder builder = new HttpRequests.Builder(Constant.ANONYMOUS) + .addHeader(Constant.ACCESSSESSION, mgrVcmm.getAccessSession()) + .setUrl(vnfmObject.getString("url"), vnfPath).setParams(paramsJson); + MethodType methodType = MethodType.methodType(HttpRequests.Builder.class, new Class[0]); + MethodHandle mt = + MethodHandles.lookup().findVirtual(builder.getClass(), methodName, methodType).bindTo(builder); + + builder = (HttpRequests.Builder)mt.invoke(); + httpMethod = builder.execute(); + result = httpMethod.getResponseBodyAsString(); + LOG.warn("function=call, msg=response status is {}. result is {}", httpMethod.getStatusCode(), result); + resultJson.put(Constant.RETCODE, httpMethod.getStatusCode()); + resultJson.put("data", result); + } catch(IOException e) { + LOG.info("function=call, msg=IOException, e is {}", e); + } catch(ReflectiveOperationException e) { + LOG.info("function=call, msg=ReflectiveOperationException, e is {}", e); + } catch(Throwable e) { + LOG.info("function=call, msg=Throwable, e is {}", e); + } finally { + if(httpMethod != null) { + httpMethod.releaseConnection(); + } + } + + if(httpMethod == null) { + resultJson.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultJson.put("data", "get connection error"); + } + + return resultJson; + } + + /** + * common method + * <br/> + * + * @param vnfmObject + * @param path + * url defined + * @param methodName + * [get, put, delete, post] + * @param paramsJson + * raw data with json format, if <code>methodName</code> is get + * or delete, fill it with null + * @return + * @since NFVO 0.5 + */ + public static JSONObject call(JSONObject vnfmObject, String path, String methodName, String paramsJson, + String authModel) { + LOG.info("request-param=" + paramsJson + ",authModel=" + authModel + ",path=" + path + ",vnfmInfo=" + + vnfmObject); + JSONObject resultJson = new JSONObject(); + + ConnectMgrVnfm mgrVcmm = new ConnectMgrVnfm(); + + if(Constant.HTTP_OK != mgrVcmm.connect(vnfmObject, authModel)) { + resultJson.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultJson.put("data", "connect fail."); + return resultJson; + } + + HttpMethod httpMethod = null; + try { + + String result = null; + String vnfPath = path.contains("%s") ? String.format(path, mgrVcmm.getRoaRand()) : path; + LOG.info("function=call, msg=url is {}, session is {}", vnfmObject.getString("url") + vnfPath, + mgrVcmm.getAccessSession()); + HttpRequests.Builder builder = + new HttpRequests.Builder(authModel).addHeader(Constant.ACCESSSESSION, mgrVcmm.getAccessSession()) + .setUrl(vnfmObject.getString("url"), vnfPath).setParams(paramsJson); + MethodType methodType = MethodType.methodType(HttpRequests.Builder.class, new Class[0]); + MethodHandle mt = + MethodHandles.lookup().findVirtual(builder.getClass(), methodName, methodType).bindTo(builder); + + builder = (HttpRequests.Builder)mt.invoke(); + httpMethod = builder.execute(); + result = httpMethod.getResponseBodyAsString(); + LOG.warn("function=call, msg=response status is {}. result is {}", httpMethod.getStatusCode(), result); + resultJson.put(Constant.RETCODE, httpMethod.getStatusCode()); + resultJson.put("data", result); + + // logout delete tokens + String token = mgrVcmm.getAccessSession(); + String roaRand = mgrVcmm.getRoaRand(); + String vnfmUrl = vnfmObject.getString("url"); + removeTokens(vnfmUrl, token, roaRand); + } catch(IOException e) { + LOG.info("function=call, msg=IOException, e is {}", e); + } catch(ReflectiveOperationException e) { + LOG.info("function=call, msg=ReflectiveOperationException, e is {}", e); + } catch(Throwable e) { + LOG.info("function=call, msg=Throwable, e is {}", e); + } finally { + if(httpMethod != null) { + httpMethod.releaseConnection(); + } + } + + if(httpMethod == null) { + resultJson.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultJson.put("data", "get connection error"); + } + + return resultJson; + } + + /** + * <br> + * + * @since NFVO 0.5 + */ + private static void removeTokens(String vnfmUrl, String token, String roaRand) { + HttpMethod httpMethodToken = null; + String tokenUrl = String.format(ParamConstants.CSM_AUTH_DISCONNECT, "manoadmin", roaRand); + LOG.info("removeTokens tokenUrl=" + tokenUrl); + try { + httpMethodToken = new HttpRequests.Builder(Constant.CERTIFICATE).setUrl(vnfmUrl.trim(), tokenUrl) + .setParams("").addHeader("X-Auth-Token", token).delete().execute(); + int statusCode = httpMethodToken.getStatusCode(); + String result = httpMethodToken.getResponseBodyAsString(); + LOG.info("removeTokens int=" + statusCode + ", result=" + result); + } catch(IOException e) { + LOG.info("function=call, msg=IOException, e is {}", e); + } catch(Throwable e) { + LOG.info("function=call, msg=Throwable, e is {}", e); + } finally { + if(httpMethodToken != null) { + httpMethodToken.releaseConnection(); + } + } + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/VnfmException.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/VnfmException.java new file mode 100644 index 00000000..06517ef3 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/VnfmException.java @@ -0,0 +1,74 @@ +/* + * Copyright 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.nfvo.vnfmadapter.common; + +/** + * VNFM exception. + * .</br> + * + * @author + * @version NFVO 0.5 Sep 10, 2016 + */ +public class VnfmException extends Exception { + + private static final long serialVersionUID = 1L; + + /** + * + * Constructor<br> + * + * @since NFVO 0.5 + */ + public VnfmException() { + super(); + } + + /** + * + * Constructor<br> + * + * @param message + * @param cause + * @since NFVO 0.5 + */ + public VnfmException(String message, Throwable cause) { + super(message, cause); + } + + /** + * + * Constructor<br> + * + * @param message + * @since NFVO 0.5 + */ + public VnfmException(String message) { + super(message); + } + + /** + * + * Constructor<br> + * + * @param cause + * @since NFVO 0.5 + */ + public VnfmException(Throwable cause) { + super(cause); + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/VnfmJsonUtil.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/VnfmJsonUtil.java new file mode 100644 index 00000000..ab9f7935 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/VnfmJsonUtil.java @@ -0,0 +1,78 @@ +/* + * Copyright 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.nfvo.vnfmadapter.common; +import java.io.IOException; +import java.io.InputStream; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONArray; +import net.sf.json.JSONException; +import net.sf.json.JSONObject; +import net.sf.json.util.JSONTokener; + +/** + * VNFM JSON utils.</br> + * + * @author + * @version NFVO 0.5 Sep 10, 2016 + */ +public final class VnfmJsonUtil { + + private static final Logger LOGGER = LoggerFactory.getLogger(VnfmJsonUtil.class); + + private VnfmJsonUtil(){ + //private constructor + } + + /** + * Get the JSON string from input http context. + * <br/> + * + * @param vnfReq HttpServletRequest + * @return + * @since NFVO 0.5 + */ + @SuppressWarnings("unchecked") + public static <T> T getJsonFromContexts(HttpServletRequest vnfReq) { + try { + InputStream vnfInput = vnfReq.getInputStream(); + String vnfJsonStr = IOUtils.toString(vnfInput); + JSONTokener vnfJsonTokener = new JSONTokener(vnfJsonStr); + + if(vnfJsonTokener.nextClean() == Character.codePointAt("{", 0)) { + return (T)JSONObject.fromObject(vnfJsonStr); + } + + vnfJsonTokener.back(); + + if(vnfJsonTokener.nextClean() == Character.codePointAt("[", 0)) { + return (T)JSONArray.fromObject(vnfJsonStr); + } + } catch(IOException e) { + LOGGER.error("function=getJsonFromContext, msg=IOException occurs, e={}.", e); + } catch(JSONException e) { + LOGGER.error("function=getJsonFromContext, msg=JSONException occurs, e={}.", e); + } + + return null; + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/VnfmUtil.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/VnfmUtil.java new file mode 100644 index 00000000..0da2142b --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/VnfmUtil.java @@ -0,0 +1,94 @@ +/* + * Copyright 2016-2017 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.nfvo.vnfmadapter.common; + +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.common.servicetoken.VnfmRestfulUtil; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.constant.ParamConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; + +/** + * Provide function of getting vnfmInfo + * <br/> + * + * @author + * @version NFVO 0.5 Aug 25, 2016 + */ +public final class VnfmUtil { + + private static final Logger LOGGER = LoggerFactory.getLogger(VnfmUtil.class); + + private VnfmUtil() { + + } + + /** + * Get vnfmInfo by ip + * <br/> + * + * @param vnfmId + * @return + * @since NFVO 0.5 + */ + public static JSONObject getVnfmById(String vnfmId) { + RestfulResponse rsp = VnfmRestfulUtil.getRemoteResponse(String.format(ParamConstants.ESR_GET_VNFM_URL, vnfmId), + VnfmRestfulUtil.TYPE_GET, null); + if(rsp == null || rsp.getStatus() != Constant.HTTP_OK) { + LOGGER.error("funtion=getVnfmById, status={}", rsp.getStatus()); + return null; + } + return JSONObject.fromObject(rsp.getResponseContent()); + } + + public static JSONObject mockForTest(String vnfmId){ + String vInfo = "{\"vnfmId\":\"1234\", \"name\":\"vnfm\", \"type\":\"Tacker\", \"vimId\":\"\", \"vendor\":\"huawei\", \"version\":\"v1.0\", \"description\":\"vnfm\", \"certificateUrl\":\"\", \"url\":\"https://192.168.44.126:30001\", \"userName\":\"manoadmin\", \"password\":\"User@12345\", \"createTime\":\"2016-07-06 15:33:18\"}"; + JSONObject json = JSONObject.fromObject(vInfo); + json.put("vnfmId",vnfmId); + return json; + } + + /** + * Get vnfmInfo by id + * <br/> + * + * @param ip + * @return + * @since NFVO 0.5 + */ + public static String getVnfmIdByIp(String ip) { + RestfulResponse rsp = + VnfmRestfulUtil.getRemoteResponse(ParamConstants.ESR_GET_VNFMS_URL, VnfmRestfulUtil.TYPE_GET, null); + if(rsp == null || rsp.getStatus() != Constant.HTTP_OK) { + return ""; + } + + JSONArray vnfmList = JSONArray.fromObject(rsp.getResponseContent()); + LOGGER.info("vnfm ip: {}, vnfmList: {}", ip, vnfmList); + for(int i = 0; i < vnfmList.size(); i++) { + if(vnfmList.getJSONObject(i).getString("url").contains(ip)) { + return vnfmList.getJSONObject(i).getString("vnfmId"); + } + } + + return ""; + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/servicetoken/HttpRestfulHelp.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/servicetoken/HttpRestfulHelp.java new file mode 100644 index 00000000..9efd9a72 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/servicetoken/HttpRestfulHelp.java @@ -0,0 +1,67 @@ +/* + * Copyright 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.nfvo.vnfmadapter.common.servicetoken; + +import java.util.HashMap; +import java.util.Map; + +import org.openo.baseservice.roa.util.restclient.HttpRest; +import org.openo.baseservice.roa.util.restclient.Restful; + +/** + * HTTP Restful helper. + * .</br> + * + * @author + * @version NFVO 0.5 Sep 10, 2016 + */ +public class HttpRestfulHelp { + + public static final String PROTO_HTTPS = "https"; + + public static final String PROTO_HTTP = "http"; + + private static final Map<String, Restful> INSTANCES = new HashMap<>(2); + + private HttpRestfulHelp() { + // constructor + } + + /** + * Factory method to create Restful instances. + * <br> + * + * @param ssloptionfile + * @param restoptionfile + * @return + * @since NFVO 0.5 + */ + public static synchronized Restful getRestInstance(String ssloptionfile, String restoptionfile) { + Restful rest = INSTANCES.get(PROTO_HTTP); + if(rest != null) { + return rest; + } + rest = createHttpsRest(ssloptionfile, restoptionfile); + INSTANCES.put(PROTO_HTTP, rest); + return rest; + } + + private static Restful createHttpsRest(String ssloptionfile, String restoptionfile) { //NOSONAR + return new HttpRest(); + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/servicetoken/VNFRestfulUtil.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/servicetoken/VNFRestfulUtil.java new file mode 100644 index 00000000..cf7c986f --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/servicetoken/VNFRestfulUtil.java @@ -0,0 +1,460 @@ +/* + * Copyright 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.nfvo.vnfmadapter.common.servicetoken; + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +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.RestfulFactory; +import org.openo.baseservice.roa.util.restclient.RestfulOptions; +import org.openo.baseservice.roa.util.restclient.RestfulParametes; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.common.VnfmException; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; + +/** + * Utility class.</br> + * + * @author + * @version NFVO 0.5 Sep 10, 2016 + */ +public final class VNFRestfulUtil { + + public static final String TYPE_GET = "get"; + + public static final String TYPE_ADD = "add"; + + public static final String TYPE_POST = "post"; + + public static final String TYPE_PUT = "put"; + + public static final String TYPE_DEL = "delete"; + + public static final int ERROR_STATUS_CODE = -1; + + public static final String CONTENT_TYPE = "Content-type"; + + public static final String APPLICATION = "application/json"; + + private static final Logger LOG = LoggerFactory.getLogger(VNFRestfulUtil.class); + + private VNFRestfulUtil() { + + } + + /** + * within our module, we support a default method to invoke + * + * @param methodNames String + * @param path + * rest service url + * @param methodName + * [post, delete, put, get, asyncPost, asyncDelete, asyncPut, + * asyncGet] + * @param bodyParam + * rest body msg + * @return + */ + @SuppressWarnings("unchecked") + public static RestfulResponse getRestResByDefault(String path, String methodNames, JSONObject bodyParam) { + RestfulParametes restParametes = new RestfulParametes(); + Map<String, String> headerMap = new HashMap<>(2); + headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION); + restParametes.setHeaderMap(headerMap); + + if(Constant.GET.equals(methodNames) || Constant.DELETE.equals(methodNames)) { + if(null != bodyParam) { + Map<String, String> vnfParamMap = new HashMap<>(Constant.DEFAULT_COLLECTION_SIZE); + if(path.contains("?")) { + String[] vnFutlList = path.split("\\?"); + String[] vnFparams = vnFutlList[1].split("&"); + int paramsSize = vnFparams.length; + + for(int i = 0; i < paramsSize; i++) { + vnfParamMap.put(vnFparams[i].split("=")[0], vnFparams[i].split("=")[1]); + } + } + + String vnFparamKey = null; + Iterator<String> nameItr = bodyParam.keys(); + while(nameItr.hasNext()) { + vnFparamKey = nameItr.next(); + vnfParamMap.put(vnFparamKey, bodyParam.get(vnFparamKey).toString()); + + } + LOG.warn("method is GET or DEL,and paramsMap = " + vnfParamMap); + restParametes.setParamMap(vnfParamMap); + } + } else { + restParametes.setRawData(bodyParam == null ? null : bodyParam.toString()); + } + return getRestRes(methodNames, path, restParametes); + } + + + /** + * encapsulate the java reflect exception + * + * @param methodName + * Restful's method + * @param objects + * method param array + * @return + */ + private static boolean isAnyNull(Object... objects) { + for(int i = 0; i < objects.length; i++) { + if(objects[i] == null) { + return true; + } + } + return false; + + } + + private static Class<?>[] formArray(Object[] objects) { + Class<?>[] vnfClasses = new Class[objects.length]; + for(int i = 0; i < objects.length; i++) { + vnfClasses[i] = objects[i].getClass(); + } + return vnfClasses; + + } + + /** + * Helps to invoke methods on Restful. + * <br> + * + * @param methodName + * @param objects + * @return + * @since NFVO 0.5 + */ + public static RestfulResponse getRestRes(String methodName, Object... objects) { + Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP); + try { + if(isAnyNull(objects, rest)) { + return null; + } + + Class<?>[] vnfClasses = formArray(objects); + + if(methodName.startsWith("async")) { + vnfClasses[vnfClasses.length - 1] = RestfulAsyncCallback.class; + } + + Class<?> rtType = methodName.startsWith("async") ? void.class : RestfulResponse.class; + MethodType mt = MethodType.methodType(rtType, vnfClasses); + Object reuslt = MethodHandles.lookup().findVirtual(rest.getClass(), methodName, mt).bindTo(rest) + .invokeWithArguments(objects); + if(reuslt != null) { + return (RestfulResponse)reuslt; + } + LOG.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.", methodName); + return null; + } catch(ReflectiveOperationException e) { + LOG.error("function=getRestRes, msg=error occurs, e={}.", e); + } catch(ServiceException e) { + + LOG.error("function=getRestRes, msg=ServiceException occurs, status={}", e.getHttpCode()); + LOG.error("function=getRestRes, msg=ServiceException occurs, reason={}.", e.getCause().getMessage()); + LOG.error("function=getRestRes, msg=ServiceException occurs, e={}.", e); + RestfulResponse response = new RestfulResponse(); + response.setStatus(e.getHttpCode()); + response.setResponseJson(e.getCause().getMessage()); + return response; + + } catch(Throwable e) { //NOSONAR + try { + throw (VnfmException)new VnfmException().initCause(e.getCause()); + } catch(VnfmException e1) { + LOG.error("function=getRestRes, msg=VnfmException occurs, e={},e1={}.", e1, e); + } + + } + return null; + } + + /** + * Send request to manager. + * @param path + * @param methodName + * @param paraJson + * @return + */ + public static JSONObject sendReqToApp(String path, String methodName, JSONObject paraJson) { + JSONObject retJson = new JSONObject(); + retJson.put("retCode", Constant.REST_FAIL); + String abPath = null; + String vnfmId = null; + if(paraJson != null && paraJson.containsKey("vnfmInfo")) { + JSONObject vnfmObj = paraJson.getJSONObject("vnfmInfo"); + vnfmId = vnfmObj.getString("id"); + } else { + abPath = path; + } + LOG.warn("function=sendReqToApp, msg=url to send to app is: " + abPath); + + RestfulResponse restfulResponse = VNFRestfulUtil.getRestResByDefault(path, methodName, paraJson); + if(restfulResponse == null || abPath == null) { + LOG.error("function=sendReqToApp, msg=data from app is null"); + retJson.put("data", "get null result"); + } else if(restfulResponse.getStatus() == Constant.HTTP_OK) { + JSONObject object = JSONObject.fromObject(restfulResponse.getResponseContent()); + if(!abPath.contains("vnfdmgr/v1")) { + LOG.warn("function=sendReqToApp, msg=result from app is: " + object.toString()); + } + if(object.getInt("retCode") == Constant.REST_SUCCESS) { + retJson.put("retCode", Constant.REST_SUCCESS); + retJson.put("data", withVnfmIdSuffix(vnfmId, object.get("data"))); + return retJson; + } else { + retJson.put("retCode", Constant.REST_FAIL); + if(object.containsKey("msg")) { + retJson.put("data", object.getString("msg")); + return retJson; + } else { + return object; + } + } + } else { + LOG.error("function=sendReqToApp, msg=status from app is: " + restfulResponse.getStatus()); + LOG.error("function=sendReqToApp, msg=result from app is: " + restfulResponse.getResponseContent()); + retJson.put("data", "send to app get error status: " + restfulResponse.getStatus()); + } + return retJson; + } + + /** + * append suffix to result with vnfmId + * + * @param vnfmId + * @param dataJson + * @return + */ + private static Object withVnfmIdSuffix(String vnfmId, Object dataJson) { + Object result = new Object(); + if(vnfmId == null) { + return dataJson; + } + + if(dataJson instanceof JSONObject) { + JSONObject jsonObject = (JSONObject)dataJson; + jsonObject.put("vnfmId", vnfmId); + result = jsonObject; + } else if(dataJson instanceof JSONArray) { + JSONArray dataArray = (JSONArray)dataJson; + JSONArray resultArray = new JSONArray(); + + for(Object obj : dataArray) { + JSONObject jsonObject = JSONObject.fromObject(obj); + jsonObject.put("vnfmId", vnfmId); + resultArray.add(jsonObject); + } + result = resultArray; + } + return result; + } + + /** + * Make HTTP method calls<br> + * + * @param paramsMap Map<String, String> + * @param params String + * @param domainTokens String + * @param isNfvoApp Boolean + * @return + * @since NFVO 0.5 + */ + public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params, String domainTokens, + boolean isNfvoApp) { + String utilUrl = paramsMap.get("url"); + String utilMethodType = paramsMap.get("methodType"); + String utilPath = paramsMap.get("path"); + String authMode = paramsMap.get("authMode"); + + RestfulResponse rsp = null; + Restful rest = null; + String sslOptionFile = ""; + try { + String restClientFile = "restclient.json"; + + if(isNfvoApp) { + sslOptionFile = "ssl.nfvo.properties"; + } else { + sslOptionFile = "ssl.vcmm.properties"; + } + + LOG.warn("function=getRemoteResponse,AuthenticationMode=" + authMode); + + rest = HttpRestfulHelp.getRestInstance(sslOptionFile, restClientFile); + + RestfulOptions opt = new RestfulOptions(); + String[] strs = utilPath.split("(http(s)?://)|:"); + + opt.setHost(strs[1]); + opt.setPort(Integer.parseInt(strs[2])); + + RestfulParametes restfulParametes = new RestfulParametes(); + Map<String, String> headerMap = new HashMap<>(3); + headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION); + headerMap.put(Constant.HEADER_AUTH_TOKEN, domainTokens); + restfulParametes.setHeaderMap(headerMap); + restfulParametes.setRawData(params); + + if(rest != null) { + if(TYPE_GET.equalsIgnoreCase(utilMethodType)) { + rsp = rest.get(utilUrl, restfulParametes, opt); + } else if(TYPE_POST.equalsIgnoreCase(utilMethodType)) { + rsp = rest.post(utilUrl, restfulParametes, opt); + } else if(TYPE_PUT.equalsIgnoreCase(utilMethodType)) { + rsp = rest.put(utilUrl, restfulParametes, opt); + } else if(TYPE_DEL.equalsIgnoreCase(utilMethodType)) { + rsp = rest.delete(utilUrl, restfulParametes, opt); + } + } + } catch(ServiceException e) { + LOG.error("function=restfulResponse, get restful response catch exception {}", e); + } + return rsp; + } + + /** + * Make HTTP method calls + * <br> + * + * @param paramsMap + * @param params + * @return + * @since NFVO 0.5 + */ + public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + if(null == paramsMap){ + return null; + } + String url = paramsMap.get("url"); + String methodType = paramsMap.get("methodType"); + + RestfulResponse rsp = null; + Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP); + try { + + RestfulParametes restfulParametes = new RestfulParametes(); + Map<String, String> headerMap = new HashMap<>(3); + headerMap.put(CONTENT_TYPE, APPLICATION); + restfulParametes.setHeaderMap(headerMap); + restfulParametes.setRawData(params); + + if (rest != null) { + if (TYPE_GET.equalsIgnoreCase(methodType)) { + rsp = rest.get(url, restfulParametes); + } else if (TYPE_POST.equalsIgnoreCase(methodType)) { + rsp = rest.post(url, restfulParametes); + } else if (TYPE_PUT.equalsIgnoreCase(methodType)) { + rsp = rest.put(url, restfulParametes); + } else if (TYPE_DEL.equalsIgnoreCase(methodType)) { + rsp = rest.delete(url, restfulParametes); + } + } + } catch (ServiceException e) { + LOG.error("function=getRemoteResponse, get restful response catch exception {}", e); + } + return rsp; + } + + + /** + * Helps to make the parameter map. + * <br> + * + * @param url + * @param methodType + * @param path + * @param authMode + * @return + * @since NFVO 0.5 + */ + public static Map<String, String> generateParamsMap(String url, String methodType, String path, String authMode) { + Map<String, String> utilParamsMap = new HashMap<>(6); + utilParamsMap.put("url", url); + utilParamsMap.put("methodType", methodType); + utilParamsMap.put("path", path); + utilParamsMap.put("authMode", authMode); + return utilParamsMap; + } + + /** + * Helps to make the parameter map.<br> + * + * @param url + * @param methodType + * @param path + * @return + * @since NFVO 0.5 + */ + public static Map<String, String> generateParamsMap(String url, String methodType, String path) { + Map<String, String> paramsMap = new HashMap<>(6); + paramsMap.put("url", url); + paramsMap.put("methodType", methodType); + paramsMap.put("path", path); + paramsMap.put("authMode", "Certificate"); + return paramsMap; + } + + /** + * Cookup the response + * <br> + * + * @param vnfmInfo + * @param vnfmId + * @return + * @since NFVO 0.5 + */ + public static JSONObject getResultToVnfm(JSONObject vnfmInfo, String vnfmId) { + JSONObject retJson = new JSONObject(); + retJson.put("retCode", Constant.REST_FAIL); + if(vnfmInfo == null) { + LOG.error("function=getResultToVnfm, msg=data from vnfm is null"); + retJson.put("data", "get null result"); + return retJson; + } + + if(vnfmInfo.getInt("retCode") == Constant.REST_SUCCESS) { + retJson.put("retCode", Constant.REST_SUCCESS); + retJson.put("data", withVnfmIdSuffix(vnfmId, vnfmInfo.get("data"))); + return retJson; + } else { + retJson.put("retCode", Constant.REST_FAIL); + if(vnfmInfo.containsKey("msg")) { + retJson.put("data", vnfmInfo.getString("msg")); + return retJson; + } else { + return vnfmInfo; + } + } + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/servicetoken/VnfmRestfulUtil.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/servicetoken/VnfmRestfulUtil.java new file mode 100644 index 00000000..7f177773 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/common/servicetoken/VnfmRestfulUtil.java @@ -0,0 +1,404 @@ +/* + * Copyright 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.nfvo.vnfmadapter.common.servicetoken; + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +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.RestfulFactory; +import org.openo.baseservice.roa.util.restclient.RestfulOptions; +import org.openo.baseservice.roa.util.restclient.RestfulParametes; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.common.VnfmException; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; + +/** + * VNFM Restful Utility. + * .</br> + * + * @author + * @version NFVO 0.5 Sep 10, 2016 + */ +public final class VnfmRestfulUtil { + + public static final String TYPE_GET = "get"; + + public static final String TYPE_ADD = "add"; + + public static final String TYPE_POST = "post"; + + public static final String TYPE_PUT = "put"; + + public static final String TYPE_DEL = "delete"; + + public static final int ERROR_STATUS_CODE = -1; + + private static final Logger LOG = LoggerFactory.getLogger(VnfmRestfulUtil.class); + + private VnfmRestfulUtil() { + + } + + /** + * within our module, we support a default method to invoke + * + * @param path + * rest service url + * @param methodNames + * [post, delete, put, get, asyncPost, asyncDelete, asyncPut, + * asyncGet] + * @param bodyParam + * rest body msg + * @return + */ + @SuppressWarnings("unchecked") + public static RestfulResponse getRestResByDefault(String path, String methodNames, JSONObject bodyParam) { + RestfulParametes restParametes = new RestfulParametes(); + Map<String, String> headerMap = new HashMap<>(2); + headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION); + restParametes.setHeaderMap(headerMap); + + if(Constant.GET.equals(methodNames) || Constant.DELETE.equals(methodNames)) { + if(null != bodyParam) { + Map<String, String> vnfParamsMap = new HashMap<>(Constant.DEFAULT_COLLECTION_SIZE); + if(path.contains("?")) { + String[] vnfUtlList = path.split("\\?"); + String[] vnfParams = vnfUtlList[1].split("&"); + int paramsSize = vnfParams.length; + + for(int i = 0; i < paramsSize; i++) { + vnfParamsMap.put(vnfParams[i].split("=")[0], vnfParams[i].split("=")[1]); + } + } + + String vnfParamKey = null; + Iterator<String> nameItr = bodyParam.keys(); + while(nameItr.hasNext()) { + vnfParamKey = nameItr.next(); + vnfParamsMap.put(vnfParamKey, bodyParam.get(vnfParamKey).toString()); + + } + LOG.warn("method is GET or DEL,and paramsMap = " + vnfParamsMap); + restParametes.setParamMap(vnfParamsMap); + } + } else { + restParametes.setRawData(bodyParam == null ? null : bodyParam.toString()); + } + return getRestRes(methodNames, path, restParametes); + } + + /** + * encapsulate the java reflect exception + * + * @param methodName + * Restful's method + * @param objects + * method param array + * @return + */ + private static boolean isAnyNull(Object... objects) { + for(int i = 0; i < objects.length; i++) { + if(objects[i] == null) { + return true; + } + } + return false; + + } + + private static Class<?>[] formArray(Object[] objects) { + Class<?>[] vnfClasses = new Class[objects.length]; + for(int i = 0; i < objects.length; i++) { + vnfClasses[i] = objects[i].getClass(); + } + return vnfClasses; + + } + + /** + * Helps to invoke http methods Restful + * <br> + * + * @param methodName String + * @param objects String + * @return + * @since NFVO 0.5 + */ + public static RestfulResponse getRestRes(String methodName, Object... objects) { + Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP); + try { + if(isAnyNull(objects, rest)) { + return null; + } + + Class<?>[] vnfClasses = formArray(objects); + + if(methodName.startsWith("async")) { + vnfClasses[vnfClasses.length - 1] = RestfulAsyncCallback.class; + } + + Class<?> rtType = methodName.startsWith("async") ? void.class : RestfulResponse.class; + MethodType mt = MethodType.methodType(rtType, vnfClasses); + Object reuslt = MethodHandles.lookup().findVirtual(rest.getClass(), methodName, mt).bindTo(rest) + .invokeWithArguments(objects); + if(reuslt != null) { + return (RestfulResponse)reuslt; + } + LOG.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.", methodName); + return null; + } catch(ReflectiveOperationException e) { + LOG.error("function=getRestRes, msg=error occurs, e={}.", e); + } catch(ServiceException e) { + + LOG.error("function=getRestRes, msg=ServiceException occurs, status={}", e.getHttpCode()); + LOG.error("function=getRestRes, msg=ServiceException occurs, reason={}.", e.getCause().getMessage()); + LOG.error("function=getRestRes, msg=ServiceException occurs, e={}.", e); + RestfulResponse response = new RestfulResponse(); + response.setStatus(e.getHttpCode()); + response.setResponseJson(e.getCause().getMessage()); + return response; + + } catch(Throwable e) { //NOSONAR + try { + throw (VnfmException)new VnfmException().initCause(e.getCause()); + } catch(VnfmException e1) { + LOG.error("function=getRestRes, msg=VnfmException occurs, e={},e1={}.", e1, e); + } + + } + return null; + } + + /** + * Helps to send Request to vnfm. + * <br> + * + * @param path String + * @param methodName String + * @param paraJson JSONObject + * @return + * @since NFVO 0.5 + */ + public static JSONObject sendReqToApp(String path, String methodName, JSONObject paraJson) { + JSONObject retJson = new JSONObject(); + retJson.put("retCode", Constant.REST_FAIL); + String abPath = null; + String vnfmId = null; + if(paraJson != null && paraJson.containsKey("vnfmInfo")) { + JSONObject vnfmObj = paraJson.getJSONObject("vnfmInfo"); + vnfmId = vnfmObj.getString("id"); + } else { + abPath = path; + } + LOG.warn("function=sendReqToApp, msg=url to send to app is: " + abPath); + + RestfulResponse restfulResponse = VnfmRestfulUtil.getRestResByDefault(path, methodName, paraJson); + if(restfulResponse == null || abPath == null) { + LOG.error("function=sendReqToApp, msg=data from app is null"); + retJson.put("data", "get null result"); + } else if(restfulResponse.getStatus() == Constant.HTTP_OK) { + JSONObject object = JSONObject.fromObject(restfulResponse.getResponseContent()); + if(!abPath.contains("vnfdmgr/v1")) { + LOG.warn("function=sendReqToApp, msg=result from app is: " + object.toString()); + } + if(object.getInt("retCode") == Constant.REST_SUCCESS) { + retJson.put("retCode", Constant.REST_SUCCESS); + retJson.put("data", withVnfmIdSuffix(vnfmId, object.get("data"))); + return retJson; + } else { + retJson.put("retCode", Constant.REST_FAIL); + if(object.containsKey("msg")) { + retJson.put("data", object.getString("msg")); + return retJson; + } else { + return object; + } + } + } else { + LOG.error("function=sendReqToApp, msg=status from app is: " + restfulResponse.getStatus()); + LOG.error("function=sendReqToApp, msg=result from app is: " + restfulResponse.getResponseContent()); + retJson.put("data", "send to app get error status: " + restfulResponse.getStatus()); + } + return retJson; + } + + /** + * append suffix to result with vnfmId + * + * @param vnfmId + * @param dataJson + * @return + */ + private static Object withVnfmIdSuffix(String vnfmId, Object dataJson) { + Object result = new Object(); + if(vnfmId == null) { + return dataJson; + } + + if(dataJson instanceof JSONObject) { + JSONObject jsonObject = (JSONObject)dataJson; + jsonObject.put("vnfmId", vnfmId); + result = jsonObject; + } else if(dataJson instanceof JSONArray) { + JSONArray dataArray = (JSONArray)dataJson; + JSONArray resultArray = new JSONArray(); + + for(Object obj : dataArray) { + JSONObject jsonObject = JSONObject.fromObject(obj); + jsonObject.put("vnfmId", vnfmId); + resultArray.add(jsonObject); + } + result = resultArray; + } + return result; + } + + /** + * Make request and get HTTP response + * <br> + * + * @param paramsMap Map<String, String> + * @param params String + * @param domainTokens String + * @param isNfvoApp boolean + * @return + * @since NFVO 0.5 + */ + public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params, String domainTokens, + boolean isNfvoApp) { + String utilUrl = paramsMap.get("url"); + String utilMethodType = paramsMap.get("methodType"); + String utilPath = paramsMap.get("path"); + String authMode = paramsMap.get("authMode"); + + RestfulResponse rsp = null; + Restful rest = null; + String sslOptionFile = ""; + try { + String restClientFile = "restclient.json"; + + if(isNfvoApp) { + sslOptionFile = "ssl.nfvo.properties"; + } else { + sslOptionFile = "ssl.vcmm.properties"; + } + + LOG.warn("function=getRemoteResponse,AuthenticationMode=" + authMode); + + rest = HttpRestfulHelp.getRestInstance(sslOptionFile, restClientFile); + + RestfulOptions opt = new RestfulOptions(); + String[] strs = utilPath.split("(http(s)?://)|:"); + + opt.setHost(strs[1]); + opt.setPort(Integer.parseInt(strs[2])); + + RestfulParametes restfulParametes = new RestfulParametes(); + Map<String, String> headerMap = new HashMap<>(3); + headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION); + headerMap.put(Constant.HEADER_AUTH_TOKEN, domainTokens); + restfulParametes.setHeaderMap(headerMap); + restfulParametes.setRawData(params); + + if(rest != null) { + if(TYPE_GET.equalsIgnoreCase(utilMethodType)) { + rsp = rest.get(utilUrl, restfulParametes, opt); + } else if(TYPE_POST.equalsIgnoreCase(utilMethodType)) { + rsp = rest.post(utilUrl, restfulParametes, opt); + } else if(TYPE_PUT.equalsIgnoreCase(utilMethodType)) { + rsp = rest.put(utilUrl, restfulParametes, opt); + } else if(TYPE_DEL.equalsIgnoreCase(utilMethodType)) { + rsp = rest.delete(utilUrl, restfulParametes, opt); + } + } + } catch(ServiceException e) { + LOG.error("function=restfulResponse, get restful response catch exception {}", e); + } + return rsp; + } + + /** + * Make request and get HTTP response + * <br> + * + * @param url String + * @param methodType String + * @param params String + * @return + * @since NFVO 0.5 + */ + public static RestfulResponse getRemoteResponse(String url, String methodType, String params) { + RestfulResponse rsp = null; + Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP); + try { + + RestfulParametes restfulParametes = new RestfulParametes(); + Map<String, String> headerMap = new HashMap<>(3); + headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION); + restfulParametes.setHeaderMap(headerMap); + if(params != null) { + restfulParametes.setRawData(params); + } + + if(rest != null) { + if(TYPE_GET.equalsIgnoreCase(methodType)) { + rsp = rest.get(url, restfulParametes); + } else if(TYPE_POST.equalsIgnoreCase(methodType)) { + rsp = rest.post(url, restfulParametes); + } else if(TYPE_PUT.equalsIgnoreCase(methodType)) { + rsp = rest.put(url, restfulParametes); + } else if(TYPE_DEL.equalsIgnoreCase(methodType)) { + rsp = rest.delete(url, restfulParametes); + } + } + } catch(ServiceException e) { + LOG.error("function=getRemoteResponse, get restful response catch exception {}", e); + } + return rsp; + } + + /** + * Make Params map<br> + * + * @param url String + * @param methodType String + * @param path String + * @param authMode String + * @return + * @since NFVO 0.5 + */ + public static Map<String, String> generateParamsMap(String url, String methodType, String path, String authMode) { + Map<String, String> utilParamsMap = new HashMap<>(6); + utilParamsMap.put("url", url); + utilParamsMap.put("methodType", methodType); + utilParamsMap.put("path", path); + utilParamsMap.put("authMode", authMode); + return utilParamsMap; + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/activator/RoaVnfmService2DriverMgr.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/activator/RoaVnfmService2DriverMgr.java new file mode 100644 index 00000000..4b67d2a0 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/activator/RoaVnfmService2DriverMgr.java @@ -0,0 +1,58 @@ +/* + * Copyright 2017 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.nfvo.vnfmadapter.service.activator; + +import org.openo.nfvo.vnfmadapter.service.api.internalsvc.inf.IVnfmAdapter2DriverMgrService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Jan 23, 2017 + */ +public class RoaVnfmService2DriverMgr implements DestructionAwareBeanPostProcessor { + + private static final Logger LOG = LoggerFactory.getLogger(RoaVnfmService2DriverMgr.class); + + @Override + public Object postProcessAfterInitialization(Object bean, String name) throws BeansException { + if(bean instanceof IVnfmAdapter2DriverMgrService) { + IVnfmAdapter2DriverMgrService vnfmAdapterSvc = (IVnfmAdapter2DriverMgrService)bean; + vnfmAdapterSvc.register(); + LOG.info("Successfully Registered to Driver Manager!", RoaVnfmService2DriverMgr.class); + } + + return bean; + } + + @Override + public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException { + return bean; + } + + @Override + public void postProcessBeforeDestruction(Object bean, String name) throws BeansException { + // post processing + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/activator/RoaVnfmServicePostProcessor.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/activator/RoaVnfmServicePostProcessor.java new file mode 100644 index 00000000..b84b42f2 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/activator/RoaVnfmServicePostProcessor.java @@ -0,0 +1,58 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.activator; + +import org.openo.nfvo.vnfmadapter.service.api.internalsvc.inf.IVnfmAdapterMgrService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor; + +/** + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 31, 2016 + */ +public class RoaVnfmServicePostProcessor implements DestructionAwareBeanPostProcessor { + + private static final Logger LOG = LoggerFactory.getLogger(RoaVnfmServicePostProcessor.class); + + @Override + public Object postProcessAfterInitialization(Object bean, String name) throws BeansException { + if(bean instanceof IVnfmAdapterMgrService) { + IVnfmAdapterMgrService vnfmAdapterSvc = (IVnfmAdapterMgrService)bean; + vnfmAdapterSvc.register(); + LOG.info("Successfully Registered to Microservice BUS!", RoaVnfmServicePostProcessor.class); + } + + return bean; + } + + @Override + public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException { + return bean; + } + + @Override + public void postProcessBeforeDestruction(Object bean, String name) throws BeansException { + //post processing + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/AdapterResourceManager.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/AdapterResourceManager.java new file mode 100644 index 00000000..8c731efd --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/AdapterResourceManager.java @@ -0,0 +1,644 @@ +/* + * Copyright 2016-2017 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.nfvo.vnfmadapter.service.adapter.impl; + +import java.io.BufferedInputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.httpclient.HttpStatus; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.baseservice.util.impl.SystemEnvVariablesFactory; +import org.openo.nfvo.vnfmadapter.common.DownloadCsarManager; +import org.openo.nfvo.vnfmadapter.common.VnfmException; +import org.openo.nfvo.vnfmadapter.common.servicetoken.VNFRestfulUtil; +import org.openo.nfvo.vnfmadapter.service.adapter.inf.IResourceManager; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.constant.UrlConstant; +import org.openo.nfvo.vnfmadapter.service.csm.connect.ConnectMgrVnfm; +import org.openo.nfvo.vnfmadapter.service.csm.connect.HttpRequests; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONArray; +import net.sf.json.JSONException; +import net.sf.json.JSONObject; + +/** + * Resource Manager adapter class. + * .</br> + * + * @author + * @version NFVO 0.5 Sep 13, 2016 + */ +public class AdapterResourceManager implements IResourceManager { + + private static final Logger LOG = LoggerFactory.getLogger(AdapterResourceManager.class); + + @Override + public JSONObject uploadVNFPackage(JSONObject vnfpkg, Map<String, String> paramsMap) { + JSONObject resultObj = new JSONObject(); + JSONObject csarTempObj = new JSONObject(); + + try { + // if upper layer do not provide vnfpackage info,then get the + // vnfpackage info from JSON file. + if(vnfpkg == null || vnfpkg.isEmpty()) { + String vnfPkgInfo = readVfnPkgInfoFromJson(); + vnfpkg = JSONObject.fromObject(vnfPkgInfo); // NOSONAR + } + } catch(IOException e) { + LOG.error("function=uploadVNFPackage", e); + } + + // check if parameters are null. + if(paramsMap == null || paramsMap.isEmpty()) { + resultObj.put("reason", "csarid and vnfmid are null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + + String csarid = paramsMap.get("csarid"); + String vnfmid = paramsMap.get("vnfmid"); + String vnfdid = ""; + String vnfDescriptorId = paramsMap.get("vnfDescriptorId"); + if(null == csarid || "".equals(csarid)) { + resultObj.put("reason", "csarid is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + if(null == vnfmid || "".equals(vnfmid)) { + resultObj.put("reason", "vnfmid is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + + // obtain CSAR package info + JSONObject csarobj = getVnfmCsarInfo(csarid); + String downloadUri = ""; + if(Integer.valueOf(csarobj.get("retCode").toString()) == Constant.HTTP_OK) { + LOG.info("get CSAR info successful.", csarobj.get("retCode")); + downloadUri = csarobj.getString("downloadUri"); + } else { + LOG.error("get CSAR info fail.", csarobj.get("retCode")); + resultObj.put("reason", csarobj.get("reason").toString()); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + + csarTempObj = vnfpkg.getJSONObject("template"); + String csarfilepath = csarTempObj.getString("csar_file_path"); + String csarfilename = csarTempObj.getString("csar_file_name"); + + // download csar package and save in location. + JSONObject downloadObject = + downloadCsar(downloadUri, csarfilepath + System.getProperty("file.separator") + csarfilename); + + if(Integer.valueOf(downloadObject.get("retCode").toString()) != Constant.REST_SUCCESS) { + LOG.error("download CSAR fail.", downloadObject.get("retCode")); + resultObj.put("reason", downloadObject.get("reason").toString()); + resultObj.put("retCode", downloadObject.get("retCode").toString()); + return resultObj; + } + LOG.info("download CSAR successful.", downloadObject.get("retCode")); + + // unzip csar package to location. + JSONObject unzipObject = + unzipCSAR(csarfilepath + System.getProperty("file.separator") + csarfilename, csarfilepath); + + if(Integer.valueOf(unzipObject.get("retCode").toString()) != Constant.REST_SUCCESS) { + LOG.error("unzip CSAR fail.", unzipObject.get("retCode")); + resultObj.put("reason", unzipObject.get("reason").toString()); + resultObj.put("retCode", unzipObject.get("retCode").toString()); + return resultObj; + } + LOG.info("unzip CSAR successful.", unzipObject.get("retCode")); + + Map<String, String> vnfmMap = new HashMap<>(); + vnfmMap.put("url", String.format(UrlConstant.REST_VNFMINFO_GET, vnfmid)); + vnfmMap.put("methodType", Constant.GET); + + // get VNFM connection info + JSONObject vnfmObject = getVnfmConnInfo(vnfmMap); + if(Integer.valueOf(vnfmObject.get("retCode").toString()) != Constant.HTTP_OK) { + LOG.error("get Vnfm Connection Info fail.", vnfmObject.get("retCode")); + resultObj.put("reason", vnfmObject.get("reason").toString()); + resultObj.put("retCode", vnfmObject.get("retCode").toString()); + return resultObj; + } + LOG.info("get Vnfm Connection Info successful.", vnfmObject.get("retCode")); + + String vnfmUrl = vnfmObject.getString("url"); + String userName = vnfmObject.getString("userName"); + String password = vnfmObject.getString("password"); + + // build VNFM connection and get token + ConnectMgrVnfm mgrVcmm = new ConnectMgrVnfm(); + + JSONObject connObject = new JSONObject(); + connObject.put("url", vnfmUrl); + connObject.put("userName", userName); + connObject.put("password", password); + if(Constant.HTTP_OK != mgrVcmm.connect(vnfmObject, Constant.CERTIFICATE)) { + LOG.error("get Access Session fail."); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "connect fail."); + return resultObj; + } + LOG.info("get Access Session successful."); + String connToken = mgrVcmm.getAccessSession(); + + // get vim_id + JSONObject cloudObject = getAllCloud(vnfmUrl, connToken); + String vimId = ""; + + if(!cloudObject.isEmpty() && cloudObject.get(Constant.RETCODE).equals(HttpStatus.SC_OK)) { + LOG.info("get all cloud successful.", cloudObject.get(Constant.RETCODE)); + vimId = cloudObject.getString("vim_id"); + } else { + LOG.error("get all cloud fail.", cloudObject.get(Constant.RETCODE)); + return cloudObject; + } + + // upload VNF package + csarTempObj.put("vim_id", vimId); + vnfpkg.put("template", csarTempObj); + + JSONObject uploadPkgObject = upload(vnfpkg, vnfmUrl, connToken); + LOG.info("uploadPkgObject:" + uploadPkgObject); + if(vnfdid == null || "".equals(vnfdid.trim())) { + JSONObject vnfdConf = readVnfdIdInfoFromJson(); + LOG.info("vnfdConf=" + vnfdConf); + if(vnfdConf.containsKey(vnfDescriptorId)) { + vnfdid = vnfdConf.getString(vnfDescriptorId); + } + } + LOG.info("set vnfdId=" + vnfdid); + + // get vnfd version + String vnfdVersion = ""; + + JSONObject vnfdVerObject = + getVnfdVersion(vnfmUrl, String.format(UrlConstant.URL_VNFDINFO_GET, vnfdid), connToken); + LOG.info("vnfdVerObject:" + vnfdVerObject); + if(!vnfdVerObject.isEmpty() && vnfdVerObject.get(Constant.RETCODE).equals(HttpStatus.SC_OK)) { + LOG.info("get vnfd version successful.", vnfdVerObject.get(Constant.RETCODE)); + JSONArray verArr = vnfdVerObject.getJSONArray("templates"); + JSONObject verTmpObj = verArr.getJSONObject(0); + + vnfdVersion = verTmpObj.getString("vnfdVersion"); + } else { + LOG.error("get vnfd version fail.", vnfdVerObject.get(Constant.RETCODE)); + return vnfdVerObject; + } + + // get vnfd plan info + String planName = ""; + String planId = ""; + + JSONObject vnfdPlanInfo = getVNFDPlanInfo(vnfmUrl, vnfdid, connToken); + LOG.info("vnfdPlanInfo:" + vnfdPlanInfo); + JSONObject inputsObj = new JSONObject(); + if(!vnfdPlanInfo.isEmpty() && vnfdPlanInfo.get(Constant.RETCODE).equals(HttpStatus.SC_OK)) { + LOG.info("get vnfd plan info successful.", vnfdPlanInfo.get(Constant.RETCODE)); + JSONObject planTmpObj = vnfdPlanInfo.getJSONObject("template"); + String templateName = planTmpObj.getString("template_name").trim(); + JSONArray topoTmpObj = planTmpObj.getJSONArray("topology_template"); + + JSONObject planObj = topoTmpObj.getJSONObject(0); + if("VNFD_vUGW".equals(templateName)) { + for(int i = 0; i < topoTmpObj.size(); i++) { + String name = topoTmpObj.getJSONObject(i).getString("plan_name").trim(); + if("Normal_E9K".equals(name)) { + planObj = topoTmpObj.getJSONObject(i); + } + } + } + + planName = planObj.getString("plan_name"); + planId = planObj.getString("plan_id"); + if(planObj.containsKey("inputs")) { + JSONArray inputs = planObj.getJSONArray("inputs"); + for(int i = 0; i < inputs.size(); i++) { + JSONObject obj = inputs.getJSONObject(i); + obj.put("value", obj.getString("default")); + } + inputsObj.put("inputs", inputs); + inputsObj.put("External_network", new JSONArray()); + } + } else { + LOG.error("get vnfd plan info fail.", vnfdPlanInfo.get(Constant.RETCODE)); + return vnfdPlanInfo; + } + + // return values + resultObj.put("retCode", Constant.HTTP_OK); + resultObj.put("vnfdId", vnfdid); + resultObj.put("vnfdVersion", vnfdVersion); + resultObj.put("planName", planName); + resultObj.put("planId", planId); + resultObj.put("parameters", inputsObj); + LOG.info("resultObj:" + resultObj.toString()); + + return resultObj; + } + + private JSONObject sendRequest(Map<String, String> paramsMap) { + JSONObject resultObj = new JSONObject(); + RestfulResponse rsp = VNFRestfulUtil.getRemoteResponse(paramsMap, ""); + if(null == rsp) { + LOG.error("function=sendRequest, RestfulResponse is null"); + resultObj.put("reason", "RestfulResponse is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + String resultCreate = rsp.getResponseContent(); + + if(rsp.getStatus() == Constant.HTTP_OK) { + LOG.warn("function=sendRequest, msg= status={}, result={}.", rsp.getStatus(), resultCreate); + resultObj = JSONObject.fromObject(resultCreate); + resultObj.put("retCode", Constant.HTTP_OK); + return resultObj; + } else { + LOG.error("function=sendRequest, msg=ESR return fail,status={}, result={}.", rsp.getStatus(), resultCreate); + resultObj.put("reason", "ESR return fail."); + } + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + + @Override + public JSONObject getVnfmCsarInfo(String csarid) { + JSONObject resultObj = new JSONObject(); + + if(null == csarid || "".equals(csarid)) { + resultObj.put("reason", "csarid is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + + Map<String, String> paramsMap = new HashMap<String, String>(); + + paramsMap.put("url", String.format(UrlConstant.REST_CSARINFO_GET, csarid)); + paramsMap.put("methodType", Constant.GET); + + return this.sendRequest(paramsMap); + } + + @Override + public JSONObject downloadCsar(String url, String filePath) { + JSONObject resultObj = new JSONObject(); + + if(url == null || "".equals(url)) { + resultObj.put("reason", "url is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + if(filePath == null || "".equals(filePath)) { + resultObj.put("reason", "downloadUrl filePath is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + + String status = DownloadCsarManager.download(url, filePath); + + if(Constant.DOWNLOADCSAR_SUCCESS.equals(status)) { + resultObj.put("reason", "download csar file successfully."); + resultObj.put("retCode", Constant.REST_SUCCESS); + } else { + resultObj.put("reason", "download csar file failed."); + resultObj.put("retCode", Constant.REST_FAIL); + } + return resultObj; + } + + @Override + public JSONObject getAllCloud(String url, String conntoken) { + JSONObject resultObj = new JSONObject(); + JSONArray resArray = new JSONArray(); + + if(url == null || url.equals("")) { + url = "http://127.0.0.1:31943"; + } + + // get vim_id + HttpMethod httpMethodCloud = null; + try { + httpMethodCloud = + new HttpRequests.Builder(Constant.CERTIFICATE).setUrl(url.trim(), UrlConstant.URL_ALLCLOUD_NEW_GET) + .addHeader(Constant.HEADER_AUTH_TOKEN, conntoken).setParams("").get().execute(); + + int statusCode = httpMethodCloud.getStatusCode(); + + String result = httpMethodCloud.getResponseBodyAsString(); + LOG.info(result); + if(statusCode == HttpStatus.SC_OK) { + JSONObject vimInfo = JSONObject.fromObject(result); + resArray = vimInfo.getJSONArray("vim_info"); + resultObj = resArray.getJSONObject(0); + resultObj.put(Constant.RETCODE, statusCode); + } else { + LOG.error("uploadVNFPackage get allcloud failed, code:" + statusCode + " re:" + result); + resultObj.put(Constant.RETCODE, statusCode); + resultObj.put("reason", "get allcloud failed. code:" + statusCode + " re:" + result); + return resultObj; + } + } catch(JSONException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage get allcloud JSONException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "get allcloud failed and JSONException." + e.getMessage()); + return resultObj; + } catch(VnfmException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage get allcloud VnfmException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "get allcloud failed and VnfmException." + e.getMessage()); + return resultObj; + } catch(IOException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage get allcloud IOException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "get allcloud failed and IOException." + e.getMessage()); + return resultObj; + } + return resultObj; + } + + /** + * Upload vnfpackage<br> + * + * @param vnfpackage + * @param vnfmurl + * @param conntoken + * @return + * @since NFVO 0.5 + */ + public JSONObject upload(JSONObject vnfpackage, String vnfmurl, String conntoken) { + JSONObject resultObj = new JSONObject(); + HttpMethod httpMethodVnf = null; + + try { + httpMethodVnf = new HttpRequests.Builder(Constant.CERTIFICATE) + .setUrl(vnfmurl.trim(), UrlConstant.URL_VNFPACKAGE_POST).setParams(vnfpackage.toString()) + .addHeader(Constant.HEADER_AUTH_TOKEN, conntoken).post().execute(); + + int statusCodeUp = httpMethodVnf.getStatusCode(); + + String resultUp = httpMethodVnf.getResponseBodyAsString(); + + if(statusCodeUp == HttpStatus.SC_CREATED || statusCodeUp == HttpStatus.SC_OK) { + LOG.info("uploadVNFPackage upload VNF package successful, code:" + statusCodeUp + " re:" + resultUp); + resultObj = JSONObject.fromObject(resultUp); + resultObj.put(Constant.RETCODE, statusCodeUp); + } else { + LOG.error("uploadVNFPackage upload VNF package failed, code:" + statusCodeUp + " re:" + resultUp); + resultObj.put(Constant.RETCODE, statusCodeUp); + resultObj.put("data", "upload VNF package failed, code:" + statusCodeUp + " re:" + resultUp); + return resultObj; + } + } catch(JSONException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage upload VNF package JSONException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "upload VNF package failed and JSONException." + e.getMessage()); + return resultObj; + } catch(VnfmException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage upload VNF package VnfmException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "upload VNF package failed and VnfmException." + e.getMessage()); + return resultObj; + } catch(IOException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage upload VNF package IOException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "upload VNF package failed and IOException." + e.getMessage()); + return resultObj; + } + return resultObj; + } + + /** + * Find vnfd version.<br> + * + * @param prefixUrl + * @param serviceUrl + * @return + * @since NFVO 0.5 + */ + public JSONObject getVnfdVersion(String prefixUrl, String serviceUrl, String conntoken) { + JSONObject resultObj = new JSONObject(); + HttpMethod httpMethodVnfd = null; + try { + httpMethodVnfd = new HttpRequests.Builder(Constant.CERTIFICATE).setUrl(prefixUrl.trim(), serviceUrl) + .setParams("").addHeader(Constant.HEADER_AUTH_TOKEN, conntoken).get().execute(); + + int statusCodeVnfd = httpMethodVnfd.getStatusCode(); + + String resultVnfd = httpMethodVnfd.getResponseBodyAsString(); + LOG.info("getVnfdVersion result:" + resultVnfd); + if(statusCodeVnfd == HttpStatus.SC_OK) { + resultObj = JSONObject.fromObject(resultVnfd); + resultObj.put(Constant.RETCODE, statusCodeVnfd); + } else { + LOG.error("uploadVNFPackage vnfd version failed, code:" + statusCodeVnfd + " re:" + resultVnfd); + resultObj.put(Constant.RETCODE, statusCodeVnfd); + resultObj.put("data", "get vnfd version failed, code:" + statusCodeVnfd + " re:" + resultVnfd); + return resultObj; + } + } catch(JSONException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage get vnfd version JSONException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "get vnfd version failed and JSONException." + e.getMessage()); + return resultObj; + } catch(VnfmException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage get vnfd version VnfmException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "get vnfd version failed and VnfmException." + e.getMessage()); + return resultObj; + } catch(IOException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage get vnfd version IOException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "get vnfd version failed and IOException." + e.getMessage()); + return resultObj; + } + return resultObj; + } + + /** + * Find VNFM connection information.<br> + * + * @param paramsMap + * @return + * @since NFVO 0.5 + */ + public JSONObject getVnfmConnInfo(Map<String, String> paramsMap) { + return this.sendRequest(paramsMap); + } + + @Override + public JSONObject getVNFDPlanInfo(String url, String vnfdid, String conntoken) { + JSONObject resultObj = new JSONObject(); + + HttpMethod httpMethodPlan = null; + try { + httpMethodPlan = new HttpRequests.Builder(Constant.CERTIFICATE) + .setUrl(url.trim(), String.format(UrlConstant.URL_VNFDPLANINFO_GET, vnfdid)).setParams("") + .addHeader(Constant.HEADER_AUTH_TOKEN, conntoken).get().execute(); + + int statusCode = httpMethodPlan.getStatusCode(); + + String result = httpMethodPlan.getResponseBodyAsString(); + LOG.info("getVNFDPlanInfo result=" + result); + if(statusCode == HttpStatus.SC_OK) { + resultObj = JSONObject.fromObject(result); + resultObj.put(Constant.RETCODE, statusCode); + } else { + LOG.error("uploadVNFPackage get VNFDPlanInfo failed, code:" + statusCode + " re:" + result); + resultObj.put(Constant.RETCODE, statusCode); + resultObj.put("reason", "get VNFDPlanInfo failed. code:" + statusCode + " re:" + result); + return resultObj; + } + } catch(JSONException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage get VNFDPlanInfo JSONException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "get VNFDPlanInfo failed and JSONException." + e.getMessage()); + return resultObj; + } catch(VnfmException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage get VNFDPlanInfo VnfmException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "get VNFDPlanInfo failed and VnfmException." + e.getMessage()); + return resultObj; + } catch(IOException e) { + LOG.error("function=uploadVNFPackage, msg=uploadVNFPackage get VNFDPlanInfo IOException e={}.", e); + resultObj.put(Constant.RETCODE, Constant.HTTP_INNERERROR); + resultObj.put("reason", "get VNFDPlanInfo failed and IOException." + e.getMessage()); + return resultObj; + } + return resultObj; + } + + /** + * Get VNF package information.<br> + * + * @return + * @throws IOException + * @since NFVO 0.5 + */ + public static String readVfnPkgInfoFromJson() throws IOException { + InputStream ins = null; + BufferedInputStream bins = null; + String fileContent = ""; + + String fileName = SystemEnvVariablesFactory.getInstance().getAppRoot() + System.getProperty("file.separator") + + "etc" + System.getProperty("file.separator") + "vnfpkginfo" + System.getProperty("file.separator") + + Constant.VNFPKGINFO; + + try { + ins = new FileInputStream(fileName); + bins = new BufferedInputStream(ins); + + byte[] contentByte = new byte[ins.available()]; + int num = bins.read(contentByte); + + if(num > 0) { + fileContent = new String(contentByte); + } + } catch(FileNotFoundException e) { + LOG.error(fileName + "is not found!", e); + } finally { + if(ins != null) { + ins.close(); + } + if(bins != null) { + bins.close(); + } + } + + return fileContent; + } + + private static JSONObject readVnfdIdInfoFromJson() { + JSONObject jsonObject = new JSONObject(); + InputStream ins = null; + BufferedInputStream bins = null; + String fileContent = ""; + + String fileName = SystemEnvVariablesFactory.getInstance().getAppRoot() + System.getProperty("file.separator") + + "etc" + System.getProperty("file.separator") + "vnfpkginfo" + System.getProperty("file.separator") + + "vnfd_ids.json"; + + try { + ins = new FileInputStream(fileName); + bins = new BufferedInputStream(ins); + + byte[] contentByte = new byte[ins.available()]; + int num = bins.read(contentByte); + + if(num > 0) { + fileContent = new String(contentByte); + } + if(fileContent != null) { + jsonObject = JSONObject.fromObject(fileContent).getJSONObject("vnfdIds"); + } + if(ins != null) { + ins.close(); + } + if(bins != null) { + bins.close(); + } + } catch(Exception e) { + LOG.error(fileName + " read error!", e); + } finally { + + } + + return jsonObject; + } + + /* + * unzip CSAR packge + * @param fileName filePath + * @return + */ + public JSONObject unzipCSAR(String fileName, String filePath) { + JSONObject resultObj = new JSONObject(); + + if(fileName == null || "".equals(fileName)) { + resultObj.put("reason", "fileName is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + if(filePath == null || "".equals(filePath)) { + resultObj.put("reason", "unzipCSAR filePath is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + + int status = DownloadCsarManager.unzipCSAR(fileName, filePath); + + if(Constant.UNZIP_SUCCESS == status) { + resultObj.put("reason", "unzip csar file successfully."); + resultObj.put("retCode", Constant.REST_SUCCESS); + } else { + resultObj.put("reason", "unzip csar file failed."); + resultObj.put("retCode", Constant.REST_FAIL); + } + return resultObj; + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/Driver2MSBManager.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/Driver2MSBManager.java new file mode 100644 index 00000000..bd8d3c17 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/Driver2MSBManager.java @@ -0,0 +1,110 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.adapter.impl; + +import java.util.Map; + +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.common.servicetoken.VNFRestfulUtil; +import org.openo.nfvo.vnfmadapter.service.adapter.inf.IDriver2MSBManager; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * + * Driver to MSB Manager Class.<br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 29, 2016 + */ +public class Driver2MSBManager implements IDriver2MSBManager { + + private static final Logger LOG = LoggerFactory.getLogger(Driver2MSBManager.class); + + @Override + public JSONObject registerDriver(Map<String, String> paramsMap, JSONObject driverInfo) { + JSONObject resultObj = new JSONObject(); + + RestfulResponse rsp = VNFRestfulUtil.getRemoteResponse(paramsMap, driverInfo.toString()); + if(null == rsp) { + LOG.error("function=registerDriver, RestfulResponse is null"); + resultObj.put("reason", "RestfulResponse is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + String resultCreate = rsp.getResponseContent(); + + if(rsp.getStatus() == Constant.HTTP_CREATED) { + LOG.warn("function=registerDriver, msg= status={}, result={}.", rsp.getStatus(), resultCreate); + resultObj = JSONObject.fromObject(resultCreate); + resultObj.put("retCode", Constant.HTTP_CREATED); + return resultObj; + } else if(rsp.getStatus() == Constant.HTTP_INVALID_PARAMETERS) { + LOG.error("function=registerDriver, msg=MSB return fail,invalid parameters,status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "MSB return fail,invalid parameters."); + } else if(rsp.getStatus() == Constant.HTTP_INNERERROR) { + LOG.error("function=registerDriver, msg=MSB return fail,internal system error,status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "MSB return fail,internal system error."); + } + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + + @Override + public JSONObject unregisterDriver(Map<String, String> paramsMap) { + JSONObject resultObj = new JSONObject(); + + RestfulResponse rsp = VNFRestfulUtil.getRemoteResponse(paramsMap, ""); + if(null == rsp) { + LOG.error("function=unregisterDriver, RestfulResponse is null"); + resultObj.put("reason", "RestfulResponse is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + String resultCreate = rsp.getResponseContent(); + + if(rsp.getStatus() == Constant.HTTP_NOCONTENT) { + LOG.warn("function=unregisterDriver, msg= status={}, result={}.", rsp.getStatus(), resultCreate); + resultObj = JSONObject.fromObject(resultCreate); + resultObj.put("retCode", Constant.HTTP_NOCONTENT); + return resultObj; + } else if(rsp.getStatus() == Constant.HTTP_NOTFOUND) { + LOG.error( + "function=unregisterDriver, msg=MSB return fail,can't find the service instance.status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "MSB return fail,can't find the service instance."); + } else if(rsp.getStatus() == Constant.HTTP_INVALID_PARAMETERS) { + LOG.error("function=unregisterDriver, msg=MSB return fail,invalid parameters,status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "MSB return fail,invalid parameters."); + } else if(rsp.getStatus() == Constant.HTTP_INNERERROR) { + LOG.error("function=unregisterDriver, msg=MSB return fail,internal system error,status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "MSB return fail,internal system error."); + } + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/VnfmAdapter2DriverManager.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/VnfmAdapter2DriverManager.java new file mode 100644 index 00000000..211536f9 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/VnfmAdapter2DriverManager.java @@ -0,0 +1,111 @@ +/* + * Copyright 2017 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.nfvo.vnfmadapter.service.adapter.impl; + +import java.util.Map; + +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.common.servicetoken.VNFRestfulUtil; +import org.openo.nfvo.vnfmadapter.service.adapter.inf.IVnfmAdapter2DriverManager; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Jan 23, 2017 + */ +public class VnfmAdapter2DriverManager implements IVnfmAdapter2DriverManager { + + private static final Logger LOG = LoggerFactory.getLogger(VnfmAdapter2DriverManager.class); + + @Override + public JSONObject registerDriver(Map<String, String> paramsMap, JSONObject driverInfo) { + JSONObject resultObj = new JSONObject(); + + RestfulResponse rsp = VNFRestfulUtil.getRemoteResponse(paramsMap, driverInfo.toString()); + if(null == rsp) { + LOG.error("function=registerDriver, RestfulResponse is null"); + resultObj.put("reason", "RestfulResponse is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + String resultCreate = rsp.getResponseContent(); + + if(rsp.getStatus() == Constant.HTTP_CREATED) { + LOG.warn("function=registerDriver, msg= status={}, result={}.", rsp.getStatus(), resultCreate); + resultObj.put("retCode", Constant.HTTP_CREATED); + return resultObj; + } else if(rsp.getStatus() == Constant.HTTP_INVALID_PARAMETERS) { + LOG.error("function=registerDriver, msg=DriverManager return fail,invalid parameters,status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "DriverManager return fail,invalid parameters."); + } else if(rsp.getStatus() == Constant.HTTP_INNERERROR) { + LOG.error( + "function=registerDriver, msg=DriverManager return fail,internal system error,status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "DriverManager return fail,internal system error."); + } + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + + @Override + public JSONObject unregisterDriver(Map<String, String> paramsMap) { + JSONObject resultObj = new JSONObject(); + + RestfulResponse rsp = VNFRestfulUtil.getRemoteResponse(paramsMap, ""); + if(null == rsp) { + LOG.error("function=unregisterDriver, RestfulResponse is null"); + resultObj.put("reason", "RestfulResponse is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + String resultCreate = rsp.getResponseContent(); + + if(rsp.getStatus() == Constant.HTTP_NOCONTENT) { + LOG.warn("function=unregisterDriver, msg= status={}, result={}.", rsp.getStatus(), resultCreate); + resultObj = JSONObject.fromObject(resultCreate); + resultObj.put("retCode", Constant.HTTP_NOCONTENT); + return resultObj; + } else if(rsp.getStatus() == Constant.HTTP_NOTFOUND) { + LOG.error( + "function=unregisterDriver, msg=DriverManager return fail,can't find the service instance.status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "DriverManager return fail,can't find the service instance."); + } else if(rsp.getStatus() == Constant.HTTP_INVALID_PARAMETERS) { + LOG.error( + "function=unregisterDriver, msg=DriverManager return fail,invalid parameters,status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "DriverManager return fail,invalid parameters."); + } else if(rsp.getStatus() == Constant.HTTP_INNERERROR) { + LOG.error( + "function=unregisterDriver, msg=DriverManager return fail,internal system error,status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "DriverManager return fail,internal system error."); + } + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/inf/IDriver2MSBManager.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/inf/IDriver2MSBManager.java new file mode 100644 index 00000000..6d2ff9aa --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/inf/IDriver2MSBManager.java @@ -0,0 +1,55 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.adapter.inf; + +import java.util.Map; + +import net.sf.json.JSONObject; + +/** + * + * IDriver to MSB Manager Class.<br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 29, 2016 + */ +public interface IDriver2MSBManager { + + /** + * + * Method to Register Driver.<br/> + * + * @param paramsMap + * @param driverInfo + * @return + * @since NFVO 0.5 + */ + JSONObject registerDriver(Map<String, String> paramsMap, JSONObject driverInfo); + + /** + * + * Method to Unregister Driver.<br/> + * + * @param paramsMap + * @return + * @since NFVO 0.5 + */ + JSONObject unregisterDriver(Map<String, String> paramsMap); + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/inf/IResourceManager.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/inf/IResourceManager.java new file mode 100644 index 00000000..8eb7cbf1 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/inf/IResourceManager.java @@ -0,0 +1,79 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.adapter.inf; + +import java.util.Map; + +import net.sf.json.JSONObject; + +/** + * Resource Manager interface.</br> + * + * @author + * @version NFVO 0.5 Sep 13, 2016 + */ +public interface IResourceManager { + + /** + * Get VNFM CSAR information<br> + * + * @param csarid String + * @return + * @since NFVO 0.5 + */ + JSONObject getVnfmCsarInfo(String csarid); + + /** + * Download CSAR.<br> + * + * @param url String + * @param filePath String + * @return + * @since NFVO 0.5 + */ + JSONObject downloadCsar(String url,String filePath); + + /** + * Get all clouds<br> + * + * @param url String + * @return + * @since NFVO 0.5 + */ + JSONObject getAllCloud(String url,String connToken); + + + /** + * get VNFD Plan Info.<br> + * + * @param url String + * @param vnfdid String + * @return + * @since NFVO 0.5 + */ + JSONObject getVNFDPlanInfo(String url, String vnfdid, String conntoken); + + /** + * Upload VNF package.<br> + * + * @param vnfpkg JSONObject + * @param paramsMap Map<String, String> + * @return + * @since NFVO 0.5 + */ + JSONObject uploadVNFPackage(JSONObject vnfpkg, Map<String, String> paramsMap); +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/inf/IVnfmAdapter2DriverManager.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/inf/IVnfmAdapter2DriverManager.java new file mode 100644 index 00000000..10b42429 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/adapter/inf/IVnfmAdapter2DriverManager.java @@ -0,0 +1,52 @@ +/* + * Copyright 2017 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.nfvo.vnfmadapter.service.adapter.inf; + +import java.util.Map; + +import net.sf.json.JSONObject; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Jan 23, 2017 + */ +public interface IVnfmAdapter2DriverManager { + + /** + * Method to Register Driver.<br/> + * + * @param paramsMap + * @param driverInfo + * @return + * @since NFVO 0.5 + */ + JSONObject registerDriver(Map<String, String> paramsMap, JSONObject driverInfo); + + /** + * Method to Unregister Driver.<br/> + * + * @param paramsMap + * @return + * @since NFVO 0.5 + */ + JSONObject unregisterDriver(Map<String, String> paramsMap); + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/impl/VnfmAdapter2DriverMgrService.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/impl/VnfmAdapter2DriverMgrService.java new file mode 100644 index 00000000..42cef38a --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/impl/VnfmAdapter2DriverMgrService.java @@ -0,0 +1,183 @@ +/* + * Copyright 2017 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.nfvo.vnfmadapter.service.api.internalsvc.impl; + +import java.io.BufferedInputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Executors; + +import org.openo.baseservice.util.impl.SystemEnvVariablesFactory; +import org.openo.nfvo.vnfmadapter.service.adapter.impl.VnfmAdapter2DriverManager; +import org.openo.nfvo.vnfmadapter.service.adapter.inf.IVnfmAdapter2DriverManager; +import org.openo.nfvo.vnfmadapter.service.api.internalsvc.inf.IVnfmAdapter2DriverMgrService; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.constant.UrlConstant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Jan 23, 2017 + */ +public class VnfmAdapter2DriverMgrService implements IVnfmAdapter2DriverMgrService { + + private static final Logger LOG = LoggerFactory.getLogger(VnfmAdapter2DriverMgrService.class); + + public static final String VNFMADAPTER2DRIVERMGR = "vnfmadapter2drivermgr.json"; + + @Override + public void register() { + // set URL and mothedtype + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", UrlConstant.REST_DRIVERMGR_REGISTER); + paramsMap.put("methodType", Constant.POST); + + // get vim adapter info and raise registration + try { + String adapterInfo = readVnfmAdapterInfoFromJson(); + if(!"".equals(adapterInfo)) { + JSONObject adapterObject = JSONObject.fromObject(adapterInfo); + RegisterVnfm2DriverMgrThread vnfmAdapterThread = + new RegisterVnfm2DriverMgrThread(paramsMap, adapterObject); + Executors.newSingleThreadExecutor().submit(vnfmAdapterThread); + } else { + LOG.error("vnfmadapter2drivermgr info is null,please check!"); + } + + } catch(IOException e) { + LOG.error("Failed to read vnfmadapter2drivermgr info! " + e.getMessage(), e); + } + + } + + /** + * Retrieve VIM driver information. + * + * @return + * @throws IOException + */ + public static String readVnfmAdapterInfoFromJson() throws IOException { + InputStream ins = null; + BufferedInputStream bins = null; + String fileContent = ""; + + String fileName = SystemEnvVariablesFactory.getInstance().getAppRoot() + System.getProperty("file.separator") + + "etc" + System.getProperty("file.separator") + "adapterInfo" + System.getProperty("file.separator") + + VNFMADAPTER2DRIVERMGR; + + try { + ins = new FileInputStream(fileName); + bins = new BufferedInputStream(ins); + + byte[] contentByte = new byte[ins.available()]; + int num = bins.read(contentByte); + + if(num > 0) { + fileContent = new String(contentByte); + } + } catch(FileNotFoundException e) { + LOG.error(fileName + "is not found!", e); + } finally { + if(ins != null) { + ins.close(); + } + if(bins != null) { + bins.close(); + } + } + + return fileContent; + } + + private static class RegisterVnfm2DriverMgrThread implements Runnable { + + // Thread lock Object + private final Object lockObject = new Object(); + + private IVnfmAdapter2DriverManager adapter2DriverMgr = new VnfmAdapter2DriverManager(); + + // url and mothedtype + private Map<String, String> paramsMap; + + // driver body + private JSONObject adapterInfo; + + public RegisterVnfm2DriverMgrThread(Map<String, String> paramsMap, JSONObject adapterInfo) { + this.paramsMap = paramsMap; + this.adapterInfo = adapterInfo; + } + + @Override + public void run() { + LOG.info("start register vnfmadapter to Driver Manager", RegisterVnfm2DriverMgrThread.class); + + if(paramsMap == null || adapterInfo == null) { + LOG.error("parameter is null,please check!", RegisterVnfm2DriverMgrThread.class); + return; + } + + // catch Runtime Exception + try { + sendRequest(paramsMap, adapterInfo); + } catch(RuntimeException e) { + LOG.error(e.getMessage(), e); + } + + } + + private void sendRequest(Map<String, String> paramsMap, JSONObject driverInfo) { + JSONObject resultObj = adapter2DriverMgr.registerDriver(paramsMap, driverInfo); + + if(Integer.valueOf(resultObj.get("retCode").toString()) == Constant.HTTP_CREATED) { + LOG.info("Vnfmadapter has now Successfully Registered to the Driver Manager!"); + } else { + LOG.error("Vnfmadapter failed to Register to the Driver Manager! Reason:" + + resultObj.get("reason").toString() + " retCode:" + resultObj.get("retCode").toString()); + + // if registration fails,wait one minute and try again + try { + synchronized(lockObject) { + lockObject.wait(Constant.REPEAT_REG_TIME); + } + } catch(InterruptedException e) { + LOG.error(e.getMessage(), e); + } + + sendRequest(this.paramsMap, this.adapterInfo); + } + + } + + } + + @Override + public void unregister() { + // unregister + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/impl/VnfmAdapterMgrService.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/impl/VnfmAdapterMgrService.java new file mode 100644 index 00000000..8991218a --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/impl/VnfmAdapterMgrService.java @@ -0,0 +1,181 @@ +/* + * Copyright 2016-2017 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.nfvo.vnfmadapter.service.api.internalsvc.impl; + +import java.io.BufferedInputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Executors; + +import org.openo.baseservice.util.impl.SystemEnvVariablesFactory; +import org.openo.nfvo.vnfmadapter.service.adapter.impl.Driver2MSBManager; +import org.openo.nfvo.vnfmadapter.service.adapter.inf.IDriver2MSBManager; +import org.openo.nfvo.vnfmadapter.service.api.internalsvc.inf.IVnfmAdapterMgrService; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.constant.UrlConstant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 31, 2016 + */ +public class VnfmAdapterMgrService implements IVnfmAdapterMgrService { + + private static final Logger LOG = LoggerFactory.getLogger(VnfmAdapterMgrService.class); + + public static final String VNFMADAPTERINFO = "vnfmadapterinfo.json"; + + @Override + public void register() { + // set BUS URL and mothedtype + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", UrlConstant.REST_MSB_REGISTER); + paramsMap.put("methodType", Constant.POST); + + // get vim adapter info and raise registration + try { + String adapterInfo = readVnfmAdapterInfoFromJson(); + if(!"".equals(adapterInfo)) { + JSONObject adapterObject = JSONObject.fromObject(adapterInfo); + RegisterVnfmAdapterThread vnfmAdapterThread = new RegisterVnfmAdapterThread(paramsMap, adapterObject); + Executors.newSingleThreadExecutor().submit(vnfmAdapterThread); + } else { + LOG.error("VnfmAdapter info is null,please check!"); + } + + } catch(IOException e) { + LOG.error("Failed to read VnfmAdapter info! " + e.getMessage(), e); + } + + } + + /** + * Retrieve VIM driver information. + * @return + * @throws IOException + */ + public String readVnfmAdapterInfoFromJson() throws IOException { + InputStream ins = null; + BufferedInputStream bins = null; + String fileContent = ""; + + String fileName = SystemEnvVariablesFactory.getInstance().getAppRoot() + System.getProperty("file.separator") + + "etc" + System.getProperty("file.separator") + "adapterInfo" + System.getProperty("file.separator") + + VNFMADAPTERINFO; + + try { + ins = new FileInputStream(fileName); + bins = new BufferedInputStream(ins); + + byte[] contentByte = new byte[ins.available()]; + int num = bins.read(contentByte); + + if(num > 0) { + fileContent = new String(contentByte); + } + } catch(FileNotFoundException e) { + LOG.error(fileName + "is not found!", e); + } finally { + if (ins != null) { + ins.close(); + } + if (bins != null) { + bins.close(); + } + } + + return fileContent; + } + + private static class RegisterVnfmAdapterThread implements Runnable { + + // Thread lock Object + private final Object lockObject = new Object(); + + private IDriver2MSBManager adapter2MSBMgr = new Driver2MSBManager(); + + // url and mothedtype + private Map<String, String> paramsMap; + + // driver body + private JSONObject adapterInfo; + + public RegisterVnfmAdapterThread(Map<String, String> paramsMap, JSONObject adapterInfo) { + this.paramsMap = paramsMap; + this.adapterInfo = adapterInfo; + } + + @Override + public void run() { + LOG.info("start register vnfmadapter", RegisterVnfmAdapterThread.class); + + if(paramsMap == null || adapterInfo == null) { + LOG.error("parameter is null,please check!", RegisterVnfmAdapterThread.class); + return; + } + + // catch Runtime Exception + try { + sendRequest(paramsMap, adapterInfo); + } catch(RuntimeException e) { + LOG.error(e.getMessage(), e); + } + + } + + private void sendRequest(Map<String, String> paramsMap, JSONObject driverInfo) { + JSONObject resultObj = adapter2MSBMgr.registerDriver(paramsMap, driverInfo); + + if(Integer.valueOf(resultObj.get("retCode").toString()) == Constant.HTTP_CREATED) { + LOG.info("Vnfmadapter has now Successfully Registered to the Microservice BUS!"); + } else { + LOG.error("Vnfmadapter failed to Register to the Microservice BUS! Reason:" + + resultObj.get("reason").toString() + " retCode:" + resultObj.get("retCode").toString()); + + // if registration fails,wait one minute and try again + try { + synchronized(lockObject) { + lockObject.wait(Constant.REPEAT_REG_TIME); + } + } catch(InterruptedException e) { + LOG.error(e.getMessage(), e); + } + + sendRequest(this.paramsMap, this.adapterInfo); + } + + } + + } + + @Override + public void unregister() { + //unregister + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/inf/IVnfmAdapter2DriverMgrService.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/inf/IVnfmAdapter2DriverMgrService.java new file mode 100644 index 00000000..7aa7277d --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/inf/IVnfmAdapter2DriverMgrService.java @@ -0,0 +1,42 @@ +/* + * Copyright 2017 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.nfvo.vnfmadapter.service.api.internalsvc.inf; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Jan 23, 2017 + */ +public interface IVnfmAdapter2DriverMgrService { + + /** + * VimAdapter register interface.<br> + * + * @since NFVO 0.5 + */ + void register(); + + /** + * VimAdapter unregister interface.<br> + * + * @since NFVO 0.5 + */ + void unregister(); +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/inf/IVnfmAdapterMgrService.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/inf/IVnfmAdapterMgrService.java new file mode 100644 index 00000000..c25a2de1 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/api/internalsvc/inf/IVnfmAdapterMgrService.java @@ -0,0 +1,39 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.api.internalsvc.inf; + +/** + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 31, 2016 + */ +public interface IVnfmAdapterMgrService { + + /** + * VimAdapter register interface. + */ + void register(); + + /** + * VimAdapter unregister interface. + */ + void unregister(); + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/constant/Constant.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/constant/Constant.java new file mode 100644 index 00000000..e20375f5 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/constant/Constant.java @@ -0,0 +1,136 @@ +/* + * Copyright 2016-2017 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.nfvo.vnfmadapter.service.constant; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/** + * Provide constant value + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 3, 2016 + */ +public class Constant { + + public static final String POST = "post"; + + public static final String PUT = "put"; + + public static final String DELETE = "delete"; + + public static final String GET = "get"; + + public static final String ASYNCPOST = "asyncPost"; + + public static final String ASYNCGET = "asyncGet"; + + public static final String ASYNCPUT = "asyncPut"; + + public static final String ASYNCDELETE = "asyncDelete"; + + public static final String ENCODEING = "utf-8"; + + public static final String COOKIE = "Cookie"; + + public static final String ACCESSSESSION = "accessSession"; + + public static final String CONTENT_TYPE = "Content-Type"; + + public static final String APPLICATION = "application/json"; + + public static final String HEADER_SUBJECT_TOKEN = "X-Subject-Token"; + + public static final String HEADER_AUTH_TOKEN = "accessSession"; + + public static final String DOWNLOADCSAR_SUCCESS = "Success"; + + public static final int UNZIP_SUCCESS = 0; + + public static final int UNZIP_FAIL = -1; + + public static final String DOWNLOADCSAR_FAIL = "FAIL"; + + public static final int HTTP_OK = 200; + + public static final int HTTP_CREATED = 201; + + public static final int HTTP_ACCEPTED = 202; + + public static final int HTTP_NOCONTENT = 204; + + public static final int HTTP_BAD_REQUEST = 400; + + public static final int HTTP_UNAUTHORIZED = 401; + + public static final int HTTP_NOTFOUND = 404; + + public static final int HTTP_NOT_ACCEPTABLE = 406; + + public static final int HTTP_CONFLICT = 409; + + public static final int HTTP_INVALID_PARAMETERS = 415; + + public static final int HTTP_INNERERROR = 500; + + public static final List<String> AUTHLIST = Collections.unmodifiableList(Arrays.asList(Constant.ANONYMOUS, Constant.CERTIFICATE)); + + public static final int INTERNAL_EXCEPTION = 600; + + public static final int REPEAT_REG_TIME = 60 * 1000; + + public static final int MIN_PWD_LENGTH = 6; + + public static final int MAX_PWD_LENGTH = 160; + + public static final int MIN_URL_LENGTH = 7; + + public static final int MAX_VNFM_NAME_LENGTH = 64; + + public static final int MIN_VNFM_NAME_LENGTH = 1; + + public static final int MAX_URL_LENGTH = 256; + + public static final int REST_SUCCESS = 1; + + public static final int DEFAULT_COLLECTION_SIZE = 10; + + public static final int REST_FAIL = -1; + + public static final String ROARAND = "?roarand=%s"; + + public static final String ANONYMOUS = "Anonymous"; + + public static final String CERTIFICATE = "Certificate"; + + public static final String RETCODE = "retCode"; + + public static final String STATUS = "status"; + + public static final String VNFPKGINFO="vnfpkginfo.json"; + + public static final int ERROR_STATUS_CODE = -1; + + public static final String COLON=":"; + + private Constant() { + //private constructor + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/constant/ParamConstants.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/constant/ParamConstants.java new file mode 100644 index 00000000..5d897871 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/constant/ParamConstants.java @@ -0,0 +1,123 @@ +/* + * Copyright 2016-2017 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.nfvo.vnfmadapter.service.constant; + +/** + * + * @author + * + * @version NFVO 0.5 Sep 6, 2016 + */ +public class ParamConstants { + + public static final String GET_TOKENS_V1 = "{\"grantType\": \"password\", \"userName\": \"%s\",\"value\": \"%s\"}"; + + public static final String GET_TOKENS_V2 = + "{\"auth\":{\"identity\": {\"methods\": [\"password\"],\"password\": {\"user\": {\"name\": \"%s\",\"password\": \"%s\"}}}}}"; + + public static final String GET_IAM_TOKENS = + "{\"auth\": {\"identity\": {\"methods\": [\"password\"],\"password\": {\"user\": {\"name\": " + + "\"%s\",\"password\": \"%s\",\"domain\": {\"name\": \"%s\"}}}},\"scope\": {\"domain\": {\"name\": \"%s\"}}}}"; + + public static final String GET_TOKEN_SUC_RESP = + "{\"token\": {\"methods\": [\"password\"],\"expires_at\": \"\",\"user\": {\"id\": \"%s\"," + + "\"name\": \"%s\"},\"roa_rand\": \"%s\"}}"; + + public static final String GET_TOKEN_FAIL_RESP = "{\"Information\": \"%s\"}"; + + public static final String REST_3RD_CONNECTION = "/rest/plat/smapp/v1/oauth/token"; + + public static final String REST_3RD_DISCONNECT = "/rest/plat/smapp/v1/sessions?roarand=%s"; + + public static final String REST_3RD_HANDSHAKE = "/rest/plat/ssm/v1/sessions/verify"; + + public static final String IAM_AUTH = "/v3/auth/tokens"; + + public static final String CSM_AUTH_CONNECT = "/v2/auth/tokens"; + + public static final String CSM_AUTH_DISCONNECT = "/v2/auth/tokens/%s/%s"; + + public static final String CSM_AUTH_HANDSHAKE = "/v2/nfvo/shakehand?roattr=status"; + + public static final String VNFMMED = "/rest/vnfmmed/"; + + public static final String CONNECTMGR_CONNECT = "/connectmgr/v1/connect"; + + public static final String CONNECTMGR_DISCONNECT = "/connectmgr/v1/disconnect"; + + public static final String CONNECTMGR_HANDSHAKE = "/connectmgr/v1/handshake"; + + public static final String CREATE_VNF_PERF = "/staticsmgr/v1/vnfperformance"; + + public static final String VNFMGR_INSTANCE = "/vnfmgr/v1/instances"; + + + public static final String VNFD_FLAVOR = "/vnfdmgr/v1/flavor"; + + public static final String UPDATE_RESOURCE = "/rest/v1/resmanage/resuse/updateres"; + + public static final String VNF_QUERY = "/resmgr/v1/vnfs"; + + public static final String VMS_QUERY = "/resmgr/v1/vms"; + + public static final String VNFMGR_VNFKPI = "/staticsmgr/v1/vnfkpi"; + + public static final String RES_VNF = "/rest/v1/resmanage/vappvm"; + + public static final String NOTIFY_VNF_PERF = "/rest/v1/resmanage/vappvm"; + + public static final String PARAM_MODULE = "VnfmDriver"; + + public static final String GET_ALL_SOS = "/rest/sodriver/v1/sos"; + + public static final String OPERATION_LOG_PATH = "/rest/plat/audit/v1/logs"; + + public static final String SYSTEM_LOG_PATH = "/rest/plat/audit/v1/systemlogs"; + + public static final String SECURITY_LOG_PATH = "/rest/plat/audit/v1/seculogs"; + + public static final String GET_VNFM_VNF = "/rest/v1/resmanage/vapps?vnfmId=%s"; + + public static final String GET_RES_NET = "/rest/v1/resmanage/virtualnetworks?id=%s"; + + public static final String GET_JOB_STATUS = "/vnfmgr/v1/jobs/%s"; + + public static final String VNF_INSTANCE = "/v2/vapps/instances"; + + public static final String VNF_INSTANCE_DEL = "/v2/vapps/instances/%s"; + + public static final String VNF_INSTANCE_GET = "/v2/vapps/instances/%s"; + + public static final String VNF_SCALE = "/v2/vapps/instances/%s/scale"; + + public static final String VNF_GET_VMINFO = "/v2/vapps/instances/%s/vm"; + + + public static final String MSB_REGISTER_URL = "/openoapi/microservices/v1/services"; + + public static final String MSB_UNREGISTER_URL = "/openoapi/microservices/v1/services/hw-vnfm"; + + public static final String ESR_GET_VNFM_URL = "/openoapi/extsys/v1/vnfms/%s"; + + public static final String ESR_GET_VNFMS_URL = "/openoapi/extsys/v1/vnfms"; + + public static final String GRANT_RES_URL = "/openoapi/resmgr/v1/resource/grant"; + + private ParamConstants() { + // private contstructor + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/constant/UrlConstant.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/constant/UrlConstant.java new file mode 100644 index 00000000..10621271 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/constant/UrlConstant.java @@ -0,0 +1,53 @@ +/* + * Copyright 2016-2017 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.nfvo.vnfmadapter.service.constant; + +/** + * URL constant + * + * @author + * @version NFVO 0.5 Sep 6, 2016 + */ +public class UrlConstant { + + public static final String REST_MSB_REGISTER = "/openoapi/microservices/v1/services"; + + public static final String REST_DRIVERMGR_REGISTER = "/openoapi/drivermgr/v1/drivers"; + + public static final String REST_CSARINFO_GET = "/openoapi/catalog/v1/csars/%s"; + + public static final String REST_VNFMINFO_GET = "/openoapi/extsys/v1/vnfms/%s"; + + public static final String URL_ALLCLOUD_GET = "/rest/vnfm/vnfmvim/v2/computeservice/getAllCloud"; + + public static final String URL_ALLCLOUD_NEW_GET = "/v2/vnfm/vims"; + + public static final String URL_VNFPACKAGE_POST = "/v2/vapps/templates"; + + public static final String URL_VNFDINFO_GET = "/v2/vapps/templates/%s"; + + public static final String URL_VNFDPLANINFO_GET = "/v2/vapps/templates/%s/plans"; + + public static final String PORT_COMMON = "31943"; + + public static final String PORT_UPLOADVNFPKG = "30001"; + + private UrlConstant() { + // Constructor + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/api/ConnectInfo.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/api/ConnectInfo.java new file mode 100644 index 00000000..5c59c013 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/api/ConnectInfo.java @@ -0,0 +1,137 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.csm.api; + +import org.openo.nfvo.vnfmadapter.service.constant.Constant; + +/** + * Connection Information + * .</br> + * + * @author + * @version NFVO 0.5 Sep 14, 2016 + */ +public class ConnectInfo { + + private String url; + + private String userName; + + private String userPwd; + + private String authenticateMode; + + /** + * + * Constructor<br> + * + * @param url + * @since NFVO 0.5 + */ + public ConnectInfo(String url) { + this.url = url == null ? "" : url; + this.authenticateMode = Constant.ANONYMOUS; + } + + /** + * + * Constructor<br> + * + * @param url + * @param userName + * @param userPwd + * @param authenticateMode + * @since NFVO 0.5 + */ + public ConnectInfo(String url, String userName, String userPwd, String authenticateMode) { + this.url = url == null ? "" : url; + this.userName = userName == null ? "" : userName; + this.userPwd = userPwd == null ? "" : userPwd; + this.authenticateMode = authenticateMode == null ? "" : authenticateMode; + } + + public String getUrl() { + return this.url; + } + + public void setUrl(String vnfUrl) { + this.url = vnfUrl; + } + + public String getUserName() { + return this.userName; + } + + public void setUserName(String vnfUserName) { + this.userName = vnfUserName; + } + + public String getUserPwd() { + return this.userPwd; + } + + public void setUserPwd(String vnfUserPwd) { + this.userPwd = vnfUserPwd; + } + + public String getAuthenticateMode() { + return this.authenticateMode; + } + + public void setAuthenticateMode(String vnfAuthenticateMode) { + this.authenticateMode = vnfAuthenticateMode; + } + + @Override + public String toString() { + return "ConnectInfo [AuthenticateMode: " + authenticateMode + ",url=" + url + ", userName=" + userName + ']'; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((url == null) ? 0 : url.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if(this == obj) { + return true; + } + if(obj == null) { + return false; + } + + if(!(obj instanceof ConnectInfo)) { + return false; + } + + if(getClass() != obj.getClass()) { + return false; + } + ConnectInfo other = (ConnectInfo)obj; + if(url == null) { + if(other.url != null) { + return false; + } + } else if(!url.equals(other.url)) { + return false; + } + return true; + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/AbstractSslContext.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/AbstractSslContext.java new file mode 100644 index 00000000..09f0d2cf --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/AbstractSslContext.java @@ -0,0 +1,182 @@ +/* + * Copyright 2016-2017 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.nfvo.vnfmadapter.service.csm.connect; + +import net.sf.json.JSONObject; +import org.apache.http.conn.ssl.SSLContextBuilder; +import org.openo.baseservice.util.impl.SystemEnvVariablesFactory; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpRequest; + +import java.io.*; +import java.security.*; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +import javax.net.ssl.*; + +/** + * SSL context + * .</br> + * + * @author + * @version NFVO 0.5 Sep 14, 2016 + */ +public class AbstractSslContext { + private static final Logger LOG = LoggerFactory.getLogger(AbstractSslContext.class); + protected AbstractSslContext(){ + //constructor + } + + private static SSLContext getSSLContext() throws NoSuchAlgorithmException { + return SSLContext.getInstance("TLSv1.2"); + } + + protected static SSLContext getAnonymousSSLContext() throws GeneralSecurityException { + SSLContext sslContext = getSSLContext(); + sslContext.init(null, new TrustManager[] {new TrustAnyTrustManager()}, new SecureRandom()); + return sslContext; + } + protected static SSLContext getCertificateSSLContext() throws GeneralSecurityException { + SSLContext sslContext = getSSLContext(); + JSONObject sslConf = null; + try { + sslConf = readSSLConfToJson(); + } catch (Exception e) { + LOG.error("readSSLConfToJson error",e); + } + sslContext.init(createKeyManager(sslConf), createTrustManager(sslConf), new SecureRandom()); + return sslContext; + } + + protected static KeyManager[] createKeyManager(JSONObject sslConf) { + KeyManager[] kms = null; + try { + String CERT_STORE="etc/conf/server.p12"; + String CERT_STORE_PASSWORD="Changeme_123"; + String KEY_STORE_TYPE = "PKCS12"; + if(sslConf != null){ + CERT_STORE = sslConf.getString("keyStore"); + CERT_STORE_PASSWORD = sslConf.getString("keyStorePass"); + KEY_STORE_TYPE = sslConf.getString("keyStoreType"); + } + // load jks file + FileInputStream f_certStore=new FileInputStream(CERT_STORE); + KeyStore ks = KeyStore.getInstance(KEY_STORE_TYPE); + ks.load(f_certStore, CERT_STORE_PASSWORD.toCharArray()); + f_certStore.close(); + + // init and create + String alg= KeyManagerFactory.getDefaultAlgorithm(); + KeyManagerFactory kmFact = KeyManagerFactory.getInstance(alg); + kmFact.init(ks, CERT_STORE_PASSWORD.toCharArray()); + + kms = kmFact.getKeyManagers(); + } catch (Exception e) { + LOG.error("create KeyManager fail!",e); + } + return kms; + } + protected static TrustManager[] createTrustManager(JSONObject sslConf){ + TrustManager[] tms = null; + try { + + String TRUST_STORE="etc/conf/trust.jks"; + String TRUST_STORE_PASSWORD="Changeme_123"; + String TRUST_STORE_TYPE = "jks"; + if(sslConf != null){ + TRUST_STORE = sslConf.getString("trustStore"); + TRUST_STORE_PASSWORD = sslConf.getString("trustStorePass"); + TRUST_STORE_TYPE = sslConf.getString("trustStoreType"); + } + FileInputStream f_trustStore=new FileInputStream(TRUST_STORE); + KeyStore ks = KeyStore.getInstance(TRUST_STORE_TYPE); + ks.load(f_trustStore, TRUST_STORE_PASSWORD.toCharArray()); + f_trustStore.close(); + + String alg=TrustManagerFactory.getDefaultAlgorithm(); + TrustManagerFactory tmFact=TrustManagerFactory.getInstance(alg); + tmFact.init(ks); + tms=tmFact.getTrustManagers(); + + } catch (Exception e){ + LOG.error("create TrustManager fail!",e); + } + return tms; + } + + /**readSSLConfToJson + * @return + * @throws IOException + * @since NFVO 0.5 + */ + public static JSONObject readSSLConfToJson() throws IOException { + JSONObject sslJson= null; + InputStream ins = null; + BufferedInputStream bins = null; + String fileContent = ""; + + String fileName = SystemEnvVariablesFactory.getInstance().getAppRoot() + System.getProperty("file.separator") + + "etc" + System.getProperty("file.separator") + "conf" + System.getProperty("file.separator") + + "sslconf.json"; + + try { + ins = new FileInputStream(fileName); + bins = new BufferedInputStream(ins); + + byte[] contentByte = new byte[ins.available()]; + int num = bins.read(contentByte); + + if(num > 0) { + fileContent = new String(contentByte); + } + sslJson = JSONObject.fromObject(fileContent); + } catch(FileNotFoundException e) { + LOG.error(fileName + "is not found!", e); + } catch (Exception e){ + LOG.error("read sslconf file fail.please check if the 'sslconf.json' is exist."); + }finally { + if(ins != null) { + ins.close(); + } + if(bins != null) { + bins.close(); + } + } + + return sslJson; + } + private static class TrustAnyTrustManager implements X509TrustManager { + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[] {}; + } + + @Override + public void checkServerTrusted(X509Certificate[] certs, String authType) { + //NOSONAR + } + + @Override + public void checkClientTrusted(X509Certificate[] certs, String authType) { + //NOSONAR + } + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/ConnectMgrVnfm.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/ConnectMgrVnfm.java new file mode 100644 index 00000000..8775a3d5 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/ConnectMgrVnfm.java @@ -0,0 +1,174 @@ +/* + * Copyright 2016-2017 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.nfvo.vnfmadapter.service.csm.connect; + +import java.io.IOException; + +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.httpclient.HttpStatus; +import org.openo.nfvo.vnfmadapter.common.VnfmException; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.constant.ParamConstants; +import org.openo.nfvo.vnfmadapter.service.csm.api.ConnectInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONException; +import net.sf.json.JSONObject; + +/** + * VNFM connection manager + * .</br> + * + * @author + * @version NFVO 0.5 Sep 14, 2016 + */ +public class ConnectMgrVnfm { + + private static final Logger LOG = LoggerFactory.getLogger(ConnectMgrVnfm.class); + + private String accessSession; + + private String roaRand; + + public String getAccessSession() { + return accessSession; + } + + public void setAccessSession(String accessSession) { + this.accessSession = accessSession; + } + + public String getRoaRand() { + return roaRand; + } + + public void setRoaRand(String roaRand) { + this.roaRand = roaRand; + } + + + /** + * Make connection + * <br> + * + * @param vnfmObj + * @return + * @since NFVO 0.5 + */ + public int connect(JSONObject vnfmObj,String authModel) { + LOG.info("function=connect, msg=enter connect function."); + + ConnectInfo info = new ConnectInfo(vnfmObj.getString("url"), vnfmObj.getString("userName"), + vnfmObj.getString("password"), authModel); + HttpMethod httpMethod = null; + int statusCode = Constant.INTERNAL_EXCEPTION; + + try { + httpMethod = new HttpRequests.Builder(info.getAuthenticateMode()) + .setUrl(info.getUrl(), ParamConstants.CSM_AUTH_CONNECT) + .setParams(String.format(ParamConstants.GET_TOKENS_V2, info.getUserName(), info.getUserPwd())) + .post().execute(); + statusCode = httpMethod.getStatusCode(); + + String result = httpMethod.getResponseBodyAsString(); + LOG.info("connect result:"+result); + if(statusCode == HttpStatus.SC_CREATED) { + JSONObject accessObj = JSONObject.fromObject(result); + JSONObject tokenObj = accessObj.getJSONObject("token"); + Header header = httpMethod.getResponseHeader("accessSession"); + setAccessSession(header.getValue()); + setRoaRand(tokenObj.getString("roa_rand")); + statusCode = HttpStatus.SC_OK; + } else { + LOG.error("connect fail, code:" + statusCode + " re:" + result); + } + + } catch(JSONException e) { + LOG.error("function=connect, msg=connect JSONException e={}.", e); + } catch(VnfmException e) { + LOG.error("function=connect, msg=connect VnfmException e={}.", e); + } catch(IOException e) { + LOG.error("function=connect, msg=connect IOException e={}.", e); + } finally { + clearCSMPwd(info); + if(httpMethod != null) { + httpMethod.releaseConnection(); + } + } + return statusCode; + + } + /** + * Make connection + * <br> + * + * @param vnfmObj + * @return + * @since NFVO 0.5 + */ + public int connect(JSONObject vnfmObj) { + LOG.info("function=connect, msg=enter connect function."); + + ConnectInfo info = new ConnectInfo(vnfmObj.getString("url"), vnfmObj.getString("userName"), + vnfmObj.getString("password"), Constant.ANONYMOUS); + HttpMethod httpMethod = null; + int statusCode = Constant.INTERNAL_EXCEPTION; + + try { + httpMethod = new HttpRequests.Builder(info.getAuthenticateMode()) + .setUrl(info.getUrl(), ParamConstants.CSM_AUTH_CONNECT) + .setParams(String.format(ParamConstants.GET_TOKENS_V2, info.getUserName(), info.getUserPwd())) + .post().execute(); + statusCode = httpMethod.getStatusCode(); + + String result = httpMethod.getResponseBodyAsString(); + + if(statusCode == HttpStatus.SC_CREATED) { + JSONObject accessObj = JSONObject.fromObject(result); + JSONObject tokenObj = accessObj.getJSONObject("token"); + Header header = httpMethod.getResponseHeader("accessSession"); + setAccessSession(header.getValue()); + setRoaRand(tokenObj.getString("roa_rand")); + statusCode = HttpStatus.SC_OK; + } else { + LOG.error("connect fail, code:" + statusCode + " re:" + result); + } + + } catch(JSONException e) { + LOG.error("function=connect, msg=connect JSONException e={}.", e); + } catch(VnfmException e) { + LOG.error("function=connect, msg=connect VnfmException e={}.", e); + } catch(IOException e) { + LOG.error("function=connect, msg=connect IOException e={}.", e); + } finally { + clearCSMPwd(info); + if(httpMethod != null) { + httpMethod.releaseConnection(); + } + } + return statusCode; + + } + + private void clearCSMPwd(ConnectInfo connectInfo) { + if(null != connectInfo) { + connectInfo.setUserPwd(""); + } + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/HttpRequests.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/HttpRequests.java new file mode 100644 index 00000000..07f3f6b8 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/HttpRequests.java @@ -0,0 +1,375 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.csm.connect; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; + +import javax.net.ssl.SSLHandshakeException; + +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; +import org.apache.commons.httpclient.methods.DeleteMethod; +import org.apache.commons.httpclient.methods.EntityEnclosingMethod; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.commons.httpclient.methods.PutMethod; +import org.apache.commons.httpclient.methods.StringRequestEntity; +import org.apache.commons.httpclient.protocol.Protocol; +import org.apache.commons.lang.StringUtils; +import org.openo.nfvo.vnfmadapter.common.VnfmException; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpRequest; + +/** + * HTTP Request class.</br> + * + * @author + * @version NFVO 0.5 Sep 14, 2016 + */ +public final class HttpRequests { + + private static final Logger LOG = LoggerFactory.getLogger(HttpRequest.class); + + private static MultiThreadedHttpConnectionManager httpClientMgr; + + private static final int PORT = 31943; + + private HttpRequests() { + // constructor + } + + static { + httpClientMgr = new MultiThreadedHttpConnectionManager(); + httpClientMgr.getParams().setStaleCheckingEnabled(true); + httpClientMgr.getParams().setMaxTotalConnections(20); + httpClientMgr.getParams().setDefaultMaxConnectionsPerHost(100); + } + + /** + * Request builder.</br> + * + * @author + * @version NFVO 0.5 Sep 14, 2016 + */ + public static class Builder { + + private final List<Header> headers = new ArrayList<>(10); + + private String paramsJson; + + private HttpClient client; + + private HttpMethod httpMethod; + + private String encoding; + + private String url; + + private String authenticateMode; + + /** + * + * Constructor<br> + * + * @param authenticateMode + * @since NFVO 0.5 + */ + public Builder(String authenticateMode) { + this.authenticateMode = authenticateMode; + client = new HttpClient(httpClientMgr); + client.getHttpConnectionManager().getParams().setConnectionTimeout(30000); + client.getHttpConnectionManager().getParams().setSoTimeout(30000); + encoding = Constant.ENCODEING; + } + + /** + * Add header + * <br> + * + * @param name + * @param value + * @return + * @since NFVO 0.5 + */ + public Builder addHeader(String name, String value) { + headers.add(new Header(name, value)); + return this; + } + + /** + * Add headers + * <br> + * + * @param header + * @param headers + * @return + * @since NFVO 0.5 + */ + public Builder addHeaders(Header header, Header... headers) { + if(header != null) { + this.headers.add(header); + } + if(headers != null && headers.length > 0) { + for(Header h : headers) { + this.headers.add(h); + } + } + return this; + } + + /** + * Add headers + * <br> + * + * @param headers + * @return + * @since NFVO 0.5 + */ + public Builder addHeaders(List<Header> headers) { + if(headers != null && !headers.isEmpty()) { + this.headers.addAll(headers); + } + return this; + } + + /** + * Update URL + * <br> + * + * @param url + * @param path + * @return + * @throws VnfmException + * @since NFVO 0.5 + */ + public Builder setUrl(String url, String path) throws VnfmException { + if(StringUtils.isEmpty(url)) { + throw new VnfmException("com.huawei.nfvo.vcmmadapter.fusionsphere.check.httprequest.url"); + } + + this.url = url + path; + + LOG.info("setUrl: url =" + url); + + Protocol.registerProtocol("https", + new Protocol("https", SslProtocolSocketFactory.getInstance().get(authenticateMode), PORT)); + + return this; + } + + /** + * Update URL + * <br> + * + * @param url + * @param path + * @param defPort + * @return + * @throws VnfmException + * @since NFVO 0.5 + */ + public Builder setUrl(String url, String path, int defPort) throws VnfmException { + if(StringUtils.isEmpty(url)) { + throw new VnfmException("com.huawei.nfvo.vcmmadapter.fusionsphere.check.httprequest.url"); + } + + this.url = url + path; + + LOG.info("setUrl: url =" + url); + + Protocol.registerProtocol("https", + new Protocol("https", SslProtocolSocketFactory.getInstance().get(authenticateMode), defPort)); + + return this; + } + + /** + * HTTP POST + * <br> + * + * @return + * @since NFVO 0.5 + */ + public Builder post() { + this.httpMethod = new PostMethod(url); + return this; + } + + /** + * HTTP GET + * <br> + * + * @return + * @since NFVO 0.5 + */ + public Builder get() { + this.httpMethod = new GetMethod(url); + return this; + } + + /** + * HTTP PUT + * <br> + * + * @return + * @since NFVO 0.5 + */ + public Builder put() { + this.httpMethod = new PutMethod(url); + return this; + } + + /** + * HTTP DELETE + * <br> + * + * @return + * @since NFVO 0.5 + */ + public Builder delete() { + this.httpMethod = new DeleteMethod(url); + return this; + } + + /** + * Update Params + * <br> + * + * @param json + * @return + * @since NFVO 0.5 + */ + public Builder setParams(String json) { + this.paramsJson = json; + return this; + } + + /** + * Set the encoding + * <br> + * + * @param encode + * @return + * @since NFVO 0.5 + */ + public Builder setEncoding(String encode) { + this.encoding = encode; + return this; + } + + /** + * Make HTTP request + * <br> + * + * @return + * @since NFVO 0.5 + */ + public String request() { + String result = null; + try { + result = executeMethod().getResponseBodyAsString(); + } catch(SSLHandshakeException e) { + LOG.error(String.format("function=request, msg=http request url: %s, SSLHandshake Fail : ", url), e); + try { + LOG.error("function=request, msg=SSLHandshake Fail, start refresh certificate ..."); + SslProtocolSocketFactory socketFactory = SslProtocolSocketFactory.getInstance(); + socketFactory.refresh(authenticateMode); + Protocol.registerProtocol("https", + new Protocol("https", SslProtocolSocketFactory.getInstance().get(authenticateMode), PORT)); + LOG.error("function=request, msg=SSLHandshake Fail, certificate refresh successful ."); + + result = executeMethod().getResponseBodyAsString(); + } catch(IOException ioe) { + LOG.error(String.format("function=request, msg=http request url: %s, error: ", url), ioe); + } catch(VnfmException ose) { + LOG.error(String.format("function=request, msg=http request url: %s, error: ", url), ose); + } + } catch(IOException | VnfmException e) { + LOG.error(String.format("function=request, msg=http request url: %s, error: ", url), e); + } finally { + httpMethod.releaseConnection(); + } + return result; + } + + /** + * Execute the HTTP method + * <br> + * + * @return + * @throws VnfmException + * @throws IOException + * @since NFVO 0.5 + */ + public HttpMethod execute() throws VnfmException, IOException { + try { + executeMethod(); + } catch(SSLHandshakeException e) { + LOG.error(String.format("function=execute, msg=http request url: %s, SSLHandshake Fail : ", url), e); + LOG.error("function=execute, SSLHandshake Fail, start refresh certificate ..."); + SslProtocolSocketFactory socketFactory = SslProtocolSocketFactory.getInstance(); + socketFactory.refresh(authenticateMode); + Protocol.registerProtocol("https", + new Protocol("https", SslProtocolSocketFactory.getInstance().get(authenticateMode), PORT)); + LOG.error("function=execute, SSLHandshake Fail, certificate refresh successful ."); + + executeMethod(); + } + return httpMethod; + } + + private HttpMethod executeMethod() throws VnfmException, IOException { + if(httpMethod == null) { + httpMethod = new GetMethod(url); + } + + handleParams(); + + client.executeMethod(httpMethod); + + return httpMethod; + } + + private void handleParams() throws UnsupportedEncodingException { + if(paramsJson != null && !paramsJson.isEmpty()) { + StringRequestEntity stringRequestEntity = + new StringRequestEntity(paramsJson, "application/json", encoding); + String contentLengthString = String.valueOf(stringRequestEntity.getContentLength()); + + if(httpMethod instanceof PostMethod || httpMethod instanceof PutMethod) { + ((EntityEnclosingMethod)httpMethod).setRequestEntity(stringRequestEntity); + ((EntityEnclosingMethod)httpMethod).addRequestHeader("Content-Length", contentLengthString); + } else { + httpMethod.setQueryString(paramsJson); + } + addHeader("Content-Type", String.format("application/json;charset=%s", encoding)); + } + + for(Header header : headers) { + httpMethod.addRequestHeader(header); + } + } + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslAnonymousSocket.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslAnonymousSocket.java new file mode 100644 index 00000000..09ec841a --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslAnonymousSocket.java @@ -0,0 +1,89 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.csm.connect; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.Socket; +import java.security.GeneralSecurityException; + +import javax.net.ssl.SSLSocketFactory; + +import org.apache.commons.httpclient.ConnectTimeoutException; +import org.apache.commons.httpclient.params.HttpConnectionParams; +import org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory; +import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; +import org.openo.nfvo.vnfmadapter.common.VnfmException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Create socket with Anonymous + */ +public class SslAnonymousSocket extends AbstractSslContext implements SecureProtocolSocketFactory { + + private static final Logger LOG = LoggerFactory.getLogger(SslAnonymousSocket.class); + + private SSLSocketFactory sslSocketFactory = null; + + /** + * Initialize + * <br> + * + * @throws VnfmException + * @since NFVO 0.5 + */ + public void init() throws VnfmException { + try { + sslSocketFactory = getAnonymousSSLContext().getSocketFactory(); + } catch(GeneralSecurityException e) { + LOG.error("function=init, get Anonymous SSLContext exception, exceptioninfo", e); + throw (VnfmException)new VnfmException().initCause(e); + } + } + + @Override + public Socket createSocket(String host, int port) throws IOException { + return sslSocketFactory.createSocket(host, port); + } + + @Override + public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException { + return sslSocketFactory.createSocket(host, port, clientHost, clientPort); + } + + @Override + public Socket createSocket(String host, int port, InetAddress localAddress, int localPort, + HttpConnectionParams params) throws IOException, ConnectTimeoutException { + if(params == null) { + throw new IOException("Illegal socket parameters!"); + } else { + int timeout = params.getConnectionTimeout(); + + if(timeout == 0) { + return createSocket(host, port, localAddress, localPort); + } else { + return ControllerThreadSocketFactory.createSocket(this, host, port, localAddress, localPort, timeout); + } + } + } + + @Override + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException { + return sslSocketFactory.createSocket(socket, host, port, autoClose); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslCertificateSocket.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslCertificateSocket.java new file mode 100644 index 00000000..9eca6e28 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslCertificateSocket.java @@ -0,0 +1,87 @@ +/* + * Copyright 2017 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.nfvo.vnfmadapter.service.csm.connect; + +import org.apache.commons.httpclient.ConnectTimeoutException; +import org.apache.commons.httpclient.params.HttpConnectionParams; +import org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory; +import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; +import org.openo.nfvo.vnfmadapter.common.VnfmException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.net.ssl.SSLSocketFactory; +import java.io.IOException; +import java.net.InetAddress; +import java.net.Socket; +import java.security.GeneralSecurityException; + +/** + * Created by QuanZhong on 2017/3/6. + */ +public class SslCertificateSocket extends AbstractSslContext implements SecureProtocolSocketFactory { + + private static final Logger LOG = LoggerFactory.getLogger(SslAnonymousSocket.class); + + private SSLSocketFactory sslSocketFactory = null; + + /** + * Initialize + * <br> + * + * @throws VnfmException + * @since NFVO 0.5 + */ + public void init() throws VnfmException { + try { + sslSocketFactory = getCertificateSSLContext().getSocketFactory(); + } catch(GeneralSecurityException e) { + LOG.error("function=init, get Anonymous SSLContext exception, exceptioninfo", e); + throw (VnfmException)new VnfmException().initCause(e); + } + } + + @Override + public Socket createSocket(String host, int port) throws IOException { + return sslSocketFactory.createSocket(host, port); + } + + @Override + public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException { + return sslSocketFactory.createSocket(host, port, clientHost, clientPort); + } + + @Override + public Socket createSocket(String host, int port, InetAddress localAddress, int localPort, + HttpConnectionParams params) throws IOException, ConnectTimeoutException { + if(params == null) { + throw new IOException("Illegal socket parameters!"); + } else { + int timeout = params.getConnectionTimeout(); + + if(timeout == 0) { + return createSocket(host, port, localAddress, localPort); + } else { + return ControllerThreadSocketFactory.createSocket(this, host, port, localAddress, localPort, timeout); + } + } + } + + @Override + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException { + return sslSocketFactory.createSocket(socket, host, port, autoClose); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslProtocolSocketFactory.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslProtocolSocketFactory.java new file mode 100644 index 00000000..d14d939a --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslProtocolSocketFactory.java @@ -0,0 +1,101 @@ +/* + * Copyright 2016-2017 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.nfvo.vnfmadapter.service.csm.connect; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; +import org.openo.nfvo.vnfmadapter.common.VnfmException; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SSL Socket Factory. + * .</br> + * + * @author + * @version NFVO 0.5 Sep 14, 2016 + */ +public class SslProtocolSocketFactory { + + private static final Logger LOG = LoggerFactory.getLogger(SslProtocolSocketFactory.class); + + private static final Map<String, ProtocolSocketFactory> SOCKMAP = + new ConcurrentHashMap<String, ProtocolSocketFactory>(2); + + private static SslProtocolSocketFactory singleinstance = null; + + /** + * Generate instance of SslProtocolSocketFactory + * <br> + * + * @return + * @since NFVO 0.5 + */ + public static synchronized SslProtocolSocketFactory getInstance() { + if(singleinstance == null) { + singleinstance = new SslProtocolSocketFactory(); + } + return singleinstance; + } + + /** + * + * <br> + * + * @param authenticateMode + * @return + * @throws VnfmException + * @since NFVO 0.5 + */ + public synchronized ProtocolSocketFactory get(String authenticateMode) throws VnfmException { + if(SOCKMAP.get(authenticateMode) == null) { + if(Constant.ANONYMOUS.equals(authenticateMode)) { + SslAnonymousSocket anonymous = new SslAnonymousSocket(); + anonymous.init(); + SOCKMAP.put(Constant.ANONYMOUS, anonymous); + }else if (Constant.CERTIFICATE.equals(authenticateMode)){ + SslCertificateSocket certificateSocket = new SslCertificateSocket(); + certificateSocket.init(); + SOCKMAP.put(Constant.CERTIFICATE, certificateSocket); + } else { + LOG.error("funtion=get, msg=ProtocolSocketFactory Unknown AuthenticateMode={}", authenticateMode); + throw new VnfmException(String.format("Illegal Auth mode", authenticateMode)); + } + } + + return SOCKMAP.get(authenticateMode); + } + + /** + * Refresh local socket map + * <br> + * + * @param autherMode + * @throws VnfmException + * @since NFVO 0.5 + */ + public synchronized void refresh(String autherMode) throws VnfmException { + if(Constant.ANONYMOUS.equals(autherMode)) { + SslAnonymousSocket anonymous = new SslAnonymousSocket(); + anonymous.init(); + SOCKMAP.put(Constant.ANONYMOUS, anonymous); + } + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/inf/InterfaceConnectMgr.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/inf/InterfaceConnectMgr.java new file mode 100644 index 00000000..f2a2c5e5 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/inf/InterfaceConnectMgr.java @@ -0,0 +1,45 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.csm.inf; + +import org.openo.nfvo.vnfmadapter.common.VnfmException; + +import net.sf.json.JSONObject; +/** + * Provide interface for connecting + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 25, 2016 + */ +@FunctionalInterface +public interface InterfaceConnectMgr { + + /** + * Provide interface for connecting + * <br/> + * + * @param obj + * @return + * @throws VnfmException + * @since NFVO 0.5 + */ + int connect(JSONObject obj) throws VnfmException; + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/inf/InterfaceVnfMgr.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/inf/InterfaceVnfMgr.java new file mode 100644 index 00000000..8a1cb0b3 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/inf/InterfaceVnfMgr.java @@ -0,0 +1,83 @@ +/* + * Copyright 2016-2017 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.nfvo.vnfmadapter.service.csm.inf; + +import net.sf.json.JSONObject; + +/** + * Provide interfaces for instantiate or terminate VNF. + * <br/> + * + * @author + * @version NFVO 0.5 Aug 24, 2016 + */ +public interface InterfaceVnfMgr { + + /** + * Provide interface for scale VNF. + * @param vnfObject + * @param vnfmObject + * @param vnfmId + * @param vnfInstanceId + * @return + */ + public JSONObject scaleVnf(JSONObject vnfObject, JSONObject vnfmObject, String vnfmId, String vnfInstanceId); + /** + * Provide interface for instantiate VNF. + * <br/> + * + * @param subJsonObject + * @param vnfmObjcet + * @return + * @since NFVO 0.5 + */ + JSONObject createVnf(JSONObject subJsonObject, JSONObject vnfmObjcet); + + /** + * Provide interface for terminate VNF + * <br/> + * + * @param vnfmObject + * @param vnfId + * @param vnfObject + * @return + * @since NFVO 0.5 + */ + JSONObject removeVnf(JSONObject vnfmObject, String vnfId, JSONObject vnfObject); + + /** + * Provide interface for get VNF info + * <br/> + * + * @param vnfmObject + * @param vnfId + * @return + * @since NFVO 0.5 + */ + JSONObject getVnf(JSONObject vnfmObject, String vnfId); + + /** + * Retrieve job + * <br> + * + * @param vnfmObject + * @param jobId + * @return + * @since NFVO 0.5 + */ + JSONObject getJob(JSONObject vnfmObject, String jobId); +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/vnf/VnfMgrVnfm.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/vnf/VnfMgrVnfm.java new file mode 100644 index 00000000..dea8c0bf --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/csm/vnf/VnfMgrVnfm.java @@ -0,0 +1,223 @@ +/* + * Copyright 2016-2017 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.nfvo.vnfmadapter.service.csm.vnf; + +import net.sf.json.JSONArray; +import org.openo.nfvo.vnfmadapter.common.ResultRequestUtil; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.constant.ParamConstants; +import org.openo.nfvo.vnfmadapter.service.csm.inf.InterfaceVnfMgr; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONException; +import net.sf.json.JSONObject; + +import javax.print.attribute.standard.ReferenceUriSchemesSupported; + +/** + * create or terminate VNF to M + * <br/> + * + * @author + * @version NFVO 0.5 Aug 24, 2016 + */ +public class VnfMgrVnfm implements InterfaceVnfMgr { + + private static final Logger LOG = LoggerFactory.getLogger(VnfMgrVnfm.class); + + @Override + public JSONObject scaleVnf(JSONObject vnfObject, JSONObject vnfmObject, String vnfmId, String vnfInstanceId) { + LOG.warn("function=scaleVnf, msg=enter to scale a vnf"); + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + String path = String.format(ParamConstants.VNF_SCALE, vnfInstanceId); + + int scaleType = getScaleType(vnfObject.getString("type")); + //build request json object + JSONObject paramJson = new JSONObject(); + JSONObject scaleInfo = new JSONObject(); + JSONArray vduList = new JSONArray(); + JSONObject vdu = new JSONObject(); + vdu.put("vdu_type",this.getVduType(vnfmObject,vnfInstanceId));//TODO:set vdu_type + vdu.put("h_steps",vnfObject.get("numberOfSteps")); + vduList.add(vdu); + scaleInfo.put("vnf_id",vnfInstanceId); + scaleInfo.put("scale_type",0); + scaleInfo.put("scale_action",scaleType); + scaleInfo.put("vdu_list",vduList); + if(scaleType == 0){//scale_in + JSONArray vmList = new JSONArray(); + try { + JSONObject additionalParam = vnfObject.getJSONObject("additionalParam"); + vmList = additionalParam.getJSONArray("vm_list"); + }catch (JSONException e) { + LOG.error("the param 'additionalParam' or 'vm_list' not found,please check it",e); + } + scaleInfo.put("vm_list",vmList); + } + paramJson.put("scale_info",scaleInfo); + JSONObject queryResult = ResultRequestUtil.call(vnfmObject, path, Constant.PUT, paramJson.toString(),Constant.CERTIFICATE); + LOG.info("SCALE execute result:"+queryResult.toString()); + try { + int statusCode = queryResult.getInt(Constant.RETCODE); + + if(statusCode == Constant.HTTP_CREATED || statusCode == Constant.HTTP_OK) { + restJson.put(Constant.RETCODE, Constant.REST_SUCCESS); + JSONObject resultObj = new JSONObject(); + resultObj.put("jobId", vnfInstanceId + "_" + Constant.PUT); + restJson.put("data", resultObj); + } else { + LOG.error("function=scaleVnf, msg=send create vnf msg to csm get wrong status: " + statusCode); + } + + } catch(JSONException e) { + LOG.error("function=scaleVnf, msg=parse scale vnf return data occoured JSONException, e={}.", e); + } + + return restJson; + } + + + private String getVduType(JSONObject vnfmObject, String vnfInstanceId){ + String vduType = ""; + try { + JSONObject queryResult = ResultRequestUtil.call(vnfmObject, String.format(ParamConstants.VNF_GET_VMINFO, vnfInstanceId), Constant.GET, null,Constant.CERTIFICATE); + LOG.info("getVduType result="+queryResult); + vduType = queryResult.getJSONObject("data").getJSONArray("vms").getJSONObject(0).getString("vdu_type"); + } catch (Exception e) { + LOG.error("get vdu_type failed.",e); + } + LOG.info("vdu_type="+vduType); + return vduType; + } + private int getScaleType(String type){ + if("SCALE_OUT".equalsIgnoreCase(type)){ + return 1; + }else if("SCALE_IN".equalsIgnoreCase(type)){ + return 0; + } + return -1; + } + @Override + public JSONObject createVnf(JSONObject subJsonObject, JSONObject vnfmObject) { + LOG.info("function=createVnf, msg=enter to create a vnf"); + LOG.info("createVnf csm request body :"+subJsonObject); + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + String path = ParamConstants.VNF_INSTANCE + Constant.ROARAND; + + JSONObject queryResult = ResultRequestUtil.call(vnfmObject, path, Constant.POST, subJsonObject.toString(),Constant.CERTIFICATE); + LOG.info("createVnf csm response content:"+queryResult); + try { + int statusCode = queryResult.getInt(Constant.RETCODE); + + if(statusCode == Constant.HTTP_CREATED) { + restJson.put(Constant.RETCODE, Constant.REST_SUCCESS); + JSONObject appInfo = JSONObject.fromObject(queryResult.getString("data")).getJSONObject("app_info"); + JSONObject resultObj = new JSONObject(); + resultObj.put("vnfInstanceId", appInfo.getString("id")); + resultObj.put("jobId", appInfo.getString("id") + "_" + Constant.POST); + restJson.put("data", resultObj); + } else { + LOG.error("function=createVnf, msg=send create vnf msg to csm get wrong status: " + statusCode); + } + + } catch(JSONException e) { + LOG.error("function=createVnf, msg=parse create vnf return data occoured JSONException, e={}.", e); + } + + return restJson; + } + + @Override + public JSONObject removeVnf(JSONObject vnfmObject, String vnfId, JSONObject vnfObject) { + LOG.warn("function=removeVnf, msg=enter to remove a vnf: {}", vnfId); + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + + JSONObject queryResult = ResultRequestUtil.call(vnfmObject, + String.format(ParamConstants.VNF_INSTANCE_DEL, vnfId) + Constant.ROARAND, Constant.DELETE, null,Constant.CERTIFICATE); + + int statusCode = queryResult.getInt(Constant.RETCODE); + + if(statusCode == Constant.HTTP_NOCONTENT) { + restJson.put(Constant.RETCODE, Constant.REST_SUCCESS); + JSONObject resultObj = new JSONObject(); + resultObj.put("jobId", vnfId + "_" + Constant.DELETE); + restJson.put("data", resultObj); + } else { + LOG.error("function=removeVnf, msg=send remove vnf msg to csm get wrong status: {}", statusCode); + } + + return restJson; + } + + @Override + public JSONObject getVnf(JSONObject vnfmObject, String vnfId) { + LOG.warn("function=getVnf, msg=enter to get a vnf: {}", vnfId); + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + + JSONObject queryResult = ResultRequestUtil.call(vnfmObject, + String.format(ParamConstants.VNF_INSTANCE_GET, vnfId) + Constant.ROARAND + "&type=status", Constant.GET, + null,Constant.CERTIFICATE); + + int statusCode = queryResult.getInt("retCode"); + + if(statusCode == Constant.HTTP_OK || statusCode == Constant.HTTP_CREATED) { + if(null == (queryResult.get("data"))) { + LOG.warn("function=getVnf, msg=query is null {}", queryResult.get("data")); + return restJson; + } + restJson.put(Constant.RETCODE, Constant.REST_SUCCESS); + restJson.put("data", JSONObject.fromObject(queryResult.getString("data")).getJSONArray("basic")); + } else { + LOG.error("function=getVnf, msg=send get vnf msg to csm get wrong status: {}", statusCode); + } + + return restJson; + } + + @Override + public JSONObject getJob(JSONObject vnfmObject, String jobId) { + LOG.warn("function=getJob, msg=enter to get a job: {}", jobId); + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + + String vnfId = jobId.split("_")[0]; + JSONObject queryResult = ResultRequestUtil.call(vnfmObject, + String.format(ParamConstants.VNF_INSTANCE_GET, vnfId) + Constant.ROARAND + "&type=status", Constant.GET, + null,Constant.CERTIFICATE); + + int statusCode = queryResult.getInt("retCode"); + + if(statusCode == Constant.HTTP_OK || statusCode == Constant.HTTP_CREATED) { + + if((queryResult.get("data")) == null) { + LOG.warn("function=getJob, msg=query is null {}", queryResult.get("data")); + return restJson; + } + restJson.put(Constant.RETCODE, Constant.REST_SUCCESS); + restJson.put("data", JSONObject.fromObject(queryResult.getString("data")).getJSONArray("basic")); + } else { + LOG.error("function=getJob, msg=send get vnf msg to csm get wrong status: {}", statusCode); + } + + return restJson; + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/dao/impl/VnfmDaoImpl.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/dao/impl/VnfmDaoImpl.java new file mode 100644 index 00000000..c104bd16 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/dao/impl/VnfmDaoImpl.java @@ -0,0 +1,62 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.dao.impl; + +import java.util.List; + +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.nfvo.vnfmadapter.service.dao.inf.AbstractDao; +import org.openo.nfvo.vnfmadapter.service.dao.inf.VnfmDao; +import org.openo.nfvo.vnfmadapter.service.entity.Vnfm; +import org.openo.nfvo.vnfmadapter.service.mapper.VnfmMapper; + +/** + * VNFM DAO + * .</br> + * + * @author + * @version NFVO 0.5 Sep 14, 2016 + */ +public class VnfmDaoImpl extends AbstractDao implements VnfmDao { + + @Override + public int insertVnfm(Vnfm vnfm) throws ServiceException { + return getMapperManager(VnfmMapper.class).insertVnfm(vnfm); + } + + @Override + public int deleteVnfm(String vnfmDn) throws ServiceException { + return getMapperManager(VnfmMapper.class).deleteVnfm(vnfmDn); + } + + @Override + public int updateVnfm(Vnfm vnfm) throws ServiceException { + return getMapperManager(VnfmMapper.class).updateVnfm(vnfm); + } + + @Override + public List<Vnfm> indexVnfms(int pageSize, int pageNo) throws ServiceException { + VnfmMapper vnfmMapper = getMapperManager(VnfmMapper.class); + int offset = (pageNo - 1) * pageSize; + return vnfmMapper.indexVnfms(offset, pageSize); + } + + @Override + public Vnfm getVnfmById(String id) { + return getMapperManager(VnfmMapper.class).getVnfmById(id); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/dao/inf/AbstractDao.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/dao/inf/AbstractDao.java new file mode 100644 index 00000000..592c3d50 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/dao/inf/AbstractDao.java @@ -0,0 +1,50 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.dao.inf; + +import org.apache.ibatis.session.SqlSession; + +/** + * database abstract class to get the MapperManager. + */ +public class AbstractDao { + + private SqlSession session; + + protected AbstractDao() { + //Constructor + } + + public SqlSession getSession() { + return session; + } + + public void setSession(SqlSession session) { + this.session = session; + } + + /** + * get Mybatis Mapper. + * + * @param type : The class of the instance + * @param <T> : The type of the instance + * @return Mapper : The instance + */ + public <T> T getMapperManager(Class<T> type) { + return (T)getSession().getMapper(type); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/dao/inf/VnfmDao.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/dao/inf/VnfmDao.java new file mode 100644 index 00000000..8fc4431c --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/dao/inf/VnfmDao.java @@ -0,0 +1,87 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.dao.inf; + +import java.util.List; + +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.nfvo.vnfmadapter.service.entity.Vnfm; + +/** + * VNFM DAO + * .</br> + * + * @author + * @version NFVO 0.5 Sep 14, 2016 + */ +public interface VnfmDao { + + /** + * Add VNFM + * <br> + * + * @param vnfm + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + int insertVnfm(Vnfm vnfm) throws ServiceException; + + /** + * Delete VNFM + * <br> + * + * @param vnfmDn + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + int deleteVnfm(String vnfmDn) throws ServiceException; + + /** + * Update VNFM + * <br> + * + * @param vnfm + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + int updateVnfm(Vnfm vnfm) throws ServiceException; + + /** + * Index VNFM + * <br> + * + * @param pageSize + * @param pageNo + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + List<Vnfm> indexVnfms(int pageSize, int pageNo) throws ServiceException; + + /** + * Get VNFM by id. + * <br> + * + * @param id + * @return + * @since NFVO 0.5 + */ + Vnfm getVnfmById(String id); +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/entity/Vnfm.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/entity/Vnfm.java new file mode 100644 index 00000000..dec1724c --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/entity/Vnfm.java @@ -0,0 +1,110 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.entity; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +/** + * Provide database class + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 3, 2016 + */ +public class Vnfm { + + private String id; + + private String version; + + private String vnfdId; + + private String vnfPackageId; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getVnfdId() { + return vnfdId; + } + + public void setVnfdId(String vnfdId) { + this.vnfdId = vnfdId; + } + + public String getVnfPackageId() { + return vnfPackageId; + } + + public void setVnfPackageId(String vnfPackageId) { + this.vnfPackageId = vnfPackageId; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if(this == obj) { + return true; + } + if(obj == null) { + return false; + } + if(!(obj instanceof Vnfm)) { + return false; + } + if(getClass() != obj.getClass()) { + return false; + } + Vnfm other = (Vnfm)obj; + if(id == null) { + if(other.id != null) { + return false; + } + } else if(!id.equals(other.id)) { + return false; + } + return true; + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/mapper/VnfmMapper.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/mapper/VnfmMapper.java new file mode 100644 index 00000000..63317626 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/mapper/VnfmMapper.java @@ -0,0 +1,91 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.mapper; + +import java.util.List; + +import org.apache.ibatis.annotations.Param; +import org.openo.nfvo.vnfmadapter.service.entity.Vnfm; + +/** + * VNFM mapper.</br> + * + * @author + * @version NFVO 0.5 Sep 14, 2016 + */ +public interface VnfmMapper { + + /** + * Add VNFM + * <br> + * + * @param vnfm Vnfm + * @return + * @since NFVO 0.5 + */ + int insertVnfm(Vnfm vnfm); + + /** + * Update VNFM + * <br> + * + * @param vnfm Vnfm + * @return + * @since NFVO 0.5 + */ + int updateVnfm(Vnfm vnfm); + + /** + * Delete VNFM + * <br> + * + * @param vnfmDn + * @return + * @since NFVO 0.5 + */ + int deleteVnfm(String vnfmDn); + + /** + * Index VNFM + * <br> + * + * @param offset + * @param pageSize + * @return + * @since NFVO 0.5 + */ + List<Vnfm> indexVnfms(@Param("offset") int offset, @Param("pageSize") int pageSize); + + /** + * Get VNFM counts. + * <br> + * + * @return + * @since NFVO 0.5 + */ + int getCountVnfms(); + + /** + * Get VNFM by id + * <br> + * + * @param id + * @return + * @since NFVO 0.5 + */ + Vnfm getVnfmById(String id); +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/AuthMgr.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/AuthMgr.java new file mode 100644 index 00000000..1793755d --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/AuthMgr.java @@ -0,0 +1,74 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.process; + +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONException; +import net.sf.json.JSONObject; + +/** + * Provide function for authInfo. + * <br/> + * + * @author + * @version NFVO 0.5 Aug 24, 2016 + */ +public class AuthMgr { + + private static final Logger LOG = LoggerFactory.getLogger(AuthMgr.class); + + /** + * Provide function for add authInfo. + * <br/> + * + * @param params + * @return + * @since NFVO 0.5 + */ + public JSONObject authToken(JSONObject params) { + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + try { + String userName = params.getString("userName"); + + restJson = getStatusResult(userName); + } catch(JSONException e) { + LOG.error("function=login, msg=Params error occurs, e={}.", e); + restJson.put("data", "JSONException"); + return restJson; + } + return restJson; + } + + private JSONObject getStatusResult(String userName) { + JSONObject restJson = new JSONObject(); + JSONObject authResult = new JSONObject(); + JSONObject addInfo = new JSONObject(); + authResult.put("accessSession", "1234"); + authResult.put("roaRand", "RoaRand"); + authResult.put("expires", 1800); + addInfo.put("expires", 10); + addInfo.put("passwdStatus", "expiring"); + authResult.put("additionalInfo", addInfo); + restJson.put("retCode", Constant.REST_SUCCESS); + restJson.put("data", authResult); + return restJson; + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/RegisterMgr.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/RegisterMgr.java new file mode 100644 index 00000000..7da24c0e --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/RegisterMgr.java @@ -0,0 +1,83 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.process; + +import java.util.HashMap; +import java.util.Map; + +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.common.RegisterConfigInfo; +import org.openo.nfvo.vnfmadapter.common.servicetoken.VnfmRestfulUtil; +import org.openo.nfvo.vnfmadapter.service.constant.ParamConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * Provide function for register or unregister service to Bus. + * <br/> + * + * @author + * @version NFVO 0.5 Aug 24, 2016 + */ +public class RegisterMgr { + + private static final Logger LOG = LoggerFactory.getLogger(RegisterMgr.class); + + /** + * Register service to the Bus + * <br/> + * + * @since NFVO 0.5 + */ + public void register() { + RestfulResponse rsp = VnfmRestfulUtil.getRemoteResponse(ParamConstants.MSB_REGISTER_URL, + VnfmRestfulUtil.TYPE_POST, getRegsiterBody()); + + LOG.error("funtion=register, status={}", rsp.getStatus()); + } + + /** + * UnRegister service to the Bus + * <br/> + * + * @since NFVO 0.5 + */ + public void unRegister() { + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", ParamConstants.MSB_UNREGISTER_URL); + paramsMap.put("methodType", VnfmRestfulUtil.TYPE_DEL); + RestfulResponse rsp = VnfmRestfulUtil.getRemoteResponse(ParamConstants.MSB_UNREGISTER_URL, + VnfmRestfulUtil.TYPE_DEL, null); + + LOG.error("funtion=register, status={}", rsp.getStatus()); + } + + private String getRegsiterBody() { + JSONObject body = new JSONObject(); + body.put("serviceName", RegisterConfigInfo.getInstance().getServiceName()); + body.put("version", RegisterConfigInfo.getInstance().getVersion()); + body.put("url", RegisterConfigInfo.getInstance().getUrl()); + body.put("protocol", RegisterConfigInfo.getInstance().getProtocol()); + body.put("port", RegisterConfigInfo.getInstance().getPort()); + body.put("ip", RegisterConfigInfo.getInstance().getIp()); + body.put("ttl", RegisterConfigInfo.getInstance().getTtl()); + + return body.toString(); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/VnfMgr.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/VnfMgr.java new file mode 100644 index 00000000..816af06f --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/VnfMgr.java @@ -0,0 +1,296 @@ +/* + * Copyright 2016-2017 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.nfvo.vnfmadapter.service.process; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.nfvo.vnfmadapter.common.VnfmUtil; +import org.openo.nfvo.vnfmadapter.service.adapter.impl.AdapterResourceManager; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.csm.vnf.VnfMgrVnfm; +import org.openo.nfvo.vnfmadapter.service.dao.inf.VnfmDao; +import org.openo.nfvo.vnfmadapter.service.entity.Vnfm; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONException; +import net.sf.json.JSONObject; + +/** + * Provide function for instantiate or terminate VNF + * <br/> + * + * @author + * @version NFVO 0.5 Aug 24, 2016 + */ +public class VnfMgr { + + private static final Logger LOG = LoggerFactory.getLogger(VnfMgr.class); + + private VnfmDao vnfmDao; + + public void setVnfmDao(VnfmDao vnfmDao) { + this.vnfmDao = vnfmDao; + } + + + /** + * Scale vnf + * @param vnfObject + * { + * "vnfInstanceId":"5", + * "type":"SCALE_OUT", + * "aspectId":"101", + * "numberOfSteps":"1", + * "additionalParam":{} + * } + * @param vnfmId + * @param vnfInstanceId + * @return + */ + public JSONObject scaleVNF(JSONObject vnfObject, String vnfmId, String vnfInstanceId) { + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + try { + + if(vnfObject.isNullObject() || vnfObject.isEmpty()) { + return restJson; + } + + JSONObject vnfmObjcet = VnfmUtil.getVnfmById(vnfmId); + LOG.info("vnfm info:"+vnfmObjcet); + if(vnfmObjcet.isNullObject()) { + LOG.error("function=scaleVNF,can't find vnfm from db by vnfmId="+vnfmId); + return restJson; + } + restJson = (new VnfMgrVnfm()).scaleVnf(vnfObject, vnfmObjcet, vnfmId, vnfInstanceId); + } catch(JSONException e) { + LOG.error("function=scaleVNF, msg=JSONException occurs, e={}.", e); + } + + return restJson; + } + + /** + * Provide function for instantiate VNF + * <br/> + * + * @param vnfObject + * @param vnfmId + * @return + * @since NFVO 0.5 + */ + public JSONObject addVnf(JSONObject vnfObject, String vnfmId) { + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + try { + + if(vnfObject.isNullObject() || vnfObject.isEmpty()) { + return restJson; + } + + JSONObject vnfmObjcet = VnfmUtil.getVnfmById(vnfmId); + + if(vnfmObjcet.isNullObject()) { + return restJson; + } + + Map<String, String> conMap = new ConcurrentHashMap<>(Constant.DEFAULT_COLLECTION_SIZE); + conMap.put("csarid", vnfObject.getString("vnfPackageId")); + conMap.put("vnfmid", vnfmId); + conMap.put("vnfDescriptorId",vnfObject.getString("vnfDescriptorId")); + + JSONObject resObjcet = (new AdapterResourceManager()).uploadVNFPackage(null, conMap); + + if(resObjcet.getInt(Constant.RETCODE) == Constant.REST_FAIL) { + return restJson; + } + + JSONObject csmBody = transferVnfBody(vnfObject, resObjcet, vnfmId); + restJson = (new VnfMgrVnfm()).createVnf(csmBody, vnfmObjcet); + saveVnfInfo(restJson, resObjcet); + } catch(JSONException e) { + LOG.error("function=addVnf, msg=JSONException occurs, e={}.", e); + } + + return restJson; + } + + /** + * Provide function for terminate VNF + * <br/> + * + * @param vnfId + * @param vnfmId + * @param vnfObject + * @return + * @since NFVO 0.5 + */ + public JSONObject deleteVnf(String vnfId, String vnfmId, JSONObject vnfObject) { + LOG.warn("function=deleteVnf ,msg=enter to delete a vnf, vnfId:{}, vnfmId:{}", vnfId, vnfmId); + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + try { + JSONObject vnfmObjcet = VnfmUtil.getVnfmById(vnfmId); + if(vnfmObjcet.isNullObject()) { + LOG.error("function=deleteVnf, msg=vnfm not exists, vnfmId: {}", vnfmId); + return restJson; + } + + restJson = (new VnfMgrVnfm()).removeVnf(vnfmObjcet, vnfId, vnfObject); + } catch(JSONException e) { + LOG.error("function=deleteVnf, msg=JSONException occurs, e={}.", e); + } + return restJson; + } + + /** + * Provide function for get VNF + * <br/> + * + * @param vnfId + * @param vnfmId + * @return + * @since NFVO 0.5 + */ + public JSONObject getVnf(String vnfId, String vnfmId) { + LOG.warn("function=getVnf ,msg=enter to get a vnf, vnfId:{}, vnfmId:{}", vnfId, vnfmId); + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + try { + JSONObject vnfmObjcet = VnfmUtil.getVnfmById(vnfmId); + if(vnfmObjcet.isNullObject()) { + LOG.error("function=getVnf, msg=vnfm not exists, vnfmId: {}", vnfmId); + return restJson; + } + + restJson = (new VnfMgrVnfm()).getVnf(vnfmObjcet, vnfId); + + return restJson.getInt(Constant.RETCODE) == Constant.REST_FAIL ? restJson : getVnfBody(restJson); + + } catch(JSONException e) { + LOG.error("function=getVnf, msg=JSONException occurs, e={}.", e); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + } + return restJson; + } + + private JSONObject getVnfBody(JSONObject restJson) { + try { + JSONObject vnfInfoJson = new JSONObject(); + JSONObject basicInfoJson = new JSONObject(); + + JSONObject retJson = restJson.getJSONArray("data").getJSONObject(0); + + basicInfoJson.put("vnfInstanceId", retJson.getString("id")); + basicInfoJson.put("vnfInstanceName", retJson.getString("vapp_name")); + basicInfoJson.put("vnfInstanceDescription", "vFW"); + + Vnfm vnfm = vnfmDao.getVnfmById(retJson.getString("id")); + basicInfoJson.put("vnfdId", vnfm == null ? "" : vnfm.getVnfdId()); + basicInfoJson.put("vnfdPackageId", vnfm == null ? "" : vnfm.getVnfPackageId()); + basicInfoJson.put("version", vnfm == null ? "" : vnfm.getVersion()); + basicInfoJson.put("vnfProvider", "hw"); + basicInfoJson.put("vnfType", retJson.get("vapp_type")); + basicInfoJson.put("vnfStatus", retJson.getString(Constant.STATUS)); + + vnfInfoJson.put("vnfInfo", basicInfoJson); + vnfInfoJson.put(Constant.RETCODE, Constant.REST_SUCCESS); + return vnfInfoJson; + } catch(JSONException e) { + LOG.error("function=getVnf, msg=JSONException occurs, e={}.", e); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + return restJson; + } catch(IndexOutOfBoundsException e) { + LOG.error("function=getVnf, msg=IndexOutOfBoundsException occurs, e={}.", e); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + return restJson; + } + } + + @SuppressWarnings("unchecked") + private JSONObject transferVnfBody(JSONObject vnfObject, JSONObject resObject, String vnfmId) { + JSONObject restJson = new JSONObject(); + JSONObject vappIfno = new JSONObject(); + restJson.put("vnfd_id", resObject.getString("vnfdId")); + restJson.put("plan_id", resObject.getOrDefault("planId", "")); + restJson.put("plan_name", resObject.getOrDefault("planName", "")); + restJson.put("vapp_name", vnfObject.get("vnfInstanceName")); + restJson.put("project_id", vnfmId); + restJson.put("parameters", resObject.getJSONObject("parameters")); + restJson.put("nfvo_id", ""); + restJson.put("location", ""); + restJson.put("vnfm_id", vnfmId); + vappIfno.put("vapp_info", restJson); + return vappIfno; + } + + /** + * Provide function for get job + * <br/> + * + * @param jobId + * @param vnfmId + * @return + * @since NFVO 0.5 + */ + public JSONObject getJob(String jobId, String vnfmId) { + LOG.warn("function=getJob ,msg=enter to get a job, vnfId:{}", jobId); + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + try { + JSONObject vnfmObjcet = VnfmUtil.getVnfmById(vnfmId); + if(vnfmObjcet.isNullObject()) { + LOG.error("function=getJob, msg=vnfm not exists, vnfmId: {}", vnfmId); + return restJson; + } + + restJson = (new VnfMgrVnfm()).getJob(vnfmObjcet, jobId); + + } catch(JSONException e) { + LOG.error("function=getJob, msg=JSONException occurs, e={}.", e); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + } + return restJson; + } + + /** + * Provide function for save vnfInfo + * <br/> + * + * @param vnfObject + * @param resObject + * @since NFVO 0.5 + */ + public void saveVnfInfo(JSONObject vnfObject, JSONObject resObject) { + LOG.warn("function=saveVnfInfo , vnfObject:{}", vnfObject); + if(vnfObject.getInt(Constant.RETCODE) == Constant.REST_SUCCESS) { + Vnfm info = new Vnfm(); + info.setId(vnfObject.getJSONObject("data").getString("vnfInstanceId")); + info.setVersion(resObject.getString("vnfdVersion")); + info.setVnfdId(resObject.getString("vnfdId")); + info.setVnfPackageId(""); + try { + vnfmDao.insertVnfm(info); + } catch(Exception e) { + LOG.error("function=saveVnfInfo, msg=ServiceException occurs, e={}.", e); + } + } + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/VnfResourceMgr.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/VnfResourceMgr.java new file mode 100644 index 00000000..11bb2291 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/process/VnfResourceMgr.java @@ -0,0 +1,254 @@ +/* + * Copyright 2016-2017 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.nfvo.vnfmadapter.service.process; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.common.servicetoken.VnfmRestfulUtil; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.constant.ParamConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONArray; +import net.sf.json.JSONException; +import net.sf.json.JSONObject; + +/** + * Provide function of resource for VNFM. + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 25, 2016 + */ +public class VnfResourceMgr { + + private static final Logger LOG = LoggerFactory.getLogger(VnfResourceMgr.class); + + /** + * Provide function of grant resource for VNFM. + * <br/> + * + * @param vnfObj + * @param vnfId + * @param vnfmId + * @return + * @since NFVO 0.5 + */ + public JSONObject grantVnfResource(JSONObject vnfObj, String vnfId, String vnfmId) { + LOG.warn("function=grantVnfResource, msg=enter to grant vnf resource, params: {}", vnfObj); + JSONObject resultJson = new JSONObject(); + resultJson.put("retCode", Constant.REST_FAIL); + try { + String type = vnfObj.getString("type"); + String requestType = vnfObj.getString("operation_right"); + String vnfName = vnfObj.getString("vnf_name"); + + if(StringUtils.isEmpty(type) || StringUtils.isEmpty(requestType) || StringUtils.isEmpty(vnfName) + || StringUtils.isEmpty(vnfId)) { + LOG.error("function=grantVnfResource, msg=grant basic params error"); + resultJson.put("errorMsg", "basic params error"); + return resultJson; + } + + JSONArray vmList = vnfObj.getJSONArray("vm_list"); + + Map<String, Integer> resMap = calculateGrantRes(vmList); + + if(null == resMap) { + LOG.error("function=grantVnfResource, msg=grant resource params error"); + resultJson.put("errorMsg", "resource params error"); + return resultJson; + } + + JSONObject grantObj = new JSONObject(); + grantObj.put("vimId", vnfObj.getString("vim_id")); + grantObj.put("vnfId", vnfId); + grantObj.put("vnfName", vnfName); + grantObj.put("vnfmId", vnfmId); + String action = getGrantAction(type, requestType); + grantObj.put("action", action); + + JSONObject grantParam = parseGrantParam(resMap, grantObj); + resultJson = sendGrantToResmgr(grantParam); + LOG.error("function=grantVnfResource, resultJson={}.", resultJson); + } catch(JSONException e) { + LOG.error("function=grantVnfResource, msg=parse params occoured JSONException e={}.", e); + resultJson.put("errorMsg", "params parse exception"); + } + + return resultJson; + } + + /** + * <br> + * + * @param grantParam + * @return + * @since NFVO 0.5 + */ + private JSONObject sendGrantToResmgr(JSONObject grantParam) { + RestfulResponse rsp = VnfmRestfulUtil.getRemoteResponse(ParamConstants.GRANT_RES_URL, VnfmRestfulUtil.TYPE_PUT, + grantParam.toString()); + if(rsp == null || rsp.getStatus() != Constant.HTTP_OK) { + return null; + } + LOG.error("funtion=sendGrantToResmgr, status={}", rsp.getStatus()); + return JSONObject.fromObject(rsp.getResponseContent()); + } + + /** + * <br> + * + * @param resMap + * @param grantParam + * @return + * @since NFVO 0.5 + */ + private JSONObject parseGrantParam(Map<String, Integer> resMap, JSONObject grantParam) { + JSONObject result = new JSONObject(); + result.put("vnfInstanceId", grantParam.getString("vnfId")); + result.put("vimId", grantParam.getString("vimId")); + + JSONArray resource = new JSONArray(); + JSONObject resourceObj = new JSONObject(); + resourceObj.put("type", "vdu"); + JSONObject resourceTemplate = new JSONObject(); + JSONObject storage = new JSONObject(); + storage.put("sizeOfStorage", resMap.get("diskNum")); + storage.put("typeOfStorage", ""); + storage.put("swImageDescriptor", ""); + JSONObject compute = new JSONObject(); + JSONObject virtualMemory = new JSONObject(); + virtualMemory.put("virtualMemSize", resMap.get("memNum")); + JSONObject virtualCpu = new JSONObject(); + virtualCpu.put("numVirtualCpu", resMap.get("cpuNum")); + compute.put("virtualMemory", virtualMemory); + compute.put("virtualCpu", virtualCpu); + resourceTemplate.put("virtualStorageDescriptor", storage); + resourceTemplate.put("virtualComputeDescriptor", compute); + resourceObj.put("resourceTemplate", resourceTemplate); + resourceObj.put("resourceDefinitionId", ""); + resourceObj.put("vdu", grantParam.getString("vnfName")); + resource.add(resourceObj); + + if("online".equals(grantParam.getString("action")) || "scaleOut".equals(grantParam.getString("action"))) { + result.put("addResource", resource); + } else { + result.put("removeResource", resource); + } + + JSONObject additionalParam = new JSONObject(); + additionalParam.put("vnfmId", grantParam.getString("vnfmId")); + additionalParam.put("vimId", grantParam.getString("vimId")); + additionalParam.put("tenant", ""); + result.put("additionalParam", additionalParam); + LOG.info("funtion=parseGrantParam, result={}", result); + return result; + } + + private Map<String, Integer> calculateGrantRes(JSONArray vmList) { + Map<String, Integer> resMap = new HashMap<>(Constant.DEFAULT_COLLECTION_SIZE); + int vmSize = vmList.size(); + int cpuNum = 0; + int memNum = 0; + int diskNum = 0; + int diskSize = 0; + int cpuTmp = 0; + int memTmp = 0; + int diskTmp = 0; + int initNum = 0; + + try { + for(int i = 0; i < vmSize; i++) { + JSONObject resInfo = vmList.getJSONObject(i); + JSONObject vmFlavor = resInfo.getJSONObject("vm_flavor"); + initNum = Integer.parseInt(resInfo.getString("init_number")); + + if(initNum == 0) { + continue; + } + + JSONArray volumList = vmFlavor.getJSONArray("storage"); + diskSize = volumList.size(); + + for(int j = 0; j < diskSize; j++) { + JSONObject volumeInfo = volumList.getJSONObject(j); + diskTmp += getDiskQuantity(volumeInfo); + } + + cpuTmp = Integer.parseInt(vmFlavor.getString("num_cpus")); + memTmp = Integer.parseInt(vmFlavor.getString("mem_size")); + + cpuNum += cpuTmp * initNum; + memNum += memTmp * initNum; + diskNum += diskTmp * initNum; + + diskTmp = 0; + + } + } catch(JSONException e) { + LOG.error("function=calculateGrantRes, msg=parse params occoured JSONException e={}.", e); + return null; + } + + resMap.put("cpuNum", cpuNum); + resMap.put("memNum", memNum); + resMap.put("diskNum", diskNum); + return resMap; + } + + private String getGrantAction(String type, String requestType) { + String action = "unknown"; + + if(("increase").equals(requestType)) { + if(("instantiation").equals(type)) { + action = "online"; + } else if(("scale").equals(type)) { + action = "scaleOut"; + } + + } else if(("decrease").equals(requestType)) { + if(("instantiation").equals(type)) { + action = "offline"; + } else if(("scale").equals(type)) { + action = "scaleIn"; + } + } + + return action; + } + + private int getDiskQuantity(JSONObject volumeObj) { + int disk = 0; + if(volumeObj.containsKey("vol_type")) { + if("local_volume".equals(volumeObj.getString("vol_type"))) { + disk = Integer.parseInt(volumeObj.getString("vol_size")); + } + } else if(volumeObj.containsKey("storage_type") && "local_image".equals(volumeObj.getString("storage_type"))) { + + disk = Integer.parseInt(volumeObj.getString("disk_size")); + + } + return disk; + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/AuthRoa.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/AuthRoa.java new file mode 100644 index 00000000..445dd619 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/AuthRoa.java @@ -0,0 +1,151 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.rest; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.openo.nfvo.vnfmadapter.common.VnfmJsonUtil; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.constant.ParamConstants; +import org.openo.nfvo.vnfmadapter.service.process.AuthMgr; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * Provide interfaces for authInfo + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 24, 2016 + */ +@Path("/rest/plat/smapp/v1") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class AuthRoa { + + private static final Logger LOG = LoggerFactory.getLogger(AuthRoa.class); + + private AuthMgr authMgr; + + public void setAuthMgr(AuthMgr authMgr) { + this.authMgr = authMgr; + } + + /** + * Provide interface for add authInfo + * <br/> + * + * @param context + * @return + * @since NFVO 0.5 + */ + @PUT + @Path("/oauth/token") + public String authToken(@Context HttpServletRequest context, @Context HttpServletResponse resp) { + LOG.warn("function=login, msg=enter to get token."); + JSONObject subJsonObject = VnfmJsonUtil.getJsonFromContexts(context); + LOG.warn("subJsonObject: {}", subJsonObject); + + if(null == subJsonObject) { + LOG.error("function=login, msg=params are insufficient"); + String resultStr = "Login params insufficient"; + resp.setStatus(Constant.HTTP_BAD_REQUEST); + + return resultStr; + } + + JSONObject authResult = authMgr.authToken(subJsonObject); + LOG.warn("authResult: {}", authResult); + if(authResult.getInt("retCode") == Constant.REST_SUCCESS) { + JSONObject data = authResult.getJSONObject("data"); + + resp.setStatus(Constant.HTTP_OK); + // resp.setHeader("accessSession", data.getString("accessSession")); + return data.toString();// String.format(ParamConstants.GET_TOKEN_SUC_RESP, + // data.getString("userName"), + // data.getString("userName"), data.getString("roaRand")); + } else if(authResult.getInt("retCode") == Constant.HTTP_INNERERROR) { + Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(authResult.getString("data")).build(); + + return String.format(ParamConstants.GET_TOKEN_FAIL_RESP, authResult.getString("data")); + } else { + Response.status(Response.Status.UNAUTHORIZED).entity(authResult.getString("data")).build(); + + return String.format(ParamConstants.GET_TOKEN_FAIL_RESP, authResult.getString("data")); + } + } + + /** + * Provide interface for delete authInfo + * <br/> + * + * @param context + * @param userName + * @param roarand + * @return + * @since NFVO 0.5 + */ + @DELETE + @Path("/auth/tokens/{userName}/{roarand}") + public String delAuthToken(@Context HttpServletRequest context, @PathParam("userName") String userName, + @PathParam("roarand") String roarand, @Context HttpServletResponse resp) { + LOG.warn("function=logout, msg=enter to logout"); + JSONObject resultJson = new JSONObject(); + + resultJson.put("Information", "Operation success"); + resp.setStatus(Constant.HTTP_NOCONTENT); + LOG.warn("function=logout, msg=end to logout"); + return resultJson.toString(); + } + + /** + * Provide interface for handshake authInfo + * <br/> + * + * @param context + * @param roattr + * @return + * @since NFVO 0.5 + */ + @GET + @Path("/nfvo/shakehand") + public String shakehand(@Context HttpServletRequest context, @QueryParam("roattr") String roattr, + @Context HttpServletResponse resp) { + JSONObject resultJson = new JSONObject(); + resultJson.put("status", "running"); + resultJson.put("description", "Operation success"); + resp.setStatus(Constant.HTTP_OK); + + return resultJson.toString(); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/SwaggerRoa.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/SwaggerRoa.java new file mode 100644 index 00000000..5dfd290b --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/SwaggerRoa.java @@ -0,0 +1,49 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.rest; + +import java.io.IOException; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +import org.apache.commons.io.IOUtils; + +/** + * Swagger API Doc.<br/> + * + * @author + * @version NFVO 0.5 Oct 24, 2016 + */ +@Path("/openoapi/hwvnfm/v1") +@Produces({MediaType.APPLICATION_JSON}) +public class SwaggerRoa { + /** + * API doc. + * @param filename + * @return + * @throws IOException + */ + @GET + @Path("/swagger.json") + public String apidoc() throws IOException{ + ClassLoader classLoader = getClass().getClassLoader(); + return IOUtils.toString(classLoader.getResourceAsStream("swagger.json")); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/VnfAdapterResourceRoa.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/VnfAdapterResourceRoa.java new file mode 100644 index 00000000..138e284e --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/VnfAdapterResourceRoa.java @@ -0,0 +1,68 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.rest; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +import org.openo.nfvo.vnfmadapter.service.adapter.impl.AdapterResourceManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + + +/** + * Provide interfaces of resource for VNFM. + * <br/> + * + * @author + * @version NFVO 0.5 Aug 24, 2016 + */ +@Path("/rest/v2/computeservice/getAllCloud") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class VnfAdapterResourceRoa { + + private static final Logger LOG = LoggerFactory.getLogger(VnfAdapterResourceRoa.class); + + + /** + * Provide function of grant resource. + * <br/> + * + * @param context + * @return + * @since NFVO 0.5 + */ + @GET + public String getAllCloudInfo(@Context HttpServletRequest context) { + LOG.info("function=getAllCloudInfo, msg=getAllCloudInfo resource"); + + //Find a way to get url and pass it getAllCloud(); //NOSONAR + + AdapterResourceManager arm = new AdapterResourceManager(); + JSONObject resultObj = arm.getAllCloud("",""); + + return resultObj.getString("vim_id"); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/VnfResourceRoa.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/VnfResourceRoa.java new file mode 100644 index 00000000..ad7663e8 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/VnfResourceRoa.java @@ -0,0 +1,105 @@ +/* + * Copyright 2016-2017 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.nfvo.vnfmadapter.service.rest; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +import org.openo.nfvo.vnfmadapter.common.VnfmJsonUtil; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.process.VnfResourceMgr; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * Provide interfaces of resource for VNFM. + * <br/> + * + * @author + * @version NFVO 0.5 Aug 24, 2016 + */ +@Path("/rest/vnfmmed/csm/v2/vapps") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class VnfResourceRoa { + + private static final Logger LOG = LoggerFactory.getLogger(VnfResourceRoa.class); + + private VnfResourceMgr vnfResourceMgr; + + public void setVnfResourceMgr(VnfResourceMgr vnfResourceMgr) { + this.vnfResourceMgr = vnfResourceMgr; + } + + /** + * Provide function of grant resource. + * <br/> + * + * @param context + * @param vnfId + * @return + * @since NFVO 0.5 + */ + @PUT + @Path("/instances/{vnfId}/grant") + public String grantVnfRes(@Context HttpServletRequest context, @PathParam("vnfId") String vnfId) { + LOG.info("function=grantVnfRes, msg=enter to grant vnf resource."); + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + + JSONObject dataObject = VnfmJsonUtil.getJsonFromContexts(context); + LOG.info("function=grantVnfRes, dataObject: {}", dataObject); + /*if(null == dataObject) { + LOG.error("function=grantVnfRes, msg=param error"); + restJson.put("data", "Params error"); + return restJson.toString(); + } + + JSONObject grantObj = dataObject.getJSONObject("grant"); + + if(null == grantObj) { + LOG.error("function=grantVnfRes, msg=param error"); + restJson.put("data", "Grant param error"); + return restJson.toString(); + } + + String vnfmId = grantObj.getString("project_id"); + + JSONObject resultObj = vnfResourceMgr.grantVnfResource(grantObj, vnfId, vnfmId);*/ + JSONObject res = new JSONObject(); + res.put("msg","grant success"); + return res.toString(); + } + + @PUT + @Path("/lifecycle_changes_notification") + public String notify(@Context HttpServletRequest context) { + LOG.info("function=notify, msg=enter to notify vnf resource"); + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_SUCCESS); + + return restJson.toString(); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/VnfRoa.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/VnfRoa.java new file mode 100644 index 00000000..c68cb61c --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/VnfRoa.java @@ -0,0 +1,286 @@ +/* + * Copyright 2016-2017 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.nfvo.vnfmadapter.service.rest; + +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +import org.apache.commons.collections.map.UnmodifiableMap; +import org.apache.commons.lang3.StringUtils; +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.nfvo.vnfmadapter.common.VnfmJsonUtil; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.process.VnfMgr; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * Provide interfaces for instantiate or terminate VNF. + * <br/> + * + * @author + * @version NFVO 0.5 Aug 24, 2016 + */ +@SuppressWarnings("unchecked") +@Path("/openoapi/hwvnfm/v1") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class VnfRoa { + + private static final Logger LOG = LoggerFactory.getLogger(VnfRoa.class); + + private VnfMgr vnfMgr; + + private static Map<String, String> PROGRESSITEM; + + private static Map<String, String> JOBSTATUSITEM; + + static { + Map<String, String> map = new HashMap<>(); + map.put("Building", "50"); + map.put("Active", "100"); + map.put("Stopped", "50"); + map.put("Error", "100"); + PROGRESSITEM = UnmodifiableMap.decorate(map); + + map = new HashMap<>(); + map.put("Building", "processing"); + map.put("Active", "finished"); + map.put("Stopped", "processing"); + map.put("Error", "error"); + JOBSTATUSITEM = UnmodifiableMap.decorate(map); + } + + public void setVnfMgr(VnfMgr vnfMgr) { + this.vnfMgr = vnfMgr; + } + + /** + * Scale VNF + * + * @param context + * * { + * "vnfInstanceId":"5", + * "type":"SCALE_OUT", + * "aspectId":"101", + * "numberOfSteps":"1", + * "additionalParam":{} + * } + * @param resp + * @param vnfmId + * @return + * { + * "jobId":"1" + * } + * @throws ServiceException + */ + @POST + @Path("/{vnfmId}/vnfs/{vnfInstanceId}/scale") + public String scaleVnf(@Context HttpServletRequest context, @Context HttpServletResponse resp, + @PathParam("vnfmId") String vnfmId, @PathParam("vnfInstanceId") String vnfInstanceId) + throws ServiceException { + JSONObject jsonObject = VnfmJsonUtil.getJsonFromContexts(context); + LOG.info("function=scaleVNF, msg=enter to scale a vnf. request body:" + jsonObject); + JSONObject result = new JSONObject(); + String msg = ""; + if(null == jsonObject) { + msg = "the parameters do not meet the requirements,please check it!"; + LOG.error("function=scalVnf," + msg); + resp.setStatus(Constant.HTTP_NOT_ACCEPTABLE); + result.put("msg", msg); + return result.toString(); + } + + result = vnfMgr.scaleVNF(jsonObject, vnfmId, vnfInstanceId); + LOG.info("function=scaleVNF,result=" + result.toString()); + if(result.getInt(Constant.RETCODE) == Constant.REST_FAIL) { + LOG.error("function=scaleVNF, msg=scaleVnf fail"); + resp.setStatus(Constant.HTTP_INNERERROR); + return result.toString(); + } + return JSONObject.fromObject(result.getJSONObject("data")).toString(); + } + + /** + * Provide function for instantiate VNF + * <br/> + * + * @param context + * @param resp + * @param vnfmId + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + @POST + @Path("/{vnfmId}/vnfs") + public String addVnf(@Context HttpServletRequest context, @Context HttpServletResponse resp, + @PathParam("vnfmId") String vnfmId) throws ServiceException { + LOG.warn("function=addVnf, msg=enter to add a vnf"); + JSONObject subJsonObject = VnfmJsonUtil.getJsonFromContexts(context); + JSONObject restJson = new JSONObject(); + + if(null == subJsonObject) { + LOG.error("function=addVnf, msg=params are insufficient"); + resp.setStatus(Constant.HTTP_INNERERROR); + return restJson.toString(); + } + LOG.info("addVnf request info from (LCM):" + subJsonObject); + restJson = vnfMgr.addVnf(subJsonObject, vnfmId); + + if(restJson.getInt(Constant.RETCODE) == Constant.REST_FAIL) { + LOG.error("function=addVnf, msg=addvnf fail"); + resp.setStatus(Constant.HTTP_INNERERROR); + return restJson.toString(); + } + + return JSONObject.fromObject(restJson.getJSONObject("data")).toString(); + } + + /** + * Provide function for terminate VNF + * <br/> + * + * @param vnfmId + * @param resp + * @param vnfInstanceId + * @param context + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + @POST + @Path("/{vnfmId}/vnfs/{vnfInstanceId}/terminate") + public String delVnf(@PathParam("vnfmId") String vnfmId, @Context HttpServletResponse resp, + @PathParam("vnfInstanceId") String vnfInstanceId, @Context HttpServletRequest context) + throws ServiceException { + LOG.warn("function=delVnf, msg=enter to delete a vnf: vnfInstanceId: {}, vnfmId: {}", vnfInstanceId, vnfmId); + JSONObject vnfObject = VnfmJsonUtil.getJsonFromContexts(context); + JSONObject restJson = new JSONObject(); + + if(StringUtils.isEmpty(vnfInstanceId) || StringUtils.isEmpty(vnfmId)) { + resp.setStatus(Constant.HTTP_INNERERROR); + return restJson.toString(); + } + + restJson = vnfMgr.deleteVnf(vnfInstanceId, vnfmId, vnfObject); + if(restJson.getInt(Constant.RETCODE) == Constant.REST_FAIL) { + LOG.error("function=delVnf, msg=delVnf fail"); + resp.setStatus(Constant.HTTP_INNERERROR); + return restJson.toString(); + } + + return JSONObject.fromObject(restJson.getJSONObject("data")).toString(); + } + + /** + * Provide function for get VNF + * <br/> + * + * @param vnfmId + * @param resp + * @param vnfInstanceId + * @param context + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + @GET + @Path("/{vnfmId}/vnfs/{vnfInstanceId}") + public String getVnf(@PathParam("vnfmId") String vnfmId, @Context HttpServletResponse resp, + @PathParam("vnfInstanceId") String vnfInstanceId, @Context HttpServletRequest context) + throws ServiceException { + LOG.warn("function=getVnf, msg=enter to get a vnf: vnfInstanceId: {}, vnfmId: {}", vnfInstanceId, vnfmId); + JSONObject restJson = new JSONObject(); + + if(StringUtils.isEmpty(vnfInstanceId) || StringUtils.isEmpty(vnfmId)) { + resp.setStatus(Constant.HTTP_INNERERROR); + return restJson.toString(); + } + + restJson = vnfMgr.getVnf(vnfInstanceId, vnfmId); + if(restJson.getInt(Constant.RETCODE) == Constant.REST_FAIL) { + LOG.error("function=getVnf, msg=getVnf fail"); + resp.setStatus(Constant.HTTP_INNERERROR); + return restJson.toString(); + } + + restJson.remove(Constant.RETCODE); + return restJson.toString(); + } + + /** + * Provide function for get job + * <br/> + * + * @param jobId + * @param vnfmId + * @param resp + * @param responseId + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + @GET + @Path("/{vnfmId}/jobs/{jobId}") + public String getJob(@PathParam("jobId") String jobId, @PathParam("vnfmId") String vnfmId, + @Context HttpServletResponse resp, @QueryParam("@responseId") String responseId) throws ServiceException { + LOG.warn("function=getJob, msg=enter to get a job: jobId: {}", jobId); + JSONObject restJson = new JSONObject(); + + if(StringUtils.isEmpty(jobId) || StringUtils.isEmpty(vnfmId)) { + resp.setStatus(Constant.HTTP_INNERERROR); + return restJson.toString(); + } + + restJson = vnfMgr.getJob(jobId, vnfmId); + if(restJson.getInt(Constant.RETCODE) == Constant.REST_FAIL) { + LOG.error("function=getJob, msg=getJob fail"); + resp.setStatus(Constant.HTTP_INNERERROR); + return restJson.toString(); + } + + return getJobBody(restJson); + } + + private String getJobBody(JSONObject restJson) { + JSONObject responseJson = new JSONObject(); + JSONObject jobInfoJson = new JSONObject(); + JSONObject retJson = restJson.getJSONArray("data").getJSONObject(0); + jobInfoJson.put("jobId", retJson.getString("id")); + responseJson.put("progress", PROGRESSITEM.get(retJson.getString(Constant.STATUS))); + responseJson.put("status", JOBSTATUSITEM.get(retJson.getString(Constant.STATUS))); + responseJson.put("errorCode", "null"); + responseJson.put("responseId", PROGRESSITEM.get(retJson.getString(Constant.STATUS))); + jobInfoJson.put("responsedescriptor", responseJson); + return jobInfoJson.toString(); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/ExceptionMessage.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/ExceptionMessage.java new file mode 100644 index 00000000..7b4738dc --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/ExceptionMessage.java @@ -0,0 +1,64 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.rest.exceptionmapper; + +import org.apache.http.HttpStatus; + +/** + * Exception response model.<br> + * + * @author + * @version NFVO 0.5 Sep 27, 2016 + */ +public class ExceptionMessage { + + private String errorCode = "unknown.error"; + + private int httpCode = HttpStatus.SC_INTERNAL_SERVER_ERROR; + + private String message; + + @Override + public String toString() { + return "Error {errorCode=" + this.errorCode + ", httpCode=" + this.httpCode + ", message=" + + this.message + "}"; + } + + public String getErrorCode() { + return this.errorCode; + } + + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } + + public String getMessage() { + return this.message; + } + + public void setMessage(String message) { + this.message = message; + } + + public int getHttpCode() { + return this.httpCode; + } + + public void setHttpCode(int httpCode) { + this.httpCode = httpCode; + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/GenericExceptionMapper.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/GenericExceptionMapper.java new file mode 100644 index 00000000..25eb8c24 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/GenericExceptionMapper.java @@ -0,0 +1,41 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.rest.exceptionmapper; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +/** + * Generic exception response provider.<br> + * + * + * @author + * @version NFVO 0.5 Sep 27, 2016 + */ +@Provider +public class GenericExceptionMapper implements ExceptionMapper<Exception>{ + + @Override + public Response toResponse(Exception exception) { + ExceptionMessage message = new ExceptionMessage(); + message.setMessage(exception.getMessage()); + return Response.status(message.getHttpCode()).type( + MediaType.APPLICATION_JSON).entity(message).build(); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/ServiceExceptionMapper.java b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/ServiceExceptionMapper.java new file mode 100644 index 00000000..957c0d40 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/ServiceExceptionMapper.java @@ -0,0 +1,45 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.rest.exceptionmapper; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +import org.openo.baseservice.remoteservice.exception.ServiceException; + +/** + * ServiceException response provider.<br> + * + * @author + * @version NFVO 0.5 Sep 27, 2016 + */ +@Provider +public class ServiceExceptionMapper implements ExceptionMapper<ServiceException>{ + + @Override + public Response toResponse(ServiceException exception) { + ExceptionMessage message = new ExceptionMessage(); + message.setErrorCode(exception.getId()); + message.setHttpCode(exception.getHttpCode()); + message.setMessage(exception.getMessage()); + return Response.status(message.getHttpCode()). + type(MediaType.APPLICATION_JSON).entity(message).build(); + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/resources/log4j.properties b/huawei/vnfmadapter/VnfmadapterService/service/src/main/resources/log4j.properties new file mode 100644 index 00000000..833c7a77 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/resources/log4j.properties @@ -0,0 +1,23 @@ +############################################################################### +# Copyright 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. +############################################################################### +log4j.rootLogger=INFO,root +log4j.appender.root.Append=true +log4j.appender.root.File=${catalina.base}/logs/vnfmadapterservice.log +log4j.appender.root.layout.ConversionPattern=%d %-5p [%t][%X{moduleID}][%C %L] %m%n +log4j.appender.root.layout=org.apache.log4j.PatternLayout +log4j.appender.root.MaxBackupIndex=50 +log4j.appender.root.MaxFileSize=20MB +log4j.appender.root=org.apache.log4j.RollingFileAppender
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/resources/mybatis/mysql/vnfmadapter.xml b/huawei/vnfmadapter/VnfmadapterService/service/src/main/resources/mybatis/mysql/vnfmadapter.xml new file mode 100644 index 00000000..d9b72958 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/resources/mybatis/mysql/vnfmadapter.xml @@ -0,0 +1,77 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2016-2017, 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. + --> +<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> +<mapper namespace="org.openo.nfvo.vnfmadapter.service.mapper.VnfmMapper"> + <resultMap type="org.openo.nfvo.vnfmadapter.service.entity.Vnfm" + id="VnfmResultMap"> + <result property="id" javaType="String" column="ID" jdbcType="VARCHAR" /> + <result property="version" javaType="String" column="VERSION" jdbcType="VARCHAR" /> + <result property="vnfdId" javaType="String" column="VNFDID" jdbcType="VARCHAR" /> + <result property="vnfPackageId" javaType="String" column="VNFPACKAGEID" jdbcType="VARCHAR" /> + </resultMap> + + <sql id="Base_Column_List"> + ID, VERSION, VNFDID, VNFPACKAGEID + </sql> + + <insert id="insertVnfm" parameterType="org.openo.nfvo.vnfmadapter.service.entity.Vnfm"> + INSERT INTO VNFM (ID, VERSION, VNFDID, VNFPACKAGEID) + VALUES(#{id},#{version},#{vnfdId},#{vnfPackageId}) + </insert> + + <update id="updateVnfm" parameterType="org.openo.nfvo.vnfmadapter.service.entity.Vnfm"> + UPDATE VNFM + <set> + <if test="id != null"> + id=#{id}, + </if> + <if test="version != null"> + version=#{version}, + </if> + <if test="vnfdId != null"> + vnfdId=#{vnfdId}, + </if> + <if test="vnfPackageId != null"> + vnfPackageId=#{vnfPackageId}, + </if> + </set> + WHERE ID=#{id} + </update> + + <delete id="deleteVnfm" parameterType="String"> + DELETE FROM VNFM WHERE ID = #{id} + </delete> + + <select id="indexVnfms" resultMap="VnfmResultMap" > + select + <include refid="Base_Column_List" /> + FROM VNFM + ORDER BY NAME DESC + <if test="offset!=0 and pageSize!=0 "> + limit ${offset}, ${pageSize} + </if> + </select> + + <select id="getCountVnfms" parameterType="String" resultType="java.lang.Integer"> + SELECT COUNT(*) FROM VNFM + </select> + + <select id="getVnfmById" parameterType="java.lang.String" resultType="org.openo.nfvo.vnfmadapter.service.entity.Vnfm"> + SELECT * FROM VNFM + WHERE id = #{id} + </select> +</mapper>
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/resources/registerService.properties b/huawei/vnfmadapter/VnfmadapterService/service/src/main/resources/registerService.properties new file mode 100644 index 00000000..b7520c0f --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/resources/registerService.properties @@ -0,0 +1,23 @@ +############################################################################### +# Copyright 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. +############################################################################### +serviceName=hw-vnfm +version=v1 +url=/openoapi/hw-vnfm/v1 +protocol=REST +visualRange=1 +ip=10.229.33.207 +port=8988 +ttl=0
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/resources/spring/Vnfmadapter/services.xml b/huawei/vnfmadapter/VnfmadapterService/service/src/main/resources/spring/Vnfmadapter/services.xml new file mode 100644 index 00000000..fb73cd4b --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/resources/spring/Vnfmadapter/services.xml @@ -0,0 +1,117 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Copyright (c) 2016-2017, 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. + --> + +<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:osgi="http://www.springframework.org/schema/osgi" xmlns:osgix="http://www.springframework.org/schema/osgi-compendium" + xmlns:ctx="http://www.springframework.org/schema/context" + xmlns:jaxrs="http://cxf.apache.org/jaxrs" + xmlns:http-conf="http://cxf.apache.org/transports/http/configuration" + xsi:schemaLocation=" + http://www.springframework.org/schema/beans + http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/osgi + http://www.springframework.org/schema/osgi/spring-osgi.xsd + http://www.springframework.org/schema/context + http://www.springframework.org/schema/context/spring-context.xsd + http://www.springframework.org/schema/osgi-compendium + http://www.springframework.org/schema/osgi-compendium/spring-osgi-compendium.xsd + http://cxf.apache.org/jaxrs + http://cxf.apache.org/schemas/jaxrs.xsd + http://cxf.apache.org/transports/http/configuration + http://cxf.apache.org/schemas/configuration/http-conf.xsd + http://www.springframework.org/schema/aop + http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "> + + <!-- these are included in the dependency jar --> + <import resource="classpath:META-INF/cxf/cxf.xml" /> + <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/> + + <bean id="jsonProvider" class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" /> + + <bean id="source" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> + <property name="driverClassName" value="com.mysql.jdbc.Driver"/> + <property name="url" value="jdbc:mysql://localhost:3306/vnfmdb" /> + <property name="username" value="root"/> + <property name="password" value="rootpass"/> + </bean> + + <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> + <property name="dataSource" ref="source" /> + <property name="mapperLocations" value="classpath*:mybatis/mysql/*.xml" /> + <!-- <property name="configLocation" value="classpath:mybatis-config.xml" /> --> + </bean> + + <bean id="session" class="org.mybatis.spring.SqlSessionTemplate"> + <constructor-arg index="0" ref="sessionFactory" /> + </bean> + + + <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> + <property name="dataSource" ref="source" /> + </bean> + + <bean id="vnfmDao" + class="org.openo.nfvo.vnfmadapter.service.dao.impl.VnfmDaoImpl"> + <property name="session" ref="session"></property> + </bean> + + <bean id="vnfMgr" class="org.openo.nfvo.vnfmadapter.service.process.VnfMgr"> + <property name="vnfmDao" ref="vnfmDao"></property> + </bean> + + <bean id="VnfRoa" class="org.openo.nfvo.vnfmadapter.service.rest.VnfRoa"> + <property name="vnfMgr" ref="vnfMgr"></property> + </bean> + + <bean id="vnfResourceMgr" + class="org.openo.nfvo.vnfmadapter.service.process.VnfResourceMgr"> + </bean> + + <bean id="VnfResourceRoa" class="org.openo.nfvo.vnfmadapter.service.rest.VnfResourceRoa"> + <property name="vnfResourceMgr" ref="vnfResourceMgr"></property> + </bean> + + <bean id="authMgr" class="org.openo.nfvo.vnfmadapter.service.process.AuthMgr" /> + + <bean id="AuthRoa" class="org.openo.nfvo.vnfmadapter.service.rest.AuthRoa"> + <property name="authMgr" ref="authMgr"></property> + </bean> + + <bean id="VnfAdaResRoa" class="org.openo.nfvo.vnfmadapter.service.rest.VnfAdapterResourceRoa"> + </bean> + + <bean id="SwaggerRoa" class="org.openo.nfvo.vnfmadapter.service.rest.SwaggerRoa"></bean> + + <!-- bean id="registerMgr" class="org.openo.nfvo.vnfmadapter.service.process.RegisterMgr" + init-method="register" destroy-method="unRegister"> + </bean--> + + <jaxrs:server id="restContainer" address="/"> + <jaxrs:serviceBeans> + <ref bean="AuthRoa" /> + <ref bean="VnfResourceRoa" /> + <ref bean="VnfRoa" /> + <ref bean="VnfAdaResRoa" /> + <ref bean="SwaggerRoa" /> + </jaxrs:serviceBeans> + <jaxrs:providers> + <ref bean="jsonProvider" /> + <bean class="org.openo.nfvo.vnfmadapter.service.rest.exceptionmapper.ServiceExceptionMapper" /> + <bean class="org.openo.nfvo.vnfmadapter.service.rest.exceptionmapper.GenericExceptionMapper" /> + </jaxrs:providers> + </jaxrs:server> +</beans> diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/resources/spring/Vnfmadapter/svc_register.xml b/huawei/vnfmadapter/VnfmadapterService/service/src/main/resources/spring/Vnfmadapter/svc_register.xml new file mode 100644 index 00000000..8fa5e0d2 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/resources/spring/Vnfmadapter/svc_register.xml @@ -0,0 +1,43 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Copyright 2016-2017 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. + --> + +<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:aop="http://www.springframework.org/schema/aop" + xmlns:osgi="http://www.springframework.org/schema/osgi" xmlns:osgix="http://www.springframework.org/schema/osgi-compendium" + xmlns:ctx="http://www.springframework.org/schema/context" + xmlns:jaxrs="http://cxf.apache.org/jaxrs" + xmlns:http-conf="http://cxf.apache.org/transports/http/configuration" + xsi:schemaLocation=" + http://www.springframework.org/schema/beans + http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/osgi + http://www.springframework.org/schema/osgi/spring-osgi.xsd + http://www.springframework.org/schema/context + http://www.springframework.org/schema/context/spring-context.xsd + http://www.springframework.org/schema/osgi-compendium + http://www.springframework.org/schema/osgi-compendium/spring-osgi-compendium.xsd + http://cxf.apache.org/jaxrs + http://cxf.apache.org/schemas/jaxrs.xsd + http://cxf.apache.org/transports/http/configuration + http://cxf.apache.org/schemas/configuration/http-conf.xsd + http://www.springframework.org/schema/aop + http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> + <bean class="org.openo.nfvo.vnfmadapter.service.activator.RoaVnfmServicePostProcessor"></bean> + <bean class="org.openo.nfvo.vnfmadapter.service.api.internalsvc.impl.VnfmAdapterMgrService"></bean> + <bean class="org.openo.nfvo.vnfmadapter.service.activator.RoaVnfmService2DriverMgr"></bean> + <bean class="org.openo.nfvo.vnfmadapter.service.api.internalsvc.impl.VnfmAdapter2DriverMgrService"></bean> +</beans>
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/resources/swagger.json b/huawei/vnfmadapter/VnfmadapterService/service/src/main/resources/swagger.json new file mode 100644 index 00000000..aa3bf1f6 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/resources/swagger.json @@ -0,0 +1,608 @@ +{ + "swagger": "2.0", + "info": { + "title": "Huawei VNFM Driver API", + "description": "VNF service provider.", + "version": "1.0.0" + }, + "tags": [ + { + "name": "Huawei VNFM Driver services" + } + ], + "basePath": "/openoapi", + "paths": { + "/{vnfmtype}/v1/{vnfmid}/vnfs": { + "post": { + "summary": "Instantiate VNF", + "description": "Add VNF", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "parameters": [ + { + "name": "vnfmtype", + "in": "path", + "description": "vnfm type", + "required": true, + "type": "string" + }, + { + "name": "vnfmid", + "in": "path", + "description": "vnfm id", + "required": true, + "type": "string" + }, + { + "in": "body", + "name": "vnf", + "description": "Provide required properties of VNF.", + "required": true, + "schema": { + "$ref": "#/definitions/Vnf" + } + } + ], + "responses": { + "200": { + "description": "VNF Response", + "schema": { + "$ref": "#/definitions/VnfResponse" + } + }, + "401": { + "description": "Unauthorized" + }, + "404": { + "description": "VNF Not Found" + }, + "500": { + "description": "VNF service failed to process the request", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, + "/{vnfmtype}/v1/{vnfmid}/vnfs/{vnfInstanceId}/terminate": { + "post": { + "summary": "Terminate VNF", + "description": "Delete VNF", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "parameters": [ + { + "name": "vnfmtype", + "in": "path", + "description": "vnfm type", + "required": true, + "type": "string" + }, + { + "name": "vnfmid", + "in": "path", + "description": "vnfm id", + "required": true, + "type": "string" + }, + { + "name": "vnfInstanceId", + "in": "path", + "description": "vnfm instance id", + "required": true, + "type": "string" + }, + { + "in": "body", + "name": "vnfTerminate", + "description": "Provide required properties of VNF.", + "required": true, + "schema": { + "$ref": "#/definitions/VnfTerminate" + } + } + ], + "responses": { + "200": { + "description": "VNF Response", + "schema": { + "$ref": "#/definitions/VnfTerminateResponse" + } + }, + "401": { + "description": "Unauthorized" + }, + "404": { + "description": "VNF Not Found" + }, + "500": { + "description": "VNF service failed to process the request", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, + "/{vnfmtype}/v1/{vnfmid}/vnfs/{vnfInstanceId}": { + "get": { + "summary": "Query VNF", + "description": "Get VNF Details", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "parameters": [ + { + "name": "vnfmtype", + "in": "path", + "description": "vnfm type", + "required": true, + "type": "string" + }, + { + "name": "vnfmid", + "in": "path", + "description": "vnfm id", + "required": true, + "type": "string" + }, + { + "name": "vnfInstanceId", + "in": "path", + "description": "vnfm instance id", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "VNF Response", + "schema": { + "$ref": "#/definitions/VnfInfoResponse" + } + }, + "401": { + "description": "Unauthorized" + }, + "404": { + "description": "VNF Not Found" + }, + "500": { + "description": "VNF service failed to process the request", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, + "/{vnfmtype}/v1/jobs/{jobid}": { + "get": { + "summary": "Get VNF operational status", + "description": "VNF operational status", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "parameters": [ + { + "name": "vnfmtype", + "in": "path", + "description": "vnfm type", + "required": true, + "type": "string" + }, + { + "name": "jobid", + "in": "path", + "description": "jobid", + "required": true, + "type": "string" + }, + { + "name": "responseId", + "in": "query", + "description": "vnfm response id", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "VNF Response", + "schema": { + "$ref": "#/definitions/VnfStatusResponse" + } + }, + "401": { + "description": "Unauthorized" + }, + "404": { + "description": "VNF Not Found" + }, + "500": { + "description": "VNF service failed to process the request", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + } + }, + "definitions": { + "VnfStatusResponse": { + "type": "object", + "description": "Operational Status Response.", + "required": [ + "jobId", + "responseDescriptor", + "status", + "progress", + "statusDescription", + "errorCode", + "responseId", + "responseHistoryList" + ], + "properties": { + "jobId": { + "type": "string", + "description": "Job ID" + }, + "responseDescriptor": { + "type": "string", + "description": "Including vnfStatus,statusDescription,errorCode,progress,responseHistoryList,responseId." + }, + "status": { + "type": "string", + "description": "JOB status started processing finished error" + }, + "progress": { + "type": "integer", + "description": "Progress (1 - 100)" + }, + "statusDescription": { + "type": "string", + "description": "Progress Description" + }, + "errorCode": { + "type": "integer", + "description": "Errorcode" + }, + "responseId": { + "type": "integer", + "description": "Response Identifier" + }, + "responseHistoryList": { + "type": "array", + "items": { + "$ref": "#/definitions/HistoryDetails" + } + } + } + }, + "HistoryDetails": { + "type": "object", + "description": "InitiateVnfResponse.", + "required": [ + "vnfStatus", + "statusDescription", + "errorCode", + "progress", + "responseId" + ], + "properties": { + "vnfStatus": { + "type": "string", + "description": "Vnf Job Status." + }, + "statusDescription": { + "type": "string", + "description": "Progress Description." + }, + "errorCode": { + "type": "integer", + "description": "Error code." + }, + "progress": { + "type": "integer", + "description": "progress (1-100)." + }, + "responseId": { + "type": "integer", + "description": "Response Identifier." + } + } + }, + "VnfResponse": { + "type": "object", + "description": "InitiateVnfResponse.", + "required": [ + "jobId", + "vnfInstanceId" + ], + "properties": { + "jobId": { + "type": "string", + "description": "Identifier of the VNF lifecycle operation occurrence." + }, + "vnfInstanceId": { + "type": "string", + "description": "Identifier of the VNF instance." + } + } + }, + "VnfTerminateResponse": { + "type": "object", + "description": "TerminateVnfResponse.", + "required": [ + "jobId" + ], + "properties": { + "jobId": { + "type": "string", + "description": "Identifier of the VNF lifecycle operation occurrence." + } + } + }, + "VnfInfoResponse": { + "type": "object", + "description": "The information items about the selected VNF instance(s) that are returned..", + "required": [ + "VnfInfo" + ], + "properties": { + "VnfInfo": { + "$ref": "#/definitions/VnfInfo" + } + } + }, + "VnfInfo": { + "type": "object", + "description": "The information items about the selected VNF instance(s) that are returned..", + "required": [ + "vnfInstanceId", + "vnfInstanceName", + "vnfInstanceDescription", + "vnfdId", + "vnfPackageId", + "version", + "vnfProvider", + "vnfType", + "vnfStatus" + ], + "properties": { + "vnfInstanceId": { + "type": "string", + "description": "VNF instance identifier." + }, + "vnfInstanceName": { + "type": "string", + "description": "VNF instance name." + }, + "vnfInstanceDescription": { + "type": "string", + "description": "Human-readable description of the VNF instance." + }, + "vnfdId": { + "type": "string", + "description": "Identifier of the VNFD on which the VNF instance is based." + }, + "vnfPackageId": { + "type": "string", + "description": "Identifier of the VNF Package used to manage the lifecycle of the VNF instance." + }, + "version": { + "type": "string", + "description": "Version of the VNF." + }, + "vnfProvider": { + "type": "string", + "description": "Name of the person or company providing the VNF." + }, + "vnfType": { + "type": "string", + "description": "VNF Application Type." + }, + "vnfStatus": { + "default": "active", + "enum": [ + "inactive", + "active" + ], + "description": "The instantiation state of the VNF. Possible values:INACTIVE (Vnf is terminated or not instantiated ), ACTIVE (Vnf is instantiated). [instantiationState]." + } + } + }, + "VnfTerminate": { + "type": "object", + "description": "Terminate VNF.", + "required": [ + "terminationType", + "gracefulTerminationTimeout" + ], + "properties": { + "terminationType": { + "default": "forceful", + "enum": [ + "forceful", + "graceful" + ], + "description": "Signals whether forceful or graceful termination is requested.." + }, + "gracefulTerminationTimeout": { + "type": "integer", + "format": "int32", + "description": "The time interval (second) to wait for the VNF to be taken out of service during graceful termination, before shutting down the VNF and releasing the resources." + } + } + }, + "Vnf": { + "type": "object", + "description": "VNF encapsulate an external IP for the given project in a domain. Each property description is provided with 1. required 2. update allowed 3. format. whenever its needs to be mentioned explicitly.", + "required": [ + "vnfInstanceName", + "vnfPackageId", + "vnfDescriptorId", + "flavourId", + "vnfInstanceDescription", + "extVirtualLink" + ], + "properties": { + "vnfInstanceName": { + "type": "string", + "description": "Human-readable name of the VNF instance to be created.." + }, + "vnfPackageId": { + "type": "string", + "description": "VNF packageId." + }, + "vnfDescriptorId": { + "type": "string", + "description": "Information sufficient to identify the VNF Descriptor which defines the VNF to be created." + }, + "flavourId": { + "type": "string", + "description": "verify." + }, + "vnfInstanceDescription": { + "type": "string", + "description": "Human-readable description of the VNF instance to be created." + }, + "extVirtualLink": { + "$ref": "#/definitions/ExtVirtualLinkData" + } + } + }, + "ExtVirtualLinkData": { + "type": "object", + "description": "References to external virtual links to connect the VNF to.", + "required": [ + "vlInstanceId", + "vim", + "networkId", + "cpdId" + ], + "properties": { + "vlInstanceId": { + "type": "string", + "description": "Identifier of the VL instance." + }, + "vim": { + "$ref": "#/definitions/VimInfo" + }, + "networkId": { + "type": "string", + "description": "The network UUID of network" + }, + "cpdId": { + "type": "string", + "description": "Identifier of the external CPD in VNFD" + } + } + }, + "VimInfo": { + "type": "object", + "description": "Information about the VIM that manages this resource.", + "required": [ + "vimInfoId", + "vimId", + "interfaceInfo", + "accessInfo", + "interfaceEndpoint" + ], + "properties": { + "vimInfoId": { + "type": "string", + "description": "The identifier of this VimInfo instance, for the purpose of referencing it from other information elements." + }, + "vimId": { + "type": "string", + "description": "The identifier of the VIM.." + }, + "interfaceInfo": { + "$ref": "#/definitions/interfaceInfo" + }, + "accessInfo": { + "$ref": "#/definitions/accessInfo" + }, + "interfaceEndpoint": { + "type": "string", + "description": "Information about the interface endpoint. An example is a URL." + } + } + }, + "interfaceInfo": { + "type": "object", + "description": "Information about the interface to the VIM, including VIM provider type, API version, and protocol type..", + "required": [ + "vimType", + "apiVersion", + "protocolType" + ], + "properties": { + "vimType": { + "type": "string", + "description": "vim" + }, + "apiVersion": { + "type": "string", + "description": "api version" + }, + "protocolType": { + "type": "string", + "description": "Type of the protocol" + } + } + }, + "accessInfo": { + "type": "object", + "description": "Authentication credentials for accessing the VIM. Examples may include those to support different authentication schemes, e.g., OAuth, Token, etc..", + "required": [ + "tenant", + "username", + "password" + ], + "properties": { + "tenant": { + "type": "string", + "description": "Tenant Name of tenant" + }, + "username": { + "type": "string", + "description": "Username for login" + }, + "password": { + "type": "string", + "description": "Password of login user" + } + } + }, + "Error": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } +}
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/main/webapp/WEB-INF/web.xml b/huawei/vnfmadapter/VnfmadapterService/service/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 00000000..eef98c0e --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,51 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Copyright 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. + --> + +<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee + http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> + <servlet> + <servlet-name>CXFServlet</servlet-name> + <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> + <load-on-startup>1</load-on-startup> + </servlet> + <servlet-mapping> + <servlet-name>CXFServlet</servlet-name> + <url-pattern>/*</url-pattern> + </servlet-mapping> + <listener> + <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> + </listener> + <context-param> + <param-name>contextConfigLocation</param-name> + <param-value>WEB-INF/classes/spring/Vnfmadapter/*.xml + </param-value> + </context-param> + + <session-config> + <session-timeout>10000000</session-timeout> + </session-config> + + <display-name>vnfmadapter-service</display-name> + + + <welcome-file-list> + <welcome-file>index.html</welcome-file> + </welcome-file-list> + +</web-app>
\ No newline at end of file diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/common/DownloadCsarManagerTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/common/DownloadCsarManagerTest.java new file mode 100644 index 00000000..85ac321e --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/common/DownloadCsarManagerTest.java @@ -0,0 +1,74 @@ +/* + * Copyright 2017 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.nfvo.vnfmadapter.common; + +import org.apache.http.HttpResponse; +import org.apache.http.ProtocolVersion; +import org.apache.http.StatusLine; +import org.apache.http.message.BasicHttpResponse; +import org.apache.http.message.BasicStatusLine; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; + +import javax.servlet.http.HttpServletRequest; + +/** + * Created by QuanZhong on 2017/3/17. + */ +public class DownloadCsarManagerTest { + + @Test + public void getFileNameTest(){ + ProtocolVersion version = new ProtocolVersion("HTTP",1,1); + StatusLine sl = new BasicStatusLine(version,200,"success"); + HttpResponse response = new BasicHttpResponse(sl); + response.setHeader("Content-Disposition","filename"); + DownloadCsarManager.getFileName(response); + } + + @Test + public void downloadTest(){ + DownloadCsarManager.download("http://www.baidu.com"); + DownloadCsarManager.download("http://www.baidu.com","/opt"); + DownloadCsarManager.getRandomFileName(); + } + @Test + public void getFilePath(){ + ProtocolVersion version = new ProtocolVersion("HTTP",1,1); + StatusLine sl = new BasicStatusLine(version,200,"success"); + HttpResponse response = new BasicHttpResponse(sl); + response.setHeader("Content-Disposition","filename"); + DownloadCsarManager.getFilePath(response); + } + @Test + public void testUnzip(){ + DownloadCsarManager.unzipCSAR("test.zip","/opt"); + } + + @Test + public void testJsonUtils(){ + MockHttpServletRequest req = new MockHttpServletRequest(); + req.setContent("[{'abc':123}]".getBytes()); + VnfmJsonUtil.getJsonFromContexts(req); + } + @Test + public void testJsonUtils2(){ + MockHttpServletRequest req = new MockHttpServletRequest(); + req.setContent("{'abc':123}".getBytes()); + VnfmJsonUtil.getJsonFromContexts(req); + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/common/FileUtil.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/common/FileUtil.java new file mode 100644 index 00000000..10f24353 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/common/FileUtil.java @@ -0,0 +1,50 @@ +/* + * Copyright 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.nfvo.vnfmadapter.common; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +public class FileUtil { + + public static String ReadFile(String path) { + File file = new File(path); + BufferedReader reader = null; + String laststr = ""; + try { + reader = new BufferedReader(new FileReader(file)); + String tempString = null; + while((tempString = reader.readLine()) != null) { + laststr = laststr + tempString; + } + reader.close(); + } catch(IOException e) { + e.printStackTrace(); + } finally { + if(reader != null) { + try { + reader.close(); + } catch(IOException e1) { + } + } + } + return laststr; + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/common/ResultRequestUtilTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/common/ResultRequestUtilTest.java new file mode 100644 index 00000000..1e8a9f3b --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/common/ResultRequestUtilTest.java @@ -0,0 +1,63 @@ +/* + * Copyright 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.nfvo.vnfmadapter.common; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.openo.nfvo.vnfmadapter.service.csm.connect.ConnectMgrVnfm; + +import mockit.Mock; +import mockit.MockUp; +import net.sf.json.JSONObject; + +public class ResultRequestUtilTest { + + @Test + public void callTestInternalError(){ + new MockUp<ConnectMgrVnfm>(){ + @Mock + public int connect(JSONObject vnfmObj) { + return 500; + } + }; + JSONObject vnfmObject = new JSONObject();; + String path = "http://localhost:8080"; + String methodName = "get"; + String paramsJson = ""; + JSONObject resp = ResultRequestUtil.call(vnfmObject, path, methodName, paramsJson); + assertTrue(resp.get("data").equals("connect fail.")); + } + + @Test + public void callTestConnectionErrot(){ + new MockUp<ConnectMgrVnfm>(){ + @Mock + public int connect(JSONObject vnfmObj) { + return 200; + } + }; + JSONObject vnfmObject = new JSONObject(); + vnfmObject.put("url", "/test/123"); + String path = "http://localhost:8080"; + String methodName = "get"; + String paramsJson = ""; + JSONObject resp = ResultRequestUtil.call(vnfmObject, path, methodName, paramsJson); + assertTrue(resp.get("data").equals("get connection error")); + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/common/VnfmUtilTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/common/VnfmUtilTest.java new file mode 100644 index 00000000..fa60eb48 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/common/VnfmUtilTest.java @@ -0,0 +1,113 @@ +/* + * Copyright 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.nfvo.vnfmadapter.common; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.common.servicetoken.VnfmRestfulUtil; + +import mockit.Mock; +import mockit.MockUp; +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; + +public class VnfmUtilTest { + + @Test + public void getVnfmByIdTestNullResp(){ + JSONObject resp = VnfmUtil.getVnfmById("1234"); + assertNull(resp); + } + + @Test + public void getVnfmByIdTestSuccess(){ + new MockUp<VnfmRestfulUtil>(){ + @Mock + public RestfulResponse getRemoteResponse(String url, String methodType, String params) { + RestfulResponse resp = new RestfulResponse(); + resp.setStatus(200); + return resp; + } + }; + JSONObject resp = VnfmUtil.getVnfmById("1234"); + assertNotNull(resp); + } + + @Test + public void getVnfmIdByIpTestNullResp(){ + String resp = VnfmUtil.getVnfmIdByIp("localhost"); + assertTrue("".equals(resp)); + } + + @Test + public void getVnfmIdByIpTestSuccess(){ + new MockUp<VnfmRestfulUtil>(){ + @Mock + public RestfulResponse getRemoteResponse(String url, String methodType, String params) { + RestfulResponse resp = new RestfulResponse(); + resp.setStatus(200); + JSONArray respArray = new JSONArray(); + JSONObject obj = new JSONObject(); + obj.put("url", "localhost"); + obj.put("vnfmId", "1234"); + respArray.add(obj); + resp.setResponseJson(respArray.toString()); + return resp; + } + }; + String resp = VnfmUtil.getVnfmIdByIp("localhost"); + assertTrue("1234".equals(resp)); + } + + @Test + public void getVnfmIdByIpTestSuccessInvalidIP(){ + new MockUp<VnfmRestfulUtil>(){ + @Mock + public RestfulResponse getRemoteResponse(String url, String methodType, String params) { + RestfulResponse resp = new RestfulResponse(); + resp.setStatus(200); + JSONArray respArray = new JSONArray(); + JSONObject obj = new JSONObject(); + obj.put("url", "127.0.0.1"); + obj.put("vnfmId", "1234"); + respArray.add(obj); + resp.setResponseJson(respArray.toString()); + return resp; + } + }; + String resp = VnfmUtil.getVnfmIdByIp("localhost"); + assertTrue("".equals(resp)); + } + @Test + public void getVnfmIdByIpTestSuccessEmptyResp(){ + new MockUp<VnfmRestfulUtil>(){ + @Mock + public RestfulResponse getRemoteResponse(String url, String methodType, String params) { + RestfulResponse resp = new RestfulResponse(); + resp.setStatus(200); + JSONArray respArray = new JSONArray(); + resp.setResponseJson(respArray.toString()); + return resp; + } + }; + String resp = VnfmUtil.getVnfmIdByIp("localhost"); + assertTrue("".equals(resp)); + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/common/servicetoken/HttpRestfulHelpTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/common/servicetoken/HttpRestfulHelpTest.java new file mode 100644 index 00000000..a50dde98 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/common/servicetoken/HttpRestfulHelpTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 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.nfvo.vnfmadapter.common.servicetoken; + +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; +import org.openo.baseservice.roa.util.restclient.Restful; + +/** + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 10, 2016 + */ +public class HttpRestfulHelpTest { + + @Test + public void testGetRestInstance() { + Restful rest = HttpRestfulHelp.getRestInstance(null, null); + assertNotNull(rest); + } + + @Test + public void testGetRestInstance1() { + HttpRestfulHelp.getRestInstance(null, null); + Restful rest = HttpRestfulHelp.getRestInstance(null, null); + assertNotNull(rest); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/common/servicetoken/VNFRestfulUtilTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/common/servicetoken/VNFRestfulUtilTest.java new file mode 100644 index 00000000..3da7a813 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/common/servicetoken/VNFRestfulUtilTest.java @@ -0,0 +1,322 @@ +/* + * Copyright 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.nfvo.vnfmadapter.common.servicetoken; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.testutils.JsonUtil; + +import mockit.Mock; +import mockit.MockUp; +import net.sf.json.JSONObject; + +/** + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 10, 2016 + */ +public class VNFRestfulUtilTest { + + @Test + public void getRestResByDefaultTestGet(){ + String path="http://localhost:8080"; + String methodNames = "get"; + JSONObject bodyParam = new JSONObject(); + bodyParam.put("id", "1234"); + RestfulResponse resp = VNFRestfulUtil.getRestResByDefault(path, methodNames, bodyParam); + assertNotNull(resp); + } + + @Test + public void getRestResByDefaultTestDelete(){ + String path="http://localhost:8080"; + String methodNames = "delete"; + JSONObject bodyParam = new JSONObject(); + bodyParam.put("id", "1234"); + RestfulResponse resp = VNFRestfulUtil.getRestResByDefault(path, methodNames, bodyParam); + assertNotNull(resp); + } + @Test + public void getRestResByDefaultTestPost(){ + String path="http://localhost:8080"; + String methodNames = "post"; + JSONObject bodyParam = new JSONObject(); + bodyParam.put("id", "1234"); + RestfulResponse resp = VNFRestfulUtil.getRestResByDefault(path, methodNames, bodyParam); + assertNotNull(resp); + } + + @Test + public void sendReqToAppTestNullResp(){ + String path="http://localhost:8080"; + String methodNames = "get"; + JSONObject bodyParam = new JSONObject(); + bodyParam.put("id", "1234"); + JSONObject resp = VNFRestfulUtil.sendReqToApp(path, methodNames, bodyParam); + assertNotNull(resp); + } + @Test + public void sendReqToAppTest(){ + new MockUp<VNFRestfulUtil>(){ + @Mock + public RestfulResponse getRestResByDefault(String path, String methodNames, JSONObject bodyParam) { + RestfulResponse resp = new RestfulResponse(); + resp.setStatus(200); + Map<String,Object> map = new HashMap<>(); + map.put("retCode", 1); + resp.setResponseJson(toJson(map)); + return resp; + } + }; + String path="http://localhost:8080/vnfdmgr/v1"; + String methodNames = "get"; + JSONObject bodyParam = new JSONObject(); + bodyParam.put("vnfmInfo", new JSONObject().put("id", "6775")); + JSONObject resp = VNFRestfulUtil.sendReqToApp(path, methodNames, bodyParam); + assertNotNull(resp); + } + + @Test + public void sendReqToAppTest2(){ + new MockUp<VNFRestfulUtil>(){ + @Mock + public RestfulResponse getRestResByDefault(String path, String methodNames, JSONObject bodyParam) { + RestfulResponse resp = new RestfulResponse(); + resp.setStatus(200); + Map<String,Object> map = new HashMap<>(); + map.put("retCode", -1); + resp.setResponseJson(toJson(map)); + return resp; + } + }; + String path="http://localhost:8080/vnfdmgr/v1"; + String methodNames = "get"; + JSONObject bodyParam = new JSONObject(); + bodyParam.put("vnfmInfo", new JSONObject().put("id", "6775")); + JSONObject resp = VNFRestfulUtil.sendReqToApp(path, methodNames, bodyParam); + assertNotNull(resp); + } + @Test + public void sendReqToAppTest3(){ + new MockUp<VNFRestfulUtil>(){ + @Mock + public RestfulResponse getRestResByDefault(String path, String methodNames, JSONObject bodyParam) { + RestfulResponse resp = new RestfulResponse(); + resp.setStatus(500); + Map<String,Object> map = new HashMap<>(); + map.put("retCode", -1); + resp.setResponseJson(toJson(map)); + return resp; + } + }; + String path="http://localhost:8080/vnfdmgr/v1"; + String methodNames = "get"; + JSONObject bodyParam = new JSONObject(); + bodyParam.put("vnfmInfo", new JSONObject().put("id", "6775")); + JSONObject resp = VNFRestfulUtil.sendReqToApp(path, methodNames, bodyParam); + assertNotNull(resp); + } + + @Test + public void getRemoteResponseTest(){ + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/123"); + paramsMap.put("methodType", "delete"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("authMode", "test"); + + boolean isNfvoApp = false; + RestfulResponse resp = VNFRestfulUtil.getRemoteResponse(paramsMap, "", "test123", isNfvoApp); + assertNull(resp); + } + + @Test + public void getRemoteResponse2Test(){ + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/123"); + paramsMap.put("methodType", "get"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("authMode", "test"); + + boolean isNfvoApp = false; + RestfulResponse resp = VNFRestfulUtil.getRemoteResponse(paramsMap, "", "test123", isNfvoApp); + assertNull(resp); + } + + @Test + public void getRemoteResponse3Test(){ + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/123"); + paramsMap.put("methodType", "post"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("authMode", "test"); + + boolean isNfvoApp = false; + RestfulResponse resp = VNFRestfulUtil.getRemoteResponse(paramsMap, "", "test123", isNfvoApp); + assertNull(resp); + } + @Test + public void getRemoteResponse4Test(){ + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/123"); + paramsMap.put("methodType", "put"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("authMode", "test"); + + boolean isNfvoApp = false; + RestfulResponse resp = VNFRestfulUtil.getRemoteResponse(paramsMap, "", "test123", isNfvoApp); + assertNull(resp); + } + @Test + public void getRemoteResponse5Test(){ + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/123"); + paramsMap.put("methodType", "patch"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("authMode", "test"); + boolean isNfvoApp = false; + RestfulResponse resp = VNFRestfulUtil.getRemoteResponse(paramsMap, "", "test123", isNfvoApp); + assertNull(resp); + } + @Test + public void getRemoteResponseTrueTest(){ + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/123"); + paramsMap.put("methodType", "patch"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("authMode", "test"); + boolean isNfvoApp = true; + RestfulResponse resp = VNFRestfulUtil.getRemoteResponse(paramsMap, "", "test123", isNfvoApp); + assertNull(resp); + } + + @Test + public void getRemoteResponseDeleteTest(){ + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/123"); + paramsMap.put("methodType", "delete"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("authMode", "test"); + RestfulResponse resp = VNFRestfulUtil.getRemoteResponse(paramsMap, ""); + assertNull(resp); + } + @Test + public void getRemoteResponseGetTest(){ + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/123"); + paramsMap.put("methodType", "get"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("authMode", "test"); + + RestfulResponse resp = VNFRestfulUtil.getRemoteResponse(paramsMap, ""); + assertNull(resp); + } + @Test + public void getRemoteResponsePostTest(){ + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/123"); + paramsMap.put("methodType", "post"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("authMode", "test"); + + RestfulResponse resp = VNFRestfulUtil.getRemoteResponse(paramsMap, ""); + assertNull(resp); + } + @Test + public void getRemoteResponsePutTest(){ + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/123"); + paramsMap.put("methodType", "put"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("authMode", "test"); + + RestfulResponse resp = VNFRestfulUtil.getRemoteResponse(paramsMap, ""); + assertNull(resp); + } + @Test + public void getRemoteResponsePatchTest(){ + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/123"); + paramsMap.put("methodType", "patch"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("authMode", "test"); + + RestfulResponse resp = VNFRestfulUtil.getRemoteResponse(paramsMap, ""); + assertNull(resp); + } + + @Test + public void getRemoteResponseNullTest(){ + + RestfulResponse resp = VNFRestfulUtil.getRemoteResponse(null, ""); + assertNull(resp); + } + @Test + public void generateParamsMapTest(){ + String url = "/test/123"; + String methodType="get"; + String path="http://localhost:8080"; + String authMode="test"; + Map<String, String> res = VNFRestfulUtil.generateParamsMap(url, methodType, path, authMode); + assertTrue(res.get("url").equals("/test/123")); + } + + @Test + public void generateParams2MapTest(){ + String url = "/test/123"; + String methodType="get"; + String path="http://localhost:8080"; + Map<String, String> res = VNFRestfulUtil.generateParamsMap(url, methodType, path); + assertTrue(res.get("url").equals("/test/123")); + } + @Test + public void getResultToVnfmTest(){ + JSONObject vnfmInfo= new JSONObject(); + vnfmInfo.put("retCode", 1); + String vnfmId="123"; + JSONObject res = VNFRestfulUtil.getResultToVnfm(vnfmInfo, vnfmId); + assertNotNull(res); + } + + @Test + public void getResultToVnfm2Test(){ + JSONObject vnfmInfo= new JSONObject(); + vnfmInfo.put("retCode", -1); + String vnfmId="123"; + JSONObject res = VNFRestfulUtil.getResultToVnfm(vnfmInfo, vnfmId); + assertNotNull(res); + } + + public static String toJson(Map o) { + try { + return JsonUtil.marshal(o); + } catch (IOException e) { + return ""; + } + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/common/servicetoken/VnfmRestfulUtilTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/common/servicetoken/VnfmRestfulUtilTest.java new file mode 100644 index 00000000..d03b39c5 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/common/servicetoken/VnfmRestfulUtilTest.java @@ -0,0 +1,240 @@ +/* + * Copyright 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.nfvo.vnfmadapter.common.servicetoken; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; + +import mockit.Mock; +import mockit.MockUp; +import net.sf.json.JSONObject; + +public class VnfmRestfulUtilTest { + @Test + public void testGetRestResByDefaultByNull() { + RestfulResponse result = VnfmRestfulUtil.getRestResByDefault("path", "methodNames", new JSONObject()); + assertNull(result); + } + + @Test + public void testGetRestResByDefaultByGet() { + RestfulResponse result = VnfmRestfulUtil.getRestResByDefault("path", "get", new JSONObject()); + assertNotNull(result); + } + + @Test + public void testGetRestResByDefaultByPut() { + RestfulResponse result = VnfmRestfulUtil.getRestResByDefault("path", "put", new JSONObject()); + assertNotNull(result); + } + + @Test + public void testSendReqToApp() { + new MockUp<VnfmRestfulUtil>() { + + @Mock + public RestfulResponse getRestResByDefault(String path, String methodNames, JSONObject bodyParam) { + RestfulResponse restfulResponse = new RestfulResponse(); + restfulResponse.setStatus(Constant.HTTP_OK); + String responseString = "{\"retCode\":1,\"data\":\"success\"}"; + restfulResponse.setResponseJson(responseString); + return restfulResponse; + } + }; + JSONObject result = VnfmRestfulUtil.sendReqToApp("path", "put", new JSONObject()); + assertEquals(Constant.REST_SUCCESS, result.get("retCode")); + } + + @Test + public void testSendReqToAppByErrorMsg() { + new MockUp<VnfmRestfulUtil>() { + + @Mock + public RestfulResponse getRestResByDefault(String path, String methodNames, JSONObject bodyParam) { + RestfulResponse restfulResponse = new RestfulResponse(); + restfulResponse.setStatus(Constant.HTTP_OK); + String responseString = "{\"retCode\":-1,\"data\":\"fail\",\"msg\":\"fail\"}"; + restfulResponse.setResponseJson(responseString); + return restfulResponse; + } + }; + JSONObject result = VnfmRestfulUtil.sendReqToApp("path", "put", new JSONObject()); + assertEquals(Constant.REST_FAIL, result.get("retCode")); + } + + @Test + public void testSendReqToAppByError() { + new MockUp<VnfmRestfulUtil>() { + + @Mock + public RestfulResponse getRestResByDefault(String path, String methodNames, JSONObject bodyParam) { + RestfulResponse restfulResponse = new RestfulResponse(); + restfulResponse.setStatus(Constant.HTTP_OK); + String responseString = "{\"retCode\":-1,\"data\":\"fail\"}"; + restfulResponse.setResponseJson(responseString); + return restfulResponse; + } + }; + JSONObject result = VnfmRestfulUtil.sendReqToApp("path", "put", new JSONObject()); + assertEquals(Constant.REST_FAIL, result.get("retCode")); + } + + @Test + public void testSendReqToAppByFail() { + JSONObject result = VnfmRestfulUtil.sendReqToApp("path", "put", new JSONObject()); + assertEquals(Constant.REST_FAIL, result.get("retCode")); + } + + @Test + public void testSendReqToAppByVnfmInfo() { + JSONObject paraJson = new JSONObject(); + JSONObject vnfmObj = new JSONObject(); + vnfmObj.put("id", "id"); + paraJson.put("vnfmInfo", vnfmObj); + JSONObject result = VnfmRestfulUtil.sendReqToApp("path", "put", paraJson); + assertEquals(Constant.REST_FAIL, result.get("retCode")); + } + + @Test + public void testGenerateParamsMap2() { + Map<String, String> result = VnfmRestfulUtil.generateParamsMap("url", "methodType", "path", "authMode"); + Map<String, String> paramsMap = new HashMap<String, String>(6); + paramsMap.put("url", "url"); + paramsMap.put("methodType", "methodType"); + paramsMap.put("path", "path"); + paramsMap.put("authMode", "authMode"); + assertEquals(paramsMap, result); + } + @Test + public void getRemoteResponseTestGet(){ + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/123"); + paramsMap.put("methodType", "get"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("authMode", "test"); + boolean isNfvoApp = false; + RestfulResponse resp = VnfmRestfulUtil.getRemoteResponse(paramsMap, "", "test123", isNfvoApp); + assertNull(resp); + } + @Test + public void getRemoteResponseTestGetTrueNfvo(){ + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/123"); + paramsMap.put("methodType", "get"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("authMode", "test"); + boolean isNfvoApp = true; + RestfulResponse resp = VnfmRestfulUtil.getRemoteResponse(paramsMap, "", "test123", isNfvoApp); + assertNull(resp); + } + @Test + public void getRemoteResponseTestPost(){ + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/123"); + paramsMap.put("methodType", "post"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("authMode", "test"); + + boolean isNfvoApp = false; + RestfulResponse resp = VnfmRestfulUtil.getRemoteResponse(paramsMap, "", "test123", isNfvoApp); + assertNull(resp); + } + @Test + public void getRemoteResponseTestPut(){ + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/123"); + paramsMap.put("methodType", "put"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("authMode", "test"); + + boolean isNfvoApp = false; + RestfulResponse resp = VnfmRestfulUtil.getRemoteResponse(paramsMap, "", "test123", isNfvoApp); + assertNull(resp); + } + + @Test + public void getRemoteResponseTestDelete(){ + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/123"); + paramsMap.put("methodType", "delete"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("authMode", "test"); + + boolean isNfvoApp = false; + RestfulResponse resp = VnfmRestfulUtil.getRemoteResponse(paramsMap, "", "test123", isNfvoApp); + assertNull(resp); + } + + @Test + public void getRemoteResponse2TestDelete(){ + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/123"); + paramsMap.put("methodType", "delete"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("authMode", "test"); + RestfulResponse resp = VnfmRestfulUtil.getRemoteResponse("/test/123", "", "test123"); + assertNull(resp); + } + @Test + public void getRemoteResponse2TestGet(){ + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/123"); + paramsMap.put("methodType", "get"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("authMode", "test"); + RestfulResponse resp = VnfmRestfulUtil.getRemoteResponse("/test/123", "", "test123"); + assertNull(resp); + } + @Test + public void getRemoteResponse2Testput(){ + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/123"); + paramsMap.put("methodType", "put"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("authMode", "test"); + RestfulResponse resp = VnfmRestfulUtil.getRemoteResponse("/test/123", "", "test123"); + assertNull(resp); + } + @Test + public void getRemoteResponse2TestPost(){ + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/123"); + paramsMap.put("methodType", "put"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("authMode", "post"); + RestfulResponse resp = VnfmRestfulUtil.getRemoteResponse("/test/123", "", "test123"); + assertNull(resp); + } + @Test + public void getRemoteResponse2TestPatch(){ + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/123"); + paramsMap.put("methodType", "patch"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("authMode", "post"); + RestfulResponse resp = VnfmRestfulUtil.getRemoteResponse("/test/123", "", "test123"); + assertNull(resp); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/activator/RoaVnfmServicePostProcessorTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/activator/RoaVnfmServicePostProcessorTest.java new file mode 100644 index 00000000..82d8c2b4 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/activator/RoaVnfmServicePostProcessorTest.java @@ -0,0 +1,52 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.activator; + +import org.junit.Assert; +import org.junit.Test; +import org.openo.nfvo.vnfmadapter.service.api.internalsvc.impl.VnfmAdapterMgrService; + +/** + * Created by QuanZhong on 2017/3/17. + */ +public class RoaVnfmServicePostProcessorTest { + @Test + public void testPostProcessAfterInitialization(){ + RoaVnfmServicePostProcessor dm = new RoaVnfmServicePostProcessor(); + dm.postProcessAfterInitialization(new VnfmAdapterMgrService(),"abc"); + Assert.assertTrue(true); + } + @Test + public void testPostProcessAfterInitialization2(){ + RoaVnfmServicePostProcessor dm = new RoaVnfmServicePostProcessor(); + dm.postProcessAfterInitialization(null,"abc"); + Assert.assertTrue(true); + } + + @Test + public void testpostProcessBeforeDestruction(){ + RoaVnfmServicePostProcessor dm = new RoaVnfmServicePostProcessor(); + dm.postProcessBeforeDestruction(new VnfmAdapterMgrService(),"abc"); + Assert.assertTrue(true); + } + + @Test + public void testpostProcessBeforeInitialization(){ + RoaVnfmServicePostProcessor dm = new RoaVnfmServicePostProcessor(); + dm.postProcessBeforeInitialization(new VnfmAdapterMgrService(),"abc"); + Assert.assertTrue(true); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/activator/TestRoaVnfmService2DriverMgr.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/activator/TestRoaVnfmService2DriverMgr.java new file mode 100644 index 00000000..f75f4e44 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/activator/TestRoaVnfmService2DriverMgr.java @@ -0,0 +1,52 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.activator; + +import org.junit.Assert; +import org.junit.Test; +import org.openo.nfvo.vnfmadapter.service.api.internalsvc.impl.VnfmAdapter2DriverMgrService; + +/** + * Created by QuanZhong on 2017/3/17. + */ +public class TestRoaVnfmService2DriverMgr { + @Test + public void testPostProcessAfterInitialization(){ + RoaVnfmService2DriverMgr dm = new RoaVnfmService2DriverMgr(); + dm.postProcessAfterInitialization(new VnfmAdapter2DriverMgrService(),"abc"); + Assert.assertTrue(true); + } + @Test + public void testPostProcessAfterInitialization2(){ + RoaVnfmService2DriverMgr dm = new RoaVnfmService2DriverMgr(); + dm.postProcessAfterInitialization(null,"abc"); + Assert.assertTrue(true); + } + + @Test + public void testpostProcessBeforeDestruction(){ + RoaVnfmService2DriverMgr dm = new RoaVnfmService2DriverMgr(); + dm.postProcessBeforeDestruction(new VnfmAdapter2DriverMgrService(),"abc"); + Assert.assertTrue(true); + } + + @Test + public void testpostProcessBeforeInitialization(){ + RoaVnfmService2DriverMgr dm = new RoaVnfmService2DriverMgr(); + dm.postProcessBeforeInitialization(new VnfmAdapter2DriverMgrService(),"abc"); + Assert.assertTrue(true); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/AdapterResourceManagerTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/AdapterResourceManagerTest.java new file mode 100644 index 00000000..895c167b --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/AdapterResourceManagerTest.java @@ -0,0 +1,311 @@ +/* + * Copyright 2016-2017 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.nfvo.vnfmadapter.service.adapter.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.common.DownloadCsarManager; +import org.openo.nfvo.vnfmadapter.common.servicetoken.VNFRestfulUtil; +import org.openo.nfvo.vnfmadapter.testutils.JsonUtil; + +import mockit.Mock; +import mockit.MockUp; +import net.sf.json.JSONException; +import net.sf.json.JSONObject; + +public class AdapterResourceManagerTest { + + AdapterResourceManager manager = null; + + @Before + public void setUp() { + manager = new AdapterResourceManager(); + } + + @Test(expected = JSONException.class) + public void uploadVNFPackageTestJsonException() { + JSONObject vnfpkg = new JSONObject(); + Map<String, String> paramsMap = new HashMap<>(); + JSONObject res = manager.uploadVNFPackage(vnfpkg, paramsMap); + assertTrue(res != null); + + } + + @Test(expected = JSONException.class) + public void uploadVNFPackageTestJsonException2() { + JSONObject vnfpkg = new JSONObject(); + Map<String, String> paramsMap = new HashMap<>(); + JSONObject res = manager.uploadVNFPackage(null, paramsMap); + assertTrue(res != null); + + } + + @Test + public void uploadVNFPackageTestJsonException3() { + JSONObject vnfpkg = new JSONObject(); + vnfpkg.put("name", "test"); + Map<String, String> paramsMap = new HashMap<>(); + JSONObject res = manager.uploadVNFPackage(vnfpkg, paramsMap); + assertTrue(res.get("reason").equals("csarid and vnfmid are null.")); + + } + + @Test + public void uploadVNFPackageTestEmptyParam() { + JSONObject vnfpkg = new JSONObject(); + vnfpkg.put("name", "test"); + Map<String, String> paramsMap = new HashMap<>(); + JSONObject res = manager.uploadVNFPackage(vnfpkg, paramsMap); + assertTrue(res.get("reason").equals("csarid and vnfmid are null.")); + + } + + @Test + public void uploadVNFPackageTestNullParam() { + JSONObject vnfpkg = new JSONObject(); + vnfpkg.put("name", "test"); + Map<String, String> paramsMap = new HashMap<>(); + JSONObject res = manager.uploadVNFPackage(vnfpkg, null); + assertTrue(res.get("reason").equals("csarid and vnfmid are null.")); + + } + + @Test + public void uploadVNFPackageTestInvalidCsrid() { + JSONObject vnfpkg = new JSONObject(); + vnfpkg.put("name", "test"); + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("csarid", ""); + JSONObject res = manager.uploadVNFPackage(vnfpkg, paramsMap); + assertTrue(res.get("reason").equals("csarid is null.")); + + } + + @Test + public void uploadVNFPackageTestInvalidCsrid2() { + JSONObject vnfpkg = new JSONObject(); + vnfpkg.put("name", "test"); + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("csarid", null); + JSONObject res = manager.uploadVNFPackage(vnfpkg, paramsMap); + assertTrue(res.get("reason").equals("csarid is null.")); + + } + + @Test + public void uploadVNFPackageTestInvalidVnfmid() { + JSONObject vnfpkg = new JSONObject(); + vnfpkg.put("name", "test"); + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("csarid", "csarid123"); + paramsMap.put("vnfmid", null); + JSONObject res = manager.uploadVNFPackage(vnfpkg, paramsMap); + assertTrue(res.get("reason").equals("vnfmid is null.")); + + } + + @Test + public void uploadVNFPackageTestInvalidVnfmid2() { + JSONObject vnfpkg = new JSONObject(); + vnfpkg.put("name", "test"); + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("csarid", "csarid123"); + paramsMap.put("vnfmid", ""); + JSONObject res = manager.uploadVNFPackage(vnfpkg, paramsMap); + assertTrue(res.get("reason").equals("vnfmid is null.")); + + } + + @Test + public void uploadVNFPackageTestNullResp() { + JSONObject vnfpkg = new JSONObject(); + vnfpkg.put("name", "test"); + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("csarid", "csarid123"); + paramsMap.put("vnfmid", "vnfmid1234"); + JSONObject res = manager.uploadVNFPackage(vnfpkg, paramsMap); + assertTrue(res.get("reason").equals("RestfulResponse is null.")); + + } + + @Test + public void downloadCsarTestNullUrl() { + String url = null; + String filePath = null; + JSONObject res = manager.downloadCsar(url, filePath); + assertTrue(res.get("reason").equals("url is null.")); + } + + @Test + public void downloadCsarTestEmptyUrl() { + String url = ""; + String filePath = null; + JSONObject res = manager.downloadCsar(url, filePath); + assertTrue(res.get("reason").equals("url is null.")); + } + + @Test + public void downloadCsarTestNullFilePath() { + String url = "http://localhost:8080"; + String filePath = null; + JSONObject res = manager.downloadCsar(url, filePath); + assertTrue(res.get("reason").equals("downloadUrl filePath is null.")); + } + + @Test + public void downloadCsarTestEmptyFilePath() { + String url = "http://localhost:8080"; + String filePath = ""; + JSONObject res = manager.downloadCsar(url, filePath); + assertTrue(res.get("reason").equals("downloadUrl filePath is null.")); + } + + @Test + public void getVnfmConnInfoTestSuccess() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + RestfulResponse resp = new RestfulResponse(); + resp.setStatus(200); + Map<String, String> objMap = new HashMap<String, String>(); + objMap.put("id", "test123"); + + String responseString = toJson(objMap); + resp.setResponseJson(responseString); + return resp; + } + + }; + Map<String, String> paramsMap = new HashMap<String, String>(); + JSONObject res = manager.getVnfmConnInfo(paramsMap); + assertTrue(res.get("id").equals("test123")); + } + + @Test + public void getVnfmConnInfoTestNullResp() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + + return null; + } + + }; + Map<String, String> paramsMap = new HashMap<String, String>(); + JSONObject res = manager.getVnfmConnInfo(paramsMap); + assertTrue(res.get("reason").equals("RestfulResponse is null.")); + } + + @Test + public void getVnfmConnInfoTestServerError() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + RestfulResponse resp = new RestfulResponse(); + resp.setStatus(500); + Map<String, String> objMap = new HashMap<String, String>(); + objMap.put("id", "test123"); + + String responseString = toJson(objMap); + resp.setResponseJson(responseString); + return resp; + } + + }; + Map<String, String> paramsMap = new HashMap<String, String>(); + JSONObject res = manager.getVnfmConnInfo(paramsMap); + assertTrue(res.get("reason").equals("ESR return fail.")); + } + + @Test + public void uploadTestInternalError() { + JSONObject vnfpackage = new JSONObject(); + String vnfmurl = "http://localhost"; + String conntoken = "test"; + JSONObject res = manager.upload(vnfpackage, vnfmurl, conntoken); + assertEquals(res.get("retCode"), 500); + } + + public static String toJson(Map o) { + try { + return JsonUtil.marshal(o); + } catch(IOException e) { + return ""; + } + } + + @Test + public void testGetAllCloud(){ + String url = null; + manager.getAllCloud(url,null); + } + + @Test + public void testGetAllCloud2(){ + String url = "http://127.0.0.1:31943"; + manager.getAllCloud(url,null); + } + @Test + public void testUnzipCSAR(){ + manager.unzipCSAR(null,null); + } + @Test + public void testUnzipCSAR2(){ + manager.unzipCSAR("vCpe.zip",null); + } + @Test + public void testUnzipCSAR3(){ + manager.unzipCSAR("vCpe.zip","/opt"); + } + @Test + public void testUnzipCSAR4(){ + new MockUp<DownloadCsarManager>(){ + @Mock + public int unzipCSAR(String fileName,String filePath){ + return 0; + } + }; + manager.unzipCSAR("vCpe.zip","/opt"); + } + @Test + public void testUnzipCSAR5(){ + new MockUp<DownloadCsarManager>(){ + @Mock + public int unzipCSAR(String fileName,String filePath){ + return -1; + } + }; + manager.unzipCSAR("vCpe.zip","/opt"); + } + + @Test + public void testGetVnfdVersion(){ + manager.getVnfdVersion("http://","127.0.0.1","token"); + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/Driver2MSBManagerTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/Driver2MSBManagerTest.java new file mode 100644 index 00000000..48a04118 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/Driver2MSBManagerTest.java @@ -0,0 +1,281 @@ +/* + * Copyright 2017 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.nfvo.vnfmadapter.service.adapter.impl; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.common.servicetoken.VNFRestfulUtil; +import org.openo.nfvo.vnfmadapter.testutils.JsonUtil; + +import mockit.Mock; +import mockit.MockUp; +import net.sf.json.JSONObject; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Jan 24, 2017 + */ +public class Driver2MSBManagerTest { + + Driver2MSBManager manager = new Driver2MSBManager(); + + Map<String, String> vim = new HashMap<String, String>(); + + @Before + public void setUp() { + vim.put("vimId", "123"); + vim.put("name", "123"); + vim.put("url", "123"); + vim.put("userName", "123"); + vim.put("password", "123"); + vim.put("type", "123"); + vim.put("version", "123"); + } + + @Test + public void registerDriverTestNullResp() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + RestfulResponse response = new RestfulResponse(); + + return null; + } + }; + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/openoapi"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("methodType", "get"); + JSONObject obj = manager.registerDriver(paramsMap, new JSONObject()); + assertTrue(obj.get("reason").equals("RestfulResponse is null.")); + } + + @Test + public void registerDriverCreateSuccess() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + RestfulResponse response = new RestfulResponse(); + response.setStatus(201); + + String vimStr = toJson(vim); + response.setResponseJson(vimStr); + return response; + } + }; + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/openoapi"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("methodType", "get"); + JSONObject obj = manager.registerDriver(paramsMap, new JSONObject()); + assertTrue(Integer.valueOf(obj.get("retCode").toString()) == 201); + } + + @Test + public void registerDriverOkSuccess() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + RestfulResponse response = new RestfulResponse(); + response.setStatus(200); + + String vimStr = toJson(vim); + response.setResponseJson(vimStr); + return response; + } + }; + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/openoapi"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("methodType", "get"); + JSONObject obj = manager.registerDriver(paramsMap, new JSONObject()); + assertTrue(Integer.valueOf(obj.get("retCode").toString()) == -1); + } + + @Test + public void registerDriverTestInvalidParams() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + RestfulResponse response = new RestfulResponse(); + response.setStatus(415); + + String vimStr = toJson(vim); + response.setResponseJson(vimStr); + return response; + } + }; + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/openoapi"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("methodType", "get"); + JSONObject obj = manager.registerDriver(paramsMap, new JSONObject()); + assertTrue(obj.get("reason").equals("MSB return fail,invalid parameters.")); + } + + @Test + public void registerDriverTestInternalError() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + RestfulResponse response = new RestfulResponse(); + response.setStatus(500); + + String vimStr = toJson(vim); + response.setResponseJson(vimStr); + return response; + } + }; + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/openoapi"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("methodType", "get"); + JSONObject obj = manager.registerDriver(paramsMap, new JSONObject()); + assertTrue(obj.get("reason").equals("MSB return fail,internal system error.")); + } + + @Test + public void unregisterDriverTestNullResp() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + RestfulResponse response = new RestfulResponse(); + + return null; + } + }; + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/openoapi"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("methodType", "get"); + JSONObject obj = manager.unregisterDriver(paramsMap); + assertTrue(obj.get("reason").equals("RestfulResponse is null.")); + } + + @Test + public void unregisterDriverDeleteSuccess() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + RestfulResponse response = new RestfulResponse(); + response.setStatus(204); + + String vimStr = toJson(vim); + response.setResponseJson(vimStr); + return response; + } + }; + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/openoapi"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("methodType", "get"); + JSONObject obj = manager.unregisterDriver(paramsMap); + assertTrue(Integer.valueOf(obj.get("retCode").toString()) == 204); + } + + @Test + public void unregisterDriverResourceNotFound() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + RestfulResponse response = new RestfulResponse(); + response.setStatus(404); + + String vimStr = toJson(vim); + response.setResponseJson(vimStr); + return response; + } + }; + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/openoapi"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("methodType", "get"); + JSONObject obj = manager.unregisterDriver(paramsMap); + assertTrue(obj.get("reason").equals("MSB return fail,can't find the service instance.")); + } + + @Test + public void unregisterDriverTestInvalidParams() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + RestfulResponse response = new RestfulResponse(); + response.setStatus(415); + + String vimStr = toJson(vim); + response.setResponseJson(vimStr); + return response; + } + }; + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/openoapi"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("methodType", "get"); + JSONObject obj = manager.unregisterDriver(paramsMap); + assertTrue(obj.get("reason").equals("MSB return fail,invalid parameters.")); + } + + @Test + public void unregisterDriverTestInternalError() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + RestfulResponse response = new RestfulResponse(); + response.setStatus(500); + + String vimStr = toJson(vim); + response.setResponseJson(vimStr); + return response; + } + }; + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/openoapi"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("methodType", "get"); + JSONObject obj = manager.unregisterDriver(paramsMap); + assertTrue(obj.get("reason").equals("MSB return fail,internal system error.")); + } + + public static String toJson(Map o) { + try { + return JsonUtil.marshal(o); + } catch(IOException e) { + return ""; + } + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/VnfmAdapter2DriverManagerTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/VnfmAdapter2DriverManagerTest.java new file mode 100644 index 00000000..f79fa704 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/adapter/impl/VnfmAdapter2DriverManagerTest.java @@ -0,0 +1,281 @@ +/* + * Copyright 2017 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.nfvo.vnfmadapter.service.adapter.impl; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.common.servicetoken.VNFRestfulUtil; +import org.openo.nfvo.vnfmadapter.testutils.JsonUtil; + +import mockit.Mock; +import mockit.MockUp; +import net.sf.json.JSONObject; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Jan 24, 2017 + */ +public class VnfmAdapter2DriverManagerTest { + + VnfmAdapter2DriverManager manager = new VnfmAdapter2DriverManager(); + + Map<String, String> vim = new HashMap<String, String>(); + + @Before + public void setUp() { + vim.put("vimId", "123"); + vim.put("name", "123"); + vim.put("url", "123"); + vim.put("userName", "123"); + vim.put("password", "123"); + vim.put("type", "123"); + vim.put("version", "123"); + } + + @Test + public void registerDriverTestNullResp() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + RestfulResponse response = new RestfulResponse(); + + return null; + } + }; + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/openoapi"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("methodType", "get"); + JSONObject obj = manager.registerDriver(paramsMap, new JSONObject()); + assertTrue(obj.get("reason").equals("RestfulResponse is null.")); + } + + @Test + public void registerDriverCreateSuccess() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + RestfulResponse response = new RestfulResponse(); + response.setStatus(201); + + String vimStr = toJson(vim); + response.setResponseJson(vimStr); + return response; + } + }; + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/openoapi"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("methodType", "get"); + JSONObject obj = manager.registerDriver(paramsMap, new JSONObject()); + assertTrue(Integer.valueOf(obj.get("retCode").toString()) == 201); + } + + @Test + public void registerDriverOkSuccess() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + RestfulResponse response = new RestfulResponse(); + response.setStatus(200); + + String vimStr = toJson(vim); + response.setResponseJson(vimStr); + return response; + } + }; + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/openoapi"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("methodType", "get"); + JSONObject obj = manager.registerDriver(paramsMap, new JSONObject()); + assertTrue(Integer.valueOf(obj.get("retCode").toString()) == -1); + } + + @Test + public void registerDriverTestInvalidParams() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + RestfulResponse response = new RestfulResponse(); + response.setStatus(415); + + String vimStr = toJson(vim); + response.setResponseJson(vimStr); + return response; + } + }; + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/openoapi"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("methodType", "get"); + JSONObject obj = manager.registerDriver(paramsMap, new JSONObject()); + assertTrue(obj.get("reason").equals("DriverManager return fail,invalid parameters.")); + } + + @Test + public void registerDriverTestInternalError() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + RestfulResponse response = new RestfulResponse(); + response.setStatus(500); + + String vimStr = toJson(vim); + response.setResponseJson(vimStr); + return response; + } + }; + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/openoapi"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("methodType", "get"); + JSONObject obj = manager.registerDriver(paramsMap, new JSONObject()); + assertTrue(obj.get("reason").equals("DriverManager return fail,internal system error.")); + } + + @Test + public void unregisterDriverTestNullResp() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + RestfulResponse response = new RestfulResponse(); + + return null; + } + }; + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/openoapi"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("methodType", "get"); + JSONObject obj = manager.unregisterDriver(paramsMap); + assertTrue(obj.get("reason").equals("RestfulResponse is null.")); + } + + @Test + public void unregisterDriverDeleteSuccess() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + RestfulResponse response = new RestfulResponse(); + response.setStatus(204); + + String vimStr = toJson(vim); + response.setResponseJson(vimStr); + return response; + } + }; + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/openoapi"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("methodType", "get"); + JSONObject obj = manager.unregisterDriver(paramsMap); + assertTrue(Integer.valueOf(obj.get("retCode").toString()) == 204); + } + + @Test + public void unregisterDriverResourceNotFound() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + RestfulResponse response = new RestfulResponse(); + response.setStatus(404); + + String vimStr = toJson(vim); + response.setResponseJson(vimStr); + return response; + } + }; + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/openoapi"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("methodType", "get"); + JSONObject obj = manager.unregisterDriver(paramsMap); + assertTrue(obj.get("reason").equals("DriverManager return fail,can't find the service instance.")); + } + + @Test + public void unregisterDriverTestInvalidParams() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + RestfulResponse response = new RestfulResponse(); + response.setStatus(415); + + String vimStr = toJson(vim); + response.setResponseJson(vimStr); + return response; + } + }; + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/openoapi"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("methodType", "get"); + JSONObject obj = manager.unregisterDriver(paramsMap); + assertTrue(obj.get("reason").equals("DriverManager return fail,invalid parameters.")); + } + + @Test + public void unregisterDriverTestInternalError() { + new MockUp<VNFRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + RestfulResponse response = new RestfulResponse(); + response.setStatus(500); + + String vimStr = toJson(vim); + response.setResponseJson(vimStr); + return response; + } + }; + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", "/test/openoapi"); + paramsMap.put("path", "http://localhost:8080"); + paramsMap.put("methodType", "get"); + JSONObject obj = manager.unregisterDriver(paramsMap); + assertTrue(obj.get("reason").equals("DriverManager return fail,internal system error.")); + } + + public static String toJson(Map o) { + try { + return JsonUtil.marshal(o); + } catch(IOException e) { + return ""; + } + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/ai/internalsvc/impl/VnfmAdapter2DriverMgrServiceTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/ai/internalsvc/impl/VnfmAdapter2DriverMgrServiceTest.java new file mode 100644 index 00000000..e3393b42 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/ai/internalsvc/impl/VnfmAdapter2DriverMgrServiceTest.java @@ -0,0 +1,51 @@ +/* + * Copyright 2017 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.nfvo.vnfmadapter.service.ai.internalsvc.impl; + +import mockit.Mock; +import mockit.MockUp; +import org.junit.Test; +import org.openo.nfvo.vnfmadapter.service.api.internalsvc.impl.VnfmAdapter2DriverMgrService; + +import java.io.IOException; + +/** + * Created by QuanZhong on 2017/3/20. + */ +public class VnfmAdapter2DriverMgrServiceTest { + + @Test + public void testRegister(){ + VnfmAdapter2DriverMgrService mgr = new VnfmAdapter2DriverMgrService(); + mgr.register(); + mgr.unregister(); + } + + @Test + public void testRegister2(){ + new MockUp<VnfmAdapter2DriverMgrService>(){ + @Mock + public String readVnfmAdapterInfoFromJson() throws IOException { + return "{'url':'http://127.0.0.1'}"; + + } + }; + VnfmAdapter2DriverMgrService mgr = new VnfmAdapter2DriverMgrService(); + mgr.register(); + mgr.unregister(); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/ai/internalsvc/impl/VnfmAdapterMgrServiceTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/ai/internalsvc/impl/VnfmAdapterMgrServiceTest.java new file mode 100644 index 00000000..2a6b7444 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/ai/internalsvc/impl/VnfmAdapterMgrServiceTest.java @@ -0,0 +1,45 @@ +/* + * Copyright 2017 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.nfvo.vnfmadapter.service.ai.internalsvc.impl; + +import mockit.Mock; +import mockit.MockUp; +import net.sf.json.JSONObject; +import org.junit.Test; +import org.openo.nfvo.vnfmadapter.service.api.internalsvc.impl.VnfmAdapterMgrService; +import org.openo.nfvo.vnfmadapter.service.process.VnfMgr; + +import java.io.IOException; + +/** + * Created by QuanZhong on 2017/3/20. + */ +public class VnfmAdapterMgrServiceTest { + @Test + public void testRegister(){ + new MockUp<VnfmAdapterMgrService>(){ + + @Mock + public String readVnfmAdapterInfoFromJson() throws IOException { + return "{'abc':'123'}"; + } + }; + VnfmAdapterMgrService mgr = new VnfmAdapterMgrService(); + mgr.register(); + + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/constant/TestConstant.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/constant/TestConstant.java new file mode 100644 index 00000000..f2142f14 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/constant/TestConstant.java @@ -0,0 +1,39 @@ +/* + * Copyright 2017 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.nfvo.vnfmadapter.service.constant; + +import junit.framework.Assert; +import org.junit.Test; + +import java.util.List; + +import static org.openo.nfvo.vnfmadapter.service.constant.Constant.AUTHLIST; + +/** + * Created by QuanZhong on 2017/3/17. + */ +public class TestConstant { + @Test + public void testCreate(){ + List<String> authlist = AUTHLIST; + authlist.contains("abc"); + String url = UrlConstant.PORT_COMMON; + authlist.contains(url); + String abc = ParamConstants.CONNECTMGR_CONNECT; + authlist.contains(abc); + Assert.assertTrue(true); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/csm/api/ConnectInfoTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/csm/api/ConnectInfoTest.java new file mode 100644 index 00000000..83a396df --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/csm/api/ConnectInfoTest.java @@ -0,0 +1,89 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.csm.api; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class ConnectInfoTest { + + @Test + public void constructorTestNullUrl(){ + ConnectInfo info = new ConnectInfo(null); + assertTrue(info.getUrl().equals("")); + } + @Test + public void constructorTestValidUrl(){ + ConnectInfo info = new ConnectInfo("localhost"); + assertTrue(info.getUrl().equals("localhost")); + } + @Test + public void constructorTest2NullData(){ + ConnectInfo info = new ConnectInfo(null,null,null,null); + assertTrue(info.getUrl().equals("") && info.getUserName().equals("") + && info.getUserPwd().equals("") && info.getAuthenticateMode().equals("")); + } + @Test + public void constructorTestValidData(){ + ConnectInfo info = new ConnectInfo("localhost","user","password","auth"); + assertTrue(info.getUrl().equals("localhost") && info.getUserName().equals("user") + && info.getUserPwd().equals("password") && info.getAuthenticateMode().equals("auth")); + } + @Test + public void hashCodeTest(){ + ConnectInfo info1 = new ConnectInfo("localhost","user","password","auth"); + ConnectInfo info2 = new ConnectInfo("localhost","user","password","auth"); + assertTrue(info1.hashCode() == info2.hashCode()); + } + + @Test + public void equalsTest(){ + ConnectInfo info1 = new ConnectInfo("localhost","user","password","auth"); + ConnectInfo info2 = new ConnectInfo("localhost","user","password","auth"); + assertTrue(info1.equals(info2)); + } + @Test + public void equalsTest2(){ + ConnectInfo info1 = new ConnectInfo("localhost","user","password","auth"); + assertTrue(info1.equals(info1)); + } + @Test + public void equalsTest3(){ + ConnectInfo info1 = new ConnectInfo("localhost","user","password","auth"); + assertTrue(!info1.equals(null)); + } + @Test + public void equalsTest4(){ + ConnectInfo info1 = new ConnectInfo("localhost","user","password","auth"); + assertTrue(!info1.equals(new Object())); + } + @Test + public void equalsTest5(){ + ConnectInfo info1 = new ConnectInfo(null,"user","password","auth"); + ConnectInfo info2 = new ConnectInfo("localhost","user","password","auth"); + assertTrue(!info1.equals(info2)); + } + @Test + public void equalsTest6(){ + ConnectInfo info1 = new ConnectInfo("testurl","user","password","auth"); + ConnectInfo info2 = new ConnectInfo("localhost","user","password","auth"); + assertTrue(!info1.equals(info2)); + } + + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/csm/connect/AbstractSslContextTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/csm/connect/AbstractSslContextTest.java new file mode 100644 index 00000000..20ed64d7 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/csm/connect/AbstractSslContextTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2017 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.nfvo.vnfmadapter.service.csm.connect; + +import net.sf.json.JSONObject; +import org.junit.Test; + +/** + * Created by QuanZhong on 2017/3/20. + */ +public class AbstractSslContextTest { + @Test + public void createKeyManagerTest(){ + AbstractSslContext asc = new AbstractSslContext(); + JSONObject json = new JSONObject(); + json.put("keyStore",""); + json.put("keyStorePass",""); + json.put("keyStoreType",""); + asc.createKeyManager(json); + } + + @Test + public void createTrustManagerTest(){ + AbstractSslContext asc = new AbstractSslContext(); + JSONObject json = new JSONObject(); + json.put("trustStore",""); + json.put("trustStorePass",""); + json.put("trustStoreType",""); + asc.createTrustManager(json); + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/csm/connect/HttpRequestsTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/csm/connect/HttpRequestsTest.java new file mode 100644 index 00000000..3a0a8ec3 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/csm/connect/HttpRequestsTest.java @@ -0,0 +1,98 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.csm.connect; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.httpclient.Header; +import org.junit.Test; +import org.openo.nfvo.vnfmadapter.common.VnfmException; + +public class HttpRequestsTest { + + String authenticateMode = "test"; + HttpRequests.Builder builder = new HttpRequests.Builder(authenticateMode); + + @Test + public void addHeaderTest(){ + builder.addHeader("id", "1234"); + assertTrue(true); + } + @Test + public void addHeadersTest(){ + Header header = new Header(); + builder.addHeaders(header, header); + assertNotNull(builder); + } + @Test + public void addHeadersListTest(){ + List<Header> list = new ArrayList<>(); + Header header = new Header(); + list.add(header); + builder.addHeaders(list); + assertNotNull(builder); + } + + @Test(expected = VnfmException.class) + public void setUrlTestException() throws VnfmException{ + String url=null; + String path=null; + builder.setUrl(url, path); + } + @Test(expected = VnfmException.class) + public void setUrlTestException2() throws VnfmException{ + String url=""; + String path=null; + builder.setUrl(url, path); + } + + @Test(expected = VnfmException.class) + public void setUrlTestNormal() throws VnfmException{ + String url="/test/123"; + String path="http://localhost:8080"; + builder.setUrl(url, path); + } + + @Test(expected = VnfmException.class) + public void setUrl2TestException() throws VnfmException{ + String url=null; + String path=null; + builder.setUrl(url, path,101); + } + @Test(expected = VnfmException.class) + public void setUrl2TestException2() throws VnfmException{ + String url=""; + String path=null; + builder.setUrl(url, path,101); + } + + @Test(expected = VnfmException.class) + public void setUrl2TestNormal() throws VnfmException{ + String url="/test/123"; + String path="http://localhost:8080"; + builder.setUrl(url, path,101); + } + @Test(expected = Exception.class) + public void requestTestException(){ + String res = builder.request(); + assertNotNull(res); + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslAnonymousSocketTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslAnonymousSocketTest.java new file mode 100644 index 00000000..23f3280d --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslAnonymousSocketTest.java @@ -0,0 +1,51 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.csm.connect; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.Socket; + +import org.apache.commons.httpclient.ConnectTimeoutException; +import org.apache.commons.httpclient.params.HttpConnectionParams; +import org.junit.Test; + +public class SslAnonymousSocketTest { + + @Test(expected = IOException.class) + public void createSocketTestException() throws IOException, ConnectTimeoutException { + String host= "localhost"; + int port = 29912; + InetAddress localAddress = null; + int localPort = 4859; + HttpConnectionParams params = null; + SslAnonymousSocket sslsocket = new SslAnonymousSocket(); + Socket socket = sslsocket.createSocket(host, port, localAddress, localPort, params); + } + + @Test(expected = Exception.class) + public void createSocketTestException2() throws IOException, ConnectTimeoutException { + String host= "localhost"; + int port = 29912; + InetAddress localAddress = null; + int localPort = 4859; + HttpConnectionParams params = new HttpConnectionParams(); + SslAnonymousSocket sslsocket = new SslAnonymousSocket(); + Socket socket = sslsocket.createSocket(host, port, localAddress, localPort, params); + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslCertificateSocketTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslCertificateSocketTest.java new file mode 100644 index 00000000..80156a02 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslCertificateSocketTest.java @@ -0,0 +1,79 @@ +/* + * Copyright 2017 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.nfvo.vnfmadapter.service.csm.connect; + +import org.apache.commons.httpclient.params.HttpConnectionParams; +import org.junit.Test; +import org.openo.nfvo.vnfmadapter.common.VnfmException; + +import java.io.IOException; + +/** + * Created by QuanZhong on 2017/3/20. + */ +public class SslCertificateSocketTest { + @Test + public void initTest(){ + SslCertificateSocket socket = new SslCertificateSocket(); + try { + socket.init(); + } catch (VnfmException e) { + e.printStackTrace(); + } + } + @Test + public void createSocketTest(){ + SslCertificateSocket socket = new SslCertificateSocket(); + try { + socket.createSocket("http://127.0.0.1",1234); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Test + public void createSocketTest2(){ + SslCertificateSocket socket = new SslCertificateSocket(); + try { + socket.createSocket("http://127.0.0.1",1234,null,4321,null); + } catch (IOException e) { + e.printStackTrace(); + } + } + @Test + public void createSocketTest3(){ + SslCertificateSocket socket = new SslCertificateSocket(); + try { + HttpConnectionParams params = new HttpConnectionParams(); + params.setConnectionTimeout(0); + socket.createSocket("http://127.0.0.1",1234,null,4321,params); + } catch (IOException e) { + e.printStackTrace(); + } + } + @Test + public void createSocketTest4(){ + SslCertificateSocket socket = new SslCertificateSocket(); + try { + HttpConnectionParams params = new HttpConnectionParams(); + params.setConnectionTimeout(3000); + socket.createSocket("http://127.0.0.1",1234,null,4321,params); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslProtocolSocketFactoryTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslProtocolSocketFactoryTest.java new file mode 100644 index 00000000..4ecea255 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/csm/connect/SslProtocolSocketFactoryTest.java @@ -0,0 +1,47 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.csm.connect; + +import static org.junit.Assert.*; + +import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; +import org.junit.Test; +import org.openo.nfvo.vnfmadapter.common.VnfmException; + +public class SslProtocolSocketFactoryTest { + + @Test + public void getInstanceTest(){ + SslProtocolSocketFactory factory = SslProtocolSocketFactory.getInstance(); + assertNotNull(factory); + } + + @Test(expected = VnfmException.class) + public void getTest() throws VnfmException{ + ProtocolSocketFactory factory = SslProtocolSocketFactory.getInstance().get("test"); + } + @Test + public void refreshTestException() throws VnfmException{ + SslProtocolSocketFactory.getInstance().refresh("test"); + assertTrue(true); + } + @Test + public void refreshTest() throws VnfmException{ + SslProtocolSocketFactory.getInstance().refresh("Anonymous"); + assertTrue(true); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/csm/vnf/VnfMgrVnfmTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/csm/vnf/VnfMgrVnfmTest.java new file mode 100644 index 00000000..403483f0 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/csm/vnf/VnfMgrVnfmTest.java @@ -0,0 +1,307 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.csm.vnf; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.openo.nfvo.vnfmadapter.common.ResultRequestUtil; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; + +import mockit.Mock; +import mockit.MockUp; +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; + +/** + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 10, 2016 + */ +public class VnfMgrVnfmTest { + + @Test + public void testCreateVnf() { + new MockUp<ResultRequestUtil>() { + + @Mock + public JSONObject call(JSONObject vnfmObjcet, String path, String methodName, String paramsJson) { + JSONObject resultJson = new JSONObject(); + resultJson.put("retCode", Constant.HTTP_CREATED); + JSONObject appInfo = new JSONObject(); + appInfo.put("vnfinstanceid", "id"); + appInfo.put("project_id", "project_id"); + JSONObject data = new JSONObject(); + data.put("app_info", appInfo); + resultJson.put("data", data); + return resultJson; + } + }; + String data = "{\"vnfmInfo\":{\"url\":\"url\"}}"; + JSONObject subJsonObject = JSONObject.fromObject(data); + JSONObject vnfmObjcet = new JSONObject(); + VnfMgrVnfm vnfMgrVnfm = new VnfMgrVnfm(); + JSONObject result = vnfMgrVnfm.createVnf(subJsonObject, vnfmObjcet); + + assertEquals(Constant.REST_SUCCESS, result.get("retCode")); + } + + @Test + public void testCreateVnfByBadRequest() { + new MockUp<ResultRequestUtil>() { + + @Mock + public JSONObject call(JSONObject vnfmObjcet, String path, String methodName, String paramsJson) { + JSONObject resultJson = new JSONObject(); + resultJson.put("retCode", Constant.HTTP_BAD_REQUEST); + return resultJson; + } + }; + String data = "{\"vnfmInfo\":{\"url\":\"url\"}}"; + JSONObject subJsonObject = JSONObject.fromObject(data); + VnfMgrVnfm vnfMgrVnfm = new VnfMgrVnfm(); + JSONObject vnfmObjcet = new JSONObject(); + JSONObject result = vnfMgrVnfm.createVnf(subJsonObject, vnfmObjcet); + + JSONObject resultJson = new JSONObject(); + resultJson.put("retCode", Constant.REST_FAIL); + assertEquals(resultJson, result); + } + + @Test + public void testCreateVnfByNotFound() { + new MockUp<ResultRequestUtil>() { + + @Mock + public JSONObject call(JSONObject vnfmObjcet, String path, String methodName, String paramsJson) { + JSONObject resultJson = new JSONObject(); + resultJson.put("retCode", Constant.HTTP_NOTFOUND); + return resultJson; + } + }; + String data = "{\"vnfmInfo\":{\"url\":\"url\"}}"; + JSONObject subJsonObject = JSONObject.fromObject(data); + JSONObject vnfmObjcet = new JSONObject(); + VnfMgrVnfm vnfMgrVnfm = new VnfMgrVnfm(); + JSONObject result = vnfMgrVnfm.createVnf(subJsonObject, vnfmObjcet); + + JSONObject resultJson = new JSONObject(); + resultJson.put("retCode", Constant.REST_FAIL); + assertEquals(resultJson, result); + } + + @Test + public void testCreateVnfByJSONException() { + new MockUp<ResultRequestUtil>() { + + @Mock + public JSONObject call(JSONObject vnfmObjcet, String path, String methodName, String paramsJson) { + JSONObject resultJson = new JSONObject(); + return resultJson; + } + }; + String data = "{\"vnfmInfo\":{\"url\":\"url\"}}"; + JSONObject subJsonObject = JSONObject.fromObject(data); + JSONObject vnfmObjcet = new JSONObject(); + VnfMgrVnfm vnfMgrVnfm = new VnfMgrVnfm(); + JSONObject result = vnfMgrVnfm.createVnf(subJsonObject, vnfmObjcet); + + JSONObject resultJson = new JSONObject(); + resultJson.put("retCode", Constant.REST_FAIL); + assertEquals(resultJson, result); + } + + @Test + public void testRemoveVnf() { + new MockUp<ResultRequestUtil>() { + + @Mock + public JSONObject call(JSONObject vnfmObjcet, String path, String methodName, String paramsJson) { + JSONObject resultJson = new JSONObject(); + resultJson.put("retCode", Constant.HTTP_NOCONTENT); + return resultJson; + } + }; + VnfMgrVnfm vnfMgrVnfm = new VnfMgrVnfm(); + JSONObject vnfmObject = new JSONObject(); + JSONObject vnfObject = new JSONObject(); + vnfmObject.put("url", "url"); + JSONObject result = vnfMgrVnfm.removeVnf(vnfmObject, "vnfId", vnfObject); + + JSONObject resultJson = new JSONObject(); + resultJson.put("retCode", Constant.REST_SUCCESS); + JSONObject retJson = new JSONObject(); + retJson.put("jobId", "vnfId" + "_" + Constant.DELETE); + resultJson.put("data", retJson); + assertEquals(resultJson, result); + } + + @Test + public void testRemoveVnfByCsmError() { + new MockUp<ResultRequestUtil>() { + + @Mock + public JSONObject call(JSONObject vnfmObjcet, String path, String methodName, String paramsJson) { + JSONObject resultJson = new JSONObject(); + resultJson.put("retCode", Constant.HTTP_INNERERROR); + return resultJson; + } + }; + VnfMgrVnfm vnfMgrVnfm = new VnfMgrVnfm(); + JSONObject vnfmObject = new JSONObject(); + vnfmObject.put("url", "url"); + JSONObject vnfObject = new JSONObject(); + JSONObject result = vnfMgrVnfm.removeVnf(vnfmObject, "vnfId", vnfObject); + + JSONObject resultJson = new JSONObject(); + resultJson.put("retCode", Constant.REST_FAIL); + assertEquals(resultJson, result); + } + @Test + public void getJobTestNormal(){ + new MockUp<ResultRequestUtil>(){ + @Mock + public JSONObject call(JSONObject vnfmObject, String path, String methodName, String paramsJson) { + JSONObject obj = new JSONObject(); + JSONObject dataobj = new JSONObject(); + dataobj.put("id", "2839"); + obj.put("retCode", 200); + JSONArray basics = new JSONArray(); + basics.add("test123"); + JSONObject basicsData = new JSONObject(); + basicsData.put("basic", basics); + obj.put("data", basicsData); + return obj; + } + + }; + VnfMgrVnfm vnfMgrVnfm = new VnfMgrVnfm(); + JSONObject vnfmObject = new JSONObject(); + + String jobId = "1234"; + JSONObject resp = vnfMgrVnfm.getJob(vnfmObject, jobId); + assertEquals(resp.get("retCode"),1); + } + + @Test + public void getJobTestCreatedNormal(){ + new MockUp<ResultRequestUtil>(){ + @Mock + public JSONObject call(JSONObject vnfmObject, String path, String methodName, String paramsJson) { + JSONObject obj = new JSONObject(); + JSONObject dataobj = new JSONObject(); + dataobj.put("id", "2839"); + obj.put("retCode", 201); + JSONArray basics = new JSONArray(); + basics.add("test123"); + JSONObject basicsData = new JSONObject(); + basicsData.put("basic", basics); + obj.put("data", basicsData); + return obj; + } + + }; + VnfMgrVnfm vnfMgrVnfm = new VnfMgrVnfm(); + JSONObject vnfmObject = new JSONObject(); + + String jobId = "1234"; + JSONObject resp = vnfMgrVnfm.getJob(vnfmObject, jobId); + assertEquals(resp.get("retCode"),1); + } + + @Test + public void getJobTestNullData(){ + new MockUp<ResultRequestUtil>(){ + @Mock + public JSONObject call(JSONObject vnfmObject, String path, String methodName, String paramsJson) { + JSONObject obj = new JSONObject(); + JSONObject dataobj = new JSONObject(); + dataobj.put("id", "2839"); + obj.put("retCode", 201); + JSONArray basics = new JSONArray(); + basics.add("test123"); + JSONObject basicsData = new JSONObject(); + basicsData.put("basic", basics); + obj.put("data", null); + return obj; + } + + }; + VnfMgrVnfm vnfMgrVnfm = new VnfMgrVnfm(); + JSONObject vnfmObject = new JSONObject(); + + String jobId = "1234"; + JSONObject resp = vnfMgrVnfm.getJob(vnfmObject, jobId); + assertEquals(resp.get("retCode"),-1); + } + + @Test + public void getJobTestInternalError(){ + new MockUp<ResultRequestUtil>(){ + @Mock + public JSONObject call(JSONObject vnfmObject, String path, String methodName, String paramsJson) { + JSONObject obj = new JSONObject(); + JSONObject dataobj = new JSONObject(); + dataobj.put("id", "2839"); + obj.put("retCode", 500); + JSONArray basics = new JSONArray(); + basics.add("test123"); + JSONObject basicsData = new JSONObject(); + basicsData.put("basic", basics); + obj.put("data", null); + return obj; + } + + }; + VnfMgrVnfm vnfMgrVnfm = new VnfMgrVnfm(); + JSONObject vnfmObject = new JSONObject(); + + String jobId = "1234"; + JSONObject resp = vnfMgrVnfm.getJob(vnfmObject, jobId); + assertEquals(resp.get("retCode"),-1); + } + + + @Test + public void testScaleVnf() { + new MockUp<ResultRequestUtil>() { + + @Mock + public JSONObject call(JSONObject vnfmObjcet, String path, String methodName, String paramsJson) { + JSONObject resultJson = new JSONObject(); + resultJson.put("retCode", Constant.HTTP_CREATED); + JSONObject appInfo = new JSONObject(); + appInfo.put("vnfinstanceid", "id"); + appInfo.put("project_id", "project_id"); + JSONObject data = new JSONObject(); + data.put("app_info", appInfo); + resultJson.put("data", data); + return resultJson; + } + }; + String data = "{\"vnfmInfo\":{\"url\":\"url\"}}"; + JSONObject subJsonObject = JSONObject.fromObject(data); + JSONObject vnfmObjcet = new JSONObject(); + VnfMgrVnfm vnfMgrVnfm = new VnfMgrVnfm(); + JSONObject result = vnfMgrVnfm.scaleVnf(subJsonObject,vnfmObjcet,"test123","test123"); + + assertEquals(Constant.REST_SUCCESS, result.get("retCode")); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/dao/impl/VnfmDaoImplTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/dao/impl/VnfmDaoImplTest.java new file mode 100644 index 00000000..4564d69b --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/dao/impl/VnfmDaoImplTest.java @@ -0,0 +1,64 @@ +/* + * Copyright 2017 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.nfvo.vnfmadapter.service.dao.impl; + +import junit.framework.Assert; +import org.junit.Test; +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.nfvo.vnfmadapter.service.entity.Vnfm; + +/** + * Created by QuanZhong on 2017/3/17. + */ +public class VnfmDaoImplTest { + + @Test + public void insertVnfm() throws ServiceException { + VnfmDaoImpl dao = new VnfmDaoImpl(); + dao.insertVnfm(new Vnfm()); + Assert.assertTrue(true); + } + + @Test + public void deleteVnfm() throws ServiceException { + VnfmDaoImpl dao = new VnfmDaoImpl(); + dao.deleteVnfm("abc"); + Assert.assertTrue(true); + } + + @Test + public void updateVnfm() throws ServiceException { + VnfmDaoImpl dao = new VnfmDaoImpl(); + dao.updateVnfm(new Vnfm()); + Assert.assertTrue(true); + } + + @Test + public void indexVnfms() throws ServiceException { + VnfmDaoImpl dao = new VnfmDaoImpl(); + dao.insertVnfm(new Vnfm()); + Assert.assertTrue(true); + + } + + @Test + public void getVnfmById() { + VnfmDaoImpl dao = new VnfmDaoImpl(); + dao.getVnfmById("abc"); + Assert.assertTrue(true); + + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/entity/VnfmTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/entity/VnfmTest.java new file mode 100644 index 00000000..c9996788 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/entity/VnfmTest.java @@ -0,0 +1,77 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.entity; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Test; + +public class VnfmTest { + Vnfm vnfm; + + @Before + public void setUp(){ + vnfm = new Vnfm(); + vnfm.setId("123"); + vnfm.setId("v1"); + vnfm.setVnfdId("1234"); + vnfm.setVnfPackageId("abcd"); + } + + @Test + public void hashCodeTest(){ + Vnfm tempVnfm = new Vnfm(); + tempVnfm.setId("123"); + tempVnfm.setId("v1"); + tempVnfm.setVnfdId("1234"); + tempVnfm.setVnfPackageId("abcd"); + assertTrue(vnfm.hashCode() == tempVnfm.hashCode()); + } + + @Test + public void equalsTest1(){ + Vnfm tempVnfm = new Vnfm(); + tempVnfm.setId("123"); + tempVnfm.setId("v1"); + tempVnfm.setVnfdId("1234"); + tempVnfm.setVnfPackageId("abcd"); + assertTrue(vnfm.equals(tempVnfm)); + } + + @Test + public void equalsTest2(){ + assertTrue(vnfm.equals(vnfm)); + } + + @Test + public void equalsTest3(){ + + assertTrue(!vnfm.equals(null)); + } + @Test + public void equalsTest4(){ + + assertTrue(!vnfm.equals(new Object())); + } + @Test + public void equalsTest5(){ + + assertTrue(!vnfm.equals(new Object())); + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/process/AuthMgrTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/process/AuthMgrTest.java new file mode 100644 index 00000000..718423c9 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/process/AuthMgrTest.java @@ -0,0 +1,64 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.process; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.common.servicetoken.VnfmRestfulUtil; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; + +import mockit.Mock; +import mockit.MockUp; +import net.sf.json.JSONObject; + +public class AuthMgrTest { + + @Test + public void testAuthTokenByDomainNameByJSONException() { + AuthMgr authMgr = new AuthMgr(); + String data = "{\"auth\":{}}"; + JSONObject params = JSONObject.fromObject(data); + + JSONObject result = authMgr.authToken(params); + + JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_FAIL); + restJson.put("data", "JSONException"); + assertEquals(restJson, result); + } + + @Test + public void testAuthToken() { + new MockUp<VnfmRestfulUtil>() { + + @Mock + public RestfulResponse getRestResByDefault(String auth, String method, JSONObject authParams) { + RestfulResponse response = null; + return response; + } + }; + + AuthMgr authMgr = new AuthMgr(); + String data = "{\"auth\":{\"identity\":{\"password\":{\"user\":{\"name\":\"om_team\",\"password\":\"123\"}}}}}"; + JSONObject params = JSONObject.fromObject(data); + + JSONObject result = authMgr.authToken(params); + assertEquals(Constant.REST_SUCCESS, result.getInt("retCode")); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/process/RegisterMgrTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/process/RegisterMgrTest.java new file mode 100644 index 00000000..eee4e1df --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/process/RegisterMgrTest.java @@ -0,0 +1,66 @@ +/* + * Copyright 2017 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.nfvo.vnfmadapter.service.process; + +import org.junit.Test; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.common.servicetoken.VnfmRestfulUtil; + +import mockit.Mock; +import mockit.MockUp; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Jan 13, 2017 + */ +public class RegisterMgrTest { + + @Test + public void testRegister() { + new MockUp<VnfmRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(String url, String methodType, String params) { + RestfulResponse rsp = new RestfulResponse(); + rsp.setStatus(200); + return rsp; + } + }; + RegisterMgr register = new RegisterMgr(); + register.register(); + } + + @Test + public void testUnRegister() { + new MockUp<VnfmRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(String url, String methodType, String params) { + RestfulResponse rsp = new RestfulResponse(); + rsp.setStatus(200); + return rsp; + } + }; + RegisterMgr register = new RegisterMgr(); + register.unRegister(); + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/process/VnfMgrTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/process/VnfMgrTest.java new file mode 100644 index 00000000..5f2b94d1 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/process/VnfMgrTest.java @@ -0,0 +1,497 @@ +/* + * Copyright 2016-2017 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.nfvo.vnfmadapter.service.process; + +import static org.junit.Assert.assertEquals; + +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.nfvo.vnfmadapter.common.ResultRequestUtil; +import org.openo.nfvo.vnfmadapter.common.VnfmUtil; +import org.openo.nfvo.vnfmadapter.service.adapter.impl.AdapterResourceManager; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.csm.vnf.VnfMgrVnfm; +import org.openo.nfvo.vnfmadapter.service.dao.impl.VnfmDaoImpl; +import org.openo.nfvo.vnfmadapter.service.dao.inf.VnfmDao; +import org.openo.nfvo.vnfmadapter.service.entity.Vnfm; + +import mockit.Mock; +import mockit.MockUp; +import net.sf.json.JSONArray; +import net.sf.json.JSONException; +import net.sf.json.JSONObject; + +public class VnfMgrTest { + + private VnfmDao vnfmDao; + + private VnfMgr vnfMgr; + + @Before + public void setUp() { + vnfMgr = new VnfMgr(); + vnfmDao = new VnfmDaoImpl(); + vnfMgr.setVnfmDao(vnfmDao); + } + + @Test + public void testAddVnfByInvalidateDataVnfInfoNull() { + String data = "{}"; + JSONObject subJsonObject = JSONObject.fromObject(data); + VnfMgr vnfMgr = new VnfMgr(); + JSONObject result = vnfMgr.addVnf(subJsonObject, "vnmfId"); + + JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_FAIL); + assertEquals(restJson, result); + } + + @Test + public void testAddVnfByInvalidateDataVnfInfoEmpty() { + String data = "{}"; + JSONObject subJsonObject = JSONObject.fromObject(data); + VnfMgr vnfMgr = new VnfMgr(); + JSONObject result = vnfMgr.addVnf(subJsonObject, "vnmfId"); + + JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_FAIL); + assertEquals(restJson, result); + } + + @Test + public void testAddVnfByVnfmObjcetIsNullObject() { + new MockUp<VnfmUtil>() { + + @Mock + public JSONObject getVnfmById(String vnfmId) { + return new JSONObject(true); + } + }; + String data = + "{\"soId\": \"soId\",\"vapp_info\":{\"vnfm_id\":\"vnfm_id\",\"soId\": \"soId\",\"do_id\": \"do_id\"}}"; + JSONObject subJsonObject = JSONObject.fromObject(data); + VnfMgr vnfMgr = new VnfMgr(); + JSONObject result = vnfMgr.addVnf(subJsonObject, "vnmfId"); + + JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_FAIL); + assertEquals(restJson, result); + } + + @Test + public void testAddVnfByVnfmObjcetTypeEmpty() { + new MockUp<VnfmUtil>() { + + @Mock + public JSONObject getVnfmById(String vnfmId) { + JSONObject obj = new JSONObject(); + obj.put("type", ""); + return obj; + } + }; + String data = + "{\"soId\": \"soId\",\"vapp_info\":{\"vnfm_id\":\"vnfm_id\",\"soId\": \"soId\",\"do_id\": \"do_id\"}}"; + JSONObject subJsonObject = JSONObject.fromObject(data); + VnfMgr vnfMgr = new VnfMgr(); + JSONObject result = vnfMgr.addVnf(subJsonObject, "vnmfId"); + + JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_FAIL); + assertEquals(restJson, result); + } + + @Test + public void testAddVnf() { + new MockUp<VnfmUtil>() { + + @Mock + public JSONObject getVnfmById(String vnfmId) { + JSONObject obj = new JSONObject(); + obj.put("type", "hw"); + obj.put("vnfmId", "123"); + obj.put("userName", "admin"); + obj.put("password", "admin"); + obj.put("url", "https://10.2.31.2:30001"); + return obj; + } + }; + + new MockUp<VnfMgrVnfm>() { + + @Mock + public JSONObject createVnf(JSONObject subJsonObject, JSONObject vnfmObjcet) { + JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_SUCCESS); + return restJson; + } + }; + + new MockUp<AdapterResourceManager>() { + + @Mock + public JSONObject uploadVNFPackage(JSONObject subJsonObject, Map<String, String> conMap) { + JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_SUCCESS); + restJson.put("vnfdId", "123"); + return restJson; + } + }; + + String data = + "{\"vnfPackageId\": \"vnfPackageId\",\"vnfId\": \"vnfId\",\"additionalParam\":{\"parameters\":{\"input\":\"input\"}}}"; + JSONObject subJsonObject = JSONObject.fromObject(data); + VnfMgr vnfMgr = new VnfMgr(); + JSONObject result = vnfMgr.addVnf(subJsonObject, "vnfmId"); + + JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_SUCCESS); + assertEquals(restJson, result); + } + + @Test + public void testDeleteVnf() { + new MockUp<VnfmUtil>() { + + @Mock + public JSONObject getVnfmById(String vnfmId) { + JSONObject obj = new JSONObject(); + obj.put("type", "hw"); + obj.put("vnfmId", "123"); + obj.put("userName", "admin"); + obj.put("password", "admin"); + obj.put("url", "https://10.2.31.2:30001"); + return obj; + } + }; + new MockUp<VnfMgrVnfm>() { + + @Mock + public JSONObject removeVnf(JSONObject vnfmObject, String vnfId, JSONObject vnfObject) { + JSONObject obj = new JSONObject(); + obj.put("retCode", Constant.REST_SUCCESS); + return obj; + } + }; + VnfMgr vnfMgr = new VnfMgr(); + JSONObject vnfObject = new JSONObject(); + JSONObject result = vnfMgr.deleteVnf("vnfId", "vnfmId", vnfObject); + + JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_SUCCESS); + assertEquals(restJson, result); + } + + @Test + public void testDeleteVnfByVnfmObjcetIsNullObject() { + new MockUp<VnfmUtil>() { + + @Mock + public JSONObject getVnfmById(String vnfmId) { + JSONObject obj = new JSONObject(true); + return obj; + } + }; + VnfMgr vnfMgr = new VnfMgr(); + JSONObject vnfObject = new JSONObject(); + JSONObject result = vnfMgr.deleteVnf("vnfId", "vnfmId", vnfObject); + + JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_FAIL); + assertEquals(restJson, result); + + } + + @Test + public void testDeleteVnfByException() { + new MockUp<VnfmUtil>() { + + @Mock + public JSONObject getVnfmById(String vnfmId) { + throw new JSONException(); + } + }; + VnfMgr vnfMgr = new VnfMgr(); + JSONObject vnfObject = new JSONObject(); + JSONObject result = vnfMgr.deleteVnf("vnfId", "vnfmId", vnfObject); + + JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_FAIL); + assertEquals(restJson, result); + + } + + @Test + public void testGetVnf() { + new MockUp<VnfmUtil>() { + + @Mock + public JSONObject getVnfmById(String vnfmId) { + JSONObject obj = new JSONObject(); + obj.put("type", "hw"); + obj.put("vnfmId", "123"); + obj.put("userName", "admin"); + obj.put("password", "admin"); + obj.put("url", "https://10.2.31.2:30001"); + return obj; + } + }; + + new MockUp<VnfmDaoImpl>() { + + @Mock + public Vnfm getVnfmById(String vnfmId) { + Vnfm obj = new Vnfm(); + obj.setId("123"); + obj.setVersion("v2.0"); + obj.setVnfdId("234"); + obj.setVnfPackageId("123"); + return obj; + } + }; + + new MockUp<ResultRequestUtil>() { + + @Mock + public JSONObject call(JSONObject vnfmObjcet, String path, String methodName, String paramsJson) { + JSONObject resultJson = new JSONObject(); + resultJson.put("retCode", Constant.HTTP_OK); + JSONObject data = new JSONObject(); + + JSONArray result = new JSONArray(); + JSONObject basicInfo = new JSONObject(); + basicInfo.put("id", "NE=345"); + basicInfo.put("vapp_name", "sc"); + basicInfo.put("status", "active"); + result.add(basicInfo); + data.put("basic", result); + resultJson.put("data", data.toString()); + return resultJson; + } + }; + + JSONObject result = vnfMgr.getVnf("vnfId", "vnfmId"); + + JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_SUCCESS); + result.remove("vnfInfo"); + assertEquals(restJson, result); + } + + @Test + public void testGetVnfFail() { + new MockUp<VnfmUtil>() { + + @Mock + public JSONObject getVnfmById(String vnfmId) { + JSONObject obj = new JSONObject(true); + return obj; + } + }; + + JSONObject result = vnfMgr.getVnf("vnfId", "vnfmId"); + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + assertEquals(restJson, result); + } + + @Test + public void testGetVnfFail1() { + new MockUp<VnfmUtil>() { + + @Mock + public JSONObject getVnfmById(String vnfmId) { + throw new JSONException(); + } + }; + + JSONObject result = vnfMgr.getVnf("vnfId", "vnfmId"); + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + assertEquals(restJson, result); + } + + @Test + public void testSaveVnfInfo() { + new MockUp<VnfmDaoImpl>() { + + @Mock + public int insertVnfm(Vnfm vnfm) throws ServiceException { + return 1; + } + }; + + VnfMgr vnfMgr = new VnfMgr(); + VnfmDao dao = new VnfmDaoImpl(); + vnfMgr.setVnfmDao(dao); + JSONObject vnfObject = new JSONObject(); + vnfObject.put("retCode", Constant.REST_SUCCESS); + vnfObject.put("vnfInstanceId", "vnfInstanceId"); + vnfObject.put("vnfPackageId", "vnfPackageId"); + JSONObject resObject = new JSONObject(); + resObject.put("vnfdVersion", "vnfdVersion"); + resObject.put("vnfdId", "vnfdId"); + vnfMgr.saveVnfInfo(vnfObject, resObject); + } + + @Test + public void testSaveVnfInfoFail() { + new MockUp<VnfmDaoImpl>() { + + @Mock + public int insertVnfm(Vnfm vnfm) throws ServiceException { + return 1; + } + }; + + VnfMgr vnfMgr = new VnfMgr(); + VnfmDao dao = new VnfmDaoImpl(); + vnfMgr.setVnfmDao(dao); + JSONObject vnfObject = new JSONObject(); + vnfObject.put("retCode", Constant.REST_FAIL); + vnfObject.put("vnfInstanceId", "vnfInstanceId"); + vnfObject.put("vnfPackageId", "vnfPackageId"); + JSONObject resObject = new JSONObject(); + resObject.put("vnfdVersion", "vnfdVersion"); + resObject.put("vnfdId", "vnfdId"); + vnfMgr.saveVnfInfo(vnfObject, resObject); + } + + @Test + public void testSaveVnfInfoServiceException() { + new MockUp<VnfmDaoImpl>() { + + @Mock + public int insertVnfm(Vnfm vnfm) throws ServiceException { + throw new ServiceException(); + } + }; + + VnfMgr vnfMgr = new VnfMgr(); + VnfmDao dao = new VnfmDaoImpl(); + vnfMgr.setVnfmDao(dao); + JSONObject vnfObject = new JSONObject(); + vnfObject.put("retCode", Constant.REST_SUCCESS); + vnfObject.put("vnfInstanceId", "vnfInstanceId"); + vnfObject.put("vnfPackageId", "vnfPackageId"); + JSONObject resObject = new JSONObject(); + resObject.put("vnfdVersion", "vnfdVersion"); + resObject.put("vnfdId", "vnfdId"); + vnfMgr.saveVnfInfo(vnfObject, resObject); + } + + @Test + public void testGetJob() { + new MockUp<VnfmUtil>() { + + @Mock + public JSONObject getVnfmById(String vnfmId) { + JSONObject obj = new JSONObject(); + obj.put("test", "success"); + return obj; + } + }; + + new MockUp<VnfMgrVnfm>() { + + @Mock + public JSONObject getJob(JSONObject vnfmObject, String jobId) { + JSONObject res = new JSONObject(); + res.put(Constant.RETCODE, Constant.REST_SUCCESS); + return res; + } + }; + VnfMgr vnfMgr = new VnfMgr(); + JSONObject result = vnfMgr.getJob("", ""); + + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_SUCCESS); + assertEquals(restJson, result); + } + + @Test + public void testGetJobFail() { + new MockUp<VnfmUtil>() { + + @Mock + public JSONObject getVnfmById(String vnfmId) { + return new JSONObject(); + } + }; + VnfMgr vnfMgr = new VnfMgr(); + JSONObject result = vnfMgr.getJob("", ""); + + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + assertEquals(restJson, result); + } + + @Test + public void testGetJobFail1() { + new MockUp<VnfmUtil>() { + + @Mock + public JSONObject getVnfmById(String vnfmId) { + return new JSONObject(true); + } + }; + VnfMgr vnfMgr = new VnfMgr(); + JSONObject result = vnfMgr.getJob("", ""); + + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + assertEquals(restJson, result); + } + @Test + public void testScaleVnf() { + new MockUp<VnfmUtil>() { + + @Mock + public JSONObject getVnfmById(String vnfmId) { + JSONObject obj = new JSONObject(); + obj.put("type", "hw"); + obj.put("vnfmId", "123"); + obj.put("userName", "admin"); + obj.put("password", "admin"); + obj.put("url", "https://10.2.31.2:30001"); + return obj; + } + }; + + new MockUp<VnfMgrVnfm>() { + + @Mock + public JSONObject scaleVnf(JSONObject vnfObject, JSONObject vnfmObject, String vnfmId, String vnfInstanceId) { + JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_SUCCESS); + return restJson; + } + }; + + String data = + "{\"vnfPackageId\": \"vnfPackageId\",\"vnfId\": \"vnfId\",\"additionalParam\":{\"parameters\":{\"input\":\"input\"}}}"; + JSONObject subJsonObject = JSONObject.fromObject(data); + VnfMgr vnfMgr = new VnfMgr(); + JSONObject result = vnfMgr.scaleVNF(subJsonObject,"testId","testId"); + + JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_SUCCESS); + assertEquals(restJson, result); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/process/VnfResourceMgrTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/process/VnfResourceMgrTest.java new file mode 100644 index 00000000..c706178b --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/process/VnfResourceMgrTest.java @@ -0,0 +1,235 @@ +/* + * Copyright 2016-2017 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.nfvo.vnfmadapter.service.process; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.vnfmadapter.common.servicetoken.VnfmRestfulUtil; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; + +import mockit.Mock; +import mockit.MockUp; +import net.sf.json.JSONObject; + +/** + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 9, 2016 + */ +public class VnfResourceMgrTest { + + @Test + public void testgrantVnfResource() { + + String data = + "{\"type\": \"instantiation\",\"operation_right\": \"increase\",\"vnf_name\": \"vnf_name\",\"vm_list\": [{\"vm_flavor\": {\"storage\": [{\"vol_type\": \"local_volume\",\"vol_size\": \"2\",\"storage_type\": \"local_image\",\"disk_size\": \"100\"}],\"num_cpus\": \"6\",\"mem_size\": \"8\"},\"init_number\": \"1\"}],\"version\": \"version\",\"template_id\": \"template_id\",\"template_name\": \"template_name\",\"plan_id\": \"plan_id\",\"plan_name\": \"plan_name\",\"project_id\": \"project_id\",\"project_name\": \"project_name\",\"creator\": \"creator\",\"status\": \"status\",\"tenant\": \"tenant\",\"parent_tenant\": \"parent_tenant\",\"vnfd_id\": \"vnfd_id\",\"location\": \"location\",\"dr_location\": \"dr_location\",\"nfvo_id\": \"nfvo_id\"}"; + JSONObject vnfObj = JSONObject.fromObject(data); + VnfResourceMgr vnfResourceMgr = new VnfResourceMgr(); + JSONObject result = vnfResourceMgr.grantVnfResource(vnfObj, "vnfId", "vnfmId"); + + JSONObject retJson = new JSONObject(); + retJson.put("retCode", Constant.REST_FAIL); + retJson.put("errorMsg", "params parse exception"); + assertEquals(retJson, result); + } + + @Test + public void testgrantVnfResourceSuccess() { + new MockUp<VnfmRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(String url, String methodType, String params) { + RestfulResponse rsp = new RestfulResponse(); + rsp.setStatus(200); + rsp.setResponseJson(new JSONObject().toString()); + return rsp; + } + }; + + JSONObject vnfObj = new JSONObject(); + String data = + "{\"type\": \"instantiation\",\"location\": \"RomaRespool\",\"version\":\"V500R001C20\",\"vendor\": \"V500R001C20B001\",\"tenant\": \"admin\",\"vnf_id\":\"NE=1304\",\"vnfm_id\": \"9a49755d-8050-4369-9e7d-0a0855097585\",\"project_id\":\"\",\"operation_right\": \"increase\",\"vnf_name\": \"wangyuans4\",\"vim_id\":\"\",\"dr_location\": \"RomaRespool\",\"nfvo_id\": \"\",\"vnf_type\": \"vNGFW\",\"plan_id\":\"V4\",\"plan_name\": \"V4\",\"vnfd_id\": \"vNGFW\",\"vm_list\": [{\"vm_flavor\":{\"location\": \"\",\"priority\": \"1\",\"storage\": [{\"vol_type\":\"local_volume\",\"vol_size\": \"200\"},{\"storage_type\": \"local_image\",\"disk_size\":\"80\"}],\"vdu_name\": \"OMU\",\"num_cpus\": \"4\",\"mem_size\": \"8192\"},\"init_number\":\"1\"}],\"ex_vim_list\": []}"; + vnfObj = JSONObject.fromObject(data); + VnfResourceMgr grantTest = new VnfResourceMgr(); + JSONObject result = grantTest.grantVnfResource(vnfObj, "1111", "abc"); + + JSONObject retJson = new JSONObject(); + assertEquals(retJson, result); + } + + @Test + public void testgrantVnfResourceSuccess1() { + new MockUp<VnfmRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(String url, String methodType, String params) { + RestfulResponse rsp = new RestfulResponse(); + rsp.setStatus(200); + rsp.setResponseJson(new JSONObject().toString()); + return rsp; + } + }; + + JSONObject vnfObj = new JSONObject(); + String data = + "{\"type\": \"instantiation\",\"location\": \"RomaRespool\",\"version\":\"V500R001C20\",\"vendor\": \"V500R001C20B001\",\"tenant\": \"admin\",\"vnf_id\":\"NE=1304\",\"vnfm_id\": \"9a49755d-8050-4369-9e7d-0a0855097585\",\"project_id\":\"\",\"operation_right\": \"decrease\",\"vnf_name\": \"wangyuans4\",\"vim_id\":\"\",\"dr_location\": \"RomaRespool\",\"nfvo_id\": \"\",\"vnf_type\": \"vNGFW\",\"plan_id\":\"V4\",\"plan_name\": \"V4\",\"vnfd_id\": \"vNGFW\",\"vm_list\": [{\"vm_flavor\":{\"location\": \"\",\"priority\": \"1\",\"storage\": [{\"vol_type\":\"local_volume\",\"vol_size\": \"200\"},{\"storage_type\": \"local_image\",\"disk_size\":\"80\"}],\"vdu_name\": \"OMU\",\"num_cpus\": \"4\",\"mem_size\": \"8192\"},\"init_number\":\"1\"}],\"ex_vim_list\": []}"; + vnfObj = JSONObject.fromObject(data); + VnfResourceMgr grantTest = new VnfResourceMgr(); + JSONObject result = grantTest.grantVnfResource(vnfObj, "1111", "abc"); + + JSONObject retJson = new JSONObject(); + assertEquals(retJson, result); + } + + @Test + public void testgrantVnfResourceSuccess2() { + new MockUp<VnfmRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(String url, String methodType, String params) { + RestfulResponse rsp = new RestfulResponse(); + rsp.setStatus(200); + rsp.setResponseJson(new JSONObject().toString()); + return rsp; + } + }; + + JSONObject vnfObj = new JSONObject(); + String data = + "{\"type\": \"scale\",\"location\": \"RomaRespool\",\"version\":\"V500R001C20\",\"vendor\": \"V500R001C20B001\",\"tenant\": \"admin\",\"vnf_id\":\"NE=1304\",\"vnfm_id\": \"9a49755d-8050-4369-9e7d-0a0855097585\",\"project_id\":\"\",\"operation_right\": \"decrease\",\"vnf_name\": \"wangyuans4\",\"vim_id\":\"\",\"dr_location\": \"RomaRespool\",\"nfvo_id\": \"\",\"vnf_type\": \"vNGFW\",\"plan_id\":\"V4\",\"plan_name\": \"V4\",\"vnfd_id\": \"vNGFW\",\"vm_list\": [{\"vm_flavor\":{\"location\": \"\",\"priority\": \"1\",\"storage\": [{\"vol_type\":\"local_volume\",\"vol_size\": \"200\"},{\"storage_type\": \"local_image\",\"disk_size\":\"80\"}],\"vdu_name\": \"OMU\",\"num_cpus\": \"4\",\"mem_size\": \"8192\"},\"init_number\":\"1\"}],\"ex_vim_list\": []}"; + vnfObj = JSONObject.fromObject(data); + VnfResourceMgr grantTest = new VnfResourceMgr(); + JSONObject result = grantTest.grantVnfResource(vnfObj, "1111", "abc"); + + JSONObject retJson = new JSONObject(); + assertEquals(retJson, result); + } + + @Test + public void testgrantVnfResourceSuccess3() { + new MockUp<VnfmRestfulUtil>() { + + @Mock + public RestfulResponse getRemoteResponse(String url, String methodType, String params) { + RestfulResponse rsp = new RestfulResponse(); + rsp.setStatus(200); + rsp.setResponseJson(new JSONObject().toString()); + return rsp; + } + }; + + JSONObject vnfObj = new JSONObject(); + String data = + "{\"type\": \"scale\",\"location\": \"RomaRespool\",\"version\":\"V500R001C20\",\"vendor\": \"V500R001C20B001\",\"tenant\": \"admin\",\"vnf_id\":\"NE=1304\",\"vnfm_id\": \"9a49755d-8050-4369-9e7d-0a0855097585\",\"project_id\":\"\",\"operation_right\": \"increase\",\"vnf_name\": \"wangyuans4\",\"vim_id\":\"\",\"dr_location\": \"RomaRespool\",\"nfvo_id\": \"\",\"vnf_type\": \"vNGFW\",\"plan_id\":\"V4\",\"plan_name\": \"V4\",\"vnfd_id\": \"vNGFW\",\"vm_list\": [{\"vm_flavor\":{\"location\": \"\",\"priority\": \"1\",\"storage\": [{\"vol_type\":\"local_volume\",\"vol_size\": \"200\"},{\"storage_type\": \"local_image\",\"disk_size\":\"80\"}],\"vdu_name\": \"OMU\",\"num_cpus\": \"4\",\"mem_size\": \"8192\"},\"init_number\":\"1\"}],\"ex_vim_list\": []}"; + vnfObj = JSONObject.fromObject(data); + VnfResourceMgr grantTest = new VnfResourceMgr(); + JSONObject result = grantTest.grantVnfResource(vnfObj, "1111", "abc"); + + JSONObject retJson = new JSONObject(); + assertEquals(retJson, result); + } + + @Test + public void testgrantVnfResourceByResMapNull() { + + String data = + "{\"type\": \"instantiation\",\"operation_right\": \"increase\",\"vnf_name\": \"vnf_name\",\"vm_list\": [{\"vm_flavors\": {\"storage\": [{\"vol_type\": \"local_volume\",\"vol_size\": \"2\",\"storage_type\": \"local_image\",\"disk_size\": \"100\"}],\"num_cpus\": \"6\",\"mem_size\": \"8\"},\"init_number\": \"1\"}],\"version\": \"version\",\"template_id\": \"template_id\",\"template_name\": \"template_name\",\"plan_id\": \"plan_id\",\"plan_name\": \"plan_name\",\"project_id\": \"project_id\",\"project_name\": \"project_name\",\"creator\": \"creator\",\"status\": \"status\",\"tenant\": \"tenant\",\"parent_tenant\": \"parent_tenant\",\"vnfd_id\": \"vnfd_id\",\"location\": \"location\",\"dr_location\": \"dr_location\",\"nfvo_id\": \"nfvo_id\"}"; + JSONObject vnfObj = JSONObject.fromObject(data); + VnfResourceMgr vnfResourceMgr = new VnfResourceMgr(); + JSONObject result = vnfResourceMgr.grantVnfResource(vnfObj, "vnfId", "vnfmId"); + + JSONObject retJson = new JSONObject(); + retJson.put("retCode", Constant.REST_FAIL); + retJson.put("errorMsg", "resource params error"); + assertEquals(retJson, result); + } + + @Test + public void testgrantVnfResourceByTypeIsEmpty() { + String data = + "{\"type\": \"\",\"operation_right\": \"increase\",\"vnf_name\": \"vnf_name\",\"vm_list\": [{\"vm_flavor\": {\"storage\": [{\"vol_type\": \"local_volume\",\"vol_size\": \"2\",\"storage_type\": \"local_image\",\"disk_size\": \"100\"}],\"num_cpus\": \"6\",\"mem_size\": \"8\"},\"init_number\": \"1\"}],\"version\": \"version\",\"template_id\": \"template_id\",\"template_name\": \"template_name\",\"plan_id\": \"plan_id\",\"plan_name\": \"plan_name\",\"project_id\": \"project_id\",\"project_name\": \"project_name\",\"creator\": \"creator\",\"status\": \"status\",\"tenant\": \"tenant\",\"parent_tenant\": \"parent_tenant\",\"vnfd_id\": \"vnfd_id\",\"location\": \"location\",\"dr_location\": \"dr_location\",\"nfvo_id\": \"nfvo_id\"}"; + JSONObject vnfObj = JSONObject.fromObject(data); + VnfResourceMgr vnfResourceMgr = new VnfResourceMgr(); + JSONObject result = vnfResourceMgr.grantVnfResource(vnfObj, "vnfId", "vnfmId"); + + JSONObject retJson = new JSONObject(); + retJson.put("retCode", Constant.REST_FAIL); + retJson.put("errorMsg", "basic params error"); + assertEquals(retJson, result); + } + + @Test + public void testgrantVnfResourceByVnfNameIsEmpty() { + String data = + "{\"type\": \"instantiation\",\"operation_right\": \"increase\",\"vnf_name\": \"\",\"vm_list\": [{\"vm_flavor\": {\"storage\": [{\"vol_type\": \"local_volume\",\"vol_size\": \"2\",\"storage_type\": \"local_image\",\"disk_size\": \"100\"}],\"num_cpus\": \"6\",\"mem_size\": \"8\"},\"init_number\": \"1\"}],\"version\": \"version\",\"template_id\": \"template_id\",\"template_name\": \"template_name\",\"plan_id\": \"plan_id\",\"plan_name\": \"plan_name\",\"project_id\": \"project_id\",\"project_name\": \"project_name\",\"creator\": \"creator\",\"status\": \"status\",\"tenant\": \"tenant\",\"parent_tenant\": \"parent_tenant\",\"vnfd_id\": \"vnfd_id\",\"location\": \"location\",\"dr_location\": \"dr_location\",\"nfvo_id\": \"nfvo_id\"}"; + JSONObject vnfObj = JSONObject.fromObject(data); + VnfResourceMgr vnfResourceMgr = new VnfResourceMgr(); + JSONObject result = vnfResourceMgr.grantVnfResource(vnfObj, "vnfId", "vnfmId"); + + JSONObject retJson = new JSONObject(); + retJson.put("retCode", Constant.REST_FAIL); + retJson.put("errorMsg", "basic params error"); + assertEquals(retJson, result); + } + + @Test + public void testgrantVnfResourceByVnfIdIsEmpty() { + String data = + "{\"type\": \"instantiation\",\"operation_right\": \"increase\",\"vnf_name\": \"vnf_name\",\"vm_list\": [{\"vm_flavor\": {\"storage\": [{\"vol_type\": \"local_volume\",\"vol_size\": \"2\",\"storage_type\": \"local_image\",\"disk_size\": \"100\"}],\"num_cpus\": \"6\",\"mem_size\": \"8\"},\"init_number\": \"1\"}],\"version\": \"version\",\"template_id\": \"template_id\",\"template_name\": \"template_name\",\"plan_id\": \"plan_id\",\"plan_name\": \"plan_name\",\"project_id\": \"project_id\",\"project_name\": \"project_name\",\"creator\": \"creator\",\"status\": \"status\",\"tenant\": \"tenant\",\"parent_tenant\": \"parent_tenant\",\"vnfd_id\": \"vnfd_id\",\"location\": \"location\",\"dr_location\": \"dr_location\",\"nfvo_id\": \"nfvo_id\"}"; + JSONObject vnfObj = JSONObject.fromObject(data); + VnfResourceMgr vnfResourceMgr = new VnfResourceMgr(); + JSONObject result = vnfResourceMgr.grantVnfResource(vnfObj, "", "vnfmId"); + + JSONObject retJson = new JSONObject(); + retJson.put("retCode", Constant.REST_FAIL); + retJson.put("errorMsg", "basic params error"); + assertEquals(retJson, result); + } + + @Test + public void testgrantVnfResourceByRequestTypeIsEmpty() { + String data = + "{\"type\": \"instantiation\",\"operation_right\": \"\",\"vnf_name\": \"vnf_name\",\"vm_list\": [{\"vm_flavor\": {\"storage\": [{\"vol_type\": \"local_volume\",\"vol_size\": \"2\",\"storage_type\": \"local_image\",\"disk_size\": \"100\"}],\"num_cpus\": \"6\",\"mem_size\": \"8\"},\"init_number\": \"1\"}],\"version\": \"version\",\"template_id\": \"template_id\",\"template_name\": \"template_name\",\"plan_id\": \"plan_id\",\"plan_name\": \"plan_name\",\"project_id\": \"project_id\",\"project_name\": \"project_name\",\"creator\": \"creator\",\"status\": \"status\",\"tenant\": \"tenant\",\"parent_tenant\": \"parent_tenant\",\"vnfd_id\": \"vnfd_id\",\"location\": \"location\",\"dr_location\": \"dr_location\",\"nfvo_id\": \"nfvo_id\"}"; + JSONObject vnfObj = JSONObject.fromObject(data); + VnfResourceMgr vnfResourceMgr = new VnfResourceMgr(); + JSONObject result = vnfResourceMgr.grantVnfResource(vnfObj, "vnfId", "vnfmId"); + + JSONObject retJson = new JSONObject(); + retJson.put("retCode", Constant.REST_FAIL); + retJson.put("errorMsg", "basic params error"); + assertEquals(retJson, result); + } + + @Test + public void testgrantVnfResourceByJSONException() { + String data = + "{\"operation_right\": \"increase\",\"vnf_name\": \"vnf_name\",\"vm_list\": [{\"vm_flavor\": {\"storage\": [{\"vol_type\": \"local_volume\",\"vol_size\": \"2\",\"storage_type\": \"local_image\",\"disk_size\": \"100\"}],\"num_cpus\": \"6\",\"mem_size\": \"8\"},\"init_number\": \"1\"}],\"version\": \"version\",\"template_id\": \"template_id\",\"template_name\": \"template_name\",\"plan_id\": \"plan_id\",\"plan_name\": \"plan_name\",\"project_id\": \"project_id\",\"project_name\": \"project_name\",\"creator\": \"creator\",\"status\": \"status\",\"tenant\": \"tenant\",\"parent_tenant\": \"parent_tenant\",\"vnfd_id\": \"vnfd_id\",\"location\": \"location\",\"dr_location\": \"dr_location\",\"nfvo_id\": \"nfvo_id\"}"; + JSONObject vnfObj = JSONObject.fromObject(data); + VnfResourceMgr vnfResourceMgr = new VnfResourceMgr(); + JSONObject result = vnfResourceMgr.grantVnfResource(vnfObj, "vnfId", "vnfmId"); + + JSONObject retJson = new JSONObject(); + retJson.put("retCode", Constant.REST_FAIL); + retJson.put("errorMsg", "params parse exception"); + assertEquals(retJson, result); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/AuthRoaTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/AuthRoaTest.java new file mode 100644 index 00000000..558d43ed --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/AuthRoaTest.java @@ -0,0 +1,203 @@ +/* + * Copyright 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.nfvo.vnfmadapter.service.rest; + +import static org.junit.Assert.assertEquals; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.openo.nfvo.vnfmadapter.common.VnfmJsonUtil; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.process.AuthMgr; + +import mockit.Mock; +import mockit.MockUp; +import net.sf.json.JSONObject; + +public class AuthRoaTest { + + private AuthRoa authRoa; + + private AuthMgr authMgr; + + @Before + public void setUp() { + authRoa = new AuthRoa(); + authMgr = new AuthMgr(); + authRoa.setAuthMgr(authMgr); + } + + @After + public void tearDown() { + authRoa = null; + authMgr = null; + } + + @Test + public void testAuthTokenBySubJsonObjectNull() { + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + new MockUp<VnfmJsonUtil>() { + + @Mock + public <T> T getJsonFromContexts(HttpServletRequest context) { + return null; + } + }; + + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + + String result = authRoa.authToken(mockInstance, mockResInstance); + + assertEquals("Login params insufficient", result); + } + + @Test + public void testAuthTokenByFail() { + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + + new MockUp<VnfmJsonUtil>() { + + @SuppressWarnings("unchecked") + @Mock + public <T> T getJsonFromContexts(HttpServletRequest context) { + JSONObject subJsonObject = new JSONObject(); + return (T)subJsonObject; + } + }; + new MockUp<AuthMgr>() { + + @Mock + public JSONObject authToken(JSONObject params) { + JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_FAIL); + restJson.put("data", "Fail!"); + return restJson; + } + }; + String result = authRoa.authToken(mockInstance, mockResInstance); + + assertEquals("{\"Information\": \"Fail!\"}", result); + } + + @Test + public void testAuthTokenByHttpInnerError() { + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + + new MockUp<VnfmJsonUtil>() { + + @SuppressWarnings("unchecked") + @Mock + public <T> T getJsonFromContexts(HttpServletRequest context) { + JSONObject subJsonObject = new JSONObject(); + return (T)subJsonObject; + } + }; + new MockUp<AuthMgr>() { + + @Mock + public JSONObject authToken(JSONObject params) { + JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.HTTP_INNERERROR); + restJson.put("data", "HttpInnerError!"); + return restJson; + } + }; + String result = authRoa.authToken(mockInstance, mockResInstance); + + assertEquals("{\"Information\": \"HttpInnerError!\"}", result); + } + + @Test + public void testAuthToken() { + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + new MockUp<VnfmJsonUtil>() { + + @SuppressWarnings("unchecked") + @Mock + public <T> T getJsonFromContexts(HttpServletRequest context) { + JSONObject subJsonObject = new JSONObject(); + return (T)subJsonObject; + } + }; + new MockUp<AuthMgr>() { + + @Mock + public JSONObject authToken(JSONObject params) { + JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_SUCCESS); + JSONObject data = new JSONObject(); + data.put("accessSession", "accessSession"); + data.put("userName", "userName"); + data.put("roaRand", "roaRand"); + restJson.put("data", data); + return restJson; + } + }; + String result = authRoa.authToken(mockInstance, mockResInstance); + + assertEquals( + "{\"token\": {\"methods\": [\"password\"],\"expires_at\": \"\",\"user\": {\"id\": \"userName\",\"name\": \"userName\"},\"roa_rand\": \"roaRand\"}}", + result); + } + + @Test + public void testDelAuthToken() { + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + String result = authRoa.delAuthToken(mockInstance, null, null, mockResInstance); + + JSONObject resultJson = new JSONObject(); + resultJson.put("Information", "Operation success"); + assertEquals(resultJson.toString(), result); + } + + @Test + public void testShakehand() { + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + String result = authRoa.shakehand(mockInstance, null, mockResInstance); + + JSONObject resultJson = new JSONObject(); + resultJson.put("status", "running"); + resultJson.put("description", "Operation success"); + assertEquals(resultJson.toString(), result); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/SwaggerRoaTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/SwaggerRoaTest.java new file mode 100644 index 00000000..ba68ed82 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/SwaggerRoaTest.java @@ -0,0 +1,42 @@ +/* + * Copyright 2017 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.nfvo.vnfmadapter.service.rest; + +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; + +import org.junit.Test; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Jan 13, 2017 + */ +public class SwaggerRoaTest { + + @Test + public void testApidoc() throws IOException { + SwaggerRoa swaggerRoa = new SwaggerRoa(); + String result = swaggerRoa.apidoc(); + assertNotNull(result); + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/VnfAdapterResourceRoaTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/VnfAdapterResourceRoaTest.java new file mode 100644 index 00000000..75b37f69 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/VnfAdapterResourceRoaTest.java @@ -0,0 +1,55 @@ +/* + * Copyright 2017 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.nfvo.vnfmadapter.service.rest; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openo.nfvo.vnfmadapter.service.adapter.impl.AdapterResourceManager; + +import mockit.Mock; +import mockit.MockUp; +import net.sf.json.JSONObject; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Jan 13, 2017 + */ +public class VnfAdapterResourceRoaTest { + + @Test + public void testGetAllCloudInfo() { + new MockUp<AdapterResourceManager>() { + + @Mock + public JSONObject getAllCloud(String url) { + JSONObject resultObj = new JSONObject(); + resultObj.put("dn", "test"); + return resultObj; + } + }; + + VnfAdapterResourceRoa vnfAdapter = new VnfAdapterResourceRoa(); + String result = vnfAdapter.getAllCloudInfo(null); + assertEquals("test", result); + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/VnfResourceRoaTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/VnfResourceRoaTest.java new file mode 100644 index 00000000..016d373b --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/VnfResourceRoaTest.java @@ -0,0 +1,268 @@ +/* + * Copyright 2016-2017 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.nfvo.vnfmadapter.service.rest; + +import static org.junit.Assert.assertEquals; + +import javax.servlet.http.HttpServletRequest; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.openo.nfvo.vnfmadapter.common.VnfmJsonUtil; +import org.openo.nfvo.vnfmadapter.common.VnfmUtil; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.process.VnfResourceMgr; + +import mockit.Mock; +import mockit.MockUp; +import net.sf.json.JSONObject; + +public class VnfResourceRoaTest { + + private VnfResourceRoa vnfResourceRoa; + + private VnfResourceMgr vnfResourceMgr; + + @Before + public void setUp() { + vnfResourceRoa = new VnfResourceRoa(); + vnfResourceMgr = new VnfResourceMgr(); + vnfResourceRoa.setVnfResourceMgr(vnfResourceMgr); + } + + @After + public void tearDown() { + vnfResourceRoa = null; + vnfResourceMgr = null; + } + + @Test + public void testGrantVnfResByDataObjectNull() { + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + new MockUp<VnfmJsonUtil>() { + + @Mock + public <T> T getJsonFromContexts(HttpServletRequest context) { + return null; + } + }; + + String result = vnfResourceRoa.grantVnfRes(mockInstance, "vnfId"); + + JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_FAIL); + restJson.put("data", "Params error"); + assertEquals(restJson.toString(), result); + } + + @Test + public void testGrantVnfResByGrantObjNull() { + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + final JSONObject dataObject = new JSONObject(); + new MockUp<VnfmJsonUtil>() { + + @SuppressWarnings("unchecked") + @Mock + public <T> T getJsonFromContexts(HttpServletRequest context) { + return (T)dataObject; + } + }; + new MockUp<JSONObject>() { + + @Mock + public JSONObject getJSONObject(String key) { + if(key == "grant") { + return null; + } + return dataObject; + } + }; + + String result = vnfResourceRoa.grantVnfRes(mockInstance, "vnfId"); + + JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_FAIL); + restJson.put("data", "Grant param error"); + assertEquals(restJson.toString(), result); + } + + @Test + public void testGrantVnfRes() { + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() { + + @Mock + public String getHeader(String name) { + return "127.0.0.1"; + } + }; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + final JSONObject dataObject = new JSONObject(); + JSONObject grant = new JSONObject(); + grant.put("project_id", "project_id"); + dataObject.put("grant", grant); + new MockUp<VnfmJsonUtil>() { + + @SuppressWarnings("unchecked") + @Mock + public <T> T getJsonFromContexts(HttpServletRequest context) { + return (T)dataObject; + } + }; + new MockUp<VnfmUtil>() { + + @Mock + public String getVnfmIdByIp(String ip) { + return "vnfmId"; + } + }; + + new MockUp<VnfResourceMgr>() { + + @Mock + public JSONObject grantVnfResource(JSONObject vnfObj, String vnfId, String vnfmId) { + JSONObject resultJson = new JSONObject(); + resultJson.put("retCode", Constant.REST_SUCCESS); + JSONObject data = new JSONObject(); + data.put("data", "success"); + resultJson.put("data", data); + return resultJson; + } + }; + String result = vnfResourceRoa.grantVnfRes(mockInstance, "vnfId"); + + JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_SUCCESS); + JSONObject data = new JSONObject(); + data.put("data", "success"); + restJson.put("data", data); + assertEquals(restJson.toString(), result); + } + + @Test + public void testGrantVnfResByFail() { + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() { + + @Mock + public String getHeader(String name) { + return "127.0.0.1"; + } + }; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + final JSONObject dataObject = new JSONObject(); + JSONObject grant = new JSONObject(); + grant.put("project_id", "project_id"); + dataObject.put("grant", grant); + new MockUp<VnfmJsonUtil>() { + + @SuppressWarnings("unchecked") + @Mock + public <T> T getJsonFromContexts(HttpServletRequest context) { + return (T)dataObject; + } + }; + new MockUp<VnfmUtil>() { + + @Mock + public String getVnfmIdByIp(String ip) { + return "vnfmId"; + } + }; + + new MockUp<VnfResourceMgr>() { + + @Mock + public JSONObject grantVnfResource(JSONObject vnfObj, String vnfId, String vnfmId) { + JSONObject resultJson = new JSONObject(); + resultJson.put("retCode", Constant.REST_FAIL); + resultJson.put("data", "Fail!"); + return resultJson; + } + }; + String result = vnfResourceRoa.grantVnfRes(mockInstance, "vnfId"); + + JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_FAIL); + restJson.put("data", "Fail!"); + assertEquals(restJson.toString(), result); + } + + @Test + public void testGrantVnfResByDataNull() { + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() { + + @Mock + public String getHeader(String name) { + return "127.0.0.1"; + } + }; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + final JSONObject dataObject = new JSONObject(); + JSONObject grant = new JSONObject(); + grant.put("project_id", "project_id"); + dataObject.put("grant", grant); + new MockUp<VnfmJsonUtil>() { + + @SuppressWarnings("unchecked") + @Mock + public <T> T getJsonFromContexts(HttpServletRequest context) { + return (T)dataObject; + } + }; + new MockUp<VnfmUtil>() { + + @Mock + public String getVnfmIdByIp(String ip) { + return "vnfmId"; + } + }; + + new MockUp<VnfResourceMgr>() { + + @Mock + public JSONObject grantVnfResource(JSONObject vnfObj, String vnfId, String vnfmId) { + JSONObject resultJson = new JSONObject(); + resultJson.put("retCode", Constant.REST_FAIL); + return resultJson; + } + }; + String result = vnfResourceRoa.grantVnfRes(mockInstance, "vnfId"); + + JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_FAIL); + assertEquals(restJson.toString(), result); + } + + @Test + public void testNotify() { + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() { + + @Mock + public String getHeader(String name) { + return "127.0.0.1"; + } + }; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + String result = vnfResourceRoa.notify(mockInstance); + + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_SUCCESS); + assertEquals(restJson.toString(), result); + } +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/VnfRoaTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/VnfRoaTest.java new file mode 100644 index 00000000..08e28bca --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/VnfRoaTest.java @@ -0,0 +1,579 @@ +/* + * Copyright 2016-2017 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.nfvo.vnfmadapter.service.rest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.nfvo.vnfmadapter.common.VnfmJsonUtil; +import org.openo.nfvo.vnfmadapter.service.constant.Constant; +import org.openo.nfvo.vnfmadapter.service.process.VnfMgr; + +import mockit.Mock; +import mockit.MockUp; +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; + +public class VnfRoaTest { + + private VnfRoa vnfRoa; + + private VnfMgr vnfMgr; + + @Before + public void setUp() { + vnfRoa = new VnfRoa(); + vnfMgr = new VnfMgr(); + vnfRoa.setVnfMgr(vnfMgr); + } + + @After + public void tearDown() { + vnfRoa = null; + vnfMgr = null; + } + + @Test + public void testAddVnf() throws ServiceException { + final JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_SUCCESS); + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + + new MockUp<VnfMgr>() { + + @Mock + public JSONObject addVnf(JSONObject subJsonObject, String vnfmId) { + JSONObject retJson = new JSONObject(); + retJson.put("id", "123"); + restJson.put("data", retJson); + return restJson; + } + }; + new MockUp<VnfmJsonUtil>() { + + @SuppressWarnings("unchecked") + @Mock + public <T> T getJsonFromContexts(HttpServletRequest VNFreq) { + return (T)restJson; + } + }; + + String result = vnfRoa.addVnf(mockInstance, mockResInstance, "vnfmId"); + + JSONObject retJson = new JSONObject(); + retJson.put("id", "123"); + assertEquals(retJson.toString(), result); + + } + + @Test + public void testAddVnfFail() throws ServiceException { + final JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_FAIL); + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + + new MockUp<VnfMgr>() { + + @Mock + public JSONObject addVnf(JSONObject subJsonObject, String vnfmId) { + return restJson; + } + }; + new MockUp<VnfmJsonUtil>() { + + @SuppressWarnings("unchecked") + @Mock + public <T> T getJsonFromContexts(HttpServletRequest VNFreq) { + return (T)restJson; + } + }; + + String result = vnfRoa.addVnf(mockInstance, mockResInstance, "vnfmId"); + + assertEquals(restJson.toString(), result); + + } + + @Test + public void testAddVnfBySubJsonObjectNull() throws ServiceException { + final JSONObject restJson = new JSONObject(); + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + + new MockUp<VnfmJsonUtil>() { + + @Mock + public <T> T getJsonFromContexts(HttpServletRequest context) { + return null; + } + }; + + String result = vnfRoa.addVnf(mockInstance, mockResInstance, "vnfmId"); + + assertEquals(restJson.toString(), result); + + } + + @Test + public void testDelVnf() throws ServiceException { + final JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_SUCCESS); + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + + new MockUp<VnfMgr>() { + + @Mock + public JSONObject deleteVnf(String vnfId, String vnfmId, JSONObject vnfObject) { + JSONObject retJson = new JSONObject(); + retJson.put("id", "123"); + restJson.put("data", retJson); + return restJson; + } + }; + + new MockUp<VnfmJsonUtil>() { + + @SuppressWarnings("unchecked") + @Mock + public <T> T getJsonFromContexts(HttpServletRequest VNFreq) { + return (T)restJson; + } + }; + + String result = vnfRoa.delVnf("vnfmId", mockResInstance, "vnfId", mockInstance); + JSONObject retJson = new JSONObject(); + retJson.put("id", "123"); + assertEquals(retJson.toString(), result); + } + + @Test + public void testDelVnfByVnfIdIsEmpty() throws ServiceException { + final JSONObject restJson = new JSONObject(); + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + + new MockUp<VnfmJsonUtil>() { + + @SuppressWarnings("unchecked") + @Mock + public <T> T getJsonFromContexts(HttpServletRequest VNFreq) { + return (T)restJson; + } + }; + + String result = vnfRoa.delVnf("vnfmId", mockResInstance, "", mockInstance); + + assertEquals(restJson.toString(), result); + } + + @Test + public void testDelVnfByVnfmIdIsEmpty() throws ServiceException { + final JSONObject restJson = new JSONObject(); + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + + new MockUp<VnfmJsonUtil>() { + + @SuppressWarnings("unchecked") + @Mock + public <T> T getJsonFromContexts(HttpServletRequest VNFreq) { + return (T)restJson; + } + }; + + String result = vnfRoa.delVnf("", mockResInstance, "vnfId", mockInstance); + + assertEquals(restJson.toString(), result); + } + + @Test + public void testDelVnfByVnfIdVnfmIdEmpty() throws ServiceException { + final JSONObject restJson = new JSONObject(); + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + + new MockUp<VnfmJsonUtil>() { + + @SuppressWarnings("unchecked") + @Mock + public <T> T getJsonFromContexts(HttpServletRequest VNFreq) { + return (T)restJson; + } + }; + + String result = vnfRoa.delVnf("", mockResInstance, "", mockInstance); + + assertEquals(restJson.toString(), result); + } + + @Test + public void testDelVnfFail() throws ServiceException { + final JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_FAIL); + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + + new MockUp<VnfMgr>() { + + @Mock + public JSONObject deleteVnf(String vnfId, String vnfmId, JSONObject vnfObject) { + return restJson; + } + }; + + new MockUp<VnfmJsonUtil>() { + + @SuppressWarnings("unchecked") + @Mock + public <T> T getJsonFromContexts(HttpServletRequest VNFreq) { + return (T)restJson; + } + }; + + String result = vnfRoa.delVnf("vnfmId", mockResInstance, "vnfId", mockInstance); + assertEquals(restJson.toString(), result); + } + + @Test + public void testGetVnfByVnfIdIsEmpty() throws ServiceException { + final JSONObject restJson = new JSONObject(); + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + + new MockUp<VnfmJsonUtil>() { + + @SuppressWarnings("unchecked") + @Mock + public <T> T getJsonFromContexts(HttpServletRequest VNFreq) { + return (T)restJson; + } + }; + + String result = vnfRoa.getVnf("vnfmId", mockResInstance, "", mockInstance); + + assertEquals(restJson.toString(), result); + } + + @Test + public void testGetVnfByVnfmIdIsEmpty() throws ServiceException { + final JSONObject restJson = new JSONObject(); + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + + new MockUp<VnfmJsonUtil>() { + + @SuppressWarnings("unchecked") + @Mock + public <T> T getJsonFromContexts(HttpServletRequest VNFreq) { + return (T)restJson; + } + }; + + String result = vnfRoa.getVnf("", mockResInstance, "vnfId", mockInstance); + + assertEquals(restJson.toString(), result); + } + + @Test + public void testGetVnfFail() throws ServiceException { + final JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_FAIL); + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + + new MockUp<VnfMgr>() { + + @Mock + public JSONObject getVnf(String vnfId, String vnfmId) { + return restJson; + } + }; + + new MockUp<VnfmJsonUtil>() { + + @SuppressWarnings("unchecked") + @Mock + public <T> T getJsonFromContexts(HttpServletRequest VNFreq) { + return (T)restJson; + } + }; + + String result = vnfRoa.getVnf("vnfmId", mockResInstance, "vnfId", mockInstance); + assertEquals(restJson.toString(), result); + } + + @Test + public void testGetVnf() throws ServiceException { + final JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_SUCCESS); + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + + new MockUp<VnfMgr>() { + + @Mock + public JSONObject getVnf(String vnfId, String vnfmId) { + JSONObject retJson = new JSONObject(); + JSONObject basicInfoJson = new JSONObject(); + basicInfoJson.put("vnfInstanceId", "123"); + basicInfoJson.put("vnfInstanceName", "1"); + basicInfoJson.put("vnfInstanceDescription", "vFW"); + basicInfoJson.put("vnfdId", "1"); + basicInfoJson.put("vnfdPackageId", "vFW"); + basicInfoJson.put("version", "vFW"); + basicInfoJson.put("vnfProvider", "hw"); + basicInfoJson.put("vnfType", "fw"); + basicInfoJson.put("vnfStatus", "active"); + retJson.put("vnfInfo", basicInfoJson); + retJson.put(Constant.RETCODE, Constant.REST_SUCCESS); + return retJson; + } + }; + + new MockUp<VnfmJsonUtil>() { + + @SuppressWarnings("unchecked") + @Mock + public <T> T getJsonFromContexts(HttpServletRequest VNFreq) { + return (T)restJson; + } + }; + + String result = vnfRoa.getVnf("vnfmId", mockResInstance, "vnfId", mockInstance); + JSONObject basicInfoJson = new JSONObject(); + JSONObject retJson = new JSONObject(); + basicInfoJson.put("vnfInstanceId", "123"); + basicInfoJson.put("vnfInstanceName", "1"); + basicInfoJson.put("vnfInstanceDescription", "vFW"); + basicInfoJson.put("vnfdId", "1"); + basicInfoJson.put("vnfdPackageId", "vFW"); + basicInfoJson.put("version", "vFW"); + basicInfoJson.put("vnfProvider", "hw"); + basicInfoJson.put("vnfType", "fw"); + basicInfoJson.put("vnfStatus", "active"); + retJson.put("vnfInfo", basicInfoJson); + assertEquals(retJson.toString(), result); + } + + @Test + public void testGetJobByJobIdNull() throws ServiceException { + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + + String result = vnfRoa.getJob(null, null, mockResInstance, "1111"); + assertEquals("{}", result); + } + + @Test + public void testGetJobByVnfmIdNull() throws ServiceException { + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + + String result = vnfRoa.getJob("123", null, mockResInstance, "1111"); + assertEquals("{}", result); + } + + @Test + public void testGetJobByVnfMgrFail() throws ServiceException { + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + new MockUp<VnfMgr>() { + + @Mock + public JSONObject getJob(String jobId, String vnfmId) { + JSONObject restJson = new JSONObject(); + restJson.put(Constant.RETCODE, Constant.REST_FAIL); + return restJson; + } + }; + String result = vnfRoa.getJob("123", "1234", mockResInstance, "1111"); + assertEquals("{\"retCode\":-1}", result); + } + + @Test + public void testGetJob() throws ServiceException { + new MockUp<VnfMgr>() { + + @Mock + public JSONObject getJob(String jobId, String vnfmId) { + JSONObject restJson = new JSONObject(); + JSONArray data = new JSONArray(); + JSONObject obj = new JSONObject(); + obj.put("id", "11111"); + obj.put("status", "Active"); + data.add(obj); + restJson.put(Constant.RETCODE, Constant.REST_SUCCESS); + restJson.put("data", data); + return restJson; + } + }; + + String result = vnfRoa.getJob("123", "1234", null, "1111"); + assertNotNull(result); + } + + @Test + public void testScaleVnf() throws ServiceException { + final JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_SUCCESS); + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + + new MockUp<VnfMgr>() { + + @Mock + public JSONObject scaleVNF(JSONObject vnfObject, String vnfmId, String vnfInstanceId) { + JSONObject retJson = new JSONObject(); + retJson.put("id", "123"); + restJson.put("data", retJson); + return restJson; + } + }; + new MockUp<VnfmJsonUtil>() { + + @SuppressWarnings("unchecked") + @Mock + public <T> T getJsonFromContexts(HttpServletRequest VNFreq) { + return (T)restJson; + } + }; + + String result = vnfRoa.scaleVnf(mockInstance,mockResInstance,"id","id"); + + JSONObject retJson = new JSONObject(); + retJson.put("id", "123"); + assertEquals(retJson.toString(), result); + + } + @Test + public void testScaleVnfFail() throws ServiceException { + final JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_FAIL); + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + + new MockUp<VnfMgr>() { + + @Mock + public JSONObject scaleVNF(JSONObject vnfObject, String vnfmId, String vnfInstanceId) { + JSONObject retJson = new JSONObject(); + retJson.put("id", "123"); + restJson.put("data", retJson); + return restJson; + } + }; + new MockUp<VnfmJsonUtil>() { + + @SuppressWarnings("unchecked") + @Mock + public <T> T getJsonFromContexts(HttpServletRequest VNFreq) { + return (T)restJson; + } + }; + String result = vnfRoa.scaleVnf(mockInstance,mockResInstance,"id","id"); + + assertEquals(restJson.toString(), result); + + } + + @Test + public void testScaleVnfFail2() throws ServiceException { + final JSONObject restJson = new JSONObject(); + restJson.put("retCode", Constant.REST_FAIL); + MockUp<HttpServletRequest> proxyStub = new MockUp<HttpServletRequest>() {}; + HttpServletRequest mockInstance = proxyStub.getMockInstance(); + + MockUp<HttpServletResponse> proxyResStub = new MockUp<HttpServletResponse>() {}; + HttpServletResponse mockResInstance = proxyResStub.getMockInstance(); + + new MockUp<VnfMgr>() { + + @Mock + public JSONObject scaleVNF(JSONObject vnfObject, String vnfmId, String vnfInstanceId) { + JSONObject retJson = new JSONObject(); + retJson.put("id", "123"); + restJson.put("data", retJson); + return restJson; + } + }; + new MockUp<VnfmJsonUtil>() { + + @SuppressWarnings("unchecked") + @Mock + public <T> T getJsonFromContexts(HttpServletRequest VNFreq) { + return null; + } + }; + String result = vnfRoa.scaleVnf(mockInstance,mockResInstance,"id","id"); + + assertEquals(restJson.toString(), result); + + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/ExceptionMessageTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/ExceptionMessageTest.java new file mode 100644 index 00000000..ca660581 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/ExceptionMessageTest.java @@ -0,0 +1,68 @@ +/* + * Copyright 2017 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.nfvo.vnfmadapter.service.rest.exceptionmapper; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Jan 13, 2017 + */ +public class ExceptionMessageTest { + + @Test + public void testToString() { + ExceptionMessage message = new ExceptionMessage(); + message.setErrorCode("1"); + message.setHttpCode(200); + message.setMessage("Success!"); + String str = message.toString(); + assertNotNull(str); + } + + @Test + public void testGetErrorCode() { + ExceptionMessage message = new ExceptionMessage(); + message.setErrorCode("1"); + String str = message.getErrorCode(); + assertEquals("1", str); + } + + @Test + public void testHttpCode() { + ExceptionMessage message = new ExceptionMessage(); + message.setHttpCode(200); + int str = message.getHttpCode(); + assertEquals(200, str); + } + + @Test + public void testGetMessage() { + ExceptionMessage message = new ExceptionMessage(); + message.setMessage("Success!"); + String str = message.getMessage(); + assertEquals("Success!", str); + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/GenericExceptionMapperTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/GenericExceptionMapperTest.java new file mode 100644 index 00000000..370cbc81 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/GenericExceptionMapperTest.java @@ -0,0 +1,43 @@ +/* + * Copyright 2017 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.nfvo.vnfmadapter.service.rest.exceptionmapper; + +import static org.junit.Assert.assertNotNull; + +import javax.ws.rs.core.Response; + +import org.junit.Test; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Jan 13, 2017 + */ +public class GenericExceptionMapperTest { + + @Test + public void testToResponse() { + GenericExceptionMapper excep = new GenericExceptionMapper(); + Exception exception = new Exception("message"); + Response res = excep.toResponse(exception); + assertNotNull(res); + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/ServiceExceptionMapperTest.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/ServiceExceptionMapperTest.java new file mode 100644 index 00000000..c9deb393 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/service/rest/exceptionmapper/ServiceExceptionMapperTest.java @@ -0,0 +1,44 @@ +/* + * Copyright 2017 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.nfvo.vnfmadapter.service.rest.exceptionmapper; + +import static org.junit.Assert.assertNotNull; + +import javax.ws.rs.core.Response; + +import org.junit.Test; +import org.openo.baseservice.remoteservice.exception.ServiceException; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Jan 13, 2017 + */ +public class ServiceExceptionMapperTest { + + @Test + public void testToResponse() { + ServiceExceptionMapper mapper = new ServiceExceptionMapper(); + ServiceException exception = new ServiceException(); + Response res = mapper.toResponse(exception); + assertNotNull(res); + } + +} diff --git a/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/testutils/JsonUtil.java b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/testutils/JsonUtil.java new file mode 100644 index 00000000..c3f88547 --- /dev/null +++ b/huawei/vnfmadapter/VnfmadapterService/service/src/test/java/org/openo/nfvo/vnfmadapter/testutils/JsonUtil.java @@ -0,0 +1,51 @@ +/* + * Copyright 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.nfvo.vnfmadapter.testutils; + + +import java.io.IOException; + +import org.codehaus.jackson.map.DeserializationConfig.Feature; +import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.jackson.type.TypeReference; + +import net.sf.json.JSON; + +public final class JsonUtil { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static <T> T unMarshal(String jsonstr, Class<T> type) throws IOException { + return MAPPER.readValue(jsonstr, type); + } + + public static <T> T unMarshal(String jsonstr, TypeReference<T> type) throws IOException { + return MAPPER.readValue(jsonstr, type); + } + + public static String marshal(Object srcObj) throws IOException { + return srcObj instanceof JSON ? srcObj.toString() : MAPPER.writeValueAsString(srcObj); + } + + public static ObjectMapper getMapper() { + return MAPPER; + } + + static { + MAPPER.setDeserializationConfig( + MAPPER.getDeserializationConfig().without(new Feature[] { Feature.FAIL_ON_UNKNOWN_PROPERTIES })); + } +}
\ No newline at end of file |