diff options
70 files changed, 5175 insertions, 5272 deletions
diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/EmsDriverApplication.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/EmsDriverApplication.java index 1984ccb..7917d67 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/EmsDriverApplication.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/EmsDriverApplication.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,6 +15,7 @@ */ package org.onap.vfc.nfvo.emsdriver; +import com.fasterxml.jackson.annotation.JsonInclude; import io.dropwizard.Application; import io.dropwizard.assets.AssetsBundle; import io.dropwizard.jetty.HttpConnectorFactory; @@ -23,12 +24,6 @@ import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import io.swagger.jaxrs.config.BeanConfig; import io.swagger.jaxrs.listing.ApiListingResource; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.onap.vfc.nfvo.emsdriver.commons.constant.Constant; @@ -41,15 +36,18 @@ import org.onap.vfc.nfvo.emsdriver.serviceregister.model.ServiceNodeVo; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; -import com.fasterxml.jackson.annotation.JsonInclude; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.List; public class EmsDriverApplication extends Application<EmsDriverConfiguration> { - - protected static Log log = LogFactory.getLog(EmsDriverApplication.class); - private ApplicationContext context = null; - - public static void main(String[] args) throws Exception { - log.info("EmsDriverApplication start"); + + protected static Log log = LogFactory.getLog(EmsDriverApplication.class); + private ApplicationContext context = null; + + public static void main(String[] args) throws Exception { + log.info("EmsDriverApplication start"); new EmsDriverApplication().run(args); log.info("EmsDriverApplication start sucess"); } @@ -62,43 +60,43 @@ public class EmsDriverApplication extends Application<EmsDriverConfiguration> { @Override public void initialize(Bootstrap<EmsDriverConfiguration> bootstrap) { // nothing to do yet - context = new FileSystemXmlApplicationContext("file:" + Constant.SYS_CFG+ "spring.xml"); - bootstrap.addBundle(new AssetsBundle("/api-doc", "/api-doc", "index.html", "api-doc")); + context = new FileSystemXmlApplicationContext("file:" + Constant.SYS_CFG + "spring.xml"); + bootstrap.addBundle(new AssetsBundle("/api-doc", "/api-doc", "index.html", "api-doc")); } @Override - public void run(EmsDriverConfiguration configuration,Environment environment) { - // register CommandResource - environment.jersey().register(new CommandResource()); - MsbConfiguration.setMsbAddress(configuration.getMsbAddress()); - //MSB register - String registerFlag = configuration.getAutoServiceRegister(); - if("false".equalsIgnoreCase(registerFlag)){ - this.msbRegisteEmsDriverService(configuration); - } - //Start workThread - this.startThread(); - initSwaggerConfig(environment, configuration); + public void run(EmsDriverConfiguration configuration, Environment environment) { + // register CommandResource + environment.jersey().register(new CommandResource()); + MsbConfiguration.setMsbAddress(configuration.getMsbAddress()); + //MSB register + String registerFlag = configuration.getAutoServiceRegister(); + if ("false".equalsIgnoreCase(registerFlag)) { + this.msbRegisteEmsDriverService(configuration); + } + //Start workThread + this.startThread(); + initSwaggerConfig(environment, configuration); } - - private void startThread(){ - String[] allThreadName = context.getBeanNamesForType(DriverThread.class); - log.info("worker num :" + allThreadName.length); - for (String threadName : allThreadName) { - DriverThread thread = (DriverThread) context.getBean(threadName); - if (thread == null) { - log.error(threadName + "Thread start error,system exit"); - System.exit(1); - }else{ - thread.setName(threadName); - thread.start(); - } - - } + + private void startThread() { + String[] allThreadName = context.getBeanNamesForType(DriverThread.class); + log.info("worker num :" + allThreadName.length); + for (String threadName : allThreadName) { + DriverThread thread = (DriverThread) context.getBean(threadName); + if (thread == null) { + log.error(threadName + "Thread start error,system exit"); + System.exit(1); + } else { + thread.setName(threadName); + thread.start(); + } + + } } + // init swagger - private void initSwaggerConfig(Environment environment, EmsDriverConfiguration configuration) - { + private void initSwaggerConfig(Environment environment, EmsDriverConfiguration configuration) { environment.jersey().register(new ApiListingResource()); environment.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL); @@ -107,43 +105,43 @@ public class EmsDriverApplication extends Application<EmsDriverConfiguration> { config.setVersion("1.0.0"); config.setResourcePackage("org.onap.vfc.nfvo.emsdriver.northbound.service"); //swagger rest api basepath - SimpleServerFactory simpleServerFactory = (SimpleServerFactory)configuration.getServerFactory(); + SimpleServerFactory simpleServerFactory = (SimpleServerFactory) configuration.getServerFactory(); String basePath = simpleServerFactory.getApplicationContextPath(); String rootPath = simpleServerFactory.getJerseyRootPath().get(); rootPath = rootPath.substring(0, rootPath.indexOf("/*")); basePath = basePath.equals("/") ? rootPath : (new StringBuilder()).append(basePath).append(rootPath).toString(); config.setBasePath(basePath); - config.setScan(true); + config.setScan(true); + } + + private void msbRegisteEmsDriverService(EmsDriverConfiguration configuration) { + SimpleServerFactory simpleServerFactory = (SimpleServerFactory) configuration.getServerFactory(); + HttpConnectorFactory connector = (HttpConnectorFactory) simpleServerFactory.getConnector(); + MsbRegisterVo registerVo = new MsbRegisterVo(); + ServiceNodeVo serviceNode = new ServiceNodeVo(); + String ip = ""; + try { + ip = InetAddress.getLocalHost().getHostAddress(); + } catch (UnknownHostException e) { + log.error("Unable to get host ip: ", e); + } + if (ip.equals("")) { + ip = connector.getBindHost(); + } + serviceNode.setIp(ip); + serviceNode.setPort(String.valueOf(connector.getPort())); + serviceNode.setTtl(0); + + List<ServiceNodeVo> nodeList = new ArrayList<ServiceNodeVo>(); + nodeList.add(serviceNode); + registerVo.setServiceName("emsdriver"); + registerVo.setUrl("/api/emsdriver/v1"); + registerVo.setNodes(nodeList); + + MsbRestServiceProxy.registerService(registerVo); + log.info("register vfc-emsdriver service to msb finished."); + } - - private void msbRegisteEmsDriverService(EmsDriverConfiguration configuration) { - SimpleServerFactory simpleServerFactory = (SimpleServerFactory)configuration.getServerFactory(); - HttpConnectorFactory connector = (HttpConnectorFactory)simpleServerFactory.getConnector(); - MsbRegisterVo registerVo = new MsbRegisterVo(); - ServiceNodeVo serviceNode = new ServiceNodeVo(); - String ip = ""; - try { - ip = InetAddress.getLocalHost().getHostAddress(); - } catch (UnknownHostException e) { - log.error("Unable to get host ip: ",e); - } - if(ip.equals("")){ - ip = connector.getBindHost(); - } - serviceNode.setIp(ip); - serviceNode.setPort(String.valueOf(connector.getPort())); - serviceNode.setTtl(0); - - List<ServiceNodeVo> nodeList = new ArrayList<ServiceNodeVo>(); - nodeList.add(serviceNode); - registerVo.setServiceName("emsdriver"); - registerVo.setUrl("/api/emsdriver/v1"); - registerVo.setNodes(nodeList); - - MsbRestServiceProxy.registerService(registerVo); - log.info("register vfc-emsdriver service to msb finished."); - - } - - + + } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/EmsDriverConfiguration.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/EmsDriverConfiguration.java index 477a901..33bf306 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/EmsDriverConfiguration.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/EmsDriverConfiguration.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,20 +15,18 @@ */ package org.onap.vfc.nfvo.emsdriver; +import com.fasterxml.jackson.annotation.JsonProperty; import io.dropwizard.Configuration; - import org.hibernate.validator.constraints.NotEmpty; -import com.fasterxml.jackson.annotation.JsonProperty; +public class EmsDriverConfiguration extends Configuration { -public class EmsDriverConfiguration extends Configuration{ - - @NotEmpty + @NotEmpty private String msbAddress; - - private String autoServiceRegister="true"; - @NotEmpty + private String autoServiceRegister = "true"; + + @NotEmpty private String defaultName = "EmsDriver-Stranger"; @JsonProperty @@ -40,16 +38,16 @@ public class EmsDriverConfiguration extends Configuration{ public void setMsbAddress(String msbAddress) { this.msbAddress = msbAddress; } - + @JsonProperty public String getAutoServiceRegister() { - return autoServiceRegister; - } - + return autoServiceRegister; + } + @JsonProperty - public void setAutoServiceRegister(String autoServiceRegister) { - this.autoServiceRegister = autoServiceRegister; - } + public void setAutoServiceRegister(String autoServiceRegister) { + this.autoServiceRegister = autoServiceRegister; + } @JsonProperty public String getDefaultName() { diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/CollectMsgReceiverThread.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/CollectMsgReceiverThread.java index 5c84a72..6d99aea 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/CollectMsgReceiverThread.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/CollectMsgReceiverThread.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -21,83 +21,77 @@ import org.onap.vfc.nfvo.emsdriver.commons.utils.DriverThread; import org.onap.vfc.nfvo.emsdriver.messagemgr.MessageChannel; import org.onap.vfc.nfvo.emsdriver.messagemgr.MessageChannelFactory; -public class CollectMsgReceiverThread extends DriverThread{ - - private long timeStamp = System.currentTimeMillis(); - - private MessageChannel collectChannel; - - private TaskThreadService taskService; - - private int thread_max_num = 100; - - - - @Override - public void dispose() { - collectChannel = MessageChannelFactory.getMessageChannel(Constant.COLLECT_CHANNEL_KEY); - - taskService = TaskThreadService.getInstance(thread_max_num); - taskService.start(); - - while (isRun()) { - - try { - if(System.currentTimeMillis() - timeStamp > Constant.ONEMINUTE){ - timeStamp = System.currentTimeMillis(); - - log.debug("COLLECT_CHANNEL Msg size :"+collectChannel.size()); - } - - Object obj = collectChannel.poll(); - if(obj == null){ - Thread.sleep(10); - continue; - } - if(obj != null && obj instanceof CollectMsg){ - CollectMsg collectMsg = (CollectMsg)obj; - taskService.add(collectMsg); - log.debug("receive a CollectMsg id = "+collectMsg.getId()); - }else{ - log.error("receive Objcet not CollectMsg "+obj); - } - - } catch (Exception e) { - log.error("dispatch alarm exception",e); - - } - } - - } - - - - /** - * @return the thread_max_num - */ - public int getThread_max_num() { - return thread_max_num; - } - - - - /** - * @param thread_max_num the thread_max_num to set - */ - public void setThread_max_num(int thread_max_num) { - this.thread_max_num = thread_max_num; - } - - - - /** - * @return the taskService - */ - public TaskThreadService getTaskService() { - return taskService; - } - - - - +public class CollectMsgReceiverThread extends DriverThread { + + private long timeStamp = System.currentTimeMillis(); + + private MessageChannel collectChannel; + + private TaskThreadService taskService; + + private int thread_max_num = 100; + + + @Override + public void dispose() { + collectChannel = MessageChannelFactory.getMessageChannel(Constant.COLLECT_CHANNEL_KEY); + + taskService = TaskThreadService.getInstance(thread_max_num); + taskService.start(); + + while (isRun()) { + + try { + if (System.currentTimeMillis() - timeStamp > Constant.ONEMINUTE) { + timeStamp = System.currentTimeMillis(); + + log.debug("COLLECT_CHANNEL Msg size :" + collectChannel.size()); + } + + Object obj = collectChannel.poll(); + if (obj == null) { + Thread.sleep(10); + continue; + } + if (obj != null && obj instanceof CollectMsg) { + CollectMsg collectMsg = (CollectMsg) obj; + taskService.add(collectMsg); + log.debug("receive a CollectMsg id = " + collectMsg.getId()); + } else { + log.error("receive Objcet not CollectMsg " + obj); + } + + } catch (Exception e) { + log.error("dispatch alarm exception", e); + + } + } + + } + + + /** + * @return the thread_max_num + */ + public int getThread_max_num() { + return thread_max_num; + } + + + /** + * @param thread_max_num the thread_max_num to set + */ + public void setThread_max_num(int thread_max_num) { + this.thread_max_num = thread_max_num; + } + + + /** + * @return the taskService + */ + public TaskThreadService getTaskService() { + return taskService; + } + + } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/TaskThread.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/TaskThread.java index 44a31d8..d764bf6 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/TaskThread.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/TaskThread.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,31 +15,6 @@ */ package org.onap.vfc.nfvo.emsdriver.collector; -import java.io.BufferedOutputStream; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Properties; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamReader; - import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -50,746 +25,749 @@ import org.onap.vfc.nfvo.emsdriver.commons.ftp.FTPSrv; import org.onap.vfc.nfvo.emsdriver.commons.ftp.RemoteFile; import org.onap.vfc.nfvo.emsdriver.commons.model.CollectMsg; import org.onap.vfc.nfvo.emsdriver.commons.model.CollectVo; -import org.onap.vfc.nfvo.emsdriver.commons.utils.DateUtil; -import org.onap.vfc.nfvo.emsdriver.commons.utils.Gunzip; -import org.onap.vfc.nfvo.emsdriver.commons.utils.StringUtil; -import org.onap.vfc.nfvo.emsdriver.commons.utils.UnZip; -import org.onap.vfc.nfvo.emsdriver.commons.utils.VarExprParser; -import org.onap.vfc.nfvo.emsdriver.commons.utils.Zip; +import org.onap.vfc.nfvo.emsdriver.commons.utils.*; import org.onap.vfc.nfvo.emsdriver.configmgr.ConfigurationImp; import org.onap.vfc.nfvo.emsdriver.configmgr.ConfigurationInterface; import org.onap.vfc.nfvo.emsdriver.messagemgr.MessageChannel; import org.onap.vfc.nfvo.emsdriver.messagemgr.MessageChannelFactory; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamReader; +import java.io.*; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +public class TaskThread implements Runnable { + + public Log log = LogFactory.getLog(TaskThread.class); + public MessageChannel pmResultChannel; + private MessageChannel cmResultChannel; + private CollectMsg data; + + private ConfigurationInterface configurationInterface = new ConfigurationImp(); + + private String localPath = Constant.SYS_DATA_TEMP; + private String resultPath = Constant.SYS_DATA_RESULT; + + private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); + + private SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); -public class TaskThread implements Runnable{ - - public Log log = LogFactory.getLog(TaskThread.class); - - private MessageChannel cmResultChannel; - public MessageChannel pmResultChannel; - - private CollectMsg data; - - private ConfigurationInterface configurationInterface = new ConfigurationImp(); - - private String localPath = Constant.SYS_DATA_TEMP; - private String resultPath = Constant.SYS_DATA_RESULT; - - private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); - - private SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - // private String csvpathAndFileName; // private String xmlPathAndFileName; // private int countNum = 0 ; - - public TaskThread(CollectMsg data) { - this.data = data; - } - public TaskThread() { - super(); - } - - @Override - public void run(){ - - cmResultChannel = MessageChannelFactory.getMessageChannel(Constant.COLLECT_RESULT_CHANNEL_KEY); - pmResultChannel = MessageChannelFactory.getMessageChannel(Constant.COLLECT_RESULT_PM_CHANNEL_KEY); - try { - collectMsgHandle(data); - } catch (Exception e) { - log.error("",e); - } - } - - private void collectMsgHandle(CollectMsg collectMsg) { - String emsName = collectMsg.getEmsName(); - String type = collectMsg.getType(); - CollectVo collectVo = configurationInterface.getCollectVoByEmsNameAndType(emsName, type); - - //ftp download - List<String> downloadfiles = this.ftpDownload(collectVo); - //paser ftp update message send - for(String fileName :downloadfiles){ - this.parseFtpAndSendMessage(fileName,collectVo); - } - } - - public void parseFtpAndSendMessage(String fileName, CollectVo collectVo) { - // - List<File> filelist = decompressed(fileName); - - for (File tempfile : filelist) { - - String unfileName = tempfile.getName(); - - Pattern pa = Pattern.compile(".*-(.*)-\\w{2}-"); - Matcher ma = pa.matcher(unfileName); - if (!ma.find()) - continue; - String nename = ma.group(1); - boolean parseResult = false; - if(Constant.COLLECT_TYPE_CM.equalsIgnoreCase(collectVo.getType())){ - parseResult = processCMXml(tempfile, nename,"CM"); - }else{ - if(unfileName.indexOf(".csv") > 0){ - parseResult = processPMCsv(tempfile); - }else{ - parseResult = processPMXml(tempfile); - } - } - - if (parseResult){ - log.info("parser "+tempfile+" sucess"); - tempfile.delete(); - }else { - log.info("parser "+tempfile+" fail"); - } - - } - } - - public boolean processPMXml(File file) { - - FileInputStream fis = null; - InputStreamReader isr = null; - XMLStreamReader reader = null; - try { - fis = new FileInputStream(file); - isr = new InputStreamReader(fis, Constant.ENCODING_UTF8); - - XMLInputFactory fac = XMLInputFactory.newInstance(); - reader = fac.createXMLStreamReader(isr); - - boolean fileHeaderStart = false; - boolean measurementStart = false; - boolean pmNameFlag = false; - boolean pmDataFlag = false; - boolean objectFlag = true; - - int index = -1; - int nameIndex = -1; - String currentMea = null; - String subName = null; - String localName = null; - String endLocalName = null; - String objectType = null; - - - LinkedHashMap<String, String> commonNameAndValue = new LinkedHashMap<String, String>(); - LinkedHashMap<String, String> pmDatas = null; - LinkedHashMap<Integer, String> pmNames = null; - - - int event = -1; - while (reader.hasNext()) { - try{ - event = reader.next(); - - switch (event) { - case XMLStreamConstants.START_ELEMENT: - localName = reader.getLocalName(); - if ("FileHeader".equalsIgnoreCase(localName)) { - fileHeaderStart = true; - } - if(fileHeaderStart){ - if(!"FileHeader".equalsIgnoreCase(localName)){ - commonNameAndValue.put(localName,reader.getElementText().trim()); - } - - } - if ("Measurements".equalsIgnoreCase(localName)) { - // a new Measurement starts - measurementStart = true; - } - if (measurementStart) { - // measurement handler - if ("ObjectType".equalsIgnoreCase(localName)) { - objectType = reader.getElementText().trim(); - commonNameAndValue.put("ObjectType",objectType); - } - if ("PmName".equalsIgnoreCase(localName)) { - pmNameFlag = true; - pmNames = new LinkedHashMap<Integer, String>(); - - } - if (pmNameFlag) { - // pmname handler, add columnNames - if ("N".equalsIgnoreCase(localName)) { - nameIndex = Integer.parseInt(getXMLAttribute(reader, "i")); - String text = reader.getElementText().trim(); - pmNames.put(nameIndex, text); - } - } - if ("PmData".equalsIgnoreCase(localName)) { - pmDataFlag = true; - pmDatas = new LinkedHashMap<String, String>(); - } - - if (pmDataFlag) { - // pmdata handler - if ("Object".equalsIgnoreCase(localName)) { - objectFlag = true; - int n = reader.getAttributeCount(); - for(int i = 0; i < n; i++) { - String name = reader.getAttributeLocalName(i); - commonNameAndValue.put(name, reader.getAttributeValue(i)); - } - } - if (objectFlag) { - - // add columnValues - if ("V".equalsIgnoreCase(localName)) { - String indexStr = getXMLAttribute(reader, "i"); - if(indexStr == null) { - log.error("ERROR: illegal value index"); - continue; - } - index = Integer.parseInt(indexStr); - String name = pmNames.get(index); - if(name == null){ - log.error("illegal data: valueIndex="+index); - continue; - } - - String value = reader.getElementText().trim(); - pmDatas.put(name, value); - } - if ("CV".equalsIgnoreCase(localName)) { - - String indexStr = getXMLAttribute(reader, "i"); - if(indexStr == null) { - log.error("ERROR: illegal value index"); - continue; - } - index = Integer.parseInt(indexStr); - - currentMea = pmNames.get(index); - if(currentMea == null){ - log.error("illegal data: valueIndex="+index); - continue; - } - } - - if ("SN".equalsIgnoreCase(localName)) { - subName = reader.getElementText().trim(); - - } - if ("SV".equalsIgnoreCase(localName)) { - String subValue = reader.getElementText().trim(); + + public TaskThread(CollectMsg data) { + this.data = data; + } + + public TaskThread() { + super(); + } + + @Override + public void run() { + + cmResultChannel = MessageChannelFactory.getMessageChannel(Constant.COLLECT_RESULT_CHANNEL_KEY); + pmResultChannel = MessageChannelFactory.getMessageChannel(Constant.COLLECT_RESULT_PM_CHANNEL_KEY); + try { + collectMsgHandle(data); + } catch (Exception e) { + log.error("", e); + } + } + + private void collectMsgHandle(CollectMsg collectMsg) { + String emsName = collectMsg.getEmsName(); + String type = collectMsg.getType(); + CollectVo collectVo = configurationInterface.getCollectVoByEmsNameAndType(emsName, type); + + //ftp download + List<String> downloadfiles = this.ftpDownload(collectVo); + //paser ftp update message send + for (String fileName : downloadfiles) { + this.parseFtpAndSendMessage(fileName, collectVo); + } + } + + public void parseFtpAndSendMessage(String fileName, CollectVo collectVo) { + // + List<File> filelist = decompressed(fileName); + + for (File tempfile : filelist) { + + String unfileName = tempfile.getName(); + + Pattern pa = Pattern.compile(".*-(.*)-\\w{2}-"); + Matcher ma = pa.matcher(unfileName); + if (!ma.find()) + continue; + String nename = ma.group(1); + boolean parseResult = false; + if (Constant.COLLECT_TYPE_CM.equalsIgnoreCase(collectVo.getType())) { + parseResult = processCMXml(tempfile, nename, "CM"); + } else { + if (unfileName.indexOf(".csv") > 0) { + parseResult = processPMCsv(tempfile); + } else { + parseResult = processPMXml(tempfile); + } + } + + if (parseResult) { + log.info("parser " + tempfile + " sucess"); + tempfile.delete(); + } else { + log.info("parser " + tempfile + " fail"); + } + + } + } + + public boolean processPMXml(File file) { + + FileInputStream fis = null; + InputStreamReader isr = null; + XMLStreamReader reader = null; + try { + fis = new FileInputStream(file); + isr = new InputStreamReader(fis, Constant.ENCODING_UTF8); + + XMLInputFactory fac = XMLInputFactory.newInstance(); + reader = fac.createXMLStreamReader(isr); + + boolean fileHeaderStart = false; + boolean measurementStart = false; + boolean pmNameFlag = false; + boolean pmDataFlag = false; + boolean objectFlag = true; + + int index = -1; + int nameIndex = -1; + String currentMea = null; + String subName = null; + String localName = null; + String endLocalName = null; + String objectType = null; + + + LinkedHashMap<String, String> commonNameAndValue = new LinkedHashMap<String, String>(); + LinkedHashMap<String, String> pmDatas = null; + LinkedHashMap<Integer, String> pmNames = null; + + + int event = -1; + while (reader.hasNext()) { + try { + event = reader.next(); + + switch (event) { + case XMLStreamConstants.START_ELEMENT: + localName = reader.getLocalName(); + if ("FileHeader".equalsIgnoreCase(localName)) { + fileHeaderStart = true; + } + if (fileHeaderStart) { + if (!"FileHeader".equalsIgnoreCase(localName)) { + commonNameAndValue.put(localName, reader.getElementText().trim()); + } + + } + if ("Measurements".equalsIgnoreCase(localName)) { + // a new Measurement starts + measurementStart = true; + } + if (measurementStart) { + // measurement handler + if ("ObjectType".equalsIgnoreCase(localName)) { + objectType = reader.getElementText().trim(); + commonNameAndValue.put("ObjectType", objectType); + } + if ("PmName".equalsIgnoreCase(localName)) { + pmNameFlag = true; + pmNames = new LinkedHashMap<Integer, String>(); + + } + if (pmNameFlag) { + // pmname handler, add columnNames + if ("N".equalsIgnoreCase(localName)) { + nameIndex = Integer.parseInt(getXMLAttribute(reader, "i")); + String text = reader.getElementText().trim(); + pmNames.put(nameIndex, text); + } + } + if ("PmData".equalsIgnoreCase(localName)) { + pmDataFlag = true; + pmDatas = new LinkedHashMap<String, String>(); + } + + if (pmDataFlag) { + // pmdata handler + if ("Object".equalsIgnoreCase(localName)) { + objectFlag = true; + int n = reader.getAttributeCount(); + for (int i = 0; i < n; i++) { + String name = reader.getAttributeLocalName(i); + commonNameAndValue.put(name, reader.getAttributeValue(i)); + } + } + if (objectFlag) { + + // add columnValues + if ("V".equalsIgnoreCase(localName)) { + String indexStr = getXMLAttribute(reader, "i"); + if (indexStr == null) { + log.error("ERROR: illegal value index"); + continue; + } + index = Integer.parseInt(indexStr); + String name = pmNames.get(index); + if (name == null) { + log.error("illegal data: valueIndex=" + index); + continue; + } + + String value = reader.getElementText().trim(); + pmDatas.put(name, value); + } + if ("CV".equalsIgnoreCase(localName)) { + + String indexStr = getXMLAttribute(reader, "i"); + if (indexStr == null) { + log.error("ERROR: illegal value index"); + continue; + } + index = Integer.parseInt(indexStr); + + currentMea = pmNames.get(index); + if (currentMea == null) { + log.error("illegal data: valueIndex=" + index); + continue; + } + } + + if ("SN".equalsIgnoreCase(localName)) { + subName = reader.getElementText().trim(); + + } + if ("SV".equalsIgnoreCase(localName)) { + String subValue = reader.getElementText().trim(); // pmDatas.put(currentMea+subName, subValue); - pmDatas.put(subName, subValue); - } - } - } - - } - - break; - case XMLStreamConstants.CHARACTERS: - // ... - break; - case XMLStreamConstants.END_ELEMENT: - // ... - endLocalName = reader.getLocalName(); - if("Object".equalsIgnoreCase(endLocalName)){ - objectFlag = false; - pmDatas.putAll(commonNameAndValue); - try { - pmResultChannel.put(pmDatas); - - } catch (InterruptedException e) { - log.error("collectResultChannel.put(resultMap) error ",e); - } + pmDatas.put(subName, subValue); + } + } + } + + } + + break; + case XMLStreamConstants.CHARACTERS: + // ... + break; + case XMLStreamConstants.END_ELEMENT: + // ... + endLocalName = reader.getLocalName(); + if ("Object".equalsIgnoreCase(endLocalName)) { + objectFlag = false; + pmDatas.putAll(commonNameAndValue); + try { + pmResultChannel.put(pmDatas); + + } catch (InterruptedException e) { + log.error("collectResultChannel.put(resultMap) error ", e); + } // System.out.println(pmDatas); // pmDatas.clear(); - } - if (endLocalName.equalsIgnoreCase("PmData")) { - pmDataFlag = false; - } - - if (endLocalName.equalsIgnoreCase("PmName")) { - pmNameFlag = false; - } - if (endLocalName.equalsIgnoreCase("Measurements")) { - // a measurement over - measurementStart = false; - } - - if("FileHeader".equalsIgnoreCase(endLocalName)){ - fileHeaderStart = false; - } - break; - } - }catch (Exception e){ - log.error("",e); - event = reader.next(); - } - } - - } catch (Exception e) { - log.error("processPMXml is Exception ",e); - return false; - } finally{ - try{ - if(reader != null)reader.close(); - if(isr!= null)isr.close(); - if(fis != null)fis.close(); - }catch (Exception e) { - e.printStackTrace(); - } - } - return true; - } - - private String getXMLAttribute(XMLStreamReader reader, String obj) { - String res = null; - if(obj == null || reader == null){ - return res; - } - int n = reader.getAttributeCount(); - for(int i = 0; i < n; i++) { - String name = reader.getAttributeLocalName(i); - if(obj.equalsIgnoreCase(name)){ - res = reader.getAttributeValue(i); - } - } - return res; - } - - public boolean processPMCsv(File tempfile) { - - FileInputStream brs = null; - InputStreamReader isr = null; - BufferedReader br = null; - - List<String> columnNames = new ArrayList<String>(); - List<String> commonValues = new ArrayList<String>(); - try { - - brs = new FileInputStream(tempfile); - isr = new InputStreamReader(brs, Constant.ENCODING_UTF8); - br = new BufferedReader(isr); - //common field - String commonField = br.readLine(); - String[] fields = commonField.split("\\|",-1); - for(String com : fields){ - String[] comNameAndValue = com.split("=",2); - columnNames.add(comNameAndValue[0].trim()); - commonValues.add(comNameAndValue[1]); - } - //column names - String columnName = br.readLine(); - String[] names = columnName.split("\\|",-1); - for(String name : names){ - columnNames.add(name); - } - - String valueLine = ""; - List<String> valuelist = new ArrayList<String>(); - - while ((valueLine = br.readLine()) != null) { - if (valueLine.trim().equals("")) { - continue; - } + } + if (endLocalName.equalsIgnoreCase("PmData")) { + pmDataFlag = false; + } + + if (endLocalName.equalsIgnoreCase("PmName")) { + pmNameFlag = false; + } + if (endLocalName.equalsIgnoreCase("Measurements")) { + // a measurement over + measurementStart = false; + } + + if ("FileHeader".equalsIgnoreCase(endLocalName)) { + fileHeaderStart = false; + } + break; + } + } catch (Exception e) { + log.error("", e); + event = reader.next(); + } + } + + } catch (Exception e) { + log.error("processPMXml is Exception ", e); + return false; + } finally { + try { + if (reader != null) reader.close(); + if (isr != null) isr.close(); + if (fis != null) fis.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + return true; + } + + private String getXMLAttribute(XMLStreamReader reader, String obj) { + String res = null; + if (obj == null || reader == null) { + return res; + } + int n = reader.getAttributeCount(); + for (int i = 0; i < n; i++) { + String name = reader.getAttributeLocalName(i); + if (obj.equalsIgnoreCase(name)) { + res = reader.getAttributeValue(i); + } + } + return res; + } + + public boolean processPMCsv(File tempfile) { + + FileInputStream brs = null; + InputStreamReader isr = null; + BufferedReader br = null; + + List<String> columnNames = new ArrayList<String>(); + List<String> commonValues = new ArrayList<String>(); + try { + + brs = new FileInputStream(tempfile); + isr = new InputStreamReader(brs, Constant.ENCODING_UTF8); + br = new BufferedReader(isr); + //common field + String commonField = br.readLine(); + String[] fields = commonField.split("\\|", -1); + for (String com : fields) { + String[] comNameAndValue = com.split("=", 2); + columnNames.add(comNameAndValue[0].trim()); + commonValues.add(comNameAndValue[1]); + } + //column names + String columnName = br.readLine(); + String[] names = columnName.split("\\|", -1); + for (String name : names) { + columnNames.add(name); + } + + String valueLine = ""; + List<String> valuelist = new ArrayList<String>(); + + while ((valueLine = br.readLine()) != null) { + if (valueLine.trim().equals("")) { + continue; + } // countNum ++; - String [] values = valueLine.split("\\|",-1); - - valuelist.addAll(commonValues); - for(String value : values){ - valuelist.add(value); - } + String[] values = valueLine.split("\\|", -1); + + valuelist.addAll(commonValues); + for (String value : values) { + valuelist.add(value); + } // this.appendLine(valuelist, bos); - //resultMap - HashMap<String,String> resultMap = this.resultMap(columnNames,valuelist); - try { - pmResultChannel.put(resultMap); - } catch (InterruptedException e) { - log.error("collectResultChannel.put(resultMap) error ",e); - } - valuelist.clear(); - } - } catch (IOException e) { - log.error("processPMCsv is fail ",e); - return false; - }finally{ - try{ - if (br != null) - br.close(); - if (isr != null) - isr.close(); - if (brs != null) - brs.close(); - - } catch (Exception e){ - log.error(e); - } - } - return true; - - } - - private HashMap<String,String> resultMap(List<String> columnNames, List<String> valuelist) { - - HashMap<String,String> resultMap = new HashMap<String,String>(); - if(columnNames.size() == valuelist.size()){ - for(int i =0;i<columnNames.size();i++){ - resultMap.put(columnNames.get(i), valuelist.get(i)); - } - } - - return resultMap; - - } - private boolean processCMXml(File tempfile, String nename, String type) { - - String csvpath = localPath+nename+"/"+type+"/"; - File csvpathfile = new File(csvpath); - if(!csvpathfile.exists()){ - csvpathfile.mkdirs(); - } - String csvFileName = nename +dateFormat.format(new Date())+ System.nanoTime(); - String csvpathAndFileName = csvpath+csvFileName+".csv"; - BufferedOutputStream bos = null; - FileOutputStream fos = null; - try { - fos = new FileOutputStream(csvpathAndFileName,false); - bos = new BufferedOutputStream(fos, 10240); - } catch (FileNotFoundException e1) { - log.error("FileNotFoundException "+StringUtil.getStackTrace(e1)); - } - - boolean FieldNameFlag = false; - boolean FieldValueFlag = false; - //line num - int countNum = 0; - String xmlPathAndFileName = null; - String localName = null; - String endLocalName = null; - String rmUID = null; - int index = -1; - ArrayList<String> names = new ArrayList<String>();// colname - LinkedHashMap<String, String> nameAndValue = new LinkedHashMap<String, String>(); - - - FileInputStream fis = null; - InputStreamReader isr = null; - XMLStreamReader reader = null; - try{ - fis = new FileInputStream(tempfile); - isr = new InputStreamReader(fis, Constant.ENCODING_UTF8); - XMLInputFactory fac = XMLInputFactory.newInstance(); - reader = fac.createXMLStreamReader(isr); - int event = -1; - boolean setcolum = true; - while (reader.hasNext()){ - try{ - event = reader.next(); - switch (event){ - case XMLStreamConstants.START_ELEMENT: - localName = reader.getLocalName(); - if ("FieldName".equalsIgnoreCase(localName)){ - FieldNameFlag = true; - } - if (FieldNameFlag){ - if ("N".equalsIgnoreCase(localName)){ - String colName = reader.getElementText().trim(); - names.add(colName); - } - } - if ("FieldValue".equalsIgnoreCase(localName)){ - FieldValueFlag = true; - - } - if (FieldValueFlag){ - if(setcolum){ - xmlPathAndFileName = this.setColumnNames(nename, names,type); - setcolum = false; - } - - if ("Object".equalsIgnoreCase(localName)){ - int ac = reader.getAttributeCount(); - for (int i = 0; i < ac; i++){ - if ("rmUID".equalsIgnoreCase(reader.getAttributeLocalName(i))){ - rmUID = reader.getAttributeValue(i).trim(); - } - } - nameAndValue.put("rmUID", rmUID); - } - if ("V".equalsIgnoreCase(localName)) { - index = Integer.parseInt(reader - .getAttributeValue(0)) - 1; - String currentName = names.get(index); - String v = reader.getElementText().trim(); - nameAndValue.put(currentName, v); - } - } - break; - case XMLStreamConstants.CHARACTERS: - break; - case XMLStreamConstants.END_ELEMENT: - endLocalName = reader.getLocalName(); - - if ("FieldName".equalsIgnoreCase(endLocalName)){ - FieldNameFlag = false; - } - if ("FieldValue".equalsIgnoreCase(endLocalName)){ - FieldValueFlag = false; - } - if ("Object".equalsIgnoreCase(endLocalName)){ - countNum ++; - this.appendLine(nameAndValue,bos); - nameAndValue.clear(); - } - break; - } - } catch (Exception e) - { - log.error(""+StringUtil.getStackTrace(e)); - event = reader.next(); - } - } - - - if(bos != null){ - bos.close(); - bos = null; - } - if(fos != null){ - fos.close(); - fos = null; - } - - String[] fileKeys = this.createZipFile(csvpathAndFileName,xmlPathAndFileName,nename); - //ftp store - Properties ftpPro = configurationInterface.getProperties(); - String ip = ftpPro.getProperty("ftp_ip"); - String port = ftpPro.getProperty("ftp_port"); - String ftp_user = ftpPro.getProperty("ftp_user"); - String ftp_password = ftpPro.getProperty("ftp_password"); - - String ftp_passive = ftpPro.getProperty("ftp_passive"); - String ftp_type = ftpPro.getProperty("ftp_type"); - String remoteFile = ftpPro.getProperty("ftp_remote_path"); - this.ftpStore(fileKeys,ip,port,ftp_user,ftp_password,ftp_passive,ftp_type,remoteFile); - //create Message - String message = this.createMessage(fileKeys[1], ftp_user, ftp_password, ip, port, countNum,nename); - - //set message - this.setMessage(message); - } catch (Exception e){ - log.error(""+StringUtil.getStackTrace(e)); - return false; - } finally{ - try{ - if (reader != null){ - reader.close(); - } - if (isr != null){ - isr.close(); - } - if (fis != null){ - fis.close(); - } - if(bos != null){ - bos.close(); - } - - if(fos != null){ - fos.close(); - } - } catch (Exception e){ - log.error(e); - } - } - return true; - } - - private void setMessage(String message) { - - try { - cmResultChannel.put(message); - } catch (Exception e) { - log.error("collectResultChannel.put(message) is error "+StringUtil.getStackTrace(e)); - } - } - - public String createMessage(String zipName,String user,String pwd,String ip, String port,int countNum, String nename) { - - StringBuffer strBuffer = new StringBuffer(); - strBuffer - .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" - + "<FILE_DATA_READY_UL xmlns:xsi=\" http://www.w3.org/2001/XMLSchema-instance\">" - + "<Header SessionID=\""); - strBuffer.append(""); - strBuffer.append("\" LicenceID=\""); - strBuffer.append(""); - strBuffer.append("\" SystemID=\""); - strBuffer.append(""); - strBuffer.append("\" Time=\""); - strBuffer.append( dateFormat2.format(new Date())); - strBuffer.append("\" PolicyID=\""); - strBuffer.append(""); - strBuffer.append("\"/><Body>"); - strBuffer.append("<DataCatalog>"); - strBuffer.append(""); - strBuffer.append("</DataCatalog><GroupID>"); - strBuffer.append(nename); - strBuffer.append("</GroupID><DataSourceName>"); - strBuffer.append(""); - strBuffer.append("</DataSourceName><InstanceID>"); - strBuffer.append(""); - strBuffer.append("</InstanceID><FileFormat>"); - strBuffer.append("csv"); - strBuffer.append("</FileFormat><CharSet>"); - strBuffer.append("gbk"); - strBuffer.append("</CharSet><FieldSeparator>"); - strBuffer.append("|"); - strBuffer.append("</FieldSeparator><IsCompressed>"); - strBuffer.append("true"); - strBuffer.append("</IsCompressed><StartTime>"); - strBuffer.append(dateFormat2.format(new Date())); - strBuffer.append("</StartTime><EndTime>"); - strBuffer.append(""); - strBuffer.append("</EndTime><FileList>"); - strBuffer.append(zipName); - strBuffer.append("</FileList><ConnectionString>"); - strBuffer.append("ftp://" + user + ":" + pwd + "@" + ip + ":" + port); - strBuffer.append("</ConnectionString>"); - strBuffer.append("<DataCount>"); - strBuffer.append(countNum); - strBuffer.append("</DataCount>"); - - strBuffer.append("<FileSize>").append("").append("</FileSize>"); - strBuffer.append("<DataGranularity>").append("").append("</DataGranularity>"); - - - strBuffer.append("</Body></FILE_DATA_READY_UL>"); - return strBuffer.toString(); - - } - - private void ftpStore(String[] fileKeys, String ip, String port, String ftp_user, String ftp_password, - String ftp_passive, String ftp_type, String remoteFile) { - String zipFilePath = fileKeys[0]; - - - FTPInterface ftpClient; - ftpClient = new FTPSrv(); - //login - try { - ftpClient.login(ip, Integer.parseInt(port), ftp_user, ftp_password, "GBK", Boolean.parseBoolean(ftp_passive), 5*60*1000); - } catch (Exception e) { - log.error("login fail,ip=["+ip+"] port=["+port+"] user=["+ftp_user+"]pwd=["+ftp_password+"]"+StringUtil.getStackTrace(e)); - return; - } + //resultMap + HashMap<String, String> resultMap = this.resultMap(columnNames, valuelist); + try { + pmResultChannel.put(resultMap); + } catch (InterruptedException e) { + log.error("collectResultChannel.put(resultMap) error ", e); + } + valuelist.clear(); + } + } catch (IOException e) { + log.error("processPMCsv is fail ", e); + return false; + } finally { + try { + if (br != null) + br.close(); + if (isr != null) + isr.close(); + if (brs != null) + brs.close(); + + } catch (Exception e) { + log.error(e); + } + } + return true; + + } + + private HashMap<String, String> resultMap(List<String> columnNames, List<String> valuelist) { + + HashMap<String, String> resultMap = new HashMap<String, String>(); + if (columnNames.size() == valuelist.size()) { + for (int i = 0; i < columnNames.size(); i++) { + resultMap.put(columnNames.get(i), valuelist.get(i)); + } + } + + return resultMap; + + } + + private boolean processCMXml(File tempfile, String nename, String type) { + + String csvpath = localPath + nename + "/" + type + "/"; + File csvpathfile = new File(csvpath); + if (!csvpathfile.exists()) { + csvpathfile.mkdirs(); + } + String csvFileName = nename + dateFormat.format(new Date()) + System.nanoTime(); + String csvpathAndFileName = csvpath + csvFileName + ".csv"; + BufferedOutputStream bos = null; + FileOutputStream fos = null; + try { + fos = new FileOutputStream(csvpathAndFileName, false); + bos = new BufferedOutputStream(fos, 10240); + } catch (FileNotFoundException e1) { + log.error("FileNotFoundException " + StringUtil.getStackTrace(e1)); + } + + boolean FieldNameFlag = false; + boolean FieldValueFlag = false; + //line num + int countNum = 0; + String xmlPathAndFileName = null; + String localName = null; + String endLocalName = null; + String rmUID = null; + int index = -1; + ArrayList<String> names = new ArrayList<String>();// colname + LinkedHashMap<String, String> nameAndValue = new LinkedHashMap<String, String>(); + + + FileInputStream fis = null; + InputStreamReader isr = null; + XMLStreamReader reader = null; + try { + fis = new FileInputStream(tempfile); + isr = new InputStreamReader(fis, Constant.ENCODING_UTF8); + XMLInputFactory fac = XMLInputFactory.newInstance(); + reader = fac.createXMLStreamReader(isr); + int event = -1; + boolean setcolum = true; + while (reader.hasNext()) { + try { + event = reader.next(); + switch (event) { + case XMLStreamConstants.START_ELEMENT: + localName = reader.getLocalName(); + if ("FieldName".equalsIgnoreCase(localName)) { + FieldNameFlag = true; + } + if (FieldNameFlag) { + if ("N".equalsIgnoreCase(localName)) { + String colName = reader.getElementText().trim(); + names.add(colName); + } + } + if ("FieldValue".equalsIgnoreCase(localName)) { + FieldValueFlag = true; + + } + if (FieldValueFlag) { + if (setcolum) { + xmlPathAndFileName = this.setColumnNames(nename, names, type); + setcolum = false; + } + + if ("Object".equalsIgnoreCase(localName)) { + int ac = reader.getAttributeCount(); + for (int i = 0; i < ac; i++) { + if ("rmUID".equalsIgnoreCase(reader.getAttributeLocalName(i))) { + rmUID = reader.getAttributeValue(i).trim(); + } + } + nameAndValue.put("rmUID", rmUID); + } + if ("V".equalsIgnoreCase(localName)) { + index = Integer.parseInt(reader + .getAttributeValue(0)) - 1; + String currentName = names.get(index); + String v = reader.getElementText().trim(); + nameAndValue.put(currentName, v); + } + } + break; + case XMLStreamConstants.CHARACTERS: + break; + case XMLStreamConstants.END_ELEMENT: + endLocalName = reader.getLocalName(); + + if ("FieldName".equalsIgnoreCase(endLocalName)) { + FieldNameFlag = false; + } + if ("FieldValue".equalsIgnoreCase(endLocalName)) { + FieldValueFlag = false; + } + if ("Object".equalsIgnoreCase(endLocalName)) { + countNum++; + this.appendLine(nameAndValue, bos); + nameAndValue.clear(); + } + break; + } + } catch (Exception e) { + log.error("" + StringUtil.getStackTrace(e)); + event = reader.next(); + } + } + + + if (bos != null) { + bos.close(); + bos = null; + } + if (fos != null) { + fos.close(); + fos = null; + } + + String[] fileKeys = this.createZipFile(csvpathAndFileName, xmlPathAndFileName, nename); + //ftp store + Properties ftpPro = configurationInterface.getProperties(); + String ip = ftpPro.getProperty("ftp_ip"); + String port = ftpPro.getProperty("ftp_port"); + String ftp_user = ftpPro.getProperty("ftp_user"); + String ftp_password = ftpPro.getProperty("ftp_password"); + + String ftp_passive = ftpPro.getProperty("ftp_passive"); + String ftp_type = ftpPro.getProperty("ftp_type"); + String remoteFile = ftpPro.getProperty("ftp_remote_path"); + this.ftpStore(fileKeys, ip, port, ftp_user, ftp_password, ftp_passive, ftp_type, remoteFile); + //create Message + String message = this.createMessage(fileKeys[1], ftp_user, ftp_password, ip, port, countNum, nename); + + //set message + this.setMessage(message); + } catch (Exception e) { + log.error("" + StringUtil.getStackTrace(e)); + return false; + } finally { + try { + if (reader != null) { + reader.close(); + } + if (isr != null) { + isr.close(); + } + if (fis != null) { + fis.close(); + } + if (bos != null) { + bos.close(); + } + + if (fos != null) { + fos.close(); + } + } catch (Exception e) { + log.error(e); + } + } + return true; + } + + private void setMessage(String message) { + + try { + cmResultChannel.put(message); + } catch (Exception e) { + log.error("collectResultChannel.put(message) is error " + StringUtil.getStackTrace(e)); + } + } + + public String createMessage(String zipName, String user, String pwd, String ip, String port, int countNum, String nename) { + + StringBuffer strBuffer = new StringBuffer(); + strBuffer + .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + + "<FILE_DATA_READY_UL xmlns:xsi=\" http://www.w3.org/2001/XMLSchema-instance\">" + + "<Header SessionID=\""); + strBuffer.append(""); + strBuffer.append("\" LicenceID=\""); + strBuffer.append(""); + strBuffer.append("\" SystemID=\""); + strBuffer.append(""); + strBuffer.append("\" Time=\""); + strBuffer.append(dateFormat2.format(new Date())); + strBuffer.append("\" PolicyID=\""); + strBuffer.append(""); + strBuffer.append("\"/><Body>"); + strBuffer.append("<DataCatalog>"); + strBuffer.append(""); + strBuffer.append("</DataCatalog><GroupID>"); + strBuffer.append(nename); + strBuffer.append("</GroupID><DataSourceName>"); + strBuffer.append(""); + strBuffer.append("</DataSourceName><InstanceID>"); + strBuffer.append(""); + strBuffer.append("</InstanceID><FileFormat>"); + strBuffer.append("csv"); + strBuffer.append("</FileFormat><CharSet>"); + strBuffer.append("gbk"); + strBuffer.append("</CharSet><FieldSeparator>"); + strBuffer.append("|"); + strBuffer.append("</FieldSeparator><IsCompressed>"); + strBuffer.append("true"); + strBuffer.append("</IsCompressed><StartTime>"); + strBuffer.append(dateFormat2.format(new Date())); + strBuffer.append("</StartTime><EndTime>"); + strBuffer.append(""); + strBuffer.append("</EndTime><FileList>"); + strBuffer.append(zipName); + strBuffer.append("</FileList><ConnectionString>"); + strBuffer.append("ftp://" + user + ":" + pwd + "@" + ip + ":" + port); + strBuffer.append("</ConnectionString>"); + strBuffer.append("<DataCount>"); + strBuffer.append(countNum); + strBuffer.append("</DataCount>"); + + strBuffer.append("<FileSize>").append("").append("</FileSize>"); + strBuffer.append("<DataGranularity>").append("").append("</DataGranularity>"); + + + strBuffer.append("</Body></FILE_DATA_READY_UL>"); + return strBuffer.toString(); + + } + + private void ftpStore(String[] fileKeys, String ip, String port, String ftp_user, String ftp_password, + String ftp_passive, String ftp_type, String remoteFile) { + String zipFilePath = fileKeys[0]; + + + FTPInterface ftpClient; + ftpClient = new FTPSrv(); + //login + try { + ftpClient.login(ip, Integer.parseInt(port), ftp_user, ftp_password, "GBK", Boolean.parseBoolean(ftp_passive), 5 * 60 * 1000); + } catch (Exception e) { + log.error("login fail,ip=[" + ip + "] port=[" + port + "] user=[" + ftp_user + "]pwd=[" + ftp_password + "]" + StringUtil.getStackTrace(e)); + return; + } // ftpClient.store(zipFilePath, remoteFile); - log.debug("store ["+zipFilePath+"]to["+remoteFile+"]"); - - FileUtils.deleteQuietly(new File(zipFilePath)); - - - } - - private String[] createZipFile(String csvpathAndFileName,String xmlPathAndFileName,String nename) { - - String zipPath = resultPath+nename +dateFormat.format(new Date())+"_"+System.nanoTime(); - - File destDir = new File(zipPath); - destDir.mkdirs(); - - try { - FileUtils.copyFileToDirectory(new File(csvpathAndFileName), destDir); - FileUtils.copyFileToDirectory(new File(xmlPathAndFileName), destDir); - } catch (IOException e) { - - } - - String destFilePath = zipPath + ".zip"; - try { - Zip zip = new Zip(destDir.getAbsolutePath(), destFilePath); - zip.setCompressLevel(9); - zip.compress(); - - FileUtils.deleteDirectory(destDir); - } catch (IOException e) { - log.error("zip.compress() is fail "+StringUtil.getStackTrace(e)); - } - return new String[] { destFilePath, zipPath + ".zip"}; - } - - - private String setColumnNames(String nename, List<String> names,String type) { - //write xml - String xmlpath = localPath+nename +"/"+type+"/"; - File xmlpathfile = new File(xmlpath); - if(!xmlpathfile.exists()){ - xmlpathfile.mkdirs(); - } - String xmlFileName = nename +dateFormat.format(new Date())+ System.nanoTime(); - String fieldLine = ""; - for (int i = 0; i < names.size(); i++) { - String field = "\t<Field>\r\n" + "\t\t<FieldNo>" + i - + "</FieldNo>\r\n" + "\t\t<FieldName>" - + names.get(i) + "</FieldName>\r\n" - + "\t\t<FieldType>" + names.get(i) - + "</FieldType>\r\n" - + "\t\t<FieldNameOther>" + names.get(i) - + "</FieldNameOther>\r\n" + - "\t</Field>\r\n"; - fieldLine = fieldLine + field; - } - - String str = "<?xml version=\"1.0\" encoding=\"gbk\"?>\r\n" - + "<xml>\r\n" + "<FILE_STRUCTURE>\r\n" + fieldLine - + "</FILE_STRUCTURE>\r\n" + "</xml>\r\n"; - String xmlPathAndFileName = xmlpath+xmlFileName+".xml"; - try { - this.writeDetail(xmlPathAndFileName,str); - } catch (Exception e) { - log.error("writeDetail is fail ,xmlFileName="+xmlFileName +StringUtil.getStackTrace(e)); - } - - return xmlPathAndFileName; - } - - private void writeDetail(String detailFileName,String str) throws Exception { - OutputStreamWriter writer = null; - OutputStream readOut = null; - try { - readOut = new FileOutputStream(new File(detailFileName), false); - writer = new OutputStreamWriter(readOut); - writer.write(str); - writer.flush(); - } finally { - - if(null != writer){ - writer.close(); - } - if(readOut != null){ - readOut.close(); - } - - } - - } - - - private void appendLine(LinkedHashMap<String, String> nameAndValue,BufferedOutputStream bos) { - StringBuilder lineDatas = new StringBuilder(); - - for (String key : nameAndValue.keySet()) { - lineDatas.append(nameAndValue.get(key)).append("|"); - } - try { - bos.write(lineDatas.toString().getBytes()); - bos.write("\n".getBytes()); - } catch (IOException e) { - log.error("appendLine error "+StringUtil.getStackTrace(e)); - } - } - + log.debug("store [" + zipFilePath + "]to[" + remoteFile + "]"); + + FileUtils.deleteQuietly(new File(zipFilePath)); + + + } + + private String[] createZipFile(String csvpathAndFileName, String xmlPathAndFileName, String nename) { + + String zipPath = resultPath + nename + dateFormat.format(new Date()) + "_" + System.nanoTime(); + + File destDir = new File(zipPath); + destDir.mkdirs(); + + try { + FileUtils.copyFileToDirectory(new File(csvpathAndFileName), destDir); + FileUtils.copyFileToDirectory(new File(xmlPathAndFileName), destDir); + } catch (IOException e) { + + } + + String destFilePath = zipPath + ".zip"; + try { + Zip zip = new Zip(destDir.getAbsolutePath(), destFilePath); + zip.setCompressLevel(9); + zip.compress(); + + FileUtils.deleteDirectory(destDir); + } catch (IOException e) { + log.error("zip.compress() is fail " + StringUtil.getStackTrace(e)); + } + return new String[]{destFilePath, zipPath + ".zip"}; + } + + + private String setColumnNames(String nename, List<String> names, String type) { + //write xml + String xmlpath = localPath + nename + "/" + type + "/"; + File xmlpathfile = new File(xmlpath); + if (!xmlpathfile.exists()) { + xmlpathfile.mkdirs(); + } + String xmlFileName = nename + dateFormat.format(new Date()) + System.nanoTime(); + String fieldLine = ""; + for (int i = 0; i < names.size(); i++) { + String field = "\t<Field>\r\n" + "\t\t<FieldNo>" + i + + "</FieldNo>\r\n" + "\t\t<FieldName>" + + names.get(i) + "</FieldName>\r\n" + + "\t\t<FieldType>" + names.get(i) + + "</FieldType>\r\n" + + "\t\t<FieldNameOther>" + names.get(i) + + "</FieldNameOther>\r\n" + + "\t</Field>\r\n"; + fieldLine = fieldLine + field; + } + + String str = "<?xml version=\"1.0\" encoding=\"gbk\"?>\r\n" + + "<xml>\r\n" + "<FILE_STRUCTURE>\r\n" + fieldLine + + "</FILE_STRUCTURE>\r\n" + "</xml>\r\n"; + String xmlPathAndFileName = xmlpath + xmlFileName + ".xml"; + try { + this.writeDetail(xmlPathAndFileName, str); + } catch (Exception e) { + log.error("writeDetail is fail ,xmlFileName=" + xmlFileName + StringUtil.getStackTrace(e)); + } + + return xmlPathAndFileName; + } + + private void writeDetail(String detailFileName, String str) throws Exception { + OutputStreamWriter writer = null; + OutputStream readOut = null; + try { + readOut = new FileOutputStream(new File(detailFileName), false); + writer = new OutputStreamWriter(readOut); + writer.write(str); + writer.flush(); + } finally { + + if (null != writer) { + writer.close(); + } + if (readOut != null) { + readOut.close(); + } + + } + + } + + + private void appendLine(LinkedHashMap<String, String> nameAndValue, BufferedOutputStream bos) { + StringBuilder lineDatas = new StringBuilder(); + + for (String key : nameAndValue.keySet()) { + lineDatas.append(nameAndValue.get(key)).append("|"); + } + try { + bos.write(lineDatas.toString().getBytes()); + bos.write("\n".getBytes()); + } catch (IOException e) { + log.error("appendLine error " + StringUtil.getStackTrace(e)); + } + } + // private void appendLine(List<String> values,BufferedOutputStream bos) { // StringBuilder lineDatas = new StringBuilder(); // @@ -804,269 +782,264 @@ public class TaskThread implements Runnable{ // } // } - public List<File> decompressed(String fileName){ - List<File> filelist = new ArrayList<File>(); - - if (fileName.indexOf(".gz") > 1) - { - try { - File decompressFile = deGz(fileName); - filelist.add(decompressFile); - new File(fileName).delete(); - } catch (IOException e) { - log.error("decompressed is fail "+StringUtil.getStackTrace(e)); - } - } else if (fileName.indexOf(".zip") > 1) - { - try { - File[] files = deZip(new File(fileName)); - new File(fileName).delete(); - for(File temp :files){ - filelist.add(temp); - } - } catch (Exception e) { - log.error("decompressed is fail "+StringUtil.getStackTrace(e)); - } - } - else { - filelist.add(new File(fileName)); - } - - return filelist; - } - - private File deGz(String gzFileName) throws IOException { - Gunzip gunzip = new Gunzip(); - String orgFile = gzFileName.replace(".gz", ""); - gunzip.unCompress(gzFileName, orgFile); - return new File(orgFile); - } - - public File[] deZip(File file) throws Exception{ - - String regx = "(.*).zip"; - Pattern p = Pattern.compile(regx); - Matcher m = p.matcher(file.getName()); - if (m.find()) - { - String orgFile = localPath + m.group(1) + "/"; - UnZip unzip = new UnZip(file.getAbsolutePath(), orgFile); + public List<File> decompressed(String fileName) { + List<File> filelist = new ArrayList<File>(); + + if (fileName.indexOf(".gz") > 1) { + try { + File decompressFile = deGz(fileName); + filelist.add(decompressFile); + new File(fileName).delete(); + } catch (IOException e) { + log.error("decompressed is fail " + StringUtil.getStackTrace(e)); + } + } else if (fileName.indexOf(".zip") > 1) { + try { + File[] files = deZip(new File(fileName)); + new File(fileName).delete(); + for (File temp : files) { + filelist.add(temp); + } + } catch (Exception e) { + log.error("decompressed is fail " + StringUtil.getStackTrace(e)); + } + } else { + filelist.add(new File(fileName)); + } + + return filelist; + } + + private File deGz(String gzFileName) throws IOException { + Gunzip gunzip = new Gunzip(); + String orgFile = gzFileName.replace(".gz", ""); + gunzip.unCompress(gzFileName, orgFile); + return new File(orgFile); + } + + public File[] deZip(File file) throws Exception { + + String regx = "(.*).zip"; + Pattern p = Pattern.compile(regx); + Matcher m = p.matcher(file.getName()); + if (m.find()) { + String orgFile = localPath + m.group(1) + "/"; + UnZip unzip = new UnZip(file.getAbsolutePath(), orgFile); unzip.deCompress(); - file = new File(orgFile); - } - File[] files = file.listFiles(); - - return files; - - } - - private List<String> ftpDownload(CollectVo collectVo) { - - List<String> fileList = new ArrayList<String>(); - //IP - String ip = collectVo.getIP(); - //port - String port = collectVo.getPort(); - //user - String user = collectVo.getUser(); - //password - String password = collectVo.getPassword(); - //isPassiveMode - String passivemode = collectVo.getPassive(); - - FTPInterface ftpClient = new FTPSrv(); - - //login - try { - log.info("ftp login ,ip=["+ip+"] port=["+port+"] user=["+user+"]password=["+password+"]"); - ftpClient.login(ip, Integer.parseInt(port), user, password, "GBK", Boolean.parseBoolean(passivemode), 5*60*1000); - } catch (Exception e) { - log.error("login fail,ip=["+ip+"] port=["+port+"] user=["+user+"]password=["+password+"]"+StringUtil.getStackTrace(e)); - return fileList; - } - - //download - String dir = collectVo.getRemotepath(); - List<String> searchExprList = new ArrayList<String>(); - String []FPath = dir.split(";"); - for(int i=0;i<FPath.length;i++){ - int oldSize = searchExprList.size(); - String conpath = FPath[i] + collectVo.getMatch(); - Hashtable<String,String> varMap = new Hashtable<String,String>(); - long collectPeriod = 900; - try { - collectPeriod = Long.parseLong(collectVo.getGranularity())*60; - log.info("collectPeriod =["+collectPeriod+"]"); - } catch (NumberFormatException e) { - e.printStackTrace(); - } - long[] d = DateUtil.getScanScope(new Date(), collectPeriod); - searchExprList.add(VarExprParser.replaceVar(conpath,d[0],d[1])); - - varMap.clear(); - varMap = null; - log.info("["+conpath+"] result["+(searchExprList.size()-oldSize)+"] path"); - conpath = null; - } - String nowdir = null; - try { - nowdir = ftpClient.pwd(); - searchExprList =getPathNoRegular(searchExprList,ftpClient); - } catch (Exception e1) { - log.error(" collect fail ",e1); - return fileList; - } - List<AFtpRemoteFile> remoteFiles = new ArrayList<AFtpRemoteFile>(); - for(String expr :searchExprList){ - ftpClient.chdir(nowdir); - String keys[] = parseExprKeys(expr); - String ftpRegular = keys[1]; - String ftpDir = keys[0]; - - boolean cdsucess = ftpClient.chdir(ftpDir); - if(cdsucess){ - AFtpRemoteFile[] arf = (AFtpRemoteFile[]) ftpClient.list(); - log.info(" list ["+ftpDir+"] result["+(arf==null?"null":arf.length)+"] files"); - //filter - - rfileFilter(remoteFiles,arf,ftpRegular); - - keys = null; - ftpRegular=ftpDir = null; - - for(AFtpRemoteFile ftpRemoteFile: remoteFiles){ - if(!new File(localPath).exists()){ - try { - new File(localPath).mkdir(); - } catch (Exception e) { - log.error("create localPath is fail localPath="+localPath+" "+StringUtil.getStackTrace(e)); - } - } - - if(!new File(localPath).exists()){ - new File(localPath).mkdirs(); - } - - String localFileName = localPath + ftpRemoteFile.getFileName(); - File loaclFile = new File(localFileName); - if (loaclFile.exists()) { - loaclFile.delete(); - } - - boolean flag = ftpClient.downloadFile(ftpRemoteFile.getAbsFileName(), localFileName); - - if(flag){ - fileList.add(localFileName); - }else{ - log.error("download file fail fileName="+ftpRemoteFile.getAbsFileName()); - } - } - - }else{ - log.error("cd dir is faill dir =["+ftpDir+"]"); - } - } - - - - return fileList; - } - - private void rfileFilter(List<AFtpRemoteFile> fileContainer, AFtpRemoteFile[] arfs, String ftpRegular) { - if (ftpRegular!=null && ftpRegular.length()>0) { - Pattern pattern = null; - try { - pattern = Pattern.compile(ftpRegular, Pattern.CASE_INSENSITIVE); - } catch (Exception e) { - log.info("["+ftpRegular+"]Pattern.compile exception:"+e.getMessage()); - //should rethrow exception or return from here - } - int hisSize = fileContainer.size(); - for (int j=0; arfs!=null&&j<arfs.length; j++) { - String fileName = parseFileName(arfs[j].getFileName()); - Matcher matcher=null; - if(pattern!=null) - matcher = pattern.matcher(fileName); - else{ - //define the flow when pattern is null - } - - if (matcher.find()) - fileContainer.add(arfs[j]); - } - log.info("["+ftpRegular+"]filter["+(fileContainer.size()-hisSize)+"]filse"); - pattern = null; - }else { - for (int j=0; arfs!=null&&j<arfs.length; j++) - fileContainer.add(arfs[j]); - } - - } - - private String parseFileName(String fileName) { - int idx = fileName.lastIndexOf("/"); - if (idx == -1) - return fileName; - return fileName.substring(idx+1, fileName.length()); - } - - private String[] parseExprKeys(String source) { - - if(source.indexOf(";") > -1){ - source = source.substring(0, source.indexOf(";")); - } - if (source.endsWith("/")) - return new String[]{source,""}; - - int idx = source.lastIndexOf("/"); - String[] dirkeys = new String[2]; - dirkeys[0] = source.substring(0, idx+1); - dirkeys[1] = source.substring(idx+1, source.length()); - return dirkeys; - } - - - public List<String> getPathNoRegular(List<String> searchExprList,FTPInterface ftpCache) throws Exception{ - boolean isregular = false; - List<String> regularList = new ArrayList<String>(); - for(String regular : searchExprList){ - Pattern lpattern = null; - try{ - lpattern = Pattern.compile("(.*/)<([^/]+)>(/.*)"); - }catch (Exception e) { - log.error("["+regular+"]compile fails:"+e.getMessage()); - e.printStackTrace(); - } - - Matcher matcher = lpattern.matcher(regular); - if(matcher.find()){ - isregular = true; - String parpath = matcher.group(1); - try{ - boolean isin = ftpCache.chdir(parpath); - if(isin){ - log.info("cd dir [" + parpath + "] sucess"); - }else{ - log.error("cd dir [" + parpath + "] fail"); - } - }catch(Exception e){ - log.error(" cd dir ["+parpath+"]fail",e); - throw e; - } - RemoteFile[] remotef = ftpCache.list(); - for(RemoteFile aremote :remotef){ - if(aremote.isDirectory()&&aremote.getFileName().matches(matcher.group(2))){ - regularList.add(matcher.group(1)+aremote.getFileName()+matcher.group(3)); - } - } - }else{ - regularList.add(regular); - } - } - if(isregular==true){ - getPathNoRegular(regularList,ftpCache); - } - return regularList; - } - + file = new File(orgFile); + } + File[] files = file.listFiles(); + + return files; + + } + + private List<String> ftpDownload(CollectVo collectVo) { + + List<String> fileList = new ArrayList<String>(); + //IP + String ip = collectVo.getIP(); + //port + String port = collectVo.getPort(); + //user + String user = collectVo.getUser(); + //password + String password = collectVo.getPassword(); + //isPassiveMode + String passivemode = collectVo.getPassive(); + + FTPInterface ftpClient = new FTPSrv(); + + //login + try { + log.info("ftp login ,ip=[" + ip + "] port=[" + port + "] user=[" + user + "]password=[" + password + "]"); + ftpClient.login(ip, Integer.parseInt(port), user, password, "GBK", Boolean.parseBoolean(passivemode), 5 * 60 * 1000); + } catch (Exception e) { + log.error("login fail,ip=[" + ip + "] port=[" + port + "] user=[" + user + "]password=[" + password + "]" + StringUtil.getStackTrace(e)); + return fileList; + } + + //download + String dir = collectVo.getRemotepath(); + List<String> searchExprList = new ArrayList<String>(); + String[] FPath = dir.split(";"); + for (int i = 0; i < FPath.length; i++) { + int oldSize = searchExprList.size(); + String conpath = FPath[i] + collectVo.getMatch(); + Hashtable<String, String> varMap = new Hashtable<String, String>(); + long collectPeriod = 900; + try { + collectPeriod = Long.parseLong(collectVo.getGranularity()) * 60; + log.info("collectPeriod =[" + collectPeriod + "]"); + } catch (NumberFormatException e) { + e.printStackTrace(); + } + long[] d = DateUtil.getScanScope(new Date(), collectPeriod); + searchExprList.add(VarExprParser.replaceVar(conpath, d[0], d[1])); + + varMap.clear(); + varMap = null; + log.info("[" + conpath + "] result[" + (searchExprList.size() - oldSize) + "] path"); + conpath = null; + } + String nowdir = null; + try { + nowdir = ftpClient.pwd(); + searchExprList = getPathNoRegular(searchExprList, ftpClient); + } catch (Exception e1) { + log.error(" collect fail ", e1); + return fileList; + } + List<AFtpRemoteFile> remoteFiles = new ArrayList<AFtpRemoteFile>(); + for (String expr : searchExprList) { + ftpClient.chdir(nowdir); + String keys[] = parseExprKeys(expr); + String ftpRegular = keys[1]; + String ftpDir = keys[0]; + + boolean cdsucess = ftpClient.chdir(ftpDir); + if (cdsucess) { + AFtpRemoteFile[] arf = (AFtpRemoteFile[]) ftpClient.list(); + log.info(" list [" + ftpDir + "] result[" + (arf == null ? "null" : arf.length) + "] files"); + //filter + + rfileFilter(remoteFiles, arf, ftpRegular); + + keys = null; + ftpRegular = ftpDir = null; + + for (AFtpRemoteFile ftpRemoteFile : remoteFiles) { + if (!new File(localPath).exists()) { + try { + new File(localPath).mkdir(); + } catch (Exception e) { + log.error("create localPath is fail localPath=" + localPath + " " + StringUtil.getStackTrace(e)); + } + } + + if (!new File(localPath).exists()) { + new File(localPath).mkdirs(); + } + + String localFileName = localPath + ftpRemoteFile.getFileName(); + File loaclFile = new File(localFileName); + if (loaclFile.exists()) { + loaclFile.delete(); + } + + boolean flag = ftpClient.downloadFile(ftpRemoteFile.getAbsFileName(), localFileName); + + if (flag) { + fileList.add(localFileName); + } else { + log.error("download file fail fileName=" + ftpRemoteFile.getAbsFileName()); + } + } + + } else { + log.error("cd dir is faill dir =[" + ftpDir + "]"); + } + } + + + return fileList; + } + + private void rfileFilter(List<AFtpRemoteFile> fileContainer, AFtpRemoteFile[] arfs, String ftpRegular) { + if (ftpRegular != null && ftpRegular.length() > 0) { + Pattern pattern = null; + try { + pattern = Pattern.compile(ftpRegular, Pattern.CASE_INSENSITIVE); + } catch (Exception e) { + log.info("[" + ftpRegular + "]Pattern.compile exception:" + e.getMessage()); + //should rethrow exception or return from here + } + int hisSize = fileContainer.size(); + for (int j = 0; arfs != null && j < arfs.length; j++) { + String fileName = parseFileName(arfs[j].getFileName()); + Matcher matcher = null; + if (pattern != null) + matcher = pattern.matcher(fileName); + else { + //define the flow when pattern is null + } + + if (matcher.find()) + fileContainer.add(arfs[j]); + } + log.info("[" + ftpRegular + "]filter[" + (fileContainer.size() - hisSize) + "]filse"); + pattern = null; + } else { + for (int j = 0; arfs != null && j < arfs.length; j++) + fileContainer.add(arfs[j]); + } + + } + + private String parseFileName(String fileName) { + int idx = fileName.lastIndexOf("/"); + if (idx == -1) + return fileName; + return fileName.substring(idx + 1, fileName.length()); + } + + private String[] parseExprKeys(String source) { + + if (source.indexOf(";") > -1) { + source = source.substring(0, source.indexOf(";")); + } + if (source.endsWith("/")) + return new String[]{source, ""}; + + int idx = source.lastIndexOf("/"); + String[] dirkeys = new String[2]; + dirkeys[0] = source.substring(0, idx + 1); + dirkeys[1] = source.substring(idx + 1, source.length()); + return dirkeys; + } + + + public List<String> getPathNoRegular(List<String> searchExprList, FTPInterface ftpCache) throws Exception { + boolean isregular = false; + List<String> regularList = new ArrayList<String>(); + for (String regular : searchExprList) { + Pattern lpattern = null; + try { + lpattern = Pattern.compile("(.*/)<([^/]+)>(/.*)"); + } catch (Exception e) { + log.error("[" + regular + "]compile fails:" + e.getMessage()); + e.printStackTrace(); + } + + Matcher matcher = lpattern.matcher(regular); + if (matcher.find()) { + isregular = true; + String parpath = matcher.group(1); + try { + boolean isin = ftpCache.chdir(parpath); + if (isin) { + log.info("cd dir [" + parpath + "] sucess"); + } else { + log.error("cd dir [" + parpath + "] fail"); + } + } catch (Exception e) { + log.error(" cd dir [" + parpath + "]fail", e); + throw e; + } + RemoteFile[] remotef = ftpCache.list(); + for (RemoteFile aremote : remotef) { + if (aremote.isDirectory() && aremote.getFileName().matches(matcher.group(2))) { + regularList.add(matcher.group(1) + aremote.getFileName() + matcher.group(3)); + } + } + } else { + regularList.add(regular); + } + } + if (isregular == true) { + getPathNoRegular(regularList, ftpCache); + } + return regularList; + } + } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/TaskThreadService.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/TaskThreadService.java index 444b9a0..848de63 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/TaskThreadService.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/TaskThreadService.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,94 +15,87 @@ */ package org.onap.vfc.nfvo.emsdriver.collector; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.onap.vfc.nfvo.emsdriver.commons.constant.Constant; import org.onap.vfc.nfvo.emsdriver.commons.model.CollectMsg; import org.onap.vfc.nfvo.emsdriver.commons.utils.StringUtil; +import java.util.concurrent.*; public class TaskThreadService extends Thread { - - public Log log = LogFactory.getLog(TaskThreadService.class); - private final ExecutorService pool; - - private BlockingQueue<CollectMsg> queue = new LinkedBlockingQueue<CollectMsg>(); - private boolean startFlag = true; - - public static TaskThreadService getInstance(int poolSize) { - return new TaskThreadService(poolSize); - } - private TaskThreadService(int poolSize) { - pool = Executors.newFixedThreadPool(poolSize); - } - - private long timeStamp = System.currentTimeMillis(); - public void run() { // run the service - try { - while(startFlag) { - - try { - if(System.currentTimeMillis() - timeStamp > Constant.ONEMINUTE){ - timeStamp = System.currentTimeMillis(); - log.debug("task queue size " + queue.size()); - } - - CollectMsg data = receive(); - if(data == null){ - continue; - } - - pool.execute(new TaskThread(data)); - - - } catch (Exception e) { - log.error("collect task process fail!"+StringUtil.getStackTrace(e)); - } - - } - - } catch (Exception ex) { - log.error("task ThreadService error "+StringUtil.getStackTrace(ex)); - pool.shutdown(); - } - log.error("Task ThreadService exit"); - } - - - - public CollectMsg receive() { - try { - return queue.poll(100, TimeUnit.MILLISECONDS); - } catch (InterruptedException e) { - log.error("queue.poll is error"+StringUtil.getStackTrace(e)); - } - return null; - } - - - - public void add(CollectMsg data){ - try { - queue.put(data); - } catch (InterruptedException e) { - log.error("queue.put is error"+StringUtil.getStackTrace(e)); - } - } - - - public int size(){ - return queue.size(); - } - - public void stopTask(){ - startFlag = false; - } + + private final ExecutorService pool; + public Log log = LogFactory.getLog(TaskThreadService.class); + private BlockingQueue<CollectMsg> queue = new LinkedBlockingQueue<CollectMsg>(); + private boolean startFlag = true; + private long timeStamp = System.currentTimeMillis(); + + private TaskThreadService(int poolSize) { + pool = Executors.newFixedThreadPool(poolSize); + } + + public static TaskThreadService getInstance(int poolSize) { + return new TaskThreadService(poolSize); + } + + public void run() { // run the service + try { + while (startFlag) { + + try { + if (System.currentTimeMillis() - timeStamp > Constant.ONEMINUTE) { + timeStamp = System.currentTimeMillis(); + log.debug("task queue size " + queue.size()); + } + + CollectMsg data = receive(); + if (data == null) { + continue; + } + + pool.execute(new TaskThread(data)); + + + } catch (Exception e) { + log.error("collect task process fail!" + StringUtil.getStackTrace(e)); + } + + } + + } catch (Exception ex) { + log.error("task ThreadService error " + StringUtil.getStackTrace(ex)); + pool.shutdown(); + } + log.error("Task ThreadService exit"); + } + + + public CollectMsg receive() { + try { + return queue.poll(100, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + log.error("queue.poll is error" + StringUtil.getStackTrace(e)); + } + return null; + } + + + public void add(CollectMsg data) { + try { + queue.put(data); + } catch (InterruptedException e) { + log.error("queue.put is error" + StringUtil.getStackTrace(e)); + } + } + + + public int size() { + return queue.size(); + } + + public void stopTask() { + startFlag = false; + } } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/AlarmManager.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/AlarmManager.java index 3535fa2..2773613 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/AlarmManager.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/AlarmManager.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,8 +14,6 @@ * limitations under the License. */ package org.onap.vfc.nfvo.emsdriver.collector.alarm; -import java.util.ArrayList; -import java.util.List; import org.onap.vfc.nfvo.emsdriver.commons.constant.Constant; import org.onap.vfc.nfvo.emsdriver.commons.model.CollectVo; @@ -24,61 +22,63 @@ import org.onap.vfc.nfvo.emsdriver.commons.utils.DriverThread; import org.onap.vfc.nfvo.emsdriver.configmgr.ConfigurationInterface; import org.onap.vfc.nfvo.emsdriver.configmgr.ConfigurationManager; -public class AlarmManager extends DriverThread{ +import java.util.ArrayList; +import java.util.List; + +public class AlarmManager extends DriverThread { + + private ConfigurationInterface configurationInterface; + + @Override + public void dispose() { + log.debug("AlarmManager is start"); + //get alarm CONFIG_PROPERTIES_LOCATION + List<EMSInfo> emsInfos = configurationInterface.getAllEMSInfo(); + while (isRun() && emsInfos.size() == 0) { + emsInfos = configurationInterface.getAllEMSInfo(); + if (emsInfos.size() == 0) { + try { + Thread.sleep(1000); + log.debug("The configuration properties from " + ConfigurationManager.CONFIG_PROPERTIES_LOCATION + " is not load"); + } catch (InterruptedException e) { + } + } + } + List<CollectVo> collectVos = new ArrayList<CollectVo>(); + for (EMSInfo emsInfo : emsInfos) { + //alarm + CollectVo CollectVo = emsInfo.getCollectVoByType(Constant.COLLECT_TYPE_ALARM); + if (CollectVo != null) { + CollectVo.setEmsName(emsInfo.getName()); + collectVos.add(CollectVo); + } else { + log.error("emsInfo.getCollectVoByType(EMS_RESOUCE) result CollectVo = null emsInfo =" + emsInfo); + } + } + + for (CollectVo collectVo : collectVos) { + AlarmTaskThread alarm = new AlarmTaskThread(collectVo); + alarm.setName(collectVo.getIP() + collectVo.getPort()); + alarm.start(); + log.info("AlarmTaskThread is start"); + } + + } - private ConfigurationInterface configurationInterface; - - @Override - public void dispose() { - log.debug("AlarmManager is start"); - //get alarm CONFIG_PROPERTIES_LOCATION - List<EMSInfo> emsInfos = configurationInterface.getAllEMSInfo(); - while(isRun() && emsInfos.size() == 0){ - emsInfos = configurationInterface.getAllEMSInfo(); - if(emsInfos.size() == 0){ - try { - Thread.sleep(1000); - log.debug("The configuration properties from " + ConfigurationManager.CONFIG_PROPERTIES_LOCATION + " is not load"); - } catch (InterruptedException e) { - } - } - } - List<CollectVo> collectVos = new ArrayList<CollectVo>(); - for(EMSInfo emsInfo : emsInfos){ - //alarm - CollectVo CollectVo = emsInfo.getCollectVoByType(Constant.COLLECT_TYPE_ALARM); - if(CollectVo != null){ - CollectVo.setEmsName(emsInfo.getName()); - collectVos.add(CollectVo); - }else{ - log.error("emsInfo.getCollectVoByType(EMS_RESOUCE) result CollectVo = null emsInfo ="+emsInfo); - } - } - - for(CollectVo collectVo : collectVos){ - AlarmTaskThread alarm = new AlarmTaskThread(collectVo); - alarm.setName(collectVo.getIP()+collectVo.getPort()); - alarm.start(); - log.info("AlarmTaskThread is start"); - } - - } + /** + * @return the configurationInterface + */ + public ConfigurationInterface getConfigurationInterface() { + return configurationInterface; + } - /** - * @return the configurationInterface - */ - public ConfigurationInterface getConfigurationInterface() { - return configurationInterface; - } + /** + * @param configurationInterface the configurationInterface to set + */ + public void setConfigurationInterface( + ConfigurationInterface configurationInterface) { + this.configurationInterface = configurationInterface; + } - /** - * @param configurationInterface the configurationInterface to set - */ - public void setConfigurationInterface( - ConfigurationInterface configurationInterface) { - this.configurationInterface = configurationInterface; - } - - } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/AlarmTaskThread.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/AlarmTaskThread.java index d964f32..235778b 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/AlarmTaskThread.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/AlarmTaskThread.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,13 +15,6 @@ */ package org.onap.vfc.nfvo.emsdriver.collector.alarm; -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.IOException; -import java.net.Socket; -import java.net.SocketException; -import java.net.UnknownHostException; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.onap.vfc.nfvo.emsdriver.commons.constant.Constant; @@ -30,265 +23,269 @@ import org.onap.vfc.nfvo.emsdriver.commons.utils.StringUtil; import org.onap.vfc.nfvo.emsdriver.messagemgr.MessageChannel; import org.onap.vfc.nfvo.emsdriver.messagemgr.MessageChannelFactory; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.net.Socket; +import java.net.SocketException; +import java.net.UnknownHostException; + + +public class AlarmTaskThread extends Thread { + public Log log = LogFactory.getLog(AlarmTaskThread.class); + + private HeartBeat heartBeat = null; + + private boolean isStop = false; + private CollectVo collectVo = null; + private int read_timeout = Constant.READ_TIMEOUT_MILLISECOND; + private int reqId; + + private Socket socket = null; + private BufferedInputStream is = null; + private BufferedOutputStream dos = null; + + private MessageChannel alarmChannel; + + + public AlarmTaskThread() { + super(); + } + + public AlarmTaskThread(CollectVo collectVo) { + + this.collectVo = collectVo; + } + + public void run() { + alarmChannel = MessageChannelFactory.getMessageChannel(Constant.RESULT_CHANNEL_KEY); + try { + this.init(); + while (!this.isStop) { + String body; + try { + body = this.receive(); + try { + alarmChannel.put(body); + } catch (InterruptedException e) { + log.error(StringUtil.getStackTrace(e)); + } + } catch (Exception e) { + e.printStackTrace(); + reinit(); + } + } + } catch (Exception e) { + log.error(StringUtil.getStackTrace(e)); + } + } + + + public String receive() throws Exception { + + Msg msg = null; + String retString = null; + + while (retString == null && !this.isStop) { + + msg = MessageUtil.readOneMsg(is); + log.debug("msg = " + msg.toString(true)); + log.info("msg.getMsgType().name = " + msg.getMsgType().name); + if ("ackLoginAlarm".equalsIgnoreCase(msg.getMsgType().name)) { + log.debug("receive login ack"); + boolean suc = this.ackLoginAlarm(msg); + if (suc) { + + if (reqId == Integer.MAX_VALUE) { + reqId = 0; + } + reqId++; + Msg msgheart = MessageUtil.putHeartBeatMsg(reqId); + heartBeat = new HeartBeat(socket, msgheart); + heartBeat.setName("CMCC_JT_HeartBeat"); + // start heartBeat + heartBeat.start(); + } + retString = null; + } + + if ("ackHeartBeat".equalsIgnoreCase(msg.getMsgType().name)) { + log.debug("received heartBeat message:" + msg.getBody()); + retString = null; + } + + + if ("realTimeAlarm".equalsIgnoreCase(msg.getMsgType().name)) { + log.debug("received alarm message"); + retString = msg.getBody(); + } + + if (retString == null) { + Thread.sleep(100); + } + } + return retString; + } + + public void init() throws Exception { + isStop = false; + //host + String host = collectVo.getIP(); + //port + String port = collectVo.getPort(); + //user + String user = collectVo.getUser(); + //password + String password = collectVo.getPassword(); + + String read_timeout = collectVo.getRead_timeout(); + if ((read_timeout != null) && (read_timeout.trim().length() > 0)) { + try { + this.read_timeout = Integer.parseInt(read_timeout); + } catch (NumberFormatException e) { + log.error(StringUtil.getStackTrace(e)); + } + } + log.info("socket connect host=" + host + ", port=" + port); + try { + int portInt = Integer.parseInt(port); + socket = new Socket(host, portInt); + + } catch (UnknownHostException e) { + throw new Exception("remote host [" + host + "]connect fail" + StringUtil.getStackTrace(e)); + } catch (IOException e) { + throw new Exception("create socket IOException " + StringUtil.getStackTrace(e)); + } + try { + socket.setSoTimeout(this.read_timeout); + socket.setTcpNoDelay(true); + socket.setKeepAlive(true); + } catch (SocketException e) { + throw new Exception(" SocketException " + StringUtil.getStackTrace(e)); + } + try { + dos = new BufferedOutputStream(socket.getOutputStream()); + + Msg msg = MessageUtil.putLoginMsg(user, password); + + try { + log.debug("send login message " + msg.toString(false)); + MessageUtil.writeMsg(msg, dos); + + } catch (Exception e) { + log.error("send login message is fail " + StringUtil.getStackTrace(e)); + } + + is = new BufferedInputStream(socket.getInputStream()); + + } catch (SocketException e) { + throw new Exception(StringUtil.getStackTrace(e)); + } + } + + private boolean ackLoginAlarm(Msg msg) throws Exception { + + boolean is_success = false; + try { + String loginres = msg.getBody(); + //ackLoginAlarm; result=fail(succ); resDesc=username-error + String[] loginbody = loginres.split(";"); + if (loginbody.length > 1) { + for (String str : loginbody) { + if (str.contains("=")) { + String[] paras1 = str.split("=", -1); + if ("result".equalsIgnoreCase(paras1[0].trim())) { + if ("succ".equalsIgnoreCase(paras1[1].trim())) { + is_success = true; + } else { + is_success = false; + } + } + } + } + } else { + log.error("login ack body Incorrect formatbody=" + loginres); + } + + + } catch (Exception e) { + log.error("pocess login ack fail" + StringUtil.getStackTrace(e)); + } + if (is_success) { + log.info("login sucess receive login ack " + msg.getBody()); + } else { + log.error("login fail receive login ack " + msg.getBody()); + this.close(); + this.isStop = true; + throw new Exception("login fail quit"); + } + return is_success; + } + + public void close() { + + if (heartBeat != null) { + heartBeat.setStop(true); + } + + if (is != null) { + try { + is.close(); + } catch (IOException e) { + } finally { + is = null; + } + } + + if (dos != null) { + try { + dos.close(); + } catch (IOException e) { + } finally { + dos = null; + } + } + + if (socket != null) { + try { + socket.close(); + } catch (IOException e) { + } finally { + socket = null; + } + + } + } + + public void reinit() { + int time = 0; + close(); + while (!this.isStop) { + close(); + time++; + try { + Thread.sleep(1000 * 30); + init(); + return; + } catch (Exception e) { + log.error("Number [" + time + "]reconnect [" + collectVo.getIP() + "]fail"); + } + } + } + + /** + * @param isStop the isStop to set + */ + public void setStop(boolean isStop) { + this.isStop = isStop; + } + + /** + * @return the heartBeat + */ + public HeartBeat getHeartBeat() { + return heartBeat; + } + -public class AlarmTaskThread extends Thread{ - public Log log = LogFactory.getLog(AlarmTaskThread.class); - - private HeartBeat heartBeat = null; - - private boolean isStop = false; - private CollectVo collectVo = null; - private int read_timeout = Constant.READ_TIMEOUT_MILLISECOND; - private int reqId; - - private Socket socket = null; - private BufferedInputStream is = null; - private BufferedOutputStream dos = null; - - private MessageChannel alarmChannel; - - - public AlarmTaskThread() { - super(); - } - - public AlarmTaskThread(CollectVo collectVo) { - - this.collectVo = collectVo; - } - - public void run() { - alarmChannel = MessageChannelFactory.getMessageChannel(Constant.RESULT_CHANNEL_KEY); - try { - this.init(); - while(!this.isStop){ - String body; - try { - body = this.receive(); - try { - alarmChannel.put(body); - } catch (InterruptedException e) { - log.error(StringUtil.getStackTrace(e)); - } - } catch (Exception e) { - e.printStackTrace(); - reinit(); - } - } - } catch (Exception e) { - log.error(StringUtil.getStackTrace(e)); - } - } - - - - public String receive() throws Exception { - - Msg msg =null; - String retString = null; - - while (retString == null && !this.isStop) { - - msg = MessageUtil.readOneMsg(is); - log.debug("msg = "+msg.toString(true)); - log.info("msg.getMsgType().name = "+msg.getMsgType().name); - if("ackLoginAlarm".equalsIgnoreCase(msg.getMsgType().name)){ - log.debug("receive login ack"); - boolean suc = this.ackLoginAlarm(msg); - if(suc){ - - if(reqId == Integer.MAX_VALUE){ - reqId = 0; - } - reqId ++; - Msg msgheart = MessageUtil.putHeartBeatMsg(reqId); - heartBeat = new HeartBeat(socket,msgheart); - heartBeat.setName("CMCC_JT_HeartBeat"); - // start heartBeat - heartBeat.start(); - } - retString = null; - } - - if("ackHeartBeat".equalsIgnoreCase(msg.getMsgType().name)){ - log.debug("received heartBeat message:"+msg.getBody()); - retString = null; - } - - - - if("realTimeAlarm".equalsIgnoreCase(msg.getMsgType().name)){ - log.debug("received alarm message"); - retString = msg.getBody(); - } - - if(retString == null){ - Thread.sleep(100); - } - } - return retString; - } - - public void init() throws Exception { - isStop = false; - //host - String host = collectVo.getIP(); - //port - String port = collectVo.getPort(); - //user - String user = collectVo.getUser(); - //password - String password = collectVo.getPassword(); - - String read_timeout = collectVo.getRead_timeout(); - if ((read_timeout != null) && (read_timeout.trim().length() > 0)) { - try { - this.read_timeout = Integer.parseInt(read_timeout); - } catch (NumberFormatException e) { - log.error(StringUtil.getStackTrace(e)); - } - } - log.info("socket connect host=" + host + ", port=" + port); - try { - int portInt = Integer.parseInt(port); - socket = new Socket(host, portInt); - - } catch (UnknownHostException e) { - throw new Exception("remote host [" + host + "]connect fail" + StringUtil.getStackTrace(e)); - } catch (IOException e) { - throw new Exception("create socket IOException " + StringUtil.getStackTrace(e)); - } - try { - socket.setSoTimeout(this.read_timeout); - socket.setTcpNoDelay(true); - socket.setKeepAlive(true); - } catch (SocketException e) { - throw new Exception(" SocketException " + StringUtil.getStackTrace(e)); - } - try { - dos = new BufferedOutputStream(socket.getOutputStream()); - - Msg msg = MessageUtil.putLoginMsg(user,password); - - try { - log.debug("send login message "+msg.toString(false)); - MessageUtil.writeMsg(msg,dos); - - } catch (Exception e) { - log.error("send login message is fail "+StringUtil.getStackTrace(e)); - } - - is = new BufferedInputStream(socket.getInputStream()); - - } catch (SocketException e) { - throw new Exception(StringUtil.getStackTrace(e)); - } - } - - private boolean ackLoginAlarm(Msg msg) throws Exception { - - boolean is_success = false; - try { - String loginres = msg.getBody(); - //ackLoginAlarm; result=fail(succ); resDesc=username-error - String [] loginbody = loginres.split(";"); - if(loginbody.length > 1){ - for(String str :loginbody){ - if(str.contains("=")){ - String [] paras1 = str.split("=",-1); - if("result".equalsIgnoreCase(paras1[0].trim())){ - if("succ".equalsIgnoreCase(paras1[1].trim())){ - is_success = true; - }else{ - is_success = false; - } - } - } - } - }else { - log.error("login ack body Incorrect formatbody=" + loginres); - } - - - } catch (Exception e) { - log.error("pocess login ack fail"+StringUtil.getStackTrace(e)); - } - if (is_success) { - log.info("login sucess receive login ack " + msg.getBody()); - } else { - log.error("login fail receive login ack " + msg.getBody()); - this.close(); - this.isStop = true; - throw new Exception("login fail quit"); - } - return is_success; - } - - public void close() { - - if(heartBeat != null){ - heartBeat.setStop(true); - } - - if (is != null) { - try { - is.close(); - } catch (IOException e) { - } finally { - is = null; - } - } - - if (dos != null) { - try { - dos.close(); - } catch (IOException e) { - } finally { - dos = null; - } - } - - if (socket != null) { - try { - socket.close(); - } catch (IOException e) { - } finally { - socket = null; - } - - } - } - - public void reinit() { - int time = 0; - close(); - while(!this.isStop) { - close(); - time++; - try { - Thread.sleep(1000 * 30); - init(); - return; - } catch (Exception e) { - log.error("Number ["+time+"]reconnect ["+collectVo.getIP()+"]fail" ); - } - } - } - - /** - * @param isStop the isStop to set - */ - public void setStop(boolean isStop) { - this.isStop = isStop; - } - - /** - * @return the heartBeat - */ - public HeartBeat getHeartBeat() { - return heartBeat; - } - - - } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/HeartBeat.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/HeartBeat.java index 96a301d..ec9005d 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/HeartBeat.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/HeartBeat.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,46 +15,48 @@ */ package org.onap.vfc.nfvo.emsdriver.collector.alarm; -import java.io.BufferedOutputStream; -import java.net.Socket; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.onap.vfc.nfvo.emsdriver.commons.constant.Constant; -public class HeartBeat extends Thread{ - public Log log = LogFactory.getLog(HeartBeat.class); - private BufferedOutputStream out = null; - private Socket socket=null; - private Msg heartStr ; - private boolean stop = false; - public boolean isStop(){ - return this.stop; - } - public void setStop(boolean stop){ - this.stop = stop; - } - - public HeartBeat( Socket socket,Msg heatMessage){ - this.socket=socket; - this.heartStr = heatMessage; - } - - public void run(){ - log.info("HeartBeat start heartStr:"+heartStr.toString(false)); - this.stop=false; - try { - while(!this.isStop()){ - out = new BufferedOutputStream(socket.getOutputStream()); - MessageUtil.writeMsg(heartStr,out); - log.info("send HeartBeat heartStr:"+heartStr.toString(false)); - Thread.sleep(Constant.ONEMINUTE); - } - } catch (Exception e) { - log.error("send HeartBeat fail ",e); - } - log.info("HeartBeat thread stop"); - } - +import java.io.BufferedOutputStream; +import java.net.Socket; + +public class HeartBeat extends Thread { + public Log log = LogFactory.getLog(HeartBeat.class); + private BufferedOutputStream out = null; + private Socket socket = null; + private Msg heartStr; + private boolean stop = false; + + public HeartBeat(Socket socket, Msg heatMessage) { + this.socket = socket; + this.heartStr = heatMessage; + } + + public boolean isStop() { + return this.stop; + } + + public void setStop(boolean stop) { + this.stop = stop; + } + + public void run() { + log.info("HeartBeat start heartStr:" + heartStr.toString(false)); + this.stop = false; + try { + while (!this.isStop()) { + out = new BufferedOutputStream(socket.getOutputStream()); + MessageUtil.writeMsg(heartStr, out); + log.info("send HeartBeat heartStr:" + heartStr.toString(false)); + Thread.sleep(Constant.ONEMINUTE); + } + } catch (Exception e) { + log.error("send HeartBeat fail ", e); + } + log.info("HeartBeat thread stop"); + } + } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/MessageUtil.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/MessageUtil.java index cc9da10..7bf7a11 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/MessageUtil.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/MessageUtil.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,150 +15,138 @@ */ package org.onap.vfc.nfvo.emsdriver.collector.alarm; -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; - - - -public class MessageUtil -{ - public static String MSG_BODY_ENCODE_CHARSET="UTF-8"; - public static int MSG_BUF_SIZE=8096 ; - - public static Msg putLoginMsg(String user,String passwd) - { - String body = String.format(Msg.reqLoginAlarm, user,passwd,"msg"); - Msg msg = new Msg(body,MsgType.reqLoginAlarm); - - - return msg; - - } - public static Msg putLoginFtp(String user,String passwd) - { - String body = String.format(Msg.reqLoginAlarm, user,passwd,"ftp"); - Msg msg = new Msg(body,MsgType.reqLoginAlarm); - - - return msg; - - } - - public static Msg putSyncMsg(int reqId,int alarmSeq) - { - String body = String.format(Msg.syncAlarmMessageMsg, reqId,alarmSeq); - Msg msg = new Msg(body,MsgType.reqSyncAlarmMsg); - - - return msg; - - } - - public static Msg putHeartBeatMsg(int reqId) - { - String body = String.format(Msg.reqHeartBeat, reqId); - Msg msg = new Msg(body,MsgType.reqHeartBeat); - return msg; - - } - - public static Msg reqSyncAlarmFile(int reqId, String startTime,String endTime) { - String body = String.format(Msg.syncActiveAlarmFileMsg, reqId,startTime,endTime); - Msg msg = new Msg(body,MsgType.reqSyncAlarmFile); - return msg; - } - - public static Msg reqSyncAlarmFileByAlarmSeq(int reqId, int alarmSeq) { - String body = String.format(Msg.syncAlarmMessageByalarmSeq, reqId,alarmSeq); - Msg msg = new Msg(body,MsgType.reqSyncAlarmFile); - return msg; - } - - public static Msg reqSyncAlarmFileByTime(int reqId, String startTime,String endTime) { - String body = String.format(Msg.syncAlarmFileMsg, reqId,startTime,endTime); - Msg msg = new Msg(body,MsgType.reqSyncAlarmFile); - return msg; - } - - public static Msg closeConnAlarmMsg() - { - String body = String.format(Msg.disconnectMsg); - Msg msg = new Msg(body,MsgType.closeConnAlarm); - return msg; - } - - public static Msg readOneMsg(BufferedInputStream is) throws Exception - { - byte[] inputB = new byte[9]; - - ByteArrayInputStream bais = null; - DataInputStream ois = null; - - Msg msg = new Msg(); - try { - DataInputStream dis = new DataInputStream(is); - dis.readFully(inputB); - bais = new ByteArrayInputStream(inputB); - ois = new DataInputStream(bais); - short StartSign = ois.readShort(); - if (StartSign != Msg.StartSign) { - throw new Exception("start sign is [" + Msg.StartSign - + "],not is [" + StartSign + "]"); - } - int msgType = ois.readByte(); - msg.setMsgType(MsgType.getMsgTypeValue(msgType)); - int timeStamp = ois.readInt(); - msg.setTimeStamp(timeStamp); - int bodylength = ois.readShort(); - msg.setLenOfBody(bodylength); - byte b[] = new byte[bodylength]; - dis.readFully(b); - msg.newBodyfromBytes(b); - } catch (Exception e) { - throw new Exception(e); - }finally{ - if(bais != null){ - bais.close(); - } - if(ois != null){ - ois.close(); - } - } - - return msg; - } - - public static void writeMsg(Msg msg,BufferedOutputStream dout) throws Exception{ - - ByteArrayOutputStream byteOutStream = null; - DataOutputStream oos = null; - try { - byteOutStream = new ByteArrayOutputStream(9); - oos = new DataOutputStream(byteOutStream); - oos.writeShort(Msg.StartSign); - oos.writeByte(msg.getMsgType().value); - oos.writeInt(Msg.creatMsgTimeStamp()); - oos.writeShort(msg.getBodyLenNow()); - - dout.write(byteOutStream.toByteArray()); - - dout.write(msg.getBodyBytes()); - dout.flush(); - } catch (Exception e) { - throw new Exception(e); - }finally{ - if(oos != null){ - oos.close(); - } - if(byteOutStream != null){ - byteOutStream.close(); - } - } - - } - +import java.io.*; + + +public class MessageUtil { + public static String MSG_BODY_ENCODE_CHARSET = "UTF-8"; + public static int MSG_BUF_SIZE = 8096; + + public static Msg putLoginMsg(String user, String passwd) { + String body = String.format(Msg.reqLoginAlarm, user, passwd, "msg"); + Msg msg = new Msg(body, MsgType.reqLoginAlarm); + + + return msg; + + } + + public static Msg putLoginFtp(String user, String passwd) { + String body = String.format(Msg.reqLoginAlarm, user, passwd, "ftp"); + Msg msg = new Msg(body, MsgType.reqLoginAlarm); + + + return msg; + + } + + public static Msg putSyncMsg(int reqId, int alarmSeq) { + String body = String.format(Msg.syncAlarmMessageMsg, reqId, alarmSeq); + Msg msg = new Msg(body, MsgType.reqSyncAlarmMsg); + + + return msg; + + } + + public static Msg putHeartBeatMsg(int reqId) { + String body = String.format(Msg.reqHeartBeat, reqId); + Msg msg = new Msg(body, MsgType.reqHeartBeat); + return msg; + + } + + public static Msg reqSyncAlarmFile(int reqId, String startTime, String endTime) { + String body = String.format(Msg.syncActiveAlarmFileMsg, reqId, startTime, endTime); + Msg msg = new Msg(body, MsgType.reqSyncAlarmFile); + return msg; + } + + public static Msg reqSyncAlarmFileByAlarmSeq(int reqId, int alarmSeq) { + String body = String.format(Msg.syncAlarmMessageByalarmSeq, reqId, alarmSeq); + Msg msg = new Msg(body, MsgType.reqSyncAlarmFile); + return msg; + } + + public static Msg reqSyncAlarmFileByTime(int reqId, String startTime, String endTime) { + String body = String.format(Msg.syncAlarmFileMsg, reqId, startTime, endTime); + Msg msg = new Msg(body, MsgType.reqSyncAlarmFile); + return msg; + } + + public static Msg closeConnAlarmMsg() { + String body = String.format(Msg.disconnectMsg); + Msg msg = new Msg(body, MsgType.closeConnAlarm); + return msg; + } + + public static Msg readOneMsg(BufferedInputStream is) throws Exception { + byte[] inputB = new byte[9]; + + ByteArrayInputStream bais = null; + DataInputStream ois = null; + + Msg msg = new Msg(); + try { + DataInputStream dis = new DataInputStream(is); + dis.readFully(inputB); + bais = new ByteArrayInputStream(inputB); + ois = new DataInputStream(bais); + short StartSign = ois.readShort(); + if (StartSign != Msg.StartSign) { + throw new Exception("start sign is [" + Msg.StartSign + + "],not is [" + StartSign + "]"); + } + int msgType = ois.readByte(); + msg.setMsgType(MsgType.getMsgTypeValue(msgType)); + int timeStamp = ois.readInt(); + msg.setTimeStamp(timeStamp); + int bodylength = ois.readShort(); + msg.setLenOfBody(bodylength); + byte b[] = new byte[bodylength]; + dis.readFully(b); + msg.newBodyfromBytes(b); + } catch (Exception e) { + throw new Exception(e); + } finally { + if (bais != null) { + bais.close(); + } + if (ois != null) { + ois.close(); + } + } + + return msg; + } + + public static void writeMsg(Msg msg, BufferedOutputStream dout) throws Exception { + + ByteArrayOutputStream byteOutStream = null; + DataOutputStream oos = null; + try { + byteOutStream = new ByteArrayOutputStream(9); + oos = new DataOutputStream(byteOutStream); + oos.writeShort(Msg.StartSign); + oos.writeByte(msg.getMsgType().value); + oos.writeInt(Msg.creatMsgTimeStamp()); + oos.writeShort(msg.getBodyLenNow()); + + dout.write(byteOutStream.toByteArray()); + + dout.write(msg.getBodyBytes()); + dout.flush(); + } catch (Exception e) { + throw new Exception(e); + } finally { + if (oos != null) { + oos.close(); + } + if (byteOutStream != null) { + byteOutStream.close(); + } + } + + } + } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/Msg.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/Msg.java index b15ba7e..6ba9604 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/Msg.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/Msg.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,94 +15,91 @@ */ package org.onap.vfc.nfvo.emsdriver.collector.alarm; -import java.io.UnsupportedEncodingException; - import org.onap.vfc.nfvo.emsdriver.commons.constant.Constant; +import java.io.UnsupportedEncodingException; + public class Msg { - public static short StartSign = (short)0xffff; - - public final static String reqLoginAlarm = "reqLoginAlarm;user=%s;key=%s;type=%s"; - - public final static String reqHeartBeat = "reqHeartBeat;reqId=%s"; - public final static String disconnectMsg = "closeConnAlarm"; - - public final static String syncAlarmMessageMsg = "reqSyncAlarmMsg;reqID=%s;alarmSeq=%s"; - public final static String syncAlarmMessageByalarmSeq = "reqSyncAlarmFile;reqID=%s;alarmSeq=%s;syncSource=1"; - public final static String syncActiveAlarmFileMsg = "reqSyncAlarmFile;reqID=%s;startTime=%s;endTime=%s;syncSource=0"; - public final static String syncAlarmFileMsg = "reqSyncAlarmFile;reqID=%s;startTime=%s;endTime=%s;syncSource=1"; - - - - private MsgType msgType; - private int timeStamp = 0; - private int lenOfBody = 0; - private String body = null; - public Msg(){} - public Msg(String body,MsgType msgType ){ - this.body = body; - this.setMsgType(msgType); - } - - public void newBodyfromBytes(byte b[]) throws UnsupportedEncodingException{ - this.body = new String(b,Constant.ENCODING_UTF8); - } - public static int creatMsgTimeStamp(){ - return (int)System.currentTimeMillis()/1000; - } - - public int getBodyLenNow(){ - return getBody().getBytes().length; - } - - - public void setTimeStamp(int timeStamp) { - this.timeStamp = timeStamp; - } - - public int getTimeStamp() { - return timeStamp; - } - - public void setLenOfBody(int lenOfBody) { - this.lenOfBody = lenOfBody; - } - - public int getLenOfBody() { - return lenOfBody; - } - - public byte[] getBodyBytes() throws UnsupportedEncodingException { - return getBody().getBytes(Constant.ENCODING_UTF8); - } - - public void setBody(String body) { - this.body = body; - } - - public String getBody() { - return body; - } - - public void setMsgType(MsgType msgType) { - this.msgType = msgType; - } - - public MsgType getMsgType() { - return msgType; - } - - public String toString(boolean isRead){ - StringBuilder sb = new StringBuilder(); - sb.append("StartSign[").append(StartSign).append("]msgType[").append(msgType.value).append("]timeStamp["); - if(isRead){ - sb.append(timeStamp).append("]lenOfBody[").append(lenOfBody); - }else{ - sb.append(creatMsgTimeStamp()).append("]lenOfBody[").append(getBodyLenNow()); - } - sb.append("]body[").append(body).append("]"); - return sb.toString(); - } + public final static String reqLoginAlarm = "reqLoginAlarm;user=%s;key=%s;type=%s"; + public final static String reqHeartBeat = "reqHeartBeat;reqId=%s"; + public final static String disconnectMsg = "closeConnAlarm"; + public final static String syncAlarmMessageMsg = "reqSyncAlarmMsg;reqID=%s;alarmSeq=%s"; + public final static String syncAlarmMessageByalarmSeq = "reqSyncAlarmFile;reqID=%s;alarmSeq=%s;syncSource=1"; + public final static String syncActiveAlarmFileMsg = "reqSyncAlarmFile;reqID=%s;startTime=%s;endTime=%s;syncSource=0"; + public final static String syncAlarmFileMsg = "reqSyncAlarmFile;reqID=%s;startTime=%s;endTime=%s;syncSource=1"; + public static short StartSign = (short) 0xffff; + private MsgType msgType; + private int timeStamp = 0; + private int lenOfBody = 0; + private String body = null; + + public Msg() { + } + + public Msg(String body, MsgType msgType) { + this.body = body; + this.setMsgType(msgType); + } + + public static int creatMsgTimeStamp() { + return (int) System.currentTimeMillis() / 1000; + } + + public void newBodyfromBytes(byte b[]) throws UnsupportedEncodingException { + this.body = new String(b, Constant.ENCODING_UTF8); + } + + public int getBodyLenNow() { + return getBody().getBytes().length; + } + + public int getTimeStamp() { + return timeStamp; + } + + public void setTimeStamp(int timeStamp) { + this.timeStamp = timeStamp; + } + + public int getLenOfBody() { + return lenOfBody; + } + + public void setLenOfBody(int lenOfBody) { + this.lenOfBody = lenOfBody; + } + + public byte[] getBodyBytes() throws UnsupportedEncodingException { + return getBody().getBytes(Constant.ENCODING_UTF8); + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + public MsgType getMsgType() { + return msgType; + } + + public void setMsgType(MsgType msgType) { + this.msgType = msgType; + } + + public String toString(boolean isRead) { + StringBuilder sb = new StringBuilder(); + sb.append("StartSign[").append(StartSign).append("]msgType[").append(msgType.value).append("]timeStamp["); + if (isRead) { + sb.append(timeStamp).append("]lenOfBody[").append(lenOfBody); + } else { + sb.append(creatMsgTimeStamp()).append("]lenOfBody[").append(getBodyLenNow()); + } + sb.append("]body[").append(body).append("]"); + return sb.toString(); + } } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/MsgType.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/MsgType.java index 8167552..0e69518 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/MsgType.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/MsgType.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,48 +16,52 @@ package org.onap.vfc.nfvo.emsdriver.collector.alarm; public enum MsgType { - - reqLoginAlarm("reqLoginAlarm",1,"all"), - ackLoginAlarm("ackLoginAlarm",2,"all"), - reqSyncAlarmMsg("reqSyncAlarmMsg",3,"msg"), - ackSyncAlarmMsg("ackSyncAlarmMsg",4,"msg"), - reqSyncAlarmFile("reqSyncAlarmFile",5,"file"), - ackSyncAlarmFile("ackSyncAlarmFile",6,"file"), - ackSyncAlarmFileResult("ackSyncAlarmFileResult",7,"file"), - reqHeartBeat("reqHeartBeat",8,"all"), - ackHeartBeat("ackHeartBeat",9,"all"), - closeConnAlarm("closeConnAlarm",10,"all"), - realTimeAlarm("realTimeAlarm",0,"all"), - undefined("undefined",-1,"all"); - - public int value = -1; - public String name = null; - public String type = null; - - MsgType(String name,int value,String type){this.name = name;this.value = value;this.type = type;} - - public static MsgType getMsgTypeValue(int msgTypeValue){ - - for(MsgType msgType : MsgType.values()){ - if(msgType.value == msgTypeValue){ - return msgType; - } - } - return undefined; - } - - public static MsgType getMsgTypeName(String msgTypeName){ - - for(MsgType msgType : MsgType.values()){ - if(msgType.name.toLowerCase().equals(msgTypeName.toLowerCase())){ - return msgType; - } - } - return undefined; - } - - public String toString(){ - return this.name; - } - + + reqLoginAlarm("reqLoginAlarm", 1, "all"), + ackLoginAlarm("ackLoginAlarm", 2, "all"), + reqSyncAlarmMsg("reqSyncAlarmMsg", 3, "msg"), + ackSyncAlarmMsg("ackSyncAlarmMsg", 4, "msg"), + reqSyncAlarmFile("reqSyncAlarmFile", 5, "file"), + ackSyncAlarmFile("ackSyncAlarmFile", 6, "file"), + ackSyncAlarmFileResult("ackSyncAlarmFileResult", 7, "file"), + reqHeartBeat("reqHeartBeat", 8, "all"), + ackHeartBeat("ackHeartBeat", 9, "all"), + closeConnAlarm("closeConnAlarm", 10, "all"), + realTimeAlarm("realTimeAlarm", 0, "all"), + undefined("undefined", -1, "all"); + + public int value = -1; + public String name = null; + public String type = null; + + MsgType(String name, int value, String type) { + this.name = name; + this.value = value; + this.type = type; + } + + public static MsgType getMsgTypeValue(int msgTypeValue) { + + for (MsgType msgType : MsgType.values()) { + if (msgType.value == msgTypeValue) { + return msgType; + } + } + return undefined; + } + + public static MsgType getMsgTypeName(String msgTypeName) { + + for (MsgType msgType : MsgType.values()) { + if (msgType.name.toLowerCase().equals(msgTypeName.toLowerCase())) { + return msgType; + } + } + return undefined; + } + + public String toString() { + return this.name; + } + } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/constant/Constant.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/constant/Constant.java index 50649a4..c54b96a 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/constant/Constant.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/constant/Constant.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,30 +18,24 @@ package org.onap.vfc.nfvo.emsdriver.commons.constant; import java.io.File; public class Constant { - - public static String SYS_HOME = System.getenv("RUNHOME")==null?System.getProperty("user.dir"):System.getenv("RUNHOME"); - - public static String SYS_CFG = SYS_HOME + File.separator + "conf" + File.separator; - public static String SYS_DATA = SYS_HOME + File.separator + "data" + File.separator; - public static String SYS_DATA_TEMP = SYS_DATA + File.separator + "temp" + File.separator; - public static String SYS_DATA_RESULT = SYS_DATA + File.separator + "RESULT" + File.separator; - public static String COLLECT_TYPE_CM = "EMS_RESOUCE"; - public static String COLLECT_TYPE_PM = "EMS_PERFORMANCE"; - public static String COLLECT_TYPE_ALARM = "EMS_ALARM"; - - public static String ENCODING_UTF8 = "UTF-8"; - public static String ENCODING_GBK = "GBK"; - - public static final String COLLECT_CHANNEL_KEY = "COLLECT_CHANNEL_KEY"; - public static final String COLLECT_RESULT_CHANNEL_KEY = "COLLECT_RESULT_CHANNEL_KEY"; - public static final String COLLECT_RESULT_PM_CHANNEL_KEY = "COLLECT_RESULT_PM_CHANNEL_KEY"; - public static final String RESULT_CHANNEL_KEY = "RESULT_CHANNEL_KEY"; - - - public static final String MSBAPIROOTDOMAIN = "/api/microservices/v1/services"; - - //alarm - public static final int READ_TIMEOUT_MILLISECOND = 180000; - public static final long ONEMINUTE = 60000; - + + public static final String COLLECT_CHANNEL_KEY = "COLLECT_CHANNEL_KEY"; + public static final String COLLECT_RESULT_CHANNEL_KEY = "COLLECT_RESULT_CHANNEL_KEY"; + public static final String COLLECT_RESULT_PM_CHANNEL_KEY = "COLLECT_RESULT_PM_CHANNEL_KEY"; + public static final String RESULT_CHANNEL_KEY = "RESULT_CHANNEL_KEY"; + public static final String MSBAPIROOTDOMAIN = "/api/microservices/v1/services"; + //alarm + public static final int READ_TIMEOUT_MILLISECOND = 180000; + public static final long ONEMINUTE = 60000; + public static String SYS_HOME = System.getenv("RUNHOME") == null ? System.getProperty("user.dir") : System.getenv("RUNHOME"); + public static String SYS_CFG = SYS_HOME + File.separator + "conf" + File.separator; + public static String SYS_DATA = SYS_HOME + File.separator + "data" + File.separator; + public static String SYS_DATA_TEMP = SYS_DATA + File.separator + "temp" + File.separator; + public static String SYS_DATA_RESULT = SYS_DATA + File.separator + "RESULT" + File.separator; + public static String COLLECT_TYPE_CM = "EMS_RESOUCE"; + public static String COLLECT_TYPE_PM = "EMS_PERFORMANCE"; + public static String COLLECT_TYPE_ALARM = "EMS_ALARM"; + public static String ENCODING_UTF8 = "UTF-8"; + public static String ENCODING_GBK = "GBK"; + } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/AFtpRemoteFile.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/AFtpRemoteFile.java index 8692687..beb36a7 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/AFtpRemoteFile.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/AFtpRemoteFile.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,27 +18,27 @@ package org.onap.vfc.nfvo.emsdriver.commons.ftp; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; -public class AFtpRemoteFile implements RemoteFile{ - protected FTPClient ftpClient = null; - protected FTPFile ftpFile = null; - protected String currDir = null; - - public AFtpRemoteFile(FTPFile rfile, FTPClient ftpClient, String currDir){ - this.ftpClient = ftpClient; - this.ftpFile = rfile; - this.currDir = currDir; - } - - - public String getFileName() { - return ftpFile.getName(); - } - - public String getAbsFileName() { - return currDir.concat(getFileName()); - } - - public boolean isDirectory() { - return ftpFile.isDirectory(); - } +public class AFtpRemoteFile implements RemoteFile { + protected FTPClient ftpClient = null; + protected FTPFile ftpFile = null; + protected String currDir = null; + + public AFtpRemoteFile(FTPFile rfile, FTPClient ftpClient, String currDir) { + this.ftpClient = ftpClient; + this.ftpFile = rfile; + this.currDir = currDir; + } + + + public String getFileName() { + return ftpFile.getName(); + } + + public String getAbsFileName() { + return currDir.concat(getFileName()); + } + + public boolean isDirectory() { + return ftpFile.isDirectory(); + } }
\ No newline at end of file diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/FTPInterface.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/FTPInterface.java index ceca30f..660c906 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/FTPInterface.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/FTPInterface.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,32 +18,34 @@ package org.onap.vfc.nfvo.emsdriver.commons.ftp; import java.io.IOException; public interface FTPInterface { - - /** + + /** * login ftp - * @throws Exception - */ - public void login(String host, int port, String user, String pwd, String encode,boolean isPassiveMode, int timeout) throws Exception; - - /** + * + * @throws Exception + */ + public void login(String host, int port, String user, String pwd, String encode, boolean isPassiveMode, int timeout) throws Exception; + + /** * close ftp - */ - public void logout(); - - /** + */ + public void logout(); + + /** * download file - * @return - */ - public boolean downloadFile(String remoteFile,String localFile); - + * + * @return + */ + public boolean downloadFile(String remoteFile, String localFile); + public boolean chdir(String dir); - + public RemoteFile[] list(); - + public String pwd() throws IOException; - + // public RemoteFile[] list(String dir); - + // public boolean store(String localFile,String remoteFile); - + } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/FTPSrv.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/FTPSrv.java index 4f987a5..1e82b78 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/FTPSrv.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/FTPSrv.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,159 +15,156 @@ */ package org.onap.vfc.nfvo.emsdriver.commons.ftp; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.net.ftp.*; +import org.onap.vfc.nfvo.emsdriver.commons.utils.StringUtil; + import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.TimeZone; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.net.ftp.FTP; -import org.apache.commons.net.ftp.FTPClient; -import org.apache.commons.net.ftp.FTPClientConfig; -import org.apache.commons.net.ftp.FTPFile; -import org.apache.commons.net.ftp.FTPReply; -import org.onap.vfc.nfvo.emsdriver.commons.utils.StringUtil; +public class FTPSrv implements FTPInterface { + private Log log = LogFactory.getLog(FTPSrv.class); + private FTPClient ftpClient = null; -public class FTPSrv implements FTPInterface{ - private Log log = LogFactory.getLog(FTPSrv.class); - private FTPClient ftpClient = null; - - - /** - * login FTP - * @param host - * @param port - * @param user - * @param pwd - * @param encode - * @param timeout - * @throws Exception - */ - public void login(String host, int port, String user, String pwd, String encode, boolean isPassiveMode,int timeout) throws Exception { - ftpClient = new FTPClient(); - - FTPClientConfig ftpClientConfig = new FTPClientConfig(); - ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID()); - this.ftpClient.setControlEncoding("GBK"); - this.ftpClient.configure(ftpClientConfig); + + /** + * login FTP + * + * @param host + * @param port + * @param user + * @param pwd + * @param encode + * @param timeout + * @throws Exception + */ + public void login(String host, int port, String user, String pwd, String encode, boolean isPassiveMode, int timeout) throws Exception { + ftpClient = new FTPClient(); + + FTPClientConfig ftpClientConfig = new FTPClientConfig(); + ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID()); + this.ftpClient.setControlEncoding("GBK"); + this.ftpClient.configure(ftpClientConfig); // ftpClient.setParserFactory(new ExtendsDefaultFTPFileEntryParserFactory()); - - if(encode!=null && encode.length()>0){ - ftpClient.setControlEncoding(encode); - } - - ftpClient.connect(host, port); - int reply = this.ftpClient.getReplyCode(); - if (!FTPReply.isPositiveCompletion(reply)) { - this.ftpClient.disconnect(); - return ; - } - - if(!ftpClient.login(user, pwd)){ - throw new Exception("login["+host+"],port["+port+"] fail, please check user and password"); - } - if(isPassiveMode){ - ftpClient.enterLocalPassiveMode(); - }else{ - ftpClient.enterLocalActiveMode(); - } - ftpClient.setFileType(FTP.BINARY_FILE_TYPE); - this.ftpClient.setBufferSize(1024 * 2); - this.ftpClient.setDataTimeout(3*60 * 1000); - try{ - this.ftpClient.setSoTimeout(timeout); - }catch(Exception e){ - e.printStackTrace(); - } - } - - - /** - * logout - */ - public void logout(){ - if(ftpClient != null){ - try { - ftpClient.logout(); - ftpClient.disconnect(); - }catch(Exception e){ - } - ftpClient = null; - } - } - - - public boolean chdir(String dir) { - boolean sucess = false; - try { - if(ftpClient.changeWorkingDirectory(dir)){ - sucess = true; - }else{ - sucess = false; - } - } catch (IOException e) { - log.error("chdir dir ="+dir+" is error"+StringUtil.getStackTrace(e)); - sucess = false; - } - - return sucess; - } - - - public boolean downloadFile(String remoteFile, String localFile) { - boolean sucess = false; - BufferedOutputStream toLfileOutput = null; - try { - toLfileOutput = new BufferedOutputStream(new FileOutputStream(localFile)); - ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); - if (ftpClient.retrieveFile(remoteFile, toLfileOutput)){ - sucess = true; - }else{ - sucess = false; - } - } catch (Exception ioe) { - sucess = false; - log.error("downloadFile remoteFile ="+remoteFile +" is fail ",ioe); - } finally { - if (toLfileOutput != null) - try { - toLfileOutput.close(); - } catch (IOException e) { - } - } - - return sucess; - } - - - public RemoteFile[] list() { - AFtpRemoteFile[] ftpRemoteFiles = null; - String currdir = null; - try { - currdir = ftpClient.printWorkingDirectory(); - if (currdir.endsWith("/") == false) { - currdir = currdir + "/"; - } - FTPFile[] rfileList = null; - rfileList = ftpClient.listFiles(currdir); - ftpRemoteFiles = new AFtpRemoteFile[rfileList.length]; - for (int i=0; i<rfileList.length; i++){ - ftpRemoteFiles[i] = new AFtpRemoteFile(rfileList[i], ftpClient, currdir); - } - } catch (IOException e) { - log.error("Ftp list currdir = "+currdir+" is fail "+StringUtil.getStackTrace(e)); - } - return ftpRemoteFiles; - } - - - @Override - public String pwd() throws IOException { - String returnValue = ftpClient.printWorkingDirectory(); - return returnValue; - } + + if (encode != null && encode.length() > 0) { + ftpClient.setControlEncoding(encode); + } + + ftpClient.connect(host, port); + int reply = this.ftpClient.getReplyCode(); + if (!FTPReply.isPositiveCompletion(reply)) { + this.ftpClient.disconnect(); + return; + } + + if (!ftpClient.login(user, pwd)) { + throw new Exception("login[" + host + "],port[" + port + "] fail, please check user and password"); + } + if (isPassiveMode) { + ftpClient.enterLocalPassiveMode(); + } else { + ftpClient.enterLocalActiveMode(); + } + ftpClient.setFileType(FTP.BINARY_FILE_TYPE); + this.ftpClient.setBufferSize(1024 * 2); + this.ftpClient.setDataTimeout(3 * 60 * 1000); + try { + this.ftpClient.setSoTimeout(timeout); + } catch (Exception e) { + e.printStackTrace(); + } + } + + + /** + * logout + */ + public void logout() { + if (ftpClient != null) { + try { + ftpClient.logout(); + ftpClient.disconnect(); + } catch (Exception e) { + } + ftpClient = null; + } + } + + + public boolean chdir(String dir) { + boolean sucess = false; + try { + if (ftpClient.changeWorkingDirectory(dir)) { + sucess = true; + } else { + sucess = false; + } + } catch (IOException e) { + log.error("chdir dir =" + dir + " is error" + StringUtil.getStackTrace(e)); + sucess = false; + } + + return sucess; + } + + + public boolean downloadFile(String remoteFile, String localFile) { + boolean sucess = false; + BufferedOutputStream toLfileOutput = null; + try { + toLfileOutput = new BufferedOutputStream(new FileOutputStream(localFile)); + ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); + if (ftpClient.retrieveFile(remoteFile, toLfileOutput)) { + sucess = true; + } else { + sucess = false; + } + } catch (Exception ioe) { + sucess = false; + log.error("downloadFile remoteFile =" + remoteFile + " is fail ", ioe); + } finally { + if (toLfileOutput != null) + try { + toLfileOutput.close(); + } catch (IOException e) { + } + } + + return sucess; + } + + + public RemoteFile[] list() { + AFtpRemoteFile[] ftpRemoteFiles = null; + String currdir = null; + try { + currdir = ftpClient.printWorkingDirectory(); + if (currdir.endsWith("/") == false) { + currdir = currdir + "/"; + } + FTPFile[] rfileList = null; + rfileList = ftpClient.listFiles(currdir); + ftpRemoteFiles = new AFtpRemoteFile[rfileList.length]; + for (int i = 0; i < rfileList.length; i++) { + ftpRemoteFiles[i] = new AFtpRemoteFile(rfileList[i], ftpClient, currdir); + } + } catch (IOException e) { + log.error("Ftp list currdir = " + currdir + " is fail " + StringUtil.getStackTrace(e)); + } + return ftpRemoteFiles; + } + + + @Override + public String pwd() throws IOException { + String returnValue = ftpClient.printWorkingDirectory(); + return returnValue; + } // public boolean store(String localFile, String remoteFile) { // @@ -194,6 +191,6 @@ public class FTPSrv implements FTPInterface{ // } // return sucess; // } - + } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/RemoteFile.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/RemoteFile.java index 636c3ed..7a99571 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/RemoteFile.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/RemoteFile.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -17,9 +17,9 @@ package org.onap.vfc.nfvo.emsdriver.commons.ftp; public interface RemoteFile { - public String getFileName(); - - public String getAbsFileName(); - - public boolean isDirectory(); + public String getFileName(); + + public String getAbsFileName(); + + public boolean isDirectory(); } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/model/CollectMsg.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/model/CollectMsg.java index fed0294..3e274e3 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/model/CollectMsg.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/model/CollectMsg.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,61 +16,60 @@ package org.onap.vfc.nfvo.emsdriver.commons.model; public class CollectMsg { - - private long id; - - private String emsName; - - private String type; - /** - * @return the id - */ - public long getId() { - return id; - } + private long id; - /** - * @param id the id to set - */ - public void setId(long id) { - this.id = id; - } + private String emsName; - /** - * @return the emsName - */ - public String getEmsName() { - return emsName; - } + private String type; - /** - * @param emsName the emsName to set - */ - public void setEmsName(String emsName) { - this.emsName = emsName; - } + /** + * @return the id + */ + public long getId() { + return id; + } - /** - * @return the type - */ - public String getType() { - return type; - } + /** + * @param id the id to set + */ + public void setId(long id) { + this.id = id; + } - /** - * @param type the type to set - */ - public void setType(String type) { - this.type = type; - } + /** + * @return the emsName + */ + public String getEmsName() { + return emsName; + } + + /** + * @param emsName the emsName to set + */ + public void setEmsName(String emsName) { + this.emsName = emsName; + } + + /** + * @return the type + */ + public String getType() { + return type; + } + + /** + * @param type the type to set + */ + public void setType(String type) { + this.type = type; + } + + @Override + public String toString() { + return "CollectMsg [id=" + id + ", emsName=" + emsName + ", type=" + + type + "]"; + } - @Override - public String toString() { - return "CollectMsg [id=" + id + ", emsName=" + emsName + ", type=" - + type + "]"; - } - - } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/model/CollectVo.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/model/CollectVo.java index 75aaa59..c79d3bf 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/model/CollectVo.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/model/CollectVo.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -17,247 +17,245 @@ package org.onap.vfc.nfvo.emsdriver.commons.model; /** * @author boco - * */ public class CollectVo { - - private String emsName; - - private String type; - - private String crontab; - - private String IP; - - private String port; - - private String user; - - private String password; - - private String remotepath; - - private String match; - - private String passive; - - private String ftptype; - - private String granularity; - - private boolean iscollect = false; - - private String read_timeout; - - - - /** - * @return the iscollect - */ - public boolean isIscollect() { - return iscollect; - } - - /** - * @param iscollect the iscollect to set - */ - public void setIscollect(boolean iscollect) { - this.iscollect = iscollect; - } - - /** - * @return the type - */ - public String getType() { - return type; - } - - /** - * @param type the type to set - */ - public void setType(String type) { - this.type = type; - } - - /** - * @return the crontab - */ - public String getCrontab() { - return crontab; - } - - /** - * @param crontab the crontab to set - */ - public void setCrontab(String crontab) { - this.crontab = crontab; - } - - /** - * @return the iP - */ - public String getIP() { - return IP; - } - - /** - * @param ip the iP to set - */ - public void setIP(String ip) { - IP = ip; - } - - /** - * @return the port - */ - public String getPort() { - return port; - } - - /** - * @param port the port to set - */ - public void setPort(String port) { - this.port = port; - } - - /** - * @return the user - */ - public String getUser() { - return user; - } - - /** - * @param user the user to set - */ - public void setUser(String user) { - this.user = user; - } - - /** - * @return the password - */ - public String getPassword() { - return password; - } - - /** - * @param password the password to set - */ - public void setPassword(String password) { - this.password = password; - } - - /** - * @return the remotepath - */ - public String getRemotepath() { - return remotepath; - } - - /** - * @param remotepath the remotepath to set - */ - public void setRemotepath(String remotepath) { - this.remotepath = remotepath; - } - - /** - * @return the match - */ - public String getMatch() { - return match; - } - - /** - * @param match the match to set - */ - public void setMatch(String match) { - this.match = match; - } - - /** - * @return the passive - */ - public String getPassive() { - return passive; - } - - /** - * @param passive the passive to set - */ - public void setPassive(String passive) { - this.passive = passive; - } - - /** - * @return the ftptype - */ - public String getFtptype() { - return ftptype; - } - - /** - * @param ftptype the ftptype to set - */ - public void setFtptype(String ftptype) { - this.ftptype = ftptype; - } - - /** - * @return the granularity - */ - public String getGranularity() { - return granularity; - } - - /** - * @param granularity the granularity to set - */ - public void setGranularity(String granularity) { - this.granularity = granularity; - } - - - @Override - public String toString() { - return "CollectVo [emsName=" + emsName + ", type=" + type - + ", crontab=" + crontab + ", IP=" + IP + ", port=" + port - + ", user=" + user + ", password=" + password + ", remotepath=" - + remotepath + ", match=" + match + ", passive=" + passive - + ", ftptype=" + ftptype + ", granularity=" + granularity - + ", iscollect=" + iscollect + ", read_timeout=" + read_timeout - + "]"; - } - - /** - * @return the emsName - */ - public String getEmsName() { - return emsName; - } - - /** - * @param emsName the emsName to set - */ - public void setEmsName(String emsName) { - this.emsName = emsName; - } - - /** - * @return the read_timeout - */ - public String getRead_timeout() { - return read_timeout; - } - - /** - * @param read_timeout the read_timeout to set - */ - public void setRead_timeout(String read_timeout) { - this.read_timeout = read_timeout; - } + + private String emsName; + + private String type; + + private String crontab; + + private String IP; + + private String port; + + private String user; + + private String password; + + private String remotepath; + + private String match; + + private String passive; + + private String ftptype; + + private String granularity; + + private boolean iscollect = false; + + private String read_timeout; + + + /** + * @return the iscollect + */ + public boolean isIscollect() { + return iscollect; + } + + /** + * @param iscollect the iscollect to set + */ + public void setIscollect(boolean iscollect) { + this.iscollect = iscollect; + } + + /** + * @return the type + */ + public String getType() { + return type; + } + + /** + * @param type the type to set + */ + public void setType(String type) { + this.type = type; + } + + /** + * @return the crontab + */ + public String getCrontab() { + return crontab; + } + + /** + * @param crontab the crontab to set + */ + public void setCrontab(String crontab) { + this.crontab = crontab; + } + + /** + * @return the iP + */ + public String getIP() { + return IP; + } + + /** + * @param ip the iP to set + */ + public void setIP(String ip) { + IP = ip; + } + + /** + * @return the port + */ + public String getPort() { + return port; + } + + /** + * @param port the port to set + */ + public void setPort(String port) { + this.port = port; + } + + /** + * @return the user + */ + public String getUser() { + return user; + } + + /** + * @param user the user to set + */ + public void setUser(String user) { + this.user = user; + } + + /** + * @return the password + */ + public String getPassword() { + return password; + } + + /** + * @param password the password to set + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * @return the remotepath + */ + public String getRemotepath() { + return remotepath; + } + + /** + * @param remotepath the remotepath to set + */ + public void setRemotepath(String remotepath) { + this.remotepath = remotepath; + } + + /** + * @return the match + */ + public String getMatch() { + return match; + } + + /** + * @param match the match to set + */ + public void setMatch(String match) { + this.match = match; + } + + /** + * @return the passive + */ + public String getPassive() { + return passive; + } + + /** + * @param passive the passive to set + */ + public void setPassive(String passive) { + this.passive = passive; + } + + /** + * @return the ftptype + */ + public String getFtptype() { + return ftptype; + } + + /** + * @param ftptype the ftptype to set + */ + public void setFtptype(String ftptype) { + this.ftptype = ftptype; + } + + /** + * @return the granularity + */ + public String getGranularity() { + return granularity; + } + + /** + * @param granularity the granularity to set + */ + public void setGranularity(String granularity) { + this.granularity = granularity; + } + + + @Override + public String toString() { + return "CollectVo [emsName=" + emsName + ", type=" + type + + ", crontab=" + crontab + ", IP=" + IP + ", port=" + port + + ", user=" + user + ", password=" + password + ", remotepath=" + + remotepath + ", match=" + match + ", passive=" + passive + + ", ftptype=" + ftptype + ", granularity=" + granularity + + ", iscollect=" + iscollect + ", read_timeout=" + read_timeout + + "]"; + } + + /** + * @return the emsName + */ + public String getEmsName() { + return emsName; + } + + /** + * @param emsName the emsName to set + */ + public void setEmsName(String emsName) { + this.emsName = emsName; + } + + /** + * @return the read_timeout + */ + public String getRead_timeout() { + return read_timeout; + } + + /** + * @param read_timeout the read_timeout to set + */ + public void setRead_timeout(String read_timeout) { + this.read_timeout = read_timeout; + } } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/model/CrontabVo.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/model/CrontabVo.java index 66fbede..1a925fe 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/model/CrontabVo.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/model/CrontabVo.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -17,112 +17,109 @@ package org.onap.vfc.nfvo.emsdriver.commons.model; /** * @author boco - * */ public class CrontabVo { - - private String type; - - private String crontab; - private String match; - private String granularity; - - private boolean iscollect = false; - - private String read_timeout; - - /** - * @return the type - */ - public String getType() { - return type; - } - - /** - * @param type the type to set - */ - public void setType(String type) { - this.type = type; - } - - /** - * @return the crontab - */ - public String getCrontab() { - return crontab; - } - - /** - * @param crontab the crontab to set - */ - public void setCrontab(String crontab) { - this.crontab = crontab; - } - - /** - * @return the match - */ - public String getMatch() { - return match; - } - - /** - * @param match the match to set - */ - public void setMatch(String match) { - this.match = match; - } - - /** - * @return the granularity - */ - public String getGranularity() { - return granularity; - } - - /** - * @param granularity the granularity to set - */ - public void setGranularity(String granularity) { - this.granularity = granularity; - } - - /** - * @return the iscollect - */ - public boolean isIscollect() { - return iscollect; - } - - /** - * @param iscollect the iscollect to set - */ - public void setIscollect(boolean iscollect) { - this.iscollect = iscollect; - } - - /** - * @return the read_timeout - */ - public String getRead_timeout() { - return read_timeout; - } - - /** - * @param read_timeout the read_timeout to set - */ - public void setRead_timeout(String read_timeout) { - this.read_timeout = read_timeout; - } - - @Override - public String toString() { - return "CrontabVo [type=" + type + ", crontab=" + crontab + ", match=" - + match + ", granularity=" + granularity + ", iscollect=" - + iscollect + ", read_timeout=" + read_timeout + "]"; - } - - - - + + private String type; + + private String crontab; + private String match; + private String granularity; + + private boolean iscollect = false; + + private String read_timeout; + + /** + * @return the type + */ + public String getType() { + return type; + } + + /** + * @param type the type to set + */ + public void setType(String type) { + this.type = type; + } + + /** + * @return the crontab + */ + public String getCrontab() { + return crontab; + } + + /** + * @param crontab the crontab to set + */ + public void setCrontab(String crontab) { + this.crontab = crontab; + } + + /** + * @return the match + */ + public String getMatch() { + return match; + } + + /** + * @param match the match to set + */ + public void setMatch(String match) { + this.match = match; + } + + /** + * @return the granularity + */ + public String getGranularity() { + return granularity; + } + + /** + * @param granularity the granularity to set + */ + public void setGranularity(String granularity) { + this.granularity = granularity; + } + + /** + * @return the iscollect + */ + public boolean isIscollect() { + return iscollect; + } + + /** + * @param iscollect the iscollect to set + */ + public void setIscollect(boolean iscollect) { + this.iscollect = iscollect; + } + + /** + * @return the read_timeout + */ + public String getRead_timeout() { + return read_timeout; + } + + /** + * @param read_timeout the read_timeout to set + */ + public void setRead_timeout(String read_timeout) { + this.read_timeout = read_timeout; + } + + @Override + public String toString() { + return "CrontabVo [type=" + type + ", crontab=" + crontab + ", match=" + + match + ", granularity=" + granularity + ", iscollect=" + + iscollect + ", read_timeout=" + read_timeout + "]"; + } + + } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/model/EMSInfo.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/model/EMSInfo.java index 1a2b5d4..2cc2682 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/model/EMSInfo.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/model/EMSInfo.java @@ -1,12 +1,12 @@ /** * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd - * + * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * <p> + * http://www.apache.org/licenses/LICENSE-2.0 + * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,38 +19,38 @@ import java.util.HashMap; import java.util.Map; public class EMSInfo { - - private String name; - - - private Map<String,CollectVo> collectMap = new HashMap<String,CollectVo>(); - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name the name to set - */ - public void setName(String name) { - this.name = name; - } - - public CollectVo getCollectVoByType(String type){ - CollectVo collectVo = this.collectMap.get(type); - return collectVo; - } - - public void putCollectMap(String type,CollectVo collectVo) { - - this.collectMap.put(type, collectVo); - } - - @Override - public String toString() { - return "EMSInfo [name=" + name + ", collectMap=" + collectMap + "]"; - } + + private String name; + + + private Map<String, CollectVo> collectMap = new HashMap<String, CollectVo>(); + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + + public CollectVo getCollectVoByType(String type) { + CollectVo collectVo = this.collectMap.get(type); + return collectVo; + } + + public void putCollectMap(String type, CollectVo collectVo) { + + this.collectMap.put(type, collectVo); + } + + @Override + public String toString() { + return "EMSInfo [name=" + name + ", collectMap=" + collectMap + "]"; + } } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/DateUtil.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/DateUtil.java index 7cfd8fe..2613759 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/DateUtil.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/DateUtil.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -21,64 +21,64 @@ import java.util.Calendar; import java.util.Date; public class DateUtil { - - - public static long[] getScanScope(Date fireTime, long collectPeriod) { - Calendar fire = Calendar.getInstance(); - long start = 0L; - long end = 0L; - fire.setTime(fireTime); - fire.set(Calendar.SECOND,0); - fire.set(Calendar.MILLISECOND, 0); - - if (collectPeriod < 3600) {//minute - long minite = fire.get(Calendar.MINUTE); - long collectMinite = (int)collectPeriod/60; - long s = minite%collectMinite; - end = fire.getTimeInMillis() - s*60*1000; - start = end - collectPeriod * 1000; - }else if (collectPeriod == 3600) { - fire.set(Calendar.MINUTE, 0); - end = fire.getTimeInMillis(); - start = end - collectPeriod * 1000; - }else if (collectPeriod == 24*60*60){ //day - fire.set(Calendar.HOUR_OF_DAY, 0); - fire.set(Calendar.MINUTE, 0); - end = fire.getTimeInMillis(); - start = end - collectPeriod * 1000; - }else{ - - if (collectPeriod>0) { - end = fire.getTimeInMillis()-(fire.getTimeInMillis()+8*60*60*1000)%(collectPeriod*1000); - }else { - return null; - } - start = end - collectPeriod * 1000; - } - - return new long[] {start,end}; - } - - public static String TimeString(String timeString){ - if(timeString == null){ - return ""; - }else{ - timeString = timeString.replace("T", " "); - if(timeString.contains("+")){ - timeString = timeString.substring(0, timeString.indexOf("+")); - } - return timeString; - } - } - - public static String addTime(String srcTimeString,String period) throws ParseException{ - String finaldate = TimeString(srcTimeString); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - Date date = sdf.parse(finaldate); - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - calendar.add(Calendar.MINUTE, Integer.valueOf(period)); - return sdf.format(calendar.getTime()); - } + + + public static long[] getScanScope(Date fireTime, long collectPeriod) { + Calendar fire = Calendar.getInstance(); + long start = 0L; + long end = 0L; + fire.setTime(fireTime); + fire.set(Calendar.SECOND, 0); + fire.set(Calendar.MILLISECOND, 0); + + if (collectPeriod < 3600) {//minute + long minite = fire.get(Calendar.MINUTE); + long collectMinite = (int) collectPeriod / 60; + long s = minite % collectMinite; + end = fire.getTimeInMillis() - s * 60 * 1000; + start = end - collectPeriod * 1000; + } else if (collectPeriod == 3600) { + fire.set(Calendar.MINUTE, 0); + end = fire.getTimeInMillis(); + start = end - collectPeriod * 1000; + } else if (collectPeriod == 24 * 60 * 60) { //day + fire.set(Calendar.HOUR_OF_DAY, 0); + fire.set(Calendar.MINUTE, 0); + end = fire.getTimeInMillis(); + start = end - collectPeriod * 1000; + } else { + + if (collectPeriod > 0) { + end = fire.getTimeInMillis() - (fire.getTimeInMillis() + 8 * 60 * 60 * 1000) % (collectPeriod * 1000); + } else { + return null; + } + start = end - collectPeriod * 1000; + } + + return new long[]{start, end}; + } + + public static String TimeString(String timeString) { + if (timeString == null) { + return ""; + } else { + timeString = timeString.replace("T", " "); + if (timeString.contains("+")) { + timeString = timeString.substring(0, timeString.indexOf("+")); + } + return timeString; + } + } + + public static String addTime(String srcTimeString, String period) throws ParseException { + String finaldate = TimeString(srcTimeString); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date date = sdf.parse(finaldate); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.add(Calendar.MINUTE, Integer.valueOf(period)); + return sdf.format(calendar.getTime()); + } } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/DriverThread.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/DriverThread.java index fda2a4f..9ed1e6b 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/DriverThread.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/DriverThread.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,74 +18,77 @@ package org.onap.vfc.nfvo.emsdriver.commons.utils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -public abstract class DriverThread implements Runnable{ - protected Log log = LogFactory.getLog(this.getClass()); - private String name = null; - private Thread t = null; - private boolean run = false; - private boolean end = false; - - public synchronized void start() { - t = new Thread(this); - t.start(); - } - public void setName(String name) { - this.name = name; - if (t != null) - t.setName(name); - } - - public String getName() { - if (t != null) - return t.getName(); - return name; - } - - public abstract void dispose(); - - final public void run() { - t = Thread.currentThread(); - if (name != null) - t.setName(name); - - try { - dispose(); - } catch (Throwable e) { - e.printStackTrace(); - } - this.setEnd(true); - - } - - public boolean stop(){ - - this.setRun(false); - while(!isEnd()){ - try { - Thread.sleep(1); - } catch (InterruptedException e) { - log.error("InterruptedException :"+StringUtil.getStackTrace(e)); - } - } - return end; - } - - public void interrupt() { - if (t != null) - t.interrupt(); - } - - public void setRun(boolean run) { - this.run = run; - } - - public boolean isRun() { - return run; - } - public void setEnd(boolean end) { - this.end = end; - } - public boolean isEnd() { - return end; - } +public abstract class DriverThread implements Runnable { + protected Log log = LogFactory.getLog(this.getClass()); + private String name = null; + private Thread t = null; + private boolean run = false; + private boolean end = false; + + public synchronized void start() { + t = new Thread(this); + t.start(); + } + + public String getName() { + if (t != null) + return t.getName(); + return name; + } + + public void setName(String name) { + this.name = name; + if (t != null) + t.setName(name); + } + + public abstract void dispose(); + + final public void run() { + t = Thread.currentThread(); + if (name != null) + t.setName(name); + + try { + dispose(); + } catch (Throwable e) { + e.printStackTrace(); + } + this.setEnd(true); + + } + + public boolean stop() { + + this.setRun(false); + while (!isEnd()) { + try { + Thread.sleep(1); + } catch (InterruptedException e) { + log.error("InterruptedException :" + StringUtil.getStackTrace(e)); + } + } + return end; + } + + public void interrupt() { + if (t != null) + t.interrupt(); + } + + public boolean isRun() { + return run; + } + + public void setRun(boolean run) { + this.run = run; + } + + public boolean isEnd() { + return end; + } + + public void setEnd(boolean end) { + this.end = end; + } } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/Gunzip.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/Gunzip.java index ab824ec..bd6b1d1 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/Gunzip.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/Gunzip.java @@ -1,12 +1,12 @@ /** * Copyright 2017 CMCC Technologies Co., Ltd - * + * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * <p> + * http://www.apache.org/licenses/LICENSE-2.0 + * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -15,80 +15,75 @@ */ package org.onap.vfc.nfvo.emsdriver.commons.utils; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; +import java.io.*; import java.util.zip.GZIPInputStream; public class Gunzip { - - /** - * - */ - public void unCompress(String gzFileName, String toFile) - throws IOException { - GZIPInputStream gzIn = null; - FileOutputStream fileOutput = null; - FileInputStream gzInput = new FileInputStream(gzFileName); - try { - gzIn = new GZIPInputStream(gzInput); - File tofile = new File(toFile); - enable(tofile); - fileOutput = new FileOutputStream(tofile, false); - - moveBytes(gzIn, fileOutput, -1, -1, 1024); - } finally{ - if(gzIn != null){ - gzIn.close(); - } - if(fileOutput != null){ - fileOutput.close(); - } - - } - - - } - - private void enable(File tofile) throws IOException { - if (!tofile.exists()) { - String parentPath = tofile.getParent(); - if (parentPath != null) - new File(parentPath).mkdirs(); - tofile.createNewFile(); - } - } - - - public long moveBytes(InputStream input, OutputStream output, long off, long len, int bufsize) - throws IOException { - if (off > 0) - input.skip(off); - - long totalNum = 0; - byte[] buf = new byte[bufsize]; - - while (true) { - if (len>0 && (len-totalNum)<=0) - break; - - else if (len>0 && bufsize>(len-totalNum)) - bufsize = (int)(len-totalNum); - - int readNum = input.read(buf, 0, bufsize); - if (readNum <= 0) - break; - - output.write(buf, 0, readNum); - totalNum += readNum; - } - buf = null; - return totalNum; - } - - + + /** + * + */ + public void unCompress(String gzFileName, String toFile) + throws IOException { + GZIPInputStream gzIn = null; + FileOutputStream fileOutput = null; + FileInputStream gzInput = new FileInputStream(gzFileName); + try { + gzIn = new GZIPInputStream(gzInput); + File tofile = new File(toFile); + enable(tofile); + fileOutput = new FileOutputStream(tofile, false); + + moveBytes(gzIn, fileOutput, -1, -1, 1024); + } finally { + if (gzIn != null) { + gzIn.close(); + } + if (fileOutput != null) { + fileOutput.close(); + } + + } + + + } + + private void enable(File tofile) throws IOException { + if (!tofile.exists()) { + String parentPath = tofile.getParent(); + if (parentPath != null) + new File(parentPath).mkdirs(); + tofile.createNewFile(); + } + } + + + public long moveBytes(InputStream input, OutputStream output, long off, long len, int bufsize) + throws IOException { + if (off > 0) + input.skip(off); + + long totalNum = 0; + byte[] buf = new byte[bufsize]; + + while (true) { + if (len > 0 && (len - totalNum) <= 0) + break; + + else if (len > 0 && bufsize > (len - totalNum)) + bufsize = (int) (len - totalNum); + + int readNum = input.read(buf, 0, bufsize); + if (readNum <= 0) + break; + + output.write(buf, 0, readNum); + totalNum += readNum; + } + buf = null; + return totalNum; + } + + }
\ No newline at end of file diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/StringUtil.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/StringUtil.java index b8089ec..e10ab20 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/StringUtil.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/StringUtil.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -21,42 +21,42 @@ import java.io.StringWriter; public class StringUtil { - public static String getStackTrace(Throwable t){ - - StringWriter sw = null; - PrintWriter pw = null; - try { - sw = new StringWriter(); - pw = new PrintWriter(sw); - t.printStackTrace(pw); - pw.flush(); - sw.flush(); - return sw.getBuffer().toString(); - } catch (Exception e) { - - }finally{ - try { - if(pw != null) pw.close(); - if(sw != null) sw.close(); - } catch (Exception e2) { - - } - } - return null; - } - - public static String addSlash(String dirName) { - if (dirName.endsWith(File.separator)) - return dirName; - return dirName + File.separator; - } - - public static boolean isBank(String str){ - - if(str == null || str.trim().length() == 0){ - - return true; - } - return false; - } + public static String getStackTrace(Throwable t) { + + StringWriter sw = null; + PrintWriter pw = null; + try { + sw = new StringWriter(); + pw = new PrintWriter(sw); + t.printStackTrace(pw); + pw.flush(); + sw.flush(); + return sw.getBuffer().toString(); + } catch (Exception e) { + + } finally { + try { + if (pw != null) pw.close(); + if (sw != null) sw.close(); + } catch (Exception e2) { + + } + } + return null; + } + + public static String addSlash(String dirName) { + if (dirName.endsWith(File.separator)) + return dirName; + return dirName + File.separator; + } + + public static boolean isBank(String str) { + + if (str == null || str.trim().length() == 0) { + + return true; + } + return false; + } } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/UnZip.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/UnZip.java index c8aa6be..b065083 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/UnZip.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/UnZip.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,80 +15,80 @@ */ package org.onap.vfc.nfvo.emsdriver.commons.utils; +import org.apache.tools.zip.ZipEntry; +import org.apache.tools.zip.ZipFile; + import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; -import org.apache.tools.zip.ZipEntry; -import org.apache.tools.zip.ZipFile; - public class UnZip { - protected String deCompressPath = null; - protected String zipFilePath = null; - - /** - * - */ - public UnZip(String zipFilePath, String toPath) throws IOException { - File zipFile = new File( - new File(zipFilePath).getAbsolutePath()); - if (!zipFile.isFile()) - throw new IOException("not found file '"+zipFilePath+"'"); - - this.deCompressPath = toPath; - this.zipFilePath = zipFile.getAbsolutePath(); + protected String deCompressPath = null; + protected String zipFilePath = null; + + /** + * + */ + public UnZip(String zipFilePath, String toPath) throws IOException { + File zipFile = new File( + new File(zipFilePath).getAbsolutePath()); + if (!zipFile.isFile()) + throw new IOException("not found file '" + zipFilePath + "'"); + + this.deCompressPath = toPath; + this.zipFilePath = zipFile.getAbsolutePath(); + + if (deCompressPath == null) + deCompressPath = zipFile.getParent() + File.separator; + + else if (deCompressPath.charAt(deCompressPath.length() - 1) != '/') + deCompressPath = deCompressPath + File.separator; + } - if (deCompressPath == null) - deCompressPath = zipFile.getParent() + File.separator; - - else if (deCompressPath.charAt(deCompressPath.length()-1) != '/') - deCompressPath = deCompressPath + File.separator; - } + /** + * + */ + public void deCompress() throws IOException { + ZipFile zipFile = new ZipFile(zipFilePath); + try { + Enumeration<ZipEntry> e = zipFile.getEntries(); + for (ZipEntry entry; e.hasMoreElements(); ) { + if (!(entry = e.nextElement()).isDirectory()) { + String toPath = new StringBuffer( + deCompressPath).append(entry.getName()).toString(); + toPath = toPath.replace("\\", File.separator); + deCompressFile(zipFile.getInputStream(entry), toPath); + } + } + } catch (IOException e) { + throw e; + } finally { + zipFile.close(); + } + } - /** - * - */ - public void deCompress() throws IOException { - ZipFile zipFile = new ZipFile(zipFilePath); - try{ - Enumeration<ZipEntry> e = zipFile.getEntries(); - for (ZipEntry entry; e.hasMoreElements(); ) { - if (!(entry=e.nextElement()).isDirectory()) { - String toPath = new StringBuffer( - deCompressPath).append(entry.getName()).toString(); - toPath = toPath.replace("\\", File.separator); - deCompressFile(zipFile.getInputStream(entry), toPath); - } - } - }catch(IOException e){ - throw e; - }finally{ - zipFile.close(); - } - } - - /** - * - */ - protected void deCompressFile(InputStream input, String toPath) - throws IOException { - byte byteBuf[] = new byte[2048]; - String path = new File(toPath).getParent(); - if(!new File(path).exists()){ - new File(path).mkdirs(); - } - FileOutputStream output = new FileOutputStream(toPath, false); - try{ - for (int count=0; (count=input.read(byteBuf,0,byteBuf.length))!=-1;) - output.write(byteBuf, 0, count); - }catch(IOException e){ - throw e; - }finally{ - output.close(); - input.close(); - } - } + /** + * + */ + protected void deCompressFile(InputStream input, String toPath) + throws IOException { + byte byteBuf[] = new byte[2048]; + String path = new File(toPath).getParent(); + if (!new File(path).exists()) { + new File(path).mkdirs(); + } + FileOutputStream output = new FileOutputStream(toPath, false); + try { + for (int count = 0; (count = input.read(byteBuf, 0, byteBuf.length)) != -1; ) + output.write(byteBuf, 0, count); + } catch (IOException e) { + throw e; + } finally { + output.close(); + input.close(); + } + } } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/VarExprParser.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/VarExprParser.java index 309a856..354a344 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/VarExprParser.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/VarExprParser.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,123 +15,124 @@ */ package org.onap.vfc.nfvo.emsdriver.commons.utils; -import java.text.SimpleDateFormat; -import java.util.Locale; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import java.text.SimpleDateFormat; import java.util.Calendar; +import java.util.Locale; +import java.util.regex.Matcher; +import java.util.regex.Pattern; final public class VarExprParser { - private static Log log = LogFactory.getFactory().getInstance(VarExprParser.class); - private static Pattern varPattern = Pattern.compile("(\\$\\{([^\\}]+)\\})", - Pattern.CASE_INSENSITIVE); - - final static public String replaceVar(String str,long scan_start_time,long scan_stop_time) { - if (str.indexOf("${") == -1) - return str; + private static Log log = LogFactory.getFactory().getInstance(VarExprParser.class); + private static Pattern varPattern = Pattern.compile("(\\$\\{([^\\}]+)\\})", + Pattern.CASE_INSENSITIVE); + + final static public String replaceVar(String str, long scan_start_time, long scan_stop_time) { + if (str.indexOf("${") == -1) + return str; + + // 支持原系统变量 + str = str.replace("${s_year}", "${SCAN_START_TIME,yyyy}"); + str = str.replace("${s_mon}", "${SCAN_START_TIME,MM}"); + str = str.replace("${s_day}", "${SCAN_START_TIME,dd}"); + str = str.replace("${s_hour}", "${SCAN_START_TIME,HH}"); + str = str.replace("${s_min}", "${SCAN_START_TIME,mm}"); + str = str.replace("${e_year}", "${SCAN_STOP_TIME,yyyy}"); + str = str.replace("${e_mon}", "${SCAN_STOP_TIME,MM}"); + str = str.replace("${e_day}", "${SCAN_STOP_TIME,dd}"); + str = str.replace("${e_hour}", "${SCAN_STOP_TIME,HH}"); + str = str.replace("${e_min}", "${SCAN_STOP_TIME,mm}"); + + String expr = null, varName = null, value = null; + Matcher matcher = varPattern.matcher(str); + while (matcher.find()) { + value = null; + expr = matcher.group(1); + varName = matcher.group(2); + if (expr.indexOf("${SCAN_START_TIME") != -1) { + value = getTime(scan_start_time, varName, "yyyy-MM-dd HH:mm:ss"); + } else if (expr.indexOf("${SCAN_STOP_TIME") != -1) { + value = getTime(scan_stop_time, varName, "yyyy-MM-dd HH:mm:ss"); + } + if (value == null) { + log.warn(" expr [" + str + "] var[" + + expr + "]is fail"); + continue; + } + str = str.replace(expr, value); + } + expr = value = null; + matcher = null; + return str; + } + + private static String getTime(long time, String value, String defaultParam) { + String timeStr = null; + String formatStr = null; + String increaseTime = null; + if (value.indexOf(",") == -1) { + formatStr = defaultParam; + timeStr = value; + } else { + timeStr = value.split(",")[0]; + formatStr = value.split(",")[1]; + } + + if (timeStr.indexOf("+") == -1 && timeStr.indexOf("-") == -1) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formatStr, Locale.ENGLISH); + return simpleDateFormat.format(time); + } else { + if (timeStr.indexOf("+") != -1) { + increaseTime = timeStr.substring(timeStr.indexOf("+") + 1, timeStr.length() - 1); + } + if (timeStr.indexOf("-") != -1) { + increaseTime = timeStr.substring(timeStr.indexOf("-"), timeStr.length() - 1); + } + if (timeStr.toLowerCase().endsWith("h")) { + Calendar cal = Calendar.getInstance(); + cal.setTimeInMillis(time); + cal.add(Calendar.HOUR, Integer.parseInt(increaseTime)); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formatStr, Locale.ENGLISH); + return simpleDateFormat.format(cal.getTimeInMillis()); + } else if (timeStr.toLowerCase().endsWith("m")) { + Calendar cal = Calendar.getInstance(); + cal.setTimeInMillis(time); + cal.add(Calendar.MINUTE, Integer.parseInt(increaseTime)); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formatStr, Locale.ENGLISH); + return simpleDateFormat.format(cal.getTimeInMillis()); + } + } + return null; + } + + /** + * 仅支持该两个变量替换 省得正则匹配慢 + * + * @param result + * @param scan_start_time + * @param scan_stop_time + * @return + */ + public static String replaceTimeVar(String result, + String scan_start_time, String scan_stop_time) { + + boolean isReplace = false; + if (result.indexOf("${SCAN_ST") != -1) { + isReplace = true; + } + if (isReplace) { + if (result.indexOf("${SCAN_START_TIME}") != -1) { - // 支持原系统变量 - str = str.replace("${s_year}", "${SCAN_START_TIME,yyyy}"); - str = str.replace("${s_mon}", "${SCAN_START_TIME,MM}"); - str = str.replace("${s_day}", "${SCAN_START_TIME,dd}"); - str = str.replace("${s_hour}", "${SCAN_START_TIME,HH}"); - str = str.replace("${s_min}", "${SCAN_START_TIME,mm}"); - str = str.replace("${e_year}", "${SCAN_STOP_TIME,yyyy}"); - str = str.replace("${e_mon}", "${SCAN_STOP_TIME,MM}"); - str = str.replace("${e_day}", "${SCAN_STOP_TIME,dd}"); - str = str.replace("${e_hour}", "${SCAN_STOP_TIME,HH}"); - str = str.replace("${e_min}", "${SCAN_STOP_TIME,mm}"); + result = StringUtils.replace(result, "${SCAN_START_TIME}", scan_start_time); + } + if (result.indexOf("${SCAN_STOP_TIME") != -1) { - String expr = null, varName = null, value = null; - Matcher matcher = varPattern.matcher(str); - while (matcher.find()) { - value = null; - expr = matcher.group(1); - varName = matcher.group(2); - if (expr.indexOf("${SCAN_START_TIME") != -1) { - value = getTime(scan_start_time,varName,"yyyy-MM-dd HH:mm:ss"); - } else if (expr.indexOf("${SCAN_STOP_TIME") != -1) { - value = getTime(scan_stop_time,varName,"yyyy-MM-dd HH:mm:ss"); - } - if (value == null) { - log.warn(" expr [" + str + "] var[" - + expr + "]is fail"); - continue; - } - str = str.replace(expr, value); - } - expr = value = null; - matcher = null; - return str; - } - - private static String getTime(long time,String value,String defaultParam){ - String timeStr = null; - String formatStr = null; - String increaseTime = null; - if (value.indexOf(",") == -1){ - formatStr = defaultParam; - timeStr = value; - }else{ - timeStr = value.split(",")[0]; - formatStr = value.split(",")[1]; - } - - if(timeStr.indexOf("+")==-1&&timeStr.indexOf("-")==-1){ - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formatStr, Locale.ENGLISH); - return simpleDateFormat.format(time); - }else{ - if(timeStr.indexOf("+")!=-1){ - increaseTime = timeStr.substring(timeStr.indexOf("+")+1, timeStr.length()-1); - } - if(timeStr.indexOf("-")!=-1){ - increaseTime = timeStr.substring(timeStr.indexOf("-"), timeStr.length()-1); - } - if(timeStr.toLowerCase().endsWith("h")){ - Calendar cal = Calendar.getInstance(); - cal.setTimeInMillis(time); - cal.add(Calendar.HOUR,Integer.parseInt(increaseTime)); - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formatStr, Locale.ENGLISH); - return simpleDateFormat.format(cal.getTimeInMillis()); - }else if(timeStr.toLowerCase().endsWith("m")){ - Calendar cal = Calendar.getInstance(); - cal.setTimeInMillis(time); - cal.add(Calendar.MINUTE,Integer.parseInt(increaseTime)); - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formatStr, Locale.ENGLISH); - return simpleDateFormat.format(cal.getTimeInMillis()); - } - } - return null; - } - /** - * 仅支持该两个变量替换 省得正则匹配慢 - * @param result - * @param scan_start_time - * @param scan_stop_time - * @return - */ - public static String replaceTimeVar(String result, - String scan_start_time, String scan_stop_time){ - - boolean isReplace = false; - if(result.indexOf("${SCAN_ST") != -1){ - isReplace = true; - } - if(isReplace){ - if(result.indexOf("${SCAN_START_TIME}") != -1){ - - result = StringUtils.replace(result, "${SCAN_START_TIME}", scan_start_time); - } - if(result.indexOf("${SCAN_STOP_TIME") != -1){ - - result = StringUtils.replace(result, "${SCAN_STOP_TIME}", scan_stop_time); - } - } - return result; + result = StringUtils.replace(result, "${SCAN_STOP_TIME}", scan_stop_time); + } + } + return result; } } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/XmlUtil.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/XmlUtil.java index e5a7839..92345bf 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/XmlUtil.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/XmlUtil.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,23 +15,21 @@ */ package org.onap.vfc.nfvo.emsdriver.commons.utils; -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; - -import javax.xml.stream.XMLStreamException; - import org.jdom.Document; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; +import javax.xml.stream.XMLStreamException; +import java.io.IOException; +import java.io.InputStream; + public class XmlUtil { - public static Document getDocument(InputStream is) throws XMLStreamException, JDOMException, IOException{ - - SAXBuilder builder = new SAXBuilder(); - Document doc = builder.build(is); - return doc; - } + public static Document getDocument(InputStream is) throws XMLStreamException, JDOMException, IOException { + + SAXBuilder builder = new SAXBuilder(); + Document doc = builder.build(is); + return doc; + } } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/Zip.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/Zip.java index 2e83349..6c624a2 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/Zip.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/commons/utils/Zip.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -24,85 +24,86 @@ import java.util.zip.ZipOutputStream; public class Zip { - protected int compressDirectoryCount = 0; - protected int compressFileCount = 0; - - protected int relativeAddrIdx = 0; - protected int compressLevel = 6; - protected String zipFilePath = null; - protected String compressPath = null; - - protected ZipOutputStream zipOutput = null; - - /** - * - */ - public Zip(String compressPath, String zipFilePath) throws IOException{ - File compressFile = new File(compressPath); - if (!compressFile.exists()) - throw new IOException("the file or directory '"+compressPath+"' not found!"); - - this.zipFilePath = zipFilePath; - this.compressPath = compressFile.getAbsolutePath(); - - if (this.zipFilePath == null) { - StringBuffer zipFilePathBuf = new StringBuffer(this.compressPath); - int bufLen = zipFilePathBuf.length(); - if (zipFilePathBuf.charAt(bufLen-1) == '/') - zipFilePathBuf.deleteCharAt(bufLen-1); - this.zipFilePath = zipFilePathBuf.append(".zip").toString(); - } - relativeAddrIdx = this.compressPath.lastIndexOf(File.separator)+1; - } - - /** - * - */ - public void compress() throws IOException { - File theFile = new File(zipFilePath); - - if (!theFile.exists()) { - String parentPath = theFile.getParent(); - if (parentPath != null) - new File(parentPath).mkdirs(); - theFile.createNewFile(); - } - zipOutput = new ZipOutputStream(new FileOutputStream(zipFilePath)); - zipOutput.setMethod(ZipOutputStream.DEFLATED); - zipOutput.setLevel(compressLevel); - compressDirectory(new File(compressPath)); - zipOutput.close(); - } - - protected void compressDirectory(File directoryPath) throws IOException { - if (directoryPath.isFile()) { - compressFile(directoryPath.getAbsolutePath()); - }else{ - File listFiles[] = directoryPath.listFiles(); - for (int i=0; i<listFiles.length; i++) - if (listFiles[i].isFile()) { - compressFile(listFiles[i].getAbsolutePath()); - }else { - compressDirectoryCount ++; - compressDirectory(listFiles[i]); - } - } - - - } - protected void compressFile(String absolutePath) throws IOException { - compressFileCount ++; - byte byteBuf[] = new byte[2048]; - zipOutput.putNextEntry(new ZipEntry(absolutePath.substring(relativeAddrIdx))); - - FileInputStream input= new FileInputStream(absolutePath); - for (int count=0; (count=input.read(byteBuf,0,byteBuf.length))!=-1;) - zipOutput.write(byteBuf, 0, count); - input.close(); - zipOutput.closeEntry(); - } - - public void setCompressLevel(int level) { - compressLevel = level; - } + protected int compressDirectoryCount = 0; + protected int compressFileCount = 0; + + protected int relativeAddrIdx = 0; + protected int compressLevel = 6; + protected String zipFilePath = null; + protected String compressPath = null; + + protected ZipOutputStream zipOutput = null; + + /** + * + */ + public Zip(String compressPath, String zipFilePath) throws IOException { + File compressFile = new File(compressPath); + if (!compressFile.exists()) + throw new IOException("the file or directory '" + compressPath + "' not found!"); + + this.zipFilePath = zipFilePath; + this.compressPath = compressFile.getAbsolutePath(); + + if (this.zipFilePath == null) { + StringBuffer zipFilePathBuf = new StringBuffer(this.compressPath); + int bufLen = zipFilePathBuf.length(); + if (zipFilePathBuf.charAt(bufLen - 1) == '/') + zipFilePathBuf.deleteCharAt(bufLen - 1); + this.zipFilePath = zipFilePathBuf.append(".zip").toString(); + } + relativeAddrIdx = this.compressPath.lastIndexOf(File.separator) + 1; + } + + /** + * + */ + public void compress() throws IOException { + File theFile = new File(zipFilePath); + + if (!theFile.exists()) { + String parentPath = theFile.getParent(); + if (parentPath != null) + new File(parentPath).mkdirs(); + theFile.createNewFile(); + } + zipOutput = new ZipOutputStream(new FileOutputStream(zipFilePath)); + zipOutput.setMethod(ZipOutputStream.DEFLATED); + zipOutput.setLevel(compressLevel); + compressDirectory(new File(compressPath)); + zipOutput.close(); + } + + protected void compressDirectory(File directoryPath) throws IOException { + if (directoryPath.isFile()) { + compressFile(directoryPath.getAbsolutePath()); + } else { + File listFiles[] = directoryPath.listFiles(); + for (int i = 0; i < listFiles.length; i++) + if (listFiles[i].isFile()) { + compressFile(listFiles[i].getAbsolutePath()); + } else { + compressDirectoryCount++; + compressDirectory(listFiles[i]); + } + } + + + } + + protected void compressFile(String absolutePath) throws IOException { + compressFileCount++; + byte byteBuf[] = new byte[2048]; + zipOutput.putNextEntry(new ZipEntry(absolutePath.substring(relativeAddrIdx))); + + FileInputStream input = new FileInputStream(absolutePath); + for (int count = 0; (count = input.read(byteBuf, 0, byteBuf.length)) != -1; ) + zipOutput.write(byteBuf, 0, count); + input.close(); + zipOutput.closeEntry(); + } + + public void setCompressLevel(int level) { + compressLevel = level; + } } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/configmgr/ConfigurationImp.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/configmgr/ConfigurationImp.java index f8223db..62cc732 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/configmgr/ConfigurationImp.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/configmgr/ConfigurationImp.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,43 +15,43 @@ */ package org.onap.vfc.nfvo.emsdriver.configmgr; -import java.util.List; -import java.util.Properties; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.onap.vfc.nfvo.emsdriver.commons.model.CollectVo; import org.onap.vfc.nfvo.emsdriver.commons.model.EMSInfo; +import java.util.List; +import java.util.Properties; + + +public class ConfigurationImp implements ConfigurationInterface { + + private Log log = LogFactory.getLog(ConfigurationImp.class); + + @Override + public List<EMSInfo> getAllEMSInfo() { + List<EMSInfo> emsInfos = ConfigurationManager.getAllEMSInfos(); + return emsInfos; + } + + @Override + public CollectVo getCollectVoByEmsNameAndType(String emsName, String type) { + CollectVo collectVo = null; + + EMSInfo emsInfo = ConfigurationManager.getEMSInfoByName(emsName); + if (emsInfo != null) { + collectVo = emsInfo.getCollectVoByType(type); + } else { + log.error("ConfigurationManager.getEMSInfoByName return null"); + } + return collectVo; + } + + @Override + public Properties getProperties() { + Properties p = ConfigurationManager.getProperties(); + return p; + } + -public class ConfigurationImp implements ConfigurationInterface{ - - private Log log = LogFactory.getLog(ConfigurationImp.class); - - @Override - public List<EMSInfo> getAllEMSInfo() { - List<EMSInfo> emsInfos = ConfigurationManager.getAllEMSInfos(); - return emsInfos; - } - - @Override - public CollectVo getCollectVoByEmsNameAndType(String emsName, String type) { - CollectVo collectVo = null; - - EMSInfo emsInfo = ConfigurationManager.getEMSInfoByName(emsName); - if(emsInfo != null){ - collectVo = emsInfo.getCollectVoByType(type); - }else{ - log.error("ConfigurationManager.getEMSInfoByName return null"); - } - return collectVo; - } - - @Override - public Properties getProperties() { - Properties p = ConfigurationManager.getProperties(); - return p; - } - - } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/configmgr/ConfigurationInterface.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/configmgr/ConfigurationInterface.java index 65d2ca7..e4f156c 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/configmgr/ConfigurationInterface.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/configmgr/ConfigurationInterface.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,17 +15,18 @@ */ package org.onap.vfc.nfvo.emsdriver.configmgr; -import java.util.List; -import java.util.Properties; - import org.onap.vfc.nfvo.emsdriver.commons.model.CollectVo; import org.onap.vfc.nfvo.emsdriver.commons.model.EMSInfo; +import java.util.List; +import java.util.Properties; + public interface ConfigurationInterface { - - public List<EMSInfo> getAllEMSInfo(); - public CollectVo getCollectVoByEmsNameAndType(String emsName,String type); - public Properties getProperties(); + public List<EMSInfo> getAllEMSInfo(); + + public CollectVo getCollectVoByEmsNameAndType(String emsName, String type); + + public Properties getProperties(); } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/configmgr/ConfigurationManager.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/configmgr/ConfigurationManager.java index 7fb2078..4550e87 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/configmgr/ConfigurationManager.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/configmgr/ConfigurationManager.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,17 +15,8 @@ */ package org.onap.vfc.nfvo.emsdriver.configmgr; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.ConcurrentHashMap; - +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; import com.google.common.annotations.VisibleForTesting; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -40,277 +31,280 @@ import org.onap.vfc.nfvo.emsdriver.commons.utils.StringUtil; import org.onap.vfc.nfvo.emsdriver.commons.utils.XmlUtil; import org.onap.vfc.nfvo.emsdriver.northbound.client.HttpClientUtil; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; public class ConfigurationManager extends DriverThread { - protected static Log log = LogFactory.getLog(ConfigurationManager.class); - public final static String CONFIG_PROPERTIES_LOCATION = Constant.SYS_CFG + "config.properties"; - /** - * ESM Cache - */ - @VisibleForTesting - static Map<String, EMSInfo> emsInfoCache = new ConcurrentHashMap<String, EMSInfo>(); - private static Map<String, CrontabVo> emsCrontab= new ConcurrentHashMap<String, CrontabVo>(); - private static List<String> emsIdList = new ArrayList<String>(); - @VisibleForTesting - static Properties properties = null; - - @Override - public void dispose() { - - //this.log.debug("start loading " + cacheFilePath); - File file = new File(CONFIG_PROPERTIES_LOCATION); - if(!file.exists() || !file.isFile()){ - log.error("cacheFilePath " + CONFIG_PROPERTIES_LOCATION +" not exist or is not File"); - return; - } - InputStream in = null; - try{ - properties = new Properties(); - in = new FileInputStream(file); - properties.load(in); - Map<String, CrontabVo> emsMap = readCorntab(); - - emsCrontab.putAll(emsMap); - - new ReceiveSource().start(); - }catch(Exception e) { - log.error("read ["+file.getAbsolutePath()+"]Exception :",e); - }finally { - if(in != null) { - try { - in.close(); - } catch (Exception e) { - } - } - } - } - - public Map<String, CrontabVo> readCorntab() { - String path = Constant.SYS_CFG + "crontab.xml"; - File cfg = new File(path); - log.debug("start loading " + path); - if(!cfg.exists() || !cfg.isFile()){ - log.debug("not exists " + path); - return null; - } - InputStream is = null; - Map<String, CrontabVo> tmpcache = new HashMap<String, CrontabVo>(); - - try { - is = new FileInputStream(cfg); - Document doc = XmlUtil.getDocument(is); - - Element root = doc.getRootElement(); - - @SuppressWarnings("unchecked") - List<Element> children = root.getChildren(); - - for(Iterator<Element> it = children.iterator();it.hasNext();){ - CrontabVo crontabVo = new CrontabVo(); - Element child = it.next(); - String type = child.getAttributeValue("type"); - if(StringUtil.isBank(type)){ - continue; - } - crontabVo.setType(type); - if(Constant.COLLECT_TYPE_ALARM.equalsIgnoreCase(type)){ - boolean iscollect = Boolean.parseBoolean(child.getAttributeValue("iscollect")); - if(iscollect){ - crontabVo.setIscollect(iscollect); - }else{ - continue; - } - - crontabVo.setRead_timeout(child.getChildText("readtimeout")); - }else{ - String crontab = child.getAttributeValue("crontab"); - if(!StringUtil.isBank(type) && !StringUtil.isBank(crontab)){ - crontabVo.setCrontab(crontab); - }else{ - continue; - } - crontabVo.setMatch(child.getChildText("match")); - crontabVo.setGranularity(child.getChildText("granularity")); - } - tmpcache.put(type.toUpperCase(), crontabVo); - } - - } catch (Exception e) { - log.error("load crontab.xml is error "+StringUtil.getStackTrace(e)); - }finally{ - try { - if(is != null){ - is.close(); - is = null; - } - } catch (Exception e2) { - } - cfg = null; - } - return tmpcache; - } - - public static synchronized List<EMSInfo> getAllEMSInfos(){ - List<EMSInfo> list = new ArrayList<EMSInfo>(); - for(EMSInfo emsinfo :emsInfoCache.values()){ - list.add(emsinfo); - } - return list; - } - - public static synchronized EMSInfo getEMSInfoByName(String emsName){ - EMSInfo emsInfo= emsInfoCache.get(emsName); - return emsInfo; - } - - public static synchronized Properties getProperties() { - return properties; - } - - class ReceiveSource extends Thread{ - long timeStamp = System.currentTimeMillis(); - - public void run() { - while(true){ - - try { - if(System.currentTimeMillis() - timeStamp > Constant.ONEMINUTE){ - timeStamp = System.currentTimeMillis(); - log.debug("ReceiveSource run"); - } - //get emsId list - List<String> emsIds = this.getEmsIdList(); - if(emsIds.size() > 0){ - emsIdList.clear(); - emsIdList.addAll(emsIds); - } - - for(String emsId : emsIdList){ - //get emsInfo by emsId - Map<String, EMSInfo> emsInfoMap = this.getEmsInfo(emsId); - - emsInfoCache.putAll(emsInfoMap); - } - if(emsInfoCache.size() > 0){ - Thread.sleep(30*60*1000); - }else{ - Thread.sleep(60*1000); - } - } catch (Exception e) { - try { - Thread.sleep(60*1000); - } catch (InterruptedException e1) { - e1.printStackTrace(); - } - log.error("ReceiveSource exception",e); - } - } - } - - private Map<String, EMSInfo> getEmsInfo(String emsId) { - Map<String, EMSInfo> tmpcache = new ConcurrentHashMap<String, EMSInfo>(); - String msbAddress = properties.getProperty("msbAddress"); - String emstUrl = properties.getProperty("esr_emsUrl"); - //set emsId to url - emstUrl = String.format(emstUrl, emsId); - String getemstUrl = "http://"+msbAddress+emstUrl; - String emsResult = HttpClientUtil.doGet(getemstUrl, Constant.ENCODING_UTF8); - log.debug(getemstUrl+" result="+emsResult); - JSONObject reagobj = JSONObject.parseObject(emsResult); - - JSONObject esr_system_info_list = reagobj.getJSONObject("esr-system-info-list"); - JSONArray esr_system_info = esr_system_info_list.getJSONArray("esr-system-info"); - Iterator<Object> it = esr_system_info.iterator(); - EMSInfo emsInfo = new EMSInfo(); - emsInfo.setName(emsId); - tmpcache.put(emsId, emsInfo); - while(it.hasNext()){ - Object obj = it.next(); - JSONObject collect = (JSONObject)obj; - String system_type = (String)collect.get("system-type"); - CollectVo collectVo = new CollectVo(); - if(Constant.COLLECT_TYPE_CM.equalsIgnoreCase(system_type)){ - CrontabVo crontabVo = emsCrontab.get(system_type); - if(crontabVo != null){ - collectVo.setType(system_type); - collectVo.setCrontab(crontabVo.getCrontab()); - collectVo.setIP(collect.getString("ip-address")); - collectVo.setPort(collect.getString("port")); - collectVo.setUser(collect.getString("user-name")); - collectVo.setPassword(collect.getString("password")); - - collectVo.setRemotepath(collect.getString("remote-path")); - collectVo.setMatch(crontabVo.getMatch()); - collectVo.setPassive(collect.getString("passive")); - collectVo.setGranularity(crontabVo.getGranularity()); - }else{ - log.error("emsCrontab.get(system_type) result crontabVo is null system_type=["+system_type+"] emsCrontabMap="+emsCrontab ); - } - - - }else if(Constant.COLLECT_TYPE_PM.equalsIgnoreCase(system_type)){ - CrontabVo crontabVo = emsCrontab.get(system_type); - if(crontabVo != null){ - collectVo.setType(system_type); - collectVo.setCrontab(crontabVo.getCrontab()); - collectVo.setIP(collect.getString("ip-address")); - collectVo.setPort(collect.getString("port")); - collectVo.setUser(collect.getString("user-name")); - collectVo.setPassword(collect.getString("password")); - - collectVo.setRemotepath(collect.getString("remote-path")); - collectVo.setMatch(crontabVo.getMatch()); - collectVo.setPassive(collect.getString("passive")); - collectVo.setGranularity(crontabVo.getGranularity()); - }else{ - log.error("emsCrontab.get(system_type) result crontabVo is null system_type=["+system_type+"]" ); - } - }else if(Constant.COLLECT_TYPE_ALARM.equalsIgnoreCase(system_type)){ - CrontabVo crontabVo = emsCrontab.get(system_type); - if(crontabVo != null){ - collectVo.setIscollect(crontabVo.isIscollect()); - collectVo.setType(system_type); - collectVo.setIP(collect.getString("ip-address")); - collectVo.setPort(collect.getString("port")); - collectVo.setUser(collect.getString("user-name")); - collectVo.setPassword(collect.getString("password")); - collectVo.setRead_timeout(crontabVo.getRead_timeout()); - }else{ - log.error("emsCrontab.get(system_type) result crontabVo is null system_type=["+system_type+"]"); - } - - - }else{ - log.error("ems system-type ="+system_type+" "); - } - - emsInfo.putCollectMap(system_type, collectVo); - } - return tmpcache; - } - - private List<String> getEmsIdList() { - List<String> emsIds = new ArrayList<String>(); - //http - String msbAddress = properties.getProperty("msbAddress"); - String url = properties.getProperty("esr_ems_listUrl"); - String getemsListUrl = "http://"+msbAddress+url; - - String result = HttpClientUtil.doGet(getemsListUrl, Constant.ENCODING_UTF8); - log.debug(getemsListUrl+" result="+result); - JSONObject reagobj = JSONObject.parseObject(result); - JSONArray esr_emsIds = reagobj.getJSONArray("esr-ems"); - Iterator<Object> it = esr_emsIds.iterator(); - while(it.hasNext()){ - Object obj = it.next(); - JSONObject emsId = (JSONObject)obj; - String emsIdStr = (String)emsId.get("ems-id"); - emsIds.add(emsIdStr); - } - return emsIds; - } - } + public final static String CONFIG_PROPERTIES_LOCATION = Constant.SYS_CFG + "config.properties"; + protected static Log log = LogFactory.getLog(ConfigurationManager.class); + /** + * ESM Cache + */ + @VisibleForTesting + static Map<String, EMSInfo> emsInfoCache = new ConcurrentHashMap<String, EMSInfo>(); + @VisibleForTesting + static Properties properties = null; + private static Map<String, CrontabVo> emsCrontab = new ConcurrentHashMap<String, CrontabVo>(); + private static List<String> emsIdList = new ArrayList<String>(); + + public static synchronized List<EMSInfo> getAllEMSInfos() { + List<EMSInfo> list = new ArrayList<EMSInfo>(); + for (EMSInfo emsinfo : emsInfoCache.values()) { + list.add(emsinfo); + } + return list; + } + + public static synchronized EMSInfo getEMSInfoByName(String emsName) { + EMSInfo emsInfo = emsInfoCache.get(emsName); + return emsInfo; + } + + public static synchronized Properties getProperties() { + return properties; + } + + @Override + public void dispose() { + + //this.log.debug("start loading " + cacheFilePath); + File file = new File(CONFIG_PROPERTIES_LOCATION); + if (!file.exists() || !file.isFile()) { + log.error("cacheFilePath " + CONFIG_PROPERTIES_LOCATION + " not exist or is not File"); + return; + } + InputStream in = null; + try { + properties = new Properties(); + in = new FileInputStream(file); + properties.load(in); + Map<String, CrontabVo> emsMap = readCorntab(); + + emsCrontab.putAll(emsMap); + + new ReceiveSource().start(); + } catch (Exception e) { + log.error("read [" + file.getAbsolutePath() + "]Exception :", e); + } finally { + if (in != null) { + try { + in.close(); + } catch (Exception e) { + } + } + } + } + + public Map<String, CrontabVo> readCorntab() { + String path = Constant.SYS_CFG + "crontab.xml"; + File cfg = new File(path); + log.debug("start loading " + path); + if (!cfg.exists() || !cfg.isFile()) { + log.debug("not exists " + path); + return null; + } + InputStream is = null; + Map<String, CrontabVo> tmpcache = new HashMap<String, CrontabVo>(); + + try { + is = new FileInputStream(cfg); + Document doc = XmlUtil.getDocument(is); + + Element root = doc.getRootElement(); + + @SuppressWarnings("unchecked") + List<Element> children = root.getChildren(); + + for (Iterator<Element> it = children.iterator(); it.hasNext(); ) { + CrontabVo crontabVo = new CrontabVo(); + Element child = it.next(); + String type = child.getAttributeValue("type"); + if (StringUtil.isBank(type)) { + continue; + } + crontabVo.setType(type); + if (Constant.COLLECT_TYPE_ALARM.equalsIgnoreCase(type)) { + boolean iscollect = Boolean.parseBoolean(child.getAttributeValue("iscollect")); + if (iscollect) { + crontabVo.setIscollect(iscollect); + } else { + continue; + } + + crontabVo.setRead_timeout(child.getChildText("readtimeout")); + } else { + String crontab = child.getAttributeValue("crontab"); + if (!StringUtil.isBank(type) && !StringUtil.isBank(crontab)) { + crontabVo.setCrontab(crontab); + } else { + continue; + } + crontabVo.setMatch(child.getChildText("match")); + crontabVo.setGranularity(child.getChildText("granularity")); + } + tmpcache.put(type.toUpperCase(), crontabVo); + } + + } catch (Exception e) { + log.error("load crontab.xml is error " + StringUtil.getStackTrace(e)); + } finally { + try { + if (is != null) { + is.close(); + is = null; + } + } catch (Exception e2) { + } + cfg = null; + } + return tmpcache; + } + + class ReceiveSource extends Thread { + long timeStamp = System.currentTimeMillis(); + + public void run() { + while (true) { + + try { + if (System.currentTimeMillis() - timeStamp > Constant.ONEMINUTE) { + timeStamp = System.currentTimeMillis(); + log.debug("ReceiveSource run"); + } + //get emsId list + List<String> emsIds = this.getEmsIdList(); + if (emsIds.size() > 0) { + emsIdList.clear(); + emsIdList.addAll(emsIds); + } + + for (String emsId : emsIdList) { + //get emsInfo by emsId + Map<String, EMSInfo> emsInfoMap = this.getEmsInfo(emsId); + + emsInfoCache.putAll(emsInfoMap); + } + if (emsInfoCache.size() > 0) { + Thread.sleep(30 * 60 * 1000); + } else { + Thread.sleep(60 * 1000); + } + } catch (Exception e) { + try { + Thread.sleep(60 * 1000); + } catch (InterruptedException e1) { + e1.printStackTrace(); + } + log.error("ReceiveSource exception", e); + } + } + } + + private Map<String, EMSInfo> getEmsInfo(String emsId) { + Map<String, EMSInfo> tmpcache = new ConcurrentHashMap<String, EMSInfo>(); + String msbAddress = properties.getProperty("msbAddress"); + String emstUrl = properties.getProperty("esr_emsUrl"); + //set emsId to url + emstUrl = String.format(emstUrl, emsId); + String getemstUrl = "http://" + msbAddress + emstUrl; + String emsResult = HttpClientUtil.doGet(getemstUrl, Constant.ENCODING_UTF8); + log.debug(getemstUrl + " result=" + emsResult); + JSONObject reagobj = JSONObject.parseObject(emsResult); + + JSONObject esr_system_info_list = reagobj.getJSONObject("esr-system-info-list"); + JSONArray esr_system_info = esr_system_info_list.getJSONArray("esr-system-info"); + Iterator<Object> it = esr_system_info.iterator(); + EMSInfo emsInfo = new EMSInfo(); + emsInfo.setName(emsId); + tmpcache.put(emsId, emsInfo); + while (it.hasNext()) { + Object obj = it.next(); + JSONObject collect = (JSONObject) obj; + String system_type = (String) collect.get("system-type"); + CollectVo collectVo = new CollectVo(); + if (Constant.COLLECT_TYPE_CM.equalsIgnoreCase(system_type)) { + CrontabVo crontabVo = emsCrontab.get(system_type); + if (crontabVo != null) { + collectVo.setType(system_type); + collectVo.setCrontab(crontabVo.getCrontab()); + collectVo.setIP(collect.getString("ip-address")); + collectVo.setPort(collect.getString("port")); + collectVo.setUser(collect.getString("user-name")); + collectVo.setPassword(collect.getString("password")); + + collectVo.setRemotepath(collect.getString("remote-path")); + collectVo.setMatch(crontabVo.getMatch()); + collectVo.setPassive(collect.getString("passive")); + collectVo.setGranularity(crontabVo.getGranularity()); + } else { + log.error("emsCrontab.get(system_type) result crontabVo is null system_type=[" + system_type + "] emsCrontabMap=" + emsCrontab); + } + + + } else if (Constant.COLLECT_TYPE_PM.equalsIgnoreCase(system_type)) { + CrontabVo crontabVo = emsCrontab.get(system_type); + if (crontabVo != null) { + collectVo.setType(system_type); + collectVo.setCrontab(crontabVo.getCrontab()); + collectVo.setIP(collect.getString("ip-address")); + collectVo.setPort(collect.getString("port")); + collectVo.setUser(collect.getString("user-name")); + collectVo.setPassword(collect.getString("password")); + + collectVo.setRemotepath(collect.getString("remote-path")); + collectVo.setMatch(crontabVo.getMatch()); + collectVo.setPassive(collect.getString("passive")); + collectVo.setGranularity(crontabVo.getGranularity()); + } else { + log.error("emsCrontab.get(system_type) result crontabVo is null system_type=[" + system_type + "]"); + } + } else if (Constant.COLLECT_TYPE_ALARM.equalsIgnoreCase(system_type)) { + CrontabVo crontabVo = emsCrontab.get(system_type); + if (crontabVo != null) { + collectVo.setIscollect(crontabVo.isIscollect()); + collectVo.setType(system_type); + collectVo.setIP(collect.getString("ip-address")); + collectVo.setPort(collect.getString("port")); + collectVo.setUser(collect.getString("user-name")); + collectVo.setPassword(collect.getString("password")); + collectVo.setRead_timeout(crontabVo.getRead_timeout()); + } else { + log.error("emsCrontab.get(system_type) result crontabVo is null system_type=[" + system_type + "]"); + } + + + } else { + log.error("ems system-type =" + system_type + " "); + } + + emsInfo.putCollectMap(system_type, collectVo); + } + return tmpcache; + } + + private List<String> getEmsIdList() { + List<String> emsIds = new ArrayList<String>(); + //http + String msbAddress = properties.getProperty("msbAddress"); + String url = properties.getProperty("esr_ems_listUrl"); + String getemsListUrl = "http://" + msbAddress + url; + + String result = HttpClientUtil.doGet(getemsListUrl, Constant.ENCODING_UTF8); + log.debug(getemsListUrl + " result=" + result); + JSONObject reagobj = JSONObject.parseObject(result); + JSONArray esr_emsIds = reagobj.getJSONArray("esr-ems"); + Iterator<Object> it = esr_emsIds.iterator(); + while (it.hasNext()) { + Object obj = it.next(); + JSONObject emsId = (JSONObject) obj; + String emsIdStr = (String) emsId.get("ems-id"); + emsIds.add(emsIdStr); + } + return emsIds; + } + } } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/messagemgr/MessageChannel.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/messagemgr/MessageChannel.java index 50304c3..7ee159e 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/messagemgr/MessageChannel.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/messagemgr/MessageChannel.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -21,45 +21,46 @@ import java.util.concurrent.TimeUnit; public class MessageChannel { - - private BlockingQueue<Object> queue = null; - - public MessageChannel(int size){ - if(size>0){ - queue = new LinkedBlockingQueue<Object>(size); - }else{ - queue = new LinkedBlockingQueue<Object>(); - } - } - - public MessageChannel(){ - queue = new LinkedBlockingQueue<Object>(); - } - public void put(Object msg) throws InterruptedException{ - while(!queue.offer(msg)){ - queue.poll(); - } - } - - public Object get() throws InterruptedException{ - return queue.take(); - } - - public Object poll() throws InterruptedException{ - return queue.poll(100, TimeUnit.MILLISECONDS); - } - - public int size(){ - return queue.size(); - } - public void clear(){ - queue.clear(); - } + private BlockingQueue<Object> queue = null; + + public MessageChannel(int size) { + if (size > 0) { + queue = new LinkedBlockingQueue<Object>(size); + } else { + queue = new LinkedBlockingQueue<Object>(); + } + } + + public MessageChannel() { + queue = new LinkedBlockingQueue<Object>(); + } + + public void put(Object msg) throws InterruptedException { + while (!queue.offer(msg)) { + queue.poll(); + } + } + + public Object get() throws InterruptedException { + return queue.take(); + } + + public Object poll() throws InterruptedException { + return queue.poll(100, TimeUnit.MILLISECONDS); + } + + public int size() { + return queue.size(); + } + + public void clear() { + queue.clear(); + } + + public BlockingQueue<Object> getQueue() { + return queue; + } + - public BlockingQueue<Object> getQueue() { - return queue; - } - - } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/messagemgr/MessageChannelFactory.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/messagemgr/MessageChannelFactory.java index d14b108..cca8058 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/messagemgr/MessageChannelFactory.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/messagemgr/MessageChannelFactory.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -19,43 +19,43 @@ import java.util.HashMap; import java.util.Map; public class MessageChannelFactory { - - public static Map<String, MessageChannel> map = new HashMap<String, MessageChannel>(); - - public synchronized static MessageChannel getMessageChannel(String key,Integer size){ - if(map.get(key) != null){ - return map.get(key); - } - MessageChannel mc = null; - if(size != null && size > 0){ - mc = new MessageChannel(size); - }else{ - mc = new MessageChannel(); - } - - map.put(key, mc); - return mc; - } - - public synchronized static MessageChannel getMessageChannel(String key){ - if(map.get(key) != null){ - return map.get(key); - } - MessageChannel mc = new MessageChannel(); - - map.put(key, mc); - return mc; - } - - public synchronized static boolean destroyMessageChannel(String key){ - if(map.get(key) != null){ - map.remove(key); - return true; - } - return false; - } - - public synchronized static void clean(){ - map.clear(); - } + + public static Map<String, MessageChannel> map = new HashMap<String, MessageChannel>(); + + public synchronized static MessageChannel getMessageChannel(String key, Integer size) { + if (map.get(key) != null) { + return map.get(key); + } + MessageChannel mc = null; + if (size != null && size > 0) { + mc = new MessageChannel(size); + } else { + mc = new MessageChannel(); + } + + map.put(key, mc); + return mc; + } + + public synchronized static MessageChannel getMessageChannel(String key) { + if (map.get(key) != null) { + return map.get(key); + } + MessageChannel mc = new MessageChannel(); + + map.put(key, mc); + return mc; + } + + public synchronized static boolean destroyMessageChannel(String key) { + if (map.get(key) != null) { + map.remove(key); + return true; + } + return false; + } + + public synchronized static void clean() { + map.clear(); + } } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/northbound/client/HttpClientFactory.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/northbound/client/HttpClientFactory.java index 32e8fa6..00c1558 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/northbound/client/HttpClientFactory.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/northbound/client/HttpClientFactory.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,36 +15,35 @@ */ package org.onap.vfc.nfvo.emsdriver.northbound.client; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.SSLContext; - import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContextBuilder; +import javax.net.ssl.SSLContext; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + /** * HttpClient - */ -public class HttpClientFactory{ - - - public static CloseableHttpClient getSSLClientFactory() throws Exception { - - SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { - //信任所有 - public boolean isTrusted(X509Certificate[] chain, - String authType) throws CertificateException { - return true; - } - }).build(); - SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); - CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); - - return httpclient; - } - + */ +public class HttpClientFactory { + + + public static CloseableHttpClient getSSLClientFactory() throws Exception { + + SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { + //信任所有 + public boolean isTrusted(X509Certificate[] chain, + String authType) throws CertificateException { + return true; + } + }).build(); + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); + CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); + + return httpclient; + } + } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/northbound/client/HttpClientUtil.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/northbound/client/HttpClientUtil.java index 8551b20..63e90aa 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/northbound/client/HttpClientUtil.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/northbound/client/HttpClientUtil.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,118 +15,112 @@ */ package org.onap.vfc.nfvo.emsdriver.northbound.client; -import java.io.IOException; - +import org.apache.commons.codec.binary.Base64; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpEntity; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; -import org.apache.commons.codec.binary.Base64; +import java.io.IOException; /* * HttpClient post request */ public class HttpClientUtil { - - private static Log log = LogFactory.getLog(HttpClientUtil.class); - - public static String doPost(String url,String json,String charset){ - CloseableHttpClient httpClient = null; + + private static Log log = LogFactory.getLog(HttpClientUtil.class); + + public static String doPost(String url, String json, String charset) { + CloseableHttpClient httpClient = null; HttpPost httpPost = null; String result = null; - try{ + try { httpClient = HttpClientFactory.getSSLClientFactory(); httpPost = new HttpPost(url); if (null != json) { - StringEntity s = new StringEntity(json); - s.setContentEncoding("UTF-8"); - s.setContentType("application/json"); // set contentType - httpPost.setEntity(s); - } + StringEntity s = new StringEntity(json); + s.setContentEncoding("UTF-8"); + s.setContentType("application/json"); // set contentType + httpPost.setEntity(s); + } CloseableHttpResponse response = httpClient.execute(httpPost); try { - if(response != null){ - HttpEntity resEntity = response.getEntity(); - if(resEntity != null){ - result = EntityUtils.toString(resEntity,charset); - } - } - } catch (Exception e) { - log.error("httpClient.execute(httpPost) is fail",e); - }finally{ - if(response != null){ - response.close(); - } - } - }catch(Exception e){ - log.error("doPost is fail ",e); - }finally{ - if(httpClient != null){ - try { - httpClient.close(); - } catch (IOException e) { - } - } - - } + if (response != null) { + HttpEntity resEntity = response.getEntity(); + if (resEntity != null) { + result = EntityUtils.toString(resEntity, charset); + } + } + } catch (Exception e) { + log.error("httpClient.execute(httpPost) is fail", e); + } finally { + if (response != null) { + response.close(); + } + } + } catch (Exception e) { + log.error("doPost is fail ", e); + } finally { + if (httpClient != null) { + try { + httpClient.close(); + } catch (IOException e) { + } + } + + } return result; } - - public static String doDelete(String url ,String charset){ - CloseableHttpClient httpClient = null; + + public static String doDelete(String url, String charset) { + CloseableHttpClient httpClient = null; HttpDelete httpDelete = null; String result = null; - try{ + try { httpClient = HttpClientFactory.getSSLClientFactory(); httpDelete = new HttpDelete(url); - + CloseableHttpResponse response = httpClient.execute(httpDelete); - + try { - if(response != null){ - HttpEntity resEntity = response.getEntity(); - if(resEntity != null){ - result = EntityUtils.toString(resEntity,charset); - } - } - } catch (Exception e) { - log.error("",e); - }finally{ - if(response != null){ - response.close(); - } - } - }catch(Exception e){ - log.error("doDelete is fail ",e); - }finally{ - if(httpClient != null){ - try { - httpClient.close(); - } catch (IOException e) { - } - } + if (response != null) { + HttpEntity resEntity = response.getEntity(); + if (resEntity != null) { + result = EntityUtils.toString(resEntity, charset); + } + } + } catch (Exception e) { + log.error("", e); + } finally { + if (response != null) { + response.close(); + } + } + } catch (Exception e) { + log.error("doDelete is fail ", e); + } finally { + if (httpClient != null) { + try { + httpClient.close(); + } catch (IOException e) { + } + } } return result; } - - public static String doGet(String url, String charset){ - CloseableHttpClient httpClient = null; + + public static String doGet(String url, String charset) { + CloseableHttpClient httpClient = null; HttpGet httpGet = null; String result = null; - try{ + try { httpClient = HttpClients.createDefault(); httpGet = new HttpGet(url); httpGet.setHeader("Content-Type", "application/json"); @@ -138,30 +132,30 @@ public class HttpClientUtil { httpGet.setHeader("Authorization", "Basic " + authenticationEncoding); CloseableHttpResponse response = httpClient.execute(httpGet); - log.info("1 doGet sucess url ="+url); + log.info("1 doGet sucess url =" + url); try { - if(response != null){ - HttpEntity resEntity = response.getEntity(); - if(resEntity != null){ - result = EntityUtils.toString(resEntity,charset); - } - } - } catch (Exception e) { - log.error("",e); - }finally{ - if(response != null){ - response.close(); - } - } - }catch(Exception e){ - log.error("doGet is fail ",e); - }finally{ - if(httpClient != null){ - try { - httpClient.close(); - } catch (IOException e) { - } - } + if (response != null) { + HttpEntity resEntity = response.getEntity(); + if (resEntity != null) { + result = EntityUtils.toString(resEntity, charset); + } + } + } catch (Exception e) { + log.error("", e); + } finally { + if (response != null) { + response.close(); + } + } + } catch (Exception e) { + log.error("doGet is fail ", e); + } finally { + if (httpClient != null) { + try { + httpClient.close(); + } catch (IOException e) { + } + } } return result; } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/northbound/client/NorthMessageMgr.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/northbound/client/NorthMessageMgr.java index dad1599..aa01c99 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/northbound/client/NorthMessageMgr.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/northbound/client/NorthMessageMgr.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,21 +15,7 @@ */ package org.onap.vfc.nfvo.emsdriver.northbound.client; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.Properties; - -import org.apache.log4j.Level; -import org.onap.vfc.nfvo.emsdriver.commons.constant.Constant; -import org.onap.vfc.nfvo.emsdriver.commons.utils.DriverThread; -import org.onap.vfc.nfvo.emsdriver.configmgr.ConfigurationInterface; -import org.onap.vfc.nfvo.emsdriver.messagemgr.MessageChannel; -import org.onap.vfc.nfvo.emsdriver.messagemgr.MessageChannelFactory; - import com.alibaba.fastjson.JSONObject; - import evel_javalibrary.att.com.AgentMain; import evel_javalibrary.att.com.AgentMain.EVEL_ERR_CODES; import evel_javalibrary.att.com.EvelFault; @@ -38,321 +24,331 @@ import evel_javalibrary.att.com.EvelFault.EVEL_SOURCE_TYPES; import evel_javalibrary.att.com.EvelFault.EVEL_VF_STATUSES; import evel_javalibrary.att.com.EvelHeader; import evel_javalibrary.att.com.EvelScalingMeasurement; +import org.apache.log4j.Level; +import org.onap.vfc.nfvo.emsdriver.commons.constant.Constant; +import org.onap.vfc.nfvo.emsdriver.commons.utils.DriverThread; +import org.onap.vfc.nfvo.emsdriver.configmgr.ConfigurationInterface; +import org.onap.vfc.nfvo.emsdriver.messagemgr.MessageChannel; +import org.onap.vfc.nfvo.emsdriver.messagemgr.MessageChannelFactory; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; +import java.util.Properties; + +public class NorthMessageMgr extends DriverThread { + + private MessageChannel alarmChannel = MessageChannelFactory.getMessageChannel(Constant.RESULT_CHANNEL_KEY); + private MessageChannel collectResultPMChannel = MessageChannelFactory.getMessageChannel(Constant.COLLECT_RESULT_PM_CHANNEL_KEY); + private MessageChannel collectResultChannel = MessageChannelFactory.getMessageChannel(Constant.COLLECT_RESULT_CHANNEL_KEY); + private ConfigurationInterface configurationInterface; + + private boolean threadStop = false; + private Level level = Level.DEBUG; + + @Override + public void dispose() { + log.info("NorthMessageMgr Thread start threadStop=" + threadStop); + try { + Properties properties = configurationInterface.getProperties(); + String event_api_url = properties.getProperty("event_api_url"); + String port = properties.getProperty("port"); + String path = properties.getProperty("path"); + String topic = properties.getProperty("topic"); + String username = properties.getProperty("username"); + String password = properties.getProperty("password"); + String levelStr = properties.getProperty("level"); + if ("debug".equals(levelStr)) { + level = Level.DEBUG; + } else { + level = Level.INFO; + } + + //login north + event_api_url = "http://" + event_api_url; + log.info("AgentMain.evel_initialize start event_api_url=[" + event_api_url + "]port=[" + port + "]path=[" + path + "]" + + "topic=[" + topic + "]username=[" + username + "]password=[" + password + "]level=[" + level + "]"); + try { + EVEL_ERR_CODES evecode = AgentMain.evel_initialize(event_api_url, Integer.parseInt(port), + path, topic, + username, + password, + level); + log.info("AgentMain.evel_initialize sucess EVEL_ERR_CODES=" + evecode); + } catch (Exception e) { + log.error("AgentMain.evel_initialize fail ", e); + } catch (Error e1) { + log.error("AgentMain.evel_initialize Error ", e1); + } + } catch (Exception e2) { + log.error("NorthMessageMgr start fail ", e2); + } + + new HeatBeatTread().start(); + // + new AlarmMessageRecv().start(); + + new ResultMessageRecv().start(); + + new CollectMessageRecv().start(); + + log.info("NorthMessageMgr start sucess "); + } + + /** + * @return the configurationInterface + */ + public ConfigurationInterface getConfigurationInterface() { + return configurationInterface; + } + + /** + * @param configurationInterface the configurationInterface to set + */ + public void setConfigurationInterface( + ConfigurationInterface configurationInterface) { + this.configurationInterface = configurationInterface; + } + + class HeatBeatTread extends Thread { + + public void run() { + + while (!threadStop) { + + try { + EvelHeader header = EvelHeader.evel_new_heartbeat("Hearbeat_EMS", "EMS-driver"); + header.evel_nfnamingcode_set("EMS-driver"); + header.evel_nfcnamingcode_set("EMS-driver"); + AgentMain.evel_post_event(header); + log.info("HeatBeat send!"); + try { + Thread.sleep(60 * 1000); + } catch (Exception e) { + e.printStackTrace(); + } + } catch (Exception e) { + log.error("HeatBeatTread exception", e); + } + } + } + } + + class AlarmMessageRecv extends Thread { + long timeStamp = System.currentTimeMillis(); + + public void run() { + while (!threadStop) { + + try { + if (System.currentTimeMillis() - timeStamp > Constant.ONEMINUTE) { + timeStamp = System.currentTimeMillis(); + + log.info("ALARM_CHANNEL Msg size :" + alarmChannel.size()); + } + + Object obj = alarmChannel.poll(); + if (obj == null) { + continue; + } + if (obj instanceof String) { + String result = (String) obj; + JSONObject reagobj = JSONObject.parseObject(result); + + EvelFault evelFault = this.resultEvelFault(reagobj); + + //send + log.info("AgentMain.evel_post_event alarm start"); + AgentMain.evel_post_event(evelFault); + log.info("AgentMain.evel_post_event alarm sucess"); + } else { + log.error("AlarmMessageRecv receive Object = " + obj); + } + + } catch (Exception e) { + log.error("AlarmMessageRecv exception", e); + } + } + } + + private EvelFault resultEvelFault(JSONObject reagobj) { + + String eventName = null; + EvelHeader.PRIORITIES pri = null; + EVEL_SEVERITIES severity = null; + EVEL_VF_STATUSES status = null; + String alarmStatus = reagobj.getString("alarmStatus"); + String origSeverity = reagobj.getString("origSeverity"); + if ("0".equals(alarmStatus)) { + status = EVEL_VF_STATUSES.EVEL_VF_STATUS_IDLE; + eventName = "Fault_" + reagobj.getString("neType") + "_" + reagobj.getString("alarmTitle") + "Cleared"; + + if ("1".equals(origSeverity)) { + severity = EVEL_SEVERITIES.EVEL_SEVERITY_CRITICAL; + pri = EvelHeader.PRIORITIES.EVEL_PRIORITY_HIGH; + } else if ("2".equals(origSeverity)) { + severity = EVEL_SEVERITIES.EVEL_SEVERITY_MAJOR; + pri = EvelHeader.PRIORITIES.EVEL_PRIORITY_MEDIUM; + } else if ("3".equals(origSeverity)) { + severity = EVEL_SEVERITIES.EVEL_SEVERITY_MINOR; + pri = EvelHeader.PRIORITIES.EVEL_PRIORITY_NORMAL; + } else if ("4".equals(origSeverity)) { + severity = EVEL_SEVERITIES.EVEL_SEVERITY_WARNING; + pri = EvelHeader.PRIORITIES.EVEL_PRIORITY_LOW; + + } + } else { + status = EVEL_VF_STATUSES.EVEL_VF_STATUS_ACTIVE; + eventName = "Fault_" + reagobj.getString("neType") + "_" + reagobj.getString("alarmTitle"); + pri = EvelHeader.PRIORITIES.EVEL_PRIORITY_NORMAL; + severity = EVEL_SEVERITIES.EVEL_SEVERITY_NORMAL; + } + + String evnId = reagobj.getString("alarmId"); + String alarmCondition = reagobj.getString("specificProblem"); + + String specificProblem = reagobj.getString("specificProblem"); + + EvelFault flt = new EvelFault(eventName, evnId, alarmCondition, + specificProblem, pri, severity, + EVEL_SOURCE_TYPES.EVEL_SOURCE_VIRTUAL_NETWORK_FUNCTION, + status); + flt.evel_nfcnamingcode_set(""); + flt.evel_nfnamingcode_set(""); + flt.evel_header_type_set("applicationVnf"); + String eventTime = reagobj.getString("eventTime"); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date eventTimeD = new Date(); + try { + eventTimeD = format.parse(eventTime); + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + flt.evel_start_epoch_set(eventTimeD.getTime()); + flt.evel_last_epoch_set(eventTimeD.getTime()); + + flt.evel_fault_category_set(reagobj.getString("alarmType")); + flt.evel_fault_interface_set(reagobj.getString("objectName")); + String neUID = reagobj.getString("neUID"); + flt.evel_reporting_entity_id_set(neUID.substring(0, 9));// + flt.evel_reporting_entity_name_set(neUID.substring(0, 9)); + flt.evel_header_set_sourceid(true, reagobj.getString("neName")); + flt.evel_header_set_source_name(reagobj.getString("objectName")); + + flt.evel_header_set_priority(pri); + for (String key : reagobj.keySet()) { + flt.evel_fault_addl_info_add(key, reagobj.getString(key)); + } + + return flt; + } + } + + class ResultMessageRecv extends Thread { + long timeStamp = System.currentTimeMillis(); + + public void run() { + while (!threadStop) { + + try { + if (System.currentTimeMillis() - timeStamp > Constant.ONEMINUTE) { + timeStamp = System.currentTimeMillis(); + + log.debug("COLLECT_RESULT_CHANNEL Msg size :" + collectResultChannel.size()); + } + + Object obj = collectResultChannel.poll(); + if (obj == null) { + continue; + } + if (obj instanceof String) { + //http + Properties properties = configurationInterface.getProperties(); + String msbAddress = properties.getProperty("msbAddress"); + String url = properties.getProperty("dataNotifyUrl"); + String postUrl = "http://" + msbAddress + url; + HttpClientUtil.doPost(postUrl, (String) obj, Constant.ENCODING_UTF8); + } + + } catch (Exception e) { + log.error("ResultMessageRecv exception", e); + } + } + } + } + + class CollectMessageRecv extends Thread { + long timeStamp = System.currentTimeMillis(); + + public void run() { + log.info("CollectMessageRecv Thread is start threadStop=" + threadStop); + while (!threadStop) { + + try { + if (System.currentTimeMillis() - timeStamp > Constant.ONEMINUTE) { + timeStamp = System.currentTimeMillis(); + + log.debug(Constant.COLLECT_RESULT_PM_CHANNEL_KEY + " Msg size :" + collectResultPMChannel.size()); + } + + Object obj = collectResultPMChannel.poll(); + if (obj == null) { + continue; + } + if (obj instanceof Map) { + @SuppressWarnings("unchecked") + Map<String, String> reMap = (Map<String, String>) obj; + log.debug("reMap =" + reMap); + EvelScalingMeasurement evelScalingMeasurement = this.resultEvelScalingMeasurement(reMap); + log.debug("evelScalingMeasurement=" + evelScalingMeasurement); + //send + log.info("AgentMain.evel_post_event start"); + AgentMain.evel_post_event(evelScalingMeasurement); + log.info("AgentMain.evel_post_event sucess"); + + } else { + log.error("CollectMessageRecv receive Object = " + obj); + } + + } catch (Exception e) { + log.error("CollectMessageRecv exception", e); + } catch (Error e) { + log.error("CollectMessageRecv Error", e); + } + } + } + + private EvelScalingMeasurement resultEvelScalingMeasurement(Map<String, String> reMap) { + String evname = "Mfvs_" + reMap.get("ElementType") + reMap.get("ObjectType"); + String evid = reMap.get("StartTime") + reMap.get("ObjectType") + reMap.get("rmUID"); + int Period = Integer.parseInt(reMap.get("Period") != null ? reMap.get("Period") : "15"); + EvelScalingMeasurement sm = new EvelScalingMeasurement(Period, evname, evid); + + for (String key : reMap.keySet()) { + sm.evel_measurement_custom_measurement_add(reMap.get("ElementType"), key, reMap.get(key)); + + } + + sm.evel_nfcnamingcode_set(""); + sm.evel_nfnamingcode_set(""); + sm.evel_header_type_set("applicationVnf"); + String rmUID = reMap.get("rmUID"); + sm.evel_reporting_entity_id_set(rmUID.substring(0, 9));// + String Dn = reMap.get("Dn"); + if (Dn != null) + sm.evel_reporting_entity_name_set(Dn.substring(0, Dn != null && Dn.indexOf(";") > 0 ? Dn.indexOf(";") : Dn.length())); + else { + // decide the flow if Dn is null + + } + sm.evel_header_set_sourceid(true, reMap.get("rmUID")); + sm.evel_header_set_source_name(reMap.get("rmUID")); + + sm.evel_header_set_priority(EvelHeader.PRIORITIES.EVEL_PRIORITY_NORMAL); + return sm; + } + } -public class NorthMessageMgr extends DriverThread{ - - private MessageChannel alarmChannel = MessageChannelFactory.getMessageChannel(Constant.RESULT_CHANNEL_KEY); - private MessageChannel collectResultPMChannel = MessageChannelFactory.getMessageChannel(Constant.COLLECT_RESULT_PM_CHANNEL_KEY); - private MessageChannel collectResultChannel = MessageChannelFactory.getMessageChannel(Constant.COLLECT_RESULT_CHANNEL_KEY); - private ConfigurationInterface configurationInterface ; - - private boolean threadStop = false; - private Level level = Level.DEBUG; - - @Override - public void dispose() { - log.info("NorthMessageMgr Thread start threadStop="+threadStop); - try { - Properties properties = configurationInterface.getProperties(); - String event_api_url = properties.getProperty("event_api_url"); - String port = properties.getProperty("port"); - String path = properties.getProperty("path"); - String topic = properties.getProperty("topic"); - String username = properties.getProperty("username"); - String password = properties.getProperty("password"); - String levelStr = properties.getProperty("level"); - if("debug".equals(levelStr)){ - level = Level.DEBUG; - }else{ - level = Level.INFO; - } - - //login north - event_api_url = "http://"+event_api_url; - log.info("AgentMain.evel_initialize start event_api_url=["+event_api_url+"]port=["+port+"]path=["+path+"]" - + "topic=["+topic+"]username=["+username+"]password=["+password+"]level=["+level+"]"); - try{ - EVEL_ERR_CODES evecode = AgentMain.evel_initialize(event_api_url, Integer.parseInt(port), - path,topic, - username, - password, - level); - log.info("AgentMain.evel_initialize sucess EVEL_ERR_CODES="+evecode); - } catch( Exception e ){ - log.error("AgentMain.evel_initialize fail ",e); - }catch( Error e1 ){ - log.error("AgentMain.evel_initialize Error ",e1); - } - } catch (Exception e2) { - log.error("NorthMessageMgr start fail ",e2); - } - - new HeatBeatTread().start(); - // - new AlarmMessageRecv().start(); - - new ResultMessageRecv().start(); - - new CollectMessageRecv().start(); - - log.info("NorthMessageMgr start sucess "); - } - - - class HeatBeatTread extends Thread{ - - public void run() { - - while(!threadStop){ - - try { - EvelHeader header = EvelHeader.evel_new_heartbeat("Hearbeat_EMS","EMS-driver"); - header.evel_nfnamingcode_set("EMS-driver"); - header.evel_nfcnamingcode_set("EMS-driver"); - AgentMain.evel_post_event(header); - log.info("HeatBeat send!"); - try { - Thread.sleep(60*1000); - } catch( Exception e ){ - e.printStackTrace(); - } - } catch (Exception e) { - log.error("HeatBeatTread exception",e); - } - } - } - } - - class AlarmMessageRecv extends Thread{ - long timeStamp = System.currentTimeMillis(); - - public void run() { - while(!threadStop){ - - try { - if(System.currentTimeMillis() - timeStamp > Constant.ONEMINUTE){ - timeStamp = System.currentTimeMillis(); - - log.info("ALARM_CHANNEL Msg size :"+alarmChannel.size()); - } - - Object obj = alarmChannel.poll(); - if(obj == null){ - continue; - } - if(obj instanceof String){ - String result = (String)obj; - JSONObject reagobj = JSONObject.parseObject(result); - - EvelFault evelFault = this.resultEvelFault(reagobj); - - //send - log.info("AgentMain.evel_post_event alarm start"); - AgentMain.evel_post_event(evelFault); - log.info("AgentMain.evel_post_event alarm sucess"); - }else{ - log.error("AlarmMessageRecv receive Object = "+obj); - } - - } catch (Exception e) { - log.error("AlarmMessageRecv exception",e); - } - } - } - - private EvelFault resultEvelFault(JSONObject reagobj) { - - String eventName = null; - EvelHeader.PRIORITIES pri = null; - EVEL_SEVERITIES severity = null; - EVEL_VF_STATUSES status = null; - String alarmStatus = reagobj.getString("alarmStatus"); - String origSeverity = reagobj.getString("origSeverity"); - if("0".equals(alarmStatus)){ - status = EVEL_VF_STATUSES.EVEL_VF_STATUS_IDLE; - eventName = "Fault_"+reagobj.getString("neType")+"_"+reagobj.getString("alarmTitle")+"Cleared"; - - if("1".equals(origSeverity)){ - severity = EVEL_SEVERITIES.EVEL_SEVERITY_CRITICAL; - pri = EvelHeader.PRIORITIES.EVEL_PRIORITY_HIGH; - }else if("2".equals(origSeverity)){ - severity = EVEL_SEVERITIES.EVEL_SEVERITY_MAJOR; - pri = EvelHeader.PRIORITIES.EVEL_PRIORITY_MEDIUM; - }else if("3".equals(origSeverity)){ - severity = EVEL_SEVERITIES.EVEL_SEVERITY_MINOR; - pri = EvelHeader.PRIORITIES.EVEL_PRIORITY_NORMAL; - }else if("4".equals(origSeverity)){ - severity = EVEL_SEVERITIES.EVEL_SEVERITY_WARNING; - pri = EvelHeader.PRIORITIES.EVEL_PRIORITY_LOW; - - } - }else{ - status = EVEL_VF_STATUSES.EVEL_VF_STATUS_ACTIVE; - eventName = "Fault_"+reagobj.getString("neType")+"_"+reagobj.getString("alarmTitle"); - pri = EvelHeader.PRIORITIES.EVEL_PRIORITY_NORMAL; - severity = EVEL_SEVERITIES.EVEL_SEVERITY_NORMAL; - } - - String evnId = reagobj.getString("alarmId"); - String alarmCondition = reagobj.getString("specificProblem"); - - String specificProblem = reagobj.getString("specificProblem"); - - EvelFault flt = new EvelFault(eventName, evnId,alarmCondition, - specificProblem,pri,severity, - EVEL_SOURCE_TYPES.EVEL_SOURCE_VIRTUAL_NETWORK_FUNCTION, - status); - flt.evel_nfcnamingcode_set(""); - flt.evel_nfnamingcode_set(""); - flt.evel_header_type_set("applicationVnf"); - String eventTime = reagobj.getString("eventTime"); - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - Date eventTimeD = new Date(); - try { - eventTimeD = format.parse(eventTime); - } catch (ParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - flt.evel_start_epoch_set(eventTimeD.getTime()); - flt.evel_last_epoch_set(eventTimeD.getTime()); - - flt.evel_fault_category_set(reagobj.getString("alarmType")); - flt.evel_fault_interface_set(reagobj.getString("objectName")); - String neUID = reagobj.getString("neUID"); - flt.evel_reporting_entity_id_set(neUID.substring(0,9));// - flt.evel_reporting_entity_name_set(neUID.substring(0,9)); - flt.evel_header_set_sourceid(true, reagobj.getString("neName")); - flt.evel_header_set_source_name(reagobj.getString("objectName")); - - flt.evel_header_set_priority(pri); - for(String key : reagobj.keySet()){ - flt.evel_fault_addl_info_add(key, reagobj.getString(key)); - } - - return flt; - } - } - - class ResultMessageRecv extends Thread{ - long timeStamp = System.currentTimeMillis(); - - public void run() { - while(!threadStop){ - - try { - if(System.currentTimeMillis() - timeStamp > Constant.ONEMINUTE){ - timeStamp = System.currentTimeMillis(); - - log.debug("COLLECT_RESULT_CHANNEL Msg size :"+collectResultChannel.size()); - } - - Object obj = collectResultChannel.poll(); - if(obj == null){ - continue; - } - if(obj instanceof String){ - //http - Properties properties = configurationInterface.getProperties(); - String msbAddress = properties.getProperty("msbAddress"); - String url = properties.getProperty("dataNotifyUrl"); - String postUrl = "http://"+msbAddress+url; - HttpClientUtil.doPost(postUrl, (String)obj, Constant.ENCODING_UTF8); - } - - } catch (Exception e) { - log.error("ResultMessageRecv exception",e); - } - } - } - } - - class CollectMessageRecv extends Thread{ - long timeStamp = System.currentTimeMillis(); - - public void run() { - log.info("CollectMessageRecv Thread is start threadStop="+threadStop); - while(!threadStop){ - - try { - if(System.currentTimeMillis() - timeStamp > Constant.ONEMINUTE){ - timeStamp = System.currentTimeMillis(); - - log.debug(Constant.COLLECT_RESULT_PM_CHANNEL_KEY+" Msg size :"+collectResultPMChannel.size()); - } - - Object obj = collectResultPMChannel.poll(); - if(obj == null){ - continue; - } - if(obj instanceof Map){ - @SuppressWarnings("unchecked") - Map<String,String> reMap = (Map<String,String>)obj; - log.debug("reMap ="+reMap); - EvelScalingMeasurement evelScalingMeasurement = this.resultEvelScalingMeasurement(reMap); - log.debug("evelScalingMeasurement="+evelScalingMeasurement); - //send - log.info("AgentMain.evel_post_event start"); - AgentMain.evel_post_event(evelScalingMeasurement); - log.info("AgentMain.evel_post_event sucess"); - - }else{ - log.error("CollectMessageRecv receive Object = "+obj); - } - - } catch (Exception e) { - log.error("CollectMessageRecv exception",e); - }catch (Error e) { - log.error("CollectMessageRecv Error",e); - } - } - } - - private EvelScalingMeasurement resultEvelScalingMeasurement(Map<String,String> reMap) { - String evname = "Mfvs_"+reMap.get("ElementType")+reMap.get("ObjectType"); - String evid = reMap.get("StartTime")+reMap.get("ObjectType")+reMap.get("rmUID"); - int Period = Integer.parseInt(reMap.get("Period")!=null?reMap.get("Period"):"15"); - EvelScalingMeasurement sm = new EvelScalingMeasurement(Period,evname, evid); - - for(String key : reMap.keySet()){ - sm.evel_measurement_custom_measurement_add(reMap.get("ElementType"), key, reMap.get(key)); - - } - - sm.evel_nfcnamingcode_set(""); - sm.evel_nfnamingcode_set(""); - sm.evel_header_type_set("applicationVnf"); - String rmUID = reMap.get("rmUID"); - sm.evel_reporting_entity_id_set(rmUID.substring(0,9));// - String Dn = reMap.get("Dn"); - if(Dn!=null) - sm.evel_reporting_entity_name_set(Dn.substring(0, Dn != null && Dn.indexOf(";")>0?Dn.indexOf(";"):Dn.length())); - else - { - // decide the flow if Dn is null - - } - sm.evel_header_set_sourceid(true, reMap.get("rmUID")); - sm.evel_header_set_source_name(reMap.get("rmUID")); - - sm.evel_header_set_priority(EvelHeader.PRIORITIES.EVEL_PRIORITY_NORMAL); - return sm; - } - } - - /** - * @return the configurationInterface - */ - public ConfigurationInterface getConfigurationInterface() { - return configurationInterface; - } - - /** - * @param configurationInterface the configurationInterface to set - */ - public void setConfigurationInterface( - ConfigurationInterface configurationInterface) { - this.configurationInterface = configurationInterface; - } - } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/northbound/service/CommandResource.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/northbound/service/CommandResource.java index 44c23b4..93a6ea8 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/northbound/service/CommandResource.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/northbound/service/CommandResource.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,6 +15,7 @@ */ package org.onap.vfc.nfvo.emsdriver.northbound.service; +import com.codahale.metrics.annotation.Timed; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @@ -23,9 +24,6 @@ import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import com.codahale.metrics.annotation.Timed; @Path("/ems-driver") @Produces(MediaType.APPLICATION_JSON) @@ -38,8 +36,8 @@ public class CommandResource { @ApiOperation(value = "get ems-driver Info") public String executeCommand(@QueryParam("command") String command) { - System.out.println("receiver command = "+command); + System.out.println("receiver command = " + command); return command; } - + } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/serviceregister/MsbConfiguration.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/serviceregister/MsbConfiguration.java index 9d30de6..bc57fb8 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/serviceregister/MsbConfiguration.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/serviceregister/MsbConfiguration.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,14 +16,14 @@ package org.onap.vfc.nfvo.emsdriver.serviceregister; public class MsbConfiguration { - protected static String msbAddress; + protected static String msbAddress; - public static String getMsbAddress() { - return msbAddress; - } + public static String getMsbAddress() { + return msbAddress; + } + + public static void setMsbAddress(String msbAddress) { + MsbConfiguration.msbAddress = "http://" + msbAddress; + } - public static void setMsbAddress(String msbAddress) { - MsbConfiguration.msbAddress ="http://"+ msbAddress; - } - } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/serviceregister/MsbRestServiceProxy.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/serviceregister/MsbRestServiceProxy.java index 1e0693c..437744c 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/serviceregister/MsbRestServiceProxy.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/serviceregister/MsbRestServiceProxy.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,46 +16,45 @@ package org.onap.vfc.nfvo.emsdriver.serviceregister; -import java.util.ArrayList; -import java.util.List; - +import com.alibaba.fastjson.JSON; import org.onap.vfc.nfvo.emsdriver.commons.constant.Constant; import org.onap.vfc.nfvo.emsdriver.northbound.client.HttpClientUtil; import org.onap.vfc.nfvo.emsdriver.serviceregister.model.MsbRegisterVo; import org.onap.vfc.nfvo.emsdriver.serviceregister.model.ServiceNodeVo; -import com.alibaba.fastjson.JSON; +import java.util.ArrayList; +import java.util.List; public class MsbRestServiceProxy { - public static String registerService(MsbRegisterVo registerInfo){ - String url = MsbConfiguration.getMsbAddress()+Constant.MSBAPIROOTDOMAIN; - String registerObj = JSON.toJSONString(registerInfo); - - String registerResponse = HttpClientUtil.doPost(url, registerObj, Constant.ENCODING_UTF8); + public static String registerService(MsbRegisterVo registerInfo) { + String url = MsbConfiguration.getMsbAddress() + Constant.MSBAPIROOTDOMAIN; + String registerObj = JSON.toJSONString(registerInfo); + + String registerResponse = HttpClientUtil.doPost(url, registerObj, Constant.ENCODING_UTF8); return registerResponse; } - public static void unRegiserService(String serviceName,String version,String ip,String port){ - String url = MsbConfiguration.getMsbAddress()+Constant.MSBAPIROOTDOMAIN+"/"+serviceName+"/version/"+version+"/nodes/"+ip+"/"+port; + public static void unRegiserService(String serviceName, String version, String ip, String port) { + String url = MsbConfiguration.getMsbAddress() + Constant.MSBAPIROOTDOMAIN + "/" + serviceName + "/version/" + version + "/nodes/" + ip + "/" + port; HttpClientUtil.doDelete(url, Constant.ENCODING_UTF8); } - - public static List<String> queryService(String serviceName,String version){ - List<String> ipList = new ArrayList<String>(); - String url = MsbConfiguration.getMsbAddress()+Constant.MSBAPIROOTDOMAIN+"/"+serviceName+"/version/"+version; - String response = HttpClientUtil.doGet(url, Constant.ENCODING_UTF8); - if(response !=null && !"".equals(response)){ - MsbRegisterVo msbRegisterVo = JSON.parseObject(response,MsbRegisterVo.class); - List<ServiceNodeVo> nodeList = msbRegisterVo.getNodes(); - - for(ServiceNodeVo node :nodeList){ - String ip = node.getIp(); - ipList.add(ip); - } - } - return ipList; - + + public static List<String> queryService(String serviceName, String version) { + List<String> ipList = new ArrayList<String>(); + String url = MsbConfiguration.getMsbAddress() + Constant.MSBAPIROOTDOMAIN + "/" + serviceName + "/version/" + version; + String response = HttpClientUtil.doGet(url, Constant.ENCODING_UTF8); + if (response != null && !"".equals(response)) { + MsbRegisterVo msbRegisterVo = JSON.parseObject(response, MsbRegisterVo.class); + List<ServiceNodeVo> nodeList = msbRegisterVo.getNodes(); + + for (ServiceNodeVo node : nodeList) { + String ip = node.getIp(); + ipList.add(ip); + } + } + return ipList; + } } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/serviceregister/model/MsbRegisterVo.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/serviceregister/model/MsbRegisterVo.java index c3f8fd1..c828fce 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/serviceregister/model/MsbRegisterVo.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/serviceregister/model/MsbRegisterVo.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -19,87 +19,97 @@ import java.util.List; public class MsbRegisterVo { - private String serviceName = "emsdriver"; - private String version = "v1"; - private String url = "/api/emsdriver/v1"; - private String protocol = "REST"; - private String visualRange = "1"; - private List<ServiceNodeVo> nodes; - - - /** - * @return the serviceName - */ - public String getServiceName() { - return serviceName; - } - /** - * @param serviceName the serviceName to set - */ - public void setServiceName(String serviceName) { - this.serviceName = serviceName; - } - /** - * @return the version - */ - public String getVersion() { - return version; - } - /** - * @param version the version to set - */ - public void setVersion(String version) { - this.version = version; - } - /** - * @return the url - */ - public String getUrl() { - return url; - } - /** - * @param url the url to set - */ - public void setUrl(String url) { - this.url = url; - } - /** - * @return the protocol - */ - public String getProtocol() { - return protocol; - } - /** - * @param protocol the protocol to set - */ - public void setProtocol(String protocol) { - this.protocol = protocol; - } - /** - * @return the visualRange - */ - public String getVisualRange() { - return visualRange; - } - /** - * @param visualRange the visualRange to set - */ - public void setVisualRange(String visualRange) { - this.visualRange = visualRange; - } - /** - * @return the nodes - */ - public List<ServiceNodeVo> getNodes() { - return nodes; - } - /** - * @param nodes the nodes to set - */ - public void setNodes(List<ServiceNodeVo> nodes) { - this.nodes = nodes; - } - - - + private String serviceName = "emsdriver"; + private String version = "v1"; + private String url = "/api/emsdriver/v1"; + private String protocol = "REST"; + private String visualRange = "1"; + private List<ServiceNodeVo> nodes; + + + /** + * @return the serviceName + */ + public String getServiceName() { + return serviceName; + } + + /** + * @param serviceName the serviceName to set + */ + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + /** + * @return the version + */ + public String getVersion() { + return version; + } + + /** + * @param version the version to set + */ + public void setVersion(String version) { + this.version = version; + } + + /** + * @return the url + */ + public String getUrl() { + return url; + } + + /** + * @param url the url to set + */ + public void setUrl(String url) { + this.url = url; + } + + /** + * @return the protocol + */ + public String getProtocol() { + return protocol; + } + + /** + * @param protocol the protocol to set + */ + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + /** + * @return the visualRange + */ + public String getVisualRange() { + return visualRange; + } + + /** + * @param visualRange the visualRange to set + */ + public void setVisualRange(String visualRange) { + this.visualRange = visualRange; + } + + /** + * @return the nodes + */ + public List<ServiceNodeVo> getNodes() { + return nodes; + } + + /** + * @param nodes the nodes to set + */ + public void setNodes(List<ServiceNodeVo> nodes) { + this.nodes = nodes; + } + + } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/serviceregister/model/ServiceNodeVo.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/serviceregister/model/ServiceNodeVo.java index e716287..1708d27 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/serviceregister/model/ServiceNodeVo.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/serviceregister/model/ServiceNodeVo.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -17,46 +17,51 @@ package org.onap.vfc.nfvo.emsdriver.serviceregister.model; public class ServiceNodeVo { - private String ip; - private String port; - private int ttl; - - /** - * @return the ip - */ - public String getIp() { - return ip; - } - /** - * @param ip the ip to set - */ - public void setIp(String ip) { - this.ip = ip; - } - /** - * @return the port - */ - public String getPort() { - return port; - } - /** - * @param port the port to set - */ - public void setPort(String port) { - this.port = port; - } - /** - * @return the ttl - */ - public int getTtl() { - return ttl; - } - /** - * @param ttl the ttl to set - */ - public void setTtl(int ttl) { - this.ttl = ttl; - } - - + private String ip; + private String port; + private int ttl; + + /** + * @return the ip + */ + public String getIp() { + return ip; + } + + /** + * @param ip the ip to set + */ + public void setIp(String ip) { + this.ip = ip; + } + + /** + * @return the port + */ + public String getPort() { + return port; + } + + /** + * @param port the port to set + */ + public void setPort(String port) { + this.port = port; + } + + /** + * @return the ttl + */ + public int getTtl() { + return ttl; + } + + /** + * @param ttl the ttl to set + */ + public void setTtl(int ttl) { + this.ttl = ttl; + } + + } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/taskscheduler/CollectManager.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/taskscheduler/CollectManager.java index f21f2fb..ee0368f 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/taskscheduler/CollectManager.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/taskscheduler/CollectManager.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,9 +15,6 @@ */ package org.onap.vfc.nfvo.emsdriver.taskscheduler; -import java.util.ArrayList; -import java.util.List; - import org.onap.vfc.nfvo.emsdriver.commons.constant.Constant; import org.onap.vfc.nfvo.emsdriver.commons.model.CollectVo; import org.onap.vfc.nfvo.emsdriver.commons.model.EMSInfo; @@ -25,88 +22,91 @@ import org.onap.vfc.nfvo.emsdriver.commons.utils.DriverThread; import org.onap.vfc.nfvo.emsdriver.configmgr.ConfigurationInterface; import org.quartz.Job; +import java.util.ArrayList; +import java.util.List; + + +public class CollectManager extends DriverThread { + + private ConfigurationInterface configurationInterface; + + public void dispose() { + if (configurationInterface != null) { + List<EMSInfo> emsInfos = configurationInterface.getAllEMSInfo(); + while (isRun() && emsInfos.size() == 0) { + + emsInfos = configurationInterface.getAllEMSInfo(); + if (emsInfos.size() == 0) { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + } + } + + } + + List<CollectVo> collectVos = new ArrayList<CollectVo>(); + for (EMSInfo emsInfo : emsInfos) { + //cm + CollectVo CollectVoCm = emsInfo.getCollectVoByType(Constant.COLLECT_TYPE_CM); + if (CollectVoCm != null) { + CollectVoCm.setEmsName(emsInfo.getName()); + collectVos.add(CollectVoCm); + } + + //pm + CollectVo CollectVoPm = emsInfo.getCollectVoByType(Constant.COLLECT_TYPE_PM); + if (CollectVoPm != null) { + CollectVoPm.setEmsName(emsInfo.getName()); + collectVos.add(CollectVoPm); + } + + } + if (collectVos.size() > 0) { + this.addCollectJob(collectVos); + log.info("1 addCollectJob is OK "); + } else { + log.error("collectVos size is 0"); + } + + } else { + log.error("configurationInterface = null,check spring.xml"); + } + } + + private void addCollectJob(List<CollectVo> collectVos) { + for (CollectVo collectVo : collectVos) { + try { + String jobName = collectVo.getEmsName() + "_" + collectVo.getType() + collectVo.getIP(); + Job job = new CollectOderJob(); + String jobClass = job.getClass().getName(); + String time = collectVo.getCrontab(); + if (time != null && !"".equals(time)) { + QuartzManager.addJob(jobName, jobClass, time, collectVo); + } else { + log.error("type =[" + collectVo.getType() + "]ip=[" + collectVo.getIP() + "] crontab is null,check EMSInfo.xml"); + } + + } catch (Exception e) { + log.error("addJob is error", e); + } + } + } + + /** + * @return the configurationInterface + */ + public ConfigurationInterface getConfigurationInterface() { + return configurationInterface; + } + + /** + * @param configurationInterface the configurationInterface to set + */ + public void setConfigurationInterface( + ConfigurationInterface configurationInterface) { + this.configurationInterface = configurationInterface; + } -public class CollectManager extends DriverThread{ - - private ConfigurationInterface configurationInterface; - public void dispose() { - if(configurationInterface != null){ - List<EMSInfo> emsInfos = configurationInterface.getAllEMSInfo(); - while(isRun() && emsInfos.size() == 0){ - - emsInfos = configurationInterface.getAllEMSInfo(); - if(emsInfos.size() == 0){ - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - } - } - - } - - List<CollectVo> collectVos = new ArrayList<CollectVo>(); - for(EMSInfo emsInfo : emsInfos){ - //cm - CollectVo CollectVoCm = emsInfo.getCollectVoByType(Constant.COLLECT_TYPE_CM); - if(CollectVoCm != null){ - CollectVoCm.setEmsName(emsInfo.getName()); - collectVos.add(CollectVoCm); - } - - //pm - CollectVo CollectVoPm = emsInfo.getCollectVoByType(Constant.COLLECT_TYPE_PM); - if(CollectVoPm != null){ - CollectVoPm.setEmsName(emsInfo.getName()); - collectVos.add(CollectVoPm); - } - - } - if(collectVos.size() > 0){ - this.addCollectJob(collectVos); - log.info("1 addCollectJob is OK "); - }else{ - log.error("collectVos size is 0"); - } - - }else{ - log.error("configurationInterface = null,check spring.xml"); - } - } - - private void addCollectJob(List<CollectVo> collectVos) { - for(CollectVo collectVo : collectVos){ - try { - String jobName = collectVo.getEmsName()+"_"+collectVo.getType()+collectVo.getIP(); - Job job = new CollectOderJob(); - String jobClass = job.getClass().getName(); - String time = collectVo.getCrontab(); - if(time != null && !"".equals(time)){ - QuartzManager.addJob(jobName, jobClass, time,collectVo); - }else{ - log.error("type =["+collectVo.getType()+"]ip=["+collectVo.getIP()+"] crontab is null,check EMSInfo.xml"); - } - - } catch (Exception e) { - log.error("addJob is error",e); - } - } - } - - /** - * @return the configurationInterface - */ - public ConfigurationInterface getConfigurationInterface() { - return configurationInterface; - } - - /** - * @param configurationInterface the configurationInterface to set - */ - public void setConfigurationInterface( - ConfigurationInterface configurationInterface) { - this.configurationInterface = configurationInterface; - } - - } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/taskscheduler/CollectOderJob.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/taskscheduler/CollectOderJob.java index 0cffb3a..71ceb63 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/taskscheduler/CollectOderJob.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/taskscheduler/CollectOderJob.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -28,30 +28,30 @@ import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; -public class CollectOderJob implements Job { - - private Log log = LogFactory.getLog(DriverThread.class); - private MessageChannel collectChannel = MessageChannelFactory.getMessageChannel(Constant.COLLECT_CHANNEL_KEY); - - public void execute(JobExecutionContext context) throws JobExecutionException { - // TODO Auto-generated method stub - CollectVo collectVo = (CollectVo)context.getJobDetail().getJobDataMap().get("collectVo"); - if(collectVo != null){ - CollectMsg collectMsg = new CollectMsg(); - collectMsg.setEmsName(collectVo.getEmsName()); - collectMsg.setId(System.nanoTime()); - collectMsg.setType(collectVo.getType()); - - try { - collectChannel.put(collectMsg); - } catch (InterruptedException e) { - log.error("collectChannel.put is error ",e); - } - }else{ - log.error("collectVo is null, collectMsg is not created! "); - } - - - } +public class CollectOderJob implements Job { + + private Log log = LogFactory.getLog(DriverThread.class); + private MessageChannel collectChannel = MessageChannelFactory.getMessageChannel(Constant.COLLECT_CHANNEL_KEY); + + public void execute(JobExecutionContext context) throws JobExecutionException { + // TODO Auto-generated method stub + CollectVo collectVo = (CollectVo) context.getJobDetail().getJobDataMap().get("collectVo"); + if (collectVo != null) { + CollectMsg collectMsg = new CollectMsg(); + collectMsg.setEmsName(collectVo.getEmsName()); + collectMsg.setId(System.nanoTime()); + collectMsg.setType(collectVo.getType()); + + try { + collectChannel.put(collectMsg); + } catch (InterruptedException e) { + log.error("collectChannel.put is error ", e); + } + } else { + log.error("collectVo is null, collectMsg is not created! "); + } + + + } } diff --git a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/taskscheduler/QuartzManager.java b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/taskscheduler/QuartzManager.java index ca62dc0..c182c2a 100644 --- a/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/taskscheduler/QuartzManager.java +++ b/ems/boco/src/main/java/org/onap/vfc/nfvo/emsdriver/taskscheduler/QuartzManager.java @@ -1,12 +1,12 @@ /** * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd - * + * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * <p> + * http://www.apache.org/licenses/LICENSE-2.0 + * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,148 +16,141 @@ package org.onap.vfc.nfvo.emsdriver.taskscheduler; -import java.text.ParseException; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.onap.vfc.nfvo.emsdriver.commons.model.CollectVo; -import org.quartz.CronTrigger; -import org.quartz.Job; -import org.quartz.JobDetail; -import org.quartz.Scheduler; -import org.quartz.SchedulerException; -import org.quartz.SchedulerFactory; +import org.quartz.*; import org.quartz.impl.StdSchedulerFactory; +import java.text.ParseException; + public class QuartzManager { - private static Log log = LogFactory.getFactory().getInstance(QuartzManager.class); - private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory(); - private static String JOB_GROUP_NAME = "EXTJWEB_JOBGROUP_NAME"; - private static String TRIGGER_GROUP_NAME = "EXTJWEB_TRIGGERGROUP_NAME"; - - /** - * @param jobName - * @param job - * @param time - * @throws SchedulerException - * @throws ParseException - */ - public static boolean addJob(String jobName, String jobClass, String time,CollectVo collectVo) { - boolean sucess = false; - try { - Scheduler sched = gSchedulerFactory.getScheduler(); - JobDetail jobDetail = new JobDetail(jobName, JOB_GROUP_NAME, Class.forName(jobClass)); - - CronTrigger trigger = new CronTrigger(jobName, TRIGGER_GROUP_NAME); - trigger.setCronExpression(time); - - jobDetail.getJobDataMap().put("collectVo", collectVo); - sched.scheduleJob(jobDetail, trigger); - if (!sched.isShutdown()){ - sched.start(); - - } - sucess = true; - log.info("add job sucess cronExpression="+time); - } catch (Exception e) { - log.error("add job fail cronExpression="+time,e); - sucess = false; - } - return sucess; - } - - - - /** - * @param jobName - * @param time - */ - @SuppressWarnings("unchecked") - public static boolean modifyJobTime(String jobName, String time,CollectVo collectVo) { - boolean sucess = false; - try { - Scheduler sched = gSchedulerFactory.getScheduler(); - CronTrigger trigger = (CronTrigger) sched.getTrigger(jobName, TRIGGER_GROUP_NAME); - if(trigger == null) { - return false; - } - String oldTime = trigger.getCronExpression(); - if (!oldTime.equalsIgnoreCase(time)) { - JobDetail jobDetail = sched.getJobDetail(jobName, JOB_GROUP_NAME); - - Class<Job> objJobClass = jobDetail.getJobClass(); - String jobClass = objJobClass.getName(); - removeJob(jobName); - - addJob(jobName, jobClass, time,collectVo); - } - sucess = true; - } catch (Exception e) { - log.error("modifyJobTime fail cronExpression="+time,e); - sucess = false; - } - return sucess ; - } - - /** - - - /** - * @param jobName - */ - public static boolean removeJob(String jobName) { - boolean sucess = false; - try { - Scheduler sched = gSchedulerFactory.getScheduler(); - sched.pauseTrigger(jobName, TRIGGER_GROUP_NAME); - sched.unscheduleJob(jobName, TRIGGER_GROUP_NAME); - sched.deleteJob(jobName, JOB_GROUP_NAME); - sucess = true; - } catch (Exception e) { - sucess = false; - log.error("remove job fail jobName="+jobName,e); - } - return sucess; - } - - - - /** - * - * @return - */ - public static boolean startJobs() { - boolean sucess = false; - try { - Scheduler sched = gSchedulerFactory.getScheduler(); - sched.start(); - sucess = true; - } catch (Exception e) { - sucess = false; - log.error("start jobs fail",e); - } - return sucess; - } - - /** - * - * @return - */ - public static boolean shutdownJobs() { - boolean sucess = false; - try { - Scheduler sched = gSchedulerFactory.getScheduler(); - if(!sched.isShutdown()) { - sched.shutdown(); - } - sucess = true; - } catch (Exception e) { - sucess = false; - log.error("shutdown jobs fail ",e); - } - - return sucess; - } + private static Log log = LogFactory.getFactory().getInstance(QuartzManager.class); + private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory(); + private static String JOB_GROUP_NAME = "EXTJWEB_JOBGROUP_NAME"; + private static String TRIGGER_GROUP_NAME = "EXTJWEB_TRIGGERGROUP_NAME"; + + /** + * @param jobName + * @param job + * @param time + * @throws SchedulerException + * @throws ParseException + */ + public static boolean addJob(String jobName, String jobClass, String time, CollectVo collectVo) { + boolean sucess = false; + try { + Scheduler sched = gSchedulerFactory.getScheduler(); + JobDetail jobDetail = new JobDetail(jobName, JOB_GROUP_NAME, Class.forName(jobClass)); + + CronTrigger trigger = new CronTrigger(jobName, TRIGGER_GROUP_NAME); + trigger.setCronExpression(time); + + jobDetail.getJobDataMap().put("collectVo", collectVo); + sched.scheduleJob(jobDetail, trigger); + if (!sched.isShutdown()) { + sched.start(); + + } + sucess = true; + log.info("add job sucess cronExpression=" + time); + } catch (Exception e) { + log.error("add job fail cronExpression=" + time, e); + sucess = false; + } + return sucess; + } + + + /** + * @param jobName + * @param time + */ + @SuppressWarnings("unchecked") + public static boolean modifyJobTime(String jobName, String time, CollectVo collectVo) { + boolean sucess = false; + try { + Scheduler sched = gSchedulerFactory.getScheduler(); + CronTrigger trigger = (CronTrigger) sched.getTrigger(jobName, TRIGGER_GROUP_NAME); + if (trigger == null) { + return false; + } + String oldTime = trigger.getCronExpression(); + if (!oldTime.equalsIgnoreCase(time)) { + JobDetail jobDetail = sched.getJobDetail(jobName, JOB_GROUP_NAME); + + Class<Job> objJobClass = jobDetail.getJobClass(); + String jobClass = objJobClass.getName(); + removeJob(jobName); + + addJob(jobName, jobClass, time, collectVo); + } + sucess = true; + } catch (Exception e) { + log.error("modifyJobTime fail cronExpression=" + time, e); + sucess = false; + } + return sucess; + } + + /** + + + /** + * @param jobName + */ + public static boolean removeJob(String jobName) { + boolean sucess = false; + try { + Scheduler sched = gSchedulerFactory.getScheduler(); + sched.pauseTrigger(jobName, TRIGGER_GROUP_NAME); + sched.unscheduleJob(jobName, TRIGGER_GROUP_NAME); + sched.deleteJob(jobName, JOB_GROUP_NAME); + sucess = true; + } catch (Exception e) { + sucess = false; + log.error("remove job fail jobName=" + jobName, e); + } + return sucess; + } + + + /** + * + * @return + */ + public static boolean startJobs() { + boolean sucess = false; + try { + Scheduler sched = gSchedulerFactory.getScheduler(); + sched.start(); + sucess = true; + } catch (Exception e) { + sucess = false; + log.error("start jobs fail", e); + } + return sucess; + } + + /** + * + * @return + */ + public static boolean shutdownJobs() { + boolean sucess = false; + try { + Scheduler sched = gSchedulerFactory.getScheduler(); + if (!sched.isShutdown()) { + sched.shutdown(); + } + sucess = true; + } catch (Exception e) { + sucess = false; + log.error("shutdown jobs fail ", e); + } + + return sucess; + } } diff --git a/ems/boco/src/test/java/foo/AppTest.java b/ems/boco/src/test/java/foo/AppTest.java index 42d6239..0e993ad 100644 --- a/ems/boco/src/test/java/foo/AppTest.java +++ b/ems/boco/src/test/java/foo/AppTest.java @@ -1,12 +1,12 @@ /** * Copyright 2017 CMCC Technologies Co., Ltd - * + * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * <p> + * http://www.apache.org/licenses/LICENSE-2.0 + * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,32 +23,28 @@ import junit.framework.TestSuite; /** * Unit test for simple App. */ -public class AppTest - extends TestCase -{ +public class AppTest + extends TestCase { /** * Create the test case * * @param testName name of the test case */ - public AppTest( String testName ) - { - super( testName ); + public AppTest(String testName) { + super(testName); } /** * @return the suite of tests being tested */ - public static Test suite() - { - return new TestSuite( AppTest.class ); + public static Test suite() { + return new TestSuite(AppTest.class); } /** * Rigourous Test :-) */ - public void testApp() - { - assertTrue( true ); + public void testApp() { + assertTrue(true); } } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/CollectMsgReceiverThreadTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/CollectMsgReceiverThreadTest.java index a57f0f3..2cfd6a0 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/CollectMsgReceiverThreadTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/CollectMsgReceiverThreadTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -17,35 +17,35 @@ package org.onap.vfc.nfvo.emsdriver.collector; import org.junit.Before; import org.junit.Test; -import org.onap.vfc.nfvo.emsdriver.commons.model.CollectMsg; public class CollectMsgReceiverThreadTest { - CollectMsgReceiverThread col = null; - @Before - public void setUp() { - col = new CollectMsgReceiverThread(); - } - - - @Test - public void dispose() { - new Thread(){ - public void run() { - try { - Thread.sleep(10); - col.setRun(false); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - }.start(); - col.setRun(true); - col.dispose(); - col.getTaskService().stopTask(); - col.getThread_max_num(); - col.setThread_max_num(1); - - } + CollectMsgReceiverThread col = null; + + @Before + public void setUp() { + col = new CollectMsgReceiverThread(); + } + + + @Test + public void dispose() { + new Thread() { + public void run() { + try { + Thread.sleep(10); + col.setRun(false); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + }.start(); + col.setRun(true); + col.dispose(); + col.getTaskService().stopTask(); + col.getThread_max_num(); + col.setThread_max_num(1); + + } } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/TaskThreadServiceTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/TaskThreadServiceTest.java index b22b260..22924f4 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/TaskThreadServiceTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/TaskThreadServiceTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,51 +15,49 @@ */ package org.onap.vfc.nfvo.emsdriver.collector; -import static org.junit.Assert.*; - import org.junit.Before; import org.junit.Test; -import org.onap.vfc.nfvo.emsdriver.collector.TaskThreadService; import org.onap.vfc.nfvo.emsdriver.commons.model.CollectMsg; +import static org.junit.Assert.assertNotNull; + public class TaskThreadServiceTest { - - private TaskThreadService taskThreadService; - private CollectMsg collectMsg; - - @Before - public void setUp() { - collectMsg = new CollectMsg(); - taskThreadService = TaskThreadService.getInstance(1); - } - - @Test - public void add() { - taskThreadService.add(collectMsg); - taskThreadService.size(); - new Thread(){ - public void run() { - try { - Thread.sleep(10); - taskThreadService.stopTask(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - }.start(); - taskThreadService.run(); - - } - @Test - public void receive() { - taskThreadService.add(collectMsg); - CollectMsg collectMsg = taskThreadService.receive(); - - assertNotNull(collectMsg); - } - - - + private TaskThreadService taskThreadService; + private CollectMsg collectMsg; + + @Before + public void setUp() { + collectMsg = new CollectMsg(); + taskThreadService = TaskThreadService.getInstance(1); + } + + @Test + public void add() { + taskThreadService.add(collectMsg); + taskThreadService.size(); + new Thread() { + public void run() { + try { + Thread.sleep(10); + taskThreadService.stopTask(); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + }.start(); + taskThreadService.run(); + + } + + @Test + public void receive() { + taskThreadService.add(collectMsg); + CollectMsg collectMsg = taskThreadService.receive(); + + assertNotNull(collectMsg); + } + + } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/TaskThreadTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/TaskThreadTest.java index f6d2b9b..d6365b6 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/TaskThreadTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/TaskThreadTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,75 +15,76 @@ */ package org.onap.vfc.nfvo.emsdriver.collector; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.IOException; -import java.util.List; - import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.onap.vfc.nfvo.emsdriver.collector.TaskThread; import org.onap.vfc.nfvo.emsdriver.commons.constant.Constant; import org.onap.vfc.nfvo.emsdriver.commons.model.CollectVo; import org.onap.vfc.nfvo.emsdriver.commons.utils.Gzip; import org.onap.vfc.nfvo.emsdriver.messagemgr.MessageChannelFactory; +import java.io.File; +import java.io.IOException; +import java.util.List; + +import static org.junit.Assert.assertTrue; + public class TaskThreadTest { - private String csvPath = System.getProperty("user.dir")+"/data/" +"PM-ENB-EUTRANCELLNB-test.csv"; - private String xmlPath = System.getProperty("user.dir")+"/data/" +"PM-test.xml"; - private String gzPath = System.getProperty("user.dir")+"/data/" +"PM-ENB-EUTRANCELLNB-testa.csv.gz"; - private TaskThread taskThread; - private List<File> list = null; - @Before + private String csvPath = System.getProperty("user.dir") + "/data/" + "PM-ENB-EUTRANCELLNB-test.csv"; + private String xmlPath = System.getProperty("user.dir") + "/data/" + "PM-test.xml"; + private String gzPath = System.getProperty("user.dir") + "/data/" + "PM-ENB-EUTRANCELLNB-testa.csv.gz"; + private TaskThread taskThread; + private List<File> list = null; + + @Before public void setUp() throws IOException { - taskThread = new TaskThread(); - taskThread.pmResultChannel = MessageChannelFactory.getMessageChannel(Constant.COLLECT_RESULT_PM_CHANNEL_KEY); - Gzip gzip = new Gzip(); - gzip.compress(csvPath, gzPath); + taskThread = new TaskThread(); + taskThread.pmResultChannel = MessageChannelFactory.getMessageChannel(Constant.COLLECT_RESULT_PM_CHANNEL_KEY); + Gzip gzip = new Gzip(); + gzip.compress(csvPath, gzPath); + } + + @Test + public void decompressed() { + list = taskThread.decompressed(gzPath); + assertTrue(list.size() > 0); + new File(gzPath).delete(); + } + + @Test + public void processPMCsv() { + list = taskThread.decompressed(gzPath); + for (File file : list) { + boolean re = taskThread.processPMCsv(file); + assertTrue(re); + } + } + + @Test + public void processPMXml() { + File file = new File(xmlPath); + boolean re = taskThread.processPMXml(file); + assertTrue(re); + System.out.println(taskThread.pmResultChannel.size()); + } + + @Test + public void parseFtpAndSendMessage() { + CollectVo collectVo = new CollectVo(); + collectVo.setType("ems-p"); + taskThread.parseFtpAndSendMessage(gzPath, collectVo); + } + + @Test + public void createMessage() { + CollectVo collectVo = new CollectVo(); + collectVo.setType("ems-p"); + taskThread.createMessage("zipName", "user", "pwd", "ip", "port", 122, "nename"); } - - @Test - public void decompressed(){ - list = taskThread.decompressed(gzPath); - assertTrue(list.size() > 0); - new File(gzPath).delete(); - } - @Test - public void processPMCsv(){ - list = taskThread.decompressed(gzPath); - for(File file : list){ - boolean re = taskThread.processPMCsv(file); - assertTrue(re); - } - } - @Test - public void processPMXml(){ - File file = new File(xmlPath); - boolean re = taskThread.processPMXml(file); - assertTrue(re); - System.out.println(taskThread.pmResultChannel.size()); - } - - @Test - public void parseFtpAndSendMessage(){ - CollectVo collectVo = new CollectVo(); - collectVo.setType("ems-p"); - taskThread.parseFtpAndSendMessage(gzPath,collectVo); - } - - @Test - public void createMessage(){ - CollectVo collectVo = new CollectVo(); - collectVo.setType("ems-p"); - taskThread.createMessage("zipName", "user", "pwd", "ip", "port", 122, "nename"); - } - - @After + @After public void setDown() throws IOException { - new File(gzPath).delete(); - new File(gzPath.replace(".gz", "")).delete(); + new File(gzPath).delete(); + new File(gzPath.replace(".gz", "")).delete(); } } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/AlarmSocketServer.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/AlarmSocketServer.java index ada1fd3..dbdb3cd 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/AlarmSocketServer.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/AlarmSocketServer.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -25,81 +25,81 @@ import java.net.SocketTimeoutException; public class AlarmSocketServer { - boolean stop = false; - InputStreamReader isr = null; - BufferedOutputStream dos = null; - Socket socket = null; - ServerSocket server = null; - public void socketServer(){ - - try { - server = new ServerSocket(12345); - socket = server.accept(); - - socket.setSoTimeout(3*1000); - socket.setTcpNoDelay(true); - socket.setKeepAlive(true); - InputStream in = socket.getInputStream(); - isr = new InputStreamReader(in); - dos = new BufferedOutputStream(socket.getOutputStream()); - while(!stop){ - int len = 0; - char b[] = new char[1024 * 8]; - try{ - len = isr.read(b, 0, b.length); - }catch(SocketTimeoutException e){ - e.printStackTrace(); - break; - } - if (len > 0) { - String restlu = new String(b, 0, len); - if(restlu.contains("reqLoginAlarm")){ - Msg msg = new Msg("ackLoginAlarm;result=succ;resDesc= ",MsgType.ackLoginAlarm); - - MessageUtil.writeMsg(msg,dos); - } - if(restlu.contains("reqHeartBeat")){ - Msg msg = new Msg("ackHeartBeat;result=succ;resDesc= ",MsgType.ackHeartBeat); - - MessageUtil.writeMsg(msg,dos); - } - Msg msg = new Msg("realTimeAlarm;result=succ;resDesc= ",MsgType.realTimeAlarm); - - MessageUtil.writeMsg(msg,dos); - - - - }else{ - System.out.println("len:" +len); - Thread.sleep(10); - } - - } - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - public void stop(){ - try { - stop = true; - if(isr != null){ - isr.close(); - } - if(dos != null){ - dos.close(); - } - if(socket != null){ - socket.close(); - } - if(server != null){ - server.close(); - } - - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + boolean stop = false; + InputStreamReader isr = null; + BufferedOutputStream dos = null; + Socket socket = null; + ServerSocket server = null; + + public void socketServer() { + + try { + server = new ServerSocket(12345); + socket = server.accept(); + + socket.setSoTimeout(3 * 1000); + socket.setTcpNoDelay(true); + socket.setKeepAlive(true); + InputStream in = socket.getInputStream(); + isr = new InputStreamReader(in); + dos = new BufferedOutputStream(socket.getOutputStream()); + while (!stop) { + int len = 0; + char b[] = new char[1024 * 8]; + try { + len = isr.read(b, 0, b.length); + } catch (SocketTimeoutException e) { + e.printStackTrace(); + break; + } + if (len > 0) { + String restlu = new String(b, 0, len); + if (restlu.contains("reqLoginAlarm")) { + Msg msg = new Msg("ackLoginAlarm;result=succ;resDesc= ", MsgType.ackLoginAlarm); + + MessageUtil.writeMsg(msg, dos); + } + if (restlu.contains("reqHeartBeat")) { + Msg msg = new Msg("ackHeartBeat;result=succ;resDesc= ", MsgType.ackHeartBeat); + + MessageUtil.writeMsg(msg, dos); + } + Msg msg = new Msg("realTimeAlarm;result=succ;resDesc= ", MsgType.realTimeAlarm); + + MessageUtil.writeMsg(msg, dos); + + + } else { + System.out.println("len:" + len); + Thread.sleep(10); + } + + } + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public void stop() { + try { + stop = true; + if (isr != null) { + isr.close(); + } + if (dos != null) { + dos.close(); + } + if (socket != null) { + socket.close(); + } + if (server != null) { + server.close(); + } + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/AlarmTaskThreadTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/AlarmTaskThreadTest.java index 4fd7bcd..24635e1 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/AlarmTaskThreadTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/AlarmTaskThreadTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,65 +15,64 @@ */ package org.onap.vfc.nfvo.emsdriver.collector.alarm; -import static org.junit.Assert.assertNotNull; - -import java.io.IOException; - import org.junit.Before; import org.junit.Test; -import org.onap.vfc.nfvo.emsdriver.collector.alarm.AlarmTaskThread; import org.onap.vfc.nfvo.emsdriver.commons.model.CollectVo; +import java.io.IOException; + +import static org.junit.Assert.assertNotNull; + public class AlarmTaskThreadTest { - private AlarmTaskThread taskThread; - private AlarmSocketServer server; - - @Before + private AlarmTaskThread taskThread; + private AlarmSocketServer server; + + @Before public void setUp() throws IOException { - new Thread(){ - public void run(){ - server = new AlarmSocketServer(); - server.socketServer(); - } - }.start(); - - CollectVo collectVo = new CollectVo(); - collectVo.setIP("127.0.0.1"); - collectVo.setPort("12345"); - collectVo.setUser("user"); - collectVo.setPassword("12345"); - taskThread = new AlarmTaskThread(collectVo); + new Thread() { + public void run() { + server = new AlarmSocketServer(); + server.socketServer(); + } + }.start(); + + CollectVo collectVo = new CollectVo(); + collectVo.setIP("127.0.0.1"); + collectVo.setPort("12345"); + collectVo.setUser("user"); + collectVo.setPassword("12345"); + taskThread = new AlarmTaskThread(collectVo); + } + + @Test + public void build120Alarm() { + String alarm = "{\"alarmSeq\":495,\"alarmTitle\":\"LTE cell outage\",\"alarmStatus\":1,\"alarmType\":\"processingErrorAlarm\"}"; + try { + new Thread() { + public void run() { + try { + Thread.sleep(3000); + + server.stop(); + taskThread.setStop(true); + taskThread.close(); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + }.start(); + + taskThread.init(); + taskThread.receive(); + + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertNotNull(alarm); } - - @Test - public void build120Alarm(){ - String alarm = "{\"alarmSeq\":495,\"alarmTitle\":\"LTE cell outage\",\"alarmStatus\":1,\"alarmType\":\"processingErrorAlarm\"}"; - try { - new Thread(){ - public void run(){ - try { - Thread.sleep(3000); - - server.stop(); - taskThread.setStop(true); - taskThread.close(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - }.start(); - - taskThread.init(); - taskThread.receive(); - - - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertNotNull(alarm); - } - + } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/MessageUtilTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/MessageUtilTest.java index a4f264c..2f3d637 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/MessageUtilTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/collector/alarm/MessageUtilTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,57 +15,53 @@ */ package org.onap.vfc.nfvo.emsdriver.collector.alarm; -import static org.junit.Assert.assertNotNull; - import org.junit.Test; +import static org.junit.Assert.assertNotNull; + public class MessageUtilTest { - - @Test - public void putLoginFtp(){ - Msg msg = MessageUtil.putLoginFtp("user", "passwd"); - - assertNotNull(msg); - } - @Test - public void putSyncMsg(){ - Msg msg = MessageUtil.putSyncMsg(1, 10); - - assertNotNull(msg); - } - - @Test - public void reqSyncAlarmFile(){ - Msg msg = MessageUtil.reqSyncAlarmFile(1, "2017-10-7","2017-10-7"); - - assertNotNull(msg); - } - @Test - public void reqSyncAlarmFileByAlarmSeq(){ - Msg msg = MessageUtil.reqSyncAlarmFileByAlarmSeq(1, 12); - - assertNotNull(msg); - } - @Test - public void reqSyncAlarmFileByTime(){ - Msg msg = MessageUtil.reqSyncAlarmFileByTime(1, "2017-10-7","2017-10-7"); - - assertNotNull(msg); - } - - @Test - public void closeConnAlarmMsg(){ - Msg msg = MessageUtil.closeConnAlarmMsg(); - - assertNotNull(msg); - } - - - - - - - - + + @Test + public void putLoginFtp() { + Msg msg = MessageUtil.putLoginFtp("user", "passwd"); + + assertNotNull(msg); + } + + @Test + public void putSyncMsg() { + Msg msg = MessageUtil.putSyncMsg(1, 10); + + assertNotNull(msg); + } + + @Test + public void reqSyncAlarmFile() { + Msg msg = MessageUtil.reqSyncAlarmFile(1, "2017-10-7", "2017-10-7"); + + assertNotNull(msg); + } + + @Test + public void reqSyncAlarmFileByAlarmSeq() { + Msg msg = MessageUtil.reqSyncAlarmFileByAlarmSeq(1, 12); + + assertNotNull(msg); + } + + @Test + public void reqSyncAlarmFileByTime() { + Msg msg = MessageUtil.reqSyncAlarmFileByTime(1, "2017-10-7", "2017-10-7"); + + assertNotNull(msg); + } + + @Test + public void closeConnAlarmMsg() { + Msg msg = MessageUtil.closeConnAlarmMsg(); + + assertNotNull(msg); + } + } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/AFtpRemoteFileTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/AFtpRemoteFileTest.java index e17290d..b985fa4 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/AFtpRemoteFileTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/AFtpRemoteFileTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,32 +15,34 @@ */ package org.onap.vfc.nfvo.emsdriver.commons.ftp; -import static org.junit.Assert.assertNotNull; - import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertNotNull; + public class AFtpRemoteFileTest { - AFtpRemoteFile aFtpRemoteFile = null; - @Before - public void setUp() { - FTPFile f = new FTPFile(); - f.setName("aaa/bb.txt"); - aFtpRemoteFile = new AFtpRemoteFile(f , new FTPClient(), "aaa/"); - } - - @Test - public void getFileName() { - String fileName = aFtpRemoteFile.getFileName(); - assertNotNull(fileName); - } - @Test - public void getAbsFileName() { - String absFileName = aFtpRemoteFile.getAbsFileName(); - assertNotNull(absFileName); - } - + AFtpRemoteFile aFtpRemoteFile = null; + + @Before + public void setUp() { + FTPFile f = new FTPFile(); + f.setName("aaa/bb.txt"); + aFtpRemoteFile = new AFtpRemoteFile(f, new FTPClient(), "aaa/"); + } + + @Test + public void getFileName() { + String fileName = aFtpRemoteFile.getFileName(); + assertNotNull(fileName); + } + + @Test + public void getAbsFileName() { + String absFileName = aFtpRemoteFile.getAbsFileName(); + assertNotNull(absFileName); + } + } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/FTPSrvTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/FTPSrvTest.java index 0765cac..420ee18 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/FTPSrvTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/ftp/FTPSrvTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/model/CollectMsgTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/model/CollectMsgTest.java index e53f7b3..65027f4 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/model/CollectMsgTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/model/CollectMsgTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,26 +15,25 @@ */ package org.onap.vfc.nfvo.emsdriver.commons.model; -import static org.junit.Assert.*; - import org.junit.Before; import org.junit.Test; -import org.onap.vfc.nfvo.emsdriver.commons.model.CollectMsg; + +import static org.junit.Assert.assertNotNull; public class CollectMsgTest { - - private CollectMsg collectMsg; + + private CollectMsg collectMsg; @Before public void setUp() { - collectMsg = new CollectMsg(); + collectMsg = new CollectMsg(); } @Test public void testCollectMsg() { - collectMsg.setEmsName("emsName"); - collectMsg.setId(100L); - collectMsg.setType("PM"); + collectMsg.setEmsName("emsName"); + collectMsg.setId(100L); + collectMsg.setType("PM"); assertNotNull(collectMsg.toString()); } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/model/CollectVoTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/model/CollectVoTest.java index bff3482..35ec958 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/model/CollectVoTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/model/CollectVoTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,25 +15,24 @@ */ package org.onap.vfc.nfvo.emsdriver.commons.model; -import static org.junit.Assert.assertNotNull; - import org.junit.Before; import org.junit.Test; -import org.onap.vfc.nfvo.emsdriver.commons.model.CollectVo; + +import static org.junit.Assert.assertNotNull; public class CollectVoTest { - - private CollectVo collectVo; + + private CollectVo collectVo; @Before public void setUp() { - collectVo = new CollectVo(); + collectVo = new CollectVo(); } @Test public void testCollectVo() { - collectVo.setEmsName("emsName"); - collectVo.setFtptype("ftp"); + collectVo.setEmsName("emsName"); + collectVo.setFtptype("ftp"); assertNotNull(collectVo.toString()); } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/model/EMSInfoTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/model/EMSInfoTest.java index 00490f7..93a50ad 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/model/EMSInfoTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/model/EMSInfoTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,34 +15,32 @@ */ package org.onap.vfc.nfvo.emsdriver.commons.model; -import static org.junit.Assert.assertNotNull; +import org.junit.Before; +import org.junit.Test; import java.util.HashMap; import java.util.Map; -import org.junit.Before; -import org.junit.Test; -import org.onap.vfc.nfvo.emsdriver.commons.model.CollectVo; -import org.onap.vfc.nfvo.emsdriver.commons.model.EMSInfo; +import static org.junit.Assert.assertNotNull; public class EMSInfoTest { - - private EMSInfo EMSInfo; + + private EMSInfo EMSInfo; @Before public void setUp() { - EMSInfo = new EMSInfo(); + EMSInfo = new EMSInfo(); } @Test public void testEMSInfo() { - EMSInfo.setName("emsName"); - Map<String,CollectVo> collectMap = new HashMap<String,CollectVo>(); - CollectVo collectVo = new CollectVo(); - collectVo.setEmsName("emsName"); - collectMap.put("pm", collectVo); - EMSInfo.putCollectMap("pm", collectVo); - + EMSInfo.setName("emsName"); + Map<String, CollectVo> collectMap = new HashMap<String, CollectVo>(); + CollectVo collectVo = new CollectVo(); + collectVo.setEmsName("emsName"); + collectMap.put("pm", collectVo); + EMSInfo.putCollectMap("pm", collectVo); + assertNotNull(EMSInfo.toString()); } } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/utils/GunzipTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/utils/GunzipTest.java index aebea0f..37f6e1f 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/utils/GunzipTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/utils/GunzipTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,42 +15,41 @@ */ package org.onap.vfc.nfvo.emsdriver.commons.utils; -import static org.junit.Assert.assertTrue; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import java.io.File; import java.io.IOException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.vfc.nfvo.emsdriver.commons.utils.Gunzip; +import static org.junit.Assert.assertTrue; public class GunzipTest { - private String csvPath = System.getProperty("user.dir")+"/data/" +"PM-ENB-EUTRANCELLNB-test.csv"; - private String gzPath = System.getProperty("user.dir")+"/data/" +"PM-ENB-EUTRANCELLNB-test.csv.gz"; - private Gunzip gunzip = null; - private String gunzipfile; - - - @Before + private String csvPath = System.getProperty("user.dir") + "/data/" + "PM-ENB-EUTRANCELLNB-test.csv"; + private String gzPath = System.getProperty("user.dir") + "/data/" + "PM-ENB-EUTRANCELLNB-test.csv.gz"; + private Gunzip gunzip = null; + private String gunzipfile; + + + @Before public void setUp() throws IOException { - gunzip = new Gunzip(); - Gzip gzip = new Gzip(); - gzip.compress(csvPath, gzPath); + gunzip = new Gunzip(); + Gzip gzip = new Gzip(); + gzip.compress(csvPath, gzPath); } - - @Test - public void deCompress() throws IOException{ - gunzipfile = gzPath.replace(".gz", "file"); - gunzip.unCompress(gzPath, gunzipfile); - assertTrue(new File(gunzipfile).length() > 0); - - } - - @After + + @Test + public void deCompress() throws IOException { + gunzipfile = gzPath.replace(".gz", "file"); + gunzip.unCompress(gzPath, gunzipfile); + assertTrue(new File(gunzipfile).length() > 0); + + } + + @After public void setDown() throws IOException { - new File(gunzipfile).delete(); - new File(gzPath).delete(); - + new File(gunzipfile).delete(); + new File(gzPath).delete(); + } } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/utils/Gzip.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/utils/Gzip.java index 9bee758..ccd054b 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/utils/Gzip.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/utils/Gzip.java @@ -1,12 +1,12 @@ /** * Copyright 2017 CMCC Technologies Co., Ltd - * + * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * <p> + * http://www.apache.org/licenses/LICENSE-2.0 + * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -15,65 +15,60 @@ */ package org.onap.vfc.nfvo.emsdriver.commons.utils; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; +import java.io.*; import java.util.zip.GZIPOutputStream; public class Gzip { - public void compress(String srcFileName, String toGzFile) - throws IOException { - FileInputStream fileInput = new FileInputStream(srcFileName); - compress(fileInput, toGzFile); - fileInput.close(); - - - } - - public void compress(InputStream src, String toGzFile) - throws IOException { - File theFile = new File(toGzFile); - if (!theFile.exists()) { - String parentPath = theFile.getParent(); - if (parentPath != null) - new File(parentPath).mkdirs(); - theFile.createNewFile(); - } - GZIPOutputStream gzOutput = new GZIPOutputStream(new FileOutputStream(theFile, false)); - - moveBytes(src, gzOutput, -1, -1, 1024); - gzOutput.close(); - } - - public long moveBytes(InputStream input, OutputStream output, long off, long len, int bufsize) - throws IOException { - if (off > 0) - input.skip(off); - - long totalNum = 0; - byte[] buf = new byte[bufsize]; + public void compress(String srcFileName, String toGzFile) + throws IOException { + FileInputStream fileInput = new FileInputStream(srcFileName); + compress(fileInput, toGzFile); + fileInput.close(); + + + } + + public void compress(InputStream src, String toGzFile) + throws IOException { + File theFile = new File(toGzFile); + if (!theFile.exists()) { + String parentPath = theFile.getParent(); + if (parentPath != null) + new File(parentPath).mkdirs(); + theFile.createNewFile(); + } + GZIPOutputStream gzOutput = new GZIPOutputStream(new FileOutputStream(theFile, false)); + + moveBytes(src, gzOutput, -1, -1, 1024); + gzOutput.close(); + } + + public long moveBytes(InputStream input, OutputStream output, long off, long len, int bufsize) + throws IOException { + if (off > 0) + input.skip(off); + + long totalNum = 0; + byte[] buf = new byte[bufsize]; + + while (true) { + if (len > 0 && (len - totalNum) <= 0) + break; + + else if (len > 0 && bufsize > (len - totalNum)) + bufsize = (int) (len - totalNum); + + int readNum = input.read(buf, 0, bufsize); + if (readNum <= 0) + break; + + output.write(buf, 0, readNum); + totalNum += readNum; + } + buf = null; + return totalNum; + } - while (true) { - if (len>0 && (len-totalNum)<=0) - break; - - else if (len>0 && bufsize>(len-totalNum)) - bufsize = (int)(len-totalNum); - - int readNum = input.read(buf, 0, bufsize); - if (readNum <= 0) - break; - - output.write(buf, 0, readNum); - totalNum += readNum; - } - buf = null; - return totalNum; - } - } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/utils/StringUtilTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/utils/StringUtilTest.java index a243032..077647d 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/utils/StringUtilTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/utils/StringUtilTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,44 +15,43 @@ */ package org.onap.vfc.nfvo.emsdriver.commons.utils; -import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; import java.io.File; -import org.junit.Before; -import org.junit.Test; -import org.onap.vfc.nfvo.emsdriver.commons.utils.StringUtil; +import static org.junit.Assert.*; public class StringUtilTest { - - private Throwable throwable; + + private Throwable throwable; @Before public void setUp() { - throwable = new Exception("test"); + throwable = new Exception("test"); } - + @Test public void testGetStackTrace() { - String str = StringUtil.getStackTrace(throwable); - - assertNotNull(str); + String str = StringUtil.getStackTrace(throwable); + + assertNotNull(str); } - + @Test - public void testAddSlash(){ - String str = StringUtil.addSlash("aa/bb"); - - assertTrue(str.endsWith(File.separator)); + public void testAddSlash() { + String str = StringUtil.addSlash("aa/bb"); + + assertTrue(str.endsWith(File.separator)); } @Test - public void testIsBank(){ - boolean str = StringUtil.isBank("aa/bb"); - boolean str1 = StringUtil.isBank(""); - boolean str2 = StringUtil.isBank(null); - assertFalse(str); - assertTrue(str1); - assertTrue(str2); + public void testIsBank() { + boolean str = StringUtil.isBank("aa/bb"); + boolean str1 = StringUtil.isBank(""); + boolean str2 = StringUtil.isBank(null); + assertFalse(str); + assertTrue(str1); + assertTrue(str2); } } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/utils/UnZipTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/utils/UnZipTest.java index 74c8050..ac12098 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/utils/UnZipTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/utils/UnZipTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,43 +15,45 @@ */ package org.onap.vfc.nfvo.emsdriver.commons.utils; -import static org.junit.Assert.assertTrue; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import java.io.File; import java.io.IOException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertTrue; public class UnZipTest { - private String file = "./test.txt"; - private String zipPath = "./test.zip"; - private String toPath = System.getProperty("user.dir")+"/data/"; - private UnZip unZip = null; - - @Before + private String file = "./test.txt"; + private String zipPath = "./test.zip"; + private String toPath = System.getProperty("user.dir") + "/data/"; + private UnZip unZip = null; + + public static void main(String[] str) { + System.out.println(System.getProperty("user.dir")); + } + + @Before public void setUp() throws IOException { - new File(file).createNewFile(); - Zip zip = new Zip(file,zipPath); - zip.compress(); - unZip = new UnZip(zipPath,toPath); - + new File(file).createNewFile(); + Zip zip = new Zip(file, zipPath); + zip.compress(); + unZip = new UnZip(zipPath, toPath); + } - @Test - public void deCompress() throws IOException{ - unZip.deCompress(); - - assertTrue(new File(toPath).listFiles().length > 0); - } - @After + + @Test + public void deCompress() throws IOException { + unZip.deCompress(); + + assertTrue(new File(toPath).listFiles().length > 0); + } + + @After public void setDown() throws IOException { - new File(zipPath).delete(); - new File(file).delete(); - new File(toPath+file).delete(); + new File(zipPath).delete(); + new File(file).delete(); + new File(toPath + file).delete(); } - - public static void main(String[] str){ - System.out.println(System.getProperty("user.dir")); - } } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/utils/ZipTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/utils/ZipTest.java index 4ded482..9ccb22f 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/utils/ZipTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/commons/utils/ZipTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,39 +15,39 @@ */ package org.onap.vfc.nfvo.emsdriver.commons.utils; -import static org.junit.Assert.assertTrue; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import java.io.File; import java.io.IOException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.vfc.nfvo.emsdriver.commons.utils.Zip; +import static org.junit.Assert.assertTrue; public class ZipTest { - - private String file = "./test.txt"; - private String tofile1 = "./test.zip"; - private Zip zip = null; - @Before + + private String file = "./test.txt"; + private String tofile1 = "./test.zip"; + private Zip zip = null; + + @Before public void setUp() throws IOException { - new File(file).createNewFile(); - zip = new Zip(file,tofile1); + new File(file).createNewFile(); + zip = new Zip(file, tofile1); + } + + @Test + public void compress() throws IOException { + zip.compress(); + + assertTrue(tofile1.endsWith(".zip")); } - - @Test - public void compress() throws IOException{ - zip.compress(); - - assertTrue(tofile1.endsWith(".zip")); - } - - - @After + + + @After public void setDown() throws IOException { - new File(file).delete(); - new File(tofile1).delete(); - + new File(file).delete(); + new File(tofile1).delete(); + } } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/configmgr/ConfigurationImpTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/configmgr/ConfigurationImpTest.java index 0041fa6..15284da 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/configmgr/ConfigurationImpTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/configmgr/ConfigurationImpTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,15 +15,6 @@ */ package org.onap.vfc.nfvo.emsdriver.configmgr; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.*; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jdom.Document; @@ -36,148 +27,157 @@ import org.onap.vfc.nfvo.emsdriver.commons.model.EMSInfo; import org.onap.vfc.nfvo.emsdriver.commons.utils.StringUtil; import org.onap.vfc.nfvo.emsdriver.commons.utils.XmlUtil; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.*; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + public class ConfigurationImpTest { - //normally an unit test should not log - protected static Log log = LogFactory.getLog(ConfigurationImpTest.class); - private ConfigurationManager configurationManager; - private ConfigurationImp configurationImp; - - public static void readcfg(){ - String path = Constant.SYS_CFG + "EMSInfo.xml"; - File cfg = new File(path); - log.debug("start loading " + path); - if(!cfg.exists() || !cfg.isFile()){ - log.debug("not exists " + path); - return; - } - - - InputStream is = null; - Map<String, EMSInfo> tmpcache = new HashMap<String, EMSInfo>(); - - try { - is = new FileInputStream(cfg); - Document doc = XmlUtil.getDocument(is); - - Element root = doc.getRootElement(); - - @SuppressWarnings("unchecked") - List<Element> children = root.getChildren(); - - for(Iterator<Element> it = children.iterator(); it.hasNext();){ - EMSInfo emsInfo = new EMSInfo(); - Element child = it.next(); - String name = child.getAttributeValue("name"); - if(StringUtil.isBank(name)){ - continue; - } - emsInfo.setName(name); + //normally an unit test should not log + protected static Log log = LogFactory.getLog(ConfigurationImpTest.class); + private ConfigurationManager configurationManager; + private ConfigurationImp configurationImp; + + public static void readcfg() { + String path = Constant.SYS_CFG + "EMSInfo.xml"; + File cfg = new File(path); + log.debug("start loading " + path); + if (!cfg.exists() || !cfg.isFile()) { + log.debug("not exists " + path); + return; + } + + + InputStream is = null; + Map<String, EMSInfo> tmpcache = new HashMap<String, EMSInfo>(); + + try { + is = new FileInputStream(cfg); + Document doc = XmlUtil.getDocument(is); + + Element root = doc.getRootElement(); + + @SuppressWarnings("unchecked") + List<Element> children = root.getChildren(); + + for (Iterator<Element> it = children.iterator(); it.hasNext(); ) { + EMSInfo emsInfo = new EMSInfo(); + Element child = it.next(); + String name = child.getAttributeValue("name"); + if (StringUtil.isBank(name)) { + continue; + } + emsInfo.setName(name); // tmpcache.put(name, emsInfo); - @SuppressWarnings("unchecked") - List<Element> collectList = child.getChildren(); - for(Element collect : collectList){ - - CollectVo collectVo = new CollectVo(); - - String type = collect.getAttributeValue("type"); - if("alarm".equalsIgnoreCase(type)){ - boolean iscollect = Boolean.parseBoolean(collect.getAttributeValue("iscollect")); - if(iscollect){ - collectVo.setIscollect(iscollect); - }else{ - continue; - } - collectVo.setType(type); - collectVo.setIP(collect.getChildText("ip")); - collectVo.setPort(collect.getChildText("port")); - collectVo.setUser(collect.getChildText("user")); - collectVo.setPassword(collect.getChildText("password")); - collectVo.setRead_timeout(collect.getChildText("readtimeout")); - }else{ - String crontab = collect.getAttributeValue("crontab"); - if(!StringUtil.isBank(type) && !StringUtil.isBank(crontab)){ - collectVo.setType(type); - collectVo.setCrontab(crontab); - }else{ - continue; - } - collectVo.setIP(collect.getChildText("ip")); - collectVo.setPort(collect.getChildText("port")); - collectVo.setUser(collect.getChildText("user")); - collectVo.setPassword(collect.getChildText("password")); - collectVo.setRemotepath(collect.getChildText("remotepath")); - collectVo.setMatch(collect.getChildText("match")); - collectVo.setPassive(collect.getChildText("passive")); - collectVo.setFtptype(collect.getChildText("ftptype")); - collectVo.setGranularity(collect.getChildText("granularity")); - } - - emsInfo.putCollectMap(type, collectVo); - } - tmpcache.put(name, emsInfo); - } - ConfigurationManager.emsInfoCache.putAll(tmpcache); - - File file = new File(ConfigurationManager.CONFIG_PROPERTIES_LOCATION); - if(!file.exists() || !file.isFile()){ - log.error("cacheFilePath " + ConfigurationManager.CONFIG_PROPERTIES_LOCATION +" not exist or is not File"); - return; - } - InputStream in = null; - try{ - ConfigurationManager.properties = new Properties(); - in = new FileInputStream(file); - ConfigurationManager.properties.load(in); - }catch (Exception e) { - e.printStackTrace(); - } - } catch (Exception e) { - log.error("load EMSInfo.xml is error "+StringUtil.getStackTrace(e)); - }finally{ - tmpcache.clear(); - try { - if(is != null){ - is.close(); - is = null; - } - } catch (Exception e2) { - } - cfg = null; - } - } - - - @Before + @SuppressWarnings("unchecked") + List<Element> collectList = child.getChildren(); + for (Element collect : collectList) { + + CollectVo collectVo = new CollectVo(); + + String type = collect.getAttributeValue("type"); + if ("alarm".equalsIgnoreCase(type)) { + boolean iscollect = Boolean.parseBoolean(collect.getAttributeValue("iscollect")); + if (iscollect) { + collectVo.setIscollect(iscollect); + } else { + continue; + } + collectVo.setType(type); + collectVo.setIP(collect.getChildText("ip")); + collectVo.setPort(collect.getChildText("port")); + collectVo.setUser(collect.getChildText("user")); + collectVo.setPassword(collect.getChildText("password")); + collectVo.setRead_timeout(collect.getChildText("readtimeout")); + } else { + String crontab = collect.getAttributeValue("crontab"); + if (!StringUtil.isBank(type) && !StringUtil.isBank(crontab)) { + collectVo.setType(type); + collectVo.setCrontab(crontab); + } else { + continue; + } + collectVo.setIP(collect.getChildText("ip")); + collectVo.setPort(collect.getChildText("port")); + collectVo.setUser(collect.getChildText("user")); + collectVo.setPassword(collect.getChildText("password")); + collectVo.setRemotepath(collect.getChildText("remotepath")); + collectVo.setMatch(collect.getChildText("match")); + collectVo.setPassive(collect.getChildText("passive")); + collectVo.setFtptype(collect.getChildText("ftptype")); + collectVo.setGranularity(collect.getChildText("granularity")); + } + + emsInfo.putCollectMap(type, collectVo); + } + tmpcache.put(name, emsInfo); + } + ConfigurationManager.emsInfoCache.putAll(tmpcache); + + File file = new File(ConfigurationManager.CONFIG_PROPERTIES_LOCATION); + if (!file.exists() || !file.isFile()) { + log.error("cacheFilePath " + ConfigurationManager.CONFIG_PROPERTIES_LOCATION + " not exist or is not File"); + return; + } + InputStream in = null; + try { + ConfigurationManager.properties = new Properties(); + in = new FileInputStream(file); + ConfigurationManager.properties.load(in); + } catch (Exception e) { + e.printStackTrace(); + } + } catch (Exception e) { + log.error("load EMSInfo.xml is error " + StringUtil.getStackTrace(e)); + } finally { + tmpcache.clear(); + try { + if (is != null) { + is.close(); + is = null; + } + } catch (Exception e2) { + } + cfg = null; + } + } + + + @Before public void setUp() throws IOException { - configurationImp = new ConfigurationImp(); - configurationManager = new ConfigurationManager(); - readcfg(); + configurationImp = new ConfigurationImp(); + configurationManager = new ConfigurationManager(); + readcfg(); } - - @Test - public void getAllEMSInfo() { - - List<EMSInfo> list = configurationImp.getAllEMSInfo(); - - assertTrue(list.size() >0); - } - - @Test - public void getCollectVoByEmsNameAndType() { - - CollectVo collectVo = configurationImp.getCollectVoByEmsNameAndType("1234","cm"); - - assertNotNull(collectVo); - } - - @Test - public void getProperties() { - - Properties properties = configurationImp.getProperties(); - - assertNotNull(properties); - } - + + @Test + public void getAllEMSInfo() { + + List<EMSInfo> list = configurationImp.getAllEMSInfo(); + + assertTrue(list.size() > 0); + } + + @Test + public void getCollectVoByEmsNameAndType() { + + CollectVo collectVo = configurationImp.getCollectVoByEmsNameAndType("1234", "cm"); + + assertNotNull(collectVo); + } + + @Test + public void getProperties() { + + Properties properties = configurationImp.getProperties(); + + assertNotNull(properties); + } + } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/configmgr/ConfigurationManagerTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/configmgr/ConfigurationManagerTest.java index ef6ccfb..222029e 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/configmgr/ConfigurationManagerTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/configmgr/ConfigurationManagerTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,59 +15,59 @@ */ package org.onap.vfc.nfvo.emsdriver.configmgr; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import org.junit.Before; +import org.junit.Test; +import org.onap.vfc.nfvo.emsdriver.commons.model.CrontabVo; +import org.onap.vfc.nfvo.emsdriver.commons.model.EMSInfo; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Properties; -import org.junit.Before; -import org.junit.Test; -import org.onap.vfc.nfvo.emsdriver.commons.model.CrontabVo; -import org.onap.vfc.nfvo.emsdriver.commons.model.EMSInfo; -import org.onap.vfc.nfvo.emsdriver.configmgr.ConfigurationManager; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; public class ConfigurationManagerTest { - private ConfigurationManager configurationManager; - @Before + private ConfigurationManager configurationManager; + + @Before public void setUp() throws IOException { - configurationManager = new ConfigurationManager(); - ConfigurationImpTest.readcfg(); + configurationManager = new ConfigurationManager(); + ConfigurationImpTest.readcfg(); } - - @Test - public void getAllEMSInfos() { - - List<EMSInfo> list = ConfigurationManager.getAllEMSInfos(); - - assertTrue(list.size() >0); - } - - @Test - public void getEMSInfoByName() { - - EMSInfo eMSInfo = ConfigurationManager.getEMSInfoByName("1234"); - - assertNotNull(eMSInfo); - } - - @Test - public void getProperties() { - - Properties properties = ConfigurationManager.getProperties(); - - assertNotNull(properties); - } - - @Test - public void readCorntab() { - - Map<String, CrontabVo> list = configurationManager.readCorntab(); - System.out.println(list); - assertTrue(list.size() >0); - } - + + @Test + public void getAllEMSInfos() { + + List<EMSInfo> list = ConfigurationManager.getAllEMSInfos(); + + assertTrue(list.size() > 0); + } + + @Test + public void getEMSInfoByName() { + + EMSInfo eMSInfo = ConfigurationManager.getEMSInfoByName("1234"); + + assertNotNull(eMSInfo); + } + + @Test + public void getProperties() { + + Properties properties = ConfigurationManager.getProperties(); + + assertNotNull(properties); + } + + @Test + public void readCorntab() { + + Map<String, CrontabVo> list = configurationManager.readCorntab(); + System.out.println(list); + assertTrue(list.size() > 0); + } + } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/messagemgr/MessageChannelFactoryTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/messagemgr/MessageChannelFactoryTest.java index da8cb25..167a51f 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/messagemgr/MessageChannelFactoryTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/messagemgr/MessageChannelFactoryTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,38 +15,36 @@ */ package org.onap.vfc.nfvo.emsdriver.messagemgr; -import static org.junit.Assert.assertNotNull; - import org.junit.Test; -import org.onap.vfc.nfvo.emsdriver.messagemgr.MessageChannel; -import org.onap.vfc.nfvo.emsdriver.messagemgr.MessageChannelFactory; + +import static org.junit.Assert.assertNotNull; public class MessageChannelFactoryTest { - @Test - public void getMessageChannel(){ - MessageChannel messageChannel = MessageChannelFactory.getMessageChannel("aaa", 100); - - assertNotNull(messageChannel); - } - - @Test - public void getMessageChannelTest(){ - MessageChannel messageChannel = MessageChannelFactory.getMessageChannel("aaa"); - - assertNotNull(messageChannel); - } - - @Test - public void destroyMessageChannel(){ - boolean result = MessageChannelFactory.destroyMessageChannel("aaa"); - - assertNotNull(result); - } - - @Test - public void clean(){ - MessageChannelFactory.clean(); - - } + @Test + public void getMessageChannel() { + MessageChannel messageChannel = MessageChannelFactory.getMessageChannel("aaa", 100); + + assertNotNull(messageChannel); + } + + @Test + public void getMessageChannelTest() { + MessageChannel messageChannel = MessageChannelFactory.getMessageChannel("aaa"); + + assertNotNull(messageChannel); + } + + @Test + public void destroyMessageChannel() { + boolean result = MessageChannelFactory.destroyMessageChannel("aaa"); + + assertNotNull(result); + } + + @Test + public void clean() { + MessageChannelFactory.clean(); + + } } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/messagemgr/MessageChannelTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/messagemgr/MessageChannelTest.java index 25c68d1..a80a5be 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/messagemgr/MessageChannelTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/messagemgr/MessageChannelTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,58 +15,59 @@ */ package org.onap.vfc.nfvo.emsdriver.messagemgr; -import static org.junit.Assert.*; - import org.junit.Before; import org.junit.Test; -import org.onap.vfc.nfvo.emsdriver.messagemgr.MessageChannel; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; public class MessageChannelTest { - private MessageChannel messageChannel; - @Before + private MessageChannel messageChannel; + + @Before public void setUp() { - messageChannel = new MessageChannel(); - } - - @Test - public void MessageChannel(){ - MessageChannel messageChannel = new MessageChannel(10); - assertNotNull(messageChannel.getQueue()); - MessageChannel messageChannel1 = new MessageChannel(0); - assertNotNull(messageChannel1.getQueue()); - } - - @Test - public void put() throws Exception{ - Object obj = new Object(); - messageChannel.put(obj); - - assertEquals(1, messageChannel.size()); - } - - @Test - public void get() throws Exception{ - Object obj = new Object(); - messageChannel.put(obj); - Object objr = messageChannel.get(); - assertNotNull(objr); - } - - @Test - public void poll() throws Exception{ - Object obj = new Object(); - messageChannel.put(obj); - Object objr = messageChannel.poll(); - assertNotNull(objr); - } - - @Test - public void clear() throws Exception{ - Object obj = new Object(); - messageChannel.put(obj); - messageChannel.clear(); - assertEquals(0, messageChannel.size()); - } - + messageChannel = new MessageChannel(); + } + + @Test + public void MessageChannel() { + MessageChannel messageChannel = new MessageChannel(10); + assertNotNull(messageChannel.getQueue()); + MessageChannel messageChannel1 = new MessageChannel(0); + assertNotNull(messageChannel1.getQueue()); + } + + @Test + public void put() throws Exception { + Object obj = new Object(); + messageChannel.put(obj); + + assertEquals(1, messageChannel.size()); + } + + @Test + public void get() throws Exception { + Object obj = new Object(); + messageChannel.put(obj); + Object objr = messageChannel.get(); + assertNotNull(objr); + } + + @Test + public void poll() throws Exception { + Object obj = new Object(); + messageChannel.put(obj); + Object objr = messageChannel.poll(); + assertNotNull(objr); + } + + @Test + public void clear() throws Exception { + Object obj = new Object(); + messageChannel.put(obj); + messageChannel.clear(); + assertEquals(0, messageChannel.size()); + } + } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/northbound/service/CommandResourceTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/northbound/service/CommandResourceTest.java index cb6c087..fe5f98e 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/northbound/service/CommandResourceTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/northbound/service/CommandResourceTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -19,10 +19,10 @@ import org.junit.Test; public class CommandResourceTest { - @Test - public void testExecuteCommand(){ - CommandResource commandResource = new CommandResource(); - commandResource.executeCommand("aaa"); - } + @Test + public void testExecuteCommand() { + CommandResource commandResource = new CommandResource(); + commandResource.executeCommand("aaa"); + } } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/serviceregister/MsbConfigurationTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/serviceregister/MsbConfigurationTest.java index e3398d7..342cdc5 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/serviceregister/MsbConfigurationTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/serviceregister/MsbConfigurationTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,15 +18,15 @@ package org.onap.vfc.nfvo.emsdriver.serviceregister; import org.junit.Test; public class MsbConfigurationTest { - - @Test - public void testSetMsbAddress(){ - MsbConfiguration.setMsbAddress("aaa/bnn"); - } - - @Test - public void testGetMsbAddress(){ - MsbConfiguration.getMsbAddress(); - } + + @Test + public void testSetMsbAddress() { + MsbConfiguration.setMsbAddress("aaa/bnn"); + } + + @Test + public void testGetMsbAddress() { + MsbConfiguration.getMsbAddress(); + } } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/serviceregister/MsbRestServiceProxyTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/serviceregister/MsbRestServiceProxyTest.java index 25c599e..9caf35a 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/serviceregister/MsbRestServiceProxyTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/serviceregister/MsbRestServiceProxyTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,32 +15,34 @@ */ package org.onap.vfc.nfvo.emsdriver.serviceregister; -import java.util.List; - import org.junit.Before; import org.junit.Test; import org.onap.vfc.nfvo.emsdriver.serviceregister.model.MsbRegisterVo; +import java.util.List; + public class MsbRestServiceProxyTest { - @Before - public void upSet(){ - MsbConfiguration.setMsbAddress(""); - } - @Test - public void testRegisterService(){ - MsbRegisterVo registerInfo = new MsbRegisterVo(); - registerInfo.setServiceName("ems-driver"); - registerInfo.setUrl("/api/emsdriver/v1"); - MsbRestServiceProxy.registerService(registerInfo); - } - @Test - public void testunRegiserService(){ - MsbRestServiceProxy.unRegiserService("emsdriver","v1","172.0.0.1","9999"); - } - - @Test - public void testqueryService(){ - List<String> queryService = MsbRestServiceProxy.queryService("emsdriver","v1"); - } + @Before + public void upSet() { + MsbConfiguration.setMsbAddress(""); + } + + @Test + public void testRegisterService() { + MsbRegisterVo registerInfo = new MsbRegisterVo(); + registerInfo.setServiceName("ems-driver"); + registerInfo.setUrl("/api/emsdriver/v1"); + MsbRestServiceProxy.registerService(registerInfo); + } + + @Test + public void testunRegiserService() { + MsbRestServiceProxy.unRegiserService("emsdriver", "v1", "172.0.0.1", "9999"); + } + + @Test + public void testqueryService() { + List<String> queryService = MsbRestServiceProxy.queryService("emsdriver", "v1"); + } } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/serviceregister/model/MsbRegisterVoTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/serviceregister/model/MsbRegisterVoTest.java index da51a9f..286c739 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/serviceregister/model/MsbRegisterVoTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/serviceregister/model/MsbRegisterVoTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,37 +15,37 @@ */ package org.onap.vfc.nfvo.emsdriver.serviceregister.model; -import java.util.ArrayList; - import org.junit.Before; import org.junit.Test; +import java.util.ArrayList; + public class MsbRegisterVoTest { - private MsbRegisterVo msbRegisterVo; + private MsbRegisterVo msbRegisterVo; @Before public void setUp() { - msbRegisterVo = new MsbRegisterVo(); + msbRegisterVo = new MsbRegisterVo(); } - + @Test - public void testMsbRegisterVo(){ - msbRegisterVo.setProtocol("REST"); - msbRegisterVo.setServiceName("serviceName"); - msbRegisterVo.setUrl("http://"); - msbRegisterVo.setVersion("version"); - msbRegisterVo.setVisualRange("vr"); - ArrayList<ServiceNodeVo> list = new ArrayList<ServiceNodeVo>(); - list.add(new ServiceNodeVo()); - msbRegisterVo.setNodes(list); - msbRegisterVo.getNodes(); - msbRegisterVo.getProtocol(); - msbRegisterVo.getServiceName(); - msbRegisterVo.getUrl(); - msbRegisterVo.getVersion(); - msbRegisterVo.getVisualRange(); - + public void testMsbRegisterVo() { + msbRegisterVo.setProtocol("REST"); + msbRegisterVo.setServiceName("serviceName"); + msbRegisterVo.setUrl("http://"); + msbRegisterVo.setVersion("version"); + msbRegisterVo.setVisualRange("vr"); + ArrayList<ServiceNodeVo> list = new ArrayList<ServiceNodeVo>(); + list.add(new ServiceNodeVo()); + msbRegisterVo.setNodes(list); + msbRegisterVo.getNodes(); + msbRegisterVo.getProtocol(); + msbRegisterVo.getServiceName(); + msbRegisterVo.getUrl(); + msbRegisterVo.getVersion(); + msbRegisterVo.getVisualRange(); + } } diff --git a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/serviceregister/model/ServiceNodeVoTest.java b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/serviceregister/model/ServiceNodeVoTest.java index 6c4b98f..6b603d1 100644 --- a/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/serviceregister/model/ServiceNodeVoTest.java +++ b/ems/boco/src/test/java/org/onap/vfc/nfvo/emsdriver/serviceregister/model/ServiceNodeVoTest.java @@ -1,4 +1,4 @@ -/** +/* * Copyright 2017 BOCO Corporation. CMCC Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,28 +15,28 @@ */ package org.onap.vfc.nfvo.emsdriver.serviceregister.model; -import static org.junit.Assert.*; - import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertNotNull; + public class ServiceNodeVoTest { - - private ServiceNodeVo serviceNodeVo; + + private ServiceNodeVo serviceNodeVo; @Before public void setUp() { - serviceNodeVo = new ServiceNodeVo(); + serviceNodeVo = new ServiceNodeVo(); } - + @Test - public void testServiceNodeVo(){ - serviceNodeVo.setIp("127.0.0.1"); - serviceNodeVo.setPort("100"); - serviceNodeVo.setTtl(1); - assertNotNull(serviceNodeVo.getIp()); - assertNotNull(serviceNodeVo.getPort()); - assertNotNull(serviceNodeVo.getTtl()); + public void testServiceNodeVo() { + serviceNodeVo.setIp("127.0.0.1"); + serviceNodeVo.setPort("100"); + serviceNodeVo.setTtl(1); + assertNotNull(serviceNodeVo.getIp()); + assertNotNull(serviceNodeVo.getPort()); + assertNotNull(serviceNodeVo.getTtl()); } } |