diff options
Diffstat (limited to 'juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo')
66 files changed, 12093 insertions, 0 deletions
diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/AsyncCallback.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/AsyncCallback.java new file mode 100644 index 0000000..2369d18 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/AsyncCallback.java @@ -0,0 +1,46 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common; + +import org.openo.baseservice.roa.util.restclient.RestfulAsyncCallback; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + * Async Callback class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public class AsyncCallback implements RestfulAsyncCallback { + + private static final Logger LOGGER = LoggerFactory.getLogger(AsyncCallback.class); + + @Override + public void callback(RestfulResponse response) { + LOGGER.warn("function=callback, msg=status={}, content={}.", response.getStatus(), response.getResponseContent()); + } + + @Override + public void handleExcepion(Throwable e) { + LOGGER.error("function=callback, msg= e is {}.", e); + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/BaseTimeJob.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/BaseTimeJob.java new file mode 100644 index 0000000..1698702 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/BaseTimeJob.java @@ -0,0 +1,85 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.nfvo.jujuvnfmadapter.common; + +import java.util.Calendar; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * + * Base time job class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public abstract class BaseTimeJob implements Runnable { + + private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); + + private long initialDelay = 1; + + private long period = 1; + + private String startTime = ""; + + @Override + public abstract void run(); + + /** + * + * Stop method.<br> + * + * @since NFVO 0.5 + */ + public void stop() { + service.shutdown(); + } + + public void setInitialDelay(long initialDelay) { + this.initialDelay = initialDelay; + } + + public void setPeriod(long period) { + this.period = period; + } + + /** + * + * Start method.<br> + * + * @since NFVO 0.5 + */ + public void start() { + if(startTime.length() != 0) { + String[] vnfTime = startTime.split(":"); + if(vnfTime.length == 2) { + int minute = Integer.parseInt(vnfTime[0]) * 60 + Integer.parseInt(vnfTime[1]); + Calendar calendar = Calendar.getInstance(); + int curMinute = calendar.get(Calendar.HOUR_OF_DAY) * 60 + calendar.get(Calendar.MINUTE); + if(curMinute <= minute) { + initialDelay = (minute - curMinute) * 60L; + } else { + initialDelay = (minute + 24 * 60 - curMinute) * 60L; + } + } + } + service.scheduleAtFixedRate(this, initialDelay, period, TimeUnit.SECONDS); + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/CryptUtil.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/CryptUtil.java new file mode 100644 index 0000000..9582f52 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/CryptUtil.java @@ -0,0 +1,63 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common; + +/** + * + * Cryptographic utility class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public final class CryptUtil { + + /** + * Constructor<br/> + * <p> + * </p> + * + */ + private CryptUtil() { + //Empty Constructor + } + + /** + * + * Decription.<br> + * + * @param pwd + * @return + * @since NFVO 0.5 + */ + public static String deCrypt(String pwd) { + return pwd; + } + + /** + * + * Encryption.<br> + * + * @param pwd + * @return + * @since NFVO 0.5 + */ + public static String enCrypt(String pwd) { + return pwd; + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/DownloadCsarManager.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/DownloadCsarManager.java new file mode 100644 index 0000000..dd21809 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/DownloadCsarManager.java @@ -0,0 +1,240 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Enumeration; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import org.apache.http.Header; +import org.apache.http.HeaderElement; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; + +/** + * Utility class to download CSAR + * + * @author + * @version NFVO 0.5 Sep 5, 2016 + * + */ +public class DownloadCsarManager { + + private static final Logger LOG = LoggerFactory.getLogger(DownloadCsarManager.class); + + public static final int CACHE = 100 * 1024; + + private DownloadCsarManager(){ + //private constructor + } + + /** + * Download from given URL. + * @param url String + * @return + */ + public static String download(String url) { + return download(url, null); + } + + /** + * Download from given URL to given file location. + * @param url String + * @param filepath String + * @return + */ + public static String download(String url, String filepath) { + String status = ""; + try { + CloseableHttpClient client = HttpClients.createDefault(); + HttpGet httpget = new HttpGet(url); + CloseableHttpResponse response = client.execute(httpget); + + HttpEntity entity = response.getEntity(); + InputStream is = entity.getContent(); + if (filepath == null){ + filepath = getFilePath(response); //NOSONAR + } + + File file = new File(filepath); + file.getParentFile().mkdirs(); + FileOutputStream fileout = new FileOutputStream(file); + + byte[] buffer = new byte[CACHE]; + int ch; + while ((ch = is.read(buffer)) != -1) { + fileout.write(buffer,0,ch); + } + is.close(); + fileout.flush(); + fileout.close(); + status = Constant.DOWNLOADCSAR_SUCCESS; + + } catch (Exception e) { + status = Constant.DOWNLOADCSAR_FAIL; + LOG.error("Download csar file failed! "+ e.getMessage(), e); + } + return status; + } + + /** + * Retrieve file path from given response. + * @param response HttpResponse + * @return + */ + public static String getFilePath(HttpResponse response) { + String filepath = System.getProperty("java.home"); + String filename = getFileName(response); + + if (filename != null) { + filepath += filename; + } else { + filepath += getRandomFileName(); + } + return filepath; + } + + /** + * Retrieve file name from given response. + * @param response HttpResponse + * @return + */ + public static String getFileName(HttpResponse response) { + Header contentHeader = response.getFirstHeader("Content-Disposition"); + String filename = null; + if (contentHeader != null) { + HeaderElement[] values = contentHeader.getElements(); + if (values.length == 1) { + NameValuePair param = values[0].getParameterByName("filename"); + if (param != null) { + try { + filename = param.getValue(); + } catch (Exception e) { + LOG.error("getting filename failed! "+ e.getMessage(), e); + } + } + } + } + return filename; + } + + /** + * Provides random file name. + * @return + */ + public static String getRandomFileName() { + return String.valueOf(System.currentTimeMillis()); + } + + /** + * unzip CSAR packge + * @param fileName filePath + * @return + */ + public static int unzipCSAR(String fileName,String filePath){ + final int BUFFER = 2048; + int status=0; + + try { + ZipFile zipFile = new ZipFile(fileName); + Enumeration emu = zipFile.entries(); + int i=0; + while(emu.hasMoreElements()){ + ZipEntry entry = (ZipEntry)emu.nextElement(); + //read directory as file first,so only need to create directory + if (entry.isDirectory()) + { + new File(filePath + entry.getName()).mkdirs(); + continue; + } + BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); + File file = new File(filePath + entry.getName()); + //Because that is random to read zipfile,maybe the file is read first + //before the directory is read,so we need to create directory first. + File parent = file.getParentFile(); + if(parent != null && (!parent.exists())){ + parent.mkdirs(); + } + FileOutputStream fos = new FileOutputStream(file); + BufferedOutputStream bos = new BufferedOutputStream(fos,BUFFER); + + int count; + byte data[] = new byte[BUFFER]; + while ((count = bis.read(data, 0, BUFFER)) != -1) + { + bos.write(data, 0, count); + } + bos.flush(); + bos.close(); + bis.close(); + + if(entry.getName().endsWith(".zip")){ + File subFile = new File(filePath+entry.getName()); + if(subFile.exists()){ + int subStatus = unzipCSAR(filePath+entry.getName(),subFile.getParent()+"/"); + if(subStatus != 0){ + LOG.error("sub file unzip fail!"+subFile.getName()); + status=Constant.UNZIP_FAIL; + return status; + } + } + } + } + status=Constant.UNZIP_SUCCESS; + zipFile.close(); + } catch (Exception e) { + status=Constant.UNZIP_FAIL; + e.printStackTrace(); + } + return status; + } + + private static String getImagesPath(String csarfilepath){ + File imageFile = new File(csarfilepath+"SoftwareImages"); + if(imageFile.exists()){ + File[] charmFiles = imageFile.listFiles(); + for(File file : charmFiles){ + if(!file.getName().endsWith(".zip")){ + return file.getAbsolutePath(); + } + } + } + return csarfilepath; + } + public static void main(String[] args) { + System.out.println(getImagesPath("e:/juju/csar2/")); + } +}
\ No newline at end of file diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/EntityUtils.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/EntityUtils.java new file mode 100644 index 0000000..9899c34 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/EntityUtils.java @@ -0,0 +1,297 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common; + +import java.io.File; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeoutException; + +import org.apache.commons.lang3.StringUtils; +import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 30, 2016 + */ +public class EntityUtils { + + private static final Logger LOG = LoggerFactory.getLogger(EntityUtils.class); + + public static final String RESULT_CODE_KEY = "retCode"; + + public static final String MSG_KEY = "msg"; + + public static final String DATA_KEY = "data"; + + public static final String STATUS = "status"; + + /** + * Constructor<br/> + * <p> + * </p> + */ + private EntityUtils() { + // Empty Constructor + } + + /** + * <br> + * + * @param jsonObject + * @param clazz + * @return T + * @throws Exception + */ + @SuppressWarnings("unchecked") + public static <T> T toEntity(JSONObject jsonObject, Class<?> clazz) throws Exception { // NOSONAR + T instance = (T)clazz.newInstance(); + Field[] fields = clazz.getDeclaredFields(); + for(int i = 0; i < fields.length; i++) { + fields[i].setAccessible(true); + fields[i].set(instance, jsonObject.get(fields[i].getName())); + } + return instance; + } + + /** + * format the obj to str style as json format. + * <br/> + * + * @param obj + * @param clazz + * @return + * @since NFVO 0.5 + */ + public static String toString(Object obj, Class<?> clazz) { + JSONObject jsonObj = new JSONObject(); + try { + Field[] fields = clazz.getDeclaredFields(); + for(int i = 0; i < fields.length; i++) { + fields[i].setAccessible(true); + jsonObj.put(fields[i].getName(), obj != null ? fields[i].get(obj) : ""); + } + } catch(Exception e) { + LOG.error("to string error:", e); + } + return jsonObj.toString(); + } + + /** + * <br> + * <p> + * </p> + * + * @author + */ + public static class ExeRes { + + public static final int SUCCESS = 0; + + public static final int FAILURE = -1; + + private int code; + + private String body; + + /** + * @return Returns the code. + */ + public int getCode() { + return code; + } + + /** + * @param code The code to set. + */ + public void setCode(int code) { + this.code = code; + } + + /** + * @return Returns the body. + */ + public String getBody() { + return body; + } + + /** + * @param body The body to set. + */ + public void setBody(String body) { + this.body = body; + } + + @Override + public String toString() { + try { + return EntityUtils.toString(this, this.getClass()); + } catch(Exception e) { + LOG.error("to string error:", e); + return "code:" + this.getCode() + ",body:" + this.getBody(); + } + } + + } + + /** + * <br> + * + * @param command + * @return String + */ + public static String formatCommand(List<String> command) { + StringBuilder builder = new StringBuilder(); + if(command != null) { + for(String cmd : command) { + builder.append(cmd).append(" "); // NOSONAR + } + } + return builder.toString(); + + } + + /** + * <br> + * + * @param dir + * @param command + * @return + */ + public static ExeRes execute(String dir, String... command) { + List<String> commands = new ArrayList<>(command.length); + for(String arg : command) { + commands.add(arg); + } + return execute(dir, commands); + + } + + /** + * execute local command + * <br/> + * + * @param dir the command path + * @param command + * @return response msg + * @since NFVO 0.5 + */ + public static ExeRes execute(String dir, List<String> command) { + ExeRes er = new ExeRes(); + StringBuilder sb = new StringBuilder(); + try { + if(SwitchController.isDebugModel()) { + String resContent = new String(FileUtils.readFile(new File(JujuConfigUtil.getValue("juju_cmd_res_file")), "UTF-8")); + er.setBody(resContent); + return er; + } + ProcessBuilder pb = new ProcessBuilder(command); + if(StringUtils.isNotBlank(dir)) { + pb.directory(new File(dir)); + } + pb.redirectErrorStream(true); + Process p = pb.start(); + + // wait the process result + buildProcessResult(er, p); + + InputStream in = p.getInputStream(); + byte[] buffer = new byte[1024]; + int length; + while((length = in.read(buffer)) > 0) { + sb.append(new String(buffer, 0, length)); + } + in.close(); + er.setBody(sb.toString()); + } catch(Exception e) { + er.setCode(ExeRes.FAILURE); + er.setBody(e.getMessage()); + LOG.error("execute the command failed:{}", command, e); + } + return er; + } + + /** + * <br/> + * + * @param er + * @param p + * @throws TimeoutException + * @throws InterruptedException + * @since NFVO 0.5 + */ + private static void buildProcessResult(ExeRes er, Process p) throws TimeoutException, InterruptedException { + Worker worker = new Worker(p); + worker.start(); + try { + worker.join(Constant.PROCESS_WAIT_MILLIS); + if(worker.exitValue != null) { + int exit = worker.exitValue; + if(exit != 0) { + er.setCode(ExeRes.FAILURE); + LOG.warn("the process exit non-normal"); + } else { + er.setCode(ExeRes.SUCCESS); + } + } else { + er.setCode(ExeRes.FAILURE); + LOG.warn("the process execute timeout."); + throw new TimeoutException(); + } + } catch(InterruptedException e) { + worker.interrupt(); + Thread.currentThread().interrupt(); + throw e; + } + } + + private static class Worker extends Thread { + + private final Process process; + + private Integer exitValue; + + private Worker(Process process) { + this.process = process; + } + + /** + * <br/> + * + * @since NFVO 0.5 + */ + @Override + public void run() { + try { + exitValue = process.waitFor(); + } catch(InterruptedException e) { + return; + } + } + + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/FileUtils.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/FileUtils.java new file mode 100644 index 0000000..cb68a5b --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/FileUtils.java @@ -0,0 +1,501 @@ +/* + * Copyright (c) 2016, Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * FileUtils + * <br/> + * <p> + * </p> + * + * @author quanzhong@huawei.com + * @version NFVO 0.5 Sep 23, 2016 + */ +public class FileUtils { + + public static final String UTF8 = "UTF-8"; + + public static final String GBK = "GBK"; + + private static Logger log = LoggerFactory.getLogger(FileUtils.class); + + private FileUtils(){ + + } + /** + * get current classPath as str. and the trailing slash will be remove + * <br/> + * + * @return + * @since NFVO 0.5 + */ + public static String getClassPath(){ + String path = ClassLoader.getSystemClassLoader().getResource("./").getPath(); + if(path.endsWith("/")){ + path = path.substring(0, path.length()-1); + } + return path; + } + /** + * read data from the file + * <br/> + * + * @param file + * @param charsetName + * @return + * @throws IOException + * @since NFVO 0.5 + */ + public static byte[] readFile(File file, String charsetName) throws IOException { + if(file != null) { + FileReader reader = new FileReader(file); + StringBuilder buffer = new StringBuilder(); + char[] cbuf = new char[1024]; + int legth; + while((legth = reader.read(cbuf)) != -1) { + buffer.append(new String(cbuf, 0, legth)); + } + reader.close(); + return buffer.toString().getBytes(charsetName); + } + return new byte[]{}; + } + + /** + * write data as file to the filePath + * <br/> + * + * @param data + * @param filePath + * @return + * @since NFVO 0.5 + */ + public static int writeFile(byte[] data, String filePath) { + try { + OutputStream out = new FileOutputStream(filePath); + out.write(data, 0, data.length); + out.close(); + return 0; + } catch (Exception e) { + log.error("write file fail,filePath:"+filePath, e); + } + return -1; + } + + /** + * List all files in directory + * @param file + * @return + * @throws FileNotFoundException + */ + public static List<File> listFiles(File file) throws FileNotFoundException{ + List<File> list = new ArrayList<>(); + list(file, list); + return list; + } + /** + * List all files in directory + * @param file + * @param list + * @throws FileNotFoundException + */ + private static void list(File file, List<File> list) throws FileNotFoundException{ + if(!file.exists()){ + throw new FileNotFoundException(file.getAbsolutePath()); + } + File[] files = file.listFiles(); + if(files != null && files.length > 0 ){ + for(File f : files){ + if(f.isFile()){ + list.add(f); + }else{ + list(f, list); + } + } + } + } + + + /** + * createDirs (cycle create) + * <br/> + * + * @param file + * @since NFVO 0.5 + */ + public static void createDirs(File file){ + if(file.getParentFile().exists()){ + file.mkdir(); + }else{ + createDirs(file.getParentFile()); + file.mkdir(); + } + } + + /** + *mkDirs + * <br/> + * + * @param path + * @since NFVO 0.5 + */ + public static void mkDirs(String path){ + File file = new File(path); + createDirs(file); + } + + + + public static String getSuperUrl(String file) { + return new File(file).getParentFile().getAbsolutePath(); + + } + + /** + * absolute url + * + * @author sunny.sun + * @return file this application absolute url + */ + public static String getAppAbsoluteUrl() { + + // ��ȡ��class���ڵľ���·�� + String file = UnCompressUtil.class.getClassLoader().getResource("/") == null ? null + : UnCompressUtil.class.getClassLoader().getResource("/").toString(); + if (file == null) { + file = UnCompressUtil.class.getProtectionDomain().getCodeSource() + .getLocation().getFile().substring(1); + } + // ��class�ļ���war��ʱ������"zip:D:/ ..."����·�� + if (file.startsWith("zip")) { + file = file.substring(4); + + // ��class�ļ���class�ļ���ʱ������"file:/F:/ ..."����·�� + } else if (file.startsWith("file")) { + file = file.substring(6); + + // ��class�ļ���jar�ļ���ʱ������"jar:file:/F:/ ..."����·�� + } else if (file.startsWith("jar")) { + file = file.substring(10); + } + + if (!isWindows()) + return ("/" + file).replace("%20", " "); + + return file.replace("%20", " "); + } + + public static String getWEBClassAbsoluteUrl() { + + return getAppAbsoluteUrl(); + } + + /** + * @param floder + * @return + */ + public static File newFloder(String floder) { + File file = new File(floder); + if (!file.exists()) { + file.mkdirs(); + } + return file; + } + + + + public static void copyFile(String oldPath, String newPath, boolean flag) + throws Exception { + int byteread = 0; + File oldfile = new File(oldPath); + if (oldfile.exists()) { // �ļ�����ʱ + if (flag == false) { + delFiles(newPath); + } + if (new File(newPath).exists() && flag == true) { + return; + } + newFile(newPath); + FileInputStream fis = new FileInputStream(oldPath); // ����ԭ�ļ� + FileOutputStream fos = new FileOutputStream(newPath); + byte[] buffer = new byte[1024]; + while ((byteread = fis.read(buffer)) != -1) { + fos.write(buffer, 0, byteread); + } + fos.close(); + fis.close(); + } else { + throw new FileNotFoundException("the " + oldfile + " is not exits "); + } + + } + + /** + * @param filePathAndName + * String exp c:/fqf.txt + * @param fileContent + * String + * @return boolean + */ + public static boolean delFiles(String filePathAndName) { + + boolean flag = false; + File myDelFile = new File(filePathAndName); + if (!myDelFile.exists()) + return true; + if (myDelFile.isDirectory()) { + File[] fs = myDelFile.listFiles(); + for (int i = 0; i < fs.length; i++) { + if (fs[i].isFile()) + flag = fs[i].delete(); + if (fs[i].isDirectory()) { + flag = delFiles(fs[i].getAbsolutePath()); + flag = fs[i].delete(); + } + } + } + flag = myDelFile.delete(); + return flag; + } + + /** + * create new file + * + * @param filePathAndName + * String + * @return + * @throws IOException + */ + public static File newFile(String fileName) throws IOException { + File file = new File(fileName); + + newFloder(file.getParentFile().toString()); + + if (!file.exists()) { + file.createNewFile(); + } + return file; + } + + /** + * the file down all the hidden files + * + * @author sunny.sun + * */ + public static List<File> getFiles(String path) { + + List<File> list = new ArrayList<File>(); + File file = new File(path); + if (!file.exists()) { + + file.mkdirs(); + } + + File[] files = file.listFiles(); + for (int i = 0; i < files.length; i++) { + if (files[i].isFile() && !files[i].isHidden()) { + list.add(files[i]); + } + if (files[i].isDirectory() && !files[i].isHidden()) { + List<File> list2 = getFiles(files[i].getPath());// use myself + list.addAll(list2); + } + } + return list; + } + + /** + * causes the os of this computer is Windows + * + * @author sunny.sun + * */ + public static boolean isWindows() { + + String os = System.getProperty("os.name").toLowerCase(); + // windows + return (os.indexOf("win") >= 0); + + } + + public static void copy(String oldfile, String newfile, boolean flag) + throws Exception { + File oldf = new File(oldfile); + File newf = new File(newfile); + boolean oisd = (oldfile.endsWith("/") || oldfile.endsWith("\\")); + boolean nisd = (newfile.endsWith("/") || newfile.endsWith("\\")); + + // Դ�ļ������� + if (!oldf.exists()) { + throw new Exception("the from data is not exists "); + } + // ����ļ����У������� + if (oldf.exists() && !newf.exists()) { + if (newfile.endsWith("/") || newfile.endsWith("\\")) { + newFloder(newfile); + } else { + newFile(newfile); + } + } + // Ŀ�����ļ�����Դ���ļ��� + if (oldf.exists() && oisd && !nisd) { + throw new Exception( + "the from data is directory,but the to data is a file"); + } + // Դ�Ǹ��ļ�,Ŀ�����ļ� + if (!oisd && !nisd) { + copyFile(oldf.getAbsolutePath(), newf.getAbsolutePath(), flag); + } + // Դ�Ǹ��ļ��У�Ŀ�����ļ��� + if (oisd && nisd) { + newFloder(newf.getAbsolutePath()); + List<File> list = getFiles(oldf.getAbsolutePath()); + for (int i = 0; i < list.size(); i++) { + copyFile(list.get(i).getAbsolutePath(), newf.getAbsolutePath() + + "/" + list.get(i).getName(), flag); + } + } + // Դ�Ǹ��ļ���Ŀ���Ǹ��ļ��� + if (!oisd && nisd) { + newFloder(newf.getAbsolutePath()); + copyFile(oldf.getAbsolutePath(), newf.getAbsolutePath() + "/" + + oldf.getName(), flag); + } + + } + + /** + * causes the os of this computer is mac + * + * @author sunny.sun + * */ + public static boolean isMac() { + + String os = System.getProperty("os.name").toLowerCase(); + // Mac + return (os.indexOf("mac") >= 0); + + } + + /** + * causes the os of this computer is unix + * + * @author sunny.sun + * */ + public static boolean isUnix() { + + String os = System.getProperty("os.name").toLowerCase(); + // linux or unix + return (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0); + + } + + /** + * @param file + * @return + * @throws Exception + */ + public static boolean isUsed(String file) throws Exception { + File f = new File(file); + if (!f.exists()) { + throw new Exception("the file is not exists .."); + } + File f1 = new File(file + ".temp"); + f.renameTo(f1); + if (f.exists()) { + return true; + } else { + f1.renameTo(f); + return false; + } + + } + /** + * Remove the file name's extension (only remove the last) + * <br/> + * + * @param file + * @return + * @since NFVO 0.5 + */ + public static String getBaseFileName(File file){ + if(file.getName().lastIndexOf(".") > 0){ + return file.getName().substring(0,file.getName().lastIndexOf(".")); + }else{ + return file.getName(); + } + + } + + /** + * fix file path to linux seperate,and remove the head and end slash + * <br/> + * + * @param path + * @return + * @since NFVO 0.5 + */ + public static String fixPath(String path){ + String newPath = path; + if(path == null){ + return newPath; + } + newPath = newPath.replaceAll("\\\\", "/"); + if(newPath.startsWith("/")){ + newPath = newPath.substring(1, newPath.length()); + } + if(newPath.endsWith("/")){ + newPath = newPath.substring(0, newPath.length()-1); + } + return newPath; + } + + /** + * fix file path to linux seperate,and add the head and end slash + * <br/> + * + * @param path + * @return + * @since NFVO 0.5 + */ + public static String getFriendlyPath(String path){ + String newPath = path; + if(path == null){ + return newPath; + } + newPath = newPath.replaceAll("\\\\", "/"); + if(!newPath.startsWith("/")){ + newPath = "/"+newPath; + } + if(!newPath.endsWith("/")){ + newPath = newPath + "/"; + } + return newPath; + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/JujuConfigUtil.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/JujuConfigUtil.java new file mode 100644 index 0000000..26ef602 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/JujuConfigUtil.java @@ -0,0 +1,49 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common; + +import java.util.ResourceBundle; + +/** + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public class JujuConfigUtil { + + private static ResourceBundle bundle = ResourceBundle.getBundle("juju-config"); + + private JujuConfigUtil() { + // private constructor + } + + /** + * read the juju-config.properties file + * <br/> + * + * @param key + * @return + * @since NFVO 0.5 + */ + public static String getValue(String key){ + return bundle.getString(key); + } + +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/LocalComandUtils.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/LocalComandUtils.java new file mode 100644 index 0000000..31886e4 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/LocalComandUtils.java @@ -0,0 +1,263 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common; + +import java.io.File; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeoutException; + +import org.apache.commons.lang3.StringUtils; +import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * For execute local command + * (support control overtime) + * <br/> + * <p> + * </p> + * + * @author quanzhong@huawei.com + * @version NFVO 0.5 Sep 19, 2016 + */ +public class LocalComandUtils { + private LocalComandUtils(){ + + } + + private static final Logger log = LoggerFactory.getLogger(LocalComandUtils.class); + + + /** + * <br> + * + * @param command + * @return String + */ + public static String formatCommand(List<String> command) { + StringBuilder builder = new StringBuilder(); + if(command != null) { + for(String cmd : command) { + builder.append(cmd).append(" "); // NOSONAR + } + } + return builder.toString(); + + } + + /** + * <br> + * + * @param dir + * @param command + * @return + */ + public static ExeRes execute(String dir, String... command) { + List<String> commands = new ArrayList<>(command.length); + for(String arg : command) { + commands.add(arg); + } + return execute(dir, commands); + + } + + /** + * execute local command + * <br/> + * + * @param dir the command path + * @param command + * @param timeout millis + * @return response msg + * @since NFVO 0.5 + */ + public static ExeRes execute(String dir, List<String> command,long timeout) { + ExeRes er = new ExeRes(); + StringBuilder sb = new StringBuilder(); + try { + if(SwitchController.isDebugModel()) { + command.set(0, "juju.bat"); + } + ProcessBuilder pb = new ProcessBuilder(command); + if(StringUtils.isNotBlank(dir)) { + pb.directory(new File(dir)); + } + pb.redirectErrorStream(true); + Process p = pb.start(); + + // wait the process result + buildProcessResult(er, p, timeout); + + InputStream in = p.getInputStream(); + byte[] buffer = new byte[1024]; + int length; + while((length = in.read(buffer)) > 0) { + sb.append(new String(buffer, 0, length)); + } + in.close(); + er.setBody(sb.toString()); + } catch(Exception e) { + er.setCode(ExeRes.FAILURE); + er.setBody(e.getMessage()); + log.error("execute the command failed:{}", command, e); + } + return er; + } + + /** + * execute local command + * <br/> + * + * @param dir the command path + * @param command + * @return response msg + * @since NFVO 0.5 + */ + public static ExeRes execute(String dir, List<String> command) { + return execute(dir,command,Constant.PROCESS_WAIT_MILLIS); + } + + /** + * <br/> + * + * @param er + * @param p + * @param timeout millis + * @throws TimeoutException + * @throws InterruptedException + * @since NFVO 0.5 + */ + private static void buildProcessResult(ExeRes er, Process p,long timeout) throws TimeoutException, InterruptedException { + Worker worker = new Worker(p); + worker.start(); + try { + worker.join(timeout); + if(worker.exitValue != null) { + int exit = worker.exitValue; + if(exit != 0) { + er.setCode(ExeRes.FAILURE); + log.warn("the process exit non-normal"); + } else { + er.setCode(ExeRes.SUCCESS); + } + } else { + er.setCode(ExeRes.FAILURE); + log.warn("the process execute timeout."); + throw new TimeoutException(); + } + } catch(InterruptedException e) { + worker.interrupt(); + Thread.currentThread().interrupt(); + throw e; + } + } + + /** + * + * <br/> + * <p> + * </p> + * + * @author quanzhong@huawei.com + * @version NFVO 0.5 Sep 19, 2016 + */ + private static class Worker extends Thread { + + private final Process process; + + private Integer exitValue; + + private Worker(Process process) { + this.process = process; + } + + /** + * <br/> + * + * @since NFVO 0.5 + */ + @Override + public void run() { + try { + exitValue = process.waitFor(); + } catch(InterruptedException e) { + return; + } + } + + } + + /** + * <br> + * <p> + * </p> + * + * @author + */ + public static class ExeRes { + + public static final int SUCCESS = 0; + + public static final int FAILURE = -1; + + private int code; + + private String body; + + /** + * @return Returns the code. + */ + public int getCode() { + return code; + } + + /** + * @param code The code to set. + */ + public void setCode(int code) { + this.code = code; + } + + /** + * @return Returns the body. + */ + public String getBody() { + return body; + } + + /** + * @param body The body to set. + */ + public void setBody(String body) { + this.body = body; + } + + @Override + public String toString() { + try { + return EntityUtils.toString(this, this.getClass()); + } catch(Exception e) { + log.error("to string error:", e); + return "code:" + this.getCode() + ",body:" + this.getBody(); + } + } + + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/ResourceUtil.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/ResourceUtil.java new file mode 100644 index 0000000..ccfa31a --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/ResourceUtil.java @@ -0,0 +1,45 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common; + +/** + * + * Resource utility class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public class ResourceUtil { + + private ResourceUtil() { + + } + + /** + * + * Get message.<br> + * + * @param key + * @return + * @since NFVO 0.5 + */ + public static String getMessage(String key) { + return key; + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/SpringContextHolder.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/SpringContextHolder.java new file mode 100644 index 0000000..118f3e4 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/SpringContextHolder.java @@ -0,0 +1,107 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; + +/** + * + * Spring context holder class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public class SpringContextHolder implements ApplicationContextAware { + + private static final Logger LOG = LoggerFactory.getLogger(SpringContextHolder.class); + + private static ApplicationContext appContext; + + /** + * application context<br/> + * + * @param applicationContext + */ + @Override + public void setApplicationContext(ApplicationContext applicationContext) { + setAppContext(applicationContext); + } + + /** + * <br> + * + * @return applicationContext + */ + public static ApplicationContext getApplicationContext() { + checkApplicationContext(); + return appContext; + } + + /** + * + * Get spring bean.<br> + * + * @param name + * @return + * @since NFVO 0.5 + */ + @SuppressWarnings("unchecked") + public static <T> T getSpringBean(String name) { + checkApplicationContext(); + return (T)appContext.getBean(name); + } + + /** + * + * Get spring bean.<br> + * + * @param requiredType + * @return + * @since NFVO 0.5 + */ + @SuppressWarnings("unchecked") + public static <T> T getSpringBean(Class<T> requiredType) { + checkApplicationContext(); + return (T)appContext.getBeansOfType(requiredType); + } + + private static void checkApplicationContext() { + if(appContext == null) { + LOG.error("spring appContext do not insert."); + throw new IllegalStateException("spring appContext is null."); + } + } + + /** + * + * Clean application context.<br> + * + * @since NFVO 0.5 + */ + public static void cleanApplicationContext() { + appContext = null; + } + + private static void setAppContext(ApplicationContext applicationContext) { + SpringContextHolder.appContext = applicationContext; + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/StringUtil.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/StringUtil.java new file mode 100644 index 0000000..0e819d3 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/StringUtil.java @@ -0,0 +1,148 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common; + +import java.io.IOException; +import java.io.InputStream; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONArray; +import net.sf.json.JSONException; +import net.sf.json.JSONObject; +import net.sf.json.util.JSONTokener; + +/** + * + * String utility class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public final class StringUtil { + + private static final Logger LOG = LoggerFactory.getLogger(StringUtil.class); + + private StringUtil() { + + } + + /** + * + * Check whther the string is valid or not.<br> + * + * @param str + * @return + * @since NFVO 0.5 + */ + public static boolean isValidString(String str) { + return str != null && !"".equals(str.trim()); + } + + /** + * + * Check whether the Url is valid or not.<br> + * + * @param url + * @return + * @since NFVO 0.5 + */ + public static boolean isValidUrl(String url) { + String reg = + "http[s]?://(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)){3}:[0-9]{2,5}"; + Pattern pattern = Pattern.compile(reg); + Matcher matcher = pattern.matcher(url); + return matcher.matches(); + } + + /** + * + * Get the JSON string from input http context.<br> + * + * @param vnfReq + * @return + * @since NFVO 0.5 + */ + @SuppressWarnings("unchecked") + public static <T> T getJsonFromContexts(HttpServletRequest vnfReq) { + try { + InputStream vnfInput = vnfReq.getInputStream(); + String vnfJsonStr = IOUtils.toString(vnfInput); + JSONTokener vnfJsonTokener = new JSONTokener(vnfJsonStr); + + if(vnfJsonTokener.nextClean() == Character.codePointAt("{", 0)) { + return (T)JSONObject.fromObject(vnfJsonStr); + } + + vnfJsonTokener.back(); + + if(vnfJsonTokener.nextClean() == Character.codePointAt("[", 0)) { + return (T)JSONArray.fromObject(vnfJsonStr); + } + } catch(IOException e) { + LOG.error("function=getJsonFromContext, msg=IOException occurs, e={}.", e); + } catch(JSONException e) { + LOG.error("function=getJsonFromContext, msg=JSONException occurs, e={}.", e); + } + + return null; + } + + /** + * + * Translate sites to site array.<br> + * + * @param sites + * @return + * @since NFVO 0.5 + */ + public static JSONArray transSitesToArray(String sites) { + String[] siteList = sites.split("&"); + int siteSize = siteList.length; + JSONArray siteArray = new JSONArray(); + for(int i = 0; i < siteSize; i++) { + siteArray.add(siteList[i]); + } + + return siteArray; + } + + /** + * + * Check whether the string is valid or not.<br> + * + * @param fields + * @return + * @since NFVO 0.5 + */ + public static boolean isValidAnyString(String... fields) { + for(String str : fields) { + if(!isValidString(str)) { + return false; + } + } + return true; + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/SwitchController.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/SwitchController.java new file mode 100644 index 0000000..dbcdcf5 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/SwitchController.java @@ -0,0 +1,55 @@ +/* + * Copyright 2016-2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common; + +/** + * <br/> + * <p> + * to assist debug + * </p> + * + * @author + * @version NFVO 0.5 Sep 13, 2016 + */ +public class SwitchController { + + /** + * turn debug model + */ + private static boolean debugModel = false; + public static String vnfmServiceUrl = null; + + public SwitchController() { //NOSONAR + //Constructor + } + + /** + * @return Returns the debugModel. + */ + public static boolean isDebugModel() { + return debugModel; + } + + + /** + * @param debugModel The debugModel to set. + */ + public static void setDebugModel(boolean debugModel) { + SwitchController.debugModel = debugModel; + } + +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/UnCompressUtil.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/UnCompressUtil.java new file mode 100644 index 0000000..eda6b78 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/UnCompressUtil.java @@ -0,0 +1,301 @@ +/* + * Copyright (c) 2016, Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.zip.GZIPInputStream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +import org.apache.commons.compress.archivers.ArchiveInputStream; +import org.apache.commons.compress.archivers.ArchiveStreamFactory; +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.compressors.CompressorStreamFactory; +import org.apache.commons.compress.compressors.xz.XZCompressorInputStream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * <br/> + * <p> + * </p> + * + * @author quanzhong@huawei.com + * @version NFVO 0.5 Oct 28, 2016 + */ +public class UnCompressUtil { + + private static Logger log = LoggerFactory.getLogger(UnCompressUtil.class); + + public static Map<String, String> archiveMap = new HashMap<String, String>(); + + public static Map<String, String> compressorMap = new HashMap<String, String>(); + + static { + // archive type + archiveMap.put(ArchiveStreamFactory.AR, ArchiveStreamFactory.AR); + archiveMap.put(ArchiveStreamFactory.ARJ, ArchiveStreamFactory.ARJ); + archiveMap.put(ArchiveStreamFactory.CPIO, ArchiveStreamFactory.CPIO); + archiveMap.put(ArchiveStreamFactory.DUMP, ArchiveStreamFactory.DUMP); + archiveMap.put(ArchiveStreamFactory.JAR, ArchiveStreamFactory.JAR); + archiveMap.put(ArchiveStreamFactory.SEVEN_Z, ArchiveStreamFactory.SEVEN_Z); + archiveMap.put(ArchiveStreamFactory.TAR, ArchiveStreamFactory.TAR); + archiveMap.put(ArchiveStreamFactory.ZIP, ArchiveStreamFactory.ZIP); + + // compressor type + compressorMap.put(CompressorStreamFactory.BZIP2, CompressorStreamFactory.BZIP2); + compressorMap.put(CompressorStreamFactory.DEFLATE, CompressorStreamFactory.DEFLATE); + compressorMap.put(CompressorStreamFactory.GZIP, CompressorStreamFactory.GZIP); + compressorMap.put(CompressorStreamFactory.LZMA, CompressorStreamFactory.LZMA); + compressorMap.put(CompressorStreamFactory.PACK200, CompressorStreamFactory.PACK200); + compressorMap.put(CompressorStreamFactory.SNAPPY_FRAMED, CompressorStreamFactory.SNAPPY_FRAMED); + compressorMap.put(CompressorStreamFactory.SNAPPY_RAW, CompressorStreamFactory.SNAPPY_RAW); + compressorMap.put(CompressorStreamFactory.XZ, CompressorStreamFactory.XZ); + compressorMap.put(CompressorStreamFactory.Z, CompressorStreamFactory.Z); + } + + /** + * tar.gz + * <br/> + * + * @param zipfileName + * @param outputDirectory + * @param fileNames + * @return + * @since NFVO 0.5 + */ + public static boolean unCompressGzip(String zipfileName, String outputDirectory, List<String> fileNames) { + FileInputStream fis = null; + ArchiveInputStream in = null; + BufferedInputStream bis = null; + try { + fis = new FileInputStream(zipfileName); + GZIPInputStream gis = new GZIPInputStream(new BufferedInputStream(fis)); + in = new ArchiveStreamFactory().createArchiveInputStream("tar", gis); + bis = new BufferedInputStream(in); + TarArchiveEntry entry = (TarArchiveEntry)in.getNextEntry(); + while(entry != null) { + String name = entry.getName(); + String[] names = name.split("/"); + String fileName = outputDirectory; + for(int i = 0; i < names.length; i++) { + String str = names[i]; + fileName = fileName + File.separator + str; + } + if(name.endsWith("/")) { + FileUtils.mkDirs(fileName); + } else { + File file = getRealFileName(outputDirectory, name); + if(null != fileNames) { + fileNames.add(file.getName()); + } + BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); + int b = -1; + while((b = bis.read()) != -1) { + bos.write(b); + } + log.debug("ungzip to:" + file.getCanonicalPath()); + bos.flush(); + bos.close(); + } + entry = (TarArchiveEntry)in.getNextEntry(); + } + return true; + } catch(Exception e) { + log.error("UnCompressGZip faield:", e); + return false; + } finally { + try { + if(null != bis) { + bis.close(); + } + } catch(IOException e) { + log.error("UnCompressGZip faield:", e); + } + } + } + + public static void unCompressAllZip(String sourcePath, String targetPath) throws FileNotFoundException { + for(File file : FileUtils.listFiles(new File(sourcePath))) { + unCompressZip(file.getAbsolutePath(), + targetPath + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")),new ArrayList<String>()); + } + } + + /** + * zip + * <br/> + * + * @param sourceFile unzipPath + * @param targetPath zippath + * @param fileNames + * @since NFVO 0.5 + */ + public static boolean unCompressZip(String sourceFile, String targetPath,List<String> fileNames) { + try { + BufferedOutputStream dest = null; + FileInputStream fis = new FileInputStream(sourceFile); + ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); + ZipEntry entry = null; + while((entry = zis.getNextEntry()) != null) { + String name = entry.getName(); + String[] names = name.split("/"); + String fileName = targetPath; + for(int i = 0; i < names.length; i++) { + String str = names[i]; + fileName = fileName + File.separator + str; + } + if(name.endsWith("/")) { + FileUtils.mkDirs(fileName); + } else { + int count; + byte data[] = new byte[2048]; + File file = getRealFileName(targetPath, name); + fileNames.add(file.getName()); + dest = new BufferedOutputStream(new FileOutputStream(file)); + + while((count = zis.read(data, 0, 2048)) != -1) { + dest.write(data, 0, count); + } + log.debug("unzip to:" + file.getCanonicalPath()); + dest.flush(); + dest.close(); + } + } + zis.close(); + return true; + } catch(Exception e) { + log.error("UnCompressZip faield:", e); + } + return false; + } + + private static File getRealFileName(String zippath, String absFileName) { + String[] dirs = absFileName.split("/", absFileName.length()); + + File ret = new File(zippath); + + if(dirs.length > 1) { + for(int i = 0; i < dirs.length - 1; i++) { + ret = new File(ret, dirs[i]); + } + } + + if(!ret.exists()) { + ret.mkdirs(); + } + + ret = new File(ret, dirs[dirs.length - 1]); + + return ret; + } + + /** + * tar.xz + * <br/> + * + * @param zipfileName + * @param outputDirectory + * @param fileNames + * @return + * @since NFVO 0.5 + */ + public static boolean unCompressTarXZ(String zipfileName, String outputDirectory, List<String> fileNames) { + ArchiveInputStream in = null; + BufferedInputStream bis = null; + try { + XZCompressorInputStream xzis = + new XZCompressorInputStream(new BufferedInputStream(new FileInputStream(zipfileName))); + in = new ArchiveStreamFactory().createArchiveInputStream("tar", xzis); + bis = new BufferedInputStream(in); + TarArchiveEntry entry = (TarArchiveEntry)in.getNextEntry(); + while(entry != null) { + String name = entry.getName(); + String[] names = name.split("/"); + String fileName = outputDirectory; + for(int i = 0; i < names.length; i++) { + String str = names[i]; + fileName = fileName + File.separator + str; + } + if(name.endsWith("/")) { + FileUtils.mkDirs(fileName); + } else { + File file = getRealFileName(outputDirectory, name); + if(null != fileNames) { + fileNames.add(file.getName()); + } + BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); + int b = -1; + while((b = bis.read()) != -1) { + bos.write(b); + } + log.debug("ungzip to:" + file.getCanonicalPath()); + bos.flush(); + bos.close(); + } + entry = (TarArchiveEntry)in.getNextEntry(); + } + return true; + } catch(Exception e) { + log.error("unCompressTarXZ faield:", e); + } finally { + try { + if(null != bis) { + bis.close(); + } + } catch(IOException e) { + log.error("unCompressTarXZ faield:", e); + } + } + return false; + } + + /** + * only support .zip/.tar.gz/.tar.xz + * <br/> + * + * @param zipfileName + * @param outputDirectory + * @param fileNames + * @return + * @since NFVO 0.5 + */ + public static boolean unCompress(String zipfileName, String outputDirectory, List<String> fileNames) { + if(zipfileName.endsWith(".zip")){ + return unCompressZip(zipfileName,outputDirectory,fileNames); + }else if(zipfileName.endsWith(".tar.gz")){ + return unCompressGzip(zipfileName,outputDirectory,fileNames); + }else if(zipfileName.endsWith(".tar.xz")){ + return unCompressTarXZ(zipfileName,outputDirectory,fileNames); + }else{ + log.error("not supprot file type:->"+zipfileName); + return false; + } + } + + +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/VNFJsonUtil.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/VNFJsonUtil.java new file mode 100644 index 0000000..57e7202 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/VNFJsonUtil.java @@ -0,0 +1,420 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common; + +import java.io.IOException; +import java.io.InputStream; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.io.IOUtils; +import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.jackson.type.TypeReference; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.ezmorph.object.DateMorpher; +import net.sf.json.JSON; +import net.sf.json.JSONArray; +import net.sf.json.JSONException; +import net.sf.json.JSONObject; +import net.sf.json.JsonConfig; +import net.sf.json.processors.JsonValueProcessor; +import net.sf.json.util.CycleDetectionStrategy; +import net.sf.json.util.JSONTokener; +import net.sf.json.util.JSONUtils; + +/** + * + * Virtual Network Function Json Utility class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 10, 2016 + */ +public final class VNFJsonUtil { + + private static final Logger LOG = LoggerFactory.getLogger(VNFJsonUtil.class); + + private static final ObjectMapper VNFMAPPER = new ObjectMapper(); + + private static final String ERROR = "error"; + static { + VNFMAPPER.setDeserializationConfig(VNFMAPPER.getDeserializationConfig() + .without(org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES)); + } + + private VNFJsonUtil() { + } + + /** + * + * UnMarshal method.<br> + * + * @param vnfJsonstr + * @param type + * @return + * @throws IOException + * @since NFVO 0.5 + */ + public static <T> T unMarshal(String vnfJsonstr, Class<T> type) throws IOException { + return VNFMAPPER.readValue(vnfJsonstr, type); + } + + /** + * + * UnMarshal method.<br> + * + * @param vnfJsonstr + * @param type + * @return + * @throws IOException + * @since NFVO 0.5 + */ + public static <T> T unMarshal(String vnfJsonstr, TypeReference<T> type) throws IOException { + return VNFMAPPER.readValue(vnfJsonstr, type); + } + + /** + * + * Marshal method.<br> + * + * @param srcObj + * @return + * @throws IOException + * @since NFVO 0.5 + */ + public static String marshal(Object srcObj) throws IOException { + if(srcObj instanceof JSON) { + return srcObj.toString(); + } + return VNFMAPPER.writeValueAsString(srcObj); + } + + public static ObjectMapper getMapper() { + return VNFMAPPER; + } + + /** + * + * Get Json field string.<br> + * + * @param vnfJsonObj + * @param fieldName + * @return + * @since NFVO 0.5 + */ + public static String getJsonFieldStr(JSONObject vnfJsonObj, String fieldName) { + if(null == vnfJsonObj || null == vnfJsonObj.get(fieldName) || "null".equals(vnfJsonObj.getString(fieldName))) { + LOG.warn("getJsonFieldStr: VNFJson object field(" + fieldName + ") is null."); + return ""; + } + + return vnfJsonObj.getString(fieldName); + } + + /** + * + * Get Json field integer.<br> + * + * @param vnfJsonObj + * @param fieldName + * @return + * @since NFVO 0.5 + */ + public static Integer getJsonFieldInt(JSONObject vnfJsonObj, String fieldName) { + if(null == vnfJsonObj || null == vnfJsonObj.get(fieldName)) { + LOG.warn("getJsonFieldInt: VNFJson object field(" + fieldName + ") is Null"); + return 0; + } + return vnfJsonObj.getInt(fieldName); + } + + /** + * + * Get Json field long.<br> + * + * @param vnfJsonObj + * @param fieldName + * @return + * @since NFVO 0.5 + */ + public static Long getJsonFieldLong(JSONObject vnfJsonObj, String fieldName) { + if(null == vnfJsonObj || null == vnfJsonObj.get(fieldName)) { + LOG.warn("getJsonFieldLong: VNFJson object field(" + fieldName + ") is null"); + return 0L; + } + return vnfJsonObj.getLong(fieldName); + } + + /** + * + * Parse error information.<br> + * + * @param errorInfo + * @return + * @since NFVO 0.5 + */ + public static String parseErrorInfo(String errorInfo) { + if((errorInfo != null) && (!errorInfo.isEmpty())) { + JSONObject errorInfoJst = JSONObject.fromObject(errorInfo); + if(errorInfoJst.has(ERROR) && errorInfoJst.getJSONObject(ERROR).has("message")) { + return errorInfoJst.getJSONObject(ERROR).getString("message"); + } + } + return "System Error!"; + } + + static { + VNFMAPPER.setDeserializationConfig(VNFMAPPER.getDeserializationConfig() + .without(org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES)); + } + + /** + * + * Convert VNF Json to objects.<br> + * + * @param vnfJsonString + * @param pojoCalss + * @return + * @since NFVO 0.5 + */ + @SuppressWarnings("unchecked") + public static <T> T vnfJsonToObjects(String vnfJsonString, Class<T> pojoCalss) { + JSONObject vnfJsonObject = JSONObject.fromObject(vnfJsonString); + return (T)JSONObject.toBean(vnfJsonObject, pojoCalss); + } + + /** + * + * Convert VNF Json to objects.<br> + * + * @param vnfJsonString + * @param vnfJsonConfig + * @return + * @since NFVO 0.5 + */ + @SuppressWarnings("unchecked") + public static <T> T vnfJsonToObjects(String vnfJsonString, JsonConfig vnfJsonConfig) { + JSONObject vnfJsonObject = JSONObject.fromObject(vnfJsonString); + return (T)JSONObject.toBean(vnfJsonObject, vnfJsonConfig); + } + + /** + * + * Convert VNF Json to lists.<br> + * + * @param vnfJsonString + * @param pojoClass + * @return + * @since NFVO 0.5 + */ + @SuppressWarnings("unchecked") + public static <T> List<T> vnfJsonToLists(String vnfJsonString, Class<T> pojoClass) { + JSONArray vnfJsonVNFArray = JSONArray.fromObject(vnfJsonString); + JSONObject vnfJsonObject; + List<T> list = new ArrayList<>(20); + for(int i = 0; i < vnfJsonVNFArray.size(); i++) { + vnfJsonObject = vnfJsonVNFArray.getJSONObject(i); + list.add((T)JSONObject.toBean(vnfJsonObject, pojoClass)); + } + return list; + } + + /** + * + * Convert VNF Json to list.<br> + * + * @param vnfJsonString + * @param pojoClass + * @param dataFormat + * @return + * @since NFVO 0.5 + */ + @SuppressWarnings("unchecked") + public static <T> List<T> vnfJsonToList(String vnfJsonString, Class<T> pojoClass, String dataFormat) { + JsonConfig vnfJsonConfig = configJson(dataFormat); + JSONArray vnfJsonVNFArray = JSONArray.fromObject(vnfJsonString, vnfJsonConfig); + JSONObject vnfJsonObject; + List<T> list = new ArrayList<>(20); + for(int i = 0; i < vnfJsonVNFArray.size(); i++) { + vnfJsonObject = vnfJsonVNFArray.getJSONObject(i); + list.add((T)JSONObject.toBean(vnfJsonObject, pojoClass)); + } + return list; + } + + /** + * + * Object to json string.<br> + * + * @param javaObj + * @return + * @since NFVO 0.5 + */ + public static String objectToJsonStr(Object javaObj) { + JSONObject vnfJson = JSONObject.fromObject(javaObj); + return vnfJson.toString(); + } + + /** + * + * object to json.<br> + * + * @param javaObj + * @return + * @since NFVO 0.5 + */ + public static JSONObject objectToJson(Object javaObj) { + return JSONObject.fromObject(javaObj); + } + + /** + * + * Object to json.<br> + * + * @param javaObj + * @param vnfJsonConfig + * @return + * @since NFVO 0.5 + */ + public static String objectToJson(Object javaObj, JsonConfig vnfJsonConfig) { + JSONObject vnfJson = JSONObject.fromObject(javaObj, vnfJsonConfig); + return vnfJson.toString(); + } + + /** + * + * Object to json.<br> + * + * @param javaObj + * @param dataFormat + * @return + * @since NFVO 0.5 + */ + public static String objectToJson(Object javaObj, String dataFormat) { + JsonConfig vnfJsonConfig = configJson(dataFormat); + JSONObject vnfJson = JSONObject.fromObject(javaObj, vnfJsonConfig); + return vnfJson.toString(); + + } + + /** + * + * List to json.<br> + * + * @param list + * @return + * @since NFVO 0.5 + */ + public static <T> String listToJson(List<T> list) { + JSONArray vnfJson = JSONArray.fromObject(list); + return vnfJson.toString(); + } + + /** + * + * List to json.<br> + * + * @param list + * @param dataFormat + * @return + * @since NFVO 0.5 + */ + public static <T> String listToJson(List<T> list, String dataFormat) { + JsonConfig vnfJsonConfig = configJson(dataFormat); + JSONArray vnfJson = JSONArray.fromObject(list, vnfJsonConfig); + return vnfJson.toString(); + } + + /** + * + * Config json.<br> + * + * @param datePattern + * @return + * @since NFVO 0.5 + */ + public static JsonConfig configJson(final String datePattern) { + + JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[] {datePattern})); + + JsonConfig vnfJsonConfig = new JsonConfig(); + vnfJsonConfig.setIgnoreDefaultExcludes(false); + vnfJsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); + vnfJsonConfig.registerJsonValueProcessor(Date.class, new JsonValueProcessor() { + @Override + public Object processObjectValue(String key, Object value, JsonConfig vnfJsonConfig) { + if(value instanceof Date) { + return new SimpleDateFormat(datePattern).format((Date)value); + } + return value == null ? null : value.toString(); + } + @Override + public Object processArrayValue(Object value, JsonConfig vnfJsonConfig) { + String[] vnfObj = {}; + SimpleDateFormat vnfSf = new SimpleDateFormat(datePattern); + if(value instanceof Date[]) { + Date[] dates = (Date[])value; + vnfObj = new String[dates.length]; + for(int i = 0; i < dates.length; i++) { + vnfObj[i] = vnfSf.format(dates[i]); + } + } + return vnfObj; + } + }); + return vnfJsonConfig; + } + + /** + * @param context the HttpContext + * @param <T> JSONObject or JSONArray + * @return + */ + @SuppressWarnings("unchecked") + public static <T> T getJsonFromContext(HttpServletRequest context) { + try { + InputStream input = context.getInputStream(); + String vnfJsonStr = IOUtils.toString(input); + JSONTokener vnfVnfJsonTokener = new JSONTokener(vnfJsonStr); + + // "{" + if(vnfVnfJsonTokener.nextClean() == Character.codePointAt("{", 0)) { + return (T)JSONObject.fromObject(vnfJsonStr); + } + + vnfVnfJsonTokener.back(); + + // "[" + if(vnfVnfJsonTokener.nextClean() == Character.codePointAt("[", 0)) { + return (T)JSONArray.fromObject(vnfJsonStr); + } + } catch(IOException e) { + LOG.error("function=getJsonFromContext,msg= IOException occurs. exception=" + e); + } catch(JSONException e) { + LOG.error("function=getJsonFromContext,msg= JSONException occurs, exception=" + e); + } + return null; + } + +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/VnfmException.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/VnfmException.java new file mode 100644 index 0000000..3517442 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/VnfmException.java @@ -0,0 +1,84 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common; + +/** + * + * Vnfm exception class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public class VnfmException extends Exception { + + private static final long serialVersionUID = 1L; + + /** + * + * Constructor<br> + * <p> + * </p> + * + * @since NFVO 0.5 + */ + public VnfmException() { + super(); + } + + /** + * + * Constructor<br> + * <p> + * </p> + * + * @param message + * @param cause + * @since NFVO 0.5 + */ + public VnfmException(String message, Throwable cause) { + super(message, cause); + } + + /** + * + * Constructor<br> + * <p> + * </p> + * + * @param message + * @since NFVO 0.5 + */ + public VnfmException(String message) { + super(message); + } + + /** + * + * Constructor<br> + * <p> + * </p> + * + * @param cause + * @since NFVO 0.5 + */ + public VnfmException(Throwable cause) { + super(cause); + } + +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/VnfmUtil.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/VnfmUtil.java new file mode 100644 index 0000000..9817156 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/VnfmUtil.java @@ -0,0 +1,95 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common; + +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.jujuvnfmadapter.common.servicetoken.JujuVnfmRestfulUtil; +import org.openo.nfvo.jujuvnfmadapter.common.servicetoken.VnfmRestfulUtil; +import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant; +import org.openo.nfvo.jujuvnfmadapter.service.constant.UrlConstant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; +/** + * Provide function of getting vnfmInfo + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 25, 2016 + */ +public final class VnfmUtil { + + private static final Logger LOG = LoggerFactory.getLogger(VnfmUtil.class); + private VnfmUtil() { + + } + + /** + * Get vnfmInfo by ip + * <br/> + * + * @param vnfmId + * @return + * @since NFVO 0.5 + */ + public static JSONObject getVnfmById(String vnfmId) { + if(SwitchController.isDebugModel()){ + JSONObject json = new JSONObject(); + json.put("vnfmId", vnfmId); + json.put("vnfdId","testVnfdId"); + json.put("vnfPackageId", "testPackageId"); + json.put("version", "1"); + json.put("url",JujuConfigUtil.getValue("jujuvnfm_server_url")); + return json; + } + RestfulResponse rsp = VnfmRestfulUtil.getRemoteResponse(String.format(UrlConstant.REST_ESRINFO_GET, vnfmId), JujuVnfmRestfulUtil.GET_TYPE, null); + if(rsp == null || rsp.getStatus() != Constant.HTTP_OK) { + return null; + } + LOG.error("funtion=getVnfmById, status={}", rsp.getStatus()); + return JSONObject.fromObject(rsp.getResponseContent()); + } + + /** + * Get vnfmInfo by id + * <br/> + * + * @param ip + * @return + * @since NFVO 0.5 + */ + public static String getVnfmIdByIp(String ip) { + RestfulResponse rsp = + VnfmRestfulUtil.getRemoteResponse(UrlConstant.REST_ESRINFO_GET, VnfmRestfulUtil.TYPE_GET, null); + if(rsp == null || rsp.getStatus() != Constant.HTTP_OK) { + return ""; + } + + JSONArray vnfmList = JSONArray.fromObject(rsp.getResponseContent()); + for(int i = 0; i < vnfmList.size(); i++) { + if(vnfmList.getJSONObject(i).getString("url").contains(ip)) { + return vnfmList.getJSONObject(i).getString("vnfmId"); + } + } + + return ""; + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/YamlUtil.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/YamlUtil.java new file mode 100644 index 0000000..52235f2 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/YamlUtil.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2016, Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common; + +import java.io.*; +import java.util.ArrayList; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.parser.ParserException; + +import net.sf.json.JSON; +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; + +/** + * <br/> + * <p> + * </p> + * + * @author quanzhong@huawei.com + * @version NFVO 0.5 Oct 25, 2016 + */ +public class YamlUtil { + private static Logger log = LoggerFactory.getLogger(YamlUtil.class); + + + + /** + * + * <br/> + * + * @param yamlName + * @return + * @since NFVO 0.5 + */ + public static JSON yamlToJson(String yamlName){ + Object res = parseYaml(yamlName); + if(res instanceof ArrayList){ + return JSONArray.fromObject(res); + } + return JSONObject.fromObject(res); + } + + /** + * + * <br/> + * + * @param yamlName + * @return + * @since NFVO 0.5 + */ + public static String loadYaml(String yamlName){ + String res = null; + try { + Yaml yaml = new Yaml(); + File file =new File(yamlName); + + Object obj = yaml.load(new FileInputStream(file)); + if(obj != null){ + res = obj.toString(); + } + log.debug("yaml-> "+res); + }catch(ParserException e){ + log.error("error format:",e); + }catch(FileNotFoundException e) { + log.error("the yaml file not exist {}",yamlName,e); + } + return res; + } + + /** + * + * <br/> + * + * @param yamlName + * @return + * @since NFVO 0.5 + */ + public static Object parseYaml(String yamlName){ + Object obj = null; + try { + File file =new File(yamlName); + obj = new Yaml().load(new FileInputStream(file)); + }catch(ParserException e){ + log.error("error format:",e); + + }catch(FileNotFoundException e) { + log.error("the yaml file not exist {}",yamlName,e); + } + return obj; + } + + public static void main(String[] args) throws IOException { + + + Map config = new Yaml().loadAs(new FileInputStream("C:\\Users\\z00292420\\Desktop\\juju\\config2.yaml"), Map.class); + Map options = (Map)config.get("options"); + Map name = (Map)options.get("name"); + name.put("default","hello,it's me"); +// new Yaml().dump(config, new FileWriter("C:\\Users\\z00292420\\Desktop\\juju\\config2.yaml")); + String newYaml = new Yaml().dumpAsMap(config); + Writer w = new FileWriter(new File("C:\\Users\\z00292420\\Desktop\\juju")); + w.write(newYaml); + w.flush(); + w.close(); + System.out.println(newYaml); + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/servicetoken/HttpRestHelp.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/servicetoken/HttpRestHelp.java new file mode 100644 index 0000000..1c0da4f --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/servicetoken/HttpRestHelp.java @@ -0,0 +1,79 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common.servicetoken; + +import java.util.HashMap; +import java.util.Map; + +import org.openo.baseservice.roa.util.restclient.HttpRest; +import org.openo.baseservice.roa.util.restclient.Restful; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + * Http rest help class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public class HttpRestHelp { + + public static final String PROTO_HTTP = "http"; + + private static final Logger LOG = LoggerFactory.getLogger(HttpRestHelp.class); + + private static final Map<String, Restful> INSTANCES = new HashMap<>(2); + + private HttpRestHelp() { + // constructor + } + + private static Restful createHttpsRest(String ssloptionfile, String restoptionfile, boolean isHttps) { + + HttpRest rest = new HttpRest(); + setHttpsRestOption(rest, restoptionfile); + return rest; + } + + /** + * + * Get rest instance class.<br> + * + * @param ssloptionfile + * @param restoptionfile + * @param isHttps + * @return + * @since NFVO 0.5 + */ + public static synchronized Restful getRestInstance(String ssloptionfile, String restoptionfile, boolean isHttps) { + Restful rest = INSTANCES.get(PROTO_HTTP); + if(null != rest) { + return rest; + } + rest = createHttpsRest(ssloptionfile, restoptionfile, isHttps); + INSTANCES.put(PROTO_HTTP, rest); + return rest; + } + + private static void setHttpsRestOption(HttpRest httpRest, String restoptfile) { + LOG.info("setHttpsRestOption"); + } + +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/servicetoken/HttpRestfulHelp.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/servicetoken/HttpRestfulHelp.java new file mode 100644 index 0000000..b1f66e9 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/servicetoken/HttpRestfulHelp.java @@ -0,0 +1,69 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common.servicetoken; + +import java.util.HashMap; +import java.util.Map; + +import org.openo.baseservice.roa.util.restclient.HttpRest; +import org.openo.baseservice.roa.util.restclient.Restful; + +/** + * + * Http restful help class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public class HttpRestfulHelp { + + public static final String PROTO_HTTPS = "https"; + + public static final String PROTO_HTTP = "http"; + + private static final Map<String, Restful> INSTANCES = new HashMap<>(2); + + private HttpRestfulHelp() { + // constructor + } + + /** + * + * Get rest instance.<br> + * + * @param ssloptionfile + * @param restoptionfile + * @return + * @since NFVO 0.5 + */ + public static synchronized Restful getRestInstance(String ssloptionfile, String restoptionfile) { + Restful rest = INSTANCES.get(PROTO_HTTP); + if(rest != null) { + return rest; + } + rest = createHttpsRest(ssloptionfile, restoptionfile); + INSTANCES.put(PROTO_HTTP, rest); + return rest; + } + + private static Restful createHttpsRest(String ssloptionfile, String restoptionfile) { + return new HttpRest(); + } + +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/servicetoken/JujuVnfmRestfulUtil.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/servicetoken/JujuVnfmRestfulUtil.java new file mode 100644 index 0000000..238e7ad --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/servicetoken/JujuVnfmRestfulUtil.java @@ -0,0 +1,315 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common.servicetoken; + +import java.util.HashMap; +import java.util.Map; + +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.baseservice.roa.util.restclient.Restful; +import org.openo.baseservice.roa.util.restclient.RestfulFactory; +import org.openo.baseservice.roa.util.restclient.RestfulOptions; +import org.openo.baseservice.roa.util.restclient.RestfulParametes; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + * Juju VNFM restful utility class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public final class JujuVnfmRestfulUtil { + + public static final String GET_TYPE = "get"; + + public static final String ADD_TYPE = "add"; + + public static final String POST_TYPE = "post"; + + public static final String PUT_TYPE = "put"; + + public static final String DEL_TYPE = "delete"; + + public static final String METHOD_TYPE = "methodType"; + + public static final int ERROR_STATUS_CODE = -1; + + public static final String CONTENT_TYPE = "Content-type"; + + public static final String APPLICATION = "application/json"; + + public static final String HEADER_AUTH_TOKEN = "X-Auth-Token"; + + private static final Logger LOG = LoggerFactory.getLogger(JujuVnfmRestfulUtil.class); + + private JujuVnfmRestfulUtil() { + // constructor + } + + /** + * + * Get Vim response content.<br> + * + * @param url + * @param restParametes + * @param type + * @return + * @since NFVO 0.5 + */ + public static String getVimResponseContent(String url, RestfulParametes restParametes, String type) { + Map<String, Object> resMap = getVimResponseContent(url, restParametes, null, type); + + return resMap.get("responseContent").toString(); + + } + + /** + * + * Get Vim response content.<br> + * + * @param url + * @param restParametes + * @param opt + * @param type + * @return + * @since NFVO 0.5 + */ + public static Map<String, Object> getVimResponseContent(String url, RestfulParametes restParametes, + RestfulOptions opt, String type) { + Map<String, Object> resMap = new HashMap<>(2); + + try { + Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP); + RestfulResponse rsp = null; + if (rest != null) { + if (GET_TYPE.equals(type)) { + rsp = rest.get(url, restParametes, opt); + } else if (ADD_TYPE.equals(type)) { + rsp = rest.post(url, restParametes, opt); + } else if (PUT_TYPE.equals(type)) { + rsp = rest.put(url, restParametes, opt); + } else if (DEL_TYPE.equals(type)) { + rsp = rest.delete(url, restParametes, opt); + } + if (null != rsp) { + resMap.put("responseContent", rsp.getResponseContent()); + resMap.put("statusCode", rsp.getStatus()); + } + } + LOG.info("get response data success!"); + } catch (ServiceException e) { + LOG.error("get response data catch exception {}.", e); + } + + return resMap; + } + + /** + * + * Get Vim response result.<br> + * + * @param url + * @param type + * @return + * @since NFVO 0.5 + */ + public static RestfulResponse getVimResponseResult(String url, String type) { + RestfulParametes restParametes = new RestfulParametes(); + return getVimResponseResult(url, restParametes, type); + } + + /** + * + * Get Vim response result.<br> + * + * @param url + * @param restParametes + * @param type + * @return + * @since NFVO 0.5 + */ + public static RestfulResponse getVimResponseResult(String url, RestfulParametes restParametes, String type) { + return vimRestfulResponse(url, restParametes, null, type); + } + + /** + * + * Get Vim response.<br> + * + * @param url + * @param restParametes + * @param opt + * @param type + * @return + * @since NFVO 0.5 + */ + public static RestfulResponse vimRestfulResponse(String url, RestfulParametes restParametes, RestfulOptions opt, + String type) { + RestfulResponse rsp = null; + try { + Map<String, String> headerMap = new HashMap<>(2); + headerMap.put(CONTENT_TYPE, APPLICATION); + restParametes.setHeaderMap(headerMap); + Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP); + + if (rest != null) { + if (GET_TYPE.equals(type)) { + rsp = rest.get(url, restParametes, opt); + } else if (ADD_TYPE.equals(type)) { + rsp = rest.post(url, restParametes, opt); + } else if (PUT_TYPE.equals(type)) { + rsp = rest.put(url, restParametes, opt); + } else if (DEL_TYPE.equals(type)) { + rsp = rest.delete(url, restParametes, opt); + } + } + LOG.info("get response data success!"); + } catch (ServiceException e) { + LOG.error("get response data catch ServiceException {}.", e); + } + return rsp; + } + + /** + * + * Get remote response.<br> + * + * @param paramsMap + * @param params + * @param domainTokens + * @param isHttps + * @return + * @since NFVO 0.5 + */ + public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params, String domainTokens, + boolean isHttps) { + String url = paramsMap.get("url"); + String methodType = paramsMap.get(METHOD_TYPE); + String path = paramsMap.get("path"); + + RestfulResponse rsp = null; + Restful rest = null; + String sslOptionFile = ""; + try { + String restClientFile = "restclient.json"; + + if (isHttps) { + sslOptionFile = "ssl.nfvo.properties"; + + } + + rest = HttpRestHelp.getRestInstance(sslOptionFile, restClientFile, isHttps); + + RestfulOptions opt = new RestfulOptions(); + String[] strs = path.split("(http(s)?://)|:"); + + opt.setHost(strs[1]); + opt.setPort(Integer.parseInt(strs[2])); + + RestfulParametes restfulParametes = new RestfulParametes(); + Map<String, String> headerMap = new HashMap<>(3); + headerMap.put(CONTENT_TYPE, APPLICATION); + headerMap.put(HEADER_AUTH_TOKEN, domainTokens); + restfulParametes.setHeaderMap(headerMap); + restfulParametes.setRawData(params); + + if (rest != null) { + if (GET_TYPE.equalsIgnoreCase(methodType)) { + rsp = rest.get(url, restfulParametes, opt); + } else if (POST_TYPE.equalsIgnoreCase(methodType)) { + rsp = rest.post(url, restfulParametes, opt); + } else if (PUT_TYPE.equalsIgnoreCase(methodType)) { + rsp = rest.put(url, restfulParametes, opt); + } else if (DEL_TYPE.equalsIgnoreCase(methodType)) { + rsp = rest.delete(url, restfulParametes, opt); + } + } + } catch (ServiceException e) { + LOG.error("function=restfulResponse, get restful response catch exception {}", e); + } + return rsp; + } + + /** + * + * Get remote response.<br> + * + * @param paramsMap + * @param params + * @return + * @since NFVO 0.5 + */ + public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) { + if(null == paramsMap){ + return null; + } + String url = paramsMap.get("url"); + String methodType = paramsMap.get(METHOD_TYPE); + + RestfulResponse rsp = null; + Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP); + try { + + RestfulParametes restfulParametes = new RestfulParametes(); + Map<String, String> headerMap = new HashMap<>(3); + headerMap.put(CONTENT_TYPE, APPLICATION); + restfulParametes.setHeaderMap(headerMap); + restfulParametes.setRawData(params); + + if (rest != null) { + if (GET_TYPE.equalsIgnoreCase(methodType)) { + rsp = rest.get(url, restfulParametes); + } else if (POST_TYPE.equalsIgnoreCase(methodType)) { + rsp = rest.post(url, restfulParametes); + } else if (PUT_TYPE.equalsIgnoreCase(methodType)) { + rsp = rest.put(url, restfulParametes); + } else if (DEL_TYPE.equalsIgnoreCase(methodType)) { + rsp = rest.delete(url, restfulParametes); + } + } + } catch (ServiceException e) { + LOG.error("function=getRemoteResponse, get restful response catch exception {}", e); + } + return rsp; + } + + /** + * + * Generate parameter map.<br> + * + * @param url + * @param methodType + * @param path + * @param authMode + * @return + * @since NFVO 0.5 + */ + public static Map<String, String> generateParametesMap(String url, String methodType, String path, + String authMode) { + Map<String, String> paramsMap = new HashMap<>(6); + paramsMap.put("url", url); + paramsMap.put(METHOD_TYPE, methodType); + paramsMap.put("path", path); + paramsMap.put("authMode", authMode); + return paramsMap; + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/servicetoken/VNFAuthConfigInfo.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/servicetoken/VNFAuthConfigInfo.java new file mode 100644 index 0000000..4e7c13e --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/servicetoken/VNFAuthConfigInfo.java @@ -0,0 +1,147 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common.servicetoken; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + * Vnf Authentication configuration information class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public class VNFAuthConfigInfo { + + private static final Logger LOG = LoggerFactory.getLogger(VNFAuthConfigInfo.class); + + private static final String AUTH_CONFIG_FILE = "identity.VNFProperties"; + + private static VNFAuthConfigInfo authConfig = new VNFAuthConfigInfo(); + + private static long lastModify = 0L; + + private String vnfUserName; + + private String vnfEncryptedPW; + + private String vnfDomain; + + private String vnfResourceDomain; + + private String defaultDomain; + + private VNFAuthConfigInfo() { + Properties vnfProp = new Properties(); + InputStream authIn = null; + + try { + if(isVNFProModified(getAuthCofigPath())) { + authIn = new FileInputStream(getAuthCofigPath()); + + vnfProp.load(authIn); + vnfUserName = vnfProp.getProperty("name"); + vnfEncryptedPW = vnfProp.getProperty("value"); + vnfDomain = vnfProp.getProperty("vnfDomain"); + vnfResourceDomain = vnfProp.getProperty("vnfResourceDomain"); + defaultDomain = vnfProp.getProperty("defaultDomain"); + authIn.close(); + } + + } catch(IOException e) { + LOG.error("loadAuthConfig can't find config file>> e = {}", e); + } finally { + try { + if(authIn != null) { + + authIn.close(); + } + } catch(IOException e) { + LOG.error("loadAuthConfig can't find config file>> e = {}", e); + } + + } + + } + + private String getAuthCofigPath() { + return AUTH_CONFIG_FILE; + } + + public static VNFAuthConfigInfo getInstance() { + return authConfig; + } + + public String getUserName() { + return vnfUserName; + } + + public String getEncryptedPW() { + return vnfEncryptedPW; + } + + public String getDomain() { + return vnfDomain; + } + + public void setUserName(String vnfuserName) { + this.vnfUserName = vnfuserName; + } + + public void setEncryptedPW(String vnfencryptedPW) { + this.vnfEncryptedPW = vnfencryptedPW; + } + + public void setDomain(String vnfDomain) { + this.vnfDomain = vnfDomain; + } + + public String getResourceDomain() { + return vnfResourceDomain; + } + + public void setResourceDomain(String vnfResourceDomain) { + this.vnfResourceDomain = vnfResourceDomain; + } + + public String getDefaultDomain() { + return defaultDomain; + } + + public void setDefaultDomain(String defaultDomain) { + this.defaultDomain = defaultDomain; + } + + private static boolean isVNFProModified(String filename) { + boolean returnValue = false; + File inputFile = new File(filename); + if(inputFile.lastModified() > lastModify) { + lastModify = inputFile.lastModified(); + returnValue = true; + } + return returnValue; + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/servicetoken/VNFRestfulUtil.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/servicetoken/VNFRestfulUtil.java new file mode 100644 index 0000000..b7eee2c --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/servicetoken/VNFRestfulUtil.java @@ -0,0 +1,437 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common.servicetoken; + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.baseservice.roa.util.restclient.Restful; +import org.openo.baseservice.roa.util.restclient.RestfulAsyncCallback; +import org.openo.baseservice.roa.util.restclient.RestfulFactory; +import org.openo.baseservice.roa.util.restclient.RestfulOptions; +import org.openo.baseservice.roa.util.restclient.RestfulParametes; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.jujuvnfmadapter.common.AsyncCallback; +import org.openo.nfvo.jujuvnfmadapter.common.VnfmException; +import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; + +/** + * + * VNF Restful utility class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public final class VNFRestfulUtil { + + public static final String TYPE_GET = "get"; + + public static final String TYPE_ADD = "add"; + + public static final String TYPE_POST = "post"; + + public static final String TYPE_PUT = "put"; + + public static final String TYPE_DEL = "delete"; + + public static final int ERROR_STATUS_CODE = -1; + + private static final Logger LOG = LoggerFactory.getLogger(VNFRestfulUtil.class); + + private VNFRestfulUtil() { + + } + + /** + * + * within our module, we support a default method to invoke.<br> + * + * @param path, rest service url + * @param methodNames, [post, delete, put, get, asyncPost, asyncDelete, asyncPut,asyncGet] + * @param bodyParam, rest body msg + * @return + * @since NFVO 0.5 + */ + @SuppressWarnings("unchecked") + public static RestfulResponse getRestResByDefault(String path, String methodNames, JSONObject bodyParam) { + RestfulParametes restParametes = new RestfulParametes(); + Map<String, String> headerMap = new HashMap<>(2); + headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION); + restParametes.setHeaderMap(headerMap); + + if(Constant.GET.equals(methodNames) || Constant.DELETE.equals(methodNames)) { + if(null != bodyParam) { + Map<String, String> vnfparamsMap = new HashMap<>(Constant.DEFAULT_COLLECTION_SIZE); + if(path.contains("?")) { + String[] vnfUtlList = path.split("\\?"); + String[] vnfParams = vnfUtlList[1].split("&"); + int paramsSize = vnfParams.length; + + for(int i = 0; i < paramsSize; i++) { + vnfparamsMap.put(vnfParams[i].split("=")[0], vnfParams[i].split("=")[1]); + } + } + + String vnfParamKey; + Iterator<String> nameItr = bodyParam.keys(); + while(nameItr.hasNext()) { + vnfParamKey = nameItr.next(); + vnfparamsMap.put(vnfParamKey, bodyParam.get(vnfParamKey).toString()); + + } + LOG.warn("method is GET or DEL,and paramsMap = " + vnfparamsMap); + restParametes.setParamMap(vnfparamsMap); + } + } else { + restParametes.setRawData(bodyParam == null ? null : bodyParam.toString()); + } + return getRestRes(methodNames, path, restParametes); + } + + /** + * send restful notification to other module + * + * @param path + * service url + * @param methodName + * [post, delete, put, get, asyncPost, asyncDelete, asyncPut, + * asyncGet] + * @param bodyParam + * rest body msg + */ + public static void sentEvtByRest(String path, String methodName, JSONObject bodyParam) { + RestfulParametes restParametes = new RestfulParametes(); + Map<String, String> headerMap = new HashMap<>(2); + headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION); + restParametes.setHeaderMap(headerMap); + restParametes.setRawData(bodyParam == null ? null : bodyParam.toString()); + getRestRes(methodName, path, restParametes, new AsyncCallback()); + } + + /** + * encapsulate the java reflect exception + * + * @param methodName + * Restful's method + * @param objects + * method param array + * @return + */ + private static boolean isAnyNull(Object... objects) { + for(int i = 0; i < objects.length; i++) { + if(objects[i] == null) { + return true; + } + } + return false; + + } + + private static Class<?>[] formArray(Object[] objects) { + Class<?>[] vnfClasses = new Class[objects.length]; + for(int i = 0; i < objects.length; i++) { + vnfClasses[i] = objects[i].getClass(); + } + return vnfClasses; + + } + + /** + * + * Get restful resource.<br> + * + * @param methodName + * @param objects + * @return + * @since NFVO 0.5 + */ + public static RestfulResponse getRestRes(String methodName, Object... objects) { + Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP); + try { + if(isAnyNull(objects, rest)) { + return null; + } + + Class<?>[] vnfClasses = formArray(objects); + + if(methodName.startsWith("async")) { + vnfClasses[vnfClasses.length - 1] = RestfulAsyncCallback.class; + } + + Class<?> rtType = methodName.startsWith("async") ? void.class : RestfulResponse.class; + MethodType mt = MethodType.methodType(rtType, vnfClasses); + Object reuslt = MethodHandles.lookup().findVirtual(rest.getClass(), methodName, mt).bindTo(rest) + .invokeWithArguments(objects); + if(reuslt != null) { + return (RestfulResponse)reuslt; + } + LOG.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.", methodName); + return null; + } catch(ReflectiveOperationException e) { + LOG.error("function=getRestRes, msg=error occurs, e={}.", e); + } catch(ServiceException e) { + + LOG.error("function=getRestRes, msg=ServiceException occurs, status={}", e.getHttpCode()); + LOG.error("function=getRestRes, msg=ServiceException occurs, reason={}.", e.getCause().getMessage()); + LOG.error("function=getRestRes, msg=ServiceException occurs, e={}.", e); + RestfulResponse response = new RestfulResponse(); + response.setStatus(e.getHttpCode()); + response.setResponseJson(e.getCause().getMessage()); + return response; + + } catch(Throwable e) {//NOSONAR + try { + throw (VnfmException)new VnfmException().initCause(e.getCause()); + } catch(VnfmException e1) { + LOG.error("function=getRestRes, msg=VnfmException occurs, e={},e1={}.", e1, e); + } + + } + return null; + } + + /** + * + * Send request to application.<br> + * + * @param path + * @param methodName + * @param paraJson + * @return + * @since NFVO 0.5 + */ + public static JSONObject sendReqToApp(String path, String methodName, JSONObject paraJson) { + JSONObject retJson = new JSONObject(); + retJson.put(Constant.RETURN_CODE, Constant.REST_FAIL); + String abPath = null; + String vnfmId = null; + if(paraJson != null && paraJson.containsKey("vnfmInfo")) { + JSONObject vnfmObj = paraJson.getJSONObject("vnfmInfo"); + vnfmId = vnfmObj.getString("id"); + } else { + abPath = path; + } + LOG.warn("function=sendReqToApp, msg=url to send to app is: " + abPath); + + RestfulResponse restfulResponse = VNFRestfulUtil.getRestResByDefault(path, methodName, paraJson); + if(restfulResponse == null || abPath == null) { + LOG.error("function=sendReqToApp, msg=data from app is null"); + retJson.put("data", "get null result"); + } else if(restfulResponse.getStatus() == Constant.HTTP_OK) { + JSONObject object = JSONObject.fromObject(restfulResponse.getResponseContent()); + if(!abPath.contains("vnfdmgr/v1")) { + LOG.warn("function=sendReqToApp, msg=result from app is: " + object.toString()); + } + if(object.getInt(Constant.RETURN_CODE) == Constant.REST_SUCCESS) { + retJson.put(Constant.RETURN_CODE, Constant.REST_SUCCESS); + retJson.put("data", withVnfmIdSuffix(vnfmId, object.get("data"))); + return retJson; + } else { + retJson.put(Constant.RETURN_CODE, Constant.REST_FAIL); + if(object.containsKey("msg")) { + retJson.put("data", object.getString("msg")); + return retJson; + } else { + return object; + } + } + } else { + LOG.error("function=sendReqToApp, msg=status from app is: " + restfulResponse.getStatus()); + LOG.error("function=sendReqToApp, msg=result from app is: " + restfulResponse.getResponseContent()); + retJson.put("data", "send to app get error status: " + restfulResponse.getStatus()); + } + return retJson; + } + + /** + * append suffix to result with vnfmId + * + * @param vnfmId + * @param dataJson + * @return + */ + private static Object withVnfmIdSuffix(String vnfmId, Object dataJson) { + Object result = new Object(); + if(vnfmId == null) { + return dataJson; + } + + if(dataJson instanceof JSONObject) { + JSONObject jsonObject = (JSONObject)dataJson; + jsonObject.put("vnfmId", vnfmId); + result = jsonObject; + } else if(dataJson instanceof JSONArray) { + JSONArray dataArray = (JSONArray)dataJson; + JSONArray resultArray = new JSONArray(); + + for(Object obj : dataArray) { + JSONObject jsonObject = JSONObject.fromObject(obj); + jsonObject.put("vnfmId", vnfmId); + resultArray.add(jsonObject); + } + result = resultArray; + } + return result; + } + + /** + * + * Get remote response.<br> + * + * @param paramsMap + * @param params + * @param domainTokens + * @param isNfvoApp + * @return + * @since NFVO 0.5 + */ + public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params, String domainTokens, + boolean isNfvoApp) { + String utilUrl = paramsMap.get("url"); + String utilMethodType = paramsMap.get(Constant.METHOD_TYPE); + String utilPath = paramsMap.get("path"); + String authMode = paramsMap.get(Constant.AUTH_MODE); + + RestfulResponse rsp = null; + Restful rest = null; + String sslOptionFile = ""; + try { + String restClientFile = "restclient.json"; + + if(isNfvoApp) { + sslOptionFile = "ssl.nfvo.properties"; + } else { + sslOptionFile = "ssl.vcmm.properties"; + } + + LOG.warn("function=getRemoteResponse,AuthenticationMode=" + authMode); + + rest = HttpRestfulHelp.getRestInstance(sslOptionFile, restClientFile); + + RestfulOptions opt = new RestfulOptions(); + String[] strs = utilPath.split("(http(s)?://)|:"); + + opt.setHost(strs[1]); + opt.setPort(Integer.parseInt(strs[2])); + + RestfulParametes restfulParametes = new RestfulParametes(); + Map<String, String> headerMap = new HashMap<>(3); + headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION); + headerMap.put(Constant.HEADER_AUTH_TOKEN, domainTokens); + restfulParametes.setHeaderMap(headerMap); + restfulParametes.setRawData(params); + + if(rest != null) { + if(TYPE_GET.equalsIgnoreCase(utilMethodType)) { + rsp = rest.get(utilUrl, restfulParametes, opt); + } else if(TYPE_POST.equalsIgnoreCase(utilMethodType)) { + rsp = rest.post(utilUrl, restfulParametes, opt); + } else if(TYPE_PUT.equalsIgnoreCase(utilMethodType)) { + rsp = rest.put(utilUrl, restfulParametes, opt); + } else if(TYPE_DEL.equalsIgnoreCase(utilMethodType)) { + rsp = rest.delete(utilUrl, restfulParametes, opt); + } + } + } catch(ServiceException e) { + LOG.error("function=restfulResponse, get restful response catch exception {}", e); + } + return rsp; + } + + /** + * + * Generate parameters map.<br> + * + * @param url + * @param methodType + * @param path + * @param authMode + * @return + * @since NFVO 0.5 + */ + public static Map<String, String> generateParamsMap(String url, String methodType, String path, String authMode) { + Map<String, String> utilParamsMap = new HashMap<>(6); + utilParamsMap.put("url", url); + utilParamsMap.put("methodType", methodType); + utilParamsMap.put("path", path); + utilParamsMap.put("authMode", authMode); + return utilParamsMap; + } + + /** + * + * Generate parameters map.<br> + * + * @param url + * @param methodType + * @param path + * @return + * @since NFVO 0.5 + */ + public static Map<String, String> generateParamsMap(String url, String methodType, String path) { + Map<String, String> paramsMap = new HashMap<>(6); + paramsMap.put("url", url); + paramsMap.put("methodType", methodType); + paramsMap.put("path", path); + paramsMap.put("authMode", "Certificate"); + return paramsMap; + } + + /** + * + * Get result to vnfm.<br> + * + * @param vnfmInfo + * @param vnfmId + * @return + * @since NFVO 0.5 + */ + public static JSONObject getResultToVnfm(JSONObject vnfmInfo, String vnfmId) { + JSONObject retJson = new JSONObject(); + retJson.put(Constant.RETURN_CODE, Constant.REST_FAIL); + if(vnfmInfo == null) { + LOG.error("function=getResultToVnfm, msg=data from vnfm is null"); + retJson.put("data", "get null result"); + return retJson; + } + + if(vnfmInfo.getInt(Constant.RETURN_CODE) == Constant.REST_SUCCESS) { + retJson.put(Constant.RETURN_CODE, Constant.REST_SUCCESS); + retJson.put("data", withVnfmIdSuffix(vnfmId, vnfmInfo.get("data"))); + return retJson; + } else { + retJson.put(Constant.RETURN_CODE, Constant.REST_FAIL); + if(vnfmInfo.containsKey("msg")) { + retJson.put("data", vnfmInfo.getString("msg")); + return retJson; + } else { + return vnfmInfo; + } + } + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/servicetoken/VnfmRestfulUtil.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/servicetoken/VnfmRestfulUtil.java new file mode 100644 index 0000000..3e3f793 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/servicetoken/VnfmRestfulUtil.java @@ -0,0 +1,401 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common.servicetoken; + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.baseservice.roa.util.restclient.Restful; +import org.openo.baseservice.roa.util.restclient.RestfulAsyncCallback; +import org.openo.baseservice.roa.util.restclient.RestfulFactory; +import org.openo.baseservice.roa.util.restclient.RestfulOptions; +import org.openo.baseservice.roa.util.restclient.RestfulParametes; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.jujuvnfmadapter.common.EntityUtils; +import org.openo.nfvo.jujuvnfmadapter.common.VnfmException; +import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; + +/** + * <br> + * <p> + * </p> + * + * @author + */ +public final class VnfmRestfulUtil { + + public static final String TYPE_GET = "get"; + + public static final String TYPE_ADD = "add"; + + public static final String TYPE_POST = "post"; + + public static final String TYPE_PUT = "put"; + + public static final String TYPE_DEL = "delete"; + + public static final int ERROR_STATUS_CODE = -1; + + private static final Logger LOG = LoggerFactory.getLogger(VnfmRestfulUtil.class); + + /** + * Constructor<br/> + * <p> + * </p> + * + */ + private VnfmRestfulUtil() { + // Default Constructor + } + + /** + * within our module, we support a default method to invoke + * + * @param path + * rest service url + * @param methodNames + * [post, delete, put, get, asyncPost, asyncDelete, asyncPut, + * asyncGet] + * @param bodyParam + * rest body msg + * @return + */ + @SuppressWarnings("unchecked") + public static RestfulResponse getRestResByDefault(String path, String methodNames, JSONObject bodyParam) { + RestfulParametes restParametes = new RestfulParametes(); + Map<String, String> headerMap = new HashMap<>(2); + headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION); + restParametes.setHeaderMap(headerMap); + + if(Constant.GET.equals(methodNames) || Constant.DELETE.equals(methodNames)) { + if(null != bodyParam) { + Map<String, String> vnfParamsMap = new HashMap<>(Constant.DEFAULT_COLLECTION_SIZE); + if(path.contains("?")) { + String[] vnfUtlList = path.split("\\?"); + String[] vnfParams = vnfUtlList[1].split("&"); + int paramsSize = vnfParams.length; + + for(int i = 0; i < paramsSize; i++) { + vnfParamsMap.put(vnfParams[i].split("=")[0], vnfParams[i].split("=")[1]); + } + } + + String vnfParamKey = null; + Iterator<String> nameItr = bodyParam.keys(); + while(nameItr.hasNext()) { + vnfParamKey = nameItr.next(); + vnfParamsMap.put(vnfParamKey, bodyParam.get(vnfParamKey).toString()); + + } + LOG.warn("method is GET or DEL,and paramsMap = " + vnfParamsMap); + restParametes.setParamMap(vnfParamsMap); + } + } else { + restParametes.setRawData(bodyParam == null ? null : bodyParam.toString()); + } + return getRestRes(methodNames, path, restParametes); + } + + /** + * encapsulate the java reflect exception + * + * @param objects + * method param array + * @return + */ + private static boolean isAnyNull(Object... objects) { + for(int i = 0; i < objects.length; i++) { + if(objects[i] == null) { + return true; + } + } + return false; + + } + + private static Class<?>[] formArray(Object[] objects) { + Class<?>[] vnfclasses = new Class[objects.length]; + for(int i = 0; i < objects.length; i++) { + vnfclasses[i] = objects[i].getClass(); + } + return vnfclasses; + + } + + /** + * <br> + * + * @param methodName + * @param objects + * @return + */ + public static RestfulResponse getRestRes(String methodName, Object... objects) { + Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP); + try { + if(isAnyNull(objects, rest)) { + return null; + } + + Class<?>[] vnfClasses = formArray(objects); + + if(methodName.startsWith("async")) { + vnfClasses[vnfClasses.length - 1] = RestfulAsyncCallback.class; + } + + Class<?> rtType = methodName.startsWith("async") ? void.class : RestfulResponse.class; + MethodType mt = MethodType.methodType(rtType, vnfClasses); + Object reuslt = MethodHandles.lookup().findVirtual(rest.getClass(), methodName, mt).bindTo(rest) + .invokeWithArguments(objects); + if(reuslt != null) { + return (RestfulResponse)reuslt; + } + LOG.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.", methodName); + return null; + } catch(ReflectiveOperationException e) { + LOG.error("function=getRestRes, msg=error occurs, e={}.", e); + } catch(ServiceException e) { + + LOG.error("function=getRestRes, msg=ServiceException occurs, status={}", e.getHttpCode()); + LOG.error("function=getRestRes, msg=ServiceException occurs, reason={}.", e.getCause().getMessage()); + LOG.error("function=getRestRes, msg=ServiceException occurs, e={}.", e); + RestfulResponse response = new RestfulResponse(); + response.setStatus(e.getHttpCode()); + response.setResponseJson(e.getCause().getMessage()); + return response; + + } catch(Throwable e) {//NOSONAR + try { + throw (VnfmException)new VnfmException().initCause(e.getCause()); + } catch(VnfmException e1) { + LOG.error("function=getRestRes, msg=VnfmException occurs, e={},e1={}.", e1, e); + } + + } + return null; + } + + /** + * <br> + * + * @param path + * @param methodName + * @param paraJson + * @return + */ + public static JSONObject sendReqToApp(String path, String methodName, JSONObject paraJson) { + JSONObject retJson = new JSONObject(); + retJson.put(Constant.RETURN_CODE, Constant.REST_FAIL); + String abPath = null; + String vnfmId = null; + if(paraJson != null && paraJson.containsKey("vnfmInfo")) { + JSONObject vnfmObj = paraJson.getJSONObject("vnfmInfo"); + vnfmId = vnfmObj.getString("id"); + } else { + abPath = path; + } + LOG.warn("function=sendReqToApp, msg=url to send to app is: " + abPath); + + RestfulResponse restfulResponse = VnfmRestfulUtil.getRestResByDefault(path, methodName, paraJson); + if(restfulResponse == null || abPath == null) { + LOG.error("function=sendReqToApp, msg=data from app is null"); + retJson.put("data", "get null result"); + } else if(restfulResponse.getStatus() == Constant.HTTP_OK) { + JSONObject object = JSONObject.fromObject(restfulResponse.getResponseContent()); + if(!abPath.contains("vnfdmgr/v1")) { + LOG.warn("function=sendReqToApp, msg=result from app is: " + object.toString()); + } + if(object.getInt(Constant.RETURN_CODE) == Constant.REST_SUCCESS) { + retJson.put(Constant.RETURN_CODE, Constant.REST_SUCCESS); + retJson.put("data", withVnfmIdSuffix(vnfmId, object.get("data"))); + return retJson; + } else { + retJson.put(Constant.RETURN_CODE, Constant.REST_FAIL); + if(object.containsKey("msg")) { + retJson.put("data", object.getString("msg")); + return retJson; + } else { + return object; + } + } + } else { + LOG.error("function=sendReqToApp, msg=status from app is: " + restfulResponse.getStatus()); + LOG.error("function=sendReqToApp, msg=result from app is: " + restfulResponse.getResponseContent()); + retJson.put("data", "send to app get error status: " + restfulResponse.getStatus()); + } + return retJson; + } + + /** + * append suffix to result with vnfmId + * + * @param vnfmId + * @param dataJson + * @return + */ + private static Object withVnfmIdSuffix(String vnfmId, Object dataJson) { + Object result = new Object(); + if(vnfmId == null) { + return dataJson; + } + + if(dataJson instanceof JSONObject) { + JSONObject jsonObject = (JSONObject)dataJson; + jsonObject.put("vnfmId", vnfmId); + result = jsonObject; + } else if(dataJson instanceof JSONArray) { + JSONArray dataArray = (JSONArray)dataJson; + JSONArray resultArray = new JSONArray(); + + for(Object obj : dataArray) { + JSONObject jsonObject = JSONObject.fromObject(obj); + jsonObject.put("vnfmId", vnfmId); + resultArray.add(jsonObject); + } + result = resultArray; + } + return result; + } + /** + * + * Method to get Remote Response.<br/> + * + * @param paramsMap + * @param params + * @param domainTokens + * @param isHttps + * @return + * @since NFVO 0.5 + */ + public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params, String domainTokens) { + String path = paramsMap.get("path"); + String methodType = paramsMap.get(Constant.METHOD_TYPE); + String url = paramsMap.get("url"); + + RestfulResponse rsp = null; + Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP); + try { + + RestfulOptions opt = new RestfulOptions(); + String[] strs = url.split("(http(s)?://)|:|/"); + + opt.setHost(strs[1]); + if(strs.length > 0){ + opt.setPort(Integer.parseInt(strs[2])); + }else{ + opt.setPort(80); + } + + for(int i=strs.length-1;i>=0;i--){ + if(i > 2){ + path = "/"+strs[i]+path; + } + } + LOG.info("restfull options:"+EntityUtils.toString(opt, RestfulOptions.class)); + RestfulParametes restfulParametes = new RestfulParametes(); + Map<String, String> headerMap = new HashMap<>(3); + headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION); + headerMap.put(Constant.HEADER_AUTH_TOKEN, domainTokens); + restfulParametes.setHeaderMap(headerMap); + restfulParametes.setRawData(params); + + if(rest != null) { + if(TYPE_GET.equalsIgnoreCase(methodType)) { + rsp = rest.get(path, restfulParametes, opt); + } else if(TYPE_POST.equalsIgnoreCase(methodType)) { + rsp = rest.post(path, restfulParametes, opt); + } else if(TYPE_PUT.equalsIgnoreCase(methodType)) { + rsp = rest.put(path, restfulParametes, opt); + } else if(TYPE_DEL.equalsIgnoreCase(methodType)) { + rsp = rest.delete(path, restfulParametes, opt); + } + } + } catch(ServiceException e) { + LOG.error("function=getRemoteResponse, get restful response catch exception {}", e); + } + LOG.info("request :{},response:{}",params,EntityUtils.toString(rsp, RestfulResponse.class)); + return rsp; + } + + + /** + * read DEFAULT config + * <br/> + * + * @param url + * @param methodType + * @param params + * @return + * @since NFVO 0.5 + */ + public static RestfulResponse getRemoteResponse(String url, String methodType, String params) { + RestfulResponse rsp = null; + Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP); + try { + + RestfulParametes restfulParametes = new RestfulParametes(); + Map<String, String> headerMap = new HashMap<>(3); + headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION); + restfulParametes.setHeaderMap(headerMap); + if(params != null) { + restfulParametes.setRawData(params); + } + + if(rest != null) { + if(TYPE_GET.equalsIgnoreCase(methodType)) { + rsp = rest.get(url, restfulParametes); + } else if(TYPE_POST.equalsIgnoreCase(methodType)) { + rsp = rest.post(url, restfulParametes); + } else if(TYPE_PUT.equalsIgnoreCase(methodType)) { + rsp = rest.put(url, restfulParametes); + } else if(TYPE_DEL.equalsIgnoreCase(methodType)) { + rsp = rest.delete(url, restfulParametes); + } + } + } catch(ServiceException e) { + LOG.error("function=getRemoteResponse, get restful response catch exception {}", e); + } + return rsp; + } + + /** + * <br> + * + * @param url + * @param methodType + * @param path + * @param authMode + * @return Map<String, String> + */ + public static Map<String, String> generateParamsMap(String url, String methodType, String path, String authMode) { + Map<String, String> utilParamsMap = new HashMap<>(6); + utilParamsMap.put("url", url); + utilParamsMap.put(Constant.METHOD_TYPE, methodType); + utilParamsMap.put("path", path); + utilParamsMap.put("authMode", authMode); + return utilParamsMap; + } + +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/servicetoken/module/AccessTokens.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/servicetoken/module/AccessTokens.java new file mode 100644 index 0000000..edbfd05 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/common/servicetoken/module/AccessTokens.java @@ -0,0 +1,136 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.common.servicetoken.module; + +import net.sf.json.JSONObject; + +import org.apache.commons.lang3.StringUtils; +import org.openo.nfvo.jujuvnfmadapter.common.VNFJsonUtil; + +/** + * + * Access tokens class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public class AccessTokens { + + private String accesTokens; + + private int expire; + + private long createTime; + + /** + * + * Constructor<br> + * <p> + * </p> + * + * @since NFVO 0.5 + */ + public AccessTokens() { + throw new UnsupportedOperationException(); + } + + /** + * + * Constructor<br> + * <p> + * </p> + * + * @param token + * @param ttl + * @since NFVO 0.5 + */ + public AccessTokens(String token, int ttl) { + this.accesTokens = token; + this.expire = ttl; + this.createTime = System.currentTimeMillis(); + } + + /** + * + * Constructor<br> + * <p> + * </p> + * + * @param accessToken + * @param expire + * @param createTime + * @since NFVO 0.5 + */ + public AccessTokens(String accessToken, Integer expire, Long createTime) { + this.accesTokens = accessToken; + this.expire = expire == null ? 0 : expire; + this.createTime = createTime == null ? 0 : createTime; + } + + public String getAccessToken() { + return this.accesTokens; + } + + public void setAccessToken(String token) { + this.accesTokens = token; + } + + public int getExpire() { + return this.expire; + } + + public long getCreateTime() { + return this.createTime; + } + + /** + * + * Check time validity.<br> + * + * @return + * @since NFVO 0.5 + */ + public boolean valid() { + if(this.expire == 0) { + return true; + } + return System.currentTimeMillis() - this.createTime <= 1000L * this.expire; + } + + @Override + public String toString() { + return '{'+ StringUtils.trimToEmpty(this.getAccessToken()) + '\'' + ",'expire': '" + this.getExpire() + '\'' + + ",'createTime': '" + this.getCreateTime() + '\'' + '}'; + } + + /** + * + * To entity.<br> + * + * @param jsonObject + * @return + * @since NFVO 0.5 + */ + public static AccessTokens toEntity(JSONObject jsonObject) { + String token = VNFJsonUtil.getJsonFieldStr(jsonObject, "accessToken"); + Integer expire = VNFJsonUtil.getJsonFieldInt(jsonObject, "expire"); + Long createTime = VNFJsonUtil.getJsonFieldLong(jsonObject, "createTime"); + return new AccessTokens(token, expire, createTime); + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/activator/ROAJujuServicePostProcessor.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/activator/ROAJujuServicePostProcessor.java new file mode 100644 index 0000000..3013150 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/activator/ROAJujuServicePostProcessor.java @@ -0,0 +1,61 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.activator; + +import org.openo.nfvo.jujuvnfmadapter.service.api.internalsvc.inf.IJujuAdapterMgrService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor; +import org.springframework.stereotype.Service; + +/** + * + * ROA juju service post processor class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public class ROAJujuServicePostProcessor implements DestructionAwareBeanPostProcessor{ + private static final Logger LOG = LoggerFactory.getLogger(ROAJujuServicePostProcessor.class); + + @Override + public Object postProcessAfterInitialization(Object bean, String name) throws BeansException { + if(bean instanceof IJujuAdapterMgrService){ + IJujuAdapterMgrService jujuAdapterSvc = (IJujuAdapterMgrService)bean; + jujuAdapterSvc.register(); + LOG.info("Successfully Registered to Microservice BUS!", ROAJujuServicePostProcessor.class); + } + + return bean; + } + + @Override + public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException { + // TODO Auto-generated method stub + return bean; + } + + @Override + public void postProcessBeforeDestruction(Object bean, String name) throws BeansException { + // TODO Auto-generated method stub + + } + +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/impl/AdapterResourceManager.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/impl/AdapterResourceManager.java new file mode 100644 index 0000000..5dc8184 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/impl/AdapterResourceManager.java @@ -0,0 +1,302 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.adapter.impl; + +import java.io.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.baseservice.util.impl.SystemEnvVariablesFactory; +import org.openo.nfvo.jujuvnfmadapter.common.DownloadCsarManager; +import org.openo.nfvo.jujuvnfmadapter.common.EntityUtils; +import org.openo.nfvo.jujuvnfmadapter.common.servicetoken.JujuVnfmRestfulUtil; +import org.openo.nfvo.jujuvnfmadapter.service.adapter.inf.IResourceManager; +import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant; +import org.openo.nfvo.jujuvnfmadapter.service.constant.UrlConstant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import net.sf.json.JSONObject; + +/** + * + * Adapter resource manager class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +@Service +public class AdapterResourceManager implements IResourceManager { + + private static final Logger LOG = LoggerFactory.getLogger(AdapterResourceManager.class); + + + @Override + public JSONObject getJujuVnfmInfo(Map<String, String> paramsMap) { + JSONObject resultObj = new JSONObject(); + //verify url,reserve + + RestfulResponse rsp = JujuVnfmRestfulUtil.getRemoteResponse(paramsMap,""); + if(null == rsp) { + LOG.error("function=getJujuVnfmInfo, RestfulResponse is null"); + resultObj.put(Constant.REASON, "RestfulResponse is null."); + resultObj.put(Constant.RETURN_CODE, Constant.ERROR_STATUS_CODE); + return resultObj; + } + String resultCreate = rsp.getResponseContent(); + + if(rsp.getStatus() == Constant.HTTP_OK) { + LOG.warn("function=getJujuVnfmInfo, msg= status={}, result={}.", rsp.getStatus(), resultCreate); + resultObj = JSONObject.fromObject(resultCreate); + resultObj.put(Constant.RETURN_CODE, Constant.HTTP_OK); + return resultObj; + } else { + LOG.error("function=getJujuVnfmInfo, msg=ESR return fail,status={}, result={}.", rsp.getStatus(), + resultCreate); + resultObj.put(Constant.REASON, "ESR return fail."); + } + resultObj.put(Constant.RETURN_CODE, Constant.ERROR_STATUS_CODE); + return resultObj; + } + + @Override + public JSONObject getVnfdInfo(String csarId) { + JSONObject resultObj = new JSONObject(); + JSONObject csarPkgInfoObj = new JSONObject(); + + if(null == csarId || "".equals(csarId)) { + resultObj.put("reason", "csarId is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + String downloadUri = this.fetchDownloadUrlFromCatalog(csarId); + if(downloadUri == null){ + LOG.error("fetchDownloadUrlFromCatalog return null,csarId="+csarId); + resultObj.put(Constant.REASON, "fetchDownloadUrlFromCatalog is null."); + resultObj.put(Constant.RETURN_CODE, Constant.ERROR_STATUS_CODE); + return resultObj; + } + String csarPkgInfo; + try { + csarPkgInfo = readCsarPkgInfo(); + csarPkgInfoObj = JSONObject.fromObject(csarPkgInfo); //NOSONAR + } catch (IOException e) { + e.printStackTrace(); + } + + String csarfilepath = csarPkgInfoObj.getString("csar_file_path"); + String csarfilename = csarPkgInfoObj.getString("csar_file_name"); + + // download csar package and save in location. + JSONObject downloadObject = downloadCsar(downloadUri, csarfilepath+ System.getProperty("file.separator") +csarfilename); + + if (Integer.valueOf(downloadObject.get("retCode").toString()) != Constant.REST_SUCCESS) { + LOG.error("download CSAR fail.", downloadObject.get("retCode")); + resultObj.put("reason", downloadObject.get("reason").toString()); + resultObj.put("retCode", downloadObject.get("retCode").toString()); + return resultObj; + } + LOG.info("download CSAR successful.", downloadObject.get("retCode")); + + // unzip csar package to location. + JSONObject unzipObject = unzipCSAR(csarfilepath+ System.getProperty("file.separator") +csarfilename, csarfilepath); + + if (Integer.valueOf(unzipObject.get("retCode").toString()) != Constant.REST_SUCCESS) { + LOG.error("unzip CSAR fail.", unzipObject.get("retCode")); + resultObj.put("reason", unzipObject.get("reason").toString()); + resultObj.put("retCode", unzipObject.get("retCode").toString()); + return resultObj; + } + LOG.info("unzip CSAR successful.", unzipObject.get("retCode")); + + resultObj.put(Constant.RETURN_CODE, Constant.HTTP_OK); + resultObj.put("csarFilePath", getImagesPath(csarfilepath)); + + return resultObj; + } + private String getImagesPath(String csarfilepath){ + File imageFile = new File(csarfilepath+"SoftwareImages"); + if(imageFile.exists()){ + File[] charmFiles = imageFile.listFiles(); + for(File file : charmFiles){ + if(!file.getName().endsWith(".zip")){ + return file.getAbsolutePath()+"/"; + } + } + } + return csarfilepath; + } + + public String fetchDownloadUrlFromCatalog(String csarId){ + String downloadUri = null; + try { + Map paramsMap = new HashMap(); + + paramsMap.put("url", String.format(UrlConstant.REST_CSARINFO_GET, csarId)); + paramsMap.put("methodType", Constant.GET); + + RestfulResponse rsp = JujuVnfmRestfulUtil.getRemoteResponse(paramsMap,""); + if(null == rsp) { + LOG.error("function=getVnfdInfo, RestfulResponse is null"); + return null; + } + String resultCreate = rsp.getResponseContent(); + + if(rsp.getStatus() != Constant.HTTP_OK) { + LOG.error("function=getVnfdInfo, msg=catalog return fail,status={}, result={}.", rsp.getStatus(), + resultCreate); + return null; + } + JSONObject csarObj = JSONObject.fromObject(resultCreate); + downloadUri = csarObj.getString("downloadUri"); + } catch (Exception e) { + LOG.error("fetchDownloadUrlFromCatalog error",e); + } + return downloadUri; + } + + /** + * Get csar package information.<br> + * + * @return + * @throws IOException + * @since NFVO 0.5 + */ + public static String readCsarPkgInfo() throws IOException { + InputStream ins = null; + BufferedInputStream bins = null; + String fileContent = ""; + + String fileName = SystemEnvVariablesFactory.getInstance().getAppRoot() + System.getProperty("file.separator") + + "etc" + System.getProperty("file.separator") + "csarInfo" + System.getProperty("file.separator") + + Constant.CSARINFO; + + try { + ins = new FileInputStream(fileName); + bins = new BufferedInputStream(ins); + + byte[] contentByte = new byte[ins.available()]; + int num = bins.read(contentByte); + + if (num > 0) { + fileContent = new String(contentByte); + } + } catch (FileNotFoundException e) { + LOG.error(fileName + "is not found!", e); + } finally { + if (ins != null) { + ins.close(); + } + if (bins != null) { + bins.close(); + } + } + return fileContent; + } + + /** + * download CSAR.<br> + * @return + * @throws IOException + * @since NFVO 0.5 + */ + public JSONObject downloadCsar(String url, String filePath) { + JSONObject resultObj = new JSONObject(); + + if(url == null || "".equals(url)) { + resultObj.put("reason", "url is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + if(filePath == null || "".equals(filePath)) { + resultObj.put("reason", "downloadUrl filePath is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + + String status = DownloadCsarManager.download(url, filePath); + + if (Constant.DOWNLOADCSAR_SUCCESS.equals(status)) { + resultObj.put("reason", "download csar file successfully."); + resultObj.put("retCode", Constant.REST_SUCCESS); + } else { + resultObj.put("reason", "download csar file failed."); + resultObj.put("retCode", Constant.REST_FAIL); + } + return resultObj; + } + + /* + * unzip CSAR packge + * @param fileName filePath + * @return + */ + public JSONObject unzipCSAR(String fileName,String filePath) { + JSONObject resultObj = new JSONObject(); + + if(fileName == null || "".equals(fileName)) { + resultObj.put("reason", "fileName is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + if(filePath == null || "".equals(filePath)) { + resultObj.put("reason", "unzipCSAR filePath is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + + int status = DownloadCsarManager.unzipCSAR(fileName, filePath); + + + if (Constant.UNZIP_SUCCESS == status) { + resultObj.put("reason", "unzip csar file successfully."); + resultObj.put("retCode", Constant.REST_SUCCESS); + chmodToFiles(filePath); + } else { + resultObj.put("reason", "unzip csar file failed."); + resultObj.put("retCode", Constant.REST_FAIL); + } + return resultObj; + } + + + +private void chmodToFiles(String filePath) { + try { + List<String> commands = new ArrayList<String>(); + commands.add("chmod"); + commands.add("-R"); + commands.add("777"); + commands.add(filePath); + EntityUtils.ExeRes exeRes = EntityUtils.execute(null, commands); + if (exeRes.getCode() == EntityUtils.ExeRes.SUCCESS) { + LOG.info("chmod success:" + EntityUtils.formatCommand(commands)); + } else { + LOG.error("dchmod fail" + EntityUtils.formatCommand(commands) + "\n" + exeRes); + } + } catch (Exception e) { + LOG.error("chmod error:",e); + } +} +} + diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/impl/JujuAdapter2DriverManager.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/impl/JujuAdapter2DriverManager.java new file mode 100644 index 0000000..a9680ff --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/impl/JujuAdapter2DriverManager.java @@ -0,0 +1,111 @@ +/* + * Copyright 2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.adapter.impl; + +import net.sf.json.JSONObject; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.jujuvnfmadapter.common.servicetoken.JujuVnfmRestfulUtil; +import org.openo.nfvo.jujuvnfmadapter.service.adapter.inf.IJujuAdapter2DriverManager; +import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Map; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Jan 24, 2017 + */ +public class JujuAdapter2DriverManager implements IJujuAdapter2DriverManager { + + private static final Logger LOG = LoggerFactory.getLogger(JujuAdapter2DriverManager.class); + + @Override + public JSONObject registerDriver(Map<String, String> paramsMap, JSONObject driverInfo) { + JSONObject resultObj = new JSONObject(); + + RestfulResponse rsp = JujuVnfmRestfulUtil.getRemoteResponse(paramsMap, driverInfo.toString()); + if(null == rsp) { + LOG.error("function=registerDriver, RestfulResponse is null"); + resultObj.put("reason", "RestfulResponse is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + String resultCreate = rsp.getResponseContent(); + + if(rsp.getStatus() == Constant.HTTP_CREATED) { + LOG.warn("function=registerDriver, msg= status={}, result={}.", rsp.getStatus(), resultCreate); + resultObj = JSONObject.fromObject(resultCreate); + resultObj.put("retCode", Constant.HTTP_CREATED); + return resultObj; + } else if(rsp.getStatus() == Constant.INVALID_PARAMETERS) { + LOG.error("function=registerDriver, msg=DriverManager return fail,invalid parameters,status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "DriverManager return fail,invalid parameters."); + } else if(rsp.getStatus() == Constant.HTTP_INNERERROR) { + LOG.error( + "function=registerDriver, msg=DriverManager return fail,internal system error,status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "DriverManager return fail,internal system error."); + } + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + + @Override + public JSONObject unregisterDriver(Map<String, String> paramsMap) { + JSONObject resultObj = new JSONObject(); + + RestfulResponse rsp = JujuVnfmRestfulUtil.getRemoteResponse(paramsMap, ""); + if(null == rsp) { + LOG.error("function=unregisterDriver, RestfulResponse is null"); + resultObj.put("reason", "RestfulResponse is null."); + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + String resultCreate = rsp.getResponseContent(); + + if(rsp.getStatus() == Constant.UNREG_SUCCESS) { + LOG.warn("function=unregisterDriver, msg= status={}, result={}.", rsp.getStatus(), resultCreate); + resultObj = JSONObject.fromObject(resultCreate); + resultObj.put("retCode", Constant.UNREG_SUCCESS); + return resultObj; + } else if(rsp.getStatus() == Constant.HTTP_NOTFOUND) { + LOG.error( + "function=unregisterDriver, msg=DriverManager return fail,can't find the service instance.status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "DriverManager return fail,can't find the service instance."); + } else if(rsp.getStatus() == Constant.INVALID_PARAMETERS) { + LOG.error( + "function=unregisterDriver, msg=DriverManager return fail,invalid parameters,status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "DriverManager return fail,invalid parameters."); + } else if(rsp.getStatus() == Constant.HTTP_INNERERROR) { + LOG.error( + "function=unregisterDriver, msg=DriverManager return fail,internal system error,status={}, result={}.", + rsp.getStatus(), resultCreate); + resultObj.put("reason", "DriverManager return fail,internal system error."); + } + resultObj.put("retCode", Constant.REST_FAIL); + return resultObj; + } + +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/impl/JujuAdapter2MSBManager.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/impl/JujuAdapter2MSBManager.java new file mode 100644 index 0000000..0a96792 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/impl/JujuAdapter2MSBManager.java @@ -0,0 +1,110 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.adapter.impl; + +import java.util.Map; + +import org.openo.nfvo.jujuvnfmadapter.common.servicetoken.JujuVnfmRestfulUtil; +import org.openo.nfvo.jujuvnfmadapter.service.adapter.inf.IJujuAdapter2MSBManager; +import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * + * Juju adapter to msb manager class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public class JujuAdapter2MSBManager implements IJujuAdapter2MSBManager { + + private static final Logger LOG = LoggerFactory.getLogger(JujuAdapter2MSBManager.class); + + @Override + public JSONObject registerJujuAdapter(Map<String, String> paramsMap, JSONObject adapterInfo) { + JSONObject resultObj = new JSONObject(); + //verify url,reserve + + RestfulResponse rsp = JujuVnfmRestfulUtil.getRemoteResponse(paramsMap,adapterInfo.toString()); + if(null == rsp) { + LOG.error("function=registerJujuAdapter, RestfulResponse is null"); + resultObj.put(Constant.REASON, "RestfulResponse is null."); + resultObj.put(Constant.RETURN_CODE, Constant.ERROR_STATUS_CODE); + return resultObj; + } + String resultCreate = rsp.getResponseContent(); + + if(rsp.getStatus() == Constant.HTTP_CREATED) { + LOG.warn("function=registerJujuAdapter, msg= status={}, result={}.", rsp.getStatus(), resultCreate); + resultObj = JSONObject.fromObject(resultCreate); + resultObj.put(Constant.RETURN_CODE, Constant.HTTP_CREATED); + return resultObj; + } else if(rsp.getStatus() == Constant.INVALID_PARAMETERS){ + LOG.error("function=registerJujuAdapter, msg=MSB return fail,invalid parameters,status={}, result={}.", rsp.getStatus(), + resultCreate); + resultObj.put(Constant.REASON, "MSB return fail,invalid parameters."); + } else if(rsp.getStatus() == Constant.HTTP_INNERERROR){ + LOG.error("function=registerJujuAdapter, msg=MSB return fail,internal system error,status={}, result={}.", rsp.getStatus(), + resultCreate); + resultObj.put(Constant.REASON, "MSB return fail,internal system error."); + } + resultObj.put(Constant.RETURN_CODE, Constant.ERROR_STATUS_CODE); + return resultObj; + } + + @Override + public JSONObject unregisterJujuAdapter(Map<String, String> paramsMap) { + JSONObject resultObj = new JSONObject(); + //verify url,reserve + + RestfulResponse rsp = JujuVnfmRestfulUtil.getRemoteResponse(paramsMap,""); + if(null == rsp) { + LOG.error("function=unregisterJujuAdapter, RestfulResponse is null"); + resultObj.put(Constant.REASON, "RestfulResponse is null."); + resultObj.put(Constant.RETURN_CODE, Constant.ERROR_STATUS_CODE); + return resultObj; + } + String resultCreate = rsp.getResponseContent(); + + if(rsp.getStatus() == Constant.UNREG_SUCCESS) { + LOG.warn("function=unregisterJujuAdapter, msg= status={}, result={}.", rsp.getStatus(), resultCreate); + resultObj = JSONObject.fromObject(resultCreate); + resultObj.put(Constant.RETURN_CODE, Constant.UNREG_SUCCESS); + return resultObj; + } else if(rsp.getStatus() == Constant.HTTP_NOTFOUND){ + LOG.error("function=unregisterJujuAdapter, msg=MSB return fail,can't find the service instance.status={}, result={}.", rsp.getStatus(), + resultCreate); + resultObj.put(Constant.REASON, "MSB return fail,can't find the service instance."); + } else if(rsp.getStatus() == Constant.INVALID_PARAMETERS){ + LOG.error("function=unregisterJujuAdapter, msg=MSB return fail,invalid parameters,status={}, result={}.", rsp.getStatus(), + resultCreate); + resultObj.put(Constant.REASON, "MSB return fail,invalid parameters."); + } else if(rsp.getStatus() == Constant.HTTP_INNERERROR){ + LOG.error("function=unregisterJujuAdapter, msg=MSB return fail,internal system error,status={}, result={}.", rsp.getStatus(), + resultCreate); + resultObj.put(Constant.REASON, "MSB return fail,internal system error."); + } + resultObj.put(Constant.RETURN_CODE, Constant.ERROR_STATUS_CODE); + return resultObj; + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/impl/JujuClientManager.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/impl/JujuClientManager.java new file mode 100644 index 0000000..efd72d6 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/impl/JujuClientManager.java @@ -0,0 +1,449 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.adapter.impl; + +import java.io.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.baseservice.util.impl.SystemEnvVariablesFactory; +import org.openo.nfvo.jujuvnfmadapter.common.EntityUtils; +import org.openo.nfvo.jujuvnfmadapter.common.EntityUtils.ExeRes; +import org.openo.nfvo.jujuvnfmadapter.common.FileUtils; +import org.openo.nfvo.jujuvnfmadapter.common.JujuConfigUtil; +import org.openo.nfvo.jujuvnfmadapter.common.YamlUtil; +import org.openo.nfvo.jujuvnfmadapter.common.servicetoken.VnfmRestfulUtil; +import org.openo.nfvo.jujuvnfmadapter.service.adapter.inf.IJujuClientManager; +import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant; +import org.openo.nfvo.jujuvnfmadapter.service.constant.UrlConstant; +import org.openo.nfvo.jujuvnfmadapter.service.juju.JujuHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSON; +import net.sf.json.JSONObject; + + +/** + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 7, 2016 + */ +public class JujuClientManager implements IJujuClientManager { + private static final Logger LOG = LoggerFactory.getLogger(JujuClientManager.class); + + public static final String ADDRESOURCE="addResource"; + public static final String REMOVERESOURCE = "removeResource"; + + /** + * <br/> + * + * @param charmPath + * @param appName + * @return + * @since NFVO 0.5 + */ + @Override + public JSONObject deploy(String charmPath, String appName) { + JSONObject result = new JSONObject(); + if(charmPath == null || appName == null){ + String msg = "the 'charmPath' or 'appName' can not be null"; + result.put(EntityUtils.RESULT_CODE_KEY, -1); + result.put(EntityUtils.MSG_KEY, msg); + LOG.error(msg); + return result; + } + String modelName = JujuHelper.getModelName(appName); + //add-model + this.addModel(modelName);//use appName as modelName + //switch model + this.switchModel(modelName); + //deploy service + List<String> commands = new ArrayList<>(); + commands.add("juju"); + commands.add("deploy"); + if(StringUtils.isNotBlank(charmPath)){ + String fullPath = charmPath+appName; + commands.add(fullPath); + }else{ + commands.add(appName); + } + commands.add("-m"); + commands.add(modelName); + ExeRes exeRes = EntityUtils.execute(charmPath,commands); + if(exeRes.getCode() == ExeRes.SUCCESS){ + LOG.info("deploy success. command:"+EntityUtils.formatCommand(commands)); + result.put(EntityUtils.RESULT_CODE_KEY, 0); + result.put(EntityUtils.DATA_KEY, exeRes.getBody()); + }else{ + LOG.error("deploy failed. command:"+EntityUtils.formatCommand(commands)+"\n"+exeRes); + result.put(EntityUtils.RESULT_CODE_KEY, -1); + result.put(EntityUtils.MSG_KEY, "deploy failed:"+exeRes.getBody()); + } + + return result; + } + + /** + * + * <br/> + * + * @param modelName + * @return + * @since NFVO 0.5 + */ + private JSONObject addModel(String modelName) { + JSONObject result = new JSONObject(); + List<String> commands = new ArrayList<>(); + commands.add("juju"); + commands.add("add-model"); + commands.add(modelName); + getExtraParam(commands); + ExeRes exeRes = EntityUtils.execute(null,commands); + if(exeRes.getCode() == ExeRes.SUCCESS){ + LOG.info("addModel success. command:"+EntityUtils.formatCommand(commands)); + result.put(EntityUtils.RESULT_CODE_KEY, 0); + result.put(EntityUtils.DATA_KEY, exeRes.getBody()); + }else{ + LOG.error("addModel failed. command:"+EntityUtils.formatCommand(commands)+"\n"+exeRes); + result.put(EntityUtils.RESULT_CODE_KEY, -1); + result.put(EntityUtils.MSG_KEY, "addModel failed:"+exeRes.getBody()); + } + + return result; + } + + /** + * getExtraParam + * add model + juju add-model <model-name> --config image-metadata-url=http://192.168.20.106/images --config network=demo-net --config use-floating-ip=True --config use-default-secgroup=True + * @return + */ + private void getExtraParam(List<String> commands){ + try { + String configInfo = readJujuConfigInfo(); + if(configInfo != null){ + JSONObject json = JSONObject.fromObject(configInfo); + commands.add("--config"); + commands.add("image-metadata-url="+json.getString("image-metadata-url")); + commands.add("--config"); + commands.add("network="+json.getString("network")); + commands.add("--config"); + commands.add("use-floating-ip="+json.getString("use-floating-ip")); + commands.add("--config"); + commands.add("use-default-secgroup="+json.getString("use-default-secgroup")); + } + } catch (Exception e) { + LOG.error("read juju command config error:",e); + } + } + + /** + * Get csar package information.<br> + * + * @return + * @throws IOException + * @since NFVO 0.5 + */ + public static String readJujuConfigInfo() { + InputStream ins = null; + + BufferedInputStream bins = null; + String fileContent = null; + String fileName = SystemEnvVariablesFactory.getInstance().getAppRoot() + System.getProperty("file.separator") + + "etc" + System.getProperty("file.separator") + "conf" + System.getProperty("file.separator") + + "juju_conf.json"; + try { + ins = new FileInputStream(fileName); + bins = new BufferedInputStream(ins); + + byte[] contentByte = new byte[ins.available()]; + int num = bins.read(contentByte); + + if (num > 0) { + fileContent = new String(contentByte); + } + } catch (Exception e) { + LOG.error(fileName + "is not found!", e); + } finally { + try { + if (ins != null) { + ins.close(); + } + if (bins != null) { + bins.close(); + } + } catch (IOException e) { + } + } + return fileContent; + } + private JSONObject changeDir(String charmPath) { + JSONObject result = new JSONObject(); + List<String> commands = new ArrayList<>(); + commands.add("cd"); + commands.add(charmPath); + ExeRes exeRes = EntityUtils.execute(null,commands); + if(exeRes.getCode() == ExeRes.SUCCESS){ + LOG.info("changeDir success. command:"+EntityUtils.formatCommand(commands)); + result.put(EntityUtils.RESULT_CODE_KEY, 0); + result.put(EntityUtils.DATA_KEY, exeRes.getBody()); + }else{ + LOG.error("changeDir failed. command:"+EntityUtils.formatCommand(commands)+"\n"+exeRes); + result.put(EntityUtils.RESULT_CODE_KEY, -1); + result.put(EntityUtils.MSG_KEY, "addModel failed:"+exeRes.getBody()); + } + + return result; + } + + /** + * + * <br/> + * + * @param modelName + * @return + * @since NFVO 0.5 + */ + private JSONObject switchModel(String modelName) { + JSONObject result = new JSONObject(); + List<String> commands = new ArrayList<>(); + commands.add("juju"); + commands.add("switch"); + commands.add(modelName); + ExeRes exeRes = EntityUtils.execute(null,commands); + if(exeRes.getCode() == ExeRes.SUCCESS){ + LOG.info("switchModel success. command:"+EntityUtils.formatCommand(commands)); + result.put(EntityUtils.RESULT_CODE_KEY, 0); + result.put(EntityUtils.DATA_KEY, exeRes.getBody()); + }else{ + LOG.error("switchModel failed. command:"+EntityUtils.formatCommand(commands)+"\n"+exeRes); + result.put(EntityUtils.RESULT_CODE_KEY, -1); + result.put(EntityUtils.MSG_KEY, "addModel failed:"+exeRes.getBody()); + } + + return result; + } + + /** + * <br/> + * + * @param appName + * @return + * @since NFVO 0.5 + */ + @Override + public JSONObject destroy(String appName) { + String modelName = JujuHelper.getModelName(appName); + JSONObject result = new JSONObject(); + List<String> commands = new ArrayList<>(); + commands.add("juju"); + commands.add("destroy-model"); + commands.add("-y"); + commands.add(modelName); + + ExeRes exeRes = EntityUtils.execute(null,commands); + if(exeRes.getCode() == ExeRes.SUCCESS){ + LOG.info("remove success. command:"+EntityUtils.formatCommand(commands)); + result.put(EntityUtils.RESULT_CODE_KEY, 0); + result.put(EntityUtils.DATA_KEY, exeRes.getBody()); + }else{ + LOG.error("remove failed. command:"+EntityUtils.formatCommand(commands)+"\n"+exeRes); + result.put(EntityUtils.RESULT_CODE_KEY, -1); + result.put(EntityUtils.MSG_KEY, "remove failed:"+exeRes.getBody()); + } + + return result; + + } + + /** + * <br/> + * + * @param appName + * @return + * @since NFVO 0.5 + */ + @Override + public JSONObject getStatus(String appName) { + String modelName = JujuHelper.getModelName(appName); + JSONObject result = new JSONObject(); + List<String> commands = new ArrayList<>(); + commands.add("juju"); + commands.add("status"); + if(StringUtils.isNotBlank(modelName)){ + commands.add("-m"); + commands.add(modelName); + } + commands.add("--format=json"); + + ExeRes exeRes = EntityUtils.execute(null,commands); + if(exeRes.getCode() == ExeRes.SUCCESS){ + LOG.info("getStatus success. command:"+EntityUtils.formatCommand(commands)); + result.put(EntityUtils.RESULT_CODE_KEY, 0); + JSONObject dataObj = buildDataObj(exeRes); + result.put(EntityUtils.DATA_KEY, dataObj); + }else{ + LOG.error("getStatus failed. command:"+EntityUtils.formatCommand(commands)+"\n"+exeRes); + result.put(EntityUtils.RESULT_CODE_KEY, -1); + result.put(EntityUtils.MSG_KEY, "getStatus failed:"+exeRes.getBody()); + } + + return result; + } + + /** + * <br/> + * + * @param exeRes + * @return + * @since NFVO 0.5 + */ + private JSONObject buildDataObj(ExeRes exeRes) { + JSONObject dataObj = null; + if(StringUtils.isNotBlank(exeRes.getBody())){ + dataObj = JSONObject.fromObject(exeRes.getBody()); + //according to appName to select + } + return dataObj; + } + + + /** + * call the juju vnfm to grant resource(disk,mem,cpu) + * <br/> + * (fields:cpu,mem,disk,action(addResource/removeResource)) + * @param vnfId + * @param appName + * @param action + * @since NFVO 0.5 + * @return + */ + @Override + public boolean grantResource(String charmPath, String appName,String action , String vnfId){ + //1.parse yaml file + JSONObject params; + try { + params = this.parseYaml(charmPath, appName, action); + } catch(Exception e) { + LOG.error("ParseYaml error,please check it.",e); + return false; + } + if(params == null){ + LOG.error("ParseYaml fail,please check it."); + return false; + } + + //2. call grant service + String url = JujuConfigUtil.getValue("grant_jujuvnfm_url"); + Map<String, String> paramsMap = new HashMap<>(6); + paramsMap.put("url", url); + paramsMap.put(Constant.METHOD_TYPE, Constant.PUT); + paramsMap.put("path", String.format(UrlConstant.REST_JUJU_VNFM_GRANT_URL,vnfId)); + paramsMap.put(Constant.AUTH_MODE, Constant.AuthenticationMode.ANONYMOUS); + RestfulResponse rsp = VnfmRestfulUtil.getRemoteResponse(paramsMap, params.toString(), null); + if(rsp == null || rsp.getStatus() != Constant.HTTP_OK) { + LOG.error("function=grantResource, msg=send grantResource msg to juju-vnfm get wrong results"); + return false; + } + //3.process result + String response = rsp.getResponseContent(); + LOG.info("grant resource result:"+response); + return true; + } + + /** + * + * <br/> + * "constraints":"arch=amd64 cpu-cores=1 cpu-power=100 mem=1740 root-disk=8192" + * @param charmPath + * @param appName + * @param action + * @return + * @since NFVO 0.5 + */ + public JSONObject parseYaml(String charmPath, String appName,String action){ + JSONObject compute = new JSONObject(); + compute.put("action", action); + if(StringUtils.isBlank(charmPath)){ + LOG.error("the charmPath can't be null! [in unzipFileAndParseYaml]"); + return null; + } + //set default values for non 'yaml' type + if(!appName.endsWith(".yaml")){ + compute.put("cpu", 4); + compute.put("mem", 2); + compute.put("disk", 40); + return compute; + } + String yaml = FileUtils.getFriendlyPath(charmPath)+appName; + File yamlFile = new File(yaml); + if(yamlFile.exists()){ + JSON json = YamlUtil.yamlToJson(yamlFile.getAbsolutePath()); + LOG.info(yaml+":\n"+json); + if(json.isArray()){ + LOG.error("the yaml file has error format,please check it!"+yamlFile); + return null; + } + JSONObject jsonObj = (JSONObject)json; + JSONObject services = jsonObj.getJSONObject("services"); + int cpu = 0; + int mem = 0; + int disk = 0; + for(Object key: services.keySet()){ + JSONObject app = services.getJSONObject(key.toString()); + if(app.containsKey("constraints")){ + String constraints = app.getString("constraints"); + String[] vals = constraints.split("\\s+"); + LOG.info(key+"="+constraints); + for(String val : vals){ + String[] kv = val.split("="); + if("cpu-cores".equals(kv[0]) && StringUtils.isNotBlank(kv[1])){ + cpu+=Integer.valueOf(kv[1]); + }else if("mem".equals(kv[0]) && StringUtils.isNotBlank(kv[1])){ + mem+=Integer.valueOf(kv[1]); + }else if("root-disk".equals(kv[0]) && StringUtils.isNotBlank(kv[1])){ + disk+=Integer.valueOf(kv[1]); + } + } + } + } + compute.put("cpu", cpu); + compute.put("mem", mem); + compute.put("disk", disk); + }else{ + LOG.error("the yaml file not exist!file="+yamlFile); + return null; + } + LOG.info("parse yaml result-->"+compute); + return compute; + } + + + public static void main(String[] args) { + JujuClientManager jujuClientManager = new JujuClientManager(); + jujuClientManager.parseYaml("E:/workspace/openo-common-utils/src/org/openo/common/yaml", "test.yaml", "addResource"); + } + +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/inf/IJujuAdapter2DriverManager.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/inf/IJujuAdapter2DriverManager.java new file mode 100644 index 0000000..30f92e4 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/inf/IJujuAdapter2DriverManager.java @@ -0,0 +1,52 @@ +/* + * Copyright 2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.adapter.inf; + +import java.util.Map; + +import net.sf.json.JSONObject; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Jan 24, 2017 + */ +public interface IJujuAdapter2DriverManager { + + /** + * Method to Register Driver.<br/> + * + * @param paramsMap + * @param driverInfo + * @return + * @since NFVO 0.5 + */ + JSONObject registerDriver(Map<String, String> paramsMap, JSONObject driverInfo); + + /** + * Method to Unregister Driver.<br/> + * + * @param paramsMap + * @return + * @since NFVO 0.5 + */ + JSONObject unregisterDriver(Map<String, String> paramsMap); + +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/inf/IJujuAdapter2MSBManager.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/inf/IJujuAdapter2MSBManager.java new file mode 100644 index 0000000..03a9cf7 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/inf/IJujuAdapter2MSBManager.java @@ -0,0 +1,56 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.adapter.inf; + +import java.util.Map; + + +import net.sf.json.JSONObject; + +/** + * + * iJuju adapter to msb manager class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public interface IJujuAdapter2MSBManager{ + + /** + * + * Register juju adapter.<br> + * + * @param paramsMap + * @param driverInfo + * @return + * @since NFVO 0.5 + */ + JSONObject registerJujuAdapter(Map<String,String> paramsMap, JSONObject driverInfo); + + /** + * + * Unregister juju adapter.<br> + * + * @param paramsMap + * @return + * @since NFVO 0.5 + */ + JSONObject unregisterJujuAdapter(Map<String,String> paramsMap); + +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/inf/IJujuClientManager.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/inf/IJujuClientManager.java new file mode 100644 index 0000000..fab61a8 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/inf/IJujuClientManager.java @@ -0,0 +1,84 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.adapter.inf; + +import net.sf.json.JSONObject; + +/** + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 7, 2016 + */ +public interface IJujuClientManager { + + /** + * * deploy juju charm from local filesystem. The charm will get deployed on a trusty instance + * with at least 2 GB RAM + * juju deploy $HOME/charms/example --series trusty --constraints mem=2G --config + * /path/to/custom/charm-config.yaml + * <br/> + * + * @param charmPath + * @param mem (at least 2 GB RAM) unit/GB + * @param appName + * @return + * @since NFVO 0.5 + */ + JSONObject deploy(String charmPath, String appName); + + /** + * * remove a charm completely + * juju remove-application example + * juju destroy-model model-name + * <br/> + * + * @param appName + * @return + * @since NFVO 0.5 + */ + JSONObject destroy(String appName); + + /** + * juju status --format=json + * juju status -m model-name --format=json + * get the status of a single charm + * juju status example --format=json + * Here is an example output from juju status --format=json + * http://paste.ubuntu.com/23113992/ + * <br/> + * + * @param modelName + * @return + * @since NFVO 0.5 + */ + JSONObject getStatus(String modelName); + /** + * + * <br/> + * + * @param charmPath + * @param appName + * @param action + * @param vnfId + * @return + * @since NFVO 0.5 + */ + public boolean grantResource(String charmPath, String appName,String action , String vnfId); +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/inf/IResourceManager.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/inf/IResourceManager.java new file mode 100644 index 0000000..7c05fd3 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/adapter/inf/IResourceManager.java @@ -0,0 +1,53 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.adapter.inf; + +import java.util.Map; +import net.sf.json.JSONObject; + +/** + * + * iResource manager interface.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public interface IResourceManager { + + /** + * + * Get juju vnfm information.<br> + * + * @param paramsMap + * @return + * @since NFVO 0.5 + */ + JSONObject getJujuVnfmInfo(Map<String,String> paramsMap); + + /** + * + * Get vfnfd information.<br> + * + * @param paramsMap + * @return + * @since NFVO 0.5 + */ + JSONObject getVnfdInfo(String csarId); + +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/api/internalsvc/impl/JujuAdapter2DriverMgrService.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/api/internalsvc/impl/JujuAdapter2DriverMgrService.java new file mode 100644 index 0000000..a297110 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/api/internalsvc/impl/JujuAdapter2DriverMgrService.java @@ -0,0 +1,183 @@ +/* + * Copyright 2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.api.internalsvc.impl; + +import java.io.BufferedInputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Executors; + +import org.openo.baseservice.util.impl.SystemEnvVariablesFactory; +import org.openo.nfvo.jujuvnfmadapter.service.adapter.impl.JujuAdapter2DriverManager; +import org.openo.nfvo.jujuvnfmadapter.service.adapter.inf.IJujuAdapter2DriverManager; +import org.openo.nfvo.jujuvnfmadapter.service.api.internalsvc.inf.IJujuAdapter2DriverMgrService; +import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant; +import org.openo.nfvo.jujuvnfmadapter.service.constant.UrlConstant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Jan 24, 2017 + */ +public class JujuAdapter2DriverMgrService implements IJujuAdapter2DriverMgrService { + + private static final Logger LOG = LoggerFactory.getLogger(JujuAdapter2DriverMgrService.class); + + public static final String VIMADAPTER2DRIVERMGR = "vimadapter2drivermgr.json"; + + @Override + public void register() { + // set URL and mothedtype + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", UrlConstant.REST_DRIVERMGR_REGISTER); + paramsMap.put("methodType", Constant.POST); + + // get vim adapter info and raise registration + try { + String adapterInfo = readVimAdapterInfoFromJson(); + if(!"".equals(adapterInfo)) { + JSONObject adapterObject = JSONObject.fromObject(adapterInfo); + RegisterVnfm2DriverMgrThread vnfmAdapterThread = + new RegisterVnfm2DriverMgrThread(paramsMap, adapterObject); + Executors.newSingleThreadExecutor().submit(vnfmAdapterThread); + } else { + LOG.error("vnfmadapter2drivermgr info is null,please check!"); + } + + } catch(IOException e) { + LOG.error("Failed to read vnfmadapter2drivermgr info! " + e.getMessage(), e); + } + + } + + /** + * Retrieve VIM driver information. + * + * @return + * @throws IOException + */ + public static String readVimAdapterInfoFromJson() throws IOException { + InputStream ins = null; + BufferedInputStream bins = null; + String fileContent = ""; + + String fileName = SystemEnvVariablesFactory.getInstance().getAppRoot() + System.getProperty("file.separator") + + "etc" + System.getProperty("file.separator") + "adapterInfo" + System.getProperty("file.separator") + + VIMADAPTER2DRIVERMGR; + + try { + ins = new FileInputStream(fileName); + bins = new BufferedInputStream(ins); + + byte[] contentByte = new byte[ins.available()]; + int num = bins.read(contentByte); + + if(num > 0) { + fileContent = new String(contentByte); + } + } catch(FileNotFoundException e) { + LOG.error(fileName + "is not found!", e); + } finally { + if(ins != null) { + ins.close(); + } + if(bins != null) { + bins.close(); + } + } + + return fileContent; + } + + private static class RegisterVnfm2DriverMgrThread implements Runnable { + + // Thread lock Object + private final Object lockObject = new Object(); + + private IJujuAdapter2DriverManager adapter2DriverMgr = new JujuAdapter2DriverManager(); + + // url and mothedtype + private Map<String, String> paramsMap; + + // driver body + private JSONObject adapterInfo; + + public RegisterVnfm2DriverMgrThread(Map<String, String> paramsMap, JSONObject adapterInfo) { + this.paramsMap = paramsMap; + this.adapterInfo = adapterInfo; + } + + @Override + public void run() { + LOG.info("start register vnfmadapter to Driver Manager", RegisterVnfm2DriverMgrThread.class); + + if(paramsMap == null || adapterInfo == null) { + LOG.error("parameter is null,please check!", RegisterVnfm2DriverMgrThread.class); + return; + } + + // catch Runtime Exception + try { + sendRequest(paramsMap, adapterInfo); + } catch(RuntimeException e) { + LOG.error(e.getMessage(), e); + } + + } + + private void sendRequest(Map<String, String> paramsMap, JSONObject driverInfo) { + JSONObject resultObj = adapter2DriverMgr.registerDriver(paramsMap, driverInfo); + + if(Integer.valueOf(resultObj.get("retCode").toString()) == Constant.HTTP_CREATED) { + LOG.info("Vnfmadapter has now Successfully Registered to the Driver Manager!"); + } else { + LOG.error("Vnfmadapter failed to Register to the Driver Manager! Reason:" + + resultObj.get("reason").toString() + " retCode:" + resultObj.get("retCode").toString()); + + // if registration fails,wait one minute and try again + try { + synchronized(lockObject) { + lockObject.wait(Constant.REPEAT_REG_TIME); + } + } catch(InterruptedException e) { + LOG.error(e.getMessage(), e); + } + + sendRequest(this.paramsMap, this.adapterInfo); + } + + } + + } + + @Override + public void unregister() { + // unregister + } + +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/api/internalsvc/impl/JujuAdapterMgrService.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/api/internalsvc/impl/JujuAdapterMgrService.java new file mode 100644 index 0000000..58b9c23 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/api/internalsvc/impl/JujuAdapterMgrService.java @@ -0,0 +1,196 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.api.internalsvc.impl; + +import java.io.BufferedInputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Executors; + +import org.openo.baseservice.util.impl.SystemEnvVariablesFactory; +import org.openo.nfvo.jujuvnfmadapter.service.adapter.impl.JujuAdapter2MSBManager; +import org.openo.nfvo.jujuvnfmadapter.service.adapter.inf.IJujuAdapter2MSBManager; +import org.openo.nfvo.jujuvnfmadapter.service.api.internalsvc.inf.IJujuAdapterMgrService; +import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant; +import org.openo.nfvo.jujuvnfmadapter.service.constant.UrlConstant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * Juju adapter manager service class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public class JujuAdapterMgrService implements IJujuAdapterMgrService { + + private static final Logger LOG = LoggerFactory.getLogger(JujuAdapterMgrService.class); + + @Override + public void register() { + // set BUS URL and mothedtype + Map<String, String> paramsMap = new HashMap<>(); + paramsMap.put("url", UrlConstant.REST_MSB_REGISTER); + paramsMap.put("methodType", Constant.POST); + + // get juju adapter info and raise registration + try { + String adapterInfo = readJujuAdapterInfoFromJson(); + if(!"".equals(adapterInfo)) { + JSONObject adapterObject = JSONObject.fromObject(adapterInfo); + RegisterJujuAdapterThread jujuAdapterThread = new RegisterJujuAdapterThread(paramsMap, adapterObject); + Executors.newSingleThreadExecutor().submit(jujuAdapterThread); + } else { + LOG.error("JujuVnfmAdapter info is null,please check!", JujuAdapterMgrService.class); + } + + } catch(IOException e) { + LOG.error("Failed to read JujuVnfmAdapter info!" + e, JujuAdapterMgrService.class); + } + + } + + /** + * Read juju adapter information from Json.<br> + * + * @return + * @throws IOException + * @since NFVO 0.5 + */ + public static String readJujuAdapterInfoFromJson() throws IOException { + InputStream ins = null; + BufferedInputStream bins = null; + String fileContent = ""; + + String fileName = SystemEnvVariablesFactory.getInstance().getAppRoot() + + System.getProperty(Constant.FILE_SEPARATOR) + "etc" + System.getProperty(Constant.FILE_SEPARATOR) + + "adapterInfo" + System.getProperty(Constant.FILE_SEPARATOR) + Constant.JUJUADAPTERINFO; + + try { + ins = new FileInputStream(fileName); + bins = new BufferedInputStream(ins); + + byte[] contentByte = new byte[ins.available()]; + int num = bins.read(contentByte); + + if(num > 0) { + fileContent = new String(contentByte); + } + } catch(FileNotFoundException e) { + LOG.error(fileName + "is not found!", e, JujuAdapterMgrService.class); + } finally { + if(null != ins) { + ins.close(); + } + + if(null != bins) { + bins.close(); + } + } + + return fileContent; + } + + private static class RegisterJujuAdapterThread implements Runnable { + + // Thread lock Object + private final Object lockObject = new Object(); + + private IJujuAdapter2MSBManager adapter2MSBMgr = new JujuAdapter2MSBManager(); + + // url and mothedtype + private Map<String, String> paramsMap; + + // driver body + private JSONObject adapterInfo; + + public RegisterJujuAdapterThread(Map<String, String> paramsMap, JSONObject adapterInfo) { + this.paramsMap = paramsMap; + this.adapterInfo = adapterInfo; + } + + @Override + public void run() { + LOG.info("start register jujuvnfmadapter", RegisterJujuAdapterThread.class); + + if(paramsMap == null || adapterInfo == null) { + LOG.error("parameter is null,please check!", RegisterJujuAdapterThread.class); + return; + } + + // catch Runtime Exception + try { + sendRequest(paramsMap, adapterInfo); + } catch(RuntimeException e) { + LOG.error(e.getMessage(), e); + } + + } + + private void sendRequest(Map<String, String> paramsMap, JSONObject driverInfo) { + JSONObject resultObj = adapter2MSBMgr.registerJujuAdapter(paramsMap, driverInfo); + + if(Integer.valueOf(resultObj.get("retCode").toString()) == Constant.HTTP_CREATED) { + LOG.info("JujuVnfmAdapter has now Successfully Registered to the Microservice BUS!", + JujuAdapterMgrService.class); + } else { + LOG.error("JujuVnfmAdapter failed to Register to the Microservice BUS! Reason:" + + resultObj.get("reason").toString() + " retCode:" + resultObj.get("retCode").toString()); + + // if registration fails,wait one minute and try again + try { + synchronized(lockObject) { + lockObject.wait(Constant.REPEAT_REG_TIME); + } + } catch(InterruptedException e) { + LOG.error("sendRequest error", e); + } + + sendRequest(this.paramsMap, this.adapterInfo); + } + + } + + } + + @Override + public void unregister() { + // Not implemented + + } + + /** + * Main method.<br> + * + * @param args + * @since NFVO 0.5 + */ + public static void main(String[] args) { + LOG.info(SystemEnvVariablesFactory.getInstance().getAppRoot() + System.getProperty(Constant.FILE_SEPARATOR) + + "etc" + System.getProperty(Constant.FILE_SEPARATOR) + "adapterInfo" + + System.getProperty(Constant.FILE_SEPARATOR) + Constant.JUJUADAPTERINFO); + } + +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/api/internalsvc/inf/IJujuAdapter2DriverMgrService.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/api/internalsvc/inf/IJujuAdapter2DriverMgrService.java new file mode 100644 index 0000000..ab8b839 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/api/internalsvc/inf/IJujuAdapter2DriverMgrService.java @@ -0,0 +1,43 @@ +/* + * Copyright 2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.api.internalsvc.inf; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Jan 24, 2017 + */ +public interface IJujuAdapter2DriverMgrService { + + /** + * VimAdapter register interface.<br> + * + * @since NFVO 0.5 + */ + void register(); + + /** + * VimAdapter unregister interface.<br> + * + * @since NFVO 0.5 + */ + void unregister(); + +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/api/internalsvc/inf/IJujuAdapterMgrService.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/api/internalsvc/inf/IJujuAdapterMgrService.java new file mode 100644 index 0000000..c3c0f12 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/api/internalsvc/inf/IJujuAdapterMgrService.java @@ -0,0 +1,45 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.api.internalsvc.inf; + +/** + * + * Ijuju adapter manager service interface.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public interface IJujuAdapterMgrService { + + /** + * + * JujuVnfmAdapter register interface.<br> + * + * @since NFVO 0.5 + */ + void register(); + + /** + * + * JujuVnfmAdapter unregister interface.<br> + * + * @since NFVO 0.5 + */ + void unregister(); +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/constant/Constant.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/constant/Constant.java new file mode 100644 index 0000000..0ae5c7f --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/constant/Constant.java @@ -0,0 +1,219 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.constant; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/** + * Constant class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public class Constant { + + public static final String VNFM_APP = "VnfmDriver"; + + public static final String VNFM_DB = "vnfmdb"; + + public static final String VNFM_ID = "vnfmId"; + + public static final String POST = "post"; + + public static final String PUT = "put"; + + public static final String DELETE = "delete"; + + public static final String GET = "get"; + + public static final String HEAD = "head"; + + public static final String ASYNCPOST = "asyncPost"; + + public static final String ASYNCGET = "asyncGet"; + + public static final String ASYNCPUT = "asyncPut"; + + public static final String ASYNCDELETE = "asyncDelete"; + + public static final String RESPONSE_CONTENT = "responseContent"; + + public static final String STATUS_CODE = "statusCode"; + + public static final String RETURN_CODE = "retCode"; + + public static final String REASON = "reason"; + + public static final int ERROR_STATUS_CODE = -1; + + public static final String ENCODEING = "utf-8"; + + public static final String COOKIE = "Cookie"; + + public static final String ACCESSSESSION = "bspsession="; + + public static final String CONTENT_TYPE = "Content-Type"; + + public static final String METHOD_TYPE = "methodType"; + + public static final String AUTH_MODE = "authMode"; + + public static final String APPLICATION = "application/json"; + + public static final String APP_NAME = "appName"; + + public static final String HEADER_SUBJECT_TOKEN = "X-Subject-Token"; + + public static final String HEADER_AUTH_TOKEN = "X-Auth-Token"; + + public static final String CSM = "csm"; + + public static final int ERROR_CODE = -1; + + public static final int HTTP_OK = 200; + + public static final int HTTP_CREATED = 201; + + public static final int HTTP_ACCEPTED = 202; + + public static final int UNREG_SUCCESS = 204; + + public static final int HTTP_BAD_REQUEST = 400; + + public static final int HTTP_UNAUTHORIZED = 401; + + public static final int HTTP_NOTFOUND = 404; + + public static final int HTTP_CONFLICT = 409; + + public static final int INVALID_PARAMETERS = 415; + + public static final int HTTP_INNERERROR = 500; + + public static final int REPEAT_REG_TIME = 60 * 1000; + + public static final String JUJUADAPTERINFO = "jujuadapterinfo.json"; + + public static final String FILE_SEPARATOR = "file.separator"; + + public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; + + public static final List<String> AUTHLIST = + Collections.unmodifiableList(Arrays.asList(AuthenticationMode.ANONYMOUS, AuthenticationMode.CERTIFICATE)); + + public static final int INTERNAL_EXCEPTION = 600; + + public static final int TOKEN_HEAD_NULL = 601; + + public static final int TOKEN_USER_NULL = 602; + + public static final int SERVICE_URL_ERROR = 603; + + public static final int ACCESS_OBJ_NULL = 604; + + public static final int CONNECT_NOT_FOUND = 605; + + public static final int VCENTER_PARA_ERROR = 606; + + public static final int TYPE_PARA_ERROR = 607; + + public static final int CONNECT_FAIL = 608; + + public static final int DIS_CONNECT_FAIL = 609; + + public static final int HANDSHAKE_FAIL = 610; + + public static final int MIN_PWD_LENGTH = 6; + + public static final int MAX_PWD_LENGTH = 160; + + public static final int MIN_URL_LENGTH = 7; + + public static final int MAX_VNFM_NAME_LENGTH = 64; + + public static final int MIN_VNFM_NAME_LENGTH = 1; + + public static final int MAX_URL_LENGTH = 256; + + public static final int MAX_SAMPLE_NUM = 1; + + public static final int MAX_VERSION_LENGTH = 160; + + public static final int MIN_VERSION_LENGTH = 1; + + public static final String HANDSHAKE = "handShake"; + + public static final String INACTIVE = "inactive"; + + public static final String ACTIVE = "active"; + + public static final String RESOURCE_PATH = ""; + + public static final int REST_SUCCESS = 1; + + public static final int REST_PART_SUCCESS = 0; + + public static final int DEFAULT_COLLECTION_SIZE = 10; + + public static final int REST_FAIL = -1; + + public static final String ROARAND = "?roarand=%s"; + + public static final long PROCESS_WAIT_MILLIS = 30000; + + public static final String CSARINFO="csarinfo.json"; + + public static final String DOWNLOADCSAR_SUCCESS = "Success"; + + public static final String DOWNLOADCSAR_FAIL = "FAIL"; + + public static final int UNZIP_SUCCESS = 0; + + public static final int UNZIP_FAIL = -1; + + /** + * Constructor<br/> + * <p> + * </p> + */ + private Constant() { + // Private Constructor + } + + /** + * Authentication mode.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ + public static class AuthenticationMode { + + public static final String ANONYMOUS = "Anonymous"; + + public static final String CERTIFICATE = "Certificate"; + + private AuthenticationMode() { + + } + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/constant/ParamConstants.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/constant/ParamConstants.java new file mode 100644 index 0000000..fc734ce --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/constant/ParamConstants.java @@ -0,0 +1,144 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.constant; + +/** + * + * Parameter constants class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public class ParamConstants { + + public static final String GET_TOKENS_V1 = "{\"grantType\": \"password\", \"userName\": \"%s\",\"value\": \"%s\"}"; + + public static final String GET_TOKENS_V2 = + "{\"auth\":{\"identity\": {\"methods\": [\"password\"],\"password\": {\"user\": {\"name\": \"%s\",\"password\": \"%s\"}}}}}"; + + public static final String GET_IAM_TOKENS = + "{\"auth\": {\"identity\": {\"methods\": [\"password\"],\"password\": {\"user\": {\"name\": " + + "\"%s\",\"password\": \"%s\",\"domain\": {\"name\": \"%s\"}}}},\"scope\": {\"domain\": {\"name\": \"%s\"}}}}"; + + public static final String GET_TOKEN_SUC_RESP = + "{\"token\": {\"methods\": [\"password\"],\"expires_at\": \"\",\"user\": {\"id\": \"%s\"," + + "\"name\": \"%s\"},\"roa_rand\": \"%s\"}}"; + + public static final String GET_TOKEN_FAIL_RESP = "{\"Information\": \"%s\"}"; + + public static final String REST_3RD_CONNECTION = "/rest/plat/smapp/v1/oauth/token"; + + public static final String REST_3RD_DISCONNECT = "/rest/plat/smapp/v1/sessions?roarand=%s"; + + public static final String REST_3RD_HANDSHAKE = "/rest/plat/ssm/v1/sessions/verify"; + + public static final String IAM_AUTH = "/v3/auth/tokens"; + + public static final String CSM_AUTH_CONNECT = "/v2/auth/tokens"; + + public static final String CSM_AUTH_DISCONNECT = "/v2/auth/tokens/%s/%s"; + + public static final String CSM_AUTH_HANDSHAKE = "/v2/nfvo/shakehand?roattr=status"; + + public static final String VNFMMED = "/rest/vnfmmed/"; + + public static final String CONNECTMGR_CONNECT = "/connectmgr/v1/connect"; + + public static final String CONNECTMGR_DISCONNECT = "/connectmgr/v1/disconnect"; + + public static final String CONNECTMGR_HANDSHAKE = "/connectmgr/v1/handshake"; + + public static final String CREATE_VNF_PERF = "/staticsmgr/v1/vnfperformance"; + + public static final String VNFMGR_INSTANCE = "/vnfmgr/v1/instances"; + + public static final String VNF_SCALE = "/vnfmgr/v1/instances/%s/scale"; + + public static final String VNFD_FLAVOR = "/vnfdmgr/v1/flavor"; + + public static final String VNFDGR_INSTALL = "/vnfdmgr/v1/vnfd/%s/install"; + + public static final String VNFDGR_DETAIL = "/vnfdmgr/v1/vnfd/%s"; + + public static final String VNFDGR_DETAILS = "/vnfdmgr/v1/vnfd"; + + public static final String VNFDGR_TOPOLOGY = "/vnfdmgr/v1/topology/%s"; + + public static final String UPDATE_RESOURCE = "/rest/v1/resmanage/resuse/updateres"; + + public static final String VNFDGR_INSTANCE = "/vnfmmed/v1/vnfdm/"; + + public static final String VNF_QUERY = "/resmgr/v1/vnfs"; + + public static final String VMS_QUERY = "/resmgr/v1/vms"; + + public static final String REST_EVENT_ADD = "/rest/v1/resmanage/vnfm/site"; + + public static final String REST_EVENT_DEL = "/rest/v1/resmanage/vnfm/site/%s"; + + public static final String VNFMGR_VNFKPI = "/staticsmgr/v1/vnfkpi"; + + public static final String RES_VNF = "/rest/v1/resmanage/vappvm"; + + public static final String NOTIFY_VNF_PERF = "/rest/v1/resmanage/vappvm"; + + public static final String PARAM_MODULE = "VnfmDriver"; + + public static final String GET_ALL_SITES = "/rest/v1/resmanage/sites"; + + public static final String GET_ALL_SOS = "/rest/sodriver/v1/sos"; + + public static final String OPERATION_LOG_PATH = "/rest/plat/audit/v1/logs"; + + public static final String SYSTEM_LOG_PATH = "/rest/plat/audit/v1/systemlogs"; + + public static final String SECURITY_LOG_PATH = "/rest/plat/audit/v1/seculogs"; + + public static final String SCALINGPOLICY_QUERY = "/policymgr/v1/scalingpolicy"; + + public static final String SCALINGPOLICY_OPERATE = "/policymgr/v1/scalingpolicy/%s/%s"; + + public static final String ACTIVE_POLICY = "/policymgr/v1/activepolicy"; + + public static final String DEACTIVE_POLICY = "/policymgr/v1/deactivepolicy"; + + public static final String GET_VNFM_VNF = "/rest/v1/resmanage/vapps?vnfmId=%s"; + + public static final String GET_RES_NET = "/rest/v1/resmanage/virtualnetworks?id=%s"; + + public static final String GET_JOB_STATUS = "/vnfmgr/v1/jobs/%s"; + + public static final String CREATE_POLICY = "/policymgr/v1/vnfs/%s/policies"; + + public static final String REST_FOR_VNFD_PLANS = "/v2/vapps/templates/%s/plans"; + + public static final String REST_GET_VNFDS = "/v2/vapps/templates"; + + public static final String REST_FOR_VNFD_BASIC = "/v2/vapps/templates?type=basic&vendor=%s&vnfdID=%s&version=%s"; + + public static final String REST_TOPOLOGY = "/v1/vapps/templates/%s?type=templatetopology"; + + public static final String VNF_INSTANCE = "/v2/vapps/instances"; + + public static final String VNF_INSTANCE_DEL = "/v2/vapps/instances/%s"; + + private ParamConstants() { + //Constructor + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/constant/UrlConstant.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/constant/UrlConstant.java new file mode 100644 index 0000000..1074209 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/constant/UrlConstant.java @@ -0,0 +1,54 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.constant; + +/** + * Url constant class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 10, 2016 + */ +public class UrlConstant { + + public static final String REST_DRIVERMGR_REGISTER = "/openoapi/drivermgr/v1/drivers"; + + public static final String REST_MSB_REGISTER = "/api/microservices/v1/services"; + + public static final String REST_ESRINFO_GET = "/openoapi/extsys/v1/vnfms/%s"; + + public static final String REST_VNFDINFO_GET = + "/openoapi/catalog/v1/csars/%s/files?relativePath=%s&relativePath=%s"; + + public static final String REST_MSB_UNREGISTER = "/openoapi/microservices/v1/services/%s/version/%s/nodes/%s/%s"; + + public static final String REST_JUJU_CLIENT_DEPLOY = "/openoapi/jujuvnfm/v1/vnfms/deploy"; + + public static final String REST_JUJU_CLIENT_DESTORY = "/openoapi/jujuvnfm/v1/vnfms/destroy"; + + public static final String REST_JUJU_CLIENT_GET = "/openoapi/jujuvnfm/v1/vnfms/status?modelName=%s"; + + public static final String RES_VNF = "/openoapi/nslcm/v1/ns/grantvnf"; + public static final String REST_JUJU_VNFM_GRANT_URL = "/openoapi/jujuvnfm/v1/instances/%s/grant"; + + public static final String REST_CSARINFO_GET = "/openoapi/catalog/v1/csars/%s"; + + private UrlConstant() { + // Constructor + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/JujuDriver.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/JujuDriver.java new file mode 100644 index 0000000..d4b4f50 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/JujuDriver.java @@ -0,0 +1,203 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.entity; + +import java.util.List; + +import net.sf.json.JSONObject; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +/** + * + * Juju Driver Class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 10, 2016 + */ +public class JujuDriver { + + private String serviceName; + + private String protocol; + + private String version; + + private String visualRange; + + private String url; + + private List nodes; + + private String ip; + + private String port; + + private String ttl; + + private String status; + + public static final String NOTES = "notes"; + + public JujuDriver() { + // Default Constructor + } + + /** + * + * Constructor<br> + * <p> + * </p> + * + * @param jujuJsonObject + * @since NFVO 0.5 + */ + public JujuDriver(JSONObject jujuJsonObject) { + this.serviceName = jujuJsonObject.getString("serviceName"); + this.protocol = jujuJsonObject.getString("protocol"); + this.version = jujuJsonObject.getString("version"); + this.visualRange = jujuJsonObject.getString("visualRange"); + this.url = jujuJsonObject.getString("url"); + this.nodes = jujuJsonObject.getJSONArray("nodes"); + this.ip = jujuJsonObject.getJSONArray(NOTES).getString(0); + this.port = jujuJsonObject.getJSONArray(NOTES).getString(1); + this.ttl = jujuJsonObject.getJSONArray(NOTES).getString(2); + this.status = jujuJsonObject.getString("status"); + } + + public String getServiceName() { + return serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public String getVisualRange() { + return visualRange; + } + + public void setVisualRange(String visualRange) { + this.visualRange = visualRange; + } + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public List getNodes() { + return nodes; + } + + public void setNodes(List nodes) { + this.nodes = nodes; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + 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 String getTtl() { + return ttl; + } + + public void setTtl(String ttl) { + this.ttl = ttl; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((serviceName == null) ? 0 : serviceName.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if(this == obj) { + return true; + } + if(obj == null) { + return false; + } + if(!(obj instanceof JujuDriver)) { + return false; + } + if(getClass() != obj.getClass()) { + return false; + } + JujuDriver other = (JujuDriver)obj; + if(serviceName == null) { + if(other.serviceName != null) { + return false; + } + } else if(!serviceName.equals(other.serviceName)) { + return false; + } + return true; + } + +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/JujuVnfd.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/JujuVnfd.java new file mode 100644 index 0000000..bab793a --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/JujuVnfd.java @@ -0,0 +1,93 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.entity; + + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +/** + * + * Juju vnfd class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public class JujuVnfd { + + private String downloadUri; + + private String localPath; + + public String getDownloadUri() { + return downloadUri; + } + + public void setDownloadUri(String downloadUri) { + this.downloadUri = downloadUri; + } + + public String getLocalPath() { + return localPath; + } + + public void setLocalPath(String localPath) { + this.localPath = localPath; + } + + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((downloadUri == null) ? 0 : downloadUri.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if(this == obj) { + return true; + } + if(obj == null) { + return false; + } + if(!(obj instanceof JujuVnfd)) { + return false; + } + if(getClass() != obj.getClass()) { + return false; + } + JujuVnfd other = (JujuVnfd)obj; + if(downloadUri == null) { + if(other.downloadUri != null) { + return false; + } + } else if(!downloadUri.equals(other.downloadUri)) { + return false; + } + return true; + } + +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/JujuVnfm.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/JujuVnfm.java new file mode 100644 index 0000000..4a15e46 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/JujuVnfm.java @@ -0,0 +1,366 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.entity; + +import java.text.SimpleDateFormat; +import java.util.Date; + +import net.sf.json.JSONObject; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.openo.nfvo.jujuvnfmadapter.common.CryptUtil; +import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant; + +/** + * + * Juju vnfm Class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public class JujuVnfm { + + private String id; + + private String name; + + private String type; + + private String version; + + private String userName; + + private String pwd; + + private String url; + + private String vendor; + + private String extraInfo; + + private String status; + + private String createAt; + + private String updateAt; + + /** + * <br> + * + * @return String + */ + public String getId() { + return id; + } + + /** + * <br> + * + * @param id + */ + public void setId(String id) { + this.id = id; + } + + /** + * <br> + * + * @return String + */ + public String getType() { + return type; + } + + /** + * <br> + * + * @param type + */ + public void setType(String type) { + this.type = type; + } + + /** + * <br> + * + * @return String + */ + public String getName() { + return name; + } + + /** + * <br> + * + * @param name + */ + public void setName(String name) { + this.name = name; + } + + /** + * <br> + * + * @return String + */ + public String getVersion() { + return version; + } + + /** + * <br> + * + * @param version + */ + public void setVersion(String version) { + this.version = version; + } + + /** + * <br> + * + * @return String + */ + public String getUserName() { + return userName; + } + + /** + * <br> + * + * @param userName + */ + public void setUserName(String userName) { + this.userName = userName; + } + + /** + * <br> + * + * @return String + */ + public String getUrl() { + return url; + } + + /** + * <br> + * + * @param url + */ + public void setUrl(String url) { + this.url = url; + } + + /** + * <br> + * + * @return String + */ + public String getPwd() { + return pwd; + } + + /** + * <br> + * + * @param pwd + */ + public void setPwd(String pwd) { + this.pwd = pwd; + } + + /** + * <br> + * + * @return String + */ + public String getVendor() { + return vendor; + } + + /** + * <br> + * + * @param vendor + */ + public void setVendor(String vendor) { + this.vendor = vendor; + } + + /** + * <br> + * + * @return String + */ + public String getExtraInfo() { + return extraInfo; + } + + /** + * <br> + * + * @param extraInfo + */ + public void setExtraInfo(String extraInfo) { + this.extraInfo = extraInfo; + } + + /** + * <br> + * + * @return + */ + public String getStatus() { + return status; + } + + /** + * <br> + * + * @param status + */ + public void setStatus(String status) { + this.status = status; + } + + /** + * <br> + * + * @return + */ + public String getCreateAt() { + return createAt; + } + + /** + * <br> + * + * @param createAt + */ + public void setCreateAt(String createAt) { + this.createAt = createAt; + } + + /** + * <br> + * + * @return + */ + public String getUpdateAt() { + return updateAt; + } + + /** + * <br> + * + * @param updateAt + */ + public void setUpdateAt(String updateAt) { + this.updateAt = updateAt; + } + + /** + * <br/> + * + * @return + */ + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); + } + + /** + * <br/> + * + * @return + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + /** + * <br/> + * + * @param obj + * @return + */ + @Override + public boolean equals(Object obj) { + if(this == obj) { + return true; + } + if(obj == null) { + return false; + } + if(!(obj instanceof JujuVnfm)) { + return false; + } + if(getClass() != obj.getClass()) { + return false; + } + JujuVnfm other = (JujuVnfm)obj; + if(id == null) { + if(other.id != null) { + return false; + } + } else if(!id.equals(other.id)) { + return false; + } + return true; + } + + /** + * + * Update Vnfm.<br> + * + * @param otherVnfm + * @since NFVO 0.5 + */ + public void updateVnfm(JSONObject otherVnfm) { + String vnfmName = otherVnfm.getString("name"); + String vnfmUserName = otherVnfm.getString("userName"); + String vnfmPwd = CryptUtil.enCrypt(otherVnfm.getString("pwd")); + + if(!StringUtils.isEmpty(vnfmName)) { + this.name = vnfmName; + } + + if(!StringUtils.isEmpty(vnfmUserName)) { + this.userName = vnfmUserName; + } + + if(!StringUtils.isEmpty(vnfmPwd)) { + this.pwd = vnfmPwd; + } + + String vnfmExtraInfo = otherVnfm.get("extraInfo").toString(); + if(!StringUtils.isEmpty(vnfmExtraInfo)) { + this.extraInfo = vnfmExtraInfo; + } + + this.updateAt = new SimpleDateFormat(Constant.DATE_FORMAT).format(new Date()); + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/JujuVnfmInfo.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/JujuVnfmInfo.java new file mode 100644 index 0000000..d3844fa --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/JujuVnfmInfo.java @@ -0,0 +1,141 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.entity; + +import java.io.Serializable; +import java.util.Date; + +/** + * + * + * @author z00292420 + * @date 2016-9-12* + + */ +public class JujuVnfmInfo implements Serializable { + /** */ + private String id; + + /** */ + private String vnfmId; + + /** */ + private String vnfId; + + /** */ + private String appName; + + /** */ + private String jobId; + + /** */ + private Integer status; + + /** */ + private Date createTime; + + /** */ + private Date modifyTime; + + /** */ + private Date deleteTime; + + /** */ + private String extend; + + private static final long serialVersionUID = 1L; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getVnfmId() { + return vnfmId; + } + + public void setVnfmId(String vnfmId) { + this.vnfmId = vnfmId; + } + + public String getVnfId() { + return vnfId; + } + + public void setVnfId(String vnfId) { + this.vnfId = vnfId; + } + + public String getAppName() { + return appName; + } + + public void setAppName(String appName) { + this.appName = appName; + } + + public String getJobId() { + return jobId; + } + + public void setJobId(String jobId) { + this.jobId = jobId; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public Date getModifyTime() { + return modifyTime; + } + + public void setModifyTime(Date modifyTime) { + this.modifyTime = modifyTime; + } + + public Date getDeleteTime() { + return deleteTime; + } + + public void setDeleteTime(Date deleteTime) { + this.deleteTime = deleteTime; + } + + public String getExtend() { + return extend; + } + + public void setExtend(String extend) { + this.extend = extend; + } +}
\ No newline at end of file diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/JujuVnfmInfoExample.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/JujuVnfmInfoExample.java new file mode 100644 index 0000000..560aee8 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/JujuVnfmInfoExample.java @@ -0,0 +1,1682 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.entity; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * JUJU VNFM Information example + * .</br> + * + * @author + * @version NFVO 0.5 Sep 14, 2016 + */ +public class JujuVnfmInfoExample { + protected String orderByClause; + + protected boolean distinct; + + protected List<Criteria> oredCriteria; + + protected int limitStart = -1; + + protected int limitEnd = -1; + + public static final String VNFM_ID = "vnfmId"; + + public static final String VNF_ID = "vnfId"; + + public static final String APP_NAME = "appName"; + + public static final String JOB_ID = "jobId"; + + public static final String STATUS = "status"; + + public static final String CREATE_TIME = "createTime"; + + public static final String MODIFY_TIME = "modifyTime"; + + public static final String DELETE_TIME = "deleteTime"; + + /** + * Constructor<br/> + * <p> + * </p> + */ + public JujuVnfmInfoExample() { + oredCriteria = new ArrayList<>(); + } + + public void setOrderByClause(String orderByClause) { + this.orderByClause = orderByClause; + } + + public String getOrderByClause() { + return orderByClause; + } + + public void setDistinct(boolean distinct) { + this.distinct = distinct; + } + + public boolean isDistinct() { + return distinct; + } + + public List<Criteria> getOredCriteria() { + return oredCriteria; + } + + /** + * <br> + * + * @param criteria + */ + public void or(Criteria criteria) { + oredCriteria.add(criteria); + } + + /** + * <br> + * + * @return + */ + public Criteria or() { + Criteria criteria = createCriteriaInternal(); + oredCriteria.add(criteria); + return criteria; + } + + /** + * <br> + * + * @return + */ + public Criteria createCriteria() { + Criteria criteria = createCriteriaInternal(); + if (oredCriteria.isEmpty()) { + oredCriteria.add(criteria); + } + return criteria; + } + + protected Criteria createCriteriaInternal() { + return new Criteria(); + } + + /** + * <br> + * + */ + public void clear() { + oredCriteria.clear(); + orderByClause = null; + distinct = false; + } + + public void setLimitStart(int limitStart) { + this.limitStart=limitStart; + } + + public int getLimitStart() { + return limitStart; + } + + public void setLimitEnd(int limitEnd) { + this.limitEnd=limitEnd; + } + + public int getLimitEnd() { + return limitEnd; + } + + protected static class GeneratedCriteria { + protected List<Criterion> criteria; + + protected GeneratedCriteria() { + super(); + criteria = new ArrayList<>(); + } + + public boolean isValid() { + return !criteria.isEmpty(); + } + + public List<Criterion> getAllCriteria() { + return criteria; + } + + public List<Criterion> getCriteria() { + return criteria; + } + + protected void addCriterion(String condition) { + if (condition == null) { + throw new RuntimeException("Value for condition cannot be null"); //NOSONAR + } + criteria.add(new Criterion(condition)); + } + + protected void addCriterion(String condition, Object value, String property) { + if (value == null) { + throw new RuntimeException("Value for " + property + " cannot be null"); //NOSONARr + } + criteria.add(new Criterion(condition, value)); + } + + protected void addCriterion(String condition, Object value1, Object value2, String property) { + if (value1 == null || value2 == null) { + throw new RuntimeException("Between values for " + property + " cannot be null"); //NOSONAR + } + criteria.add(new Criterion(condition, value1, value2)); + } + + /** + * <br> + * + * @return + */ + public Criteria andIdIsNull() { + addCriterion("ID is null"); + return (Criteria) this; + } + + /** + * <br> + * + * @return + */ + public Criteria andIdIsNotNull() { + addCriterion("ID is not null"); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andIdEqualTo(String value) { + addCriterion("ID =", value, "id"); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andIdNotEqualTo(String value) { + addCriterion("ID <>", value, "id"); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andIdGreaterThan(String value) { + addCriterion("ID >", value, "id"); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andIdGreaterThanOrEqualTo(String value) { + addCriterion("ID >=", value, "id"); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andIdLessThan(String value) { + addCriterion("ID <", value, "id"); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andIdLessThanOrEqualTo(String value) { + addCriterion("ID <=", value, "id"); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andIdLike(String value) { + addCriterion("ID like", value, "id"); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andIdNotLike(String value) { + addCriterion("ID not like", value, "id"); + return (Criteria) this; + } + + /** + * <br> + * + * @param values + * @return + */ + public Criteria andIdIn(List<String> values) { + addCriterion("ID in", values, "id"); + return (Criteria) this; + } + + /** + * <br> + * + * @param values + * @return + */ + public Criteria andIdNotIn(List<String> values) { + addCriterion("ID not in", values, "id"); + return (Criteria) this; + } + + /** + * <br> + * + * @param value1 + * @param value2 + * @return + */ + public Criteria andIdBetween(String value1, String value2) { + addCriterion("ID between", value1, value2, "id"); + return (Criteria) this; + } + + /** + * <br> + * + * @param value1 + * @param value2 + * @return + */ + public Criteria andIdNotBetween(String value1, String value2) { + addCriterion("ID not between", value1, value2, "id"); + return (Criteria) this; + } + + /** + * <br> + * + * @return + */ + public Criteria andVnfmIdIsNull() { + addCriterion("VNFM_ID is null"); + return (Criteria) this; + } + + /** + * <br> + * + * @return + */ + public Criteria andVnfmIdIsNotNull() { + addCriterion("VNFM_ID is not null"); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andVnfmIdEqualTo(String value) { + addCriterion("VNFM_ID =", value, VNFM_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andVnfmIdNotEqualTo(String value) { + addCriterion("VNFM_ID <>", value, VNFM_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andVnfmIdGreaterThan(String value) { + addCriterion("VNFM_ID >", value, VNFM_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andVnfmIdGreaterThanOrEqualTo(String value) { + addCriterion("VNFM_ID >=", value, VNFM_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andVnfmIdLessThan(String value) { + addCriterion("VNFM_ID <", value, VNFM_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andVnfmIdLessThanOrEqualTo(String value) { + addCriterion("VNFM_ID <=", value, VNFM_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andVnfmIdLike(String value) { + addCriterion("VNFM_ID like", value, VNFM_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andVnfmIdNotLike(String value) { + addCriterion("VNFM_ID not like", value, VNFM_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param values + * @return + */ + public Criteria andVnfmIdIn(List<String> values) { + addCriterion("VNFM_ID in", values, VNFM_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param values + * @return + */ + public Criteria andVnfmIdNotIn(List<String> values) { + addCriterion("VNFM_ID not in", values, VNFM_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value1 + * @param value2 + * @return + */ + public Criteria andVnfmIdBetween(String value1, String value2) { + addCriterion("VNFM_ID between", value1, value2, VNFM_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value1 + * @param value2 + * @return + */ + public Criteria andVnfmIdNotBetween(String value1, String value2) { + addCriterion("VNFM_ID not between", value1, value2, VNFM_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @return + */ + public Criteria andVnfIdIsNull() { + addCriterion("VNF_ID is null"); + return (Criteria) this; + } + + /** + * <br> + * + * @return + */ + public Criteria andVnfIdIsNotNull() { + addCriterion("VNF_ID is not null"); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andVnfIdEqualTo(String value) { + addCriterion("VNF_ID =", value, VNF_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andVnfIdNotEqualTo(String value) { + addCriterion("VNF_ID <>", value, VNF_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andVnfIdGreaterThan(String value) { + addCriterion("VNF_ID >", value, VNF_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andVnfIdGreaterThanOrEqualTo(String value) { + addCriterion("VNF_ID >=", value, VNF_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andVnfIdLessThan(String value) { + addCriterion("VNF_ID <", value, VNF_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andVnfIdLessThanOrEqualTo(String value) { + addCriterion("VNF_ID <=", value, VNF_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andVnfIdLike(String value) { + addCriterion("VNF_ID like", value, VNF_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andVnfIdNotLike(String value) { + addCriterion("VNF_ID not like", value, VNF_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param values + * @return + */ + public Criteria andVnfIdIn(List<String> values) { + addCriterion("VNF_ID in", values, VNF_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param values + * @return + */ + public Criteria andVnfIdNotIn(List<String> values) { + addCriterion("VNF_ID not in", values, VNF_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value1 + * @param value2 + * @return + */ + public Criteria andVnfIdBetween(String value1, String value2) { + addCriterion("VNF_ID between", value1, value2, VNF_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value1 + * @param value2 + * @return + */ + public Criteria andVnfIdNotBetween(String value1, String value2) { + addCriterion("VNF_ID not between", value1, value2, VNF_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @return + */ + public Criteria andAppNameIsNull() { + addCriterion("APP_NAME is null"); + return (Criteria) this; + } + + /** + * <br> + * + * @return + */ + public Criteria andAppNameIsNotNull() { + addCriterion("APP_NAME is not null"); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andAppNameEqualTo(String value) { + addCriterion("APP_NAME =", value, APP_NAME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andAppNameNotEqualTo(String value) { + addCriterion("APP_NAME <>", value, APP_NAME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andAppNameGreaterThan(String value) { + addCriterion("APP_NAME >", value, APP_NAME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andAppNameGreaterThanOrEqualTo(String value) { + addCriterion("APP_NAME >=", value, APP_NAME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andAppNameLessThan(String value) { + addCriterion("APP_NAME <", value, APP_NAME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andAppNameLessThanOrEqualTo(String value) { + addCriterion("APP_NAME <=", value, APP_NAME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andAppNameLike(String value) { + addCriterion("APP_NAME like", value, APP_NAME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andAppNameNotLike(String value) { + addCriterion("APP_NAME not like", value, APP_NAME); + return (Criteria) this; + } + + /** + * <br> + * + * @param values + * @return + */ + public Criteria andAppNameIn(List<String> values) { + addCriterion("APP_NAME in", values, APP_NAME); + return (Criteria) this; + } + + /** + * <br> + * + * @param values + * @return + */ + public Criteria andAppNameNotIn(List<String> values) { + addCriterion("APP_NAME not in", values, APP_NAME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value1 + * @param value2 + * @return + */ + public Criteria andAppNameBetween(String value1, String value2) { + addCriterion("APP_NAME between", value1, value2, APP_NAME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value1 + * @param value2 + * @return + */ + public Criteria andAppNameNotBetween(String value1, String value2) { + addCriterion("APP_NAME not between", value1, value2, APP_NAME); + return (Criteria) this; + } + + /** + * <br> + * + * @return + */ + public Criteria andJobIdIsNull() { + addCriterion("JOB_ID is null"); + return (Criteria) this; + } + + /** + * <br> + * + * @return + */ + public Criteria andJobIdIsNotNull() { + addCriterion("JOB_ID is not null"); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andJobIdEqualTo(String value) { + addCriterion("JOB_ID =", value, JOB_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andJobIdNotEqualTo(String value) { + addCriterion("JOB_ID <>", value, JOB_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andJobIdGreaterThan(String value) { + addCriterion("JOB_ID >", value, JOB_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andJobIdGreaterThanOrEqualTo(String value) { + addCriterion("JOB_ID >=", value, JOB_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andJobIdLessThan(String value) { + addCriterion("JOB_ID <", value, JOB_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andJobIdLessThanOrEqualTo(String value) { + addCriterion("JOB_ID <=", value, JOB_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andJobIdLike(String value) { + addCriterion("JOB_ID like", value, JOB_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andJobIdNotLike(String value) { + addCriterion("JOB_ID not like", value, JOB_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param values + * @return + */ + public Criteria andJobIdIn(List<String> values) { + addCriterion("JOB_ID in", values, JOB_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param values + * @return + */ + public Criteria andJobIdNotIn(List<String> values) { + addCriterion("JOB_ID not in", values, JOB_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value1 + * @param value2 + * @return + */ + public Criteria andJobIdBetween(String value1, String value2) { + addCriterion("JOB_ID between", value1, value2, JOB_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @param value1 + * @param value2 + * @return + */ + public Criteria andJobIdNotBetween(String value1, String value2) { + addCriterion("JOB_ID not between", value1, value2, JOB_ID); + return (Criteria) this; + } + + /** + * <br> + * + * @return + */ + public Criteria andStatusIsNull() { + addCriterion("STATUS is null"); + return (Criteria) this; + } + + /** + * <br> + * + * @return + */ + public Criteria andStatusIsNotNull() { + addCriterion("STATUS is not null"); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andStatusEqualTo(Integer value) { + addCriterion("STATUS =", value, STATUS); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andStatusNotEqualTo(Integer value) { + addCriterion("STATUS <>", value, STATUS); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andStatusGreaterThan(Integer value) { + addCriterion("STATUS >", value, STATUS); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andStatusGreaterThanOrEqualTo(Integer value) { + addCriterion("STATUS >=", value, STATUS); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andStatusLessThan(Integer value) { + addCriterion("STATUS <", value, STATUS); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andStatusLessThanOrEqualTo(Integer value) { + addCriterion("STATUS <=", value, STATUS); + return (Criteria) this; + } + + /** + * <br> + * + * @param values + * @return + */ + public Criteria andStatusIn(List<Integer> values) { + addCriterion("STATUS in", values, STATUS); + return (Criteria) this; + } + + /** + * <br> + * + * @param values + * @return + */ + public Criteria andStatusNotIn(List<Integer> values) { + addCriterion("STATUS not in", values, STATUS); + return (Criteria) this; + } + + /** + * <br> + * + * @param value1 + * @param value2 + * @return + */ + public Criteria andStatusBetween(Integer value1, Integer value2) { + addCriterion("STATUS between", value1, value2, STATUS); + return (Criteria) this; + } + + /** + * <br> + * + * @param value1 + * @param value2 + * @return + */ + public Criteria andStatusNotBetween(Integer value1, Integer value2) { + addCriterion("STATUS not between", value1, value2, STATUS); + return (Criteria) this; + } + + /** + * <br> + * + * @return + */ + public Criteria andCreateTimeIsNull() { + addCriterion("CREATE_TIME is null"); + return (Criteria) this; + } + + /** + * <br> + * + * @return + */ + public Criteria andCreateTimeIsNotNull() { + addCriterion("CREATE_TIME is not null"); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andCreateTimeEqualTo(Date value) { + addCriterion("CREATE_TIME =", value, CREATE_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andCreateTimeNotEqualTo(Date value) { + addCriterion("CREATE_TIME <>", value, CREATE_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andCreateTimeGreaterThan(Date value) { + addCriterion("CREATE_TIME >", value, CREATE_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { + addCriterion("CREATE_TIME >=", value, CREATE_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andCreateTimeLessThan(Date value) { + addCriterion("CREATE_TIME <", value, CREATE_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andCreateTimeLessThanOrEqualTo(Date value) { + addCriterion("CREATE_TIME <=", value, CREATE_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param values + * @return + */ + public Criteria andCreateTimeIn(List<Date> values) { + addCriterion("CREATE_TIME in", values, CREATE_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param values + * @return + */ + public Criteria andCreateTimeNotIn(List<Date> values) { + addCriterion("CREATE_TIME not in", values, CREATE_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value1 + * @param value2 + * @return + */ + public Criteria andCreateTimeBetween(Date value1, Date value2) { + addCriterion("CREATE_TIME between", value1, value2, CREATE_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value1 + * @param value2 + * @return + */ + public Criteria andCreateTimeNotBetween(Date value1, Date value2) { + addCriterion("CREATE_TIME not between", value1, value2, CREATE_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @return + */ + public Criteria andModifyTimeIsNull() { + addCriterion("MODIFY_TIME is null"); + return (Criteria) this; + } + + /** + * <br> + * + * @return + */ + public Criteria andModifyTimeIsNotNull() { + addCriterion("MODIFY_TIME is not null"); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andModifyTimeEqualTo(Date value) { + addCriterion("MODIFY_TIME =", value, MODIFY_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andModifyTimeNotEqualTo(Date value) { + addCriterion("MODIFY_TIME <>", value, MODIFY_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andModifyTimeGreaterThan(Date value) { + addCriterion("MODIFY_TIME >", value, MODIFY_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andModifyTimeGreaterThanOrEqualTo(Date value) { + addCriterion("MODIFY_TIME >=", value, MODIFY_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andModifyTimeLessThan(Date value) { + addCriterion("MODIFY_TIME <", value, MODIFY_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andModifyTimeLessThanOrEqualTo(Date value) { + addCriterion("MODIFY_TIME <=", value, MODIFY_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param values + * @return + */ + public Criteria andModifyTimeIn(List<Date> values) { + addCriterion("MODIFY_TIME in", values, MODIFY_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param values + * @return + */ + public Criteria andModifyTimeNotIn(List<Date> values) { + addCriterion("MODIFY_TIME not in", values, MODIFY_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value1 + * @param value2 + * @return + */ + public Criteria andModifyTimeBetween(Date value1, Date value2) { + addCriterion("MODIFY_TIME between", value1, value2, MODIFY_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value1 + * @param value2 + * @return + */ + public Criteria andModifyTimeNotBetween(Date value1, Date value2) { + addCriterion("MODIFY_TIME not between", value1, value2, MODIFY_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @return + */ + public Criteria andDeleteTimeIsNull() { + addCriterion("DELETE_TIME is null"); + return (Criteria) this; + } + + /** + * <br> + * + * @return + */ + public Criteria andDeleteTimeIsNotNull() { + addCriterion("DELETE_TIME is not null"); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andDeleteTimeEqualTo(Date value) { + addCriterion("DELETE_TIME =", value, DELETE_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andDeleteTimeNotEqualTo(Date value) { + addCriterion("DELETE_TIME <>", value, DELETE_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andDeleteTimeGreaterThan(Date value) { + addCriterion("DELETE_TIME >", value, DELETE_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andDeleteTimeGreaterThanOrEqualTo(Date value) { + addCriterion("DELETE_TIME >=", value, DELETE_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andDeleteTimeLessThan(Date value) { + addCriterion("DELETE_TIME <", value, DELETE_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value + * @return + */ + public Criteria andDeleteTimeLessThanOrEqualTo(Date value) { + addCriterion("DELETE_TIME <=", value, DELETE_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param values + * @return + */ + public Criteria andDeleteTimeIn(List<Date> values) { + addCriterion("DELETE_TIME in", values, DELETE_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param values + * @return + */ + public Criteria andDeleteTimeNotIn(List<Date> values) { + addCriterion("DELETE_TIME not in", values, DELETE_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value1 + * @param value2 + * @return + */ + public Criteria andDeleteTimeBetween(Date value1, Date value2) { + addCriterion("DELETE_TIME between", value1, value2, DELETE_TIME); + return (Criteria) this; + } + + /** + * <br> + * + * @param value1 + * @param value2 + * @return + */ + public Criteria andDeleteTimeNotBetween(Date value1, Date value2) { + addCriterion("DELETE_TIME not between", value1, value2, DELETE_TIME); + return (Criteria) this; + } + } + + /** + * <br> + * <p> + * </p> + * + * @author z00292420 + * @date 2016-9-14 + */ + public static class Criteria extends GeneratedCriteria { + + protected Criteria() { + super(); + } + } + + /** + * Criterion + * .</br> + * + * @author + * @version NFVO 0.5 Sep 14, 2016 + */ + public static class Criterion { + private String condition; + + private Object value; + + private Object secondValue; + + private boolean noValue; + + private boolean singleValue; + + private boolean betweenValue; + + private boolean listValue; + + private String typeHandler; + + + + /** + * Constructor<br/> + * <p> + * </p> + * + * @param condition + */ + protected Criterion(String condition) { + super(); + this.condition = condition; + this.typeHandler = null; + this.noValue = true; + } + + /** + * Constructor<br/> + * <p> + * </p> + * + * @param condition + * @param value + * @param typeHandler + */ + protected Criterion(String condition, Object value, String typeHandler) { + super(); + this.condition = condition; + this.value = value; + this.typeHandler = typeHandler; + if (value instanceof List<?>) { + this.listValue = true; + } else { + this.singleValue = true; + } + } + + /** + * Constructor<br/> + * <p> + * </p> + * + * @param condition + * @param value + */ + protected Criterion(String condition, Object value) { + this(condition, value, null); + } + + /** + * Constructor<br/> + * <p> + * </p> + * + * @param condition + * @param value + * @param secondValue + * @param typeHandler + */ + protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { + super(); + this.condition = condition; + this.value = value; + this.secondValue = secondValue; + this.typeHandler = typeHandler; + this.betweenValue = true; + } + + /** + * Constructor<br/> + * <p> + * </p> + * + * @param condition + * @param value + * @param secondValue + */ + protected Criterion(String condition, Object value, Object secondValue) { + this(condition, value, secondValue, null); + } + + + /** + * <br> + * + * @return + */ + public String getCondition() { + return condition; + } + + /** + * <br> + * + * @return + */ + public Object getValue() { + return value; + } + + /** + * <br> + * + * @return + */ + public Object getSecondValue() { + return secondValue; + } + + /** + * <br> + * + * @return + */ + public boolean isNoValue() { + return noValue; + } + + /** + * <br> + * + * @return + */ + public boolean isSingleValue() { + return singleValue; + } + + /** + * <br> + * + * @return + */ + public boolean isBetweenValue() { + return betweenValue; + } + + /** + * <br> + * + * @return + */ + public boolean isListValue() { + return listValue; + } + + /** + * <br> + * + * @return + */ + public String getTypeHandler() { + return typeHandler; + } + } +}
\ No newline at end of file diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/MSBRequestEntity.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/MSBRequestEntity.java new file mode 100644 index 0000000..4ac27f2 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/MSBRequestEntity.java @@ -0,0 +1,370 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.entity; + +import java.io.Serializable; +import java.util.List; + +import org.openo.nfvo.jujuvnfmadapter.common.EntityUtils; + +/** + * <br/> + * <p> + * The request parameters of Register service to the Microservice Bus + * URL-path: /openoapi/microservices/v1/services + * example: + * { + * "serviceName": "catalog", + * "version": "v1", + * "url": "/openoapi/catalog/v1", + * "protocol": "REST", + * "visualRange": ["1"], + * "nodes": [ + * { + * "ip": "10.74.56.36", + * "port": "8988", + * "ttl": 0 + * } + * ] + * } + * </p> + * <p> + * the response example: + * { + * "serviceName": "catalog", + * "version": "v1", + * "url": "/openoapi/catalog/v1", + * "protocol": "REST", + * "visualRange": ["1"], + * "nodes": [ + * { + * "ip": "10.74.55.66", + * "port": "6666", + * "ttl": 0, + * "expiration": "2016-02-18T16:19:40+08:00", + * "created_at": "2016-02-18T16:03:00+08:00", + * "updated_at": "2016-02-18T16:03:00+08:00" + * }, + * { + * "ip": "10.74.56.37", + * "port": "8989", + * "ttl": 0, + * "expiration": "2016-02-18T16:13:00+08:00", + * "created_at": "2016-02-18T16:03:00+08:00", + * "updated_at": "2016-02-18T16:03:00+08:00" + * }, + * { + * "ip": "10.74.56.36", + * "port": "8988", + * "ttl": 0, + * "expiration": "2016-02-18T17:04:36+08:00", + * "created_at": "2016-02-18T16:03:00+08:00", + * "updated_at": "2016-02-18T16:03:00+08:00" + * } + * ], + * "status": "1" + * } + * the params description: + * serviceName: service name + * version: version + * url: url of the created service instance + * protocol: supported protocols: 'REST', 'UI' + * nodes: the service instance nodes list to register + * ip: the ip of the service instance node, it could also be a hostname like catalog.openo.org + * port: the port of the service instance node + * ttl: time to live, this parameter is reserved for later use + * status: service status, 1: eanbled, 0:disabled + * </p> + * + * @author + * @version NFVO 0.5 Aug 18, 2016 + */ +public class MSBRequestEntity implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -4548158998952436572L; + + private String serviceName; + + private String version; + + /** + * the actual URL of the service to be registered + */ + private String url; + + /** + * supported protocols: 'REST', 'UI' + */ + private String protocol = "REST"; + + /** + * Visibility of the service. + * External(can be accessed by external systems):0 + * Internal(can only be accessed by OPEN-O consumers):1 + */ + private String visualRange = "1"; + + /** + * only exist in response; + * status: service status, 1: eanbled, 0:disabled + */ + private String status; + + /** + * ip: the ip of the service instance node, it could also be a hostname like catalog.openo.org + * port: the port of the service instance node + * ttl: time to live, this parameter is reserved for later use + */ + private List<Node> nodes; + + /** + * @return Returns the serviceName. + */ + public String getServiceName() { + return serviceName; + } + + /** + * @param serviceName The serviceName to set. + */ + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + /** + * @return Returns the version. + */ + public String getVersion() { + return version; + } + + /** + * @param version The version to set. + */ + public void setVersion(String version) { + this.version = version; + } + + /** + * @return Returns the url. + */ + public String getUrl() { + return url; + } + + /** + * @param url The url to set. + */ + public void setUrl(String url) { + this.url = url; + } + + /** + * @return Returns the protocol. + */ + public String getProtocol() { + return protocol; + } + + /** + * @param protocol The protocol to set. + */ + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + /** + * @return Returns the visualRange. + */ + public String getVisualRange() { + return visualRange; + } + + /** + * @param visualRange The visualRange to set. + */ + public void setVisualRange(String visualRange) { + this.visualRange = visualRange; + } + + /** + * @return Returns the status. + */ + public String getStatus() { + return status; + } + + /** + * @param status The status to set. + */ + public void setStatus(String status) { + this.status = status; + } + + /** + * @return Returns the nodes. + */ + public List<Node> getNodes() { + return nodes; + } + + /** + * @param nodes The nodes to set. + */ + public void setNodes(List<Node> nodes) { + this.nodes = nodes; + } + + /** + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 18, 2016 + */ + public static class Node implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 7618395945064516270L; + + private String ip; + + private String port; + + private String ttl; + + private String expiration; + + private String createdAt; + + private String updatedAt; + + /** + * @return Returns the ip. + */ + public String getIp() { + return ip; + } + + /** + * @param ip The ip to set. + */ + public void setIp(String ip) { + this.ip = ip; + } + + /** + * @return Returns the port. + */ + public String getPort() { + return port; + } + + /** + * @param port The port to set. + */ + public void setPort(String port) { + this.port = port; + } + + /** + * @return Returns the ttl. + */ + public String getTtl() { + return ttl; + } + + /** + * @param ttl The ttl to set. + */ + public void setTtl(String ttl) { + this.ttl = ttl; + } + + /** + * @return Returns the expiration. + */ + public String getExpiration() { + return expiration; + } + + /** + * @param expiration The expiration to set. + */ + public void setExpiration(String expiration) { + this.expiration = expiration; + } + + /** + * @return Returns the created_at. + */ + public String getCreatedAt() { + return createdAt; + } + + /** + * @param createdAt The created_at to set. + */ + public void setCreatedAt(String createdAt) { + this.createdAt = createdAt; + } + + /** + * @return Returns the updated_at. + */ + public String getUpdatedAt() { + return updatedAt; + } + + /** + * @param updatedAt The updated_at to set. + */ + public void setUpdatedAt(String updatedAt) { + this.updatedAt = updatedAt; + } + + /** + * <br/> + * + * @return + * @since NFVO 0.5 + */ + @Override + public String toString() { + return EntityUtils.toString(this, Node.class); + } + + } + + /** + * <br/> + * + * @return + * @since NFVO 0.5 + */ + @Override + public String toString() { + return EntityUtils.toString(this, MSBRequestEntity.class); + } + +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/Vnfm.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/Vnfm.java new file mode 100644 index 0000000..b08b2f5 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/Vnfm.java @@ -0,0 +1,232 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.entity; + +import java.text.SimpleDateFormat; +import java.util.Date; + +import net.sf.json.JSONObject; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.openo.nfvo.jujuvnfmadapter.common.CryptUtil; +import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant; + +/** + * + * VNFM class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 12, 2016 + */ +public class Vnfm { + + private String id; + + private String name; + + private String type; + + private String version; + + private String userName; + + private String pwd; + + private String url; + + private String sites; + + private String extraInfo; + + private String status; + + private String createAt; + + private String updateAt; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getPwd() { + return pwd; + } + + public void setPwd(String pwd) { + this.pwd = pwd; + } + + public String getSites() { + return sites; + } + + public void setSites(String sites) { + this.sites = sites; + } + + public String getExtraInfo() { + return extraInfo; + } + + public void setExtraInfo(String extraInfo) { + this.extraInfo = extraInfo; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getCreateAt() { + return createAt; + } + + public void setCreateAt(String createAt) { + this.createAt = createAt; + } + + public String getUpdateAt() { + return updateAt; + } + + public void setUpdateAt(String updateAt) { + this.updateAt = updateAt; + } + + + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if(this == obj) { + return true; + } + if(obj == null) { + return false; + } + if(!(obj instanceof Vnfm)) { + return false; + } + if(getClass() != obj.getClass()) { + return false; + } + Vnfm other = (Vnfm)obj; + if(id == null) { + if(other.id != null) { + return false; + } + } else if(!id.equals(other.id)) { + return false; + } + return true; + } + + /** + * + * Update Vnfm.<br> + * + * @param otherVnfm + * @since NFVO 0.5 + */ + public void updateVnfm(JSONObject otherVnfm) { + String vnfmName = otherVnfm.getString("name"); + String vnfmUserName = otherVnfm.getString("userName"); + String vnfmPwd = CryptUtil.enCrypt(otherVnfm.getString("pwd")); + + if(!StringUtils.isEmpty(vnfmName)) { + this.name = vnfmName; + } + + if(!StringUtils.isEmpty(vnfmUserName)) { + this.userName = vnfmUserName; + } + + if(!StringUtils.isEmpty(vnfmPwd)) { + this.pwd = vnfmPwd; + } + + String vnfmExtraInfo = otherVnfm.get("extraInfo").toString(); + if(!StringUtils.isEmpty(vnfmExtraInfo)) { + this.extraInfo = vnfmExtraInfo; + } + + this.updateAt = new SimpleDateFormat(Constant.DATE_FORMAT).format(new Date()); + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/VnfmOpResult.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/VnfmOpResult.java new file mode 100644 index 0000000..9c3e626 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/entity/VnfmOpResult.java @@ -0,0 +1,125 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.entity; + +import java.util.ArrayList; +import java.util.List; + +/** + * + * Vnfm operation result class.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 10, 2016 + */ +public class VnfmOpResult { + + private String errorMessage; + + /** + * + * Task status enumerator.<br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 10, 2016 + */ + public enum TaskStatus { + INIT, SUCCESS, FAIL, PART_SUCCESS, RUNNING, TIMEOUT + } + + private TaskStatus operateStatus; + + private List<Object> results = new ArrayList<>(10); + + private int errorCode; + + /** + * + * Constructor<br> + * <p> + * </p> + * + * @since NFVO 0.5 + */ + public VnfmOpResult() { + operateStatus = TaskStatus.INIT; + errorMessage = ""; + errorCode = 0; + } + + /** + * + * Constructor<br> + * <p> + * </p> + * + * @param operateStatus + * @param errorMessage + * @since NFVO 0.5 + */ + public VnfmOpResult(TaskStatus operateStatus, String errorMessage) { + this.operateStatus = operateStatus; + this.errorMessage = errorMessage; + errorCode = 0; + } + + public void setOperateStatus(TaskStatus operateStatus) { + this.operateStatus = operateStatus; + } + + public TaskStatus getOperateStatus() { + return operateStatus; + } + + public List<Object> getResult() { + return results; + } + + /** + * + * Add Result.<br> + * + * @param result + * @since NFVO 0.5 + */ + @SuppressWarnings("unchecked") + public void addResult(Object result) { + if(result instanceof List<?>) { + this.results.addAll((List<Object>)result); + } else { + this.results.add(result); + } + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public String getErrorMessage() { + return errorMessage; + } + + @Override + public String toString() { + return getClass().getName() + "@[" + "operateStatus=" + operateStatus + ", " + "errorCode=" + errorCode + ", " + + "errorMessage=" + errorMessage + "]"; + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/exception/UnsupportedOperationException.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/exception/UnsupportedOperationException.java new file mode 100644 index 0000000..4d213e5 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/exception/UnsupportedOperationException.java @@ -0,0 +1,34 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.exception; + +/** + * <br/> + * <p> + * + * </p> + * + * @author + * @version NFVO 0.5 Aug 18, 2016 + */ +public class UnsupportedOperationException extends RuntimeException { + + /** + * + */ + private static final long serialVersionUID = 7599989642681309581L; +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/juju/JujuClientUtils.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/juju/JujuClientUtils.java new file mode 100644 index 0000000..1e72f04 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/juju/JujuClientUtils.java @@ -0,0 +1,97 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.juju; + +import org.python.core.PyInteger; +import org.python.core.PyObject; +import org.python.core.PyString; + +/** + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 22, 2016 + */ +public class JujuClientUtils { + + private static PyObjectFactory factory ; + + + private JujuClientUtils() { + // private constructor + } + + /** + * call this to connect JUJU VNFM + * <br/> + * + * @param envName + * @since NFVO 0.5 + */ + public static void init(String envName){ + factory = PyObjectFactory.build(envName); + } + + /** + * <br> + * + * @param serviceName + * @param charmUrl + * @return pyObject + */ + public static PyObject setCharm(String serviceName,String charmUrl){ + return factory.execute("set_charm", new PyString(serviceName), new PyString(charmUrl)); + } + /** + * <br> + * + * @param vnfInstanceId + * @param vnfmId + * @return pyObject + */ + public static PyObject getVnfStatus(String vnfInstanceId,String vnfmId){ + return null; + } + + /** + * <br> + * + * @param serviceName + * @param charmUrl + * @param numUnits + * @return pyObject + */ + public static PyObject deployService(String serviceName,String charmUrl, int numUnits){ + PyObject[] arrys = new PyObject[]{new PyString(serviceName), new PyString(charmUrl), new PyInteger(numUnits)}; + return factory.execute("deploy", arrys); + } + /** + * Destory a service and all of it's units. + * <br/> + * + * @param serviceName + * @param charmUrl + * @param numUnits + * @return + * @since NFVO 0.5 + */ + public static PyObject destoryService(String serviceName){ + return factory.execute("deploy",new PyString(serviceName)); + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/juju/JujuHelper.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/juju/JujuHelper.java new file mode 100644 index 0000000..ae0bffa --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/juju/JujuHelper.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2016, Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.juju; + +import org.apache.commons.lang3.StringUtils; + +/** + * <br/> + * <p> + * </p> + * + * @author quanzhong@huawei.com + * @version NFVO 0.5 Nov 4, 2016 + */ +public class JujuHelper { + + /** + * 1\ toLowerCase + * 2\remove the extension + * 3\remove the underline + * <br/> + * + * @param appName + * @return + * @since NFVO 0.5 + */ + public static String getModelName(String appName){ + if(StringUtils.isBlank(appName)){ + return appName; + } + char c = '.'; + String modelName = appName; + modelName = modelName.toLowerCase(); + if(modelName.indexOf(c) > -1){ + modelName = modelName.substring(0,modelName.indexOf(c)); + } + return modelName.replaceAll("_", ""); + + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/juju/PyObjectFactory.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/juju/PyObjectFactory.java new file mode 100644 index 0000000..2d98290 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/juju/PyObjectFactory.java @@ -0,0 +1,104 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.juju; + +import org.python.core.PyObject; +import org.python.core.PyString; +import org.python.util.PythonInterpreter; + +/** + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 22, 2016 + */ +public class PyObjectFactory { + + private static PyObject environmentClass; + + private static PyObject environmentObj; + + /** + * <br> + * + * @param envName + * @return + * @since NFVO 0.5 + */ + public static PyObjectFactory build(String envName) { + PythonInterpreter interpreter = new PythonInterpreter(); + + interpreter.exec("from jujuclient import Environment"); + + environmentClass = interpreter.get("Environment"); + PyObject env = environmentClass.__call__(); + environmentObj = env.invoke("connect", new PyString(envName)); + return new PyObjectFactory(); + } + + /** + * <br> + * + * @param methodName + * @return + * @since NFVO 0.5 + */ + public PyObject execute(String methodName) { + environmentObj.toString(); + return environmentObj.invoke(methodName); + } + + /** + * <br> + * + * @param methodName + * @param args + * @return + * @since NFVO 0.5 + */ + public PyObject execute(String methodName, PyObject args) { + return environmentObj.invoke(methodName, args); + } + + /** + * <br> + * + * @param methodName + * @param arg1 + * @param arg2 + * @return + * @since NFVO 0.5 + */ + public PyObject execute(String methodName, PyObject arg1, PyObject arg2) { + return environmentObj.invoke(methodName, arg1, arg2); + } + + /** + * <br> + * + * @param methodName + * @param args + * @return + * @since NFVO 0.5 + */ + public PyObject execute(String methodName, PyObject[] args) { + return environmentObj.invoke(methodName, args); + } + +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/juju/config/Config.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/juju/config/Config.java new file mode 100644 index 0000000..21c0cbc --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/juju/config/Config.java @@ -0,0 +1,45 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.juju.config; + +import java.util.Map; + +/** + * Created by QuanZhong on 2016/12/1. + */ +public class Config { + public Config(Map<String, ConfigItem> options) { + this.options = options; + } + + private Map<String,ConfigItem> options; + + public Map<String, ConfigItem> getOptions() { + return options; + } + + public void setOptions(Map<String, ConfigItem> options) { + this.options = options; + } + + @Override + public String toString() { + return "Config{" + + "options=" + options + + '}'; + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/juju/config/ConfigItem.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/juju/config/ConfigItem.java new file mode 100644 index 0000000..7edf0b5 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/juju/config/ConfigItem.java @@ -0,0 +1,60 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.juju.config; + +/** + * Created by QuanZhong on 2016/12/1. + */ +public class ConfigItem { + + private String defaults; + private String description; + private String type; + + public String getDefaults() { + return defaults; + } + + public void setDefaults(String defaults) { + this.defaults = defaults; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + @Override + public String toString() { + return "ConfigItem{" + + "defaults='" + defaults + '\'' + + ", description='" + description + '\'' + + ", type='" + type + '\'' + + '}'; + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/juju/config/Options.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/juju/config/Options.java new file mode 100644 index 0000000..110b9a2 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/juju/config/Options.java @@ -0,0 +1,23 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.juju.config; + +/** + * Created by QuanZhong on 2016/12/1. + */ +public class Options { +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/mapper/JujuVnfmInfoMapper.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/mapper/JujuVnfmInfoMapper.java new file mode 100644 index 0000000..2b2da41 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/mapper/JujuVnfmInfoMapper.java @@ -0,0 +1,149 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.mapper; + +import java.util.List; + + +import org.apache.ibatis.annotations.Param; +import org.openo.nfvo.jujuvnfmadapter.service.entity.JujuVnfmInfo; +import org.openo.nfvo.jujuvnfmadapter.service.entity.JujuVnfmInfoExample; + +/** + * <br> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 14, 2016 + */ +public interface JujuVnfmInfoMapper { + /** + * <br> + * + * @param example + * @return int + */ + int countByExample(JujuVnfmInfoExample example); + + /** + * <br> + * + * @param example + * @return int + */ + int deleteByExample(JujuVnfmInfoExample example); + + /** + * <br> + * + * @param id + * @return int + */ + int deleteByPrimaryKey(String id); + + /** + * <br> + * + * @param record + * @return int + */ + int insert(JujuVnfmInfo record); + + /** + * <br> + * + * @param record + * @return int + */ + int insertSelective(JujuVnfmInfo record); + + /** + * <br> + * + * @param example + * @return list + */ + List<JujuVnfmInfo> selectByExampleWithBLOBs(JujuVnfmInfoExample example); + + /** + * <br> + * + * @param example + * @return list + */ + List<JujuVnfmInfo> selectByExample(JujuVnfmInfoExample example); + + /** + * <br> + * + * @param id + * @return jujuVnfmInfo + */ + JujuVnfmInfo selectByPrimaryKey(String id); + + /** + * <br> + * + * @param record + * @param example + * @return int + */ + int updateByExampleSelective(@Param("record") JujuVnfmInfo record, @Param("example") JujuVnfmInfoExample example); + + /** + * <br> + * + * @param record + * @param example + * @return int + */ + int updateByExampleWithBLOBs(@Param("record") JujuVnfmInfo record, @Param("example") JujuVnfmInfoExample example); + + /** + * <br> + * + * @param record + * @param example + * @return int + */ + int updateByExample(@Param("record") JujuVnfmInfo record, @Param("example") JujuVnfmInfoExample example); + + /** + * <br> + * + * @param record + * @return int + */ + int updateByPrimaryKeySelective(JujuVnfmInfo record); + + /** + * <br> + * + * @param record + * @return int + */ + int updateByPrimaryKeyWithBLOBs(JujuVnfmInfo record); + + /** + * <br> + * + * @param record + * @return int + */ + int updateByPrimaryKey(JujuVnfmInfo record); +}
\ No newline at end of file diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/process/VnfMgr.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/process/VnfMgr.java new file mode 100644 index 0000000..8dc6070 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/process/VnfMgr.java @@ -0,0 +1,403 @@ +/* + * Copyright 2016-2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.process; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang.StringUtils; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.jujuvnfmadapter.common.EntityUtils; +import org.openo.nfvo.jujuvnfmadapter.common.SwitchController; +import org.openo.nfvo.jujuvnfmadapter.common.VnfmUtil; +import org.openo.nfvo.jujuvnfmadapter.common.servicetoken.VnfmRestfulUtil; +import org.openo.nfvo.jujuvnfmadapter.service.adapter.inf.IResourceManager; +import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant; +import org.openo.nfvo.jujuvnfmadapter.service.constant.UrlConstant; +import org.openo.nfvo.jujuvnfmadapter.service.entity.JujuVnfmInfo; +import org.openo.nfvo.jujuvnfmadapter.service.entity.JujuVnfmInfoExample; +import org.openo.nfvo.jujuvnfmadapter.service.mapper.JujuVnfmInfoMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONException; +import net.sf.json.JSONObject; + +/** + * Provide function for instantiate or terminate VNF + * <br/> + * + * @author + * @version NFVO 0.5 Aug 24, 2016 + */ +public class VnfMgr { + + private static final Logger LOG = LoggerFactory.getLogger(VnfMgr.class); + private JujuVnfmInfoMapper jujuVnfmInfoMapper; + private IResourceManager resourceManager; + + public IResourceManager getResourceManager() { + return resourceManager; + } + + public void setResourceManager(IResourceManager resourceManager) { + this.resourceManager = resourceManager; + } + + /** + * @return Returns the jujuVnfmInfoMapper. + */ + public JujuVnfmInfoMapper getJujuVnfmInfoMapper() { + return jujuVnfmInfoMapper; + } + + + /** + * @param jujuVnfmInfoMapper The jujuVnfmInfoMapper to set. + */ + public void setJujuVnfmInfoMapper(JujuVnfmInfoMapper jujuVnfmInfoMapper) { + this.jujuVnfmInfoMapper = jujuVnfmInfoMapper; + } + + /** + * Provide function for instantiate VNF + * <br/> + * + * @param vnfObject + * @param vnfmId + * @return + * @since NFVO 0.5 + */ + public JSONObject addVnf(JSONObject vnfObject, String vnfmId) { + JSONObject restJson = new JSONObject(); + restJson.put(EntityUtils.RESULT_CODE_KEY, Constant.REST_FAIL); + try { + + if(vnfObject.isNullObject() || vnfObject.isEmpty()) { + return restJson; + } + String vnfInstanceName = vnfObject.getString("vnfInstanceName"); + String csarId = vnfObject.getString("vnfPackageId"); + String url = null; + try { + url = vnfObject.getString("vnfmServiceUrl"); + } catch (Exception e) { + LOG.warn("the value 'vnfmServiceUrl' not exist."+e.getMessage()); + } + if (StringUtils.isBlank(url)) { + url = SwitchController.vnfmServiceUrl; + } + if (StringUtils.isBlank(url)) { + JSONObject vnfmObject = VnfmUtil.getVnfmById(vnfmId); + + if(vnfmObject == null || vnfmObject.isNullObject()) { + LOG.error("function=addVnf, msg=Unable to get the jujuvnfm info from the 'ESR', vnfmId: {}", vnfmId); + return restJson; + } + url = vnfmObject.getString("url"); + } + //call juju-cliento deploy + JSONObject params = new JSONObject(); + params.put(Constant.VNFM_ID, vnfmId); + params.put("appName", vnfInstanceName); + params.put("csarId", csarId); + + + Map<String, String> paramsMap = new HashMap<>(6); + paramsMap.put("url", url); + paramsMap.put(Constant.METHOD_TYPE, Constant.POST); + paramsMap.put("path", UrlConstant.REST_JUJU_CLIENT_DEPLOY); + paramsMap.put(Constant.AUTH_MODE, Constant.AuthenticationMode.ANONYMOUS); + RestfulResponse rsp = VnfmRestfulUtil.getRemoteResponse(paramsMap, params.toString(), null); + if(rsp == null) { + LOG.error("function=addVnf, msg=send create vnf msg to csm get wrong results"); + return restJson; + } + + int statusCode = rsp.getStatus(); + if(statusCode == Constant.HTTP_CREATED || statusCode == Constant.HTTP_OK) { + JSONObject res = JSONObject.fromObject(rsp.getResponseContent()); + String vnfId = res.getString("vnfId"); + saveJujuVnfmInfo(vnfInstanceName,vnfId,vnfId,vnfmId,vnfObject); + restJson.put(EntityUtils.RESULT_CODE_KEY, Constant.REST_SUCCESS); + JSONObject resultObj = new JSONObject(); + resultObj.put("vnfInstanceId", vnfId); + resultObj.put("jobId", vnfId + "_" + Constant.POST); + restJson.put("data", resultObj); + } else { + LOG.error("function=createVnf, msg=send create vnf msg to csm get wrong status: " + statusCode); + } + + } catch(JSONException e) { + LOG.error("function=addVnf, msg=JSONException occurs, e={}.", e); + } + LOG.info("request:{},response:{}", vnfmId, restJson.toString()); + return restJson; + } + + /** + * + * <br/> + * + * @param csarId + * @return + * @since NFVO 0.5 + */ + public String getCharmPath(String csarId){ + try { + JSONObject res = resourceManager.getVnfdInfo(csarId); + if(res != null && res.getString("csarFilePath") != null){ + return res.getString("csarFilePath"); + } + } catch(Exception e) { + LOG.error("get charmPath fail:csarId="+csarId,e); + } + LOG.warn("get charmPath fail:csarId="+csarId); + return null; + } + /** + * save object to db + * <br/> + * + * @param appName + * @param jobId + * @param vnfId + * @param vnfmId + * @since NFVO 0.5 + */ + private void saveJujuVnfmInfo(String appName,String jobId,String vnfId,String vnfmId, JSONObject vnfObject){ + JujuVnfmInfo record = new JujuVnfmInfo(); + record.setId(UUID.randomUUID().toString()); + record.setAppName(appName); + record.setJobId(jobId); + record.setVnfId(vnfId); + record.setVnfmId(vnfmId); + record.setStatus(0); + record.setCreateTime(new Date()); + record.setModifyTime(new Date()); + record.setExtend(vnfObject.toString()); + jujuVnfmInfoMapper.insert(record); + } + /** + * delete the object by vnfid + * <br/> + * + * @param vnfId + * @since NFVO 0.5 + */ + private void delJujuVnfmInfo(String vnfId){ + JujuVnfmInfoExample example = new JujuVnfmInfoExample(); + example.createCriteria().andVnfIdEqualTo(vnfId); + jujuVnfmInfoMapper.deleteByExample(example); + } + + /** + * findByVnfId from db + * <br/> + * + * @param vnfId + * @return + * @since NFVO 0.5 + */ + private JujuVnfmInfo findByVnfId(String vnfId){ + JujuVnfmInfoExample example = new JujuVnfmInfoExample(); + example.createCriteria().andVnfIdEqualTo(vnfId); + List<JujuVnfmInfo> list = jujuVnfmInfoMapper.selectByExample(example); + if(CollectionUtils.isNotEmpty(list) && !list.isEmpty()){ + return list.get(0); + } + return null; + } + + /** + * Provide function for terminate VNF + * <br/> + * + * @param vnfId + * @param vnfmId + * @param vnfObject + * @return + * @since NFVO 0.5 + */ + public JSONObject deleteVnf(String vnfId, String vnfmId, JSONObject vnfObject) { + LOG.warn("function=deleteVnf ,msg=enter to delete a vnf, vnfId:{}, vnfmId:{}", vnfId, vnfmId); + JSONObject restJson = new JSONObject(); + restJson.put(EntityUtils.RESULT_CODE_KEY, Constant.REST_FAIL); + try { + String url = SwitchController.vnfmServiceUrl; + + if (StringUtils.isBlank(url)) { + JSONObject vnfmObject = VnfmUtil.getVnfmById(vnfmId); + if(vnfmObject==null || vnfmObject.isNullObject()) { + LOG.error("function=deleteVnf, msg=Unable to get the jujuvnfm info from the 'ESR', vnfmId: {}", vnfmId); + return restJson; + } + url = vnfmObject.getString("url"); + } + + String vnfInstanceName = ""; + JujuVnfmInfo jujuInfo = findByVnfId(vnfId); + if(jujuInfo != null){ + vnfInstanceName = jujuInfo.getAppName(); + } + JSONObject params = new JSONObject(); + params.put(Constant.VNFM_ID, vnfmId); + params.put("appName", vnfInstanceName); + params.put("vnfId", vnfId); + + Map<String, String> paramsMap = new HashMap<>(6); + paramsMap.put("url", url); + paramsMap.put(Constant.METHOD_TYPE, Constant.POST); + paramsMap.put("path", UrlConstant.REST_JUJU_CLIENT_DESTORY); + paramsMap.put(Constant.AUTH_MODE, Constant.AuthenticationMode.ANONYMOUS); + RestfulResponse rsp = VnfmRestfulUtil.getRemoteResponse(paramsMap, params.toString(), null); + if(rsp == null) { + LOG.error("function=deleteVnf, msg=send create vnf msg to csm get wrong results"); + return restJson; + } + + int statusCode = rsp.getStatus(); + if(statusCode == Constant.UNREG_SUCCESS) { + restJson.put(EntityUtils.RESULT_CODE_KEY, Constant.REST_SUCCESS); + JSONObject resultObj = new JSONObject(); + resultObj.put("jobId", vnfId + "_" + Constant.DELETE); + restJson.put("data", resultObj); + delJujuVnfmInfo(vnfId); + } else { + LOG.error("function=removeVnf, msg=send remove vnf msg to csm get wrong status: {}", statusCode); + } + + } catch(JSONException e) { + LOG.error("function=deleteVnf, msg=JSONException occurs, e={}.", e); + } + return restJson; + } + + /** + * Provide function for get VNF + * <br/> + * + * @param vnfId + * @param vnfmId + * @return + * @since NFVO 0.5 + */ + public JSONObject getVnf(String vnfId, String vnfmId) { + LOG.warn("function=getVnf ,msg=enter to get a vnf, vnfId:{}, vnfmId:{}", vnfId, vnfmId); + JSONObject restJson = new JSONObject(); + restJson.put(EntityUtils.RESULT_CODE_KEY, Constant.REST_FAIL); + try { + String url = SwitchController.vnfmServiceUrl; + JSONObject vnfmObject = null; + if (StringUtils.isBlank(url)) { + // call the ESR to get jujuvnfm server url + vnfmObject = VnfmUtil.getVnfmById(vnfmId); + if(vnfmObject==null || vnfmObject.isNullObject()) { + LOG.error("Unable to get jujuvnfm url info from the 'ESR', vnfmId: {}", vnfmId); + return restJson; + } + url = vnfmObject.getString("url"); + } + + String appName = ""; + JujuVnfmInfo jujuInfo = findByVnfId(vnfId); + if(jujuInfo != null){ + appName = jujuInfo.getAppName(); + } + JSONObject params = new JSONObject(); + params.put(Constant.VNFM_ID, vnfmId); + params.put("vnfId", vnfId); + + + Map<String, String> paramsMap = new HashMap<>(6); + paramsMap.put("url", url); + paramsMap.put(Constant.METHOD_TYPE, Constant.GET); + paramsMap.put("path", String.format(UrlConstant.REST_JUJU_CLIENT_GET,appName)); + paramsMap.put(Constant.AUTH_MODE, Constant.AuthenticationMode.ANONYMOUS); + RestfulResponse rsp = VnfmRestfulUtil.getRemoteResponse(paramsMap, params.toString(), null); + if(rsp == null) { + LOG.error("function=getVnf, msg=send create vnf msg to csm get wrong results"); + return restJson; + } + JSONObject queryResult = JSONObject.fromObject(rsp.getResponseContent()); + int statusCode = rsp.getStatus(); + if(statusCode == Constant.HTTP_OK || statusCode == Constant.HTTP_CREATED) { + if(null == (queryResult.get("data"))) { + LOG.warn("function=getVnf, msg=query is null {}", queryResult.get("data")); + return restJson; + } + restJson.put(EntityUtils.RESULT_CODE_KEY, Constant.REST_SUCCESS); + restJson.put("data", JSONObject.fromObject(queryResult.getString("data"))); + } else { + LOG.error("function=getVnf, msg=send get vnf msg to csm get wrong status: {}", statusCode); + } + return restJson.getInt(EntityUtils.RESULT_CODE_KEY) == Constant.REST_FAIL ? restJson + : getVnfBody(vnfId,appName, vnfmObject); + + } catch(JSONException e) { + LOG.error("function=getVnf, msg=JSONException occurs, e={}.", e); + restJson.put(EntityUtils.RESULT_CODE_KEY, Constant.REST_FAIL); + } + return restJson; + } + + private JSONObject getVnfBody(String vnfId,String appName, JSONObject vnfmObject) { + JSONObject vnfInfoJson = new JSONObject(); + JSONObject basicInfoJson = new JSONObject(); + + basicInfoJson.put("vnfInstanceId", vnfId); + basicInfoJson.put("vnfInstanceName", appName); + basicInfoJson.put("vnfInstanceDescription", "vFW"); + basicInfoJson.put("vnfdId", vnfmObject == null ? "" : vnfmObject.getString("vnfdId")); + basicInfoJson.put("vnfdPackageId", vnfmObject == null ? "" : vnfmObject.getString("vnfPackageId")); + basicInfoJson.put("version", vnfmObject == null ? "" : vnfmObject.getString("version")); + basicInfoJson.put("vnfProvider", "hw"); + basicInfoJson.put("vnfType", appName); + basicInfoJson.put("vnfStatus", "activie"); + + vnfInfoJson.put("vnfInfo", basicInfoJson); + vnfInfoJson.put(EntityUtils.RESULT_CODE_KEY, Constant.REST_SUCCESS); + return vnfInfoJson; + } + + /** + * Provide function for get job + * <br/> + * + * @param jobId + * @param vnfmId + * @return + * @since NFVO 0.5 + */ + public JSONObject getJob(String jobId, String vnfmId) { + LOG.info("getJob->jobId="+jobId+",vnfmId="+vnfmId); + JSONObject jobInfoJson = new JSONObject(); + JSONObject responseJson = new JSONObject(); + jobInfoJson.put("jobId",jobId); + responseJson.put("progress","100"); + responseJson.put("status","finished"); + responseJson.put("errorCode","null"); + responseJson.put("responseId",(Math.random()*10+1)); + jobInfoJson.put("responseDescriptor",responseJson); + LOG.info("get job response:"+jobInfoJson); + return jobInfoJson; + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/process/VnfResourceMgr.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/process/VnfResourceMgr.java new file mode 100644 index 0000000..434817e --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/process/VnfResourceMgr.java @@ -0,0 +1,240 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.process; + +import java.util.List; +import java.util.UUID; + +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.openo.nfvo.jujuvnfmadapter.common.SwitchController; +import org.openo.nfvo.jujuvnfmadapter.common.servicetoken.VnfmRestfulUtil; +import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant; +import org.openo.nfvo.jujuvnfmadapter.service.constant.UrlConstant; +import org.openo.nfvo.jujuvnfmadapter.service.entity.JujuVnfmInfo; +import org.openo.nfvo.jujuvnfmadapter.service.entity.JujuVnfmInfoExample; +import org.openo.nfvo.jujuvnfmadapter.service.mapper.JujuVnfmInfoMapper; +import org.python.jline.internal.Log; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONArray; +import net.sf.json.JSONException; +import net.sf.json.JSONObject; + +/** + * Provide function of resource for VNFM. + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 25, 2016 + */ +public class VnfResourceMgr { + + private static final Logger LOG = LoggerFactory.getLogger(VnfResourceMgr.class); + + private JujuVnfmInfoMapper jujuVnfmInfoMapper; + + /** + * @return Returns the jujuVnfmInfoMapper. + */ + public JujuVnfmInfoMapper getJujuVnfmInfoMapper() { + return jujuVnfmInfoMapper; + } + + /** + * @param jujuVnfmInfoMapper The jujuVnfmInfoMapper to set. + */ + public void setJujuVnfmInfoMapper(JujuVnfmInfoMapper jujuVnfmInfoMapper) { + this.jujuVnfmInfoMapper = jujuVnfmInfoMapper; + } + + /** + * Provide function of grant resource for VNFM. + * <br/> + * + * @param vnfId + * @return + * @since NFVO 0.5 + */ + public JSONObject grantVnfResource(JSONObject compute, String vnfId) { + LOG.warn("function=grantVnfResource, msg=call LCM to grant vnf resource, params: {}", compute); + JSONObject resultJson = new JSONObject(); + resultJson.put("retCode", Constant.REST_FAIL); + try { + if(SwitchController.isDebugModel()){ + resultJson.put("retCode", Constant.REST_SUCCESS); + resultJson.put("data", "{'mock_result':true}"); + return resultJson; + } + JujuVnfmInfo vnfmInfo = findByVnfId(vnfId); + String vimId = getVimId(vnfmInfo); + JSONObject reqParams = this.buildGrantReq(vimId, vnfId,compute); + + resultJson = VnfmRestfulUtil.sendReqToApp(UrlConstant.RES_VNF, Constant.POST, reqParams); + } catch(JSONException e) { + LOG.error("function=grantVnfResource, msg=parse params occoured JSONException e={}.", e); + resultJson.put("errorMsg", "params parse exception"); + } + + return resultJson; + } + + /** + * { + "vnfInstanceId": 1, + "addResource": [ + { + "resourceDefinitionId": "11111", + "resourceTemplate": { + "VirtualComputeDescriptor": { + "virtualCpu": { + "numVirtualCpu": 1 + }, + "virtualMemory": { + "virtualMemSize": 1//mem in MB + } + }, + "VirtualStorageDescriptor": { + "typeOfStorage": "", + "sizeOfStorage": 111, //disk in GB + "swImageDescriptor": "" + } + }, + "type": "vdu", + "vdu": "vdu_name" + } + ], + "vimId":"", + "removeResource": [], + "additionalParam": {} +} + * + * <br/> + * + * @return + * @since NFVO 0.5 + */ + private JSONObject buildGrantReq(String vimId, String vnfInstanceId,JSONObject compute){ + JSONObject obj = new JSONObject(); + obj.put("vnfInstanceId", vnfInstanceId); + obj.put("vimId", vimId); + obj.put("additionalParam", new JSONObject()); + JSONArray array = new JSONArray(); + JSONObject resource = new JSONObject(); + resource.put("resourceDefinitionId", UUID.randomUUID().toString()); + resource.put("type", "vdu"); + resource.put("vdu", "vdu_name");//vdu_name? + JSONObject resourceTemplate = new JSONObject(); + JSONObject virtualComputeDescriptor = new JSONObject(); + JSONObject virtualCpu = new JSONObject(); + JSONObject virtualMemory = new JSONObject(); + virtualCpu.put("numVirtualCpu", compute.get("cpu") !=null?compute.get("cpu"):0); + virtualMemory.put("virtualMemSize", compute.get("mem") !=null?compute.get("mem"):0); + virtualComputeDescriptor.put("virtualCpu", virtualCpu); + virtualComputeDescriptor.put("virtualMemory", virtualMemory); + JSONObject virtualStorageDescriptor = new JSONObject(); + virtualStorageDescriptor.put("typeOfStorage", ""); + virtualStorageDescriptor.put("swImageDescriptor", ""); + virtualStorageDescriptor.put("sizeOfStorage", compute.get("disk") !=null?compute.get("disk"):0); + resourceTemplate.put("VirtualComputeDescriptor", virtualComputeDescriptor); + resourceTemplate.put("VirtualStorageDescriptor", virtualStorageDescriptor); + resource.put("resourceTemplate", resourceTemplate); + array.add(resource); + if("addResource".equals(compute.getString("action"))){ + obj.put("addResource", array); + obj.put("removeResource", new JSONArray()); + }else{ + obj.put("removeResource", array); + obj.put("addResource", new JSONArray()); + } + Log.info("buildGrantReq->result="+obj); + return obj; + } + + /** + * { + * “vnfInstanceName”:”vFW”, + * “vnfPackageId”:”1”, + * “vnfDescriptorId”:”1”, + * “vnfInstanceDescription”:”vFW_1”, + * “extVirtualLinks”:[ + * { + * ”vlInstanceId”:”1”, + * “resourceId”:”1246”, + * ” cpdId”:”11111”, + * ”vim”: + * { + * “vimInfoId”:”1”, + * “vimid”:”1”, + * “interfaceInfo”:{ + * "vimType":”vim”, + * "apiVersion":”v2”, + * "protocolType":”http” + * } + * “accessInfo”:{ + * "tenant":”tenant_vCPE”, + * "username":”vCPE”, + * "password":”vCPE_321” + * } + * “interfaceEndpoint”:”http://10.43.21.105:80/” + * } + * } + * ] + * “additionalParam”:{ + * …… + * } + * } + * <br/> + * + * @return + * @since NFVO 0.5 + */ + private String getVimId(JujuVnfmInfo vnfmInfo) { + try { + if(vnfmInfo != null && StringUtils.isNotBlank(vnfmInfo.getExtend())){ + JSONObject json = JSONObject.fromObject(vnfmInfo.getExtend()); + JSONObject extVirtualLinkLink = json.getJSONArray("extVirtualLinks").getJSONObject(0); + String vimId = extVirtualLinkLink.getJSONObject("vim").getString("vimid"); + return vimId; + } + } catch(Exception e) { + LOG.error("vnfmInfo.getExtend() format error!please check it",e); + } + return null; + } + + /** + * findByVnfId from db + * <br/> + * + * @param vnfId + * @return + * @since NFVO 0.5 + */ + private JujuVnfmInfo findByVnfId(String vnfId) { + JujuVnfmInfoExample example = new JujuVnfmInfoExample(); + example.createCriteria().andVnfIdEqualTo(vnfId); + List<JujuVnfmInfo> list = jujuVnfmInfoMapper.selectByExample(example); + if(CollectionUtils.isNotEmpty(list) && !list.isEmpty()) { + return list.get(0); + } + return null; + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/ConfigRoa.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/ConfigRoa.java new file mode 100644 index 0000000..38c12fa --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/ConfigRoa.java @@ -0,0 +1,193 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.rest; + +import java.io.File; +import java.io.IOException; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.baseservice.roa.util.restclient.RestfulResponse; +import org.openo.nfvo.jujuvnfmadapter.common.EntityUtils; +import org.openo.nfvo.jujuvnfmadapter.common.FileUtils; +import org.openo.nfvo.jujuvnfmadapter.common.JujuConfigUtil; +import org.openo.nfvo.jujuvnfmadapter.common.EntityUtils.ExeRes; +import org.openo.nfvo.jujuvnfmadapter.common.servicetoken.JujuVnfmRestfulUtil; +import org.openo.nfvo.jujuvnfmadapter.common.servicetoken.VnfmRestfulUtil; +import org.openo.nfvo.jujuvnfmadapter.service.adapter.impl.AdapterResourceManager; +import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant; +import org.openo.nfvo.jujuvnfmadapter.service.constant.UrlConstant; +import org.openo.nfvo.jujuvnfmadapter.common.SwitchController; +import org.openo.nfvo.jujuvnfmadapter.common.VnfmUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import mockit.Mock; +import mockit.MockUp; +import net.sf.json.JSONObject; + +/** + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Sep 13, 2016 + */ +@Path("/v1/config") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class ConfigRoa { + + private static final Logger LOG = LoggerFactory.getLogger(ConfigRoa.class); + + /** + * <br/> + * + * @param context + * @param resp + * @return + * @since NFVO 0.5 + */ + @GET + @Path("/") + public String initUI(@Context HttpServletRequest context, @Context HttpServletResponse resp) { + return EntityUtils.toString(new SwitchController(), SwitchController.class); + } + + /** + * <br/> + * + * @param type + * @param context + * @param resp + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + @GET + @Path("/debug/{type}") + public boolean setDebugModel(@PathParam("type") int type, @Context HttpServletRequest context, + @Context HttpServletResponse resp) throws ServiceException { + if(type == 1) { + SwitchController.setDebugModel(true); + } else { + SwitchController.setDebugModel(false); + } + LOG.debug("change to debug model:" + SwitchController.isDebugModel()); + return SwitchController.isDebugModel(); + } + + /** + * <br/> + * + * @param methodName + * @param context + * @param resp + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + @GET + @Path("/mock/{methodName}") + public boolean mock(@PathParam("methodName") String methodName, @Context HttpServletRequest context, + @Context HttpServletResponse resp) throws ServiceException { + if("getVnfmById".equals(methodName)) { + new MockUp<VnfmUtil>() { + + @Mock + public JSONObject getVnfmById(String vnfmId) { + JSONObject json = new JSONObject(); + json.put("vnfmId", vnfmId); + json.put("vnfdId", "testVnfdId"); + json.put("vnfPackageId", "testPackageId"); + json.put("version", "1"); + json.put("url", JujuConfigUtil.getValue("jujuvnfm_server_url")); + return json; + } + }; + } else if("execute".equals(methodName)) { + new MockUp<EntityUtils>() { + + @Mock + public ExeRes execute(String dir, List<String> command) { + ExeRes er = new ExeRes(); + String resContent = null; + try { + resContent = new String( + FileUtils.readFile(new File(JujuConfigUtil.getValue("juju_cmd_res_file")), "UTF-8")); + } catch(Exception e) { + LOG.error("mock fail",e); + resContent = "mock fail"; + } + er.setBody(resContent); + return er; + } + }; + }else if("fetchDownloadUrlFromCatalog".equals(methodName)) { + new MockUp<AdapterResourceManager>() { + @Mock + public String fetchDownloadUrlFromCatalog(String csarId){ + return JujuConfigUtil.getValue("catalog_download_url"); + } + }; + } + return true; + } + + /** + * <br/> + * + * @param methodName + * @param context + * @param resp + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + @GET + @Path("/unmock/{methodName}") + public boolean unmock(@PathParam("methodName") String methodName, @Context HttpServletRequest context, + @Context HttpServletResponse resp) throws ServiceException { + if("getVnfmById".equals(methodName)) { + new MockUp<VnfmUtil>() { + + @Mock + public JSONObject getVnfmById(String vnfmId) { + RestfulResponse rsp = VnfmRestfulUtil.getRemoteResponse( + String.format(UrlConstant.REST_ESRINFO_GET, vnfmId), JujuVnfmRestfulUtil.GET_TYPE, null); + if(rsp == null || rsp.getStatus() != Constant.HTTP_OK) { + return null; + } + LOG.error("funtion=getVnfmById, status={}", rsp.getStatus()); + return JSONObject.fromObject(rsp.getResponseContent()); + } + }; + } + return true; + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/JujuClientRoa.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/JujuClientRoa.java new file mode 100644 index 0000000..d6e7569 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/JujuClientRoa.java @@ -0,0 +1,252 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.rest; + +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +import org.apache.commons.lang3.StringUtils; +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.nfvo.jujuvnfmadapter.common.EntityUtils; +import org.openo.nfvo.jujuvnfmadapter.common.JujuConfigUtil; +import org.openo.nfvo.jujuvnfmadapter.common.StringUtil; +import org.openo.nfvo.jujuvnfmadapter.service.adapter.impl.JujuClientManager; +import org.openo.nfvo.jujuvnfmadapter.service.adapter.inf.IJujuClientManager; +import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant; +import org.openo.nfvo.jujuvnfmadapter.service.process.VnfMgr; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * <br/> + * <p> + * </p> + * + * @author + * @version NFVO 0.5 Aug 18, 2016 + */ +@Path("/v1/vnfms") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class JujuClientRoa { + + private static final Logger LOG = LoggerFactory.getLogger(JujuClientRoa.class); + + private IJujuClientManager jujuClientManager; + private VnfMgr vnfMgr; + + /** + * @return Returns the jujuClientManager. + */ + public IJujuClientManager getJujuClientManager() { + return jujuClientManager; + } + + /** + * @param jujuClientManager The jujuClientManager to set. + */ + public void setJujuClientManager(IJujuClientManager jujuClientManager) { + this.jujuClientManager = jujuClientManager; + } + + /** + * + * @return + */ + public VnfMgr getVnfMgr() { + return vnfMgr; + } + + /** + * + * @param vnfMgr + */ + public void setVnfMgr(VnfMgr vnfMgr) { + this.vnfMgr = vnfMgr; + } + + /** + * Set Charm url for juju deployment + * <br/> + * + * @param resp + * @param context + * parameter : charmUrl + * @return "{"charmUrl":"http://dld_url"} + * @since NFVO 0.5 + */ + @POST + @Path("/setCharmUrl") + public String setCharmUrl(@Context HttpServletRequest context, @Context HttpServletResponse resp) + throws ServiceException { + JSONObject result = new JSONObject(); + result.put("retCode", Constant.REST_FAIL); + JSONObject reqJsonObject = StringUtil.getJsonFromContexts(context); + + LOG.debug(reqJsonObject + ":"); + return result.toString(); + } + + /** + * Get VNF status + * parameter: vnfInstanceId + * <br/> + * + * @param modelName + * @param resp + * @param context + * @return Depends on juju's return + * @throws ServiceException + * @since NFVO 0.5 + */ + @GET + @Path("/status") + public String getVnfStatus(@QueryParam("modelName") String modelName, @Context HttpServletRequest context, + @Context HttpServletResponse resp) throws ServiceException { + String appName = processAppName(modelName); + JSONObject result = jujuClientManager.getStatus(appName); + LOG.debug("status json str:"+result.toString()); + return result.toString(); + + + } + + /** + * Instance VNF to juju-client + * <br/> + * deployParam: depend on juju require + * + * @param resp + * @param context + * @return status: deplay result <br> + * the return data must be include "{ + * app_info:{"vnfId":123344} + * }" + * @throws ServiceException + * @since NFVO 0.5 + */ + @POST + @Path("/deploy") + public String deploySerivce(@Context HttpServletRequest context, @Context HttpServletResponse resp) + throws ServiceException { + JSONObject result = new JSONObject(); + String msg = null; + try { + result.put(EntityUtils.RESULT_CODE_KEY, EntityUtils.ExeRes.FAILURE); + JSONObject reqJsonObject = StringUtil.getJsonFromContexts(context); + LOG.info("deploySerivce request data-->"+reqJsonObject); + if(reqJsonObject == null || reqJsonObject.get(Constant.APP_NAME) == null){ + result.put(EntityUtils.MSG_KEY, "the param 'appName' can't be null"); + resp.setStatus(Constant.HTTP_INNERERROR); + return result.toString(); + } + String csarId = (String)reqJsonObject.get("csarId"); + + String appName = reqJsonObject.getString(Constant.APP_NAME); + appName = processAppName(appName); + //1、download the catalog,unzip file and get the charmPath + String charmPath = vnfMgr.getCharmPath(csarId); + if(StringUtils.isBlank(charmPath)) { + charmPath = JujuConfigUtil.getValue("charmPath"); + } + String vnfId = UUID.randomUUID().toString(); + //2、grant resource + boolean grantRes = jujuClientManager.grantResource(charmPath, appName, JujuClientManager.ADDRESOURCE, vnfId); + LOG.info("grantResource result:"+grantRes); + //3、deploy service + if(grantRes){ + result = jujuClientManager.deploy(charmPath,appName); + if(result.getInt(EntityUtils.RESULT_CODE_KEY) == EntityUtils.ExeRes.SUCCESS){ + resp.setStatus(Constant.HTTP_CREATED); + } + result.put("vnfId", vnfId);//return vnfId + return result.toString(); + }else{ + msg = "Grant resource fail:"+vnfId; + } + } catch(Exception e) { + msg = e.getMessage(); + LOG.error("deploy fail in method deployService",e); + } + resp.setStatus(Constant.HTTP_INNERERROR); + result.put(EntityUtils.MSG_KEY, msg); + return result.toString(); + } + + /** + * <br/> + * here appName equals modelName + * @param resp + * @param context + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + @POST + @Path("/destroy") + public String destroySerivce(@Context HttpServletRequest context, @Context HttpServletResponse resp) + throws ServiceException { + JSONObject result = new JSONObject(); + result.put(EntityUtils.RESULT_CODE_KEY, EntityUtils.ExeRes.FAILURE); + String msg; + try { + JSONObject reqJsonObject = StringUtil.getJsonFromContexts(context); + if(reqJsonObject == null || reqJsonObject.get(Constant.APP_NAME) == null){ + result.put(EntityUtils.MSG_KEY, "the param 'appName' can't be null"); + resp.setStatus(Constant.HTTP_INNERERROR); + return result.toString(); + } + String appName = reqJsonObject.getString(Constant.APP_NAME); + appName = processAppName(appName); + String vnfId=""; + if(reqJsonObject.containsKey("vnfId")) { + vnfId = reqJsonObject.getString("vnfId"); + } + result = jujuClientManager.destroy(appName); + resp.setStatus(Constant.UNREG_SUCCESS); + LOG.info("destroy service success!!!"+appName+vnfId); + return result.toString(); + } catch(Exception e) { + msg = e.getMessage(); + LOG.error("destory fail in method destroyService",e); + + } + resp.setStatus(Constant.HTTP_INNERERROR); + result.put(EntityUtils.MSG_KEY, msg); + return result.toString(); + } + + private static String processAppName(String appName){ + if(appName != null && appName.indexOf(".yaml") > 0){//remove zte's attach + return appName.substring(0,appName.indexOf(".yaml"))+".yaml"; + } + return appName; + } + +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/SwaggerRoa.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/SwaggerRoa.java new file mode 100644 index 0000000..06e461a --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/SwaggerRoa.java @@ -0,0 +1,49 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.rest; + +import java.io.IOException; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +import org.apache.commons.io.IOUtils; + +/** + * Swagger API Doc.<br/> + * + * @author + * @version NFVO 0.5 Oct 24, 2016 + */ +@Path("/v1") +@Produces({MediaType.APPLICATION_JSON}) +public class SwaggerRoa { + /** + * API doc. + * @param filename + * @return + * @throws IOException + */ + @GET + @Path("/swagger.json") + public String apidoc() throws IOException{ + ClassLoader classLoader = getClass().getClassLoader(); + return IOUtils.toString(classLoader.getResourceAsStream("swagger.json")); + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/VnfResourceRoa.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/VnfResourceRoa.java new file mode 100644 index 0000000..7510e0e --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/VnfResourceRoa.java @@ -0,0 +1,102 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.rest; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +import org.openo.nfvo.jujuvnfmadapter.common.EntityUtils; +import org.openo.nfvo.jujuvnfmadapter.common.StringUtil; +import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant; +import org.openo.nfvo.jujuvnfmadapter.service.process.VnfResourceMgr; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * Provide interfaces of resource for juju VNFM to call. + * <br/> + * + * @author + * @version NFVO 0.5 Aug 24, 2016 + */ +@Path("/v1") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class VnfResourceRoa { + + private static final Logger LOG = LoggerFactory.getLogger(VnfResourceRoa.class); + + private VnfResourceMgr vnfResourceMgr; + + public void setVnfResourceMgr(VnfResourceMgr vnfResourceMgr) { + this.vnfResourceMgr = vnfResourceMgr; + } + + /** + * Provide function of grant resource. + * <br/> + *JSONObject compute : + * field:(cpu,mem,disk,action(addResource/removeResource)) + * @param context + * @param vnfId + * @return + * @since NFVO 0.5 + */ + @PUT + @Path("/instances/{vnfId}/grant") + public String grantVnfRes(@Context HttpServletRequest context, @PathParam("vnfId") String vnfId) { + LOG.info("function=grantVnfRes, msg=enter to grant vnf resource"); + JSONObject restJson = new JSONObject(); + restJson.put(EntityUtils.RESULT_CODE_KEY, Constant.REST_FAIL); + + JSONObject compute = StringUtil.getJsonFromContexts(context); + if(null == compute) { + LOG.error("function=grantVnfRes, msg=param request content can't be null!"); + restJson.put("data", "param request content can't be null!"); + return restJson.toString(); + } + + JSONObject resultObj = vnfResourceMgr.grantVnfResource(compute, vnfId); + handleResult(resultObj, restJson); + + return restJson.toString(); + } + + private void handleResult(JSONObject resultObj, JSONObject restJson) { + if(resultObj.getInt("retCode") == Constant.REST_SUCCESS) { + restJson.put("retCode", Constant.REST_SUCCESS); + restJson.put("data", resultObj.getJSONObject("data")); + } else { + if(resultObj.containsKey("data")) { + String errorMsg = resultObj.getString("data"); + LOG.error("function=handleResult, msg={}", errorMsg); + restJson.put("data", errorMsg); + } else { + LOG.error("function=handleResult, msg=Vnf Resource dispose fail"); + restJson.put("data", "Vnf Resource dispose fail"); + } + } + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/VnfRoa.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/VnfRoa.java new file mode 100644 index 0000000..df29ba3 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/VnfRoa.java @@ -0,0 +1,256 @@ +/* + * Copyright 2016-2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.rest; + +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +import org.apache.commons.collections.map.UnmodifiableMap; +import org.apache.commons.lang3.StringUtils; +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.openo.nfvo.jujuvnfmadapter.common.EntityUtils; +import org.openo.nfvo.jujuvnfmadapter.common.StringUtil; +import org.openo.nfvo.jujuvnfmadapter.common.SwitchController; +import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant; +import org.openo.nfvo.jujuvnfmadapter.service.process.VnfMgr; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * Provide interfaces for instantiate or terminate VNF. + * <br/> + * + * @author + * @version NFVO 0.5 Aug 24, 2016 + */ +@SuppressWarnings("unchecked") +@Path("/v1") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class VnfRoa { + + private static final Logger LOG = LoggerFactory.getLogger(VnfRoa.class); + + private VnfMgr vnfMgr; + + private static Map<String, String> progressItem; + + private static Map<String, String> jobStatusitem; + + static { + Map<String, String> map = new HashMap<>(); + map.put("Building", "50"); + map.put("Active", "100"); + map.put("Stopped", "50"); + map.put("Error", "100"); + progressItem = UnmodifiableMap.decorate(map); + + map = new HashMap<>(); + map.put("Building", "processing"); + map.put("Active", "finished"); + map.put("Stopped", "processing"); + map.put("Error", "error"); + jobStatusitem = UnmodifiableMap.decorate(map); + } + + public void setVnfMgr(VnfMgr vnfMgr) { + this.vnfMgr = vnfMgr; + } + + + @POST + @Path("/vnfminfo") + public String setVNFMInfo(@Context HttpServletRequest context, @Context HttpServletResponse resp) + throws ServiceException { + JSONObject result = new JSONObject(); + result.put("retCode", Constant.REST_SUCCESS); + JSONObject reqJsonObject = StringUtil.getJsonFromContexts(context); + String vnfmServiceUrl = reqJsonObject.getString("url"); + SwitchController.vnfmServiceUrl = vnfmServiceUrl; + LOG.info(reqJsonObject + ":setVNFMInfo success!"); + return result.toString(); + } + + /** + * Provide function for instantiate VNF + * <br/> + * + * @param context + * @param resp + * @param vnfmId + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + @POST + @Path("/{vnfmId}/vnfs") + public String addVnf(@Context HttpServletRequest context, @Context HttpServletResponse resp, + @PathParam("vnfmId") String vnfmId) throws ServiceException { + LOG.warn("function=addVnf, msg=enter to add a vnf"); + JSONObject subJsonObject = StringUtil.getJsonFromContexts(context); + LOG.info("request context:"+subJsonObject); + JSONObject restJson = new JSONObject(); + + if(null == subJsonObject) { + LOG.error("function=addVnf, msg=params are insufficient"); + resp.setStatus(Constant.HTTP_INNERERROR); + return restJson.toString(); + } + + restJson = vnfMgr.addVnf(subJsonObject, vnfmId); + + if(restJson.getInt(EntityUtils.RESULT_CODE_KEY) == Constant.REST_FAIL) { + LOG.error("function=addVnf, msg=addvnf fail"); + resp.setStatus(Constant.HTTP_INNERERROR); + return restJson.toString(); + } + + return JSONObject.fromObject(restJson.getJSONObject("data")).toString(); + } + + /** + * Provide function for terminate VNF + * <br/> + * + * @param vnfmId + * @param resp + * @param vnfInstanceId + * @param context + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + @DELETE + @Path("/{vnfmId}/vnfs/{vnfInstanceId}/terminate") + public String delVnfDel(@PathParam("vnfmId") String vnfmId, @Context HttpServletResponse resp, + @PathParam("vnfInstanceId") String vnfInstanceId, @Context HttpServletRequest context) + throws ServiceException { + + return this.delVnf(vnfmId, resp, vnfInstanceId, context); + } + + /** + * Provide function for terminate VNF + * <br/> + * + * @param vnfmId + * @param resp + * @param vnfInstanceId + * @param context + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + @POST + @Path("/{vnfmId}/vnfs/{vnfInstanceId}/terminate") + public String delVnf(@PathParam("vnfmId") String vnfmId, @Context HttpServletResponse resp, + @PathParam("vnfInstanceId") String vnfInstanceId, @Context HttpServletRequest context) + throws ServiceException { + LOG.warn("function=delVnf, msg=enter to delete a vnf: vnfInstanceId: {}, vnfmId: {}", vnfInstanceId, vnfmId); + JSONObject vnfObject = StringUtil.getJsonFromContexts(context); + LOG.info("request context:"+vnfObject); + JSONObject restJson = new JSONObject(); + + if(StringUtils.isEmpty(vnfInstanceId) || StringUtils.isEmpty(vnfmId)) { + resp.setStatus(Constant.HTTP_INNERERROR); + return restJson.toString(); + } + + restJson = vnfMgr.deleteVnf(vnfInstanceId, vnfmId, vnfObject); + if(restJson.getInt(EntityUtils.RESULT_CODE_KEY) == Constant.REST_FAIL) { + LOG.error("function=delVnf, msg=delVnf fail"); + resp.setStatus(Constant.HTTP_INNERERROR); + return restJson.toString(); + } + + return JSONObject.fromObject(restJson.getJSONObject("data")).toString(); + } + + /** + * Provide function for get VNF + * <br/> + * + * @param vnfmId + * @param resp + * @param vnfInstanceId + * @param context + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + @GET + @Path("/{vnfmId}/vnfs/{vnfInstanceId}") + public String getVnf(@PathParam("vnfmId") String vnfmId, @Context HttpServletResponse resp, + @PathParam("vnfInstanceId") String vnfInstanceId, @Context HttpServletRequest context) + throws ServiceException { + LOG.warn("function=getVnf, msg=enter to get a vnf: vnfInstanceId: {}, vnfmId: {}", vnfInstanceId, vnfmId); + JSONObject restJson = new JSONObject(); + + if(StringUtils.isEmpty(vnfInstanceId) || StringUtils.isEmpty(vnfmId)) { + resp.setStatus(Constant.HTTP_INNERERROR); + return restJson.toString(); + } + + restJson = vnfMgr.getVnf(vnfInstanceId, vnfmId); + if(restJson.getInt(EntityUtils.RESULT_CODE_KEY) == Constant.REST_FAIL) { + LOG.error("function=getVnf, msg=getVnf fail"); + resp.setStatus(Constant.HTTP_INNERERROR); + return restJson.toString(); + } + + restJson.remove(EntityUtils.RESULT_CODE_KEY); + return restJson.toString(); + } + + /** + * Provide function for get job + * <br/> + * + * @param jobId + * @param vnfmId + * @param resp + * @param responseId + * @return + * @throws ServiceException + * @since NFVO 0.5 + */ + @GET + @Path("/{vnfmId}/jobs/{jobId}") + public String getJob(@PathParam("jobId") String jobId, @PathParam("vnfmId") String vnfmId, + @Context HttpServletResponse resp, @QueryParam("@responseId") String responseId) throws ServiceException { + LOG.warn("function=getJob, msg=enter to get a job: jobId: {}", jobId); + JSONObject restJson = new JSONObject(); + restJson = vnfMgr.getJob(jobId, vnfmId); + + return restJson.toString(); + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/exceptionmapper/ExceptionMessage.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/exceptionmapper/ExceptionMessage.java new file mode 100644 index 0000000..3069c11 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/exceptionmapper/ExceptionMessage.java @@ -0,0 +1,64 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.rest.exceptionmapper; + +import org.apache.http.HttpStatus; + +/** + * Exception response model.<br> + * + * @author + * @version NFVO 0.5 Sep 27, 2016 + */ +public class ExceptionMessage { + + private String errorCode = "unknown.error"; + + private int httpCode = HttpStatus.SC_INTERNAL_SERVER_ERROR; + + private String message; + + @Override + public String toString() { + return "Error {errorCode=" + this.errorCode + ", httpCode=" + this.httpCode + ", message=" + + this.message + "}"; + } + + public String getErrorCode() { + return this.errorCode; + } + + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } + + public String getMessage() { + return this.message; + } + + public void setMessage(String message) { + this.message = message; + } + + public int getHttpCode() { + return this.httpCode; + } + + public void setHttpCode(int httpCode) { + this.httpCode = httpCode; + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/exceptionmapper/GenericExceptionMapper.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/exceptionmapper/GenericExceptionMapper.java new file mode 100644 index 0000000..908a0f1 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/exceptionmapper/GenericExceptionMapper.java @@ -0,0 +1,41 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.rest.exceptionmapper; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +/** + * Generic exception response provider.<br> + * + * + * @author + * @version NFVO 0.5 Sep 27, 2016 + */ +@Provider +public class GenericExceptionMapper implements ExceptionMapper<Exception>{ + + @Override + public Response toResponse(Exception exception) { + ExceptionMessage message = new ExceptionMessage(); + message.setMessage(exception.getMessage()); + return Response.status(message.getHttpCode()).type( + MediaType.APPLICATION_JSON).entity(message).build(); + } +} diff --git a/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/exceptionmapper/ServiceExceptionMapper.java b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/exceptionmapper/ServiceExceptionMapper.java new file mode 100644 index 0000000..ffddd99 --- /dev/null +++ b/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/openo/nfvo/jujuvnfmadapter/service/rest/exceptionmapper/ServiceExceptionMapper.java @@ -0,0 +1,45 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.nfvo.jujuvnfmadapter.service.rest.exceptionmapper; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +import org.openo.baseservice.remoteservice.exception.ServiceException; + +/** + * ServiceException response provider.<br> + * + * @author + * @version NFVO 0.5 Sep 27, 2016 + */ +@Provider +public class ServiceExceptionMapper implements ExceptionMapper<ServiceException>{ + + @Override + public Response toResponse(ServiceException exception) { + ExceptionMessage message = new ExceptionMessage(); + message.setErrorCode(exception.getId()); + message.setHttpCode(exception.getHttpCode()); + message.setMessage(exception.getMessage()); + return Response.status(message.getHttpCode()). + type(MediaType.APPLICATION_JSON).entity(message).build(); + } + +} |