From d4a7658f72decfef05d15973d5cee13910eb47ae Mon Sep 17 00:00:00 2001 From: Kailun Qin Date: Tue, 27 Mar 2018 18:23:01 +0800 Subject: Port nfvo/vnf_functest for framework merge Merged VNF onboarding test functions and frameworks locating separately in nfvo/vnf_functest and vnfsdk/vnf-sdk-function-test seed code. 1) Reconstructed by aligning with the original interface and sequence design; 2) Replaced Restful calls with local invokes; 3) Implemented DB support (PostgreSQL) for persistent recording; 4) Added unit tests associated; 5) Unified package names to "onap"; 6) Fixed several inherent issues. Issue-ID: VNFSDK-178 Change-Id: I2147c5df8dd400adef71dafca9073b12d992d2df Signed-off-by: Kailun Qin --- .../java/org/onap/vnfsdk/functest/FileUtil.java | 244 +++++++++++++++ .../org/onap/vnfsdk/functest/TaskExecution.java | 276 +++++++++++++++++ .../onap/vnfsdk/functest/VnfSdkFuncTestApp.java | 104 +++++++ .../functest/VnfSdkFuncTestAppConfiguration.java | 82 +++++ .../org/onap/vnfsdk/functest/common/Config.java | 36 +++ .../functest/constants/ApplicationConstants.java | 62 ++++ .../onap/vnfsdk/functest/db/TaskMgrCaseTblDAO.java | 43 +++ .../onap/vnfsdk/functest/db/TaskMgrTaskTblDAO.java | 51 +++ .../externalservice/entity/Environment.java | 67 ++++ .../externalservice/entity/EnvironmentMap.java | 53 ++++ .../externalservice/entity/OperationStatus.java | 54 ++++ .../entity/OperationStatusHandler.java | 73 +++++ .../externalservice/entity/ServiceNode.java | 61 ++++ .../entity/ServiceRegisterEntity.java | 106 +++++++ .../onap/vnfsdk/functest/models/CaseRecord.java | 123 ++++++++ .../onap/vnfsdk/functest/models/TaskRecord.java | 202 ++++++++++++ .../functest/responsehandler/TestResult.java | 54 ++++ .../functest/responsehandler/TestResultMap.java | 51 +++ .../functest/responsehandler/TestResultParser.java | 146 +++++++++ .../VnfFuncTestResponseHandler.java | 138 +++++++++ .../vnfsdk/functest/scriptmgr/ScriptManager.java | 227 ++++++++++++++ .../onap/vnfsdk/functest/taskmgr/TaskManager.java | 258 ++++++++++++++++ .../org/onap/vnfsdk/functest/util/GsonUtil.java | 55 ++++ .../vnfsdk/functest/util/RestResponseUtil.java | 55 ++++ .../onap/vnfsdk/functest/util/ZipCompressor.java | 103 +++++++ .../java/org/openo/vnfsdk/functest/FileUtil.java | 251 --------------- .../org/openo/vnfsdk/functest/TaskExecution.java | 274 ----------------- .../openo/vnfsdk/functest/VnfSdkFuncTestApp.java | 90 ------ .../functest/VnfSdkFuncTestAppConfiguration.java | 96 ------ .../org/openo/vnfsdk/functest/common/Config.java | 36 --- .../functest/common/ServiceRegistration.java | 79 ----- .../functest/constants/ApplicationConstants.java | 56 ---- .../externalservice/entity/Environment.java | 67 ---- .../externalservice/entity/EnvironmentMap.java | 53 ---- .../externalservice/entity/OperationStatus.java | 53 ---- .../entity/OperationStatusHandler.java | 74 ----- .../externalservice/entity/ServiceNode.java | 62 ---- .../entity/ServiceRegisterEntity.java | 108 ------- .../msb/MicroserviceBusConsumer.java | 49 --- .../externalservice/msb/MicroserviceBusRest.java | 37 --- .../vnfsdk/functest/resource/CommonManager.java | 341 --------------------- .../functest/responsehandler/TestResult.java | 54 ---- .../functest/responsehandler/TestResultParser.java | 143 --------- .../VnfFuncTestResponseHandler.java | 144 --------- .../org/openo/vnfsdk/functest/util/GsonUtil.java | 55 ---- .../vnfsdk/functest/util/RestResponseUtil.java | 47 --- .../openo/vnfsdk/functest/util/ZipCompressor.java | 108 ------- .../src/main/resources/migrations.xml | 57 ++++ .../src/main/resources/sample.xml | 8 + 49 files changed, 2789 insertions(+), 2277 deletions(-) create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/FileUtil.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/TaskExecution.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/VnfSdkFuncTestApp.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/VnfSdkFuncTestAppConfiguration.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/common/Config.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/constants/ApplicationConstants.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/db/TaskMgrCaseTblDAO.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/db/TaskMgrTaskTblDAO.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/Environment.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/EnvironmentMap.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/OperationStatus.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/OperationStatusHandler.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/ServiceNode.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/ServiceRegisterEntity.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/models/CaseRecord.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/models/TaskRecord.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/responsehandler/TestResult.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/responsehandler/TestResultMap.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/responsehandler/TestResultParser.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/responsehandler/VnfFuncTestResponseHandler.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/scriptmgr/ScriptManager.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/taskmgr/TaskManager.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/util/GsonUtil.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/util/RestResponseUtil.java create mode 100644 vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/util/ZipCompressor.java delete mode 100644 vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/FileUtil.java delete mode 100644 vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/TaskExecution.java delete mode 100644 vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/VnfSdkFuncTestApp.java delete mode 100644 vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/VnfSdkFuncTestAppConfiguration.java delete mode 100644 vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/common/Config.java delete mode 100644 vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/common/ServiceRegistration.java delete mode 100644 vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/constants/ApplicationConstants.java delete mode 100644 vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/Environment.java delete mode 100644 vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/EnvironmentMap.java delete mode 100644 vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/OperationStatus.java delete mode 100644 vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/OperationStatusHandler.java delete mode 100644 vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/ServiceNode.java delete mode 100644 vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/ServiceRegisterEntity.java delete mode 100644 vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/msb/MicroserviceBusConsumer.java delete mode 100644 vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/msb/MicroserviceBusRest.java delete mode 100644 vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/resource/CommonManager.java delete mode 100644 vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/responsehandler/TestResult.java delete mode 100644 vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/responsehandler/TestResultParser.java delete mode 100644 vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/responsehandler/VnfFuncTestResponseHandler.java delete mode 100644 vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/util/GsonUtil.java delete mode 100644 vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/util/RestResponseUtil.java delete mode 100644 vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/util/ZipCompressor.java create mode 100644 vnf-sdk-function-test/src/main/resources/migrations.xml create mode 100644 vnf-sdk-function-test/src/main/resources/sample.xml (limited to 'vnf-sdk-function-test/src/main') diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/FileUtil.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/FileUtil.java new file mode 100644 index 0000000..fd66362 --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/FileUtil.java @@ -0,0 +1,244 @@ +/* + * 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.onap.vnfsdk.functest; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +public final class FileUtil { + + public static final Logger LOG = LoggerFactory.getLogger(FileUtil.class); + + private static final int BUFFER_SIZE = 2 * 1024 * 1024; + + private static final int TRY_COUNT = 3; + + private FileUtil() { + + } + + /** + * Create directory. + * + * @param dir directory to create + * @return boolean + */ + public static boolean createDirectory(String dir) { + File folder = new File(dir); + int tryCount = 0; + while (tryCount < TRY_COUNT) { + tryCount++; + if (!folder.exists() && !folder.mkdirs()) { + continue; + } else { + return true; + } + } + + return folder.exists(); + } + + /** + * delete file. + * + * @param file the file to delete + * @return boolean + */ + public static boolean deleteFile(File file) { + String hintInfo = file.isDirectory() ? "dir " : "file "; + boolean isFileDeleted = file.delete(); + boolean isFileExist = file.exists(); + if (!isFileExist) { + if (isFileDeleted) { + LOG.info("delete " + hintInfo + file.getAbsolutePath()); + } else { + isFileDeleted = true; + LOG.info("file not exist. no need delete " + hintInfo + file.getAbsolutePath()); + } + } else { + LOG.info("fail to delete " + hintInfo + file.getAbsolutePath()); + } + return isFileDeleted; + } + + /** + * unzip zip file. + * + * @param zipFileName file name to zip + * @param extPlace extPlace + * @return unzip file name + * @throws IOException e1 + */ + public static List unzip(String zipFileName, String extPlace) throws IOException { + ZipFile zipFile = null; + ArrayList unzipFileNams = new ArrayList(); + + try { + zipFile = new ZipFile(zipFileName); + Enumeration fileEn = zipFile.entries(); + byte[] buffer = new byte[BUFFER_SIZE]; + + while (fileEn.hasMoreElements()) { + InputStream input = null; + BufferedOutputStream bos = null; + try { + ZipEntry entry = (ZipEntry) fileEn.nextElement(); + if (entry.isDirectory()) { + continue; + } + + input = zipFile.getInputStream(entry); + File file = new File(extPlace, entry.getName()); + if (!file.getParentFile().exists()) { + createDirectory(file.getParentFile().getAbsolutePath()); + } + + bos = new BufferedOutputStream(new FileOutputStream(file)); + while (true) { + int length = input.read(buffer); + if (length == -1) { + break; + } + bos.write(buffer, 0, length); + } + unzipFileNams.add(file.getAbsolutePath()); + } finally { + closeOutputStream(bos); + closeInputStream(input); + } + } + } finally { + closeZipFile(zipFile); + } + return unzipFileNams; + } + + public static String[] getDirectory(String directory) { + File file = new File(directory); + return file.list(new FilenameFilter() { + + public boolean accept(File current, String name) { + return new File(current, name).isDirectory(); + } + }); + } + + /** + * close InputStream. + * + * @param inputStream the inputstream to close + */ + private static void closeInputStream(InputStream inputStream) { + try { + if (inputStream != null) { + inputStream.close(); + } + } catch (Exception ex) { + LOG.error("close InputStream error!: " + ex); + } + } + + /** + * close OutputStream. + * + * @param outputStream the output stream to close + */ + private static void closeOutputStream(OutputStream outputStream) { + try { + if (outputStream != null) { + outputStream.close(); + } + } catch (Exception ex) { + LOG.error("close OutputStream error!: " + ex); + } + } + + /** + * close zipFile. + * + * @param zipFile the zipFile to close + */ + private static void closeZipFile(ZipFile zipFile) { + try { + ZipFile tempZipFile = zipFile; + if (tempZipFile != null) { + tempZipFile.close(); + } + } catch (IOException ioe) { + LOG.error("close ZipFile error!: " + ioe); + } + } + + public static Boolean checkFileExist(String filePath) { + File file = new File(filePath); + return file.exists(); + } + + public static Boolean deleteFile(String filePath) { + File file = new File(filePath); + if (file.exists()) { + return file.delete(); + } + return true; + } + + public static byte[] convertZipFiletoByteArray(String filename) { + File file = new File(filename); + byte[] emptyArray = new byte[0]; + if (!file.exists()) { + return emptyArray; + } + + byte[] byteArrayFile = new byte[(int) file.length()]; + try { + FileInputStream fileInputStream = new FileInputStream(filename); + int value = fileInputStream.read(byteArrayFile); + fileInputStream.close(); + LOG.debug("Number of bytes read from fileInputStream = " + value); + } catch (Exception e) { + LOG.error("convertZipFiletoByteArray: " + e); + } + return byteArrayFile; + } + + /** + * Interface to Delete Directory + *
+ * + * @param directory + * @since VNFSDK 2.0 + */ + public static void deleteDirectory(String directory) { + File file = new File(directory); + if (!file.exists()) { + return; + } + if (file.isDirectory()) { + for (File sub : file.listFiles()) { + deleteFile(sub); + } + } + file.delete(); + } +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/TaskExecution.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/TaskExecution.java new file mode 100644 index 0000000..51a8799 --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/TaskExecution.java @@ -0,0 +1,276 @@ +/* + * 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.onap.vnfsdk.functest; + +import com.google.gson.Gson; +import com.google.gson.stream.JsonReader; +import org.apache.commons.lang3.SystemUtils; +import org.onap.vnfsdk.functest.constants.ApplicationConstants; +import org.onap.vnfsdk.functest.externalservice.entity.Environment; +import org.onap.vnfsdk.functest.externalservice.entity.EnvironmentMap; +import org.onap.vnfsdk.functest.externalservice.entity.OperationStatus; +import org.onap.vnfsdk.functest.externalservice.entity.OperationStatus.operResultCode; +import org.onap.vnfsdk.functest.externalservice.entity.OperationStatusHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; +import java.util.Map.Entry; +import java.util.UUID; + +public class TaskExecution { + + private static final Logger LOGGER = LoggerFactory.getLogger(TaskExecution.class); + + public void executeScript(String dirPath, UUID uniqueKey) { + + String nl = File.separator; + String curDir = System.getProperty(ApplicationConstants.USER_DIR); + String confDir = curDir + nl + ApplicationConstants.CONF + nl + ApplicationConstants.ROBOT + nl; + + // Read the MetaData from the VNF package +// ObjectMapper mapper = new ObjectMapper(); + + Map mapValues = null; + try { +// mapValues = +// mapper.readValue(new FileInputStream(confDir + ApplicationConstants.ROBOTMETADATA_JSON), Map.class); + mapValues = new Gson().fromJson(new JsonReader(new FileReader(confDir + ApplicationConstants.ROBOTMETADATA_JSON)), Map.class); + } catch (IOException e) { + + LOGGER.error(ApplicationConstants.JSON_METADATA_FILE_FAILED, e); + return; + } + + // Form the variables for the upload, transfer and execute command + String scriptDirName = new File(dirPath).getName(); + mapValues.put("SCRIPT_DIR", dirPath); + + String remoteScriptDir = mapValues.get("DIR_REMOTE") + scriptDirName; + String remoteScriptResult = remoteScriptDir + "/" + "output "; + mapValues.put("DIR_REMOTE_RESULT", remoteScriptResult); + + String dirResult = mapValues.get(ApplicationConstants.DIR_RESULT) + uniqueKey; + mapValues.put(ApplicationConstants.DIR_RESULT, dirResult); + + String remoteScriptFile = remoteScriptDir + "/" + mapValues.get("MAIN_SCRIPT"); + String remoteArgs = "--argumentfile " + remoteScriptDir + "/" + "config.args "; + String remoteCommand = + ApplicationConstants.ROBOT_SPACE + "-d " + remoteScriptResult + remoteArgs + remoteScriptFile; + mapValues.put("REMOTE_COMMAND", "\"" + remoteCommand + "\""); + + String robotvariables = ""; + for (Entry values : mapValues.entrySet()) { + + robotvariables = robotvariables + " -v " + values.getKey() + ":" + values.getValue() + " "; + } + + // Execute the command + String argumentFilePath = confDir + "config.args "; + String robotScript = confDir + "RemoteConnection.robot"; + + Process process = null; + InputStream inputStream = null; + int ch; + try { + String command = "robot --argumentfile " + argumentFilePath + robotvariables + " " + robotScript; + LOGGER.info("Command execute to execute the script:" + command); + process = Runtime.getRuntime().exec(new String[]{getShellCommand(), getShellArg(), command}); + if (process != null) { + process.waitFor(); + inputStream = process.getInputStream(); + } + while ((ch = inputStream.read()) != -1) { + LOGGER.info(ApplicationConstants.CHARACTER + Integer.toString(ch)); + } + + } catch (Exception e) { + LOGGER.error(ApplicationConstants.TASKEXE_EXESCRIPT_EXCEPTION, e); + } + } + + public void executeRobotScript(UUID envId, UUID executeId) { + + String nl = File.separator; + String curDir = System.getProperty(ApplicationConstants.USER_DIR); + String confDir = curDir + nl + ApplicationConstants.CONF + nl + ApplicationConstants.ROBOT + nl; + + // Read the MetaData from the VNF package +// ObjectMapper mapper = new ObjectMapper(); + Map mapValues = null; + try { +// mapValues = +// mapper.readValue(new FileInputStream(confDir + ApplicationConstants.ROBOTMETADATA_JSON), Map.class); + mapValues = new Gson().fromJson(new JsonReader(new FileReader(confDir + ApplicationConstants.ROBOTMETADATA_JSON)), Map.class); + } catch (IOException e) { + + LOGGER.error(ApplicationConstants.JSON_METADATA_FILE_FAILED, e); + return; + } + + // Get environment of given UUID + Environment functestEnv = EnvironmentMap.getInstance().getEnv(envId); + if (null == functestEnv) { + LOGGER.error("Function Test Environment details are empty,EnvID = " + envId); + } else { + LOGGER.info("Function Test Environment path,Path = " + functestEnv.getPath()); + } + + String remoteDir = functestEnv.getPath() + mapValues.get("SCRIPT_NAME"); + + String remoteConfigArgs = remoteDir + "/" + "config.args "; + String remoteScriptFile = remoteDir + "/" + mapValues.get("MAIN_SCRIPT"); + String remoteScriptResult = remoteDir + "/" + "output "; + String dirResult = mapValues.get(ApplicationConstants.DIR_RESULT) + executeId; + + // set the argument parameters + String remoteArgs = ""; + remoteArgs = remoteArgs + " -v " + "NODE_IP" + ":" + functestEnv.getRemoteIp() + " "; + remoteArgs = remoteArgs + " -v " + "NODE_USERNAME" + ":" + functestEnv.getUserName() + " "; + remoteArgs = remoteArgs + " -v " + "NODE_PASSWORD" + ":" + functestEnv.getPassword() + " "; + + String remoteCommand = ApplicationConstants.ROBOT_SPACE + "-d " + remoteScriptResult + "--argumentfile " + + remoteConfigArgs + remoteScriptFile; + + // set the parameters required by the execute script + remoteCommand = "\"" + remoteCommand + "\""; + remoteArgs = remoteArgs + " -v " + "REMOTE_COMMAND" + ":" + remoteCommand + " "; + + remoteArgs = remoteArgs + " -v " + ApplicationConstants.DIR_RESULT + ":" + dirResult + " "; + remoteArgs = remoteArgs + " -v " + "DIR_REMOTE_RESULT" + ":" + remoteScriptResult + " "; + + // Execute script directory + String robotScript = confDir + "execute.robot"; + + Process process = null; + InputStream inputStream = null; + int ch; + try { + String command = ApplicationConstants.ROBOT + remoteArgs + robotScript; + LOGGER.info("Command execute to execute the script:" + command); + process = Runtime.getRuntime().exec(new String[]{getShellCommand(), getShellArg(), command}); + if (process != null) { + process.waitFor(); + inputStream = process.getInputStream(); + } + + while ((ch = inputStream.read()) != -1) { + LOGGER.info(ApplicationConstants.CHARACTER + Integer.toString(ch)); + } + } catch (Exception e) { + LOGGER.error(ApplicationConstants.TASKEXE_EXESCRIPT_EXCEPTION, e); + } + + OperationStatus operstatus = new OperationStatus(); + operstatus.setoResultCode(operResultCode.SUCCESS); + operstatus.setOperResultMessage("Execute function test finished"); + operstatus.setOperFinished(true); + OperationStatusHandler.getInstance().setOperStatusMap(executeId, operstatus); + } + + public void uploadScript(String dirPath, UUID uuidEnv, UUID uuidUpload) { + + String nl = File.separator; + String curDir = System.getProperty(ApplicationConstants.USER_DIR); + String confDir = curDir + nl + ApplicationConstants.CONF + nl + ApplicationConstants.ROBOT + nl; + + // Read the MetaData from the VNF package +// ObjectMapper mapper = new ObjectMapper(); + + Map mapValues = null; + try { +// mapValues = +// mapper.readValue(new FileInputStream(confDir + ApplicationConstants.ROBOTMETADATA_JSON), Map.class); + mapValues = new Gson().fromJson(new JsonReader(new FileReader(confDir + ApplicationConstants.ROBOTMETADATA_JSON)), Map.class); + } catch (Exception e) { + + LOGGER.error(ApplicationConstants.JSON_METADATA_FILE_FAILED, e); + return; + } + + // Form the variables for the upload, transfer and execute command + mapValues.put("SCRIPT_DIR", dirPath); + + String robotvariables = ""; + for (Entry values : mapValues.entrySet()) { + + robotvariables = robotvariables + " -v " + values.getKey() + ":" + values.getValue() + " "; + } + + // Append the Func test environment variables + Environment functestEnv = EnvironmentMap.getInstance().getEnv(uuidEnv); + robotvariables = robotvariables + " -v " + "NODE_IP" + ":" + functestEnv.getRemoteIp() + " "; + robotvariables = robotvariables + " -v " + "NODE_USERNAME" + ":" + functestEnv.getUserName() + " "; + robotvariables = robotvariables + " -v " + "NODE_PASSWORD" + ":" + functestEnv.getPassword() + " "; + robotvariables = robotvariables + " -v " + "DIR_REMOTE" + ":" + functestEnv.getPath() + " "; + + // Execute the command + String robotScript = confDir + "upload.robot"; + + Process process = null; + InputStream inputStream = null; + int ch; + try { + String command = ApplicationConstants.ROBOT_SPACE + robotvariables + robotScript; + LOGGER.info("Command execute to upload the script:" + command); + process = Runtime.getRuntime().exec(new String[]{getShellCommand(), getShellArg(), command}); + if (process != null) { + process.waitFor(); + inputStream = process.getInputStream(); + } + + while ((ch = inputStream.read()) != -1) { + LOGGER.info(ApplicationConstants.CHARACTER + Integer.toString(ch)); + } + + } catch (Exception e) { + LOGGER.error(ApplicationConstants.TASKEXE_EXESCRIPT_EXCEPTION, e); + } + + OperationStatus operstatus = new OperationStatus(); + operstatus.setoResultCode(operResultCode.SUCCESS); + operstatus.setOperResultMessage(""); + operstatus.setOperFinished(true); + OperationStatusHandler.getInstance().setOperStatusMap(uuidUpload, operstatus); + + } + + private String getShellCommand() { + + String shellcommand = ApplicationConstants.SHELL_COMMAND; + if (SystemUtils.IS_OS_LINUX) { + shellcommand = ApplicationConstants.SHELL_COMMAND_BASH; + } + + return shellcommand; + } + + private String getShellArg() { + + String commandArg = "/c"; + if (SystemUtils.IS_OS_LINUX) { + commandArg = "-c"; + } + + return commandArg; + } + +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/VnfSdkFuncTestApp.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/VnfSdkFuncTestApp.java new file mode 100644 index 0000000..abc8aa9 --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/VnfSdkFuncTestApp.java @@ -0,0 +1,104 @@ +/* + * 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.onap.vnfsdk.functest; + +import com.fasterxml.jackson.annotation.JsonInclude; +import io.dropwizard.Application; +import io.dropwizard.assets.AssetsBundle; +import io.dropwizard.db.DataSourceFactory; +import io.dropwizard.hibernate.HibernateBundle; +import io.dropwizard.hibernate.ScanningHibernateBundle; +import io.dropwizard.migrations.MigrationsBundle; +import io.dropwizard.server.SimpleServerFactory; +import io.dropwizard.setup.Bootstrap; +import io.dropwizard.setup.Environment; +import io.swagger.jaxrs.config.BeanConfig; +import io.swagger.jaxrs.listing.ApiListingResource; +import org.glassfish.jersey.media.multipart.MultiPartFeature; +import org.onap.vnfsdk.functest.common.Config; +import org.onap.vnfsdk.functest.db.TaskMgrCaseTblDAO; +import org.onap.vnfsdk.functest.db.TaskMgrTaskTblDAO; +import org.onap.vnfsdk.functest.scriptmgr.ScriptManager; +import org.onap.vnfsdk.functest.taskmgr.TaskManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class VnfSdkFuncTestApp extends Application { + + private static final Logger LOGGER = LoggerFactory.getLogger(VnfSdkFuncTestApp.class); + private final HibernateBundle hibernateBundle = + new ScanningHibernateBundle("org.onap.vnfsdk.functest.models") { + @Override + public DataSourceFactory getDataSourceFactory(VnfSdkFuncTestAppConfiguration configuration) { + return configuration.getDataSourceFactory(); + } + }; + + public static void main(String[] args) throws Exception { + new VnfSdkFuncTestApp().run(args); + } + + @Override + public String getName() { + return "ONAP-VNFSDK-FunctionTest"; + } + + @Override + public void initialize(Bootstrap bootstrap) { + bootstrap.addBundle(new AssetsBundle("/api-doc", "/api-doc", "index.html", "api-doc")); + bootstrap.addBundle(new MigrationsBundle() { + @Override + public DataSourceFactory getDataSourceFactory(VnfSdkFuncTestAppConfiguration configuration) { + return configuration.getDataSourceFactory(); + } + }); + bootstrap.addBundle(hibernateBundle); + } + + @Override + public void run(VnfSdkFuncTestAppConfiguration configuration, Environment environment) { + LOGGER.info("Start to initialize vnfsdk function test."); + environment.jersey().packages("org.onap.vnfsdk.functest.taskmgr"); + environment.jersey().register(MultiPartFeature.class); + initSwaggerConfig(environment, configuration); + Config.setConfigration(configuration); + LOGGER.info("Initialize vnfsdk function test finished."); + } + + private void initSwaggerConfig(Environment environment, VnfSdkFuncTestAppConfiguration configuration) { + final TaskMgrTaskTblDAO taskDAO = new TaskMgrTaskTblDAO(hibernateBundle.getSessionFactory()); + final TaskMgrCaseTblDAO caseDAO = new TaskMgrCaseTblDAO(hibernateBundle.getSessionFactory()); + environment.jersey().register(new ApiListingResource()); + environment.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL); + environment.jersey().register(new TaskManager(taskDAO, caseDAO, new ScriptManager(taskDAO, caseDAO))); + + BeanConfig config = new BeanConfig(); + config.setTitle("ONAP VnfSdk Functest Service rest API"); + config.setVersion("1.0.0"); + config.setResourcePackage("org.onap.vnfsdk.functest.taskmgr"); + + SimpleServerFactory simpleServerFactory = (SimpleServerFactory) configuration.getServerFactory(); + String basePath = simpleServerFactory.getApplicationContextPath(); + String rootPath = simpleServerFactory.getJerseyRootPath().toString(); + rootPath = rootPath.substring(0, rootPath.indexOf("/*")); + basePath = + ("/").equals(rootPath) ? rootPath : (new StringBuilder()).append(basePath).append(rootPath).toString(); + config.setBasePath(basePath); + config.setScan(true); + } + +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/VnfSdkFuncTestAppConfiguration.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/VnfSdkFuncTestAppConfiguration.java new file mode 100644 index 0000000..f4b7b83 --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/VnfSdkFuncTestAppConfiguration.java @@ -0,0 +1,82 @@ +/* + * 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.onap.vnfsdk.functest; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.dropwizard.Configuration; +import io.dropwizard.db.DataSourceFactory; +import org.hibernate.validator.constraints.NotEmpty; + +import javax.validation.Valid; +import javax.validation.constraints.NotNull; + +public class VnfSdkFuncTestAppConfiguration extends Configuration { + + @NotEmpty + private String template; + + @NotEmpty + private String defaultName = "ONAP-VnfSdk-FuncTest"; + + @Valid + private String serviceIp; + + @Valid + @NotNull + @JsonProperty + private DataSourceFactory database = new DataSourceFactory(); + + @JsonProperty("database") + public DataSourceFactory getDataSourceFactory() { + return database; + } + + @JsonProperty("database") + public void setDataSourceFactory(DataSourceFactory dataSourceFactory) { + this.database = dataSourceFactory; + } + + @JsonProperty + public String getTemplate() { + return template; + } + + @JsonProperty + public void setTemplate(String template) { + this.template = template; + } + + @JsonProperty + public String getDefaultName() { + return defaultName; + } + + @JsonProperty + public void setDefaultName(String name) { + this.defaultName = name; + } + + @JsonProperty + public String getServiceIp() { + return serviceIp; + } + + @JsonProperty + public void setServiceIp(String serviceIp) { + this.serviceIp = serviceIp; + } +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/common/Config.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/common/Config.java new file mode 100644 index 0000000..0be814c --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/common/Config.java @@ -0,0 +1,36 @@ +/* + * 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.onap.vnfsdk.functest.common; + +import org.onap.vnfsdk.functest.VnfSdkFuncTestAppConfiguration; + +public class Config { + + private static VnfSdkFuncTestAppConfiguration configuration; + + private Config() { + + } + + public static VnfSdkFuncTestAppConfiguration getConfigration() { + return configuration; + } + + public static void setConfigration(VnfSdkFuncTestAppConfiguration config) { + configuration = config; + } +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/constants/ApplicationConstants.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/constants/ApplicationConstants.java new file mode 100644 index 0000000..630db46 --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/constants/ApplicationConstants.java @@ -0,0 +1,62 @@ +/* + * 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.onap.vnfsdk.functest.constants; + +public class ApplicationConstants { + + public static final String USER_DIR = "user.dir"; + + public static final String ROBOT = "robot"; + + public static final String ROBOT_SPACE = "robot "; + + public static final String CONF = "conf"; + + public static final String ROBOTMETADATA_JSON = "robotMetaData.json"; + + public static final String JSON_METADATA_FILE_FAILED = "Reading Json Meta data file failed or file do not exist"; + + public static final String DIR_RESULT = "DIR_RESULT"; + + public static final String SCRIPT_DIR = "SCRIPT_DIR"; + + public static final String DIR_REMOTE = "DIR_REMOTE"; + + public static final String DIR_REMOTE_RESULT = "DIR_REMOTE_RESULT"; + + public static final String MAIN_SCRIPT = "MAIN_SCRIPT"; + + public static final String SHELL_COMMAND = "cmd.exe"; + + public static final String SHELL_COMMAND_BASH = "/bin/bash"; + + public static final String CHARACTER = "character ..."; + + public static final String TASKEXE_EXESCRIPT_EXCEPTION = "TaskExecution ... executeScript() ... [Exception] ..."; + + public static final String RUN_SCRIPT_EXECUTE_CMD = "Upload the script and execute the script and run command"; + + public static final String ENVIRONMENT = "environment"; + + public static final String ENVIRONMENT_JSON = "environment.json"; + + public static final String CATALOG_URI = "file:///C:/RobotScript/RobotScript.zip"; + + private ApplicationConstants() { + } + +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/db/TaskMgrCaseTblDAO.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/db/TaskMgrCaseTblDAO.java new file mode 100644 index 0000000..f228ab5 --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/db/TaskMgrCaseTblDAO.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2018 Intel Corporation Intellectual Property + * + * 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.onap.vnfsdk.functest.db; + +import io.dropwizard.hibernate.AbstractDAO; +import org.hibernate.SessionFactory; +import org.onap.vnfsdk.functest.models.CaseRecord; + +import java.util.List; + +public class TaskMgrCaseTblDAO extends AbstractDAO { + public TaskMgrCaseTblDAO(SessionFactory factory) { + super(factory); + } + + public CaseRecord findByTaskID(String taskID) { + //return Optional.ofNullable(get(taskID)); + return get(taskID); + } + + public CaseRecord saveOrUpdate(CaseRecord caseRecord) { + return persist(caseRecord); + } + + public List findAll() { + return list(namedQuery("org.onap.vnfsdk.functest.models.CaseRecord.findAll")); + } + +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/db/TaskMgrTaskTblDAO.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/db/TaskMgrTaskTblDAO.java new file mode 100644 index 0000000..2e9fbd2 --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/db/TaskMgrTaskTblDAO.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2018 Intel Corporation Intellectual Property + * + * 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.onap.vnfsdk.functest.db; + +import io.dropwizard.hibernate.AbstractDAO; +import org.hibernate.SessionFactory; +import org.onap.vnfsdk.functest.models.TaskRecord; + +import java.util.List; +import java.util.Optional; + +public class TaskMgrTaskTblDAO extends AbstractDAO { + public TaskMgrTaskTblDAO(SessionFactory factory) { + super(factory); + } + + public Optional findByPackageID(String packageID) { + return Optional.ofNullable(get(packageID)); + } + + public TaskRecord saveOrUpdate(TaskRecord taskRecord) { + return persist(taskRecord); + } + + public List findAll() { + return list(namedQuery("org.onap.vnfsdk.functest.models.TaskRecord.findAll")); + } + + public List findByTaskID(String taskID) { + StringBuilder builder = new StringBuilder("%"); + builder.append(taskID).append("%"); + return list( + namedQuery("org.onap.vnfsdk.functest.models.TaskRecord.findByTaskID") + .setParameter("taskID", builder.toString()) + ); + } +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/Environment.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/Environment.java new file mode 100644 index 0000000..b22be82 --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/Environment.java @@ -0,0 +1,67 @@ +/* + * 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.onap.vnfsdk.functest.externalservice.entity; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Environment { + + @JsonProperty("remoteIp") + private String remoteIp; + + @JsonProperty("userName") + private String userName; + + @JsonProperty("password") + private String password; + + @JsonProperty("path") + private String path; + + public String getRemoteIp() { + return remoteIp; + } + + public void setRemoteIp(String remoteIp) { + this.remoteIp = remoteIp; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/EnvironmentMap.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/EnvironmentMap.java new file mode 100644 index 0000000..c9584e2 --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/EnvironmentMap.java @@ -0,0 +1,53 @@ +/* + * 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.onap.vnfsdk.functest.externalservice.entity; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class EnvironmentMap { + + private static Map envMap = new HashMap(); + + private static EnvironmentMap oInstance = new EnvironmentMap(); + + private EnvironmentMap() { + // Empty nothing to do + } + + public static synchronized EnvironmentMap getInstance() { + return oInstance; + } + + public synchronized Map getEnvmap() { + return envMap; + } + + public synchronized void addEnv(UUID uuid, Environment envobj) { + envMap.put(uuid, envobj); + } + + public synchronized void delEnv(UUID uuid) { + envMap.remove(uuid); + } + + public synchronized Environment getEnv(UUID uuid) { + return envMap.get(uuid); + } + +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/OperationStatus.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/OperationStatus.java new file mode 100644 index 0000000..3bab7d0 --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/OperationStatus.java @@ -0,0 +1,54 @@ +/* + * 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.onap.vnfsdk.functest.externalservice.entity; + +public class OperationStatus { + + operResultCode oResultCode; + private boolean operFinished = false; + private String operResultMessage; + + ; + + public operResultCode getoResultCode() { + return oResultCode; + } + + public void setoResultCode(operResultCode oResultCode) { + this.oResultCode = oResultCode; + } + + public String getOperResultMessage() { + return operResultMessage; + } + + public void setOperResultMessage(String operResultMessage) { + this.operResultMessage = operResultMessage; + } + + public boolean isOperFinished() { + return operFinished; + } + + public void setOperFinished(boolean operFinished) { + this.operFinished = operFinished; + } + + public enum operResultCode { + SUCCESS, FAILURE, NOTFOUND + } +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/OperationStatusHandler.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/OperationStatusHandler.java new file mode 100644 index 0000000..7ba71cb --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/OperationStatusHandler.java @@ -0,0 +1,73 @@ +/* + * 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.onap.vnfsdk.functest.externalservice.entity; + +import org.onap.vnfsdk.functest.util.RestResponseUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.core.Response; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class OperationStatusHandler { + + private static final Logger LOGGER = LoggerFactory.getLogger(OperationStatusHandler.class); + + private static Map operStatusMap = new HashMap(); + + private static OperationStatusHandler oInstance = new OperationStatusHandler(); + + private OperationStatusHandler() { + // Empty nothing to do + } + + public static synchronized OperationStatusHandler getInstance() { + return oInstance; + } + + public synchronized Map getOperStatusMap() { + return operStatusMap; + } + + public synchronized void setOperStatusMap(UUID uuid, OperationStatus inputOperStatusMap) { + operStatusMap.put(uuid, inputOperStatusMap); + } + + public Response getOperationStatus(UUID uuid) { + + if (getOperStatusMap().containsKey(uuid)) { + + OperationStatus operstatus = getOperStatusMap().get(uuid); + LOGGER.info("Operation Finished?" + operstatus.isOperFinished()); + LOGGER.info("Operation Result Message" + operstatus.getOperResultMessage()); + + return RestResponseUtil.getSuccessResponse(operstatus); + } else { + OperationStatus operstatus = new OperationStatus(); + operstatus.setOperFinished(true); + operstatus.setoResultCode(OperationStatus.operResultCode.NOTFOUND); + LOGGER.error("uuid not found"); + + return RestResponseUtil.getSuccessResponse(operstatus); + + } + + } + +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/ServiceNode.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/ServiceNode.java new file mode 100644 index 0000000..ca647d5 --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/ServiceNode.java @@ -0,0 +1,61 @@ +/* + * 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.onap.vnfsdk.functest.externalservice.entity; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@JsonIgnoreProperties(ignoreUnknown = true) +public class ServiceNode { + + private String ip; + + private String port; + + private int ttl; + + public String getIp() { + return ip; + } + + public void setIp(String ip) { + this.ip = ip; + } + + public String getPort() { + return port; + } + + public void setPort(String port) { + this.port = port; + } + + public int getTtl() { + return ttl; + } + + public void setTtl(int ttl) { + this.ttl = ttl; + } + + +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/ServiceRegisterEntity.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/ServiceRegisterEntity.java new file mode 100644 index 0000000..1cf0585 --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/externalservice/entity/ServiceRegisterEntity.java @@ -0,0 +1,106 @@ +/* + * 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.onap.vnfsdk.functest.externalservice.entity; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.ArrayList; +import java.util.List; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@JsonIgnoreProperties(ignoreUnknown = true) +public class ServiceRegisterEntity { + + private String serviceName; + + private String version; + + private String url; + + private String protocol; + + private String visualRange; + + private List nodes = new ArrayList(); + + public String getServiceName() { + return serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getVisualRange() { + return visualRange; + } + + public void setVisualRange(String visualRange) { + this.visualRange = visualRange; + } + + public List getNodes() { + return nodes; + } + + public void setNodes(List nodes) { + this.nodes = nodes; + } + + + public void setSingleNode(String ip, String port, int ttl) { + ServiceNode node = new ServiceNode(); + if (ip != null && ip.length() > 0) { + node.setIp(ip); + } else { + node.setIp(null); + } + node.setPort(port); + node.setTtl(ttl); + nodes.add(node); + } + +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/models/CaseRecord.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/models/CaseRecord.java new file mode 100644 index 0000000..683cf2d --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/models/CaseRecord.java @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2018 Intel Corporation Intellectual Property + * + * 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.onap.vnfsdk.functest.models; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import javax.persistence.*; +import java.util.Objects; + +@Entity +@Table(name = "CaseRecord") +@NamedQueries( + { + @NamedQuery( + name = "org.onap.vnfsdk.functest.models.CaseRecord.findAll", + query = "SELECT c FROM CaseRecord c" + ) + }) +public class CaseRecord { + @Id + private String taskID; + + @Column(name = "funcID") + private String funcID; + + @Column(name = "testID", nullable = false) + private String testID; + + @Column(name = "testResult", nullable = false) + private String testResult; + + @Column(name = "testDescription", nullable = false) + private String testDescription; + + public CaseRecord() { + } + + public CaseRecord(String taskID, String funcID, String testID, String testResult, String testDescription) { + this.taskID = taskID; + this.funcID = funcID; + this.testID = testID; + this.testResult = testResult; + this.testDescription = testDescription; + } + + @JsonProperty + public String getTaskID() { + return taskID; + } + + @JsonProperty + public void setTaskID(String taskID) { + this.taskID = taskID; + } + + @JsonProperty + public String getFuncID() { + return funcID; + } + + @JsonProperty + public void setFuncID(String funcID) { + this.funcID = funcID; + } + + @JsonProperty + public String getTestID() { + return testID; + } + + @JsonProperty + public void setTestID(String testID) { + this.testID = testID; + } + + @JsonProperty + public String getTestResult() { + return testResult; + } + + @JsonProperty + public void setTestResult(String testResult) { + this.testResult = testResult; + } + + @JsonProperty + public String getTestDescription() { + return testDescription; + } + + @JsonProperty + public void setTestDescription(String testDescription) { + this.testDescription = testDescription; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof CaseRecord)) { + return false; + } + + final CaseRecord that = (CaseRecord) o; + + return Objects.equals(this.taskID, that.taskID); + } +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/models/TaskRecord.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/models/TaskRecord.java new file mode 100644 index 0000000..7fda025 --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/models/TaskRecord.java @@ -0,0 +1,202 @@ +/* + * Copyright (c) 2018 Intel Corporation Intellectual Property + * + * 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.onap.vnfsdk.functest.models; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import javax.persistence.*; +import java.util.Objects; + +@Entity +@Table(name = "TaskRecord") +@NamedQueries( + { + @NamedQuery( + name = "org.onap.vnfsdk.functest.models.TaskRecord.findAll", + query = "SELECT t FROM TaskRecord t" + ), + @NamedQuery(name = "org.onap.vnfsdk.functest.models.TaskRecord.findByTaskID", + query = "SELECT t FROM TaskRecord t WHERE t.taskID LIKE :taskID" + ) + }) +public class TaskRecord { + @Id + private String packageID; + + @Column(name = "taskID", nullable = false) + private String taskID; + + @Column(name = "envID", nullable = false) + private String envID; + + @Column(name = "uploadID", nullable = false) + private String uploadID; + + @Column(name = "operID", nullable = false) + private String operID; + + @Column(name = "funcID") + private String funcID; + + @Column(name = "status", nullable = false) + private String status; + + @Column(name = "operFinished", nullable = false) + private String operFinished; + + @Column(name = "operResult", nullable = false) + private String operResult; + + @Column(name = "operResultMessage") + private String operResultMessage; + + public TaskRecord() { + } + + public TaskRecord(String packageID, String taskID, String envID, String uploadID, String operID, String funcID, String status, String operFinished, String operResult, String operResultMessage) { + this.packageID = packageID; + this.taskID = taskID; + this.envID = envID; + this.uploadID = uploadID; + this.operID = operID; + this.funcID = funcID; + this.status = status; + this.operFinished = operFinished; + this.operResult = operResult; + this.operResultMessage = operResultMessage; + } + + @JsonProperty + public String getPackageID() { + return packageID; + } + + @JsonProperty + public void setPackageID(String packageID) { + this.packageID = packageID; + } + + @JsonProperty + public String getTaskID() { + return taskID; + } + + @JsonProperty + public void setTaskID(String taskID) { + this.taskID = taskID; + } + + @JsonProperty + public String getEnvID() { + return envID; + } + + @JsonProperty + public void setEnvID(String envID) { + this.envID = envID; + } + + @JsonProperty + public String getUploadID() { + return uploadID; + } + + @JsonProperty + public void setUploadID(String uploadID) { + this.uploadID = uploadID; + } + + @JsonProperty + public String getOperID() { + return operID; + } + + @JsonProperty + public void setOperID(String operID) { + this.operID = operID; + } + + @JsonProperty + public String getFuncID() { + return funcID; + } + + @JsonProperty + public void setFuncID(String funcID) { + this.funcID = funcID; + } + + @JsonProperty + public String getStatus() { + return status; + } + + @JsonProperty + public void setStatus(String status) { + this.status = status; + } + + @JsonProperty + public String getOperFinished() { + return operFinished; + } + + @JsonProperty + public void setOperFinished(String operFinished) { + this.operFinished = operFinished; + } + + @JsonProperty + public String getOperResult() { + return operResult; + } + + @JsonProperty + public void setOperResult(String operResult) { + this.operResult = operResult; + } + + @JsonProperty + public String getOperResultMessage() { + return operResultMessage; + } + + @JsonProperty + public void setOperResultMessage(String operResultMessage) { + this.operResultMessage = operResultMessage; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof TaskRecord)) { + return false; + } + + final TaskRecord that = (TaskRecord) o; + + return Objects.equals(this.packageID, that.packageID) && + Objects.equals(this.taskID, that.taskID); + } + + @Override + public int hashCode() { + return Objects.hash(packageID, taskID); + } +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/responsehandler/TestResult.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/responsehandler/TestResult.java new file mode 100644 index 0000000..10ab2e6 --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/responsehandler/TestResult.java @@ -0,0 +1,54 @@ +/* + * 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.onap.vnfsdk.functest.responsehandler; + +/** + * @author Administrator + */ +public class TestResult { + + private String name; + + private String description; + + private String status; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/responsehandler/TestResultMap.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/responsehandler/TestResultMap.java new file mode 100644 index 0000000..4f73db1 --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/responsehandler/TestResultMap.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2018 Intel Corporation Intellectual Property + * + * 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.onap.vnfsdk.functest.responsehandler; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +public class TestResultMap { + + private static final Logger LOGGER = LoggerFactory.getLogger(TestResultMap.class); + + private static Map> testResultMap = new HashMap>(); + + private static TestResultMap oInstance = new TestResultMap(); + + private TestResultMap() { + // Empty nothing to do + } + + public static synchronized TestResultMap getInstance() { + return oInstance; + } + + public synchronized Map> getTestResultMap() { + return testResultMap; + } + + public synchronized void setTestResultMap(UUID uuid, List inputTestResult) { + testResultMap.put(uuid, inputTestResult); + } + +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/responsehandler/TestResultParser.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/responsehandler/TestResultParser.java new file mode 100644 index 0000000..d3a6b39 --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/responsehandler/TestResultParser.java @@ -0,0 +1,146 @@ +/* + * 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.onap.vnfsdk.functest.responsehandler; + +import org.onap.vnfsdk.functest.FileUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public class TestResultParser { + + private static final String STATUSPASS = "PASS"; + + private static final String RESULTTAG = "test"; + + private static final String NAMETAG = "name"; + + private static final String STATUSTAG = "status"; + + private static final String KWTAG = "kw"; + + private static final String DOCTAG = "doc"; + + private static final Logger logger = LoggerFactory.getLogger(TestResultParser.class); + + public List populateResultList(String taskID, String xmlFile) { + List resultData = new ArrayList<>(); + if (!FileUtil.checkFileExist(xmlFile)) { + logger.error("File Not Found !!! :" + xmlFile); + return resultData; + } + parseResultData(taskID, xmlFile, resultData); + return resultData; + } + + private void parseResultData(String taskID, String xmlFile, List resultData) { + try { + Document doc = createDocument(xmlFile); + NodeList list = doc.getElementsByTagName(RESULTTAG); + for (int i = 0; i < list.getLength(); i++) { + Node node = list.item(i); + if (node.getNodeType() != Node.ELEMENT_NODE) { + continue; + } + + NamedNodeMap attr = node.getAttributes(); + if (null == attr) { + continue; + } + + String nameAttr = getNodeValue(attr.getNamedItem(NAMETAG)); + if (null == nameAttr) { + continue; + } + + String descriptionAttr = nameAttr; + String statusAttr = STATUSPASS; + NodeList childlist = node.getChildNodes(); + for (int j = 0; j < childlist.getLength(); j++) { + Node childNode = childlist.item(j); + if (childNode.getNodeType() != Node.ELEMENT_NODE) { + continue; + } + + if (KWTAG == childNode.getNodeName()) { + NodeList kwNodeList = childNode.getChildNodes(); + for (int k = 0; k < kwNodeList.getLength(); k++) { + Node descNode = kwNodeList.item(k); + if (descNode.getNodeType() != Node.ELEMENT_NODE) { + continue; + } + + if (DOCTAG == descNode.getNodeName()) { + if (null != descNode.getTextContent()) { + descriptionAttr = descNode.getTextContent(); + break; + } + } + } + } + + if (STATUSTAG == childNode.getNodeName()) { + NamedNodeMap statusAttrMap = childNode.getAttributes(); + if (null != statusAttrMap) { + statusAttr = getNodeValue(statusAttrMap.getNamedItem(STATUSTAG)); + } + } + } + + TestResult testData = new TestResult(); + testData.setName(nameAttr); + testData.setDescription(descriptionAttr); + testData.setStatus(statusAttr); + + resultData.add(testData); + } + + TestResultMap.getInstance().setTestResultMap(UUID.fromString(taskID), resultData); + + } catch (ParserConfigurationException | SAXException | IOException e) { + logger.error("Exception while parsing file :" + xmlFile); + logger.error("Exception while parsing file :", e); + } + } + + private Document createDocument(String fileName) throws ParserConfigurationException, SAXException, IOException { + InputStream inputStream = new FileInputStream(fileName); + DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); + Document doc = docBuilder.parse(inputStream); + doc.getDocumentElement().normalize(); + return doc; + } + + private String getNodeValue(Node namedItem) { + return (null != namedItem) ? namedItem.getNodeValue() : null; + } +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/responsehandler/VnfFuncTestResponseHandler.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/responsehandler/VnfFuncTestResponseHandler.java new file mode 100644 index 0000000..0dce5a0 --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/responsehandler/VnfFuncTestResponseHandler.java @@ -0,0 +1,138 @@ +/* + * 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.onap.vnfsdk.functest.responsehandler; + +import com.google.gson.Gson; +import com.google.gson.stream.JsonReader; +import org.onap.vnfsdk.functest.FileUtil; +import org.onap.vnfsdk.functest.util.RestResponseUtil; +import org.onap.vnfsdk.functest.util.ZipCompressor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.core.Response; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.List; +import java.util.Map; + +public class VnfFuncTestResponseHandler { + + private static final Logger logger = LoggerFactory.getLogger(VnfFuncTestResponseHandler.class); + private static int actioninProgress = 21; + private static int error = 22; + private static String resultFileName = "output.xml"; + private static String resultPathKey = "DIR_RESULT"; + private static Map mapConfigValues; + private static VnfFuncTestResponseHandler vnfFuncRspHandler; + + private VnfFuncTestResponseHandler() { + } + + public static VnfFuncTestResponseHandler getInstance() { + if (vnfFuncRspHandler == null) { + vnfFuncRspHandler = new VnfFuncTestResponseHandler(); + loadConfigurations(); + } + return vnfFuncRspHandler; + } + + public static void setConfigMap(Map inMapConfigValues) { + mapConfigValues = inMapConfigValues; + } + + @SuppressWarnings("unchecked") + private static void loadConfigurations() { + String curDir = System.getProperty("user.dir"); + String confDir = curDir + File.separator + "conf" + File.separator + "robot" + File.separator; +// ObjectMapper mapper = new ObjectMapper(); + + try { +// mapConfigValues = mapper.readValue(new FileInputStream(confDir + "robotMetaData.json"), Map.class); + mapConfigValues = new Gson().fromJson(new JsonReader(new FileReader(confDir + "robotMetaData.json")), Map.class); + } catch (IOException e) { + logger.error("Reading Json Meta data file failed or file do not exist", e); + } + } + + public Response getResponseByFuncTestId(String funcTestId) { + + if ((null == mapConfigValues) || (null == mapConfigValues.get(resultPathKey))) { + logger.warn("Result Store path not configured !!!"); + return RestResponseUtil.getErrorResponse(error); + } + + String resultPath = mapConfigValues.get(resultPathKey); + + /* + * Check whether file Exists for the Request received !!! + * ----------------------------------------------------- + */ + String fileName = resultPath + File.separator + funcTestId; + if (!FileUtil.checkFileExist(fileName)) { + logger.warn("Requested function Test result not available/In-Progress !!!"); + return RestResponseUtil.getErrorResponse(actioninProgress); + } + + String zipFileName = fileName + ".zip"; + try { + new ZipCompressor(zipFileName).compress(fileName); + } catch (IOException e) { + logger.error("getResponseByFuncTestId ", e); + } + + /* + * Convert Zip-file byteCode and to response !!! + * ----------------------------------------------------- + */ + byte[] byteArrayFile = FileUtil.convertZipFiletoByteArray(zipFileName); + + if (null != byteArrayFile) { + + /* + * Delete Result folders present if Success !!! + * ---------------------------------------------- + */ + FileUtil.deleteFile(zipFileName); + /* + * Later will delete this file + */ + logger.warn("Requested function Test result Success !!!"); + return RestResponseUtil.getSuccessResponse(byteArrayFile); + } else { + logger.warn("Requested function Test result Failed !!!"); + return RestResponseUtil.getErrorResponse(error); + } + } + + public Response downloadResults(String funcTestId) { + + if ((null == mapConfigValues) || (null == mapConfigValues.get(resultPathKey))) { + logger.warn("Result Store path not configured !!!"); + return RestResponseUtil.getErrorResponse(error); + } + + String resultPath = mapConfigValues.get(resultPathKey); + String resultfileName = resultPath + File.separator + funcTestId + File.separator + resultFileName; + logger.info(resultfileName); + TestResultParser oTestResultParser = new TestResultParser(); + List resultList = oTestResultParser.populateResultList(funcTestId, resultfileName); + return (!resultList.isEmpty()) ? RestResponseUtil.getSuccessResponse(resultList) + : RestResponseUtil.getErrorResponse(error); + } +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/scriptmgr/ScriptManager.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/scriptmgr/ScriptManager.java new file mode 100644 index 0000000..1dae79f --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/scriptmgr/ScriptManager.java @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2018 Intel Corporation Intellectual Property + * + * 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.onap.vnfsdk.functest.scriptmgr; + +import com.google.gson.Gson; +import org.onap.vnfsdk.functest.FileUtil; +import org.onap.vnfsdk.functest.TaskExecution; +import org.onap.vnfsdk.functest.constants.ApplicationConstants; +import org.onap.vnfsdk.functest.db.TaskMgrCaseTblDAO; +import org.onap.vnfsdk.functest.db.TaskMgrTaskTblDAO; +import org.onap.vnfsdk.functest.externalservice.entity.Environment; +import org.onap.vnfsdk.functest.externalservice.entity.EnvironmentMap; +import org.onap.vnfsdk.functest.externalservice.entity.OperationStatus; +import org.onap.vnfsdk.functest.externalservice.entity.OperationStatusHandler; +import org.onap.vnfsdk.functest.models.CaseRecord; +import org.onap.vnfsdk.functest.models.TaskRecord; +import org.onap.vnfsdk.functest.responsehandler.TestResult; +import org.onap.vnfsdk.functest.responsehandler.TestResultMap; +import org.onap.vnfsdk.functest.responsehandler.VnfFuncTestResponseHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.core.Response; +import java.io.*; +import java.net.URL; +import java.util.List; +import java.util.StringTokenizer; +import java.util.UUID; +import java.util.concurrent.*; + +public class ScriptManager { + + private static final Logger LOGGER = LoggerFactory.getLogger(ScriptManager.class); + private final TaskMgrTaskTblDAO taskMgrTaskTblDAO; + private final TaskMgrCaseTblDAO taskMgrCaseTblDAO; + + public ScriptManager(TaskMgrTaskTblDAO taskMgrTaskTblDAO, TaskMgrCaseTblDAO taskMgrCaseTblDAO) { + this.taskMgrTaskTblDAO = taskMgrTaskTblDAO; + this.taskMgrCaseTblDAO = taskMgrCaseTblDAO; + } + + /** + * Convert the stream to File Name
+ * + * @param dirName - Directory name + * @param fileName - FileName + * @param uploadedInputStream - Input Stream + * @return - File Path + * @throws IOException - Exception while writing file + * @since VNFSDK + */ + public static String storeChunkFileInLocal(String dirName, String fileName, InputStream uploadedInputStream) + throws IOException { + File tmpDir = new File(dirName); + LOGGER.info("tmpdir=" + dirName); + if (!tmpDir.exists()) { + tmpDir.mkdirs(); + } + StringTokenizer st = new StringTokenizer(fileName, "/"); + String actualFile = null; + while (st.hasMoreTokens()) { + actualFile = st.nextToken(); + } + File file = new File(tmpDir + File.separator + actualFile); + OutputStream os = null; + try { + int read = 0; + byte[] bytes = new byte[1024]; + os = new FileOutputStream(file, true); + while ((read = uploadedInputStream.read(bytes)) != -1) { + os.write(bytes, 0, read); + } + os.flush(); + return file.getAbsolutePath(); + } finally { + if (os != null) { + os.close(); + } + } + } + + public UUID setEnvironment(String env) { + LOGGER.info("[Scrip Manager] Set Environment."); + + try { + + // Generate UUID for each environment + final UUID envID = UUID.randomUUID(); + + // Convert input string to Environment class +// ObjectMapper mapper = new ObjectMapper(); +// Environment envObj = mapper.readValue(env, Environment.class); + Environment envObj = new Gson().fromJson(env, Environment.class); + if (null == envObj) { + // Converting input to Env object failed + return null; + } + + // Set to the environment map + EnvironmentMap.getInstance().addEnv(envID, envObj); + LOGGER.info(EnvironmentMap.getInstance().getEnv(envID).getPassword()); + + // Send the envID back + return envID; + + } catch (Exception e) { + LOGGER.error("Setting the Environment Fail", e); + } + + return null; + } + + public UUID uploadFuncTestPackage(UUID taskID, UUID envID, String url) { + LOGGER.info("[Scrip Manager] Upload Function Test Package."); + + try { + URL oracle = new URL(url); + + InputStream fis = new BufferedInputStream(oracle.openStream()); + + // Convert the stream to script folder + String nl = File.separator; + String filePath = storeChunkFileInLocal("temp", "TempFile.zip", fis); + + // Unzip the folder + String tempDir = System.getProperty("user.dir") + nl + "temp"; + List list = FileUtil.unzip(filePath, tempDir); + LOGGER.info("File path=" + filePath); + + String[] directories = FileUtil.getDirectory(tempDir); + LOGGER.info("tempdir=" + tempDir); + if (null != directories && 0 != directories.length) { + filePath = tempDir + File.separator + directories[0]; + } else { + filePath = tempDir; + } + + // generate UUID for the upload + final UUID uploadID = UUID.randomUUID(); + List taskRecordList = taskMgrTaskTblDAO.findByTaskID(taskID.toString()); + TaskRecord taskRecord = taskRecordList.get(0); + taskRecord.setUploadID(uploadID.toString()); + taskRecord.setOperID(uploadID.toString()); + taskMgrTaskTblDAO.saveOrUpdate(taskRecord); + + final String finalPath = filePath; + + ExecutorService es = Executors.newFixedThreadPool(3); + Future future = es.submit(new Callable() { + + @Override + public Integer call() throws Exception { + + new TaskExecution().uploadScript(finalPath, envID, uploadID); + return 0; + } + }); + + try { + if (0 == future.get(5, TimeUnit.SECONDS)) { + LOGGER.info("ExecutorService Done"); + + OperationStatus operStatus = OperationStatusHandler.getInstance().getOperStatusMap().get(uploadID); + taskRecord.setOperFinished(operStatus.isOperFinished() ? "True" : "False"); + taskRecord.setOperResult(operStatus.getoResultCode().toString()); + taskRecord.setOperResultMessage(operStatus.getOperResultMessage()); + taskMgrTaskTblDAO.saveOrUpdate(taskRecord); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (ExecutionException e) { + e.printStackTrace(); + } catch (TimeoutException e) { + LOGGER.info("Time out."); + e.printStackTrace(); + } + + return uploadID; + + } catch (IOException e) { + LOGGER.error(ApplicationConstants.RUN_SCRIPT_EXECUTE_CMD, e); + } + + return null; + } + + public Response getOperationResult(UUID operID) { + LOGGER.info("[Script Manager] Query functest Status by ID." + operID); + + return OperationStatusHandler.getInstance().getOperationStatus(operID); + } + + public Response downloadResults(UUID taskID) { + LOGGER.info("[Script Manager] Download functest Result by ID: " + taskID); + + Response resp = VnfFuncTestResponseHandler.getInstance().downloadResults(taskID.toString()); + + try { + TestResult testResult = TestResultMap.getInstance().getTestResultMap().get(taskID).get(0); + + CaseRecord caseRecord = taskMgrCaseTblDAO.findByTaskID(taskID.toString()); + caseRecord.setTestID(testResult.getName()); + caseRecord.setTestResult(testResult.getStatus()); + caseRecord.setTestDescription(testResult.getDescription()); + taskMgrCaseTblDAO.saveOrUpdate(caseRecord); + } catch (Exception e) { + LOGGER.error("Collect Functest Result by ID Failed.", e); + } + return resp; + } + + +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/taskmgr/TaskManager.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/taskmgr/TaskManager.java new file mode 100644 index 0000000..79e611b --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/taskmgr/TaskManager.java @@ -0,0 +1,258 @@ +/* + * Copyright (c) 2018 Intel Corporation Intellectual Property + * + * 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.onap.vnfsdk.functest.taskmgr; + +import com.codahale.metrics.annotation.Timed; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.stream.JsonReader; +import io.dropwizard.hibernate.UnitOfWork; +import io.swagger.annotations.*; +import org.eclipse.jetty.http.HttpStatus; +import org.onap.vnfsdk.functest.constants.ApplicationConstants; +import org.onap.vnfsdk.functest.db.TaskMgrCaseTblDAO; +import org.onap.vnfsdk.functest.db.TaskMgrTaskTblDAO; +import org.onap.vnfsdk.functest.externalservice.entity.OperationStatus; +import org.onap.vnfsdk.functest.externalservice.entity.OperationStatusHandler; +import org.onap.vnfsdk.functest.models.CaseRecord; +import org.onap.vnfsdk.functest.models.TaskRecord; +import org.onap.vnfsdk.functest.scriptmgr.ScriptManager; +import org.onap.vnfsdk.functest.util.RestResponseUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +@Path("/functest/taskmanager") +@Api(tags = {" Function Test Task Manager "}) +public class TaskManager { + + private static final Logger LOGGER = LoggerFactory.getLogger(TaskManager.class); + + private final TaskMgrTaskTblDAO taskMgrTaskTblDAO; + private final TaskMgrCaseTblDAO taskMgrCaseTblDAO; + private final ScriptManager scriptManager; + + public TaskManager(TaskMgrTaskTblDAO taskMgrTaskTblDAO, TaskMgrCaseTblDAO taskMgrCaseTblDAO, ScriptManager scriptManager) { + this.taskMgrTaskTblDAO = taskMgrTaskTblDAO; + this.taskMgrCaseTblDAO = taskMgrCaseTblDAO; + this.scriptManager = scriptManager; + } + + @Path("/onboard") + @POST + @ApiOperation(value = "Start Onboard Testing") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + //@Timed + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", response = String.class), + @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "internal server error", response = String.class)}) + @UnitOfWork + public Response startOnboardTesting(RequestBody requestBody) { + LOGGER.info("[Task Manager] Start Onboard Testing"); + TaskRecord taskRecord = new TaskRecord(); + CaseRecord caseRecord = new CaseRecord(); + + String packageID = requestBody.packageID; + + try { + if (taskMgrTaskTblDAO.findByPackageID(packageID).isPresent()) { + throw new Exception("Already Onboard."); + } else { + initOnboardTesting(taskRecord, caseRecord, packageID); + scriptManager.uploadFuncTestPackage(UUID.fromString(taskRecord.getTaskID()), UUID.fromString(taskRecord.getEnvID()), ApplicationConstants.CATALOG_URI); + } + return RestResponseUtil.getCreateSuccessResponse(UUID.fromString(taskRecord.getTaskID())); + + } catch (Exception e) { + if ("Already Onboard.".equals(e.getMessage())) { + LOGGER.error("The Package " + packageID + " is already the onboarding package.", e); + return RestResponseUtil.getErrorResponse(packageID); + } else { + LOGGER.error("Start Onboard Testing Fail", e); + } + } + return null; + } + + @Path("/status/{taskID}") + @GET + @ApiOperation(value = "Query Function Test Status by ID") + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", response = String.class), + @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "internal server error", response = String.class)}) + @Timed + @UnitOfWork + public Response queryTestStatus(@ApiParam(value = "taskID") @PathParam("taskID") String taskID) { + LOGGER.info("[Task Manager] Query Function Test Status by ID: " + taskID); + + try { + + List taskRecordList = taskMgrTaskTblDAO.findByTaskID(taskID); + if (taskRecordList.isEmpty()) { + throw new Exception("Task Not Exist."); + } else { + + TaskRecord taskRecord = taskRecordList.get(0); + UUID operID = UUID.fromString(taskRecord.getOperID()); + + LOGGER.info(taskRecord.getOperID()); + OperationStatus operStatus = OperationStatusHandler.getInstance().getOperStatusMap().get(operID); + /** + * To check whether the operID belongs to a record in memory. + * If so, needs refresh db: retrieve the data from the record in memory and update the db accordingly. + * If not, means a historical record in db. Obtain the data from db. + * */ + if (null != operStatus) { + taskRecord.setOperFinished(operStatus.isOperFinished() ? "True" : "False"); + taskRecord.setOperResult(operStatus.getoResultCode().toString()); + taskRecord.setOperResultMessage(operStatus.getOperResultMessage()); + taskMgrTaskTblDAO.saveOrUpdate(taskRecord); + } else { + OperationStatus oldOperStatus = new OperationStatus(); + oldOperStatus.setoResultCode(OperationStatus.operResultCode.valueOf(taskRecord.getOperResult())); + oldOperStatus.setOperResultMessage(taskRecord.getOperResultMessage()); + oldOperStatus.setOperFinished("True".equals(taskRecord.getOperFinished())); + OperationStatusHandler.getInstance().setOperStatusMap(operID, oldOperStatus); + } + return scriptManager.getOperationResult(operID); + } + } catch (Exception e) { + if ("Task Not Exist.".equals(e.getMessage())) { + LOGGER.error("The Task " + taskID + " does not exist..!", e); + return RestResponseUtil.getNotFoundResponse(taskID); + } else { + LOGGER.error("Query Function Test Status by ID Failed.", e); + } + } + return null; + } + + @Path("/result/{taskID}") + @GET + @ApiOperation(value = "Get Function Test Result by ID") + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", response = String.class), + @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "internal server error", response = String.class)}) + @Timed + @UnitOfWork + public Response collectTaskResult(@ApiParam(value = "taskID") @PathParam("taskID") String taskID) { + LOGGER.info("[Task Manager] Collect Function Test Result by ID." + taskID); + + try { + CaseRecord caseRecord = taskMgrCaseTblDAO.findByTaskID(taskID); + if (null == caseRecord) { + throw new Exception("Task Not Exist."); + } else { + /* To check whether we have already collected the result of Task: taskID. */ + if ("NOT CREATED".equals(caseRecord.getTestID())) { + return scriptManager.downloadResults(UUID.fromString(taskID)); + } else { + CaseRecord oldCaseRecord = new CaseRecord(); + oldCaseRecord.setTestID(caseRecord.getTestID()); + oldCaseRecord.setTestResult(caseRecord.getTestResult()); + oldCaseRecord.setTestDescription(caseRecord.getTestDescription()); + return RestResponseUtil.getSuccessResponse(oldCaseRecord); + } + } + } catch (Exception e) { + if ("Task Not Exist.".equals(e.getMessage())) { + LOGGER.error("The Task " + taskID + " does not exist..!", e); + return RestResponseUtil.getNotFoundResponse(taskID); + } else { + LOGGER.error("Collect Function Test Result by ID Failed.", e); + } + } + return null; + } + + private void initOnboardTesting(TaskRecord taskRecord, CaseRecord caseRecord, String packageID) { + /* Create TaskRecord entry in db */ + taskRecord.setPackageID(packageID); + // Generate UUID for each task + final UUID taskID = UUID.randomUUID(); + taskRecord.setTaskID(taskID.toString()); + // Setup the environment + final UUID envID = scriptManager.setEnvironment(loadEnvConfigurations()); + taskRecord.setEnvID(envID.toString()); + taskRecord.setUploadID("NOT CREATED"); + taskRecord.setOperID("NOT CREATED"); + taskRecord.setFuncID(""); + taskRecord.setStatus("CREATED"); + taskRecord.setOperFinished("False"); + taskRecord.setOperResult("FAILURE"); + taskRecord.setOperResultMessage(""); + taskMgrTaskTblDAO.saveOrUpdate(taskRecord); + + /* Create CaseRecord entry in db */ + caseRecord.setTaskID(taskID.toString()); + caseRecord.setFuncID(""); + caseRecord.setTestID("NOT CREATED"); + caseRecord.setTestResult("NULL"); + caseRecord.setTestDescription(""); + taskMgrCaseTblDAO.saveOrUpdate(caseRecord); + } + + private String loadEnvConfigurations() { + Map envConfigurations; + String strEnvConfigurations; + String curDir = System.getProperty("user.dir"); + String confDir = curDir + File.separator + ApplicationConstants.CONF + File.separator + ApplicationConstants.ENVIRONMENT + File.separator; + + try { + + envConfigurations = new Gson().fromJson(new JsonReader(new FileReader(confDir + ApplicationConstants.ENVIRONMENT_JSON)), Map.class); + Gson gson = new GsonBuilder().create(); + strEnvConfigurations = gson.toJson(envConfigurations); + + return strEnvConfigurations; + } catch (IOException e) { + LOGGER.error("Reading Environment Json data file failed or file does not exist", e); + } + return null; + } + + public static class RequestBody { + + @JsonProperty("packageID") + private String packageID; + + public String getPackageID() { + return packageID; + } + + public void setPackageID(String packageID) { + this.packageID = packageID; + } + } + +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/util/GsonUtil.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/util/GsonUtil.java new file mode 100644 index 0000000..b453d3c --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/util/GsonUtil.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.onap.vnfsdk.functest.util; + +import com.google.gson.Gson; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.UUID; + +public class GsonUtil { + + private GsonUtil() { + + } + + public static String generateId() { + return UUID.randomUUID().toString(); + } + + public static boolean isNotEmpty(String str) { + return str != null && !"".equals(str) && str.length() > 0; + } + + /** + * change object to str. + */ + public static String objectToString(Object obj) { + Gson gson = new Gson(); + if (obj != null) { + return gson.toJson(obj); + } else { + return null; + } + } + + public static String getNowTime() { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + return sdf.format(new Date()); + } +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/util/RestResponseUtil.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/util/RestResponseUtil.java new file mode 100644 index 0000000..40ab57e --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/util/RestResponseUtil.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.onap.vnfsdk.functest.util; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +public class RestResponseUtil { + + private RestResponseUtil() { + } + + public static Response getSuccessResponse(Object obj) { + if (obj != null) { + return Response.ok(GsonUtil.objectToString(obj)).build(); + } else { + return Response.ok().build(); + } + } + + public static Response getCreateSuccessResponse(Object obj) { + return Response.status(Status.CREATED).entity(obj).build(); + } + + public static Response getNotFoundResponse(Object obj) { + if (obj != null) { + return Response.status(Status.NOT_FOUND).entity(GsonUtil.objectToString(obj)).build(); + } else { + return Response.serverError().build(); + } + } + + public static Response getErrorResponse(Object obj) { + if (obj != null) { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(GsonUtil.objectToString(obj)).build(); + } else { + return Response.serverError().build(); + } + + } +} diff --git a/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/util/ZipCompressor.java b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/util/ZipCompressor.java new file mode 100644 index 0000000..de2875e --- /dev/null +++ b/vnf-sdk-function-test/src/main/java/org/onap/vnfsdk/functest/util/ZipCompressor.java @@ -0,0 +1,103 @@ +/* + * 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.onap.vnfsdk.functest.util; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; +import java.util.zip.CRC32; +import java.util.zip.CheckedOutputStream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +public class ZipCompressor { + + public static final Logger LOG = LoggerFactory.getLogger(ZipCompressor.class); + + static final int BUFFER = 8192; + + private File zipFile; + + public ZipCompressor(String pathName) { + zipFile = new File(pathName); + } + + /** + * compress file according file path. + * + * @param srcPathName file path name + * @throws IOException + */ + public void compress(String srcPathName) throws IOException { + File file = new File(srcPathName); + if (!file.exists()) { + throw new FileNotFoundException(srcPathName + "not exist!"); + } + try { + FileOutputStream fileOutputStream = new FileOutputStream(zipFile); + CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, new CRC32()); + ZipOutputStream out = new ZipOutputStream(cos); + String basedir = ""; + compress(file, out, basedir); + out.close(); + } catch (Exception e1) { + throw new IOException(e1); + } + } + + private void compress(File file, ZipOutputStream out, String basedir) { + if (file.isDirectory()) { + LOG.info("compress: " + basedir + file.getName()); + this.compressDirectory(file, out, basedir); + } else { + LOG.info("compress: " + basedir + file.getName()); + this.compressFile(file, out, basedir); + } + } + + private void compressDirectory(File dir, ZipOutputStream out, String basedir) { + if (!dir.exists()) { + return; + } + + File[] files = dir.listFiles(); + for (int i = 0; i < files.length; i++) { + compress(files[i], out, basedir + dir.getName() + "/"); + } + } + + private void compressFile(File file, ZipOutputStream out, String basedir) { + if (!file.exists()) { + return; + } + try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) { + + byte[] data = new byte[BUFFER]; + + ZipEntry entry = new ZipEntry(basedir + file.getName()); + out.putNextEntry(entry); + int count; + while ((count = bis.read(data, 0, BUFFER)) != -1) { + out.write(data, 0, count); + } + bis.close(); + } catch (IOException e) { + LOG.info("Exception wile compress file" + file.getAbsolutePath(), e); + } + } +} diff --git a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/FileUtil.java b/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/FileUtil.java deleted file mode 100644 index 7a5dbba..0000000 --- a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/FileUtil.java +++ /dev/null @@ -1,251 +0,0 @@ -/* - * 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.vnfsdk.functest; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public final class FileUtil { - - public static final Logger LOG = LoggerFactory.getLogger(FileUtil.class); - - private static final int BUFFER_SIZE = 2 * 1024 * 1024; - - private static final int TRY_COUNT = 3; - - private FileUtil() { - - } - - /** - * Create directory. - * - * @param dir directory to create - * @return boolean - */ - public static boolean createDirectory(String dir) { - File folder = new File(dir); - int tryCount = 0; - while(tryCount < TRY_COUNT) { - tryCount++; - if(!folder.exists() && !folder.mkdirs()) { - continue; - } else { - return true; - } - } - - return folder.exists(); - } - - /** - * delete file. - * - * @param file the file to delete - * @return boolean - */ - public static boolean deleteFile(File file) { - String hintInfo = file.isDirectory() ? "dir " : "file "; - boolean isFileDeleted = file.delete(); - boolean isFileExist = file.exists(); - if(!isFileExist) { - if(isFileDeleted) { - LOG.info("delete " + hintInfo + file.getAbsolutePath()); - } else { - isFileDeleted = true; - LOG.info("file not exist. no need delete " + hintInfo + file.getAbsolutePath()); - } - } else { - LOG.info("fail to delete " + hintInfo + file.getAbsolutePath()); - } - return isFileDeleted; - } - - /** - * unzip zip file. - * - * @param zipFileName file name to zip - * @param extPlace extPlace - * @return unzip file name - * @throws IOException e1 - */ - public static List unzip(String zipFileName, String extPlace) throws IOException { - ZipFile zipFile = null; - ArrayList unzipFileNams = new ArrayList(); - - try { - zipFile = new ZipFile(zipFileName); - Enumeration fileEn = zipFile.entries(); - byte[] buffer = new byte[BUFFER_SIZE]; - - while(fileEn.hasMoreElements()) { - InputStream input = null; - BufferedOutputStream bos = null; - try { - ZipEntry entry = (ZipEntry)fileEn.nextElement(); - if(entry.isDirectory()) { - continue; - } - - input = zipFile.getInputStream(entry); - File file = new File(extPlace, entry.getName()); - if(!file.getParentFile().exists()) { - createDirectory(file.getParentFile().getAbsolutePath()); - } - - bos = new BufferedOutputStream(new FileOutputStream(file)); - while(true) { - int length = input.read(buffer); - if(length == -1) { - break; - } - bos.write(buffer, 0, length); - } - unzipFileNams.add(file.getAbsolutePath()); - } finally { - closeOutputStream(bos); - closeInputStream(input); - } - } - } finally { - closeZipFile(zipFile); - } - return unzipFileNams; - } - - public static String[] getDirectory(String directory) { - File file = new File(directory); - return file.list(new FilenameFilter() { - - public boolean accept(File current, String name) { - return new File(current, name).isDirectory(); - } - }); - } - - /** - * close InputStream. - * - * @param inputStream the inputstream to close - */ - private static void closeInputStream(InputStream inputStream) { - try { - if(inputStream != null) { - inputStream.close(); - } - } catch(Exception ex) { - LOG.error("close InputStream error!: " + ex); - } - } - - /** - * close OutputStream. - * - * @param outputStream the output stream to close - */ - private static void closeOutputStream(OutputStream outputStream) { - try { - if(outputStream != null) { - outputStream.close(); - } - } catch(Exception ex) { - LOG.error("close OutputStream error!: " + ex); - } - } - - /** - * close zipFile. - * - * @param zipFile the zipFile to close - */ - private static void closeZipFile(ZipFile zipFile) { - try { - ZipFile tempZipFile = zipFile; - if(tempZipFile != null) { - tempZipFile.close(); - } - } catch(IOException ioe) { - LOG.error("close ZipFile error!: " + ioe); - } - } - - public static Boolean checkFileExist(String filePath) { - File file = new File(filePath); - return file.exists(); - } - - public static Boolean deleteFile(String filePath) { - File file = new File(filePath); - if(file.exists()) { - return file.delete(); - } - return true; - } - - public static byte[] convertZipFiletoByteArray(String filename) { - File file = new File(filename); - byte[] emptyArray = new byte[0]; - if(!file.exists()) { - return emptyArray; - } - - byte[] byteArrayFile = new byte[(int)file.length()]; - try { - FileInputStream fileInputStream = new FileInputStream(filename); - int value = fileInputStream.read(byteArrayFile); - fileInputStream.close(); - LOG.debug("Number of bytes read from fileInputStream = " + value); - } catch(Exception e) { - LOG.error("convertZipFiletoByteArray: " + e); - } - return byteArrayFile; - } - - /** - * Interface to Delete Directory - *
- * - * @param directory - * @since VNFSDK 2.0 - */ - public static void deleteDirectory(String directory) { - File file = new File(directory); - if(!file.exists()) { - return; - } - if(file.isDirectory()) { - for(File sub : file.listFiles()) { - deleteFile(sub); - } - } - file.delete(); - } -} diff --git a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/TaskExecution.java b/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/TaskExecution.java deleted file mode 100644 index d55ec98..0000000 --- a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/TaskExecution.java +++ /dev/null @@ -1,274 +0,0 @@ -/* - * 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.vnfsdk.functest; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Map; -import java.util.Map.Entry; -import java.util.UUID; - -import org.apache.commons.lang3.SystemUtils; -import org.openo.vnfsdk.functest.constants.ApplicationConstants; -import org.openo.vnfsdk.functest.externalservice.entity.Environment; -import org.openo.vnfsdk.functest.externalservice.entity.EnvironmentMap; -import org.openo.vnfsdk.functest.externalservice.entity.OperationStatus; -import org.openo.vnfsdk.functest.externalservice.entity.OperationStatus.operResultCode; -import org.openo.vnfsdk.functest.externalservice.entity.OperationStatusHandler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.databind.ObjectMapper; - -public class TaskExecution { - - private static final Logger LOGGER = LoggerFactory.getLogger(TaskExecution.class); - - public void executeScript(String dirPath, UUID uniqueKey) { - - String nl = File.separator; - String curDir = System.getProperty(ApplicationConstants.USER_DIR); - String confDir = curDir + nl + ApplicationConstants.CONF + nl + ApplicationConstants.ROBOT + nl; - - // Read the MetaData from the VNF package - ObjectMapper mapper = new ObjectMapper(); - - Map mapValues = null; - try { - mapValues = - mapper.readValue(new FileInputStream(confDir + ApplicationConstants.ROBOTMETADATA_JSON), Map.class); - } catch(IOException e) { - - LOGGER.error(ApplicationConstants.JSON_METADATA_FILE_FAILED, e); - return; - } - - // Form the variables for the upload, transfer and execute command - String scriptDirName = new File(dirPath).getName(); - mapValues.put("SCRIPT_DIR", dirPath); - - String remoteScriptDir = mapValues.get("DIR_REMOTE") + scriptDirName; - String remoteScriptResult = remoteScriptDir + "/" + "output "; - mapValues.put("DIR_REMOTE_RESULT", remoteScriptResult); - - String dirResult = mapValues.get(ApplicationConstants.DIR_RESULT) + uniqueKey; - mapValues.put(ApplicationConstants.DIR_RESULT, dirResult); - - String remoteScriptFile = remoteScriptDir + "/" + mapValues.get("MAIN_SCRIPT"); - String remoteArgs = "--argumentfile " + remoteScriptDir + "/" + "config.args "; - String remoteCommand = - ApplicationConstants.ROBOT_SPACE + "-d " + remoteScriptResult + remoteArgs + remoteScriptFile; - mapValues.put("REMOTE_COMMAND", "\"" + remoteCommand + "\""); - - String robotvariables = ""; - for(Entry values : mapValues.entrySet()) { - - robotvariables = robotvariables + " -v " + values.getKey() + ":" + values.getValue() + " "; - } - - // Execute the command - String argumentFilePath = confDir + "config.args "; - String robotScript = confDir + "RemoteConnection.robot"; - - Process process = null; - InputStream inputStream = null; - int ch; - try { - String command = "robot --argumentfile " + argumentFilePath + robotvariables + " " + robotScript; - LOGGER.info("Command execute to execute the script:" + command); - process = Runtime.getRuntime().exec(new String[] {getShellCommand(), getShellArg(), command}); - if(process != null) { - process.waitFor(); - inputStream = process.getInputStream(); - } - while((ch = inputStream.read()) != -1) { - LOGGER.info(ApplicationConstants.CHARACTER + Integer.toString(ch)); - } - - } catch(Exception e) { - LOGGER.error(ApplicationConstants.TASKEXE_EXESCRIPT_EXCEPTION, e); - } - } - - public void executeRobotScript(UUID envId, UUID executeId) { - - String nl = File.separator; - String curDir = System.getProperty(ApplicationConstants.USER_DIR); - String confDir = curDir + nl + ApplicationConstants.CONF + nl + ApplicationConstants.ROBOT + nl; - - // Read the MetaData from the VNF package - ObjectMapper mapper = new ObjectMapper(); - Map mapValues = null; - try { - mapValues = - mapper.readValue(new FileInputStream(confDir + ApplicationConstants.ROBOTMETADATA_JSON), Map.class); - } catch(IOException e) { - - LOGGER.error(ApplicationConstants.JSON_METADATA_FILE_FAILED, e); - return; - } - - // Get environment of given UUID - Environment functestEnv = EnvironmentMap.getInstance().getEnv(envId); - if(null == functestEnv) { - LOGGER.error("Function Test Environment details are empty,EnvID = " + envId); - } else { - LOGGER.info("Function Test Environment path,Path = " + functestEnv.getPath()); - } - - String remoteDir = functestEnv.getPath() + mapValues.get("SCRIPT_NAME"); - - String remoteConfigArgs = remoteDir + "/" + "config.args "; - String remoteScriptFile = remoteDir + "/" + mapValues.get("MAIN_SCRIPT"); - String remoteScriptResult = remoteDir + "/" + "output "; - String dirResult = mapValues.get(ApplicationConstants.DIR_RESULT) + executeId; - - // set the argument parameters - String remoteArgs = ""; - remoteArgs = remoteArgs + " -v " + "NODE_IP" + ":" + functestEnv.getRemoteIp() + " "; - remoteArgs = remoteArgs + " -v " + "NODE_USERNAME" + ":" + functestEnv.getUserName() + " "; - remoteArgs = remoteArgs + " -v " + "NODE_PASSWORD" + ":" + functestEnv.getPassword() + " "; - - String remoteCommand = ApplicationConstants.ROBOT_SPACE + "-d " + remoteScriptResult + "--argumentfile " - + remoteConfigArgs + remoteScriptFile; - - // set the parameters required by the execute script - remoteCommand = "\"" + remoteCommand + "\""; - remoteArgs = remoteArgs + " -v " + "REMOTE_COMMAND" + ":" + remoteCommand + " "; - - remoteArgs = remoteArgs + " -v " + ApplicationConstants.DIR_RESULT + ":" + dirResult + " "; - remoteArgs = remoteArgs + " -v " + "DIR_REMOTE_RESULT" + ":" + remoteScriptResult + " "; - - // Execute script directory - String robotScript = confDir + "execute.robot"; - - Process process = null; - InputStream inputStream = null; - int ch; - try { - String command = ApplicationConstants.ROBOT + remoteArgs + robotScript; - LOGGER.info("Command execute to execute the script:" + command); - process = Runtime.getRuntime().exec(new String[] {getShellCommand(), getShellArg(), command}); - if(process != null) { - process.waitFor(); - inputStream = process.getInputStream(); - } - - while((ch = inputStream.read()) != -1) { - LOGGER.info(ApplicationConstants.CHARACTER + Integer.toString(ch)); - } - } catch(Exception e) { - LOGGER.error(ApplicationConstants.TASKEXE_EXESCRIPT_EXCEPTION, e); - } - - OperationStatus operstatus = new OperationStatus(); - operstatus.setoResultCode(operResultCode.SUCCESS); - operstatus.setOperResultMessage("Execute function test finished"); - operstatus.setOperFinished(true); - OperationStatusHandler.getInstance().setOperStatusMap(executeId, operstatus); - } - - public void uploadScript(String dirPath, UUID uuidEnv, UUID uuidUpload) { - - String nl = File.separator; - String curDir = System.getProperty(ApplicationConstants.USER_DIR); - String confDir = curDir + nl + ApplicationConstants.CONF + nl + ApplicationConstants.ROBOT + nl; - - // Read the MetaData from the VNF package - ObjectMapper mapper = new ObjectMapper(); - - Map mapValues = null; - try { - - mapValues = - mapper.readValue(new FileInputStream(confDir + ApplicationConstants.ROBOTMETADATA_JSON), Map.class); - } catch(Exception e) { - - LOGGER.error(ApplicationConstants.JSON_METADATA_FILE_FAILED, e); - return; - } - - // Form the variables for the upload, transfer and execute command - mapValues.put("SCRIPT_DIR", dirPath); - - String robotvariables = ""; - for(Entry values : mapValues.entrySet()) { - - robotvariables = robotvariables + " -v " + values.getKey() + ":" + values.getValue() + " "; - } - - // Append the Func test environment variables - Environment functestEnv = EnvironmentMap.getInstance().getEnv(uuidEnv); - robotvariables = robotvariables + " -v " + "NODE_IP" + ":" + functestEnv.getRemoteIp() + " "; - robotvariables = robotvariables + " -v " + "NODE_USERNAME" + ":" + functestEnv.getUserName() + " "; - robotvariables = robotvariables + " -v " + "NODE_PASSWORD" + ":" + functestEnv.getPassword() + " "; - robotvariables = robotvariables + " -v " + "DIR_REMOTE" + ":" + functestEnv.getPath() + " "; - - // Execute the command - String robotScript = confDir + "upload.robot"; - - Process process = null; - InputStream inputStream = null; - int ch; - try { - String command = ApplicationConstants.ROBOT_SPACE + robotvariables + robotScript; - LOGGER.info("Command execute to upload the script:" + command); - process = Runtime.getRuntime().exec(new String[] {getShellCommand(), getShellArg(), command}); - if(process != null) { - process.waitFor(); - inputStream = process.getInputStream(); - } - - while((ch = inputStream.read()) != -1) { - LOGGER.info(ApplicationConstants.CHARACTER + Integer.toString(ch)); - } - - } catch(Exception e) { - LOGGER.error(ApplicationConstants.TASKEXE_EXESCRIPT_EXCEPTION, e); - } - - OperationStatus operstatus = new OperationStatus(); - operstatus.setoResultCode(operResultCode.SUCCESS); - operstatus.setOperResultMessage(""); - operstatus.setOperFinished(true); - OperationStatusHandler.getInstance().setOperStatusMap(uuidUpload, operstatus); - - } - - private String getShellCommand() { - - String shellcommand = ApplicationConstants.SHELL_COMMAND; - if(SystemUtils.IS_OS_LINUX) { - shellcommand = ApplicationConstants.SHELL_COMMAND_BASH; - } - - return shellcommand; - } - - private String getShellArg() { - - String commandArg = "/c"; - if(SystemUtils.IS_OS_LINUX) { - commandArg = "-c"; - } - - return commandArg; - } - -} diff --git a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/VnfSdkFuncTestApp.java b/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/VnfSdkFuncTestApp.java deleted file mode 100644 index b368f23..0000000 --- a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/VnfSdkFuncTestApp.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * 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.vnfsdk.functest; - -import org.glassfish.jersey.media.multipart.MultiPartFeature; -import org.openo.vnfsdk.functest.common.Config; -import org.openo.vnfsdk.functest.common.ServiceRegistration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.annotation.JsonInclude; - -import io.dropwizard.Application; -import io.dropwizard.assets.AssetsBundle; -import io.dropwizard.server.SimpleServerFactory; -import io.dropwizard.setup.Bootstrap; -import io.dropwizard.setup.Environment; -import io.swagger.jaxrs.config.BeanConfig; -import io.swagger.jaxrs.listing.ApiListingResource; - -public class VnfSdkFuncTestApp extends Application { - - private static final Logger LOGGER = LoggerFactory.getLogger(VnfSdkFuncTestApp.class); - - public static void main(String[] args) throws Exception { - new VnfSdkFuncTestApp().run(args); - } - - @Override - public String getName() { - return "OPENO-VNFSDK-FunctionTest"; - } - - @Override - public void initialize(Bootstrap bootstrap) { - bootstrap.addBundle(new AssetsBundle("/api-doc", "/api-doc", "index.html", "api-doc")); - - } - - private void initService() { - Thread registerExtsysService = new Thread(new ServiceRegistration()); - registerExtsysService.setName("Register vnfsdk-functionTest service to Microservice Bus"); - registerExtsysService.start(); - } - - @Override - public void run(VnfSdkFuncTestAppConfiguration configuration, Environment environment) { - LOGGER.info("Start to initialize vnfsdk function test."); - environment.jersey().packages("org.openo.vnfsdk.functest.resource"); - environment.jersey().register(MultiPartFeature.class); - initSwaggerConfig(environment, configuration); - Config.setConfigration(configuration); - initService(); - LOGGER.info("Initialize vnfsdk function test finished."); - } - - private void initSwaggerConfig(Environment environment, VnfSdkFuncTestAppConfiguration configuration) { - environment.jersey().register(new ApiListingResource()); - environment.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL); - - BeanConfig config = new BeanConfig(); - config.setTitle("Open-o VnfSdk Functest Service rest API"); - config.setVersion("1.0.0"); - config.setResourcePackage("org.openo.vnfsdk.functest.resource"); - - SimpleServerFactory simpleServerFactory = (SimpleServerFactory)configuration.getServerFactory(); - String basePath = simpleServerFactory.getApplicationContextPath(); - String rootPath = simpleServerFactory.getJerseyRootPath(); - rootPath = rootPath.substring(0, rootPath.indexOf("/*")); - basePath = - ("/").equals(rootPath) ? rootPath : (new StringBuilder()).append(basePath).append(rootPath).toString(); - config.setBasePath(basePath); - config.setScan(true); - } - -} diff --git a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/VnfSdkFuncTestAppConfiguration.java b/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/VnfSdkFuncTestAppConfiguration.java deleted file mode 100644 index 574fe0d..0000000 --- a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/VnfSdkFuncTestAppConfiguration.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * 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.vnfsdk.functest; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; - -import org.hibernate.validator.constraints.NotEmpty; - -import com.fasterxml.jackson.annotation.JsonProperty; - -import io.dropwizard.Configuration; -import io.dropwizard.db.DataSourceFactory; - -public class VnfSdkFuncTestAppConfiguration extends Configuration { - - @NotEmpty - private String template; - - @NotEmpty - private String defaultName = "OPENO-VnfSdk-FuncTest"; - - @NotEmpty - private String msbServerAddr; - - @Valid - private String serviceIp; - - @Valid - @NotNull - private DataSourceFactory database = new DataSourceFactory(); - - @JsonProperty("database") - public DataSourceFactory getDataSourceFactory() { - return database; - } - - @JsonProperty("database") - public void setDataSourceFactory(DataSourceFactory dataSourceFactory) { - this.database = dataSourceFactory; - } - - @JsonProperty - public String getTemplate() { - return template; - } - - @JsonProperty - public void setTemplate(String template) { - this.template = template; - } - - @JsonProperty - public String getDefaultName() { - return defaultName; - } - - @JsonProperty - public void setDefaultName(String name) { - this.defaultName = name; - } - - @JsonProperty - public String getMsbServerAddr() { - return msbServerAddr; - } - - @JsonProperty - public void setMsbServerAddr(String msbServerAddr) { - this.msbServerAddr = msbServerAddr; - } - - @JsonProperty - public String getServiceIp() { - return serviceIp; - } - - @JsonProperty - public void setServiceIp(String serviceIp) { - this.serviceIp = serviceIp; - } -} diff --git a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/common/Config.java b/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/common/Config.java deleted file mode 100644 index 23d4158..0000000 --- a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/common/Config.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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.vnfsdk.functest.common; - -import org.openo.vnfsdk.functest.VnfSdkFuncTestAppConfiguration; - -public class Config { - - private static VnfSdkFuncTestAppConfiguration configration; - - private Config() { - - } - - public static VnfSdkFuncTestAppConfiguration getConfigration() { - return configration; - } - - public static void setConfigration(VnfSdkFuncTestAppConfiguration config) { - configration = config; - } -} diff --git a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/common/ServiceRegistration.java b/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/common/ServiceRegistration.java deleted file mode 100644 index f6cffba..0000000 --- a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/common/ServiceRegistration.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * 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.vnfsdk.functest.common; - -import org.openo.vnfsdk.functest.externalservice.entity.ServiceRegisterEntity; -import org.openo.vnfsdk.functest.externalservice.msb.MicroserviceBusConsumer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ServiceRegistration implements Runnable { - - private final ServiceRegisterEntity funcTestEntity = new ServiceRegisterEntity(); - - private static final Logger LOG = LoggerFactory.getLogger(ServiceRegistration.class); - - public ServiceRegistration() { - initServiceEntity(); - } - - @Override - public void run() { - LOG.info("start extsys microservice register"); - boolean flag = false; - int retry = 0; - - while(!flag) { - LOG.info("VNF-SDK function test microservice register.retry:" + retry); - retry++; - - flag = MicroserviceBusConsumer.registerService(funcTestEntity); - if(retry >= 1000) { - flag = true; - } - - if(flag == false) { - LOG.warn("microservice register failed, sleep 30S and try again."); - threadSleep(30000); - } else { - LOG.info("microservice register success!"); - break; - } - } - LOG.info("VNF-SDK function test microservice register end."); - } - - private void threadSleep(int second) { - LOG.info("start sleep ...."); - try { - Thread.sleep(second); - } catch(InterruptedException error) { - LOG.error("thread sleep error.errorMsg:", error); - Thread.currentThread().interrupt(); - } - LOG.info("sleep end ."); - } - - private void initServiceEntity() { - funcTestEntity.setServiceName("vnfsdk"); - funcTestEntity.setProtocol("REST"); - funcTestEntity.setVersion("v1"); - funcTestEntity.setUrl("/openoapi/vnfsdk/v1"); - funcTestEntity.setSingleNode(Config.getConfigration().getServiceIp(), "8701", 0); - funcTestEntity.setVisualRange("1"); - } -} diff --git a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/constants/ApplicationConstants.java b/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/constants/ApplicationConstants.java deleted file mode 100644 index d3658a9..0000000 --- a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/constants/ApplicationConstants.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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.vnfsdk.functest.constants; - -public class ApplicationConstants { - - public static final String USER_DIR = "user.dir"; - - public static final String ROBOT = "robot"; - - public static final String ROBOT_SPACE = "robot "; - - public static final String CONF = "conf"; - - public static final String ROBOTMETADATA_JSON = "robotMetaData.json"; - - public static final String JSON_METADATA_FILE_FAILED = "Reading Json Meta data file failed or file do not exist"; - - public static final String DIR_RESULT = "DIR_RESULT"; - - public static final String SCRIPT_DIR = "SCRIPT_DIR"; - - public static final String DIR_REMOTE = "DIR_REMOTE"; - - public static final String DIR_REMOTE_RESULT = "DIR_REMOTE_RESULT"; - - public static final String MAIN_SCRIPT = "MAIN_SCRIPT"; - - public static final String SHELL_COMMAND = "cmd.exe"; - - public static final String SHELL_COMMAND_BASH = "/bin/bash"; - - public static final String CHARACTER = "character ..."; - - public static final String TASKEXE_EXESCRIPT_EXCEPTION = "TaskExecution ... executeScript() ... [Exception] ..."; - - public static final String RUN_SCRIPT_EXECUTE_CMD = "Upload the script and execute the script and run command"; - - private ApplicationConstants() { - } - -} diff --git a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/Environment.java b/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/Environment.java deleted file mode 100644 index b63e49b..0000000 --- a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/Environment.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * 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.vnfsdk.functest.externalservice.entity; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class Environment { - - @JsonProperty("remoteIp") - private String remoteIp; - - @JsonProperty("userName") - private String userName; - - @JsonProperty("password") - private String password; - - @JsonProperty("path") - private String path; - - public String getRemoteIp() { - return remoteIp; - } - - public void setRemoteIp(String remoteIp) { - this.remoteIp = remoteIp; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - -} diff --git a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/EnvironmentMap.java b/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/EnvironmentMap.java deleted file mode 100644 index e2a9ebb..0000000 --- a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/EnvironmentMap.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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.vnfsdk.functest.externalservice.entity; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -public class EnvironmentMap { - - private static Map envmap = new HashMap(); - - private static EnvironmentMap oInstance = new EnvironmentMap(); - - private EnvironmentMap() { - // Empty nothing to do - } - - public static synchronized EnvironmentMap getInstance() { - return oInstance; - } - - public synchronized Map getEnvmap() { - return envmap; - } - - public synchronized void addEnv(UUID uuid, Environment envobj) { - envmap.put(uuid, envobj); - } - - public synchronized void delEnv(UUID uuid) { - envmap.remove(uuid); - } - - public synchronized Environment getEnv(UUID uuid) { - return envmap.get(uuid); - } - -} diff --git a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/OperationStatus.java b/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/OperationStatus.java deleted file mode 100644 index 7856563..0000000 --- a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/OperationStatus.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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.vnfsdk.functest.externalservice.entity; - -public class OperationStatus { - - private boolean operFinished = false; - private String operResultMessage; - - public enum operResultCode { - SUCCESS, FAILURE, NOTFOUND - }; - - operResultCode oResultCode; - - public operResultCode getoResultCode() { - return oResultCode; - } - - public void setoResultCode(operResultCode oResultCode) { - this.oResultCode = oResultCode; - } - - public String getOperResultMessage() { - return operResultMessage; - } - - public void setOperResultMessage(String operResultMessage) { - this.operResultMessage = operResultMessage; - } - - public boolean isOperFinished() { - return operFinished; - } - - public void setOperFinished(boolean operFinished) { - this.operFinished = operFinished; - } -} diff --git a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/OperationStatusHandler.java b/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/OperationStatusHandler.java deleted file mode 100644 index 7cadec4..0000000 --- a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/OperationStatusHandler.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * 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.vnfsdk.functest.externalservice.entity; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import javax.ws.rs.core.Response; - -import org.openo.vnfsdk.functest.util.RestResponseUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class OperationStatusHandler { - - private static final Logger LOGGER = LoggerFactory.getLogger(OperationStatusHandler.class); - - private static Map operStatusMap = new HashMap(); - - private static OperationStatusHandler oInstance = new OperationStatusHandler(); - - private OperationStatusHandler() { - // Empty nothing to do - } - - public static synchronized OperationStatusHandler getInstance() { - return oInstance; - } - - public synchronized Map getOperStatusMap() { - return operStatusMap; - } - - public synchronized void setOperStatusMap(UUID uuid, OperationStatus inputOperStatusMap) { - operStatusMap.put(uuid, inputOperStatusMap); - } - - public Response getOperationStatus(UUID uuid) { - - if(getOperStatusMap().containsKey(uuid)) { - - OperationStatus operstatus = getOperStatusMap().get(uuid); - LOGGER.info("Operation Finished?" + operstatus.isOperFinished()); - LOGGER.info("Operation Result Message" + operstatus.getOperResultMessage()); - - return RestResponseUtil.getSuccessResponse(operstatus); - } else { - OperationStatus operstatus = new OperationStatus(); - operstatus.setOperFinished(true); - operstatus.setoResultCode(OperationStatus.operResultCode.NOTFOUND); - LOGGER.error("uuid not found"); - - return RestResponseUtil.getSuccessResponse(operstatus); - - } - - } - -} diff --git a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/ServiceNode.java b/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/ServiceNode.java deleted file mode 100644 index 0d38f06..0000000 --- a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/ServiceNode.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * 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.vnfsdk.functest.externalservice.entity; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@NoArgsConstructor -@AllArgsConstructor -@JsonIgnoreProperties(ignoreUnknown = true) -public class ServiceNode { - - private String ip; - - private String port; - - private int ttl; - - public String getIp() { - return ip; - } - - public void setIp(String ip) { - this.ip = ip; - } - - public String getPort() { - return port; - } - - public void setPort(String port) { - this.port = port; - } - - public int getTtl() { - return ttl; - } - - public void setTtl(int ttl) { - this.ttl = ttl; - } - - -} diff --git a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/ServiceRegisterEntity.java b/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/ServiceRegisterEntity.java deleted file mode 100644 index c6d885a..0000000 --- a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/entity/ServiceRegisterEntity.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * 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.vnfsdk.functest.externalservice.entity; - -import java.util.ArrayList; -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@NoArgsConstructor -@AllArgsConstructor -@JsonIgnoreProperties(ignoreUnknown = true) -public class ServiceRegisterEntity { - - private String serviceName; - - private String version; - - private String url; - - private String protocol; - - private String visualRange; - - private List nodes = new ArrayList(); - - public String getServiceName() { - return serviceName; - } - - public void setServiceName(String serviceName) { - this.serviceName = serviceName; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getProtocol() { - return protocol; - } - - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - public String getVisualRange() { - return visualRange; - } - - public void setVisualRange(String visualRange) { - this.visualRange = visualRange; - } - - public List getNodes() { - return nodes; - } - - public void setNodes(List nodes) { - this.nodes = nodes; - } - - - - public void setSingleNode(String ip, String port, int ttl) { - ServiceNode node = new ServiceNode(); - if(ip != null && ip.length() > 0) { - node.setIp(ip); - } else { - node.setIp(null); - } - node.setPort(port); - node.setTtl(ttl); - nodes.add(node); - } - -} diff --git a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/msb/MicroserviceBusConsumer.java b/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/msb/MicroserviceBusConsumer.java deleted file mode 100644 index 7c74545..0000000 --- a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/msb/MicroserviceBusConsumer.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * 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.vnfsdk.functest.externalservice.msb; - -import javax.ws.rs.ProcessingException; - -import org.glassfish.jersey.client.ClientConfig; -import org.openo.vnfsdk.functest.common.Config; -import org.openo.vnfsdk.functest.externalservice.entity.ServiceRegisterEntity; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.eclipsesource.jaxrs.consumer.ConsumerFactory; - -public class MicroserviceBusConsumer { - - private static final Logger LOG = LoggerFactory.getLogger(MicroserviceBusConsumer.class); - - private MicroserviceBusConsumer() { - - } - - public static boolean registerService(ServiceRegisterEntity entity) { - ClientConfig config = new ClientConfig(); - try { - MicroserviceBusRest resourceserviceproxy = ConsumerFactory - .createConsumer(Config.getConfigration().getMsbServerAddr(), config, MicroserviceBusRest.class); - resourceserviceproxy.registerService("false", entity); - } catch(ProcessingException error) { - LOG.error("Microservice register failed!", error); - return false; - } - return true; - } -} diff --git a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/msb/MicroserviceBusRest.java b/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/msb/MicroserviceBusRest.java deleted file mode 100644 index 1433605..0000000 --- a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/externalservice/msb/MicroserviceBusRest.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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.vnfsdk.functest.externalservice.msb; - -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; - -import org.openo.vnfsdk.functest.externalservice.entity.ServiceRegisterEntity; - -@Path("/openoapi/microservices/v1/services") -public interface MicroserviceBusRest { - - @Path("") - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public ServiceRegisterEntity registerService(@QueryParam("createOrUpdate") String createOrUpdate, - ServiceRegisterEntity entity); -} diff --git a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/resource/CommonManager.java b/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/resource/CommonManager.java deleted file mode 100644 index 937073b..0000000 --- a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/resource/CommonManager.java +++ /dev/null @@ -1,341 +0,0 @@ -/* - * 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.vnfsdk.functest.resource; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URL; -import java.util.List; -import java.util.StringTokenizer; -import java.util.UUID; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.eclipse.jetty.http.HttpStatus; -import org.openo.vnfsdk.functest.FileUtil; -import org.openo.vnfsdk.functest.TaskExecution; -import org.openo.vnfsdk.functest.constants.ApplicationConstants; -import org.openo.vnfsdk.functest.externalservice.entity.Environment; -import org.openo.vnfsdk.functest.externalservice.entity.EnvironmentMap; -import org.openo.vnfsdk.functest.externalservice.entity.OperationStatusHandler; -import org.openo.vnfsdk.functest.responsehandler.VnfFuncTestResponseHandler; -import org.openo.vnfsdk.functest.util.RestResponseUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.codahale.metrics.annotation.Timed; -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - -@Path("/functest") -@Api(tags = {" function test Management "}) -public class CommonManager { - - private static final Logger LOGGER = LoggerFactory.getLogger(CommonManager.class); - - @POST - @Path("/setenv") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @Timed - public Response setEnvironment(String env) { - LOGGER.info("set Environment"); - - try { - - // Generate UUID for each environment - final UUID uniqueKey = UUID.randomUUID(); - - // Convert input string to Environment class - ObjectMapper mapper = new ObjectMapper(); - Environment envObj = mapper.readValue(env, Environment.class); - if(null == envObj) { - // Converting input to Env object failed - return null; - } - - // Set to the environment map - EnvironmentMap.getInstance().addEnv(uniqueKey, envObj); - - // Send REST response - return RestResponseUtil.getSuccessResponse(uniqueKey); - - } catch(Exception e) { - LOGGER.error("Setting the Environment Fail", e); - } - - return null; - } - - @Path("/upload/{functestEnvId}") - @POST - @ApiOperation(value = "upload the function test") - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", response = String.class), - @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "internal server error", response = String.class)}) - @Timed - public Response uploadFuncTestPackage(@PathParam("functestEnvId") String functestEnvId, - @HeaderParam("URL") String url) { - LOGGER.info("Upload function test package"); - - try { - URL oracle = new URL(url); - - InputStream fis = new BufferedInputStream(oracle.openStream()); - - // Convert the stream to script folder - String nl = File.separator; - String filePath = storeChunkFileInLocal("temp", "TempFile.zip", fis); - - // Unzip the folder - String tempDir = System.getProperty("user.dir") + nl + "temp"; - List list = FileUtil.unzip(filePath, tempDir); - LOGGER.info("File path=" + filePath); - - String[] directories = FileUtil.getDirectory(tempDir); - if(null != directories) { - filePath = tempDir + File.separator + directories[0]; - } - - // convert uuid string to UUID - final UUID uuidEnv = UUID.fromString(functestEnvId); - // generate UUID for the upload - final UUID uuidUpload = UUID.randomUUID(); - - final String finalPath = filePath; - ExecutorService es = Executors.newFixedThreadPool(3); - es.submit(new Callable() { - - @Override - public Integer call() throws Exception { - - new TaskExecution().uploadScript(finalPath, uuidEnv, uuidUpload); - return 0; - } - }); - - // Send REST response - return RestResponseUtil.getSuccessResponse(uuidUpload); - - } catch(IOException e) { - LOGGER.error(ApplicationConstants.RUN_SCRIPT_EXECUTE_CMD, e); - } - - return null; - } - - @Path("/{uploadUUID}/{envUUID}/{frameworktype}") - @POST - @ApiOperation(value = "execute the function test") - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", response = String.class), - @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "internal server error", response = String.class)}) - @Timed - public Response executeFunctionTest(@PathParam("envUUID") String functestEnvId, - @PathParam("uploadUUID") String uploadId, @PathParam("frameworktype") String frameworktype) { - LOGGER.info("Execute function test"); - - try { - - final UUID envUUID = UUID.fromString(functestEnvId); - - // generate UUID for execute - final UUID executeUUID = UUID.randomUUID(); - - ExecutorService es = Executors.newFixedThreadPool(3); - es.submit(new Callable() { - - @Override - public Integer call() throws Exception { - - new TaskExecution().executeRobotScript(envUUID, executeUUID); - return 0; - } - }); - - // Send REST response - return RestResponseUtil.getSuccessResponse(executeUUID); - - } catch(Exception e) { - LOGGER.error(ApplicationConstants.RUN_SCRIPT_EXECUTE_CMD, e); - } - - return null; - } - - @Path("") - @POST - @ApiOperation(value = "execute the function test") - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", response = String.class), - @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "internal server error", response = String.class)}) - @Timed - public Response executeFuncTest(InputStream csarInputStream) { - LOGGER.info("execute function test"); - - try { - - // Upload the script and execute the script and run command - final UUID uniqueKey = UUID.randomUUID(); - - // Convert the stream to script folder - String nl = File.separator; - String filePath = - storeChunkFileInLocal("package" + nl + uniqueKey.toString(), "TempFile.rar", csarInputStream); - - // Unzip the folder - String tempDir = System.getProperty("user.dir") + nl + "package" + nl + uniqueKey + nl + "temp"; - FileUtil.unzip(filePath, tempDir); - LOGGER.info("File path=" + filePath); - - filePath = tempDir + File.separator + "RobotScript"; - if(!FileUtil.checkFileExist(filePath)) { - return RestResponseUtil.getErrorResponse(null); - } - - final String finalPath = filePath; - ExecutorService es = Executors.newFixedThreadPool(3); - es.submit(new Callable() { - - public Integer call() throws Exception { - - new TaskExecution().executeScript(finalPath, uniqueKey); - return 0; - } - }); - - // Send REST response - return RestResponseUtil.getSuccessResponse(uniqueKey.toString()); - - } catch(IOException e) { - LOGGER.error(ApplicationConstants.RUN_SCRIPT_EXECUTE_CMD, e); - } - - return null; - } - - @Path("/{functestId}") - @GET - @ApiOperation(value = "get function test result by id") - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", response = String.class), - @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "internal server error", response = String.class)}) - @Timed - public Response queryResultByFuncTest(@ApiParam(value = "functestId") @PathParam("functestId") String instanceId) { - LOGGER.info("query functest result by id." + instanceId); - // Query VNF Function test result by function test ID - return VnfFuncTestResponseHandler.getInstance().getResponseByFuncTestId(instanceId); - } - - @Path("/status/{operationId}") - @GET - @ApiOperation(value = "get function test result by id") - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", response = String.class), - @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "internal server error", response = String.class)}) - @Timed - public Response getOperationResult(@ApiParam(value = "operationId") @PathParam("operationId") String operationId) { - LOGGER.info("Query functest status by id." + operationId); - - return OperationStatusHandler.getInstance().getOperationStatus(UUID.fromString(operationId)); - } - - @Path("/download/{functestId}") - @GET - @ApiOperation(value = "get function test result by id") - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", response = String.class), - @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "internal server error", response = String.class)}) - @Timed - public Response downloadResults(@ApiParam(value = "functestId") @PathParam("functestId") String funcTestId) { - LOGGER.info("query functest result by id." + funcTestId); - return VnfFuncTestResponseHandler.getInstance().downloadResults(funcTestId); - } - - /** - * Convert the stream to File Name
- * - * @param dirName - Directory name - * @param fileName - FileName - * @param uploadedInputStream - Input Stream - * @return - File Path - * @throws IOException - Exception while writing file - * @since VNFSDK - */ - public String storeChunkFileInLocal(String dirName, String fileName, InputStream uploadedInputStream) - throws IOException { - File tmpDir = new File(dirName); - LOGGER.info("tmpdir=" + dirName); - if(!tmpDir.exists()) { - tmpDir.mkdirs(); - } - StringTokenizer st = new StringTokenizer(fileName, "/"); - String actualFile = null; - while(st.hasMoreTokens()) { - actualFile = st.nextToken(); - } - File file = new File(tmpDir + File.separator + actualFile); - OutputStream os = null; - try { - int read = 0; - byte[] bytes = new byte[1024]; - os = new FileOutputStream(file, true); - while((read = uploadedInputStream.read(bytes)) != -1) { - os.write(bytes, 0, read); - } - os.flush(); - return file.getAbsolutePath(); - } finally { - if(os != null) { - os.close(); - } - } - } - -} diff --git a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/responsehandler/TestResult.java b/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/responsehandler/TestResult.java deleted file mode 100644 index 4704717..0000000 --- a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/responsehandler/TestResult.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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.vnfsdk.functest.responsehandler; - -/** - * @author Administrator - */ -public class TestResult { - - private String name; - - private String description; - - private String status; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - -} diff --git a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/responsehandler/TestResultParser.java b/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/responsehandler/TestResultParser.java deleted file mode 100644 index 7de2461..0000000 --- a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/responsehandler/TestResultParser.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * 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.vnfsdk.functest.responsehandler; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.openo.vnfsdk.functest.FileUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -public class TestResultParser { - - private static final String STATUSPASS = "PASS"; - - private static final String RESULTTAG = "test"; - - private static final String NAMETAG = "name"; - - private static final String STATUSTAG = "status"; - - private static final String KWTAG = "kw"; - - private static final String DOCTAG = "doc"; - - private static final Logger logger = LoggerFactory.getLogger(TestResultParser.class); - - public List populateResultList(String xmlFile) { - List resultData = new ArrayList<>(); - if(!FileUtil.checkFileExist(xmlFile)) { - logger.error("File Not Found !!! :" + xmlFile); - return resultData; - } - parseResultData(xmlFile, resultData); - return resultData; - } - - private void parseResultData(String xmlFile, List resultData) { - try { - Document doc = createDocument(xmlFile); - NodeList list = doc.getElementsByTagName(RESULTTAG); - for(int i = 0; i < list.getLength(); i++) { - Node node = list.item(i); - if(node.getNodeType() != Node.ELEMENT_NODE) { - continue; - } - - NamedNodeMap attr = node.getAttributes(); - if(null == attr) { - continue; - } - - String nameAttr = getNodeValue(attr.getNamedItem(NAMETAG)); - if(null == nameAttr) { - continue; - } - - String descriptionAttr = nameAttr; - String statusAttr = STATUSPASS; - NodeList childlist = node.getChildNodes(); - for(int j = 0; j < childlist.getLength(); j++) { - Node childNode = childlist.item(j); - if(childNode.getNodeType() != Node.ELEMENT_NODE) { - continue; - } - - if(KWTAG == childNode.getNodeName()) { - NodeList kwNodeList = childNode.getChildNodes(); - for(int k = 0; k < kwNodeList.getLength(); k++) { - Node descNode = kwNodeList.item(k); - if(descNode.getNodeType() != Node.ELEMENT_NODE) { - continue; - } - - if(DOCTAG == descNode.getNodeName()) { - if(null != descNode.getTextContent()) { - descriptionAttr = descNode.getTextContent(); - break; - } - } - } - } - - if(STATUSTAG == childNode.getNodeName()) { - NamedNodeMap statusAttrMap = childNode.getAttributes(); - if(null != statusAttrMap) { - statusAttr = getNodeValue(statusAttrMap.getNamedItem(STATUSTAG)); - } - } - } - - TestResult testData = new TestResult(); - testData.setName(nameAttr); - testData.setDescription(descriptionAttr); - testData.setStatus(statusAttr); - - resultData.add(testData); - } - } catch(ParserConfigurationException | SAXException | IOException e) { - logger.error("Exception while parsing file :" + xmlFile); - logger.error("Exception while parsing file :", e); - } - } - - private Document createDocument(String fileName) throws ParserConfigurationException, SAXException, IOException { - InputStream inputStream = new FileInputStream(fileName); - DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); - Document doc = docBuilder.parse(inputStream); - doc.getDocumentElement().normalize(); - return doc; - } - - private String getNodeValue(Node namedItem) { - return (null != namedItem) ? namedItem.getNodeValue() : null; - } -} diff --git a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/responsehandler/VnfFuncTestResponseHandler.java b/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/responsehandler/VnfFuncTestResponseHandler.java deleted file mode 100644 index 7dd47d7..0000000 --- a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/responsehandler/VnfFuncTestResponseHandler.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * 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.vnfsdk.functest.responsehandler; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.List; -import java.util.Map; - -import javax.ws.rs.core.Response; - -import org.openo.vnfsdk.functest.FileUtil; -import org.openo.vnfsdk.functest.util.RestResponseUtil; -import org.openo.vnfsdk.functest.util.ZipCompressor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.databind.ObjectMapper; - -public class VnfFuncTestResponseHandler { - - private static int actioninProgress = 21; - - private static int error = 22; - - private static String resultFileName = "output.xml"; - - private static String resultpathkey = "DIR_RESULT"; - - private static Map mapConfigValues; - - private static VnfFuncTestResponseHandler vnfFuncRspHandler; - - private static final Logger logger = LoggerFactory.getLogger(VnfFuncTestResponseHandler.class); - - private VnfFuncTestResponseHandler() { - } - - public static VnfFuncTestResponseHandler getInstance() { - if(vnfFuncRspHandler == null) { - vnfFuncRspHandler = new VnfFuncTestResponseHandler(); - loadConfigurations(); - } - return vnfFuncRspHandler; - } - - public static void setConfigMap(Map inMapConfigValues) { - mapConfigValues = inMapConfigValues; - } - - public Response getResponseByFuncTestId(String funcTestId) { - - if((null == mapConfigValues) || (null == mapConfigValues.get(resultpathkey))) { - logger.warn("Result Store path not configfured !!!"); - return RestResponseUtil.getErrorResponse(error); - } - - String resultPath = mapConfigValues.get(resultpathkey); - - /* - * Check whether file Exists for the Request received !!! - * ----------------------------------------------------- - */ - String fileName = resultPath + File.separator + funcTestId; - if(!FileUtil.checkFileExist(fileName)) { - logger.warn("Resquested function Test result not avaliable/In-Progress !!!"); - return RestResponseUtil.getErrorResponse(actioninProgress); - } - - String zipFileName = fileName + ".zip"; - try { - new ZipCompressor(zipFileName).compress(fileName); - } catch(IOException e) { - logger.error("getResponseByFuncTestId ", e); - } - - /* - * Convert Zip-file byteCode and to response !!! - * ----------------------------------------------------- - */ - byte[] byteArrayFile = FileUtil.convertZipFiletoByteArray(zipFileName); - - if(null != byteArrayFile) { - - /* - * Delete Result folders present if Success !!! - * ---------------------------------------------- - */ - FileUtil.deleteFile(zipFileName); - /* - * Later will delete this file - */ - logger.warn("Resquested function Test result Sucess !!!"); - return RestResponseUtil.getSuccessResponse(byteArrayFile); - } else { - logger.warn("Resquested function Test result Faiuled !!!"); - return RestResponseUtil.getErrorResponse(error); - } - } - - public Response downloadResults(String funcTestId) { - - if((null == mapConfigValues) || (null == mapConfigValues.get(resultpathkey))) { - logger.warn("Result Store path not configfured !!!"); - return RestResponseUtil.getErrorResponse(error); - } - - String resultPath = mapConfigValues.get(resultpathkey); - String resultfileName = resultPath + File.separator + funcTestId + File.separator + resultFileName; - - TestResultParser oTestResultParser = new TestResultParser(); - List resultList = oTestResultParser.populateResultList(resultfileName); - return (!resultList.isEmpty()) ? RestResponseUtil.getSuccessResponse(resultList) - : RestResponseUtil.getErrorResponse(error); - } - - @SuppressWarnings("unchecked") - private static void loadConfigurations() { - String curDir = System.getProperty("user.dir"); - String confDir = curDir + File.separator + "conf" + File.separator + "robot" + File.separator; - ObjectMapper mapper = new ObjectMapper(); - try { - mapConfigValues = mapper.readValue(new FileInputStream(confDir + "robotMetaData.json"), Map.class); - } catch(IOException e) { - logger.error("Reading Json Meta data file failed or file do not exist", e); - return; - } - } -} diff --git a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/util/GsonUtil.java b/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/util/GsonUtil.java deleted file mode 100644 index 78936da..0000000 --- a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/util/GsonUtil.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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.vnfsdk.functest.util; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.UUID; - -import com.google.gson.Gson; - -public class GsonUtil { - - private GsonUtil() { - - } - - public static String generateId() { - return UUID.randomUUID().toString(); - } - - public static boolean isNotEmpty(String str) { - return str != null && !"".equals(str) && str.length() > 0; - } - - /** - * change object to str. - */ - public static String objectToString(Object obj) { - Gson gson = new Gson(); - if(obj != null) { - return gson.toJson(obj); - } else { - return null; - } - } - - public static String getNowTime() { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - return sdf.format(new Date()); - } -} diff --git a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/util/RestResponseUtil.java b/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/util/RestResponseUtil.java deleted file mode 100644 index 1c5404f..0000000 --- a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/util/RestResponseUtil.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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.vnfsdk.functest.util; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; - -public class RestResponseUtil { - - private RestResponseUtil() { - } - - public static Response getSuccessResponse(Object obj) { - if(obj != null) { - return Response.ok(GsonUtil.objectToString(obj)).build(); - } else { - return Response.ok().build(); - } - } - - public static Response getCreateSussceeResponse(Object obj) { - return Response.status(Status.CREATED).entity(obj).build(); - } - - public static Response getErrorResponse(Object obj) { - if(obj != null) { - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(GsonUtil.objectToString(obj)).build(); - } else { - return Response.serverError().build(); - } - - } -} diff --git a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/util/ZipCompressor.java b/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/util/ZipCompressor.java deleted file mode 100644 index 94773b3..0000000 --- a/vnf-sdk-function-test/src/main/java/org/openo/vnfsdk/functest/util/ZipCompressor.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * 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.vnfsdk.functest.util; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.zip.CRC32; -import java.util.zip.CheckedOutputStream; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ZipCompressor { - - public static final Logger LOG = LoggerFactory.getLogger(ZipCompressor.class); - - static final int BUFFER = 8192; - - private File zipFile; - - public ZipCompressor(String pathName) { - zipFile = new File(pathName); - } - - /** - * compress file according file path. - * - * @param srcPathName file path name - * @throws IOException - */ - public void compress(String srcPathName) throws IOException { - File file = new File(srcPathName); - if(!file.exists()) { - throw new FileNotFoundException(srcPathName + "not exist!"); - } - try { - FileOutputStream fileOutputStream = new FileOutputStream(zipFile); - CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, new CRC32()); - ZipOutputStream out = new ZipOutputStream(cos); - String basedir = ""; - compress(file, out, basedir); - out.close(); - } catch(Exception e1) { - throw new IOException(e1); - } - } - - private void compress(File file, ZipOutputStream out, String basedir) { - if(file.isDirectory()) { - LOG.info("compress: " + basedir + file.getName()); - this.compressDirectory(file, out, basedir); - } else { - LOG.info("compress: " + basedir + file.getName()); - this.compressFile(file, out, basedir); - } - } - - private void compressDirectory(File dir, ZipOutputStream out, String basedir) { - if(!dir.exists()) { - return; - } - - File[] files = dir.listFiles(); - for(int i = 0; i < files.length; i++) { - compress(files[i], out, basedir + dir.getName() + "/"); - } - } - - private void compressFile(File file, ZipOutputStream out, String basedir) { - if(!file.exists()) { - return; - } - try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) { - - byte[] data = new byte[BUFFER]; - - ZipEntry entry = new ZipEntry(basedir + file.getName()); - out.putNextEntry(entry); - int count; - while((count = bis.read(data, 0, BUFFER)) != -1) { - out.write(data, 0, count); - } - bis.close(); - } catch(IOException e) { - LOG.info("Exception wile compress file" + file.getAbsolutePath(), e); - } - } -} diff --git a/vnf-sdk-function-test/src/main/resources/migrations.xml b/vnf-sdk-function-test/src/main/resources/migrations.xml new file mode 100644 index 0000000..9ec5510 --- /dev/null +++ b/vnf-sdk-function-test/src/main/resources/migrations.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vnf-sdk-function-test/src/main/resources/sample.xml b/vnf-sdk-function-test/src/main/resources/sample.xml new file mode 100644 index 0000000..db1d2f0 --- /dev/null +++ b/vnf-sdk-function-test/src/main/resources/sample.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file -- cgit 1.2.3-korg