diff options
Diffstat (limited to 'common')
65 files changed, 9305 insertions, 0 deletions
diff --git a/common/pom.xml b/common/pom.xml new file mode 100644 index 0000000000..30c8689f7f --- /dev/null +++ b/common/pom.xml @@ -0,0 +1,166 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.openecomp</groupId> + <artifactId>mso</artifactId> + <version>0.0.4-SNAPSHOT</version> + </parent> + + <groupId>org.openecomp.mso</groupId> + <artifactId>common</artifactId> + <name>MSO Common classes</name> + <description>MSO Common classes:- Logger</description> + + <dependencies> + <dependency> + <groupId>com.att.eelf</groupId> + <artifactId>eelf-core</artifactId> + <version>0.0.1</version> + </dependency> + <dependency> + <groupId>ch.qos.logback</groupId> + <artifactId>logback-classic</artifactId> + <version>1.1.1</version> + </dependency> + <dependency> + <groupId>ch.qos.logback</groupId> + <artifactId>logback-core</artifactId> + <version>1.1.1</version> + </dependency> + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + </dependency> + <dependency> + <groupId>javax.servlet</groupId> + <artifactId>javax.servlet-api</artifactId> + <version>3.1.0</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.jboss.resteasy</groupId> + <artifactId>resteasy-jaxrs</artifactId> + <version>3.0.19.Final</version> + <scope>provided</scope> + <exclusions> + <exclusion> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + </exclusion> + <exclusion> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-simple</artifactId> + </exclusion> + <exclusion> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + </exclusion> + </exclusions> + </dependency> + + <dependency> + <groupId>org.jboss.spec.javax.ejb</groupId> + <artifactId>jboss-ejb-api_3.2_spec</artifactId> + <version>1.0.0.Final</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.jboss.ejb3</groupId> + <artifactId>jboss-ejb3-ext-api</artifactId> + <version>2.2.0.Final</version> + <scope>provided</scope> + </dependency> + + <dependency> + <groupId>org.codehaus.jackson</groupId> + <artifactId>jackson-mapper-asl</artifactId> + <version>1.9.13</version> + </dependency> + + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-all</artifactId> + <version>1.10.19</version> + <scope>test</scope> + </dependency> + + </dependencies> + <build> + <resources> + <resource> + <directory>src/main/resources</directory> + <filtering>true</filtering> + </resource> + <resource> + <directory>src/main/java</directory> + <includes> + <include>**/*.java</include> + </includes> + </resource> + </resources> + <plugins> + <plugin> + <groupId>com.att.eelf</groupId> + <artifactId>eelf-maven-plugin</artifactId> + <version>0.0.1</version> + <executions> + <execution> + <id>validate</id> + <phase>install</phase> + <goals> + <goal>ValidateApplicationMsgs</goal> + </goals> + <configuration> + <resources> + <resource> + <messageClass>org.openecomp.mso.logger.MessageEnum</messageClass> + </resource> + </resources> + </configuration> + </execution> + <execution> + <id>wiki</id> + <phase>install</phase> + <goals> + <goal>WikiMsgGenerator</goal> + </goals> + <configuration> + <outputDirectory>target/messages</outputDirectory> + <outputFile>messages.html</outputFile> + <wiki> + <title>Messages and Codes</title> + <space>APP</space> + <page>Messages and Codes</page> + <principal>test</principal> + <credentials>test</credentials> + <url>http://wiki.web.att.com</url> + </wiki> + <resources> + <resource> + <messageClass>org.openecomp.mso.logger.MessageEnum</messageClass> + <header><![CDATA[<p> <ac:macro ac:name="toc"/> </p> +<!-- <p> --> +<!-- <ac:macro ac:name="anchor"> <ac:default-parameter>Application Messages</ac:default-parameter> </ac:macro> </p> <h2>Application Messages</h2>]]></header> + --> + </resource> + </resources> + </configuration> + </execution> + </executions> + <dependencies> + <dependency> + <groupId>org.openecomp.mso</groupId> + <artifactId>common</artifactId> + <version>${project.version}</version> + </dependency> + </dependencies> + + </plugin> + </plugins> + </build> +</project> diff --git a/common/src/main/java/org/openecomp/mso/entity/MsoRequest.java b/common/src/main/java/org/openecomp/mso/entity/MsoRequest.java new file mode 100644 index 0000000000..4f3a4ab9de --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/entity/MsoRequest.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.entity; + + + +/** + * This simple bean holds tracking information for MSO requests within + * the adapters. This tracking information should be added to logs, + * metrics, alarms as appropriate. + * + * + */ +public class MsoRequest +{ + private String requestId; + private String serviceInstanceId; + + public MsoRequest() { + this.requestId = null; + this.serviceInstanceId = null; + } + public MsoRequest(String r, String s) { + this.requestId = r; + this.serviceInstanceId = s; + } + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public String getServiceInstanceId() { + return serviceInstanceId; + } + + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } +} diff --git a/common/src/main/java/org/openecomp/mso/entity/package-info.java b/common/src/main/java/org/openecomp/mso/entity/package-info.java new file mode 100644 index 0000000000..e97a588e32 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/entity/package-info.java @@ -0,0 +1,26 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +/** + * Entities used for logging. + */ + +package org.openecomp.mso.entity; + diff --git a/common/src/main/java/org/openecomp/mso/logger/LogFilter.java b/common/src/main/java/org/openecomp/mso/logger/LogFilter.java new file mode 100644 index 0000000000..ca25ad2e22 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/logger/LogFilter.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.logger; + + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.MDC; + +import java.io.IOException; +import java.security.Principal; + +public class LogFilter implements Filter { + @Override + public void destroy() { + // Nothing to do. + } + + @Override + public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { + final HttpServletRequest httpRequest = (HttpServletRequest) request; + final HttpServletResponse httpResponse = (HttpServletResponse) response; + + MDC.clear (); + MDC.put (MsoLogger.REMOTE_HOST, httpRequest.getRemoteAddr()); + + Principal userPrincipal = httpRequest.getUserPrincipal(); + if (null != userPrincipal) { + MDC.put (MsoLogger.PARTNERNAME, userPrincipal.getName ()); + } + chain.doFilter(httpRequest, httpResponse); + } + + @Override + public void init(final FilterConfig config) throws ServletException { + // Nothing to do + } +} diff --git a/common/src/main/java/org/openecomp/mso/logger/MessageEnum.java b/common/src/main/java/org/openecomp/mso/logger/MessageEnum.java new file mode 100644 index 0000000000..89f6df93b7 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/logger/MessageEnum.java @@ -0,0 +1,229 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.logger; + + +import com.att.eelf.i18n.EELFResolvableErrorEnum; +import com.att.eelf.i18n.EELFResourceManager; + +public enum MessageEnum implements EELFResolvableErrorEnum{ + // Api Handler Messages + APIH_REQUEST_NULL, + APIH_QUERY_FOUND, + APIH_QUERY_NOT_FOUND, + APIH_QUERY_PARAM_WRONG, + APIH_DB_ACCESS_EXC, + APIH_DB_ACCESS_EXC_REASON, + APIH_VALIDATION_ERROR, + APIH_REQUEST_VALIDATION_ERROR, + APIH_SERVICE_VALIDATION_ERROR, + APIH_GENERAL_EXCEPTION_ARG, + APIH_GENERAL_EXCEPTION, + APIH_GENERAL_WARNING, + APIH_AUDIT_EXEC, + APIH_GENERAL_METRICS, + APIH_DUPLICATE_CHECK_EXC, + APIH_DUPLICATE_FOUND, + APIH_BAD_ORDER, + APIH_DB_ATTRIBUTE_NOT_FOUND, + APIH_BPEL_COMMUNICATE_ERROR, + APIH_BPEL_RESPONSE_ERROR, + APIH_WARP_REQUEST, + APIH_ERROR_FROM_BPEL_SERVER, + APIH_DB_INSERT_EXC, + APIH_DB_UPDATE_EXC, + APIH_NO_PROPERTIES, + APIH_PROPERTY_LOAD_SUC, + APIH_LOAD_PROPERTIES_FAIL, + APIH_SDNC_COMMUNICATE_ERROR, + APIH_SDNC_RESPONSE_ERROR, + APIH_CANNOT_READ_SCHEMA, + APIH_HEALTH_CHECK_EXCEPTION, + APIH_REQUEST_VALIDATION_ERROR_REASON, + APIH_JAXB_MARSH_ERROR, + APIH_JAXB_UNMARSH_ERROR, + APIH_VNFREQUEST_VALIDATION_ERROR, + APIH_DOM2STR_ERROR, + APIH_READ_VNFOUTPUT_CLOB_EXCEPTION, + APIH_DUPLICATE_CHECK_EXC_ATT, + APIH_GENERATED_REQUEST_ID, + APIH_GENERATED_SERVICE_INSTANCE_ID, + APIH_REPLACE_REQUEST_ID, + // Resource Adapter Messages + RA_GENERAL_EXCEPTION_ARG, + RA_GENERAL_EXCEPTION, + RA_GENERAL_WARNING, + RA_MISSING_PARAM, + RA_AUDIT_EXEC, + RA_GENERAL_METRICS, + RA_CREATE_STACK_TIMEOUT, + RA_DELETE_STACK_TIMEOUT, + RA_UPDATE_STACK_TIMEOUT, + RA_CONNECTION_EXCEPTION, + RA_PARSING_ERROR, + RA_PROPERTIES_NOT_FOUND, + RA_LOAD_PROPERTIES_SUC, + RA_NETWORK_ALREADY_EXIST, + RA_UPDATE_NETWORK_ERR, + RA_CREATE_STACK_ERR, + RA_UPDATE_STACK_ERR, + RA_CREATE_TENANT_ERR, + RA_NETWORK_NOT_FOUND, + RA_NETWORK_ORCHE_MODE_NOT_SUPPORT, + RA_CREATE_NETWORK_EXC, + RA_PARAM_NOT_FOUND, + RA_CONFIG_EXC, + RA_UNKOWN_PARAM, + RA_VLAN_PARSE, + RA_DELETE_NETWORK_EXC, + RA_ROLLBACK_NULL, + RA_TENANT_NOT_FOUND, + RA_QUERY_NETWORK_EXC, + RA_CREATE_NETWORK_NOTIF_EXC, + RA_ASYNC_ROLLBACK, + RA_WSDL_NOT_FOUND, + RA_WSDL_URL_CONVENTION_EXC, + RA_INIT_NOTIF_EXC, + RA_SET_CALLBACK_AUTH_EXC, + RA_FAULT_INFO_EXC, + RA_MARSHING_ERROR, + RA_PARSING_REQUEST_ERROR, + RA_SEND_REQUEST_SDNC, + RA_RESPONSE_FROM_SDNC, + RA_EXCEPTION_COMMUNICATE_SDNC, + RA_EVALUATE_XPATH_ERROR, + RA_ANALYZE_ERROR_EXC, + RA_ERROR_GET_RESPONSE_SDNC, + RA_CALLBACK_BPEL, + RA_INIT_CALLBACK_WSDL_ERR, + RA_CALLBACK_BPEL_EXC, + RA_CALLBACK_BPEL_COMPLETE, + RA_SDNC_MISS_CONFIG_PARAM, + RA_SDNC_INVALID_CONFIG, + RA_PRINT_URL, + RA_ERROR_CREATE_SDNC_REQUEST, + RA_ERROR_CREATE_SDNC_RESPONSE, + RA_ERROR_CONVERT_XML2STR, + RA_RECEIVE_SDNC_NOTIF, + RA_INIT_SDNC_ADAPTER, + RA_SEND_REQUEST_APPC_ERR, + RA_SEND_REQUEST_SDNC_ERR, + RA_RECEIVE_BPEL_REQUEST, + RA_TENANT_ALREADY_EXIST, + RA_UPDATE_TENANT_ERR, + RA_DELETE_TEMAMT_ERR, + RA_ROLLBACK_TENANT_ERR, + RA_QUERY_VNF_ERR, + RA_VNF_ALREADY_EXIST, + RA_VNF_UNKNOWN_PARAM, + RA_VNF_EXTRA_PARAM, + RA_CREATE_VNF_ERR, + RA_VNF_NOT_EXIST, + RA_UPDATE_VNF_ERR, + RA_DELETE_VNF_ERR, + RA_ASYNC_CREATE_VNF, + RA_SEND_VNF_NOTIF_ERR, + RA_ASYNC_CREATE_VNF_COMPLETE, + RA_ASYNC_UPDATE_VNF, + RA_ASYNC_UPDATE_VNF_COMPLETE, + RA_ASYNC_QUERY_VNF, + RA_ASYNC_QUERY_VNF_COMPLETE, + RA_ASYNC_DELETE_VNF, + RA_ASYNC_DELETE_VNF_COMPLETE, + RA_ASYNC_ROLLBACK_VNF, + RA_ASYNC_ROLLBACK_VNF_COMPLETE, + RA_ROLLBACK_VNF_ERR, + RA_DB_INVALID_STATUS, + RA_CANT_UPDATE_REQUEST, + RA_DB_REQUEST_NOT_EXIST, + RA_CONFIG_NOT_FOUND, + RA_CONFIG_LOAD, + // BPEL engine Messages + BPMN_GENERAL_INFO, + BPMN_GENERAL_EXCEPTION_ARG, + BPMN_GENERAL_EXCEPTION, + BPMN_GENERAL_WARNING, + BPMN_AUDIT_EXEC, + BPMN_GENERAL_METRICS, + BPMN_URN_MAPPING_FAIL, + BPMN_VARIABLE_NULL, + BPMN_SDNC_CALLBACK_EXCEPTION, + // ASDC Messages + ASDC_GENERAL_EXCEPTION_ARG, + ASDC_GENERAL_EXCEPTION, + ASDC_GENERAL_WARNING, + ASDC_AUDIT_EXEC, + ASDC_GENERAL_METRICS, + ASDC_CREATE_SERVICE, + ASDC_ARTIFACT_ALREADY_DEPLOYED, + ASDC_CREATE_ARTIFACT, + ASDC_ARTIFACT_INSTALL_EXC, + ASDC_ARTIFACT_ALREADY_DEPLOYED_DETAIL, + ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL, + ASDC_ARTIFACT_CHECK_EXC, + ASDC_INIT_ASDC_CLIENT_EXC, + ASDC_INIT_ASDC_CLIENT_SUC, + ASDC_LOAD_ASDC_CLIENT_EXC, + ASDC_SINGLETON_CHECKT_EXC, + ASDC_SHUTDOWN_ASDC_CLIENT_EXC, + ASDC_CHECK_HEAT_TEMPLATE, + ASDC_START_INSTALL_ARTIFACT, + ASDC_ARTIFACT_TYPE_NOT_SUPPORT, + ASDC_ARTIFACT_ALREADY_EXIST, + ASDC_ARTIFACT_DOWNLOAD_SUC, + ASDC_ARTIFACT_DOWNLOAD_FAIL, + ASDC_START_DEPLOY_ARTIFACT, + ASDC_SEND_NOTIF_ASDC, + ASDC_SEND_NOTIF_ASDC_EXEC, + ASDC_RECEIVE_CALLBACK_NOTIF, + ASDC_RECEIVE_SERVICE_NOTIF, + ASDC_ARTIFACT_NULL, + ASDC_SERVICE_NOT_SUPPORT, + ASDC_ARTIFACT_DEPLOY_SUC, + ASDC_PROPERTIES_NOT_FOUND, + // Default Messages, in case Log catalog is not defined + GENERAL_EXCEPTION_ARG, + GENERAL_EXCEPTION, + GENERAL_WARNING, + AUDIT_EXEC, + GENERAL_METRICS, + LOGGER_SETUP, + LOGGER_NOT_FOUND, + LOGGER_UPDATE_SUC, + LOGGER_UPDATE_DEBUG, + LOGGER_UPDATE_DEBUG_SUC, + LOAD_PROPERTIES_SUC, + NO_PROPERTIES, + MADATORY_PARAM_MISSING, + LOAD_PROPERTIES_FAIL, + INIT_LOGGER, + INIT_LOGGER_FAIL, + JAXB_EXCEPTION, + IDENTITY_SERVICE_NOT_FOUND; + + static { + EELFResourceManager.loadMessageBundle("GenericMessages"); + EELFResourceManager.loadMessageBundle("ApiHandler"); + EELFResourceManager.loadMessageBundle("BPMN"); + EELFResourceManager.loadMessageBundle("ResourceAdapter"); + EELFResourceManager.loadMessageBundle("ASDC"); + } +} diff --git a/common/src/main/java/org/openecomp/mso/logger/MsoAlarmLogger.java b/common/src/main/java/org/openecomp/mso/logger/MsoAlarmLogger.java new file mode 100644 index 0000000000..147c1ad4f1 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/logger/MsoAlarmLogger.java @@ -0,0 +1,181 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.logger; + + +import java.io.File; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + +import org.slf4j.LoggerFactory; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.encoder.PatternLayoutEncoder; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.rolling.RollingFileAppender; +import ch.qos.logback.core.rolling.TimeBasedRollingPolicy; + +/** + * Wrapper around log4j and Nagios NRDP passive alarming for MSO. + * + * For local alarm logging, this class will look for an alarm log file name + * in the servlet context parameter "mso.alarms.file". If none is found, + * it will look for an MsoProperty of the same name. As a last resort, + * it will use the default path "/var/log/ecomp/MSO/alarms/alarm.log". + * It is expected that all alarms within an application will use the same + * alarm file, so there is no way to dynamically add other alarm files. + * + * Alarms are logged as a simple pipe-delimited string of the format: + * <dateTime>|<alarmType>|<state>|<detailMessage> + * + * This class also supports real-time Nagios NRDP alarming. If enabled via + * MsoProperties, all alarms generated and logged to the local alarm file will + * also be transmitted to a Nagios NRDP instance. NRDP requires 4 parameters + * in service alarm events (all Mso Alarms will be Service Alarms): + * hostname, servicename, state, detail + * + * The log file format is also intended to be compatible with Nagios NRDP for + * non-real-time reporting. The command-line tool for sending alarms is + * is "send_nrdp.php", which takes the same 4 parameters as input. + * It will be easy enough to translate entries from an alarm.log file to + * NRDP if real-time NRDP alarming is not enabled. + * + * For Nagios integration, the alarmTypes should all match "service names" + * configured in the receiving Nagios server. Also, the alarm state will + * be limited to the 4 values defined by Nagios: + * 0 = OK, 1 = Warning, 2 = Critical, 3 = Unknown + * + * + */ +public class MsoAlarmLogger implements ServletContextListener { + + private Logger alarmLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(MSO_ALARM_CONTEXT); + private static RollingFileAppender<ILoggingEvent> fileAppender = null; + public static final String DEFAULT_MSO_ALARM_FILE = "/var/log/ecomp/MSO/alarms/alarm.log"; + public static final String MSO_ALARM_CONTEXT = "mso.alarms"; + + public static final int OK = 0; + public static final int WARNING = 1; + public static final int CRITICAL = 2; + public static final int UNKNOWN = 3; + + /** + * Get the default MSO Alarm Logger + */ + public MsoAlarmLogger () { + + initializeAlarmLogger(null); + + } + + public MsoAlarmLogger (String alarmFile) { + initializeAlarmLogger(alarmFile); + + } + + /** + * Method to record an alarm. + * + * @param alarm - the alarm identifier (Nagios "service") + * @param state - the alarm state/severity, based on Nagios service + * state values: 0 = OK, 1 = Warning, 2 = Critical, 3 = Unknown + * @param detail - detail message (may contain additional internal + * structure per alarm type) + */ + public void sendAlarm (String alarm, int state, String detail) { + // Write the alarm to Log file + if (alarmLogger != null) { + String output = alarm + "|" + state + "|" + detail; + alarmLogger.info (output); + } + + } + + @Override + public void contextDestroyed (ServletContextEvent event) { + // Nothing to do... + } + + @Override + public void contextInitialized (ServletContextEvent event) { + String msoAlarmFile = event.getServletContext ().getInitParameter ("mso.alarm.file"); + if (msoAlarmFile == null) { + msoAlarmFile = DEFAULT_MSO_ALARM_FILE; + } + + initializeAlarmLogger (msoAlarmFile); + } + + private void initializeAlarmLogger (String alarmFile) { + synchronized (MsoAlarmLogger.class) { + if (fileAppender == null) { + if (alarmFile != null) { + fileAppender = MsoAlarmLogger.getAppender (alarmFile); + } else { + fileAppender = MsoAlarmLogger.getAppender (DEFAULT_MSO_ALARM_FILE); + } + } + } + // The alarmLogger was static originally. + // The initialization of the alarmLogger was fine, but not sure why, it lost its appender info later + // Due to that issue, the alarmLogger is not static any more. + // Instead static attribute fileAppender is added and will be assigned to the alarmLogger every time new MsoAlarmLogger is created. + alarmLogger.setLevel (Level.INFO); + alarmLogger.addAppender (fileAppender); + alarmLogger.setAdditive (false); + } + + + private static RollingFileAppender<ILoggingEvent> getAppender (String msoAlarmFile) { + // Create a Logger for alarms. Just use a default Pattern that outputs + // a message. MsoAlarmLogger will handle the formatting. + File alarmFile = new File (msoAlarmFile); + File alarmDir = alarmFile.getParentFile (); + if (!alarmDir.exists ()) { + alarmDir.mkdirs (); + } + + String logPattern = "%d{yyyy-MM-dd HH:mm:ss}|%m%n"; + + LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); + PatternLayoutEncoder encoder=new PatternLayoutEncoder(); + encoder.setPattern(logPattern); + encoder.setContext(context); + encoder.start(); + RollingFileAppender<ILoggingEvent> fileAppender=new RollingFileAppender<ILoggingEvent>(); + TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy=new TimeBasedRollingPolicy<ILoggingEvent>(); + rollingPolicy.setContext(context); + rollingPolicy.setFileNamePattern(msoAlarmFile + ".%d"); + rollingPolicy.setParent(fileAppender); + rollingPolicy.start(); + fileAppender.setFile(msoAlarmFile); + fileAppender.setAppend(true); + fileAppender.setEncoder(encoder); + fileAppender.setRollingPolicy(rollingPolicy); + fileAppender.setContext(context); + fileAppender.start(); + + return fileAppender; + } + +} diff --git a/common/src/main/java/org/openecomp/mso/logger/MsoLogInitializer.java b/common/src/main/java/org/openecomp/mso/logger/MsoLogInitializer.java new file mode 100644 index 0000000000..0c96dabbea --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/logger/MsoLogInitializer.java @@ -0,0 +1,108 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.logger; + + +import java.io.File; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.servlet.annotation.WebListener; + +import org.slf4j.LoggerFactory; + +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.joran.JoranConfigurator; + + +/** + * This class will attempt to initialize MSO log4j when part of a web application. + * It will look for the logback configuration file logback.xml in the + * following order: + * 1. In an init-param "log.configuration" in web.xml + * 2. TODO: In a property "log.configuration" in an "application.properties" file + * 3. In the default location "/etc/ecomp/mso/config" + * 4. Using the log4j default (check system property log.configuration or + * just look on the classpath for logback.xml) + * + * + */ +@WebListener +public class MsoLogInitializer implements ServletContextListener +{ + private static String DEFAULT_LOG4J_PROPERTIES_FILE = "/etc/ecomp/mso/config/logback.xml"; + private static String prefixMsoPropertiesPath = System.getProperty("mso.config.path"); + static { + if (prefixMsoPropertiesPath == null) { + prefixMsoPropertiesPath = "/"; + } else if (!(prefixMsoPropertiesPath.charAt(prefixMsoPropertiesPath.length() - 1) == '/')) { + prefixMsoPropertiesPath = prefixMsoPropertiesPath + "/"; + } + } + + public MsoLogInitializer () { + } + + + @Override + public void contextDestroyed(ServletContextEvent event) { + // Nothing to do... + } + + @Override + public void contextInitialized(ServletContextEvent event) + { + String logPropertiesFile = null; + try { + // Look first in the init-parameters + String initParam = event.getServletContext().getInitParameter("log.configuration"); + if (initParam != null && fileIsReadable(prefixMsoPropertiesPath + initParam)) { + logPropertiesFile = prefixMsoPropertiesPath + initParam; + } + else if (fileIsReadable(DEFAULT_LOG4J_PROPERTIES_FILE)) { + logPropertiesFile = DEFAULT_LOG4J_PROPERTIES_FILE; + } + + if (logPropertiesFile != null) { + // Initialize loggers with the specified file. If no such file was + // specified, will use the default Log4j resolution. + LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(context); + context.reset(); + jc.doConfigure(logPropertiesFile); + // Try it out + MsoLogger initLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL); + initLogger.info(MessageEnum.INIT_LOGGER, logPropertiesFile, "", ""); + } + } catch (Exception e) { + MsoLogger initLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL); + initLogger.error (MessageEnum.INIT_LOGGER_FAIL, "", "", MsoLogger.ErrorCode.UnknownError, "", e); + } + } + + private boolean fileIsReadable (String filePath) { + File f = new File(filePath); + if (f.exists() && f.canRead()) + return true; + return false; + } +} diff --git a/common/src/main/java/org/openecomp/mso/logger/MsoLogger.java b/common/src/main/java/org/openecomp/mso/logger/MsoLogger.java new file mode 100644 index 0000000000..c53022734f --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/logger/MsoLogger.java @@ -0,0 +1,973 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.logger; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.UUID; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.slf4j.MDC; + +import org.openecomp.mso.entity.MsoRequest; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * Simple wrapper around the EELF Logger class for MSO usage. + * This class supports all of the normal logging functions (debug, info, etc.), + * prepending a string of format "[<requestId>|<serviceId]" to each message. + * + * MSO code should initialize with these IDs when available, so that individual + * requests and/or services can be tracked throughout the various MSO component + * logs (API Handler, BPEL, and Adapters). + * + * + */ +public class MsoLogger { + // MDC parameters + public static final String REQUEST_ID = "RequestId"; + public static final String SERVICE_INSTANCE_ID = "ServiceInstanceId"; + public static final String SERVICE_NAME = "ServiceName"; + private static final String SERVICE_NAME_IS_METHOD_NAME = "ServiceNameIsMethodName"; + private static final String INSTANCE_UUID = "InstanceUUID"; + private static final String SERVER_IP = "ServerIPAddress"; + private static final String FQDN = "ServerFQDN"; + public static final String REMOTE_HOST = "RemoteHost"; + public static final String ALERT_SEVERITY = "AlertSeverity"; + public static final String TIMER = "Timer"; + private static final String USER = "User"; + private static final String DUMMY_VALUE = "trace-#"; + public static final String UNKNOWN = "UNKNOWN"; + // Audit/Metric log specigic + private static final String BEGINTIME = "BeginTimestamp"; + private static final String ENDTIME = "EndTimestamp"; + public static final String PARTNERNAME = "PartnerName"; + private static final String STATUSCODE = "StatusCode"; + private static final String RESPONSECODE = "ResponseCode"; + private static final String RESPONSEDESC = "ResponseDesc"; + // Metric log specigic + private static final String TARGETENTITY = "TargetEntity"; + private static final String TARGETSERVICENAME = "TargetServiceName"; + private static final String TARGETVIRTUALENTITY = "TargetVirtualEntity"; + + private static final String FATAL_LEVEL = "FATAL"; + private static final String ERROR_LEVEL = "ERROR"; + private static final String WARN_LEVEL = "WARN"; + private static final String INFO_LEVEL = "INFO"; + private static final String DEBUG_LEVEL = "DEBUG"; + + private static final String ERRORCODE = "ErrorCode"; + private static final String ERRORDESC = "ErrorDesc"; + +public enum Catalog {APIH, BPEL, RA, ASDC, GENERAL}; + public enum StatusCode {COMPLETE, ERROR}; + public enum ResponseCode {Suc(0), PermissionError(100), + DataError(300), DataNotFound(301), BadRequest (302), + SchemaError(400), + BusinessProcesssError(500), ServiceNotAvailable (501), InternalError (502), Conflict (503), DBAccessError(504), CommunicationError(505), + UnknownError(900); + + private int value; + public int getValue () { + return this.value; + } + private ResponseCode (int value) { + this.value = value; + } + }; + + public enum ErrorCode {PermissionError(100), AvailabilityError(200), + DataError(300), SchemaError(400), + BusinessProcesssError(500), + UnknownError(900); + + private int value; + public int getValue () { + return this.value; + } + private ErrorCode (int value) { + this.value = value; + } + }; + + private EELFLogger logger, auditLogger, metricsLogger; + private static final String CONFIG_FILE = System.getProperty ("jboss.home.dir") + "/mso-config/uuid/uuid_" + + System.getProperty ("jboss.server.name"); + private static String instanceUUID, serverIP, serverName; + private MessageEnum exceptionArg, defaultException, defaultWarning, defaultAudit, defaultMetrics; + + // For internal logging of the initialization of MSO logs + private static final Logger LOGGER = Logger.getLogger (MsoLogger.class.getName ()); + + + private MsoLogger (MsoLogger.Catalog cat) { + this.logger = EELFManager.getInstance().getErrorLogger(); + this.auditLogger = EELFManager.getInstance().getAuditLogger(); + this.metricsLogger = EELFManager.getInstance().getMetricsLogger(); + MsoLogger.initialization (); + setDefaultLogCatalog (cat); + } + + private static synchronized void initialization () { + if (instanceUUID == null || ("").equals (instanceUUID)) { + instanceUUID = getInstanceUUID (); + } + + if (serverIP == null || serverName == null || ("").equals (serverIP) || ("").equals (serverName)) { + try { + InetAddress server = InetAddress.getLocalHost (); + serverIP = server.getHostAddress (); + serverName = server.getHostName (); + } catch (UnknownHostException e) { + LOGGER.log (Level.SEVERE, "Could not get local hostname", e); + serverIP = ""; + serverName = ""; + } + } + } + + /** + * Get the MsoLogger based on the catalog + * @param cat Catalog of the logger + * @return the MsoLogger + */ + public static synchronized MsoLogger getMsoLogger (MsoLogger.Catalog cat) { + return new MsoLogger (cat); + } + + /** + * Record the Metrics event with no argument + * @param startTime Transaction starting time in millieseconds + * @param statusCode StatusCode of the transaction, either COMPLETE or ERROR + * @param responseCode The response code returned by the sub-components + * @param responseDesc Human redable description of the response code + * @param targetEntity The component which is invoked for this sub-operation + * @param targetServiceName API invoked on the TargetEntity + * @param targetVEntity Target VNF or VM acted opon by the component, if available + */ + public void recordMetricEvent (Long startTime, StatusCode statusCode, ResponseCode responseCode, String responseDesc, String targetEntity, String targetServiceName, String targetVEntity) { + prepareMetricMsg (startTime, statusCode, responseCode.getValue (), responseDesc, targetEntity, targetServiceName, targetVEntity); + metricsLogger.info (""); + MDC.remove(TIMER); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Audit event + * + * @param startTime Transaction starting time in millieseconds + * @param statusCode StatusCode of the transaction, either COMPLETE or ERROR + * @param responseCode The application specific response code + * @param responseDesc Human redable description of the application response code + */ + public void recordAuditEvent (Long startTime, StatusCode statusCode, ResponseCode responseCode, String responseDesc) { + prepareAuditMsg (startTime, statusCode, responseCode.getValue (), responseDesc); + auditLogger.info (""); + MDC.remove(TIMER); + } + + // Debug methods + /** + * Record the Debug event + * + * @param msg The log message to put + */ + public void debug (String msg) { + prepareMsg (DEBUG_LEVEL); + logger.debug (msg); + } + + /** + * Record the Debug event + * + * @param msg The log message to put + * @param t The exception to put + */ + public void debug (String msg, Throwable t) { + prepareMsg (DEBUG_LEVEL); + logger.debug (msg, t); + } + + // Info methods + /** + * Record the Info event + * + * @param msg The log message to put + */ + public void info (MessageEnum msg, String targetEntity, String targetServiceName) { + prepareErrorMsg (INFO_LEVEL, targetEntity, targetServiceName, null, ""); + + logger.info (msg); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Info event with 1 argument + * + * @param msg The log message to put + * @param arg0 The argument used in the log message + */ + public void info (MessageEnum msg, String arg0, String targetEntity, String targetServiceName) { + prepareErrorMsg (INFO_LEVEL, targetEntity, targetServiceName, null, ""); + + logger.info (msg, normalize(arg0)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Info event with 2 arguments + * + * @param msg The log message to put + * @param arg0,arg1 The arguments used in the log message + */ + public void info (MessageEnum msg, String arg0, String arg1, String targetEntity, String targetServiceName) { + prepareErrorMsg (INFO_LEVEL, targetEntity, targetServiceName, null, ""); + + logger.info (msg, normalize(arg0), normalize(arg1)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Info event with 3 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2 The arguments used in the log message + */ + public void info (MessageEnum msg, String arg0, String arg1, String arg2, String targetEntity, String targetServiceName) { + prepareErrorMsg (INFO_LEVEL, targetEntity, targetServiceName, null, ""); + + logger.info (msg, normalize(arg0), normalize(arg1), normalize(arg2)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Info event with 4 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2,arg3 The arguments used in the log message + */ + public void info (MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String targetEntity, String targetServiceName) { + prepareErrorMsg (INFO_LEVEL, targetEntity, targetServiceName, null, ""); + + logger.info (msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Info event with 5 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2,arg3,arg4 The arguments used in the log message + */ + public void info (MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4, String targetEntity, String targetServiceName) { + prepareErrorMsg (INFO_LEVEL, targetEntity, targetServiceName, null, ""); + + logger.info (msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Info event with 6 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2,arg3,arg4,arg5 The arguments used in the log message + */ + public void info (MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4, String arg5, String targetEntity, String targetServiceName) { + prepareErrorMsg (INFO_LEVEL, targetEntity, targetServiceName, null, ""); + + logger.info (msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4), normalize(arg5)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + // Warning methods + /** + * Record the Warning event + * + * @param msg The log message to put + */ + public void warn (MessageEnum msg, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + + logger.warn (msg); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Warning event + * + * @param msg The log message to put + * @param t The exception info + */ + public void warn (MessageEnum msg, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.warn (msg); + logger.warn ("Exception raised: " + getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Warn event with 1 argument + * + * @param msg The log message to put + * @param arg The argument used in the log message + */ + public void warn (MessageEnum msg, String arg, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.warn (msg, arg); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Warn event with 1 argument + * + * @param msg The log message to put + * @param arg The arguments used in the log message + * @param t The exception info + */ + public void warn (MessageEnum msg, String arg, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.warn (msg, arg); + logger.warn ("Exception raised: " + getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Warn event with 2 arguments + * + * @param msg The log message to put + * @param arg0,arg1 The arguments used in the log message + */ + public void warn (MessageEnum msg, String arg0, String arg1, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.warn (msg, normalize(arg0), normalize(arg1)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Warn event with 2 arguments + * + * @param msg The log message to put + * @param arg0,arg1 The arguments used in the log message + * @param t The exception info + */ + public void warn (MessageEnum msg, String arg0, String arg1, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.warn (msg, normalize(arg0), normalize(arg1)); + logger.warn ("Exception raised: " + getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Warn event with 3 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2 The arguments used in the log message + */ + public void warn (MessageEnum msg, String arg0, String arg1, String arg2, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.warn (msg, normalize(arg0), normalize(arg1), normalize(arg2)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Warn event with 3 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2 The arguments used in the log message + * @param t The exception info + */ + public void warn (MessageEnum msg, String arg0, String arg1, String arg2, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.warn (msg, normalize(arg0), normalize(arg1), normalize(arg2)); + logger.warn ("Exception raised: " + getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Warn event with 4 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2,arg3 The arguments used in the log message + */ + public void warn (MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.warn (msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Warn event with 4 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2, arg3 The arguments used in the log message + * @param t The exception info + */ + public void warn (MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.warn (msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); + logger.warn ("Exception raised: " + getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Warn event with 5 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2,arg3,arg4 The arguments used in the log message + */ + public void warn (MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.warn (msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Warn event with 5 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2,arg3,arg4 The arguments used in the log message + * @param t The exception info + */ + public void warn (MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.warn (msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); + logger.warn ("Exception raised: " + getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + // Error methods + /** + * Record the Error event + * + * @param msg The log message to put + */ + public void error (MessageEnum msg, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Error event + * + * @param msg The log message to put + * @param t The exception info + */ + public void error (MessageEnum msg, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg); + logger.error (exceptionArg, getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Error event with 1 argument + * + * @param msg The log message to put + * @param arg0 The arguments used in the log message + */ + public void error (MessageEnum msg, String arg0, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg, normalize(arg0)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Error event with 1 argument + * + * @param msg The log message to put + * @param arg0 The arguments used in the log message + * @param t The exception info + */ + public void error (MessageEnum msg, String arg0, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg, normalize(arg0)); + logger.error (exceptionArg, getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Error event with 2 arguments + * + * @param msg The log message to put + * @param arg0,arg1 The arguments used in the log message + */ + public void error (MessageEnum msg, String arg0, String arg1, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg, normalize(arg0), normalize(arg1)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Error event with 2 arguments + * + * @param msg The log message to put + * @param arg0,arg1 The arguments used in the log message + * @param t The exception info + */ + public void error (MessageEnum msg, String arg0, String arg1, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg, normalize(arg0), normalize(arg1)); + logger.error (exceptionArg, getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Error event with 3 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2 The arguments used in the log message + */ + public void error (MessageEnum msg, String arg0, String arg1, String arg2, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg, normalize(arg0), normalize(arg1), normalize(arg2)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Error event with 3 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2 The arguments used in the log message + * @param t The exception info + */ + public void error (MessageEnum msg, String arg0, String arg1, String arg2, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg, normalize(arg0), normalize(arg1), normalize(arg2)); + logger.error (exceptionArg, getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Error event with 4 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2,arg3 The arguments used in the log message + */ + public void error (MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Error event with 4 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2,arg3 The arguments used in the log message + * @param t The exception info + */ + public void error (MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); + logger.error (exceptionArg, getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Error event with 5 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2,arg3,arg4 The arguments used in the log message + */ + public void error (MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + /** + * Record the Error event with 5 arguments + * + * @param msg The log message to put + * @param arg0,arg1,arg2,arg3,arg4 The arguments used in the log message + * @param t The exception info + */ + public void error (MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { + prepareErrorMsg (ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); + logger.error (msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); + logger.error (exceptionArg, getNormalizedStackTrace (t)); + logger.debug ("Exception raised", t); + MDC.remove(TARGETENTITY); + MDC.remove(TARGETSERVICENAME); + } + + + + public boolean isDebugEnabled () { + return logger.isDebugEnabled(); + } + + private void prepareMsg (String loggingLevel) { + prepareMsg (loggingLevel, null, null); + } + + private void prepareMsg (String loggingLevel, String serviceNamep, String timer) { + String reqId = MDC.get (REQUEST_ID); + String svcId = MDC.get (SERVICE_INSTANCE_ID); + + // Based on the discussion with Adrian, + // if these 2 parameters is not available, using dummy value "trace-#" + if (reqId == null || reqId.isEmpty()) { + MDC.put (REQUEST_ID, DUMMY_VALUE); + } + + if (svcId == null || svcId.isEmpty()) { + MDC.put (SERVICE_INSTANCE_ID, DUMMY_VALUE); + } + + if (timer != null) { + MDC.put (TIMER, timer); + } else { + MDC.remove(TIMER); + } + + MDC.put (SERVICE_NAME, getFinalServiceName (serviceNamep)); + MDC.put (ALERT_SEVERITY, getSeverityLevel (loggingLevel)); + MDC.put (INSTANCE_UUID, instanceUUID); + MDC.put (SERVER_IP, serverIP); + MDC.put (FQDN, serverName); + } + + private void prepareAuditMsg ( long startTime, StatusCode statusCode, int responseCode, String responseDesc) { + long endTime = System.currentTimeMillis(); + prepareMsg (INFO_LEVEL, null, String.valueOf(endTime - startTime)); + prepareAuditMetricMsg (startTime, endTime, statusCode, responseCode, responseDesc); + } + + private void prepareAuditMetricMsg ( long startTime, long endTime, StatusCode statusCode, int responseCode, String responseDesc) { + Date startDate = new Date(startTime); + Date endDate = new Date(endTime); + DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + + MDC.put (BEGINTIME, String.valueOf(formatter.format(startDate))); + MDC.put (ENDTIME, String.valueOf(formatter.format(endDate))); + MDC.put (STATUSCODE, statusCode.name()); + MDC.put (RESPONSECODE, String.valueOf(responseCode)); + MDC.put (RESPONSEDESC, responseDesc); + } + + private void prepareErrorMsg (String loggingLevel, String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { + MDC.put (ALERT_SEVERITY, getSeverityLevel (loggingLevel)); + MDC.put (ERRORCODE, String.valueOf(errorCode)); + MDC.put (ERRORDESC, errorDesc); + MDC.put (TARGETENTITY, targetEntity); + MDC.put (TARGETSERVICENAME, targetServiceName); + MDC.put (SERVICE_NAME, getFinalServiceName (getServiceName())); + } + + private void prepareMetricMsg ( long startTime, StatusCode statusCode, int responseCode, String responseDesc, String targetEntity, String targetServiceName, String targetVEntity) { + long endTime = System.currentTimeMillis(); + prepareMsg (INFO_LEVEL, null, String.valueOf(endTime - startTime)); + prepareAuditMetricMsg (startTime, endTime, statusCode, responseCode, responseDesc); + + // Populate Metric log specific parameter + MDC.put (TARGETENTITY, targetEntity); + MDC.put (TARGETSERVICENAME, targetServiceName); + + if (null != targetVEntity) { + MDC.put(TARGETVIRTUALENTITY, targetVEntity); + } + } + + private String getSeverityLevel (String loggingLevel) { + String severity; + // According to the Nagios alerting: 0=OK; 1=WARNING; 2=UNKOWN; 3=CRITICAL + switch (loggingLevel) { + case ERROR_LEVEL: + severity = "2"; + break; + case FATAL_LEVEL: + severity = "3"; + break; + case WARN_LEVEL: + severity = "1"; + break; + default: + severity = "0"; + break; + } + return severity; + } + + private String getFinalServiceName (String serviceNamep) { + // This step to set the serviceName should be put after the className is get, + // since the default serviceName is obtained during the method to get the className. + // + // There's 3 ways to set the serviceName. The first method has the most priority to set the value. + // a) If the serviceName is set within the log method, this value will be used first + // b) If serviceName is not set within the log method, the value defined in the MDC will be used + // c) If nothing is set specifically, then MsoLogger will assign a default(MSO.<method_name>) value to it + String serName = MDC.get (MsoLogger.SERVICE_NAME); + + // Check if service name was already set as the method name by a previous call to this method. + String isMethodNameStr = MDC.get (MsoLogger.SERVICE_NAME_IS_METHOD_NAME); + boolean isMethodName = isMethodNameStr != null && isMethodNameStr.equals (Boolean.TRUE.toString ()); + if (serviceNamep != null) { + return serviceNamep; + } else if (serName != null && !isMethodName) { + return serName; + } + + MDC.put (MsoLogger.SERVICE_NAME_IS_METHOD_NAME, Boolean.TRUE.toString ()); + int limit; + StackTraceElement[] classArr = new Exception ().getStackTrace (); + if (classArr.length >=6) { + limit = 7; + } else { + limit = classArr.length; + } + for (int i = 1; i < limit; i++) { + String className = classArr[i].getClassName (); + if (!className.equals (this.getClass ().getName ())) { + return classArr[i].getMethodName (); + } + } + return classArr[0].getMethodName (); + } + + // Based on the discussion with Adrian, instanceUUID is used to identifiy the mso instance, + // it is generated during mso instance initialization period + // The same mso instnace will use the same instanceUUID value, even after restart + private static String getInstanceUUID () { + // Avoid creation during build and tests + if (System.getProperty ("jboss.server.name") == null) { + return "Test UUID as JBoss not found"; + } + File configFile = new File (CONFIG_FILE); + String uuid = ""; + BufferedReader in = null; + BufferedWriter bw = null; + try { + // Verify whether instanceUUID file exist, + // If yes, read the content; if not, generate the instanceUUID and write to the file + if (configFile.exists ()) { + // read the content of the file + in = new BufferedReader (new FileReader (CONFIG_FILE)); + if ((uuid = in.readLine ()) == null) { + // the file is empty, regenerate the file + uuid = UUID.randomUUID ().toString (); + FileWriter fw = new FileWriter (configFile.getAbsoluteFile ()); + bw = new BufferedWriter (fw); + bw.write (uuid); + bw.close (); + } + in.close (); + } else { + // file doesn't exist yet -> create the file and generate the instanceUUID + uuid = UUID.randomUUID ().toString (); + configFile.getParentFile ().mkdirs (); + configFile.createNewFile (); + FileWriter fw = new FileWriter (configFile.getAbsoluteFile ()); + bw = new BufferedWriter (fw); + bw.write (uuid); + bw.close (); + } + } catch (IOException e) { + LOGGER.log (Level.SEVERE, "Error trying to read UUID file", e); + } finally { + try { + if (in != null) { + in.close (); + } + if (bw != null) { + bw.close (); + } + } catch (IOException ex) { + LOGGER.log (Level.SEVERE, "Error trying to close UUID file", ex); + } + } + return uuid; + } + + /** + * Set the requestId and serviceInstanceId + * @param reqId The requestId + * @param svcId The serviceInstanceId + */ + public static void setLogContext (String reqId, String svcId) { + if (null != reqId) { + MDC.put (REQUEST_ID, reqId); + } + + if (null != svcId) { + MDC.put (SERVICE_INSTANCE_ID, svcId); + } + } + + /** + * Set the remoteIp and the basic HTTP Authentication user + * @param remoteIpp The remote ip address + * @param userp The basic http authencitation user + */ + public static void setLoggerParameters (String remoteIpp, String userp) { + if (null != remoteIpp) { + MDC.put (REMOTE_HOST, remoteIpp); + } + if (null != userp) { + MDC.put (USER, userp); + } + } + + /** + * Set the serviceName + * @param serviceNamep The service name + */ + public static void setServiceName (String serviceNamep) { + if (null != serviceNamep) { + MDC.put (SERVICE_NAME, serviceNamep); + MDC.remove (SERVICE_NAME_IS_METHOD_NAME); + } + } + + /** + * Get the serviceName + * @return The service name + */ + public static String getServiceName () { + return MDC.get (SERVICE_NAME); + } + + /** + * Reset the serviceName + */ + public static void resetServiceName () { + MDC.remove (SERVICE_NAME); + } + + /** + * Set the requestId and serviceInstanceId based on the mso request + * @param msoRequest The mso request + */ + public static void setLogContext (MsoRequest msoRequest) { + if (msoRequest != null) { + MDC.put (REQUEST_ID, msoRequest.getRequestId()); + MDC.put (SERVICE_INSTANCE_ID, msoRequest.getServiceInstanceId()); + } + else { + MDC.put (REQUEST_ID, DUMMY_VALUE); + MDC.put (SERVICE_INSTANCE_ID, DUMMY_VALUE); + } + } + + private String normalize (String input) { + if (input == null) { + return null; + } + String result = input.replace ('|', '!'); + result = result.replace ("\n", " - "); + return result; + } + + private String getNormalizedStackTrace (Throwable t) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + t.printStackTrace(pw); + return sw.toString().replace ('|', '!').replace ("\n", " - "); + } + + private void setDefaultLogCatalog (MsoLogger.Catalog cat) { + if ("APIH".equals(cat.toString())) { + exceptionArg = MessageEnum.APIH_GENERAL_EXCEPTION_ARG; + defaultException = MessageEnum.APIH_GENERAL_EXCEPTION; + defaultWarning = MessageEnum.APIH_GENERAL_WARNING; + defaultAudit = MessageEnum.APIH_AUDIT_EXEC; + defaultMetrics = MessageEnum.APIH_GENERAL_METRICS; + } else if ("RA".equals(cat.toString())) { + exceptionArg = MessageEnum.RA_GENERAL_EXCEPTION_ARG; + defaultException = MessageEnum.RA_GENERAL_EXCEPTION; + defaultWarning = MessageEnum.RA_GENERAL_WARNING; + defaultAudit = MessageEnum.RA_AUDIT_EXEC; + defaultMetrics = MessageEnum.RA_GENERAL_METRICS; + } else if ("BPEL".equals(cat.toString())) { + exceptionArg = MessageEnum.BPMN_GENERAL_EXCEPTION_ARG; + defaultException = MessageEnum.BPMN_GENERAL_EXCEPTION; + defaultWarning = MessageEnum.BPMN_GENERAL_WARNING; + defaultAudit = MessageEnum.BPMN_AUDIT_EXEC; + defaultMetrics = MessageEnum.BPMN_GENERAL_METRICS; + } else if ("ASDC".equals(cat.toString())) { + exceptionArg = MessageEnum.ASDC_GENERAL_EXCEPTION_ARG; + defaultException = MessageEnum.ASDC_GENERAL_EXCEPTION; + defaultWarning = MessageEnum.ASDC_GENERAL_WARNING; + defaultAudit = MessageEnum.ASDC_AUDIT_EXEC; + defaultMetrics = MessageEnum.ASDC_GENERAL_METRICS; + } else { + exceptionArg = MessageEnum.GENERAL_EXCEPTION_ARG; + defaultException = MessageEnum.GENERAL_EXCEPTION; + defaultWarning = MessageEnum.GENERAL_WARNING; + defaultAudit = MessageEnum.AUDIT_EXEC; + defaultMetrics = MessageEnum.GENERAL_METRICS; + } + } +} diff --git a/common/src/main/java/org/openecomp/mso/logger/MsoLoggingServlet.java b/common/src/main/java/org/openecomp/mso/logger/MsoLoggingServlet.java new file mode 100644 index 0000000000..568ab22447 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/logger/MsoLoggingServlet.java @@ -0,0 +1,155 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.logger; + + +import java.util.List; + +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; + +import org.slf4j.LoggerFactory; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.joran.JoranConfigurator; +import ch.qos.logback.core.Appender; + +@Path("/logging") +public class MsoLoggingServlet { + + private static final String DEBUGLOG = "asyncEELFDebug"; + private MsoLogger logger = MsoLogger.getMsoLogger (MsoLogger.Catalog.GENERAL); + private static final String GENERAL_LOGGER = "com.att.eelf.error"; + private static final String AUDIT_LOGGER = "com.att.eelf.audit"; + private static final String METRICS_LOGGER = "com.att.eelf.metrics"; + + @GET + @Path("/setLevel/{logContext}/{level}") + @Produces("text/plain") + public Response setLogLevel (@PathParam("logContext") String logContext, @PathParam("level") String level) { + logger.info (MessageEnum.LOGGER_SETUP, "", ""); + + LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(context); + Logger updateLogger = context.getLogger (logContext); + + if (updateLogger == null) { + logger.info (MessageEnum.LOGGER_NOT_FOUND, logContext, "", ""); + String response = "Unknown logger: " + logContext; + return Response.status (200).entity (response).build (); + } + + Level currentLevel = updateLogger.getLevel(); + if (!currentLevel.equals(Level.toLevel(level))) { + Level newLevel = Level.toLevel (level); + updateLogger.setLevel (newLevel); + logger.info (MessageEnum.LOGGER_UPDATE_SUC, updateLogger.getName (), currentLevel.toString(), newLevel.toString()); + } + + String response = "Log level set to: " + level + " for " + updateLogger.getName (); + return Response.status (200).entity (response).build (); + + } + + @GET + @Path("/loggers") + @Produces("text/plain") + @SuppressWarnings("rawtypes") + public Response getLoggers () { + StringBuilder response = new StringBuilder (); + LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(context); + List <Logger> loggerList = context.getLoggerList(); + for (Logger logger:loggerList) { + //if (logger.getLevel() != null) { + response.append (logger.getName () + ":" + logger.getLevel () + " (" + logger.getEffectiveLevel () + ")\n"); + //} + } + return Response.status (200).entity (response).build (); + + } + + @GET + @Path("/debug") + @Produces("text/plain") + @SuppressWarnings("rawtypes") + /* + * Debug log is used as a general log to store all the logs events, including events generated by MSO code or by + * components used by MSO. + * This method will only enable/disable the function to store MSO generated events into debug log, + * since those events will also be generated to error, audit, metrics log. + * The events generated by other components will not be affected by this interface. + */ + public Response updateDebugAppender (@DefaultValue("true") @QueryParam("enable") Boolean enable) { + String response; + + LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(context); + List <Logger> loggerList = context.getLoggerList(); + Logger rootLogger = context.getLogger("ROOT"); + Appender appender = rootLogger.getAppender(DEBUGLOG); + + if (null == appender) { + return Response.status (500).entity ("Not able to found Debug appender. Please verify to make sure the needed logback file is present in the config folder.").build (); + } + + if (enable) { + logger.info (MessageEnum.LOGGER_UPDATE_DEBUG, "", ""); + + for (Logger logger: loggerList) { + if (isMsoLogger (logger.getName ()) && logger.getAppender (DEBUGLOG) == null && logger.getLevel () != null) { + logger.addAppender (appender); + logger.setAdditive(false); + } + } + logger.info (MessageEnum.LOGGER_UPDATE_DEBUG_SUC, "enabled", "", ""); + response = "Debuglog successfully enabled."; + } else { + logger.info (MessageEnum.LOGGER_UPDATE_DEBUG, "", ""); + for (Logger logger: loggerList) { + if (isMsoLogger (logger.getName ())) { + logger.detachAppender (appender); + } + } + logger.info (MessageEnum.LOGGER_UPDATE_DEBUG_SUC, "disabled", "", ""); + response = "Debuglog successfully disabled."; + } + return Response.status (200).entity (response).build (); + + + } + + private boolean isMsoLogger (String loggerName) { + return loggerName.contains (GENERAL_LOGGER) || loggerName.equals (AUDIT_LOGGER) + || loggerName.equals (METRICS_LOGGER); + } + +} diff --git a/common/src/main/java/org/openecomp/mso/properties/AbstractMsoProperties.java b/common/src/main/java/org/openecomp/mso/properties/AbstractMsoProperties.java new file mode 100644 index 0000000000..69d2f98324 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/properties/AbstractMsoProperties.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.properties; + + +import java.io.IOException; +import java.util.Properties; + +import org.openecomp.mso.logger.MsoLogger; + +public abstract class AbstractMsoProperties { + + public static final int DEFAULT_RELOAD_TIME_MIN=1; + + public static final String RELOAD_TIME_PROPERTY="mso.properties.reload.time.minutes"; + + protected static MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL); + + protected String propertiesFileName; + + protected int automaticRefreshInMinutes=0; + + public String getPropertiesFileName() { + return propertiesFileName; + } + + public int getAutomaticRefreshInMinutes() { + return automaticRefreshInMinutes; + } + + protected synchronized void reloadPropertiesFile() throws IOException { + this.loadPropertiesFile(this.propertiesFileName); + } + + /** + * This method load a properties file from a source path. + * + * @param propertiesPath The path to the file + * @throws IOException In case of issues during the opening + */ + + protected abstract void loadPropertiesFile(String propertiesPath) throws IOException; + + @Override + protected abstract AbstractMsoProperties clone(); + + @Override + public abstract int hashCode(); + + @Override + public abstract boolean equals(Object obj); + + @Override + public abstract String toString(); + + +} diff --git a/common/src/main/java/org/openecomp/mso/properties/MsoJavaProperties.java b/common/src/main/java/org/openecomp/mso/properties/MsoJavaProperties.java new file mode 100644 index 0000000000..aa791f896e --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/properties/MsoJavaProperties.java @@ -0,0 +1,181 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.properties; + + +import java.io.FileReader; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.Properties; +import org.openecomp.mso.utils.CryptoUtils; + +public class MsoJavaProperties extends AbstractMsoProperties { + + + private Properties msoProperties = new Properties(); + + + public MsoJavaProperties() { + + } + + public synchronized void setProperty(String key,String value) { + msoProperties.setProperty(key, value); + } + + public synchronized String getProperty(String key, String defaultValue) { + if (msoProperties.containsKey(key)) { + return msoProperties.getProperty(key); + } else { + return defaultValue; + } + } + + public synchronized int getIntProperty(String key, int defaultValue) { + + int value = defaultValue; + if (msoProperties.containsKey(key)) { + try { + value = Integer.parseInt(msoProperties.getProperty(key)); + } catch (NumberFormatException e) { + LOGGER.debug("Exception while parsing integer: " + msoProperties.getProperty(key), e); + } + } + return value; + + } + + public synchronized boolean getBooleanProperty(String key, boolean defaultValue) { + + if (msoProperties.containsKey(key)) { + return Boolean.parseBoolean(msoProperties.getProperty(key)); + } else { + return defaultValue; + } + + } + + public synchronized String getEncryptedProperty(String key, String defaultValue, String encryptionKey) { + + if (msoProperties.containsKey(key)) { + try { + return CryptoUtils.decrypt(msoProperties.getProperty(key), encryptionKey); + } catch (GeneralSecurityException e) { + LOGGER.debug("Exception while decrypting property: " + msoProperties.getProperty(key), e); + } + } + return defaultValue; + + } + + public synchronized int size() { + return this.msoProperties.size(); + } + + + @Override + protected synchronized void reloadPropertiesFile() throws IOException { + this.loadPropertiesFile(this.propertiesFileName); + } + + /** + * This method load a properties file from a source path. + * + * @param propertiesPath The path to the file + * @throws IOException In case of issues during the opening + */ + @Override + protected synchronized void loadPropertiesFile(String propertiesPath) throws IOException { + + FileReader reader = null; + + propertiesFileName = propertiesPath; + try { + msoProperties.clear(); + reader = new FileReader(propertiesPath); + msoProperties.load(reader); + + } finally { + this.automaticRefreshInMinutes = this.getIntProperty(RELOAD_TIME_PROPERTY, DEFAULT_RELOAD_TIME_MIN); + // Always close the file + try { + if (reader != null) { + reader.close(); + } + } catch (IOException e) { + LOGGER.debug("Exception while closing reader for file:" + propertiesPath, e); + } + } + } + + @Override + public synchronized MsoJavaProperties clone() { + MsoJavaProperties msoCopy = new MsoJavaProperties(); + msoCopy.msoProperties.putAll(msoProperties); + msoCopy.propertiesFileName = this.propertiesFileName; + msoCopy.automaticRefreshInMinutes = this.automaticRefreshInMinutes; + return msoCopy; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((msoProperties == null) ? 0 : msoProperties.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + MsoJavaProperties other = (MsoJavaProperties) obj; + if (!msoProperties.equals(other.msoProperties)) { + return false; + } + return true; + } + + @Override + public String toString() { + + StringBuffer response = new StringBuffer(); + response.append("Config file " + propertiesFileName + "(Timer:" + automaticRefreshInMinutes + "mins):" + + System.getProperty("line.separator")); + for (Object key : this.msoProperties.keySet()) { + String propertyName = (String) key; + response.append(propertyName); + response.append("="); + response.append(this.msoProperties.getProperty(propertyName)); + response.append(System.getProperty("line.separator")); + } + response.append(System.getProperty("line.separator")); + response.append(System.getProperty("line.separator")); + return response.toString(); + } +} diff --git a/common/src/main/java/org/openecomp/mso/properties/MsoJsonProperties.java b/common/src/main/java/org/openecomp/mso/properties/MsoJsonProperties.java new file mode 100644 index 0000000000..323c4dbe99 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/properties/MsoJsonProperties.java @@ -0,0 +1,172 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.properties; + + +import java.io.FileReader; +import java.io.IOException; +import java.security.GeneralSecurityException; + +import org.codehaus.jackson.JsonNode; +import org.codehaus.jackson.JsonParseException; +import org.codehaus.jackson.map.JsonMappingException; +import org.codehaus.jackson.map.ObjectMapper; +import org.openecomp.mso.utils.CryptoUtils; + + +public class MsoJsonProperties extends AbstractMsoProperties { + + protected ObjectMapper mapper = new ObjectMapper(); + + protected JsonNode jsonRootNode = mapper.createObjectNode(); + + protected MsoJsonProperties() { + + } + + public synchronized JsonNode getJsonRootNode () { + return this.jsonRootNode; + } + + /** + * This method is used to get the text encrypted in the string value of the node. + * @param jsonNode The JsonNode containing the strig to decode + * @param defaultValue The default value in case of issue + * @param encryptionKey The encryption Key in AES 128 bits + * @return the String decrypted + */ + public synchronized String getEncryptedProperty(JsonNode jsonNode, String defaultValue, String encryptionKey) { + + if (jsonNode.isTextual()) { + try { + return CryptoUtils.decrypt(jsonNode.asText(), encryptionKey); + } catch (GeneralSecurityException e) { + LOGGER.debug("Exception while decrypting property: " + jsonNode.asText(), e); + } + } + + return defaultValue; + } + + /** + * This method load a properties file from a source path. + * + * @param propertiesPath The path to the file + * @throws IOException In case of issues during the opening + */ + @Override + protected synchronized void loadPropertiesFile(String propertiesPath) throws IOException { + + FileReader reader = null; + + this.propertiesFileName = propertiesPath; + + try { + // Clean + this.jsonRootNode = mapper.createObjectNode(); + + reader = new FileReader(propertiesPath); + + // Try a tree load + this.jsonRootNode = mapper.readValue(reader, JsonNode.class); + + + } finally { + JsonNode reloadJsonProp = this.jsonRootNode.get(RELOAD_TIME_PROPERTY); + if (reloadJsonProp != null) { + this.automaticRefreshInMinutes = reloadJsonProp.asInt(DEFAULT_RELOAD_TIME_MIN); + } else { + this.automaticRefreshInMinutes = DEFAULT_RELOAD_TIME_MIN; + } + + // Always close the file + try { + if (reader != null) { + reader.close(); + } + } catch (IOException e) { + LOGGER.debug("Exception while closing reader for file:" + propertiesFileName, e); + } + } + } + + @Override + public synchronized MsoJsonProperties clone() { + MsoJsonProperties msoCopy = new MsoJsonProperties(); + + ObjectMapper mapper = new ObjectMapper(); + try { + msoCopy.jsonRootNode = mapper.createObjectNode(); + msoCopy.jsonRootNode = mapper.readValue(this.jsonRootNode.toString(), JsonNode.class); + } catch (JsonParseException e) { + LOGGER.debug("JsonParseException when cloning the object:" + this.propertiesFileName, e); + } catch (JsonMappingException e) { + LOGGER.debug("JsonMappingException when cloning the object:" + this.propertiesFileName, e); + } catch (IOException e) { + LOGGER.debug("IOException when cloning the object:" + this.propertiesFileName, e); + } + + msoCopy.propertiesFileName = this.propertiesFileName; + msoCopy.automaticRefreshInMinutes = this.automaticRefreshInMinutes; + return msoCopy; + } + + + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((jsonRootNode == null) ? 0 : jsonRootNode.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + MsoJsonProperties other = (MsoJsonProperties) obj; + if (jsonRootNode == null) { + if (other.jsonRootNode != null) + return false; + } else if (!jsonRootNode.equals(other.jsonRootNode)) + return false; + return true; + } + + @Override + public String toString() { + StringBuffer response = new StringBuffer(); + response.append("Config file " + propertiesFileName + "(Timer:" + automaticRefreshInMinutes + "mins):" + + System.getProperty("line.separator")); + response.append(this.jsonRootNode.toString()); + response.append(System.getProperty("line.separator")); + response.append(System.getProperty("line.separator")); + return response.toString(); + + } + + +} diff --git a/common/src/main/java/org/openecomp/mso/properties/MsoPropertiesException.java b/common/src/main/java/org/openecomp/mso/properties/MsoPropertiesException.java new file mode 100644 index 0000000000..caf0ffad46 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/properties/MsoPropertiesException.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.properties; + + +/** + * Exception during artifact installation. + */ +public class MsoPropertiesException extends Exception { + + /** + * serialization id. + */ + private static final long serialVersionUID = 4095937499475915021L; + + /** + * @param message The message to dump + * @param cause The Throwable cause object + */ + public MsoPropertiesException (final String message) { + super (message); + + } + + /** + * @param message The message to dump + * @param cause The Throwable cause object + */ + public MsoPropertiesException (final String message, final Throwable cause) { + super (message, cause); + + } +} diff --git a/common/src/main/java/org/openecomp/mso/properties/MsoPropertiesFactory.java b/common/src/main/java/org/openecomp/mso/properties/MsoPropertiesFactory.java new file mode 100644 index 0000000000..77676314bc --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/properties/MsoPropertiesFactory.java @@ -0,0 +1,395 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.properties; + + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.Serializable; +import java.util.LinkedList; +import java.util.List; +import java.util.Map.Entry; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import javax.ejb.ConcurrencyManagement; +import javax.ejb.ConcurrencyManagementType; +import javax.ejb.LocalBean; +import javax.ejb.Schedule; +import javax.ejb.Singleton; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Response; + +import org.openecomp.mso.logger.MessageEnum; +import org.openecomp.mso.logger.MsoLogger; +import org.openecomp.mso.utils.CryptoUtils; + +/** + * This EJB Singleton class returns an instance of the mso properties for a specified file. + * This class can handle many config at the same time and is thread safe. + * This instance is a copy of the one cached so it can be modified or reloaded without impacting the others class using + * it. + * The mso properties files loaded and cached here will be reloaded every X second (it's configurable with the init + * method) + * This class can be used as an EJB or can be instantiated directly as long as the EJB has been initialized for the current + * module. Locks are made manually and not using EJB locks to allow this. + * + * + */ +@Singleton(name = "MsoPropertiesFactory") +@ConcurrencyManagement(ConcurrencyManagementType.BEAN) +@LocalBean +@Path("/properties") +public class MsoPropertiesFactory implements Serializable { + + private static final long serialVersionUID = 4365495305496742113L; + + protected static String prefixMsoPropertiesPath = System.getProperty ("mso.config.path"); + + private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.GENERAL); + + // Keep a static copy of properties for global usage + private static final ConcurrentHashMap <String, MsoPropertiesParameters> msoPropertiesCache; + + static { + if (prefixMsoPropertiesPath == null) { + // Hardcode if nothing is received + prefixMsoPropertiesPath = ""; + } + msoPropertiesCache = new ConcurrentHashMap <String, MsoPropertiesParameters> (); + } + + private static final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock (); + + public MsoPropertiesFactory () { + + } + + private boolean isJsonFile(String propertiesFilePath) { + return propertiesFilePath.endsWith(".json"); + } + + + private boolean isJavaPropertiesFile (String propertiesFilePath) { + return propertiesFilePath.endsWith(".properties"); + } + + private MsoPropertiesParameters createObjectType (MsoPropertiesParameters msoPropParams, String propertiesFilePath) throws MsoPropertiesException, IOException { + + try { + if (this.isJavaPropertiesFile(propertiesFilePath)) { + + msoPropParams.msoProperties = new MsoJavaProperties(); + msoPropParams.msoPropertiesType = MsoPropertiesParameters.MsoPropertiesType.JAVA_PROP; + } else if (this.isJsonFile(propertiesFilePath)) { + + msoPropParams.msoProperties = new MsoJsonProperties(); + msoPropParams.msoPropertiesType = MsoPropertiesParameters.MsoPropertiesType.JSON_PROP; + } else { + throw new MsoPropertiesException("Unable to load the MSO properties file because format is not recognized (only .json or .properties): " + propertiesFilePath); + } + + msoPropParams.msoProperties.loadPropertiesFile (propertiesFilePath); + + return msoPropParams; + } finally { + if (msoPropParams.msoProperties!=null) { + msoPropParams.refreshCounter = msoPropParams.msoProperties.getAutomaticRefreshInMinutes(); + } + } + + } + + /** + * This method is used to create a MsoProperties file cache and factory. + * The ID is kept in cache even if the config fails to be loaded. + * This is used to maintain the config ID until someone fixes the config file. + * + * @param msoPropertiesID A string representing the key of the config + * @param propertiesFilePath The mso properties file to load + * + * @throws MsoPropertiesException In case of issues with the mso properties loading + * + * @see MsoPropertiesFactory#getMsoJavaProperties() + * @see MsoPropertiesFactory#getMsoJsonProperties() + */ + public void initializeMsoProperties (String msoPropertiesID, + String propertiesFilePath) throws MsoPropertiesException { + + rwl.writeLock ().lock (); + + String msoPropPath="none"; + MsoPropertiesParameters msoPropertiesParams=new MsoPropertiesParameters(); + try { + msoPropPath = prefixMsoPropertiesPath + propertiesFilePath; + if (msoPropertiesCache.get (msoPropertiesID) != null) { + throw new MsoPropertiesException ("The factory contains already an instance of this mso properties: " + + msoPropPath); + } + // Create the global MsoProperties object + msoPropertiesParams = createObjectType(msoPropertiesParams, msoPropPath); + + } catch (FileNotFoundException e) { + throw new MsoPropertiesException ("Unable to load the MSO properties file because it has not been found:" + + msoPropPath, e); + + } catch (IOException e) { + throw new MsoPropertiesException ("Unable to load the MSO properties file because IOException occurs: " + + msoPropPath, e); + } finally { + // put it in all cases, just to not forget about him and attempt a default reload + msoPropertiesCache.put (msoPropertiesID, msoPropertiesParams); + rwl.writeLock ().unlock (); + } + } + + public void removeMsoProperties (String msoPropertiesID) throws MsoPropertiesException { + + rwl.writeLock ().lock (); + try { + if (MsoPropertiesFactory.msoPropertiesCache.remove (msoPropertiesID) == null) { + throw new MsoPropertiesException ("Mso properties not found in cache:" + msoPropertiesID); + } + } finally { + rwl.writeLock ().unlock (); + } + } + + /** + * This method clears all the configs in cache, the factory will then be free of any config. + * + * @see MsoPropertiesFactory#initializeMsoProperties(String, String) + */ + public void removeAllMsoProperties () { + + rwl.writeLock ().lock (); + try { + MsoPropertiesFactory.msoPropertiesCache.clear (); + } finally { + rwl.writeLock ().unlock (); + } + } + + /** + * THis method can be used to change the file and timer fields of an existing MSO properties file. + * + * @param msoPropertiesID The MSO properties ID + * @param newMsoPropPath The new file Path + * @throws MsoPropertiesException In case of the MSO Properties is not found in cache + */ + public void changeMsoPropertiesFilePath (String msoPropertiesID, + String newMsoPropPath) throws MsoPropertiesException { + + rwl.writeLock ().lock (); + try { + MsoPropertiesParameters msoPropInCache = MsoPropertiesFactory.msoPropertiesCache.get (msoPropertiesID); + + if (msoPropInCache != null) { + msoPropInCache.msoProperties.propertiesFileName = prefixMsoPropertiesPath + newMsoPropPath; + + } else { + throw new MsoPropertiesException ("Mso properties not found in cache:" + msoPropertiesID); + } + } finally { + rwl.writeLock ().unlock (); + } + } + + private AbstractMsoProperties getAndCloneProperties(String msoPropertiesID, MsoPropertiesParameters.MsoPropertiesType type) throws MsoPropertiesException { + rwl.readLock ().lock (); + try { + MsoPropertiesParameters msoPropInCache = MsoPropertiesFactory.msoPropertiesCache.get (msoPropertiesID); + if (msoPropInCache == null) { + throw new MsoPropertiesException ("Mso properties not found in cache:" + msoPropertiesID); + } else { + if (type.equals(msoPropInCache.msoPropertiesType)) { + return msoPropInCache.msoProperties.clone (); + } else { + throw new MsoPropertiesException ("Mso properties is not "+type.name()+" properties type:" + msoPropertiesID); + } + + } + } finally { + rwl.readLock ().unlock (); + } + } + + /** + * Get the MSO Properties (As Java Properties) as a copy of the mso properties cache. + * The object returned can therefore be modified. + * + * @return A copy of the mso properties, properties class can be empty if the file has not been read properly + * @throws MsoPropertiesException If the mso properties does not exist in the cache + */ + public MsoJavaProperties getMsoJavaProperties (String msoPropertiesID) throws MsoPropertiesException { + + return (MsoJavaProperties)getAndCloneProperties(msoPropertiesID,MsoPropertiesParameters.MsoPropertiesType.JAVA_PROP); + } + + /** + * Get the MSO Properties (As JSON Properties) as a copy of the mso properties cache. + * The object returned can therefore be modified. + * + * @return A copy of the mso properties, properties class can be empty if the file has not been read properly + * @throws MsoPropertiesException If the mso properties does not exist in the cache + */ + public MsoJsonProperties getMsoJsonProperties (String msoPropertiesID) throws MsoPropertiesException { + + return (MsoJsonProperties)getAndCloneProperties(msoPropertiesID,MsoPropertiesParameters.MsoPropertiesType.JSON_PROP); + } + + /** + * Get all MSO Properties as a copy of the mso properties cache. + * The objects returned can therefore be modified. + * + * @return A List of copies of the mso properties, can be empty + */ + public List <AbstractMsoProperties> getAllMsoProperties () { + + List <AbstractMsoProperties> resultList = new LinkedList <AbstractMsoProperties> (); + rwl.readLock ().lock (); + try { + + for (MsoPropertiesParameters msoProp:MsoPropertiesFactory.msoPropertiesCache.values ()) { + resultList.add(msoProp.msoProperties.clone()); + } + return resultList; + + } finally { + rwl.readLock ().unlock (); + } + + } + + /** + * This method is not intended to be called, it's used to refresh the config automatically + * + * @return true if Properties have been reloaded, false otherwise + */ + @Schedule(minute = "*/1", hour = "*", persistent = false) + public boolean reloadMsoProperties () { + AbstractMsoProperties msoPropInCache = null; + try { + if (!rwl.writeLock ().tryLock () && !rwl.writeLock ().tryLock (30L, TimeUnit.SECONDS)) { + LOGGER.debug ("Busy write lock on mso properties factory, skipping the reloading"); + return false; + } + } catch (InterruptedException e1) { + LOGGER.debug ("Interrupted while trying to acquire write lock on mso properties factory, skipping the reloading"); + Thread.currentThread ().interrupt (); + return false; + } + try { + for (Entry <String, MsoPropertiesParameters> entryMsoPropTimer : MsoPropertiesFactory.msoPropertiesCache.entrySet ()) { + + if (entryMsoPropTimer.getValue ().refreshCounter <= 1) { + // It's time to reload the config + msoPropInCache = MsoPropertiesFactory.msoPropertiesCache.get (entryMsoPropTimer.getKey ()).msoProperties; + try { + AbstractMsoProperties oldProps = msoPropInCache.clone (); + msoPropInCache.reloadPropertiesFile (); + entryMsoPropTimer.getValue().refreshCounter=entryMsoPropTimer.getValue().msoProperties.getAutomaticRefreshInMinutes(); + + if (!msoPropInCache.equals (oldProps)) { + LOGGER.info (MessageEnum.LOAD_PROPERTIES_SUC, msoPropInCache.getPropertiesFileName (), "", ""); + } + } catch (FileNotFoundException ef) { + LOGGER.error (MessageEnum.NO_PROPERTIES, msoPropInCache.propertiesFileName, "", "", MsoLogger.ErrorCode.PermissionError, "", ef); + } catch (Exception e) { + LOGGER.error (MessageEnum.LOAD_PROPERTIES_FAIL, msoPropInCache.propertiesFileName, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "", e); + } + + } else { + --entryMsoPropTimer.getValue().refreshCounter; + } + } + return true; + } catch (Exception e) { + LOGGER.error (MessageEnum.LOAD_PROPERTIES_FAIL, "Unknown. Global issue while reloading", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "", e); + return false; + } finally { + rwl.writeLock ().unlock (); + } + } + + /** + * This method can be used to known if the MSO properties instance hold is different from the one in cache + * + * @param msoPropertiesID The MSO properties ID + * @param oldMsoProperties The MSO Properties instance that must be compared to + * @return True if they are the same, false otherwise + * @throws MsoPropertiesException + */ + public boolean propertiesHaveChanged (String msoPropertiesID, AbstractMsoProperties oldMsoProperties) throws MsoPropertiesException { + rwl.readLock ().lock (); + try { + if (MsoPropertiesFactory.msoPropertiesCache.get (msoPropertiesID) == null) { + throw new MsoPropertiesException ("Mso properties not found in cache:" + msoPropertiesID); + } + + AbstractMsoProperties msoPropInCache = MsoPropertiesFactory.msoPropertiesCache.get (msoPropertiesID).msoProperties; + if (oldMsoProperties != null) { + return !oldMsoProperties.equals (msoPropInCache); + } else { + return msoPropInCache != null; + } + } finally { + rwl.readLock ().unlock (); + } + } + + @GET + @Path("/show") + @Produces("text/plain") + public Response showProperties () { + + List <AbstractMsoProperties> listMsoProp = this.getAllMsoProperties (); + StringBuffer response = new StringBuffer (); + + if (listMsoProp.isEmpty ()) { + response.append ("No file defined"); + } + + for (AbstractMsoProperties properties : listMsoProp) { + + response.append(properties.toString()); + } + + return Response.status (200).entity (response).build (); + } + + @GET + @Path("/encrypt/{value}/{cryptKey}") + @Produces("text/plain") + public Response encryptProperty (@PathParam("value") String value, @PathParam("cryptKey") String cryptKey) { + try { + String encryptedValue = CryptoUtils.encrypt (value, cryptKey); + return Response.status (200).entity (encryptedValue).build (); + } catch (Exception e) { + LOGGER.error (MessageEnum.GENERAL_EXCEPTION_ARG, "Encryption error", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Error in encrypting property", e); + return Response.status (500).entity (e.getMessage ()).build (); + } + } +} diff --git a/common/src/main/java/org/openecomp/mso/properties/MsoPropertiesParameters.java b/common/src/main/java/org/openecomp/mso/properties/MsoPropertiesParameters.java new file mode 100644 index 0000000000..358550a2bb --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/properties/MsoPropertiesParameters.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.properties; + + +public class MsoPropertiesParameters { + + protected enum MsoPropertiesType {JSON_PROP,JAVA_PROP}; + + protected MsoPropertiesType msoPropertiesType; + + protected int refreshCounter; + + protected AbstractMsoProperties msoProperties; +} diff --git a/common/src/main/java/org/openecomp/mso/properties/MsoPropertyInitializer.java b/common/src/main/java/org/openecomp/mso/properties/MsoPropertyInitializer.java new file mode 100644 index 0000000000..38e3ae3650 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/properties/MsoPropertyInitializer.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.properties; + + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.servlet.annotation.WebListener; + +import org.openecomp.mso.logger.MessageEnum; +import org.openecomp.mso.logger.MsoLogger; + +/** + * This class will attempt to initialize MSO Properties when part of a web application. + * It will look for the configuration file mso.properties in the + * following order: + * 1. In an init-param "mso.configuration" in web.xml + * 2. In a system property "mso.configuration" + * 3. In the default location "/etc/ecomp/mso/config/mso.properties" + * + * If all else fails, the MSO Properties will go uninitialized, and will + * attempt to use the default constructors within the MsoProperties class. + * + * + */ +@WebListener +public class MsoPropertyInitializer implements ServletContextListener +{ + + private MsoPropertiesFactory msoPropertiesFactory=new MsoPropertiesFactory(); + + public MsoPropertyInitializer () { + } + + @Override + public void contextDestroyed(ServletContextEvent event) { + // Nothing to do... + } + + + @Override + public void contextInitialized(ServletContextEvent event) + { + + // Note - this logger may be before or after MSO Logging configuration applied + MsoLogger initLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL); + try { + // Look first in the init-parameters + String msoPropConfigParam = event.getServletContext().getInitParameter("mso.configuration"); + if (msoPropConfigParam != null && !msoPropConfigParam.isEmpty() ) { + String[] configFileSplit = msoPropConfigParam.split(","); + for (String msoPropConfig:configFileSplit) { + String[] msoPropDecoded = msoPropConfig.split("="); + + try { + msoPropertiesFactory.initializeMsoProperties(msoPropDecoded[0], msoPropDecoded[1]); + initLogger.info(MessageEnum.LOAD_PROPERTIES_SUC, msoPropDecoded[1], "", ""); + initLogger.debug("Mso properties successfully loaded:"+msoPropDecoded[1]+",ID:"+msoPropDecoded[0]+")"); + } catch (MsoPropertiesException e) { + initLogger.error(MessageEnum.LOAD_PROPERTIES_FAIL, msoPropDecoded[1] + ". MSO Properties failed due to an mso properties exception", "", "", MsoLogger.ErrorCode.DataError, "Error in contextInitialized", e); + } + } + } + } + catch (Exception e) { + initLogger.error(MessageEnum.LOAD_PROPERTIES_FAIL, "Unknown. MSO Properties failed to initialize completely", "", "", MsoLogger.ErrorCode.DataError, "", e); + } + } +} diff --git a/common/src/main/java/org/openecomp/mso/utils/CheckResults.java b/common/src/main/java/org/openecomp/mso/utils/CheckResults.java new file mode 100644 index 0000000000..3e77a4c808 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/utils/CheckResults.java @@ -0,0 +1,118 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.utils; + + + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "checkresults") +public class CheckResults { + + @XmlElement(name = "checkresult") + private List <CheckResult> results; + + public CheckResults () { + results = new ArrayList <CheckResult> (); + } + + public List <CheckResult> getResults () { + return results; + } + + public void addHostCheckResult (String hostname, int state, String output) { + CheckResult newResult = new CheckResult (); + newResult.setType ("host"); + newResult.setHostname (hostname); + newResult.setState (state); + newResult.setOutput (output); + results.add (newResult); + } + + public void addServiceCheckResult (String hostname, String servicename, int state, String output) { + CheckResult newResult = new CheckResult (); + newResult.setType ("service"); + newResult.setHostname (hostname); + newResult.setServicename (servicename); + newResult.setState (state); + newResult.setOutput (output); + results.add (newResult); + } + + public static class CheckResult { + + private String type; + private String hostname; + private String servicename; + private int state; + private String output; + + @XmlAttribute(required = true) + public String getType () { + return type; + } + + public void setType (String type) { + this.type = type; + } + + @XmlElement(required = true) + public String getHostname () { + return hostname; + } + + public void setHostname (String hostname) { + this.hostname = hostname; + } + + @XmlElement(required = false) + public String getServicename () { + return servicename; + } + + public void setServicename (String servicename) { + this.servicename = servicename; + } + + @XmlElement(required = true) + public int getState () { + return state; + } + + public void setState (int state) { + this.state = state; + } + + @XmlElement(required = true) + public String getOutput () { + return output; + } + + public void setOutput (String output) { + this.output = output; + } + } +} diff --git a/common/src/main/java/org/openecomp/mso/utils/CryptoUtils.java b/common/src/main/java/org/openecomp/mso/utils/CryptoUtils.java new file mode 100644 index 0000000000..c926903cf3 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/utils/CryptoUtils.java @@ -0,0 +1,95 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.utils; + + + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.NoSuchAlgorithmException; + +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; + + +/** + * CryptoUtils adapted from RTTP client. + * + */ +public final class CryptoUtils { + + public static final String AES = "AES"; + + /** + * encrypt a value and generate a keyfile + * if the keyfile is not found then a new one is created + * + * @throws GeneralSecurityException + */ + public static String encrypt (String value, String keyString) throws GeneralSecurityException { + SecretKeySpec sks = getSecretKeySpec (keyString); + Cipher cipher = Cipher.getInstance (CryptoUtils.AES); + cipher.init (Cipher.ENCRYPT_MODE, sks, cipher.getParameters ()); + byte[] encrypted = cipher.doFinal (value.getBytes ()); + return byteArrayToHexString (encrypted); + } + + /** + * decrypt a value + * + * @throws GeneralSecurityException + */ + public static String decrypt (String message, String keyString) throws GeneralSecurityException { + SecretKeySpec sks = getSecretKeySpec (keyString); + Cipher cipher = Cipher.getInstance (CryptoUtils.AES); + cipher.init (Cipher.DECRYPT_MODE, sks); + byte[] decrypted = cipher.doFinal (hexStringToByteArray (message)); + return new String (decrypted); + } + + private static SecretKeySpec getSecretKeySpec (String keyString) throws NoSuchAlgorithmException { + byte[] key = hexStringToByteArray (keyString); + SecretKeySpec sks = new SecretKeySpec (key, CryptoUtils.AES); + return sks; + } + + public static String byteArrayToHexString (byte[] b) { + StringBuffer sb = new StringBuffer (b.length * 2); + for (int i = 0; i < b.length; i++) { + int v = b[i] & 0xff; + if (v < 16) { + sb.append ('0'); + } + sb.append (Integer.toHexString (v)); + } + return sb.toString ().toUpperCase (); + } + + private static byte[] hexStringToByteArray (String s) { + byte[] b = new byte[s.length () / 2]; + for (int i = 0; i < b.length; i++) { + int index = i * 2; + int v = Integer.parseInt (s.substring (index, index + 2), 16); + b[i] = (byte) v; + } + return b; + } +} diff --git a/common/src/main/java/org/openecomp/mso/utils/UUIDChecker.java b/common/src/main/java/org/openecomp/mso/utils/UUIDChecker.java new file mode 100644 index 0000000000..3e8c5e95d3 --- /dev/null +++ b/common/src/main/java/org/openecomp/mso/utils/UUIDChecker.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.utils; + +import org.openecomp.mso.logger.MessageEnum; +import org.openecomp.mso.logger.MsoLogger; + +import java.util.UUID; + +/** + */ +public class UUIDChecker { + + private UUIDChecker() { + + } + + public static boolean isValidUUID (String id) { + try { + if (null == id) { + return false; + } + UUID uuid = UUID.fromString(id); + return uuid.toString().equalsIgnoreCase(id); + } catch (IllegalArgumentException iae) { + return false; + } + } + + private static String getUUID () { + return UUID.randomUUID().toString(); + } + + public static String verifyOldUUID (String oldId, MsoLogger msoLogger) { + if (!UUIDChecker.isValidUUID(oldId)) { + String newId = UUIDChecker.getUUID(); + MsoLogger.setLogContext(newId, null); + msoLogger.info(MessageEnum.APIH_REPLACE_REQUEST_ID, oldId, "", ""); + return newId; + } + MsoLogger.setLogContext(oldId, null); + return oldId; + } + + public static String generateUUID (MsoLogger msoLogger) { + String newId = UUIDChecker.getUUID(); + MsoLogger.setLogContext(newId, null); + msoLogger.info(MessageEnum.APIH_GENERATED_REQUEST_ID, newId, "", ""); + return newId; + } + + public static String generateServiceInstanceID (MsoLogger msoLogger) { + String newId = UUIDChecker.getUUID(); + MsoLogger.setLogContext(null, newId); + msoLogger.info(MessageEnum.APIH_GENERATED_SERVICE_INSTANCE_ID, newId, "", ""); + return newId; + } +} diff --git a/common/src/main/resources/ASDC.properties b/common/src/main/resources/ASDC.properties new file mode 100644 index 0000000000..015ca3510e --- /dev/null +++ b/common/src/main/resources/ASDC.properties @@ -0,0 +1,210 @@ +### +# ============LICENSE_START======================================================= +# ECOMP MSO +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +### + +######################################################################## +#Resource key=Error Code|Message text|Resolution text |Description text +####### +# {component}-{subcomponent}-{4-digit code}{classification} +#Newlines can be utilized to add some clarity ensuring continuing line +#has atleast one leading space +#ResourceKey=\ +# ERR0000E\ +# Sample error msg txt\ +# Sample resolution msg\ +# Sample description txt +# +###### +#Error code classification category for other components +#1300-1399 Security/Permission Related +#2300-2399 Availability/Timeout Related +#3300-3399 Data Access/Integrity Related +#4300-4399 Schema Interface Type/Validation +#5300-5399 Business/Flow Processing Related +#6300-6399 Reserved \u2013 do not use +#9300-9399 Unknown Errors +# +###### +#{classification} description +# I = Information +# W = Warning +# E = Error +# F = Fatal +######################################################################## +ASDC_GENERAL_WARNING=\ + MSO-ASDC-5301W|\ + WARNING: {0}|\ + Please check other logs for more detailed info|\ + General warning +ASDC_AUDIT_EXEC=\ + MSO-ASDC-5302I|\ + Executing method: {0}. {1}|\ + No resolution needed|\ + Executing method +ASDC_GENERAL_METRICS=\ + MSO-ASDC-5305I|\ + Executed method: {0}. {1}|\ + No resolution needed|\ + Generate information for Metric events +ASDC_CREATE_SERVICE=\ + MSO-ASDC-5306I|\ + Creating new VNF Resource for service {0} with id {1} and version {2}|\ + No resolution needed|\ + Method triggered to create new VNF Resource +ASDC_CREATE_ARTIFACT=\ + MSO-ASDC-5307I|\ + Installing new {0} for service {1} with id {2} and version {3}|\ + No resolution needed|\ + Method triggered to create new VNF Resource +ASDC_ARTIFACT_ALREADY_DEPLOYED=\ + MSO-ASDC-5308W|\ + Constraint violation caught, artifact is already deployed {0} and version {1}|\ + No resolution needed|\ + Artifact is already deployed +ASDC_ARTIFACT_INSTALL_EXC=\ + MSO-ASDC-5309E|\ + Exception caught during installation of the {0}. Transaction rollback.|\ + Please check other logs for more detailed info|\ + Exception caught during installation of the artifact +ASDC_CHECK_HEAT_TEMPLATE=\ + MSO-ASDC-5310I|\ + Start to verify whether {0} with name {1} and version {2} is already deployed|\ + No resolution needed|\ + Check artifact +ASDC_ARTIFACT_ALREADY_DEPLOYED_DETAIL=\ + MSO-ASDC-5311I|\ + ResourceInstanceName:{0} (ResourceUUID:{1}) is already deployed for this Service:{2}/{3}(ServiceUUID:{4}) (ResourceName: {5})|\ + No resolution needed|\ + Resource is already deployed +ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL=\ + MSO-ASDC-5312I|\ + ResourceInstanceName:{0} (ResourceUUID:{1}) is not yet deployed for this Service:{2}/{3}(ServiceUUID:{4}) (ResourceName: {5})|\ + No resolution needed|\ + Resource is not yet deployed +ASDC_INIT_ASDC_CLIENT_EXC=\ + MSO-ASDC-5314W|\ + ASDControllerException caught during the Init/closing of ASDC Client with address {0} and environment {1}|\ + Please check other logs for more detailed info|\ + ASDControllerException caught during the Init/closing of ASDC Client +ASDC_LOAD_ASDC_CLIENT_EXC=\ + MSO-ASDC-5315W|\ + ASDCParametersException caught during loading/reloading of the ASDC Client with address {0} and environment {1}|\ + Please check other logs for more detailed info|\ + ASDCParametersException caught during loading/reloading of the ASDC Client +ASDC_SHUTDOWN_ASDC_CLIENT_EXC=\ + MSO-ASDC-5317W|\ + {0} caught during the ASDC Controller with address {1} and environment {2} shutdown|\ + Please check other logs for more detailed info|\ + Exception caught during the ASDC Controller shutdown +ASDC_START_INSTALL_ARTIFACT=\ + MSO-ASDC-5318I|\ + Trying to install the artifact:{0}|\ + No resolution needed|\ + Trying to install the artifact +ASDC_ARTIFACT_TYPE_NOT_SUPPORT=\ + MSO-ASDC-5319W|\ + This artifact type is not supported:{0}|\ + No resolution needed|\ + Artifact type is not supported +ASDC_ARTIFACT_ALREADY_EXIST=\ + MSO-ASDC-5320I|\ + No need to download the artifact as it exists already in MSO:{0} (UUID:{1}) associated to ResourceName {2}|\ + No resolution needed|\ + Artifact already exists +ASDC_ARTIFACT_DOWNLOAD_SUC=\ + MSO-ASDC-5321I|\ + Artifact successfully downloaded:{0} (UUID:{1}) (SIZE in Bytes:{2})|\ + No resolution needed|\ + Artifact successfully downloaded +ASDC_ARTIFACT_DOWNLOAD_FAIL=\ + MSO-ASDC-5322E|\ + Artifact :{0} could not be downloaded correctly from ASDC URL {1} (UUID:{2}) Error message is {3})|\ + Please check other logs for more detailed info|\ + Artifact download failed +ASDC_START_DEPLOY_ARTIFACT=\ + MSO-ASDC-5323I|\ + Trying to deploy the artifact:{0} (UUID:{1})|\ + No resolution needed|\ + Trying to deploy the artifact +ASDC_ARTIFACT_DEPLOY_SUC=\ + MSO-ASDC-5324I|\ + Resource successfully installed:{0} (UUID:{1}) (Nb of Modules:{2})|\ + No resolution needed|\ + Resource successfully installed +ASDC_SEND_NOTIF_ASDC=\ + MSO-ASDC-5325I|\ + Sending {0} ({1}) notification to ASDC for artifact:{2}|\ + No resolution needed|\ + Sending notif to ASDC +ASDC_SEND_NOTIF_ASDC_EXEC=\ + MSO-ASDC-5326W|\ + Exception caught when trying to notify ASDC|\ + Please check other logs for more detailed info|\ + Exception caught when trying to notify ASDC +ASDC_RECEIVE_CALLBACK_NOTIF=\ + MSO-ASDC-5327I|\ + Receive a callback notification in ASDC, nb of artifacts: {0} (ServiceUUID:{1})|\ + No resolution needed|\ + Receive a callback notification in ASDC +ASDC_RECEIVE_SERVICE_NOTIF=\ + MSO-ASDC-5328I|\ + Notification is ServiceVNF, (ServiceUUID:{0})|\ + No resolution needed|\ + Receive a callback notification for ServiceVNF +ASDC_ARTIFACT_NULL=\ + MSO-ASDC-5329I|\ + Nothing to deploy artifact is NULL, (ServiceUUID:{0})|\ + No resolution needed|\ + Nothing to deploy artifact is NULL +ASDC_SERVICE_NOT_SUPPORT=\ + MSO-ASDC-5330W|\ + Notification received, (ServiceUUID:{0}) is not a ServiceVNF and is therefore skipped|\ + No resolution needed|\ + Service not support +ASDC_INIT_ASDC_CLIENT_SUC=\ + MSO-ASDC-5331I|\ + ASDC Controller successfully initialized|\ + No resolution needed|\ + ASDC client initialized +ASDC_GENERAL_EXCEPTION_ARG=\ + MSO-ASDC-9300E|\ + Exception: {0}|\ + Please check other logs for more detailed info|\ + General exception with reason +ASDC_GENERAL_EXCEPTION=\ + MSO-ASDC-9301E|\ + Exception encountered|\ + Please check other logs for more detailed info|\ + Exception encountered +ASDC_ARTIFACT_CHECK_EXC=\ + MSO-ASDC-9302E|\ + Exception caught during checking existence of the artifact|\ + Please check other logs for more detailed info|\ + Exception caught during checking existence of the artifact +ASDC_SINGLETON_CHECKT_EXC=\ + MSO-ASDC-9303E|\ + Exception caught during the singleton check for ASDC with address {0} and environment {1}|\ + Please check other logs for more detailed info|\ + Exception caught during the singleton check +ASDC_PROPERTIES_NOT_FOUND=\ + MSO-ASDC-9304E|\ + Properties file: {0} not found|\ + Please verify whether properties file exist or readable|\ + Please verify whether properties file exist or readable|\ + Properties file not found diff --git a/common/src/main/resources/ApiHandler.properties b/common/src/main/resources/ApiHandler.properties new file mode 100644 index 0000000000..82d452ae4e --- /dev/null +++ b/common/src/main/resources/ApiHandler.properties @@ -0,0 +1,255 @@ +### +# ============LICENSE_START======================================================= +# ECOMP MSO +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +### + +######################################################################## +#Resource key=Error Code|Message text|Resolution text |Description text +####### +# {component}-{subcomponent}-{4-digit code}{classification} +#Newlines can be utilized to add some clarity ensuring continuing line +#has atleast one leading space +#ResourceKey=\ +# ERR0000E\ +# Sample error msg txt\ +# Sample resolution msg\ +# Sample description txt +# +####### +#Error code classification category +#1000-1099 Security/Permission Related +#2000-2099 Availability/Timeout Related +#3000-3099 Data Access/Integrity Related +#4000-4099 Schema Interface Type/Validation +#5000-5099 Business/Flow Processing Related +#6000-8099 Reserved \u2013 do not use +#9000-9099 Unknown Errors +# +###### +#{classification} description +# I = Information +# W = Warning +# E = Error +# F = Fatal +######################################################################## +APIH_QUERY_FOUND=\ + MSO-APIH-3000I|\ + Requests found when query DB with parameters {0}={1}|\ + No resolution needed|\ + Requests found when API Handler query DB +APIH_QUERY_NOT_FOUND=\ + MSO-APIH-3001I|\ + Request not found when query DB with parameters {0}={1}|\ + No resolution needed|\ + Request not found when API Handler query DB +APIH_DB_ACCESS_EXC=\ + MSO-APIH-3003E|\ + Unable to access DB|\ + Please check other logs for more detailed info|\ + Unable to access DB +APIH_DB_ACCESS_EXC_REASON=\ + MSO-APIH-3005E|\ + Unable to access DB: {0}|\ + Please check other logs for more detailed info|\ + Unable to access DB +APIH_DB_ATTRIBUTE_NOT_FOUND=\ + MSO-APIH-3006E|\ + Attribute {0} not found in DB|\ + Please check other logs for more detailed info|\ + Attribute not found in DB +APIH_DB_INSERT_EXC=\ + MSO-APIH-3007E|\ + Unable to insert record to DB|\ + Please check other logs for more detailed info|\ + Unable to insert record to DB +APIH_DB_UPDATE_EXC=\ + MSO-APIH-3008E|\ + Unable to update record to DB: {0}|\ + Please check other logs for more detailed info|\ + Unable to insert record to DB +APIH_VALIDATION_ERROR=\ + MSO-APIH-4000E|\ + Validation failed|\ + Please check other logs for more detailed info|\ + Validation failed +APIH_REQUEST_VALIDATION_ERROR=\ + MSO-APIH-4001E|\ + Validation of the input request failed, for incoming request:{0}|\ + Please check other logs for more detailed info|\ + Validation of the input request failed +APIH_SERVICE_VALIDATION_ERROR=\ + MSO-APIH-4002E|\ + Service params failed schema validation|\ + Please check other logs for more detailed info|\ + Service params failed schema validation +APIH_REQUEST_VALIDATION_ERROR_REASON=\ + MSO-APIH-4003E|\ + Validation of the input request failed:{0}|\ + Please verify the input request|\ + Validation of the input request failed +APIH_VNFREQUEST_VALIDATION_ERROR=\ + MSO-APIH-4004E|\ + Validation of the VNF Request failed|\ + Please verify the VNF Request|\ + Validation of the VNF Request failed +APIH_QUERY_PARAM_WRONG=\ + MSO-APIH-5003W|\ + Bad Request: {0}|\ + Please verify the request|\ + Bad Request +APIH_GENERAL_WARNING=\ + MSO-APIH-5004W|\ + WARNING: {0}|\ + Please check other logs for more detailed info|\ + General warning +APIH_AUDIT_EXEC=\ + MSO-APIH-5005I|\ + Executing request: {0}. {1}|\ + No resolution needed|\ + Executing method +APIH_GENERAL_METRICS=\ + MSO-APIH-5008I|\ + Executed method: {0}. {1}|\ + No resolution needed|\ + Generate information for Metric events +APIH_REQUEST_NULL=\ + MSO-APIH-5009W|\ + The request received by MSO is null|\ + Please check other logs for more detailed info|\ + The request received by MSO is null +APIH_DUPLICATE_FOUND=\ + MSO-APIH-5011W|\ + Duplicated request found: {0}|\ + Please check other logs for more detailed info|\ + Duplicated request found +APIH_BAD_ORDER=\ + MSO-APIH-5012W|\ + Request received with wrong order: {0}|\ + Please check other logs for more detailed info|\ + Request received with wrong order +APIH_BPEL_RESPONSE_ERROR=\ + MSO-APIH-5014E|\ + Abnormal response received from BPEL server: {0}|\ + Please check other logs for more detailed info|\ + Abnormal response received from BPEL server +APIH_WARP_REQUEST=\ + MSO-APIH-5015E|\ + Error wrapping request|\ + Please check other logs for more detailed info|\ + Error wrapping request to be sent to BPEL server +APIH_ERROR_FROM_BPEL_SERVER=\ + MSO-APIH-5016E|\ + Error from {0} with status:{1} and responseBody:{2}|\ + Please check other logs for more detailed info|\ + Error from BPEL Server +APIH_CANNOT_READ_SCHEMA=\ + MSO-APIH-5017E|\ + MSO Configuration Error - Unable to read the schema file|\ + Please check other logs for more detailed info|\ + MSO Configuration Error - Unable to read the schema file +APIH_PROPERTY_LOAD_SUC=\ + MSO-APIH-5018I|\ + Properties file loaded successfully|\ + No resolution needed|\ + Properties file loaded successfully +APIH_NO_PROPERTIES=\ + MSO-APIH-5019E|\ + Missing or invalid properties file: {0}|\ + Please verify whether properties file exist or redable|\ + Missing or invalid properties file +APIH_LOAD_PROPERTIES_FAIL=\ + MSO-APIH-5020E|\ + Unable to load properties file: {0}|\ + Please verify whether properties file exist or redable|\ + Unable to load properties file +APIH_GENERATED_REQUEST_ID=\ + MSO-APIH-5021I|\ + Missing requestID. Assigned {0}|\ + No resolution needed|\ + Request ID is not available +APIH_REPLACE_REQUEST_ID=\ + MSO-APIH-5022I|\ + Replaced invalid requestID of {0}|\ + No resolution needed|\ + Request ID received is not compliant with ECOMP Standards +APIH_GENERATED_SERVICE_INSTANCE_ID=\ + MSO-APIH-5023I|\ + Missing serviceInstanceID. Assigned {0}|\ + No resolution needed|\ + Service Instance ID is not available +APIH_GENERAL_EXCEPTION_ARG=\ + MSO-APIH-9000E|\ + Exception: {0}|\ + Please check other logs for more detailed info|\ + General exception with reason +APIH_GENERAL_EXCEPTION=\ + MSO-APIH-9001E|\ + Exception encountered|\ + Please check other logs for more detailed info|\ + Exception encountered +APIH_HEALTH_CHECK_EXCEPTION=\ + MSO-APIH-9002E|\ + Exception during health check|\ + Please check other logs for more detailed info|\ + Exception during health check +APIH_READ_VNFOUTPUT_CLOB_EXCEPTION=\ + MSO-APIH-9003E|\ + Exception reading vnfOutputs Clob|\ + Please check other logs for more detailed info|\ + Exception reading vnfOutputs Clob +APIH_DUPLICATE_CHECK_EXC=\ + MSO-APIH-9004E|\ + Exception during the duplication check for post services|\ + Please check other logs for more detailed info|\ + Exception during the duplicate check for post services +APIH_BPEL_COMMUNICATE_ERROR=\ + MSO-APIH-9005E|\ + Exception during BPEL POST|\ + Please check other logs for more detailed info|\ + Exception during BPEL POST +APIH_SDNC_COMMUNICATE_ERROR=\ + MSO-APIH-9006E|\ + Exception when sending HTTP POST request to SDNC Adapter|\ + Please check other logs for more detailed info|\ + Exception when sending HTTP POST request to SDNC Adapter +APIH_SDNC_RESPONSE_ERROR=\ + MSO-APIH-9007E|\ + IOException getting SDNC Adapter response body|\ + Please check other logs for more detailed info|\ + IOException getting SDNC Adapter response body +APIH_JAXB_MARSH_ERROR=\ + MSO-APIH-9008E|\ + Exception when translating query results into string with Jaxb|\ + Please check other logs for more detailed info|\ + Exception when translating query results into string with Jaxb +APIH_JAXB_UNMARSH_ERROR=\ + MSO-APIH-9009E|\ + Exception when formatting for VNF outputs with Jaxb|\ + Please check other logs for more detailed info|\ + Exception when formatting for VNF outputs +APIH_DOM2STR_ERROR=\ + MSO-APIH-9010E|\ + Error converting xml Document to String|\ + Please check other logs for more detailed info|\ + Error converting xml Document to String +APIH_DUPLICATE_CHECK_EXC_ATT=\ + MSO-APIH-9011E|\ + Exception during the duplication check for post services with the same attribute: {0}|\ + Please check other logs for more detailed info|\ + Exception during the duplicate check for post services + diff --git a/common/src/main/resources/BPMN.properties b/common/src/main/resources/BPMN.properties new file mode 100644 index 0000000000..298268bb92 --- /dev/null +++ b/common/src/main/resources/BPMN.properties @@ -0,0 +1,94 @@ +### +# ============LICENSE_START======================================================= +# ECOMP MSO +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +### + +######################################################################## +#Resource key=Error Code|Message text|Resolution text |Description text +####### +# {component}-{subcomponent}-{4-digit code}{classification} +#Newlines can be utilized to add some clarity ensuring continuing line +#has atleast one leading space +#ResourceKey=\ +# ERR0000E\ +# Sample error msg txt\ +# Sample resolution msg\ +# Sample description txt +# +####### +#Error code classification category +#1100-1199 Security/Permission Related +#2100-2199 Availability/Timeout Related +#3100-3199 Data Access/Integrity Related +#4100-4199 Schema Interface Type/Validation +#5100-5199 Business/Flow Processing Related +#6100-6199 Reserved \u2013 do not use +#9100-9199 Unknown Errors +# +###### +#{classification} description +# I = Information +# W = Warning +# E = Error +# F = Fatal +######################################################################## +BPMN_GENERAL_INFO=\ + MSO-BPEL-5100I|\ + INFO: {0}|\ + No resolution needed|\ + General info +BPMN_GENERAL_WARNING=\ + MSO-BPEL-5101W|\ + WARNING: {0}|\ + Please check other logs for more information|\ + General warning +BPMN_AUDIT_EXEC=\ + MSO-BPEL-5102I|\ + Executing method: {0}. {1}|\ + No resolution needed|\ + Executing method +BPMN_GENERAL_METRICS=\ + MSO-BPEL-5105I|\ + Executed method: {0}. {1}|\ + No resolution needed|\ + Generate information for Metric events +BPMN_URN_MAPPING_FAIL=\ + MSO-BPEL-5106E|\ + URN Mapping Task Failed to execute|\ + Please check other logs for more information|\ + URN Mapping Task Failed to execute +BPMN_VARIABLE_NULL=\ + MSO-BPEL-5107W|\ + Variable {0} is null; skipped|\ + No resolution needed|\ + Variable is null +BPMN_GENERAL_EXCEPTION_ARG=\ + MSO-BPEL-9100E|\ + Exception: {0}|\ + Please check other logs for more information|\ + General exception with reason +BPMN_GENERAL_EXCEPTION=\ + MSO-BPEL-9101E|\ + Exception encountered|\ + Please check other logs for more information|\ + Exception encountered +BPMN_SDNC_CALLBACK_EXCEPTION=\ + MSO-BPEL-9102E|\ + {0} Exception occurred during processing of MSO sdncAdapterCallbackService {1}|\ + Please check other logs for more information|\ + Exception occurred during processing of MSO sdncAdapterCallbackService diff --git a/common/src/main/resources/GenericMessages.properties b/common/src/main/resources/GenericMessages.properties new file mode 100644 index 0000000000..26403235c9 --- /dev/null +++ b/common/src/main/resources/GenericMessages.properties @@ -0,0 +1,139 @@ +### +# ============LICENSE_START======================================================= +# ECOMP MSO +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +### + +######################################################################## +#Resource key=Error Code|Message text|Resolution text |Description text +####### +# {component}-{subcomponent}-{4-digit code}{classification} +#Newlines can be utilized to add some clarity ensuring continuing line +#has atleast one leading space +#ResourceKey=\ +# ERR0000E\ +# Sample error msg txt\ +# Sample resolution msg\ +# Sample description txt +# +####### +#Error code classification category for other components +#1400-1499 Security/Permission Related +#2400-2499 Availability/Timeout Related +#3400-3499 Data Access/Integrity Related +#4400-4499 Schema Interface Type/Validation +#5400-5499 Business/Flow Processing Related +#6400-6499 Reserved \u2013 do not use +#9400-9499 Unknown Errors +# +###### +#{classification} description +# I = Information +# W = Warning +# E = Error +# F = Fatal +######################################################################## +GENERAL_WARNING=\ + MSO-GENERAL-5401W|\ + WARNING: {0}|\ + Please check other logs for more detailed info|\ + General warning +AUDIT_EXEC=\ + MSO-GENERAL-5402I|\ + Executing method: {0}. {1}|\ + No resolution needed|\ + Executing method +GENERAL_METRICS=\ + MSO-GENERAL-5405I|\ + Executed method: {0}. {1}|\ + No resolution needed|\ + Generate information for Metric events +LOGGER_SETUP=\ + MSO-GENERAL-5406I|\ + Request received to update logger level|\ + No resolution needed|\ + Request received to update logger level +LOGGER_NOT_FOUND=\ + MSO-GENERAL-5407I|\ + Logger Servlet: Logger not found: : {0}|\ + No resolution needed|\ + Logger not found +LOGGER_UPDATE_SUC=\ + MSO-GENERAL-5408I|\ + Successfully update Logger: {0} from level {1} to level {2}|\ + No resolution needed|\ + Generate information for Metric events +LOGGER_UPDATE_DEBUG=\ + MSO-GENERAL-5409I|\ + Request received to update debug mode|\ + No resolution needed|\ + Request received to update debug mode +LOGGER_UPDATE_DEBUG_SUC=\ + MSO-GENERAL-5410I|\ + Successfully {0} debug mode|\ + No resolution needed|\ + Successfully updated debug mode +LOAD_PROPERTIES_SUC=\ + MSO-GENERAL-5411I|\ + Properties file loaded successfully from file {0}|\ + No resolution needed|\ + Properties file loaded successfully +NO_PROPERTIES=\ + MSO-GENERAL-5412E|\ + Missing or invalid properties file: {0}|\ + Please verify whether properties file exist or readable|\ + Missing or invalid properties file +LOAD_PROPERTIES_FAIL=\ + MSO-GENERAL-5413E|\ + Failed loading properties file: {0}|\ + Please verify whether properties file exist or readable|\ + Failed loading properties file +INIT_LOGGER=\ + MSO-GENERAL-5414I|\ + Prepare to initialize loggers from {0}|\ + No resolution needed|\ + Prepare to initialize loggers +MADATORY_PARAM_MISSING=\ + MSO-GENERAL-5415E|\ + Not able to get mandatory parameter: {0} from file {1}|\ + No resolution needed|\ + Mandatory parameter missing +IDENTITY_SERVICE_NOT_FOUND=\ + MSO-GENERAL-5416E|\ + Identity service not found: region={0} ,cloud={1}|\ + Please check other logs for more detailed info|\ + Identity service not found +GENERAL_EXCEPTION_ARG=\ + MSO-GENERAL-9400E|\ + Exception: {0}|\ + Please check other logs for more detailed info|\ + General exception with reason +GENERAL_EXCEPTION=\ + MSO-GENERAL-9401E|\ + Exception encountered|\ + Please check other logs for more detailed info|\ + Exception encountered +INIT_LOGGER_FAIL=\ + MSO-GENERAL-9402E|\ + Failed to initialize loggers|\ + No resolution|\ + Failed to initialize loggers +JAXB_EXCEPTION=\ + MSO-GENERAL-9403E|\ + JAXB Initialization Error|\ + Please check other logs for more detailed info|\ + JAXB Initialization Error diff --git a/common/src/main/resources/ResourceAdapter.properties b/common/src/main/resources/ResourceAdapter.properties new file mode 100644 index 0000000000..f1c8b26ce1 --- /dev/null +++ b/common/src/main/resources/ResourceAdapter.properties @@ -0,0 +1,489 @@ +### +# ============LICENSE_START======================================================= +# ECOMP MSO +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +### + +######################################################################## +#Resource key=Error Code|Message text|Resolution text |Description text +####### +# {component}-{subcomponent}-{4-digit code}{classification} +#Newlines can be utilized to add some clarity ensuring continuing line +#has atleast one leading space +#ResourceKey=\ +# ERR0000E\ +# Sample error msg txt\ +# Sample resolution msg\ +# Sample description txt +# +####### +#Error code classification category +#1200-1299 Security/Permission Related +#2200-2299 Availability/Timeout Related +#3200-3299 Data Access/Integrity Related +#4200-4299 Schema Interface Type/Validation +#5200-5299 Business/Flow Processing Related +#6200-6299 Reserved \u2013 do not use +#9200-9299 Unknown Errors +# +###### +#{classification} description +# I = Information +# W = Warning +# E = Error +# F = Fatal +######################################################################## +RA_CREATE_STACK_TIMEOUT=\ + MSO-RA-2200E|\ + Create Stack - Polling timeout exceeded. cloud={0}, tenant={1}, stack={2}, status={3}|\ + Please check other logs for more detailed info|\ + Create Stack timeout +RA_DELETE_STACK_TIMEOUT=\ + MSO-RA-2201E|\ + Delete Stack - Polling timeout exceeded. cloud={0}, tenant={1}, stack={2}, status={3}|\ + Please check other logs for more detailed info|\ + Delete Stack timeout +RA_UPDATE_STACK_TIMEOUT=\ + MSO-RA-2202E|\ + Update Stack - Polling timeout exceeded. cloud={0}, tenant={1}, stack={2}, status={3}|\ + Please check other logs for more detailed info|\ + Delete Stack timeout +RA_MISSING_PARAM=\ + MSO-RA-4200I|\ + Missing Required parameter: {0}|\ + No resolution needed|\ + Mandatory Parameter Missing +RA_PARSING_ERROR=\ + MSO-RA-4201E|\ + Error parsing file {0}|\ + No resolution needed|\ + Error parsing file +RA_MARSHING_ERROR=\ + MSO-RA-4202E|\ + Error marshalling callback request with JaxB|\ + Please check other logs for more detailed info|\ + Error marshalling callback request +RA_PARSING_REQUEST_ERROR=\ + MSO-RA-4203E|\ + Error parsing request:{0}|\ + Please check other logs for more detailed info|\ + Error parsing request +RA_VLAN_PARSE=\ + MSO-RA-4204E|\ + Error parsing VLAN parameter in network stack {0}:{1}|\ + Please check other logs for more detailed info|\ + Error parsing VLAN parameter in network stack +RA_GENERAL_WARNING=\ + MSO-RA-5201W|\ + WARNING: {0}|\ + Please check other logs for more detailed info|\ + General warning +RA_AUDIT_EXEC=\ + MSO-RA-5202I|\ + Executing method: {0}. {1}|\ + No resolution needed|\ + Executing method +RA_GENERAL_METRICS=\ + MSO-RA-5205I|\ + Executed method: {0}. {1}|\ + No resolution needed|\ + Generate information for Metric events +RA_PROPERTIES_NOT_FOUND=\ + MSO-RA-5206E|\ + Properties file: {0} not found|\ + Please verify whether properties file exist or readable|\ + Properties file not found +RA_LOAD_PROPERTIES_SUC=\ + MSO-RA-5207I|\ + Properties file loaded successfully from file {0}|\ + No resolution needed|\ + Properties file loaded successfully +RA_PARAM_NOT_FOUND=\ + MSO-RA-5208E|\ + Attribute {0} not found in DB. For {1}={2}|\ + No resolution needed|\ + Attribute not found in DB +RA_UNKOWN_PARAM=\ + MSO-RA-5209E|\ + Unknown {0}:{1}|\ + Please check other logs for more detailed info|\ + Unknown attribute +RA_CONFIG_EXC=\ + MSO-RA-5210E|\ + Configuration error:{0}|\ + Please check other logs for more detailed info|\ + Configuration Error +RA_CONFIG_NOT_FOUND=\ + MSO-RA-5211E|\ + Could not found configuration file:{0}|\ + Please verify whether configuration file exist or readable|\ + Configuration file not found +RA_SEND_REQUEST_SDNC=\ + MSO-RA-5212I|\ + Sending request to SDNC:{0}|\ + No resolution needed|\ + Sending request to SDNC +RA_RESPONSE_FROM_SDNC=\ + MSO-RA-5213I|\ + Response received from SDNC:{0}|\ + No resolution needed|\ + Response received from SDNC +RA_CALLBACK_BPEL=\ + MSO-RA-5218E|\ + Callback to BPEL:{0} |\ + Please check other logs for more detailed info|\ + Callback to BPEL +RA_NETWORK_ALREADY_EXIST=\ + MSO-RA-5240W|\ + Network already exists: {0} in {1}/{2}|\ + Please check other logs for more detailed info|\ + Network already exists +RA_NETWORK_NOT_FOUND=\ + MSO-RA-5241E|\ + Network doesn't exist: {0} in {1}/{2}|\ + Please check other logs for more detailed info|\ + Network doesn't exist +RA_NETWORK_ORCHE_MODE_NOT_SUPPORT=\ + MSO-RA-5243E|\ + Network Type Orchestrated mode:{0} is not supported|\ + Please check other logs for more detailed info|\ + Network Type Orchestrated mode +RA_ROLLBACK_NULL=\ + MSO-RA-5249W|\ + Rollback: No action to perform|\ + No resolution needed|\ + Rollback: No action to perform +RA_ASYNC_ROLLBACK=\ + MSO-RA-5251I|\ + Async Rollback Network {0}|\ + No resolution needed|\ + Async Rollback Network +RA_WSDL_NOT_FOUND=\ + MSO-RA-5252E|\ + Unable to find wsdl file {0} in classpath|\ + No resolution needed|\ + Unable to find wsdl file in classpath +RA_CALLBACK_BPEL_COMPLETE=\ + MSO-RA-5258I|\ + Completed processing BPEL request|\ + No resolution needed|\ + Completed processing BPEL request +RA_SDNC_MISS_CONFIG_PARAM=\ + MSO-RA-5259E|\ + Missing configuration for:{0}|\ + Please check other logs for more detailed info|\ + Missing configuration for +RA_SDNC_INVALID_CONFIG=\ + MSO-RA-5260W|\ + Invalid configuration(most requests require atleast 3 params:method,timeout,action) for Key:{0} Value:{1}|\ + Please check other logs for more detailed info|\ + Invalid configuration +RA_TENANT_NOT_FOUND=\ + MSO-RA-5263E|\ + Tenant not found: tenant={0}, cloudSiteId={1}|\ + Please check other logs for more detailed info|\ + Tenant not found +RA_PRINT_URL=\ + MSO-RA-5264I|\ + {0} URL:{1}|\ + No resolution needed|\ + Log the URL +RA_RECEIVE_SDNC_NOTIF=\ + MSO-RA-5268I|\ + Received SDNC Notification. XML:{0}|\ + No resolution needed|\ + Received SDNC Notification +RA_INIT_SDNC_ADAPTER=\ + MSO-RA-5269I|\ + Initializing mso-sdnc-adapter|\ + No resolution needed|\ + Initializing mso-sdnc-adapter +RA_RECEIVE_BPEL_REQUEST=\ + MSO-RA-5270I|\ + BPEL request received [{0}] with callback URL [{1}]|\ + No resolution needed|\ + BPEL request received +RA_SEND_REQUEST_SDNC_ERR=\ + MSO-RA-5271E|\ + Error sending request to SDNC. Failed to start SDNC Client thread|\ + Please check other logs for more detailed info|\ + Error sending request to SDNC +RA_TENANT_ALREADY_EXIST=\ + MSO-RA-5272E|\ + Tenant {0} already exists in {1}|\ + No resolution needed|\ + Tenant alaredy exists +RA_SEND_REQUEST_APPC_ERR=\ + MSO-RA-5273E|\ + Error sending request to APPC|\ + Please check other logs for more detailed info|\ + Error sending request to APPC +RA_VNF_ALREADY_EXIST=\ + MSO-RA-5275E|\ + Stack {0} already exists in {1}/{2}|\ + No resolution needed|\ + VNF already exists +RA_VNF_UNKNOWN_PARAM=\ + MSO-RA-5276E|\ + Unknown {0}:{1}|\ + No resolution needed|\ + Uknown parameter +RA_VNF_EXTRA_PARAM=\ + MSO-RA-5277E|\ + Create Stack ({0}) extra input params received:{1}|\ + Please check other logs for more detailed info|\ + Extra input params received +RA_VNF_NOT_EXIST=\ + MSO-RA-5278E|\ + Stack {0} does not exist in {1}/{2}|\ + No resolution needed|\ + Stack does not exist +RA_ASYNC_CREATE_VNF=\ + MSO-RA-5282I|\ + Async Create VNF :{0} of type {1} in {2}/{3}|\ + No resolution needed|\ + Async Create VNF +RA_SEND_VNF_NOTIF_ERR=\ + MSO-RA-5283E|\ + Error sending createVnf notification|\ + Please check other logs for more detailed info|\ + Error sending createVnf notification +RA_ASYNC_CREATE_VNF_COMPLETE=\ + MSO-RA-5284I|\ + Completed createVnfA|\ + No resolution needed|\ + Completed createVnfA +RA_ASYNC_UPDATE_VNF=\ + MSO-RA-5285I|\ + Async Update VNF :{0} of type {1} in {2}/{3}|\ + No resolution needed|\ + Async Update VNF +RA_ASYNC_UPDATE_VNF_COMPLETE=\ + MSO-RA-5286I|\ + Completed updateVnfA|\ + No resolution needed|\ + Completed updateVnfA +RA_ASYNC_QUERY_VNF=\ + MSO-RA-5287I|\ + Async Query VNF :{0} of type {1} in {2}/{3}|\ + No resolution needed|\ + Async Query VNF +RA_ASYNC_QUERY_VNF_COMPLETE=\ + MSO-RA-5288I|\ + Completed queryVnfA|\ + No resolution needed|\ + Completed queryVnfA +RA_ASYNC_DELETE_VNF=\ + MSO-RA-5289I|\ + Async Delete VNF :{0} of type {1} in {2}/{3}|\ + No resolution needed|\ + Async Delete VNF +RA_ASYNC_DELETE_VNF_COMPLETE=\ + MSO-RA-5290I|\ + Completed deleteVnfA|\ + No resolution needed|\ + Completed deleteVnfA +RA_ASYNC_ROLLBACK_VNF=\ + MSO-RA-5291I|\ + Async Rollback VNF|\ + No resolution needed|\ + Async Rollback VNF +RA_ASYNC_ROLLBACK_VNF_COMPLETE=\ + MSO-RA-5292I|\ + Completed rollbackVnfA|\ + No resolution needed|\ + Completed rollbackVnfA +RA_DB_INVALID_STATUS=\ + MSO-RA-5293E|\ + Invalid status value|\ + Please check other logs for more detailed info|\ + Invalid status value +RA_DB_REQUEST_NOT_EXIST=\ + MSO-RA-5294E|\ + Request ID={0} does not exist in DB|\ + Please check other logs for more detailed info|\ + Record does not exist in DB +RA_CANT_UPDATE_REQUEST=\ + MSO-RA-5295E|\ + Enable to update {0} in DB for Request ID={1}|\ + Please check other logs for more detailed info|\ + Enable to update DB +RA_CONFIG_LOAD=\ + MSO-RA-5296I|\ + Configuration loaded from {0}|\ + Please check other logs for more detailed info|\ + Configuration loaded +RA_GENERAL_EXCEPTION_ARG=\ + MSO-RA-9200E|\ + Exception: {0}|\ + Please check other logs for more detailed info|\ + General exception with reason +RA_GENERAL_EXCEPTION=\ + MSO-RA-9201E|\ + Exception encountered|\ + Please check other logs for more detailed info|\ + Exception encountered +RA_CONNECTION_EXCEPTION=\ + MSO-RA-9202E|\ + Exception communicating with {0}: {1}|\ + Please check other logs for more detailed info|\ + Communication Exception +RA_EXCEPTION_COMMUNICATE_SDNC=\ + MSO-RA-9203E|\ + Exception while processing request to SDNC|\ + Please check other logs for more detailed info|\ + Exception while processing request to SDNC +RA_EVALUATE_XPATH_ERROR=\ + MSO-RA-9204E|\ + Error while evaluating xpath {0} - {1}|\ + Please check other logs for more detailed info|\ + Error while evaluating xpath +RA_ANALYZE_ERROR_EXC=\ + MSO-RA-9205E|\ + Problem analyzing error returned by SDN-C|\ + Please check other logs for more detailed info|\ + Problem analyzing error returned by SDN-C +RA_ERROR_GET_RESPONSE_SDNC=\ + MSO-RA-9206E|\ + Error getting response code from errored SDNC request|\ + Please check other logs for more detailed info|\ + Error getting response code from errored SDNC request +RA_INIT_CALLBACK_WSDL_ERR=\ + MSO-RA-9207E|\ + Caught exception initializing Callback wsdl:{0} |\ + Please check other logs for more detailed info|\ + Caught exception initializing Callback wsdl +RA_CREATE_STACK_ERR=\ + MSO-RA-9208E|\ + Create Stack Error: {0}|\ + Please check other logs for more detailed info|\ + Create Stack Error +RA_UPDATE_STACK_ERR=\ + MSO-RA-9209E|\ + Update Stack Error - Polling complete with non-success status: {0}, {1}|\ + Please check other logs for more detailed info|\ + Update Stack Error +RA_UPDATE_NETWORK_ERR=\ + MSO-RA-9210E|\ + Exception while update network, {0} in {1}/{2}|\ + Please check other logs for more detailed info |\ + Update Network Error +RA_QUERY_NETWORK_EXC=\ + MSO-RA-9211E|\ + Exception while query network: {0} in {1}/{2}|\ + Please check other logs for more detailed info|\ + Exception while query network: +RA_CREATE_NETWORK_EXC=\ + MSO-RA-9212E|\ + Exception while create network: {0} in {1}/{2}|\ + Please check other logs for more detailed info|\ + Create Network Error +RA_DELETE_NETWORK_EXC=\ + MSO-RA-9213E|\ + Exception while delete network: {0} in {1}/{2}|\ + Please check other logs for more detailed info|\ + delete Network Error +RA_CREATE_NETWORK_NOTIF_EXC=\ + MSO-RA-9214E|\ + Error sending createNetwork notification|\ + Please check other logs for more detailed info|\ + Error sending createNetwork notification +RA_WSDL_URL_CONVENTION_EXC=\ + MSO-RA-9215E|\ + {0} URL converion failed|\ + Please check other logs for more detailed info|\ + WSDL URL converion failed +RA_INIT_NOTIF_EXC=\ + MSO-RA-9216E|\ + Caught exception initializing Notification Url|\ + Please check other logs for more detailed info|\ + Caught exception initializing Notification Url +RA_SET_CALLBACK_AUTH_EXC=\ + MSO-RA-9217E|\ + Unable to set authorization in callback request|\ + Please check other logs for more detailed info|\ + Unable to set authorization in callback request +RA_FAULT_INFO_EXC=\ + MSO-RA-9218E|\ + Exception caught while getting fault info|\ + Please check other logs for more detailed info|\ + Exception caught while getting fault info +RA_CALLBACK_BPEL_EXC=\ + MSO-RA-9219E|\ + Error sending BPEL Callback request|\ + Please check other logs for more detailed info|\ + Error sending BPEL Callback request +RA_CREATE_TENANT_ERR=\ + MSO-RA-9220E|\ + Create Tenant Error: {0}|\ + Please check other logs for more detailed info|\ + Create Tenant Error +RA_DELETE_TEMAMT_ERR=\ + MSO-RA-9221E|\ + Delete Tenant Error: {0}|\ + Please check other logs for more detailed info|\ + Delete Tenant Error +RA_ERROR_CREATE_SDNC_REQUEST=\ + MSO-RA-9222E|\ + Error creating SDNC request|\ + Please check other logs for more detailed info|\ + Error creating SDNC request +RA_ERROR_CREATE_SDNC_RESPONSE=\ + MSO-RA-9223E|\ + Error creating SDNC response|\ + Please check other logs for more detailed info|\ + Error creating SDNC response +RA_ERROR_CONVERT_XML2STR=\ + MSO-RA-9224E|\ + Error converting xml Document to String|\ + Please check other logs for more detailed info |\ + Error converting xml Document to String +RA_UPDATE_TENANT_ERR=\ + MSO-RA-9225E|\ + Update Tenant Error: {0}|\ + Please check other logs for more detailed info|\ + Update Tenant Error +RA_ROLLBACK_TENANT_ERR=\ + MSO-RA-9226E|\ + Rollback Tenant Error: {0}|\ + Please check other logs for more detailed info|\ + Rollback Tenant Error +RA_QUERY_VNF_ERR=\ + MSO-RA-9227E|\ + Exception while query VNF:{0} in {1}/{2}|\ + Please check other logs for more detailed info|\ + Exception while query VNF +RA_UPDATE_VNF_ERR=\ + MSO-RA-9228E|\ + Exception while update VNF:{0} in {1}/{2}|\ + Please check other logs for more detailed info|\ + Exception while update VNF +RA_DELETE_VNF_ERR=\ + MSO-RA-9229E|\ + Exception while delete VNF:{0} in {1}/{2}|\ + Please check other logs for more detailed info|\ + Exception while delete VNF +RA_CREATE_VNF_ERR=\ + MSO-RA-9230E|\ + Exception while create VNF:{0} in {1}/{2}|\ + Please check other logs for more detailed info|\ + Exception while create VNF +RA_ROLLBACK_VNF_ERR=\ + MSO-RA-9231E|\ + Exception while rollback VNF|\ + Please check other logs for more detailed info|\ + Exception while rollback VNF diff --git a/common/src/test/java/org/openecomp/mso/adapter_utils/tests/CryptoTest.java b/common/src/test/java/org/openecomp/mso/adapter_utils/tests/CryptoTest.java new file mode 100644 index 0000000000..302102b839 --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/adapter_utils/tests/CryptoTest.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.adapter_utils.tests; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.security.GeneralSecurityException; + +import org.junit.BeforeClass; +import org.junit.Test; + +import org.openecomp.mso.utils.CryptoUtils; + +/** + * This class implements all test methods of the CryptoUtils features. + * + * + */ +public class CryptoTest { + + private static String testKey = "546573746F736973546573746F736973"; + + /** + * This method is called before any test occurs. + * It creates a fake tree from scratch + */ + @BeforeClass + public static final void prepare () { + + } + + /** + * This method implements a test of tree structure, mainly the storage of the leaves structure. + * @throws GeneralSecurityException + */ + @Test + public final void testEncryption () throws GeneralSecurityException { + String hexString = CryptoUtils.byteArrayToHexString("testosistestosi".getBytes()); + + final String testData = "This is a test string"; + final String nonTestData = "This is not the right String"; + + String encodeString = CryptoUtils.encrypt(testData, testKey); + + assertNotNull(encodeString); + + assertTrue(testData.equals(CryptoUtils.decrypt(encodeString, testKey))); + assertFalse(nonTestData.equals(CryptoUtils.decrypt(encodeString, testKey))); + + String encode2String = CryptoUtils.encrypt(testData, testKey); + assertNotNull(encode2String); + + assertEquals(encodeString,encode2String); + + assertEquals(CryptoUtils.decrypt(encodeString, testKey),CryptoUtils.decrypt(encode2String, testKey)); + } + +} diff --git a/common/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoAlarmLoggerTest.java b/common/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoAlarmLoggerTest.java new file mode 100644 index 0000000000..52246b00d9 --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoAlarmLoggerTest.java @@ -0,0 +1,131 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.adapter_utils.tests; + + +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; + +import org.junit.BeforeClass; +import org.junit.Test; + +import org.openecomp.mso.logger.MsoAlarmLogger; +import org.openecomp.mso.properties.MsoJavaProperties; +import org.openecomp.mso.properties.MsoPropertiesException; +import org.openecomp.mso.properties.MsoPropertiesFactory; + +/** + * This junit test very roughly the alarm logger + * + */ +public class MsoAlarmLoggerTest { + + public static MsoPropertiesFactory msoPropertiesFactory = new MsoPropertiesFactory(); + public static MsoAlarmLogger msoAlarmLogger; + + @BeforeClass + public static final void createObjects() throws MsoPropertiesException + { + + File outputFile = new File ("target/alarm-test.log"); + if (outputFile.exists()) { + outputFile.delete(); + } + msoAlarmLogger = new MsoAlarmLogger("target/alarm-test.log"); + } + + @Test + public void testAlarmConfig() throws MsoPropertiesException, IOException { + + msoAlarmLogger.sendAlarm("test", 0, "detail message"); + + FileInputStream inputStream = new FileInputStream("target/alarm-test.log"); + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + + String line = reader.readLine(); + String[] splitLine = line.split("\\|"); + assertTrue(splitLine.length==4); + assertTrue("test".equals(splitLine[1])); + assertTrue("0".equals(splitLine[2])); + assertTrue("detail message".equals(splitLine[3])); + + line = reader.readLine(); + assertNull(line); + reader.close(); + inputStream.close(); + + // Reset the file for others tests + PrintWriter writer = new PrintWriter(new File("target/alarm-test.log")); + writer.print(""); + writer.close(); + + } + + @Test + public void testAlarm() throws IOException { + + msoAlarmLogger.sendAlarm("test", 0, "detail message"); + msoAlarmLogger.sendAlarm("test2", 1, "detail message2"); + msoAlarmLogger.sendAlarm("test3", 2, "detail message3"); + + FileInputStream inputStream = new FileInputStream("target/alarm-test.log"); + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + + String line = reader.readLine(); + String[] splitLine = line.split("\\|"); + assertTrue(splitLine.length==4); + assertTrue("test".equals(splitLine[1])); + assertTrue("0".equals(splitLine[2])); + assertTrue("detail message".equals(splitLine[3])); + + line = reader.readLine(); + splitLine = line.split("\\|"); + assertTrue(splitLine.length==4); + assertTrue("test2".equals(splitLine[1])); + assertTrue("1".equals(splitLine[2])); + assertTrue("detail message2".equals(splitLine[3])); + + line = reader.readLine(); + splitLine = line.split("\\|"); + assertTrue(splitLine.length==4); + assertTrue("test3".equals(splitLine[1])); + assertTrue("2".equals(splitLine[2])); + assertTrue("detail message3".equals(splitLine[3])); + + line = reader.readLine(); + assertNull(line); + reader.close(); + inputStream.close(); + + // Reset the file for others tests + PrintWriter writer = new PrintWriter(new File("target/alarm-test.log")); + writer.print(""); + writer.close(); + + } +} diff --git a/common/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoLoggerTest.java b/common/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoLoggerTest.java new file mode 100644 index 0000000000..3da16be23a --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoLoggerTest.java @@ -0,0 +1,339 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.adapter_utils.tests; + +import org.openecomp.mso.entity.MsoRequest; +import org.openecomp.mso.logger.MessageEnum; +import org.openecomp.mso.logger.MsoLogger; +import org.openecomp.mso.logger.MsoLogger.ErrorCode; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.slf4j.MDC; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.PrintWriter; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URL; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +/** + * This class implements all test methods of the MsoLogger features. + * + * + */ +public class MsoLoggerTest { + + static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL); + + /** + * This method is called before any test occurs. + * It creates a fake tree from scratch + */ + @BeforeClass + public static final void prepare () { + + } + + @Before + public final void cleanErrorLogFile() throws FileNotFoundException { + URL url = this.getClass().getClassLoader().getResource("logback-test.xml"); + String logFile = url.getFile().substring(0, url.getFile().indexOf("test-classes")) + "/MSO/Test/errorjboss.server.name_IS_UNDEFINED.log"; + PrintWriter asdcConfigFileWriter = new PrintWriter(logFile); + asdcConfigFileWriter.print(""); + asdcConfigFileWriter.flush(); + asdcConfigFileWriter.close(); + } + + @Before + public final void cleanMetricLogFile() throws FileNotFoundException { + URL url = this.getClass().getClassLoader().getResource("logback-test.xml"); + String logFile = url.getFile().substring(0, url.getFile().indexOf("test-classes")) + "/MSO/Test/metricsjboss.server.name_IS_UNDEFINED.log"; + PrintWriter asdcConfigFileWriter = new PrintWriter(logFile); + asdcConfigFileWriter.print(""); + asdcConfigFileWriter.flush(); + asdcConfigFileWriter.close(); + } + + @Before + public final void cleanAuditLogFile() throws FileNotFoundException { + URL url = this.getClass().getClassLoader().getResource("logback-test.xml"); + String logFile = url.getFile().substring(0, url.getFile().indexOf("test-classes")) + "/MSO/Test/auditjbo ss.server.name_IS_UNDEFINED.log"; + PrintWriter asdcConfigFileWriter = new PrintWriter(logFile); + asdcConfigFileWriter.print(""); + asdcConfigFileWriter.flush(); + asdcConfigFileWriter.close(); + } + + + + /** + * This method implements a test of getSeverifyLevel method. + */ + @Test + public final void testGetSeverityLevel () { + + try { + String levelInfo = (String)invokePriveMethod("getSeverityLevel", "INFO"); + Assert.assertEquals (levelInfo, "0"); + + String levelWarn = (String)invokePriveMethod("getSeverityLevel", "WARN"); + Assert.assertEquals (levelWarn, "1"); + + String levelERROR = (String)invokePriveMethod("getSeverityLevel", "ERROR"); + Assert.assertEquals (levelERROR, "2"); + + String levelDEBUG = (String)invokePriveMethod("getSeverityLevel", "DEBUG"); + Assert.assertEquals (levelDEBUG, "0"); + + String levelFATAL = (String)invokePriveMethod("getSeverityLevel", "FATAL"); + Assert.assertEquals (levelFATAL, "3"); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /** + * This method implements a test of getFinalServiceName method. + */ + @Test + public final void testGetFinalServiceName () { + try { + String serviceName1 = (String)invokePriveMethod("getFinalServiceName", "testServiceName1"); + Assert.assertEquals(serviceName1, "testServiceName1"); + + MsoLogger.setServiceName("testServiceName2"); + String serviceName2 = (String)invokePriveMethod("getFinalServiceName", "testServiceName1"); + Assert.assertEquals(serviceName2, "testServiceName1"); + + String msgNull = null; + String serviceName3 = (String)invokePriveMethod("getFinalServiceName", msgNull); + Assert.assertEquals(serviceName3, "testServiceName2"); + + MsoLogger.resetServiceName(); + String serviceName4 = (String)invokePriveMethod("getFinalServiceName", msgNull); + Assert.assertEquals(serviceName4, "invoke0"); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public final void testPrepareMsg () { + try { + String msgNull = null; + MDC.clear(); + invokePrepareMsg("INFO", null, null); + + Assert.assertTrue (MDC.get(MsoLogger.REQUEST_ID).equals("trace-#") && MDC.get(MsoLogger.SERVICE_INSTANCE_ID).equals("trace-#") && MDC.get(MsoLogger.SERVICE_NAME).equals("invoke0") + && MDC.get(MsoLogger.TIMER) == null && MDC.get(MsoLogger.ALERT_SEVERITY).equals("0")); + + MsoLogger.setLoggerParameters("testRemoteIp", "testUser"); + MsoLogger.setLogContext("testReqId", "testSvcId"); + invokePrepareMsg("ERROR", "testServiceName3", null); + Assert.assertTrue (MDC.get(MsoLogger.REQUEST_ID).equals("testReqId") && MDC.get(MsoLogger.SERVICE_INSTANCE_ID).equals("testSvcId") && MDC.get(MsoLogger.SERVICE_NAME).equals("testServiceName3") + && MDC.get(MsoLogger.TIMER) == null && MDC.get(MsoLogger.ALERT_SEVERITY).equals("2") ); + + MsoLogger.setServiceName("testServiceName2"); + invokePrepareMsg("WARN", msgNull, msgNull); + Assert.assertTrue (MDC.get(MsoLogger.REQUEST_ID).equals("testReqId") && MDC.get(MsoLogger.SERVICE_INSTANCE_ID).equals("testSvcId") && MDC.get(MsoLogger.SERVICE_NAME).equals("testServiceName2") + && MDC.get(MsoLogger.TIMER) == null && MDC.get(MsoLogger.ALERT_SEVERITY).equals("1")); + + MDC.clear (); + MsoRequest msoRequest = new MsoRequest (); + msoRequest.setRequestId ("reqId2"); + msoRequest.setServiceInstanceId ("servId2"); + MsoLogger.setLogContext (msoRequest); + invokePrepareMsg("FATAL", null, "123"); + Assert.assertTrue (MDC.get(MsoLogger.REQUEST_ID).equals("reqId2") && MDC.get(MsoLogger.SERVICE_INSTANCE_ID).equals("servId2") && MDC.get(MsoLogger.TIMER).equals("123") && MDC.get(MsoLogger.ALERT_SEVERITY).equals("3")); + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + /** + * This method implements a test of log methods + */ + @Test + public final void testLogMethods () { + try { + MDC.clear(); + MsoLogger.setLogContext("reqId2", "servId2"); + MsoLogger.setServiceName("MSO.testServiceName"); + msoLogger.info (MessageEnum.LOGGER_UPDATE_SUC, "testLogger", "INFO", "DEBUG", "target entity", "target service"); + msoLogger.warn (MessageEnum.GENERAL_WARNING, "warning test", "", "", MsoLogger.ErrorCode.UnknownError, "warning test"); + msoLogger.error (MessageEnum.GENERAL_EXCEPTION, "target entity", "target service", MsoLogger.ErrorCode.UnknownError, "error test"); + + //Fetch from the error log + URL url = this.getClass().getClassLoader().getResource("logback-test.xml"); + String logFile = url.getFile().substring(0, url.getFile().indexOf("test-classes")) + "/MSO/Test/errorjboss.server.name_IS_UNDEFINED.log"; + + Path filePath = new File(logFile).toPath(); + Charset charset = Charset.defaultCharset(); + List<String> stringList = Files.readAllLines(filePath, charset); + String[] stringArray = stringList.toArray(new String[]{}); + int size = stringArray.length; + + Assert.assertTrue(stringArray[size-3].contains("|reqId2|main|MSO.testServiceName||target entity|target service|INFO|null||") && stringArray[size-3].contains("||MSO-GENERAL-5408I Successfully update Logger: testLogger from level INFO to level DEBUG")); + Assert.assertTrue(stringArray[size-2].contains("|reqId2|main|MSO.testServiceName||||WARN|UnknownError|warning test|") && stringArray[size-2].contains("|MSO-GENERAL-5401W WARNING: warning test")); + Assert.assertTrue(stringArray[size-1].contains("|reqId2|main|MSO.testServiceName||target entity|target service|ERROR|UnknownError|error test|") && stringArray[size-1].contains("|MSO-GENERAL-9401E Exception encountered")); + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /** + * This method implements a test of recordMetricEvent method. + */ + @Test + public final void testRecordMetricEvent () { + try { + MDC.clear(); + MsoLogger.setLogContext("reqId", "servId"); + msoLogger.recordMetricEvent(123456789L, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successful", "VNF" , "createVNF", null); + MDC.put (MsoLogger.REMOTE_HOST, "127.0.0.1"); + MDC.put (MsoLogger.PARTNERNAME, "testUser"); + msoLogger.recordMetricEvent(123456789L, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.ServiceNotAvailable, "Exception", "SDNC", "removeSDNC", "testVNF"); + + //Fetch from the metric log + URL url = this.getClass().getClassLoader().getResource("logback-test.xml"); + String logFile = url.getFile().substring(0, url.getFile().indexOf("test-classes")) + "/MSO/Test/metricsjboss.server.name_IS_UNDEFINED.log"; + + Path filePath = new File(logFile).toPath(); + Charset charset = Charset.defaultCharset(); + List<String> stringList = Files.readAllLines(filePath, charset); + String[] stringArray = stringList.toArray(new String[]{}); + msoLogger.error (MessageEnum.GENERAL_EXCEPTION, "", "", MsoLogger.ErrorCode.UnknownError, "test error msg"); + + Assert.assertTrue(stringArray[0].contains("|reqId|servId|main||testRecordMetricEvent||VNF|createVNF|COMPLETE|0|Successful|Test UUID as JBoss not found|INFO|0|")); + // count the occurance of symbol "|" + Assert.assertTrue ((stringArray[0].length() - stringArray[0].replace("|", "").length()) == 28); + Assert.assertTrue(stringArray[1].contains("|reqId|servId|main||testRecordMetricEvent|testUser|SDNC|removeSDNC|ERROR|501|Exception|Test UUID as JBoss not found|INFO|0|") && stringArray[1].contains("|127.0.0.1||||testVNF|||||")); + Assert.assertTrue ((stringArray[1].length() - stringArray[1].replace("|", "").length()) == 28); + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /** + * This method implements a test of testRecordAuditEvent method. + */ + @Test + public final void testRecordAuditEvent () { + + try { + + MDC.clear(); + MsoLogger.setLogContext("reqId", "servId"); + msoLogger.recordAuditEvent(123456789L, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successful"); + MDC.put (MsoLogger.REMOTE_HOST, "127.0.0.1"); + MDC.put (MsoLogger.PARTNERNAME, "testUser"); + msoLogger.recordAuditEvent(123456789L, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.ServiceNotAvailable, "Exception"); + + //Fetch from the metric log + URL url = this.getClass().getClassLoader().getResource("logback-test.xml"); + String logFile = url.getFile().substring(0, url.getFile().indexOf("test-classes")) + "/MSO/Test/auditjboss.server.name_IS_UNDEFINED.log"; + + Path filePath = new File(logFile).toPath(); + Charset charset = Charset.defaultCharset(); + List<String> stringList = Files.readAllLines(filePath, charset); + String[] stringArray = stringList.toArray(new String[]{}); + msoLogger.error (MessageEnum.GENERAL_EXCEPTION, "", "", ErrorCode.UnknownError, "log error"); + + Assert.assertTrue (stringArray[0].contains("|reqId|servId|main||testRecordAuditEvent||COMPLETE|0|Successful|Test UUID as JBoss not found|INFO|0|")); + // count the occurance of symbol "|" + Assert.assertTrue ((stringArray[0].length() - stringArray[0].replace("|", "").length()) == 25); + Assert.assertTrue (stringArray[1].contains("|reqId|servId|main||testRecordAuditEvent|testUser|ERROR|501|Exception|Test UUID as JBoss not found|INFO|0|") && stringArray[1].contains("|127.0.0.1||||||||")); + Assert.assertTrue ((stringArray[1].length() - stringArray[1].replace("|", "").length()) == 25); + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + + + + // User reflection to invoke to avoid change the publicity of the method + private static String invokePrepareMsg (String arg1, String arg2, String arg3) { + Method method; + try { + method = MsoLogger.class.getDeclaredMethod("prepareMsg", String.class, String.class, String.class); + method.setAccessible(true); + return (String)method.invoke(msoLogger, arg1, arg2, arg3); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return null; + } + + // User reflection to invoke to avoid change the publicity of the method + private static Object invokePriveMethod (String methodName, String arg) { + Method method; + try { + method = MsoLogger.class.getDeclaredMethod(methodName, String.class); + method.setAccessible(true); + return method.invoke(msoLogger, arg); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return null; + } +} diff --git a/common/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoPropertiesFactoryConcurrencyTest.java b/common/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoPropertiesFactoryConcurrencyTest.java new file mode 100644 index 0000000000..ac27b20ada --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoPropertiesFactoryConcurrencyTest.java @@ -0,0 +1,174 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.adapter_utils.tests; + + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.FileNotFoundException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import org.junit.BeforeClass; +import org.junit.Test; + +import org.openecomp.mso.properties.AbstractMsoProperties; +import org.openecomp.mso.properties.MsoJavaProperties; +import org.openecomp.mso.properties.MsoPropertiesException; +import org.openecomp.mso.properties.MsoPropertiesFactory; + +/** + * This class implements test methods of the MsoPropertiesFactory features. + * + * + */ +public class MsoPropertiesFactoryConcurrencyTest { + + public static MsoPropertiesFactory msoPropertiesFactory = new MsoPropertiesFactory(); + + public static final String MSO_PROP_ID = "TEST_PROP"; + public static final String PATH_MSO_PROP1 = MsoJavaProperties.class.getClassLoader().getResource("mso.properties") + .toString().substring(5); + public static final String PATH_MSO_PROP2 = MsoJavaProperties.class.getClassLoader().getResource("mso2.properties") + .toString().substring(5); + + /** + * This method is called before any test occurs. It creates a fake tree from + * scratch + * + * @throws MsoPropertiesException + */ + @BeforeClass + public static final void prepare() throws MsoPropertiesException { + // it's possible to have it already initialized, as tests are executed in the same JVM + msoPropertiesFactory.removeAllMsoProperties (); + msoPropertiesFactory.initializeMsoProperties(MSO_PROP_ID, PATH_MSO_PROP1); + } + + private Callable<Integer> taskReload = new Callable<Integer>() { + @Override + public Integer call() { + try { + if (!msoPropertiesFactory.reloadMsoProperties()) { + return 1; + } + } catch (Exception e) { + e.printStackTrace (); + return 1; + } + return 0; + } + }; + + private Callable<Integer> taskRead = new Callable<Integer>() { + @Override + public Integer call() { + try { + MsoJavaProperties msoProperties = msoPropertiesFactory.getMsoJavaProperties(MSO_PROP_ID); + String property1 = msoProperties.getProperty("ecomp.mso.cloud.1.cloudId", "defaultValue"); + String property2 = msoProperties.getProperty("ecomp.mso.cloud.1.keystoneUrl", "defaultValue"); + String property3 = msoProperties.getProperty("ecomp.mso.cloud.1.msoId", "defaultValue"); + String property4 = msoProperties.getProperty("ecomp.mso.cloud.1.publicNetId", "defaultValue"); + String property5 = msoProperties.getProperty("does.not.exist", "defaultValue"); + String property6 = msoProperties.getProperty("ecomp.mso.cloud.1.test", "defaultValue"); + String property7 = msoProperties.getProperty("ecomp.mso.cloud.1.boolean", "defaultValue"); + + assertEquals(property1, "MT"); + assertEquals(property2, "http://localhost:5000/v2.0"); + assertEquals(property3, "John"); + assertEquals(property4, "FD205490A48D48475607C36B9AD902BF"); + assertEquals(property5, "defaultValue"); + assertEquals(property6, "1234"); + assertEquals(property7, "true"); + + } catch (MsoPropertiesException e) { + e.printStackTrace (); + return 1; + } + return 0; + } + }; + + private Callable<Integer> taskReadAll = new Callable<Integer>() { + @Override + public Integer call() { + try { + List<AbstractMsoProperties> msoPropertiesList = msoPropertiesFactory.getAllMsoProperties(); + String property1 = ((MsoJavaProperties)msoPropertiesList.get(0)).getProperty("ecomp.mso.cloud.1.cloudId", "defaultValue"); + String property2 = ((MsoJavaProperties)msoPropertiesList.get(0)).getProperty("ecomp.mso.cloud.1.keystoneUrl", "defaultValue"); + String property3 = ((MsoJavaProperties)msoPropertiesList.get(0)).getProperty("ecomp.mso.cloud.1.msoId", "defaultValue"); + String property4 = ((MsoJavaProperties)msoPropertiesList.get(0)).getProperty("ecomp.mso.cloud.1.publicNetId", "defaultValue"); + String property5 = ((MsoJavaProperties)msoPropertiesList.get(0)).getProperty("does.not.exist", "defaultValue"); + String property6 = ((MsoJavaProperties)msoPropertiesList.get(0)).getProperty("ecomp.mso.cloud.1.test", "defaultValue"); + String property7 = ((MsoJavaProperties)msoPropertiesList.get(0)).getProperty("ecomp.mso.cloud.1.boolean", "defaultValue"); + + assertEquals(property1, "MT"); + assertEquals(property2, "http://localhost:5000/v2.0"); + assertEquals(property3, "John"); + assertEquals(property4, "FD205490A48D48475607C36B9AD902BF"); + assertEquals(property5, "defaultValue"); + assertEquals(property6, "1234"); + assertEquals(property7, "true"); + } catch (Exception e) { + e.printStackTrace (); + return 1; + } + return 0; + } + }; + + @Test + public final void testGetMsoProperties() + throws MsoPropertiesException, InterruptedException, ExecutionException, FileNotFoundException { + + List<Future<Integer>> list = new ArrayList<Future<Integer>>(); + ExecutorService executor = Executors.newFixedThreadPool(20); + + for (int i = 0; i <= 100000; i++) { + + Future<Integer> futureResult = executor.submit(taskRead); + list.add(futureResult); + + futureResult = executor.submit(taskReload); + list.add(futureResult); + + futureResult = executor.submit(taskReadAll); + list.add(futureResult); + } + executor.shutdown(); + while (!executor.awaitTermination(5, TimeUnit.SECONDS)) { + ; + } + + for (Future<Integer> result : list) { + assertTrue(result.get().equals(0)); + } + + } + +} diff --git a/common/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoPropertiesFactoryTest.java b/common/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoPropertiesFactoryTest.java new file mode 100644 index 0000000000..b0290b088e --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoPropertiesFactoryTest.java @@ -0,0 +1,611 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.adapter_utils.tests; + + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.codehaus.jackson.JsonNode; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import org.openecomp.mso.properties.MsoJavaProperties; +import org.openecomp.mso.properties.MsoJsonProperties; +import org.openecomp.mso.properties.MsoPropertiesException; +import org.openecomp.mso.properties.MsoPropertiesFactory; + +/** + * This class implements test methods of the MsoPropertiesFactory features. + * + * + */ +public class MsoPropertiesFactoryTest { + + public static MsoPropertiesFactory msoPropertiesFactory = new MsoPropertiesFactory(); + + public static final String MSO_JAVA_PROP_ID = "TEST_JAVA_PROP"; + public static final String MSO_JSON_PROP_ID = "TEST_JSON_PROP"; + public static final String PATH_MSO_JAVA_PROP1 = MsoJavaProperties.class.getClassLoader().getResource("mso.properties") + .toString().substring(5); + public static final String PATH_MSO_JAVA_PROP2 = MsoJavaProperties.class.getClassLoader().getResource("mso2.properties") + .toString().substring(5); + public static final String PATH_MSO_JSON_PROP = MsoJavaProperties.class.getClassLoader().getResource("mso.json") + .toString().substring(5); + public static final String PATH_MSO_JSON_PROP2 = MsoJavaProperties.class.getClassLoader().getResource("mso2.json") + .toString().substring(5); + public static final String PATH_MSO_JSON_PROP_BAD = MsoJavaProperties.class.getClassLoader().getResource("mso-bad.json") + .toString().substring(5); + + @BeforeClass + public static final void prepareBeforeAllTests() { + msoPropertiesFactory.removeAllMsoProperties(); + } + /** + * This method is called before any test occurs. It creates a fake tree from + * scratch + * + * @throws MsoPropertiesException + */ + @Before + public final void prepareBeforeEachTest() throws MsoPropertiesException { + + msoPropertiesFactory.initializeMsoProperties(MSO_JAVA_PROP_ID, PATH_MSO_JAVA_PROP1); + msoPropertiesFactory.initializeMsoProperties(MSO_JSON_PROP_ID, PATH_MSO_JSON_PROP); + } + + @After + public final void cleanAfterEachTest() throws MsoPropertiesException { + msoPropertiesFactory.removeAllMsoProperties (); + } + + @Test + public final void testNotRecognizedFile() { + try { + msoPropertiesFactory.initializeMsoProperties("BAD_FILE", "new_file.toto"); + + fail ("MsoPropertiesException should have been raised"); + } catch (MsoPropertiesException ep) { + assertTrue(("Unable to load the MSO properties file because format is not recognized (only .json or .properties): new_file.toto").equals(ep.getMessage())); + } + } + + @Test + public final void testDoubleInit() { + + try { + msoPropertiesFactory.initializeMsoProperties(MSO_JAVA_PROP_ID, PATH_MSO_JAVA_PROP1); + + fail ("MsoPropertiesException should have been raised"); + } catch (MsoPropertiesException ep) { + assertTrue(("The factory contains already an instance of this mso properties: "+PATH_MSO_JAVA_PROP1).equals(ep.getMessage())); + } + + + } + + /** + * This method implements a test for the getMsoJavaProperties method. + * + * @throws MsoPropertiesException + */ + @Test + public final void testGetMsoJavaProperties() throws MsoPropertiesException { + assertNotNull(msoPropertiesFactory.getMsoJavaProperties(MSO_JAVA_PROP_ID)); + assertTrue(msoPropertiesFactory.getMsoJavaProperties(MSO_JAVA_PROP_ID).size()==8); + + try { + msoPropertiesFactory.getMsoJavaProperties(MSO_JSON_PROP_ID); + + fail ("MsoPropertiesException should have been raised"); + } catch (MsoPropertiesException ep) { + assertTrue(("Mso properties is not JAVA_PROP properties type:" + MSO_JSON_PROP_ID).equals(ep.getMessage())); + } + + try { + msoPropertiesFactory.getMsoJavaProperties("DUMB_PROP"); + + fail ("MsoPropertiesException should have been raised"); + } catch (MsoPropertiesException ep) { + assertTrue(("Mso properties not found in cache:"+"DUMB_PROP").equals(ep.getMessage())); + } + + } + + /** + * This method test the MsoJavaProperties Set, equals and hascode + * @throws MsoPropertiesException + */ + @Test + public final void testSetMsoJavaProperties() throws MsoPropertiesException { + MsoJavaProperties msoPropChanged = msoPropertiesFactory.getMsoJavaProperties(MSO_JAVA_PROP_ID); + msoPropChanged.setProperty("testos", "testos"); + assertNotNull(msoPropChanged.getProperty("testos", null)); + + // Check no modification occurred on cache one + MsoJavaProperties msoPropCache = msoPropertiesFactory.getMsoJavaProperties(MSO_JAVA_PROP_ID); + assertNull(msoPropCache.getProperty("testos", null)); + assertFalse(msoPropChanged.hashCode() != msoPropCache.hashCode()); + + assertFalse(msoPropChanged.equals(null)); + assertFalse(msoPropChanged.equals(msoPropCache)); + assertFalse(msoPropChanged.equals(new Boolean(true))); + + assertTrue(msoPropChanged.equals(msoPropChanged)); + } + + + /** + * This method implements a test for the testGetMsoJsonProperties method. + * + * @throws MsoPropertiesException + */ + @Test + public final void testGetMsoJsonProperties() throws MsoPropertiesException { + assertNotNull(msoPropertiesFactory.getMsoJsonProperties(MSO_JSON_PROP_ID)); + + try { + msoPropertiesFactory.getMsoJsonProperties(MSO_JAVA_PROP_ID); + + fail ("MsoPropertiesException should have been raised"); + } catch (MsoPropertiesException ep) { + assertTrue(("Mso properties is not JSON_PROP properties type:" + MSO_JAVA_PROP_ID).equals(ep.getMessage())); + } + + try { + msoPropertiesFactory.getMsoJsonProperties("DUMB_PROP"); + + fail ("MsoPropertiesException should have been raised"); + } catch (MsoPropertiesException ep) { + assertTrue(("Mso properties not found in cache:"+"DUMB_PROP").equals(ep.getMessage())); + } + + } + + /** + * This method implements a test for the testGetAllMsoProperties method. + * + * @throws MsoPropertiesException + */ + @Test + public final void testGetAllMsoProperties() throws MsoPropertiesException { + assertNotNull(msoPropertiesFactory.getAllMsoProperties().size()==2); + + } + + /** + * This method implements a test for the testGetAllMsoProperties method. + * + * @throws MsoPropertiesException + */ + @Test + public final void testToString() throws MsoPropertiesException { + String dump = msoPropertiesFactory.getMsoJsonProperties(MSO_JSON_PROP_ID).toString(); + assertTrue(dump != null && !dump.isEmpty()); + + dump = msoPropertiesFactory.getMsoJavaProperties(MSO_JAVA_PROP_ID).toString(); + assertTrue(dump != null && !dump.isEmpty()); + + } + + /** + * This method implements a test for the getProperty of JAVA_PROP type method. + * + * @throws MsoPropertiesException + */ + @Test + public final void testGetProperties() throws MsoPropertiesException { + MsoJavaProperties msoProperties = msoPropertiesFactory.getMsoJavaProperties(MSO_JAVA_PROP_ID); + + String property1 = msoProperties.getProperty("ecomp.mso.cloud.1.cloudId", "defaultValue"); + String property2 = msoProperties.getProperty("ecomp.mso.cloud.1.keystoneUrl", "defaultValue"); + String property3 = msoProperties.getProperty("ecomp.mso.cloud.1.msoId", "defaultValue"); + String property4 = msoProperties.getProperty("ecomp.mso.cloud.1.publicNetId", "defaultValue"); + String property5 = msoProperties.getProperty("does.not.exist", "defaultValue"); + String property6 = msoProperties.getProperty("ecomp.mso.cloud.1.test", "defaultValue"); + String property7 = msoProperties.getProperty("ecomp.mso.cloud.1.boolean", "defaultValue"); + + assertEquals(property1, "MT"); + assertEquals(property2, "http://localhost:5000/v2.0"); + assertEquals(property3, "John"); + assertEquals(property4, "FD205490A48D48475607C36B9AD902BF"); + assertEquals(property5, "defaultValue"); + assertEquals(property6, "1234"); + assertEquals(property7, "true"); + } + + /** + * This method implements a test for the getIntProperty JAVA_RPOP type method. + * + * @throws MsoPropertiesException + */ + @Test + public final void testGetIntProperties() throws MsoPropertiesException { + MsoJavaProperties msoProperties = msoPropertiesFactory.getMsoJavaProperties(MSO_JAVA_PROP_ID); + int property1 = msoProperties.getIntProperty("ecomp.mso.cloud.1.test", 345); + int property2 = msoProperties.getIntProperty("ecomp.mso.cloud.1.publicNetId", 345); + int property3 = msoProperties.getIntProperty("does.not.exist", 345); + assertEquals(property1, 1234); + assertEquals(property2, 345); + assertEquals(property3, 345); + } + + /** + * This method implements a test for the getBooleanProperty JAVA_RPOP type method. + * + * @throws MsoPropertiesException + */ + @Test + public final void testGetBooleanProperty() throws MsoPropertiesException { + MsoJavaProperties msoProperties = msoPropertiesFactory.getMsoJavaProperties(MSO_JAVA_PROP_ID); + boolean property1 = msoProperties.getBooleanProperty("ecomp.mso.cloud.1.boolean", false); + boolean property2 = msoProperties.getBooleanProperty("ecomp.mso.cloud.1.publicNetId", false); + boolean property3NotThere = msoProperties.getBooleanProperty("ecomp.mso.cloud.1.publicNetIdBad", true); + + assertEquals(property1, true); + assertEquals(property2, false); + assertEquals(property3NotThere, true); + } + + /** + * This method implements a test for the getEncryptedProperty JAVA_RPOP type method. + * + * @throws MsoPropertiesException + */ + @Test + public final void testGetEncryptedProperty() throws MsoPropertiesException { + MsoJavaProperties msoProperties = msoPropertiesFactory.getMsoJavaProperties(MSO_JAVA_PROP_ID); + String property1 = msoProperties.getEncryptedProperty("ecomp.mso.cloud.1.publicNetId", "defaultValue", + "aa3871669d893c7fb8abbcda31b88b4f"); + String property2 = msoProperties.getEncryptedProperty("test", "defaultValue", + "aa3871669d893c7fb8abbcda31b88b4f"); + + + String property3Wrong = msoProperties.getEncryptedProperty("ecomp.mso.cloud.1.publicNetId", "defaultValue", + "aa3871669d893c7fb8abbcda31b88b4"); + + + assertEquals(property1, "changeme"); + assertEquals(property2, "defaultValue"); + assertEquals(property3Wrong, "defaultValue"); + } + + /** + * This method implements a test for the getEncryptedProperty JAVA_RPOP type method. + * + * @throws MsoPropertiesException + */ + @Test + public final void testencryptProperty() { + + assertTrue("FD205490A48D48475607C36B9AD902BF" + .contains(msoPropertiesFactory.encryptProperty("changeme", "aa3871669d893c7fb8abbcda31b88b4f").getEntity().toString())); + + + assertTrue("Invalid AES key length: 15 bytes".contains(msoPropertiesFactory.encryptProperty("changeme", "aa3871669d893c7fb8abbcda31b88b4").getEntity().toString())); + + } + + /** + * This method implements a test for the getJSON JSON_RPOP type method. + * + * @throws MsoPropertiesException + */ + @Test + public final void testGetJsonNode() throws MsoPropertiesException { + MsoJsonProperties msoProperties = msoPropertiesFactory.getMsoJsonProperties(MSO_JSON_PROP_ID); + + JsonNode propNode = msoProperties.getJsonRootNode(); + assertNotNull(propNode); + assertFalse(propNode.toString().isEmpty()); + assertTrue(propNode.isContainerNode()); + assertNotNull(propNode.path("asdc-connections").path("asdc-controller1")); + assertNotNull(propNode.path("asdc-connections").path("asdc-controller2")); + + } + + /** + * This method implements a test for the reloadMsoProperties method. + * + * @throws MsoPropertiesException + * + */ + @Test + public final void testReloadJavaMsoProperties() throws MsoPropertiesException { + MsoJavaProperties msoProperties = msoPropertiesFactory.getMsoJavaProperties(MSO_JAVA_PROP_ID); + + // Do some additional test on propertiesHaveChanged method + assertTrue(msoPropertiesFactory.propertiesHaveChanged(MSO_JAVA_PROP_ID, null)); + + // Change path with bad one + try { + msoPropertiesFactory.changeMsoPropertiesFilePath("DO_NOT_EXIST", PATH_MSO_JAVA_PROP2); + + fail ("MsoPropertiesException should have been raised"); + } catch (MsoPropertiesException ep) { + assertTrue(("Mso properties not found in cache:DO_NOT_EXIST").equals(ep.getMessage())); + } + + + // Change path with right one + msoPropertiesFactory.changeMsoPropertiesFilePath(MSO_JAVA_PROP_ID, PATH_MSO_JAVA_PROP2); + assertTrue(PATH_MSO_JAVA_PROP2.equals(msoPropertiesFactory.getMsoJavaProperties(MSO_JAVA_PROP_ID).getPropertiesFileName())); + + assertTrue(msoPropertiesFactory.reloadMsoProperties()); + assertFalse(msoPropertiesFactory.propertiesHaveChanged(MSO_JAVA_PROP_ID, msoProperties)); + // Do a second time as timer value is set to 2 + assertTrue(msoPropertiesFactory.reloadMsoProperties()); + assertTrue(msoPropertiesFactory.propertiesHaveChanged(MSO_JAVA_PROP_ID, msoProperties)); + + // Get the new one + msoProperties = msoPropertiesFactory.getMsoJavaProperties(MSO_JAVA_PROP_ID); + String property1 = msoProperties.getProperty("ecomp.mso.cloud.1.cloudId", "defaultValue"); + String property2 = msoProperties.getProperty("ecomp.mso.cloud.1.keystoneUrl", "defaultValue"); + String property3 = msoProperties.getProperty("ecomp.mso.cloud.1.msoId", "defaultValue"); + String property4 = msoProperties.getProperty("ecomp.mso.cloud.1.publicNetId", "defaultValue"); + String property5 = msoProperties.getProperty("does.not.exist", "defaultValue"); + String property6 = msoProperties.getProperty("ecomp.mso.cloud.1.test", "defaultValue"); + String property7 = msoProperties.getProperty("ecomp.mso.cloud.1.boolean", "defaultValue"); + + assertEquals(property1, "MT2"); + assertEquals(property2, "defaultValue"); + assertEquals(property3, "defaultValue"); + assertEquals(property4, "defaultValue"); + assertEquals(property5, "defaultValue"); + assertEquals(property6, "defaultValue"); + assertEquals(property7, "defaultValue"); + + // Additional test on propertiesHaveChanged + msoPropertiesFactory.removeAllMsoProperties(); + + // Do some additional test on propertiesHaveChanged method + try { + msoPropertiesFactory.propertiesHaveChanged(MSO_JAVA_PROP_ID, null); + + fail ("MsoPropertiesException should have been raised"); + } catch (MsoPropertiesException ep) { + assertTrue(("Mso properties not found in cache:"+MSO_JAVA_PROP_ID).equals(ep.getMessage())); + } + + try { + msoPropertiesFactory.propertiesHaveChanged(MSO_JAVA_PROP_ID, msoProperties); + + fail ("MsoPropertiesException should have been raised"); + } catch (MsoPropertiesException ep) { + assertTrue(("Mso properties not found in cache:"+MSO_JAVA_PROP_ID).equals(ep.getMessage())); + } + + } + + /** + * This method implements a test for the reloadMsoProperties method. + * + * @throws MsoPropertiesException + * + */ + @Test + public final void testReloadMoreThanAMinuteMsoProperties() throws MsoPropertiesException { + MsoJavaProperties msoProperties = msoPropertiesFactory.getMsoJavaProperties(MSO_JAVA_PROP_ID); + + msoPropertiesFactory.changeMsoPropertiesFilePath(MSO_JAVA_PROP_ID, PATH_MSO_JAVA_PROP2); + + // Simulate 2 minutes + msoPropertiesFactory.reloadMsoProperties(); + assertFalse(msoPropertiesFactory.propertiesHaveChanged(MSO_JAVA_PROP_ID, msoProperties)); + msoPropertiesFactory.reloadMsoProperties(); + + assertTrue(msoPropertiesFactory.propertiesHaveChanged(MSO_JAVA_PROP_ID, msoProperties)); + + // Get the new one + msoProperties = msoPropertiesFactory.getMsoJavaProperties(MSO_JAVA_PROP_ID); + String property1 = msoProperties.getProperty("ecomp.mso.cloud.1.cloudId", "defaultValue"); + String property2 = msoProperties.getProperty("ecomp.mso.cloud.1.keystoneUrl", "defaultValue"); + String property3 = msoProperties.getProperty("ecomp.mso.cloud.1.msoId", "defaultValue"); + String property4 = msoProperties.getProperty("ecomp.mso.cloud.1.publicNetId", "defaultValue"); + String property5 = msoProperties.getProperty("does.not.exist", "defaultValue"); + String property6 = msoProperties.getProperty("ecomp.mso.cloud.1.test", "defaultValue"); + String property7 = msoProperties.getProperty("ecomp.mso.cloud.1.boolean", "defaultValue"); + + assertEquals(property1, "MT2"); + assertEquals(property2, "defaultValue"); + assertEquals(property3, "defaultValue"); + assertEquals(property4, "defaultValue"); + assertEquals(property5, "defaultValue"); + assertEquals(property6, "defaultValue"); + assertEquals(property7, "defaultValue"); + + + } + + /** + * This method implements a test for the reloadMsoProperties method. + * + * @throws MsoPropertiesException + * + */ + @Test + public final void testReloadBadMsoProperties() throws MsoPropertiesException { + MsoJavaProperties msoProperties = msoPropertiesFactory.getMsoJavaProperties(MSO_JAVA_PROP_ID); + + msoPropertiesFactory.changeMsoPropertiesFilePath(MSO_JAVA_PROP_ID, "file-does-not-exist.properties"); + msoPropertiesFactory.reloadMsoProperties(); + assertFalse(msoPropertiesFactory.propertiesHaveChanged(MSO_JAVA_PROP_ID, msoProperties)); + // Reload it a second time as initial timer parameter was set to 2 + msoPropertiesFactory.reloadMsoProperties(); + + assertTrue(msoPropertiesFactory.propertiesHaveChanged(MSO_JAVA_PROP_ID, msoProperties)); + + // Get the new one + msoProperties = msoPropertiesFactory.getMsoJavaProperties(MSO_JAVA_PROP_ID); + String property1 = msoProperties.getProperty("ecomp.mso.cloud.1.cloudId", "defaultValue"); + String property2 = msoProperties.getProperty("ecomp.mso.cloud.1.keystoneUrl", "defaultValue"); + String property3 = msoProperties.getProperty("ecomp.mso.cloud.1.msoId", "defaultValue"); + String property4 = msoProperties.getProperty("ecomp.mso.cloud.1.publicNetId", "defaultValue"); + String property5 = msoProperties.getProperty("does.not.exist", "defaultValue"); + String property6 = msoProperties.getProperty("ecomp.mso.cloud.1.test", "defaultValue"); + String property7 = msoProperties.getProperty("ecomp.mso.cloud.1.boolean", "defaultValue"); + + assertEquals(property1, "defaultValue"); + assertEquals(property2, "defaultValue"); + assertEquals(property3, "defaultValue"); + assertEquals(property4, "defaultValue"); + assertEquals(property5, "defaultValue"); + assertEquals(property6, "defaultValue"); + assertEquals(property7, "defaultValue"); + + } + + /** + * This method implements a test for the reloadMsoProperties method. + * + * @throws MsoPropertiesException + * + */ + @Test + public final void testReloadBadMsoJsonProperties() throws MsoPropertiesException { + // Load a bad JSON file + MsoJsonProperties msoProperties = msoPropertiesFactory.getMsoJsonProperties(MSO_JSON_PROP_ID); + + msoPropertiesFactory.changeMsoPropertiesFilePath(MSO_JSON_PROP_ID, PATH_MSO_JSON_PROP_BAD); + + msoPropertiesFactory.reloadMsoProperties(); + assertFalse(msoPropertiesFactory.propertiesHaveChanged(MSO_JSON_PROP_ID, msoProperties)); + // Reload it a second time as initial timer parameter was set to 2 + msoPropertiesFactory.reloadMsoProperties(); + + assertTrue(msoPropertiesFactory.propertiesHaveChanged(MSO_JSON_PROP_ID, msoProperties)); + + // Get the new one + msoProperties = msoPropertiesFactory.getMsoJsonProperties(MSO_JSON_PROP_ID); + assertNotNull(msoProperties); + assertNotNull(msoProperties.getJsonRootNode()); + assertTrue(msoProperties.getJsonRootNode().size() == 0); + + } + + @Test + public final void testRemoveMsoProperties() throws MsoPropertiesException { + try { + msoPropertiesFactory.removeMsoProperties("DUMB_PROP"); + + fail ("MsoPropertiesException should have been raised"); + } catch (MsoPropertiesException ep) { + assertTrue(("Mso properties not found in cache:"+"DUMB_PROP").equals(ep.getMessage())); + } + + msoPropertiesFactory.removeMsoProperties(MSO_JAVA_PROP_ID); + + try { + msoPropertiesFactory.getMsoJavaProperties(MSO_JAVA_PROP_ID); + + fail ("MsoPropertiesException should have been raised"); + } catch (MsoPropertiesException ep) { + assertTrue(("Mso properties not found in cache:"+MSO_JAVA_PROP_ID).equals(ep.getMessage())); + } + + } + + @Test + public final void testInitializeWithNonExistingPropertiesFile () throws MsoPropertiesException { + try { + msoPropertiesFactory.initializeMsoProperties("NEW_BAD_FILE", "no_file.properties"); + fail ("MsoPropertiesException should have been raised"); + } catch (MsoPropertiesException ep) { + assertTrue(("Unable to load the MSO properties file because it has not been found:no_file.properties").equals(ep.getMessage())); + } + + // empty object should be returned as no config has been loaded, anyway no exception should be raised because the config ID must be loaded in cache + // This is there for automatic reload attempt + assertTrue(msoPropertiesFactory.getMsoJavaProperties("NEW_BAD_FILE").size()==0); + } + + + @Test + public final void testInitializeWithNonExistingJsonFile () throws MsoPropertiesException { + try { + msoPropertiesFactory.initializeMsoProperties("NEW_BAD_FILE", "no_file.json"); + fail ("MsoPropertiesException should have been raised"); + } catch (MsoPropertiesException ep) { + assertTrue(("Unable to load the MSO properties file because it has not been found:no_file.json").equals(ep.getMessage())); + } + + // empty object should be returned as no config has been loaded, anyway no exception should be raised because the config ID must be loaded in cache + // This is there for automatic reload attempt + assertTrue(msoPropertiesFactory.getMsoJsonProperties("NEW_BAD_FILE").getJsonRootNode()!=null); + assertTrue("{}".equals(msoPropertiesFactory.getMsoJsonProperties("NEW_BAD_FILE").getJsonRootNode().toString())); + } + + @Test + public final void testShowProperties() { + assertTrue(msoPropertiesFactory.showProperties().getEntity().toString().contains("/target/test-classes/mso.json(Timer:2mins)")); + assertTrue(msoPropertiesFactory.showProperties().getEntity().toString().contains("asdc-controller1")); + assertTrue(msoPropertiesFactory.showProperties().getEntity().toString().contains("/target/test-classes/mso.properties(Timer:2mins):")); + assertTrue(msoPropertiesFactory.showProperties().getEntity().toString().contains("ecomp.mso.cloud.1.keystoneUrl")); + + } + + @Test + public final void testGetEncryptedPropertyJson() throws MsoPropertiesException { + MsoJsonProperties msoProperties = msoPropertiesFactory.getMsoJsonProperties(MSO_JSON_PROP_ID); + assertTrue("ThePassword".equals(msoProperties.getEncryptedProperty(msoProperties.getJsonRootNode().get("asdc-connections").get("asdc-controller1").get("asdcPassword"),"defautlvalue","566B754875657232314F5548556D3665"))); + + assertTrue("defautlvalue".equals(msoProperties.getEncryptedProperty(msoProperties.getJsonRootNode().get("asdc-connections").get("asdc-controller1").get("asdcPassword"),"defautlvalue","566B754875657232314F5548556D366"))); + + + } + + @Test + public final void testHashcodeAndEqualsMsoJsonProperties() throws MsoPropertiesException { + + MsoJsonProperties msoProperties = msoPropertiesFactory.getMsoJsonProperties(MSO_JSON_PROP_ID); + + msoPropertiesFactory.changeMsoPropertiesFilePath(MSO_JSON_PROP_ID, PATH_MSO_JSON_PROP2); + + msoPropertiesFactory.reloadMsoProperties(); + assertFalse(msoPropertiesFactory.propertiesHaveChanged(MSO_JSON_PROP_ID, msoProperties)); + // Reload it a second time as initial timer parameter was set to 2 + msoPropertiesFactory.reloadMsoProperties(); + assertTrue(msoPropertiesFactory.propertiesHaveChanged(MSO_JSON_PROP_ID, msoProperties)); + + // Get the new one + MsoJsonProperties msoProperties2 = msoPropertiesFactory.getMsoJsonProperties(MSO_JSON_PROP_ID); + assertFalse(msoProperties.hashCode()==msoProperties2.hashCode()); + + assertFalse(msoProperties.equals(msoProperties2)); + assertTrue(msoProperties.equals(msoProperties)); + assertFalse(msoProperties.equals(null)); + assertFalse(msoProperties.equals(new String())); + + // Test a reload with timer set to 1 in PATH_MSO_JSON_PROP2 + msoPropertiesFactory.changeMsoPropertiesFilePath(MSO_JSON_PROP_ID, PATH_MSO_JSON_PROP); + + msoPropertiesFactory.reloadMsoProperties(); + assertTrue(msoPropertiesFactory.propertiesHaveChanged(MSO_JSON_PROP_ID, msoProperties2)); + + } + +} diff --git a/common/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoPropertyInitializerTest.java b/common/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoPropertyInitializerTest.java new file mode 100644 index 0000000000..36b6249737 --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoPropertyInitializerTest.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.adapter_utils.tests; + + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import javax.servlet.ServletContext; +import javax.servlet.ServletContextEvent; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; + +import org.openecomp.mso.properties.MsoJavaProperties; +import org.openecomp.mso.properties.MsoPropertiesException; +import org.openecomp.mso.properties.MsoPropertiesFactory; +import org.openecomp.mso.properties.MsoPropertyInitializer; + +public class MsoPropertyInitializerTest { + + public static final String ASDC_PROP = MsoJavaProperties.class.getClassLoader().getResource("mso.json").toString().substring(5); + public static ServletContextEvent servletContextEvent = Mockito.mock(ServletContextEvent.class); + public static ServletContext servletContext = Mockito.mock(ServletContext.class); + public MsoPropertyInitializer msoPropInitializer = new MsoPropertyInitializer(); + + @BeforeClass + public static final void prepareBeforeClass() throws MsoPropertiesException { + + Mockito.when(servletContextEvent.getServletContext()).thenReturn(servletContext); + } + + @Before + public final void preparebeforeEachTest() throws MsoPropertiesException { + MsoPropertiesFactory msoPropertiesFactory = new MsoPropertiesFactory(); + msoPropertiesFactory.removeAllMsoProperties(); + + } + + @Test + public void testContextInitialized() throws MsoPropertiesException { + Mockito.when(servletContext.getInitParameter("mso.configuration")).thenReturn("MSO_PROP_ASDC="+ASDC_PROP); + msoPropInitializer.contextInitialized(servletContextEvent); + + MsoPropertiesFactory msoPropertiesFactory = new MsoPropertiesFactory(); + assertNotNull(msoPropertiesFactory.getMsoJsonProperties("MSO_PROP_ASDC")); + assertFalse("{}".equals(msoPropertiesFactory.getMsoJsonProperties("MSO_PROP_ASDC").getJsonRootNode().toString())); + assertTrue(msoPropertiesFactory.getMsoJsonProperties("MSO_PROP_ASDC").getJsonRootNode().get("asdc-connections")!= null); + } + + @Test + public void testContextInitializedFailure() throws MsoPropertiesException { + Mockito.when(servletContext.getInitParameter("mso.configuration")).thenReturn("MSO_PROP_ASDC="+"Does_not_exist.json"); + msoPropInitializer.contextInitialized(servletContextEvent); + + // No exception should be raised, log instead + MsoPropertiesFactory msoPropertiesFactory = new MsoPropertiesFactory(); + + assertTrue("{}".equals(msoPropertiesFactory.getMsoJsonProperties("MSO_PROP_ASDC").getJsonRootNode().toString())); + assertTrue(msoPropertiesFactory.getMsoJsonProperties("MSO_PROP_ASDC").getJsonRootNode().get("asdc-connections")== null); + + + + } + +} diff --git a/common/src/test/java/org/openecomp/mso/entity/MsoRequestESTest.java b/common/src/test/java/org/openecomp/mso/entity/MsoRequestESTest.java new file mode 100644 index 0000000000..a4fe1d361b --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/entity/MsoRequestESTest.java @@ -0,0 +1,65 @@ +/* + * This file was automatically generated by EvoSuite + * Mon Nov 14 09:09:00 GMT 2016 + */ + +package org.openecomp.mso.entity; + +import org.junit.Test; +import static org.junit.Assert.*; + +import org.evosuite.runtime.EvoRunner; +import org.evosuite.runtime.EvoRunnerParameters; +import org.junit.runner.RunWith; + +@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) +public class MsoRequestESTest extends MsoRequestESTestscaffolding { + + @Test(timeout = 4000) + public void test0() throws Throwable { + MsoRequest msoRequest0 = new MsoRequest(); + msoRequest0.setServiceInstanceId("B1!G~O TIP1Auoc}pE"); + String string0 = msoRequest0.getServiceInstanceId(); + assertEquals("B1!G~O TIP1Auoc}pE", string0); + } + + @Test(timeout = 4000) + public void test1() throws Throwable { + MsoRequest msoRequest0 = new MsoRequest(); + msoRequest0.setServiceInstanceId(""); + String string0 = msoRequest0.getServiceInstanceId(); + assertEquals("", string0); + } + + @Test(timeout = 4000) + public void test2() throws Throwable { + MsoRequest msoRequest0 = new MsoRequest(); + String string0 = msoRequest0.getRequestId(); + assertNull(string0); + } + + @Test(timeout = 4000) + public void test3() throws Throwable { + MsoRequest msoRequest0 = new MsoRequest("'SJ", "XUQ4Vd$ppTT4"); + assertEquals("'SJ", msoRequest0.getRequestId()); + + msoRequest0.setRequestId(""); + msoRequest0.getRequestId(); + assertEquals("XUQ4Vd$ppTT4", msoRequest0.getServiceInstanceId()); + } + + @Test(timeout = 4000) + public void test4() throws Throwable { + MsoRequest msoRequest0 = new MsoRequest("'SJ", "XUQ4Vd$ppTT4"); + String string0 = msoRequest0.getRequestId(); + assertEquals("XUQ4Vd$ppTT4", msoRequest0.getServiceInstanceId()); + assertEquals("'SJ", string0); + } + + @Test(timeout = 4000) + public void test5() throws Throwable { + MsoRequest msoRequest0 = new MsoRequest(); + String string0 = msoRequest0.getServiceInstanceId(); + assertNull(string0); + } +} diff --git a/common/src/test/java/org/openecomp/mso/entity/MsoRequestESTestscaffolding.java b/common/src/test/java/org/openecomp/mso/entity/MsoRequestESTestscaffolding.java new file mode 100644 index 0000000000..9ac7ad816d --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/entity/MsoRequestESTestscaffolding.java @@ -0,0 +1,78 @@ +/** + * Scaffolding file used to store all the setups needed to run + * tests automatically generated by EvoSuite + * Mon Nov 14 09:09:00 GMT 2016 + */ + +package org.openecomp.mso.entity; + +import org.evosuite.runtime.annotation.EvoSuiteClassExclude; +import org.junit.BeforeClass; +import org.junit.Before; +import org.junit.After; +import org.junit.AfterClass; +import org.evosuite.runtime.sandbox.Sandbox; + +@EvoSuiteClassExclude +public class MsoRequestESTestscaffolding { + + @org.junit.Rule + public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); + + private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); + + private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); + + @BeforeClass + public static void initEvoSuiteFramework() { + org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.mso.entity.MsoRequest"; + org.evosuite.runtime.GuiSupport.initialize(); + org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; + org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; + org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; + org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; + org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); + org.evosuite.runtime.classhandling.JDKClassResetter.init(); + initializeClasses(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + } + + @AfterClass + public static void clearEvoSuiteFramework(){ + Sandbox.resetDefaultSecurityManager(); + java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); + } + + @Before + public void initTestCase(){ + threadStopper.storeCurrentThreads(); + threadStopper.startRecordingTime(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); + org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); + + org.evosuite.runtime.GuiSupport.setHeadless(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + org.evosuite.runtime.agent.InstrumentingAgent.activate(); + } + + @After + public void doneWithTestCase(){ + threadStopper.killAndJoinClientThreads(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); + org.evosuite.runtime.classhandling.JDKClassResetter.reset(); + resetClasses(); + org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); + org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); + org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); + } + + + private static void initializeClasses() { + org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(MsoRequestESTestscaffolding.class.getClassLoader() , + "org.openecomp.mso.entity.MsoRequest" + ); + } + + private static void resetClasses() { + } +} diff --git a/common/src/test/java/org/openecomp/mso/logger/LogFilterESTest.java b/common/src/test/java/org/openecomp/mso/logger/LogFilterESTest.java new file mode 100644 index 0000000000..22936857c6 --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/logger/LogFilterESTest.java @@ -0,0 +1,191 @@ +/* + * This file was automatically generated by EvoSuite + * Mon Nov 14 09:08:24 GMT 2016 + */ + +package org.openecomp.mso.logger; + +import org.junit.Test; +import static org.junit.Assert.*; +import static org.evosuite.shaded.org.mockito.Mockito.*; +import static org.evosuite.runtime.MockitoExtension.*; +import static org.evosuite.runtime.EvoAssertions.*; + +import java.security.Principal; +import javax.servlet.AsyncContext; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.ServletResponseWrapper; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpServletResponseWrapper; +import org.evosuite.runtime.EvoRunner; +import org.evosuite.runtime.EvoRunnerParameters; +import org.evosuite.runtime.ViolatedAssumptionAnswer; +import org.junit.runner.RunWith; + +@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) +public class LogFilterESTest extends LogFilterESTestscaffolding { + + @Test(timeout = 4000) + public void test0() throws Throwable { + LogFilter logFilter0 = new LogFilter(); + FilterChain filterChain0 = mock(FilterChain.class, new ViolatedAssumptionAnswer()); + // Undeclared exception! + try { + logFilter0.doFilter((ServletRequest) null, (ServletResponse) null, filterChain0); + fail("Expecting exception: NullPointerException"); + + } catch(NullPointerException e) { + // + // no message in exception (getMessage() returned null) + // + verifyException("org.openecomp.mso.logger.LogFilter", e); + } + } + + @Test(timeout = 4000) + public void test1() throws Throwable { + LogFilter logFilter0 = new LogFilter(); + ServletRequest servletRequest0 = mock(ServletRequest.class, new ViolatedAssumptionAnswer()); + ServletResponse servletResponse0 = mock(ServletResponse.class, new ViolatedAssumptionAnswer()); + FilterChain filterChain0 = mock(FilterChain.class, new ViolatedAssumptionAnswer()); + // Undeclared exception! + try { + logFilter0.doFilter(servletRequest0, servletResponse0, filterChain0); + fail("Expecting exception: ClassCastException"); + + } catch(ClassCastException e) { + // + // $javax.servlet.ServletRequest$$EnhancerByMockitoWithCGLIB$$d677bdba cannot be cast to javax.servlet.http.HttpServletRequest + // + verifyException("org.openecomp.mso.logger.LogFilter", e); + } + } + + @Test(timeout = 4000) + public void test2() throws Throwable { + LogFilter logFilter0 = new LogFilter(); + FilterConfig filterConfig0 = mock(FilterConfig.class, new ViolatedAssumptionAnswer()); + logFilter0.init(filterConfig0); + ServletRequest servletRequest0 = mock(ServletRequest.class, new ViolatedAssumptionAnswer()); + ServletResponse servletResponse0 = mock(ServletResponse.class, new ViolatedAssumptionAnswer()); + FilterChain filterChain0 = mock(FilterChain.class, new ViolatedAssumptionAnswer()); + // Undeclared exception! + try { + logFilter0.doFilter(servletRequest0, servletResponse0, filterChain0); + fail("Expecting exception: ClassCastException"); + + } catch(ClassCastException e) { + // + // $javax.servlet.ServletRequest$$EnhancerByMockitoWithCGLIB$$d677bdba cannot be cast to javax.servlet.http.HttpServletRequest + // + verifyException("org.openecomp.mso.logger.LogFilter", e); + } + } + + @Test(timeout = 4000) + public void test3() throws Throwable { + LogFilter logFilter0 = new LogFilter(); + FilterConfig filterConfig0 = mock(FilterConfig.class, new ViolatedAssumptionAnswer()); + logFilter0.init(filterConfig0); + ServletRequest servletRequest0 = null; + ServletResponse servletResponse0 = mock(ServletResponse.class, new ViolatedAssumptionAnswer()); + ServletResponse servletResponse1 = mock(ServletResponse.class, new ViolatedAssumptionAnswer()); + FilterChain filterChain0 = mock(FilterChain.class, new ViolatedAssumptionAnswer()); + // Undeclared exception! + try { + logFilter0.doFilter((ServletRequest) null, servletResponse1, filterChain0); + fail("Expecting exception: ClassCastException"); + + } catch(ClassCastException e) { + // + // $javax.servlet.ServletResponse$$EnhancerByMockitoWithCGLIB$$b9bd7b44 cannot be cast to javax.servlet.http.HttpServletResponse + // + verifyException("org.openecomp.mso.logger.LogFilter", e); + } + } + + @Test(timeout = 4000) + public void test4() throws Throwable { + LogFilter logFilter0 = new LogFilter(); + logFilter0.destroy(); + HttpServletRequest httpServletRequest0 = mock(HttpServletRequest.class, new ViolatedAssumptionAnswer()); + HttpServletRequestWrapper httpServletRequestWrapper0 = new HttpServletRequestWrapper(httpServletRequest0); + ServletResponse servletResponse0 = null; + ServletResponseWrapper servletResponseWrapper0 = null; + try { + servletResponseWrapper0 = new ServletResponseWrapper((ServletResponse) null); + fail("Expecting exception: IllegalArgumentException"); + + } catch(IllegalArgumentException e) { + // + // Response cannot be null + // + verifyException("javax.servlet.ServletResponseWrapper", e); + } + } + + @Test(timeout = 4000) + public void test5() throws Throwable { + LogFilter logFilter0 = new LogFilter(); + HttpServletRequest httpServletRequest0 = mock(HttpServletRequest.class, new ViolatedAssumptionAnswer()); + doReturn((String) null, (String) null, (String) null, (String) null, (String) null).when(httpServletRequest0).getRemoteAddr(); + doReturn((AsyncContext) null).when(httpServletRequest0).startAsync(any(javax.servlet.ServletRequest.class) , any(javax.servlet.ServletResponse.class)); + doReturn((Principal) null, (Principal) null, (Principal) null, (Principal) null, (Principal) null).when(httpServletRequest0).getUserPrincipal(); + HttpServletRequestWrapper httpServletRequestWrapper0 = new HttpServletRequestWrapper(httpServletRequest0); + ServletRequest servletRequest0 = httpServletRequestWrapper0.getRequest(); + HttpServletResponse httpServletResponse0 = mock(HttpServletResponse.class, new ViolatedAssumptionAnswer()); + doReturn((String) null).when(httpServletResponse0).getCharacterEncoding(); + HttpServletResponseWrapper httpServletResponseWrapper0 = new HttpServletResponseWrapper(httpServletResponse0); + FilterChain filterChain0 = mock(FilterChain.class, new ViolatedAssumptionAnswer()); + logFilter0.doFilter(servletRequest0, httpServletResponseWrapper0, filterChain0); + logFilter0.destroy(); + LogFilter logFilter1 = new LogFilter(); + HttpServletResponseWrapper httpServletResponseWrapper1 = new HttpServletResponseWrapper((HttpServletResponse) httpServletResponseWrapper0); + FilterChain filterChain1 = mock(FilterChain.class, new ViolatedAssumptionAnswer()); + logFilter0.doFilter(servletRequest0, httpServletResponseWrapper0, filterChain1); + FilterChain filterChain2 = mock(FilterChain.class, new ViolatedAssumptionAnswer()); + logFilter1.doFilter(servletRequest0, httpServletResponseWrapper1, filterChain2); + HttpServletResponseWrapper httpServletResponseWrapper2 = (HttpServletResponseWrapper)httpServletResponseWrapper1.getResponse(); + httpServletResponseWrapper1.getCharacterEncoding(); + httpServletResponseWrapper1.flushBuffer(); + httpServletRequestWrapper0.startAsync(servletRequest0, (ServletResponse) httpServletResponseWrapper1); + FilterChain filterChain3 = mock(FilterChain.class, new ViolatedAssumptionAnswer()); + logFilter1.doFilter(servletRequest0, httpServletResponseWrapper2, filterChain3); + FilterChain filterChain4 = mock(FilterChain.class, new ViolatedAssumptionAnswer()); + FilterChain filterChain5 = mock(FilterChain.class, new ViolatedAssumptionAnswer()); + logFilter1.doFilter(httpServletRequestWrapper0, httpServletResponseWrapper1, filterChain5); + logFilter1.doFilter(servletRequest0, httpServletResponseWrapper0, filterChain4); + logFilter0.destroy(); + FilterConfig filterConfig0 = mock(FilterConfig.class, new ViolatedAssumptionAnswer()); + logFilter1.init(filterConfig0); + LogFilter logFilter2 = new LogFilter(); + FilterConfig filterConfig1 = mock(FilterConfig.class, new ViolatedAssumptionAnswer()); + logFilter1.init(filterConfig1); + logFilter0.destroy(); + assertFalse(logFilter0.equals((Object)logFilter1)); + } + + @Test(timeout = 4000) + public void test6() throws Throwable { + LogFilter logFilter0 = new LogFilter(); + Principal principal0 = mock(Principal.class, new ViolatedAssumptionAnswer()); + doReturn((String) null).when(principal0).getName(); + HttpServletRequest httpServletRequest0 = mock(HttpServletRequest.class, new ViolatedAssumptionAnswer()); + doReturn("$PJ-hW?").when(httpServletRequest0).getRemoteAddr(); + doReturn(principal0).when(httpServletRequest0).getUserPrincipal(); + HttpServletRequestWrapper httpServletRequestWrapper0 = new HttpServletRequestWrapper(httpServletRequest0); + ServletRequest servletRequest0 = httpServletRequestWrapper0.getRequest(); + HttpServletResponse httpServletResponse0 = mock(HttpServletResponse.class, new ViolatedAssumptionAnswer()); + HttpServletResponseWrapper httpServletResponseWrapper0 = new HttpServletResponseWrapper(httpServletResponse0); + ServletResponse servletResponse0 = httpServletResponseWrapper0.getResponse(); + FilterChain filterChain0 = mock(FilterChain.class, new ViolatedAssumptionAnswer()); + logFilter0.doFilter(servletRequest0, servletResponse0, filterChain0); + FilterConfig filterConfig0 = mock(FilterConfig.class, new ViolatedAssumptionAnswer()); + logFilter0.init(filterConfig0); + } +} diff --git a/common/src/test/java/org/openecomp/mso/logger/LogFilterESTestscaffolding.java b/common/src/test/java/org/openecomp/mso/logger/LogFilterESTestscaffolding.java new file mode 100644 index 0000000000..50487634d4 --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/logger/LogFilterESTestscaffolding.java @@ -0,0 +1,78 @@ +/** + * Scaffolding file used to store all the setups needed to run + * tests automatically generated by EvoSuite + * Mon Nov 14 09:08:24 GMT 2016 + */ + +package org.openecomp.mso.logger; + +import org.evosuite.runtime.annotation.EvoSuiteClassExclude; +import org.junit.BeforeClass; +import org.junit.Before; +import org.junit.After; +import org.junit.AfterClass; +import org.evosuite.runtime.sandbox.Sandbox; + +@EvoSuiteClassExclude +public class LogFilterESTestscaffolding { + + @org.junit.Rule + public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); + + private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); + + private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); + + @BeforeClass + public static void initEvoSuiteFramework() { + org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.mso.logger.LogFilter"; + org.evosuite.runtime.GuiSupport.initialize(); + org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; + org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; + org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; + org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; + org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); + org.evosuite.runtime.classhandling.JDKClassResetter.init(); + initializeClasses(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + } + + @AfterClass + public static void clearEvoSuiteFramework(){ + Sandbox.resetDefaultSecurityManager(); + java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); + } + + @Before + public void initTestCase(){ + threadStopper.storeCurrentThreads(); + threadStopper.startRecordingTime(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); + org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); + + org.evosuite.runtime.GuiSupport.setHeadless(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + org.evosuite.runtime.agent.InstrumentingAgent.activate(); + } + + @After + public void doneWithTestCase(){ + threadStopper.killAndJoinClientThreads(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); + org.evosuite.runtime.classhandling.JDKClassResetter.reset(); + resetClasses(); + org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); + org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); + org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); + } + + + private static void initializeClasses() { + org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(LogFilterESTestscaffolding.class.getClassLoader() , + "org.openecomp.mso.logger.LogFilter" + ); + } + + private static void resetClasses() { + } +} diff --git a/common/src/test/java/org/openecomp/mso/logger/MsoAlarmLoggerESTestscaffolding.java b/common/src/test/java/org/openecomp/mso/logger/MsoAlarmLoggerESTestscaffolding.java new file mode 100644 index 0000000000..320b7557b7 --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/logger/MsoAlarmLoggerESTestscaffolding.java @@ -0,0 +1,90 @@ +/** + * Scaffolding file used to store all the setups needed to run + * tests automatically generated by EvoSuite + * Mon Nov 14 09:05:53 GMT 2016 + */ + +package org.openecomp.mso.logger; + +import org.evosuite.runtime.annotation.EvoSuiteClassExclude; +import org.junit.BeforeClass; +import org.junit.Before; +import org.junit.After; +import org.junit.AfterClass; +import org.evosuite.runtime.sandbox.Sandbox; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +@EvoSuiteClassExclude +public class MsoAlarmLoggerESTestscaffolding { + + @org.junit.Rule + public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); + + protected static ExecutorService executor; + + private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); + + private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); + + @BeforeClass + public static void initEvoSuiteFramework() { + org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.mso.logger.MsoAlarmLogger"; + org.evosuite.runtime.GuiSupport.initialize(); + org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; + org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; + org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; + org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; + org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); + executor = Executors.newCachedThreadPool(); + org.evosuite.runtime.classhandling.JDKClassResetter.init(); + initializeClasses(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + } + + @AfterClass + public static void clearEvoSuiteFramework(){ + Sandbox.resetDefaultSecurityManager(); + executor.shutdownNow(); + java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); + } + + @Before + public void initTestCase(){ + threadStopper.storeCurrentThreads(); + threadStopper.startRecordingTime(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); + org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); + + org.evosuite.runtime.GuiSupport.setHeadless(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + org.evosuite.runtime.agent.InstrumentingAgent.activate(); + } + + @After + public void doneWithTestCase(){ + threadStopper.killAndJoinClientThreads(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); + org.evosuite.runtime.classhandling.JDKClassResetter.reset(); + resetClasses(); + org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); + org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); + org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); + } + + + private static void initializeClasses() { + org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(MsoAlarmLoggerESTestscaffolding.class.getClassLoader() , + "org.openecomp.mso.logger.MsoAlarmLogger" + ); + } + + private static void resetClasses() { + org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(MsoAlarmLoggerESTestscaffolding.class.getClassLoader()); + + org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( + "org.openecomp.mso.logger.MsoAlarmLogger" + ); + } +} diff --git a/common/src/test/java/org/openecomp/mso/logger/MsoLogInitializerESTest.java b/common/src/test/java/org/openecomp/mso/logger/MsoLogInitializerESTest.java new file mode 100644 index 0000000000..97058d5df3 --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/logger/MsoLogInitializerESTest.java @@ -0,0 +1,37 @@ +/* + * This file was automatically generated by EvoSuite + * Mon Nov 14 09:06:06 GMT 2016 + */ + +package org.openecomp.mso.logger; + +import org.junit.Test; +import static org.junit.Assert.*; +import static org.evosuite.shaded.org.mockito.Mockito.*; + +import javax.servlet.ServletContext; +import javax.servlet.ServletContextEvent; +import org.evosuite.runtime.EvoRunner; +import org.evosuite.runtime.EvoRunnerParameters; +import org.evosuite.runtime.PrivateAccess; +import org.evosuite.runtime.ViolatedAssumptionAnswer; +import org.junit.runner.RunWith; + +@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) +public class MsoLogInitializerESTest extends MsoLogInitializerESTestscaffolding { + + @Test(timeout = 4000) + public void test0() throws Throwable { + MsoLogInitializer msoLogInitializer0 = new MsoLogInitializer(); + ServletContextEvent servletContextEvent0 = mock(ServletContextEvent.class, new ViolatedAssumptionAnswer()); + doReturn((ServletContext) null).when(servletContextEvent0).getServletContext(); + msoLogInitializer0.contextInitialized(servletContextEvent0); + } + + @Test(timeout = 4000) + public void test1() throws Throwable { + MsoLogInitializer msoLogInitializer0 = new MsoLogInitializer(); + Boolean boolean0 = (Boolean)PrivateAccess.callMethod((Class<MsoLogInitializer>) MsoLogInitializer.class, msoLogInitializer0, "fileIsReadable", (Object) "", (Class<?>) String.class); + assertTrue(boolean0); + } +} diff --git a/common/src/test/java/org/openecomp/mso/logger/MsoLogInitializerESTestscaffolding.java b/common/src/test/java/org/openecomp/mso/logger/MsoLogInitializerESTestscaffolding.java new file mode 100644 index 0000000000..c0139549fb --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/logger/MsoLogInitializerESTestscaffolding.java @@ -0,0 +1,145 @@ +/** + * Scaffolding file used to store all the setups needed to run + * tests automatically generated by EvoSuite + * Mon Nov 14 09:06:06 GMT 2016 + */ + +package org.openecomp.mso.logger; + +import org.evosuite.runtime.annotation.EvoSuiteClassExclude; +import org.junit.BeforeClass; +import org.junit.Before; +import org.junit.After; +import org.junit.AfterClass; +import org.evosuite.runtime.sandbox.Sandbox; + +@EvoSuiteClassExclude +public class MsoLogInitializerESTestscaffolding { + + @org.junit.Rule + public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); + + private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); + + private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); + + @BeforeClass + public static void initEvoSuiteFramework() { + org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.mso.logger.MsoLogInitializer"; + org.evosuite.runtime.GuiSupport.initialize(); + org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; + org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; + org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; + org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; + org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); + org.evosuite.runtime.classhandling.JDKClassResetter.init(); + initializeClasses(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + } + + @AfterClass + public static void clearEvoSuiteFramework(){ + Sandbox.resetDefaultSecurityManager(); + java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); + } + + @Before + public void initTestCase(){ + threadStopper.storeCurrentThreads(); + threadStopper.startRecordingTime(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); + org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); + + org.evosuite.runtime.GuiSupport.setHeadless(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + org.evosuite.runtime.agent.InstrumentingAgent.activate(); + } + + @After + public void doneWithTestCase(){ + threadStopper.killAndJoinClientThreads(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); + org.evosuite.runtime.classhandling.JDKClassResetter.reset(); + resetClasses(); + org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); + org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); + org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); + } + + + private static void initializeClasses() { + org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(MsoLogInitializerESTestscaffolding.class.getClassLoader() , + "org.openecomp.mso.logger.MsoLogger", + "org.openecomp.mso.logger.MessageEnum", + "com.att.eelf.i18n.EELFResolvableErrorEnum", + "org.openecomp.mso.logger.MsoLogger$ResponseCode", + "org.openecomp.mso.entity.MsoRequest", + "org.openecomp.mso.logger.MsoLogger$StatusCode", + "com.att.eelf.i18n.EELFResourceManager$RESOURCE_TYPES", + "com.att.eelf.configuration.EELFManager", + "org.openecomp.mso.logger.MsoLogger$ErrorCode", + "com.att.eelf.configuration.EELFLogger", + "com.att.eelf.i18n.EELFMsgs", + "com.att.eelf.configuration.EELFLogger$Level", + "org.openecomp.mso.logger.MsoLogger$Catalog", + "com.att.eelf.configuration.SLF4jWrapper", + "org.openecomp.mso.logger.MsoLogInitializer", + "com.att.eelf.i18n.EELFResourceManager" + ); + } + + private static void resetClasses() { + org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(MsoLogInitializerESTestscaffolding.class.getClassLoader()); + + org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( + "com.att.eelf.i18n.EELFResourceManager", + "org.openecomp.mso.logger.MessageEnum", + "org.openecomp.mso.logger.MsoLogger$Catalog", + "org.openecomp.mso.logger.MsoLogInitializer", + "org.openecomp.mso.logger.MsoLogger$ErrorCode", + "org.openecomp.mso.logger.MsoLogger", + "com.att.eelf.i18n.EELFMsgs", + "com.att.eelf.i18n.EELFResourceManager$RESOURCE_TYPES", + "org.apache.xerces.jaxp.SAXParserFactoryImpl", + "org.apache.xerces.jaxp.SAXParserImpl", + "org.apache.xerces.parsers.XMLParser", + "org.apache.xerces.parsers.AbstractSAXParser", + "org.apache.xerces.parsers.SAXParser", + "org.apache.xerces.parsers.ObjectFactory", + "org.apache.xerces.util.ParserConfigurationSettings", + "org.apache.xerces.parsers.XML11Configuration", + "org.apache.xerces.parsers.XIncludeAwareParserConfiguration", + "org.apache.xerces.util.SymbolTable", + "org.apache.xerces.impl.XMLEntityManager", + "org.apache.xerces.util.AugmentationsImpl$SmallContainer", + "org.apache.xerces.impl.XMLEntityManager$ByteBufferPool", + "org.apache.xerces.impl.XMLEntityManager$CharacterBufferPool", + "org.apache.xerces.impl.XMLEntityScanner$1", + "org.apache.xerces.impl.XMLEntityScanner", + "org.apache.xerces.impl.XMLErrorReporter", + "org.apache.xerces.impl.XMLScanner", + "org.apache.xerces.impl.XMLDocumentFragmentScannerImpl", + "org.apache.xerces.impl.XMLDocumentScannerImpl", + "org.apache.xerces.util.XMLStringBuffer", + "org.apache.xerces.util.XMLAttributesImpl", + "org.apache.xerces.impl.XMLDTDScannerImpl", + "org.apache.xerces.impl.dtd.XMLDTDProcessor", + "org.apache.xerces.impl.dtd.XMLDTDValidator", + "org.apache.xerces.impl.validation.ValidationState", + "org.apache.xerces.impl.dtd.XMLElementDecl", + "org.apache.xerces.impl.dtd.XMLSimpleType", + "org.apache.xerces.impl.dv.DTDDVFactory", + "org.apache.xerces.impl.dv.ObjectFactory", + "org.apache.xerces.impl.dv.dtd.DTDDVFactoryImpl", + "org.apache.xerces.impl.XMLVersionDetector", + "org.apache.xerces.impl.msg.XMLMessageFormatter", + "org.apache.xerces.impl.io.UTF8Reader", + "org.apache.xerces.util.XMLSymbols", + "org.apache.xerces.xni.NamespaceContext", + "org.apache.xerces.util.XMLChar", + "org.apache.xerces.impl.Constants", + "com.att.eelf.configuration.EELFLogger$Level", + "com.att.eelf.configuration.EELFManager" + ); + } +} diff --git a/common/src/test/java/org/openecomp/mso/logger/MsoLoggingServletESTest.java b/common/src/test/java/org/openecomp/mso/logger/MsoLoggingServletESTest.java new file mode 100644 index 0000000000..2761f647bc --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/logger/MsoLoggingServletESTest.java @@ -0,0 +1,34 @@ +/* + * This file was automatically generated by EvoSuite + * Mon Nov 14 09:04:06 GMT 2016 + */ + +package org.openecomp.mso.logger; + +import org.junit.Test; +import static org.junit.Assert.*; +import static org.evosuite.runtime.EvoAssertions.*; + +import org.evosuite.runtime.EvoRunner; +import org.evosuite.runtime.EvoRunnerParameters; +import org.evosuite.runtime.PrivateAccess; +import org.junit.runner.RunWith; + +@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) +public class MsoLoggingServletESTest extends MsoLoggingServletESTestscaffolding { + + @Test(timeout = 4000) + public void test0() throws Throwable { + MsoLoggingServlet msoLoggingServlet0 = new MsoLoggingServlet(); + try { + PrivateAccess.callMethod((Class<MsoLoggingServlet>) MsoLoggingServlet.class, msoLoggingServlet0, "isMsoLogger", (Object) null, (Class<?>) String.class); + fail("Expecting exception: NullPointerException"); + + } catch(NullPointerException e) { + // + // no message in exception (getMessage() returned null) + // + verifyException("org.openecomp.mso.logger.MsoLoggingServlet", e); + } + } +} diff --git a/common/src/test/java/org/openecomp/mso/logger/MsoLoggingServletESTestscaffolding.java b/common/src/test/java/org/openecomp/mso/logger/MsoLoggingServletESTestscaffolding.java new file mode 100644 index 0000000000..be6c378ccc --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/logger/MsoLoggingServletESTestscaffolding.java @@ -0,0 +1,337 @@ +/** + * Scaffolding file used to store all the setups needed to run + * tests automatically generated by EvoSuite + * Mon Nov 14 09:04:06 GMT 2016 + */ + +package org.openecomp.mso.logger; + +import org.evosuite.runtime.annotation.EvoSuiteClassExclude; +import org.junit.BeforeClass; +import org.junit.Before; +import org.junit.After; +import org.junit.AfterClass; +import org.evosuite.runtime.sandbox.Sandbox; + +@EvoSuiteClassExclude +public class MsoLoggingServletESTestscaffolding { + + @org.junit.Rule + public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); + + private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); + + private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); + + @BeforeClass + public static void initEvoSuiteFramework() { + org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.mso.logger.MsoLoggingServlet"; + org.evosuite.runtime.GuiSupport.initialize(); + org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; + org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; + org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; + org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; + org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); + org.evosuite.runtime.classhandling.JDKClassResetter.init(); + initializeClasses(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + } + + @AfterClass + public static void clearEvoSuiteFramework(){ + Sandbox.resetDefaultSecurityManager(); + java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); + } + + @Before + public void initTestCase(){ + threadStopper.storeCurrentThreads(); + threadStopper.startRecordingTime(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); + org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); + + org.evosuite.runtime.GuiSupport.setHeadless(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + org.evosuite.runtime.agent.InstrumentingAgent.activate(); + } + + @After + public void doneWithTestCase(){ + threadStopper.killAndJoinClientThreads(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); + org.evosuite.runtime.classhandling.JDKClassResetter.reset(); + resetClasses(); + org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); + org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); + org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); + } + + + private static void initializeClasses() { + org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(MsoLoggingServletESTestscaffolding.class.getClassLoader() , + "org.jboss.resteasy.spi.StringConverter", + "org.apache.xerces.impl.XMLEntityManager$CharacterBufferPool", + "org.apache.xerces.xni.XMLResourceIdentifier", + "org.apache.xerces.impl.XMLEntityManager", + "org.apache.xerces.impl.dtd.XMLDTDDescription", + "com.att.eelf.i18n.EELFMsgs", + "org.jboss.resteasy.util.ThreadLocalStack", + "org.apache.xerces.impl.dv.InvalidDatatypeValueException", + "org.apache.xerces.jaxp.UnparsedEntityHandler", + "org.apache.xerces.parsers.AbstractXMLDocumentParser", + "org.apache.xerces.impl.XMLScanner", + "org.apache.xerces.impl.dv.dtd.NOTATIONDatatypeValidator", + "org.apache.xerces.xni.parser.XMLParseException", + "org.apache.xerces.impl.XMLEntityScanner", + "org.apache.xerces.util.URI$MalformedURIException", + "org.apache.xerces.impl.XMLNSDocumentScannerImpl", + "org.jboss.resteasy.core.interception.JaxrsInterceptorRegistry", + "org.apache.xerces.impl.dtd.models.CMAny", + "org.apache.xerces.util.URI", + "org.apache.xerces.xni.parser.XMLDocumentFilter", + "org.apache.xerces.xni.parser.XMLDTDSource", + "org.apache.xerces.impl.dtd.XMLAttributeDecl", + "org.apache.xerces.parsers.XMLParser", + "org.jboss.resteasy.spi.ResteasyProviderFactory", + "org.apache.xerces.util.SymbolTable", + "org.apache.xerces.impl.io.Latin1Reader", + "org.apache.xerces.impl.dv.ValidationContext", + "org.jboss.resteasy.spi.BadRequestException", + "org.apache.xerces.impl.dtd.XMLDTDValidator", + "org.apache.xerces.impl.dtd.XML11NSDTDValidator", + "org.openecomp.mso.logger.MsoLoggingServlet", + "org.apache.xerces.util.AugmentationsImpl", + "org.jboss.resteasy.core.interception.ReaderInterceptorRegistry", + "org.apache.xerces.impl.dv.ObjectFactory", + "org.jboss.resteasy.client.exception.mapper.ClientExceptionMapper", + "org.apache.xerces.impl.dv.DatatypeValidator", + "org.jboss.resteasy.spi.InjectorFactory", + "org.jboss.resteasy.core.interception.LegacyPrecedence", + "org.apache.xerces.jaxp.SAXParserImpl", + "org.apache.xerces.xni.grammars.XMLGrammarDescription", + "org.jboss.resteasy.plugins.delegates.NewCookieHeaderDelegate", + "org.apache.xerces.xni.parser.XMLErrorHandler", + "org.apache.xerces.util.MessageFormatter", + "org.apache.xerces.impl.XMLEntityManager$1", + "org.apache.xerces.xni.parser.XMLDTDScanner", + "org.openecomp.mso.logger.MsoLogger$ErrorCode", + "org.apache.xerces.xni.XMLAttributes", + "org.apache.xerces.impl.dv.dtd.StringDatatypeValidator", + "org.apache.xerces.impl.io.MalformedByteSequenceException", + "org.apache.xerces.impl.Constants$ArrayEnumeration", + "org.jboss.resteasy.core.interception.WriterInterceptorRegistry", + "org.apache.xerces.impl.dv.DTDDVFactory", + "org.apache.xerces.impl.dv.dtd.IDDatatypeValidator", + "org.apache.xerces.impl.validation.ValidationManager", + "org.apache.xerces.xni.XNIException", + "org.apache.xerces.impl.dtd.models.CMNode", + "org.apache.xerces.xni.parser.XMLDocumentSource", + "org.apache.xerces.xni.XMLDTDContentModelHandler", + "org.jboss.resteasy.spi.StringParameterUnmarshaller", + "org.jboss.resteasy.core.MediaTypeMap", + "org.openecomp.mso.logger.MsoLogger$Catalog", + "org.apache.xerces.util.AugmentationsImpl$SmallContainer", + "org.apache.xerces.impl.XMLErrorReporter", + "org.jboss.resteasy.specimpl.ResteasyUriBuilder", + "org.apache.xerces.impl.Constants", + "org.apache.xerces.util.XMLStringBuffer", + "org.apache.xerces.jaxp.JAXPConstants", + "org.apache.xerces.xni.parser.XMLParserConfiguration", + "org.apache.xerces.xni.XMLString", + "org.apache.xerces.impl.dv.DVFactoryException", + "org.apache.xerces.impl.dv.DatatypeException", + "org.apache.xerces.parsers.XML11Configurable", + "org.apache.xerces.parsers.XIncludeAwareParserConfiguration", + "org.jboss.resteasy.logging.Logger$LoggerType", + "org.apache.xerces.impl.xs.identity.FieldActivator", + "org.apache.xerces.impl.XMLEntityScanner$1", + "org.apache.xerces.jaxp.SAXParserFactoryImpl", + "org.jboss.resteasy.util.CaseInsensitiveMap$CaseInsensitiveComparator", + "org.apache.xerces.xs.ElementPSVI", + "org.apache.xerces.parsers.AbstractSAXParser", + "org.jboss.resteasy.spi.LoggableFailure", + "org.apache.xerces.xni.parser.XMLDTDFilter", + "org.apache.xerces.xni.parser.XMLDTDContentModelSource", + "org.openecomp.mso.entity.MsoRequest", + "org.apache.xerces.xni.XMLLocator", + "org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser", + "org.apache.xerces.xni.Augmentations", + "org.apache.xerces.impl.XMLEntityHandler", + "org.jboss.resteasy.util.CaseInsensitiveMap$1", + "org.jboss.resteasy.specimpl.BuiltResponse", + "org.jboss.resteasy.core.Headers", + "org.apache.xerces.xni.parser.XMLComponent", + "org.apache.xerces.impl.dv.dtd.ListDatatypeValidator", + "org.jboss.resteasy.spi.Failure", + "org.apache.xerces.impl.XMLEntityManager$ScannedEntity", + "org.apache.xerces.jaxp.JAXPValidatorComponent", + "org.apache.xerces.xni.parser.XMLDTDContentModelFilter", + "org.apache.xerces.xs.PSVIProvider", + "org.apache.xerces.impl.XMLEntityManager$ByteBufferPool", + "org.jboss.resteasy.specimpl.ResponseBuilderImpl", + "org.jboss.resteasy.core.interception.ClientResponseFilterRegistry", + "org.apache.xerces.impl.dtd.XMLEntityDecl", + "org.apache.xerces.xs.ItemPSVI", + "org.jboss.resteasy.specimpl.MultivaluedTreeMap", + "org.apache.xerces.impl.dv.dtd.ENTITYDatatypeValidator", + "org.apache.xerces.xni.parser.XMLEntityResolver", + "org.jboss.resteasy.client.core.ClientErrorInterceptor", + "org.apache.xerces.impl.dtd.XMLNSDTDValidator", + "org.apache.xerces.impl.XMLDTDScannerImpl", + "org.apache.xerces.impl.dv.dtd.NMTOKENDatatypeValidator", + "org.apache.xerces.parsers.ObjectFactory", + "org.jboss.resteasy.spi.ResteasyProviderFactory$SortedKey", + "org.apache.xerces.xni.parser.XMLConfigurationException", + "org.apache.xerces.impl.XML11NSDocumentScannerImpl", + "org.apache.xerces.parsers.SAXParser", + "com.att.eelf.i18n.EELFResolvableErrorEnum", + "org.apache.xerces.impl.XMLEntityManager$RewindableInputStream", + "org.jboss.resteasy.core.interception.ContainerRequestFilterRegistry", + "org.jboss.resteasy.specimpl.VariantListBuilderImpl", + "org.apache.xerces.xni.parser.XMLInputSource", + "org.apache.xerces.xni.parser.XMLComponentManager", + "com.att.eelf.configuration.EELFLogger$Level", + "org.jboss.resteasy.core.interception.JaxrsInterceptorRegistry$InterceptorFactory", + "org.apache.xerces.impl.io.UTF8Reader", + "org.apache.xerces.impl.dtd.XMLSimpleType", + "org.apache.xerces.impl.XML11DocumentScannerImpl", + "org.apache.xerces.util.AugmentationsImpl$AugmentationsItemsContainer", + "org.apache.xerces.util.XMLChar", + "org.apache.xerces.impl.XML11DTDScannerImpl", + "org.apache.xerces.impl.dtd.XMLElementDecl", + "com.att.eelf.i18n.EELFResourceManager$RESOURCE_TYPES", + "org.apache.xerces.xni.grammars.Grammar", + "org.apache.xerces.impl.dtd.models.ContentModelValidator", + "com.att.eelf.configuration.EELFLogger", + "org.apache.xerces.xni.grammars.XMLGrammarLoader", + "org.apache.xerces.xni.XMLDocumentHandler", + "org.apache.xerces.impl.io.UCSReader", + "org.apache.xerces.impl.XMLEntityManager$CharacterBuffer", + "org.apache.xerces.impl.validation.ValidationState", + "org.apache.xerces.impl.XMLEntityManager$Entity", + "org.jboss.resteasy.spi.HttpRequest", + "org.apache.xerces.util.XMLResourceIdentifierImpl", + "org.jboss.resteasy.logging.Logger", + "org.jboss.resteasy.spi.ConstructorInjector", + "org.apache.xerces.xni.NamespaceContext", + "org.apache.xerces.impl.dtd.XMLDTDLoader", + "org.jboss.resteasy.util.CaseInsensitiveMap", + "org.apache.xerces.util.XMLSymbols", + "org.apache.xerces.parsers.ObjectFactory$ConfigurationError", + "org.jboss.resteasy.core.interception.ContainerResponseFilterRegistry", + "org.apache.xerces.impl.io.ASCIIReader", + "org.jboss.resteasy.core.interception.InterceptorRegistry", + "org.apache.xerces.impl.dtd.XMLDTDProcessor", + "org.apache.xerces.impl.XMLDocumentFragmentScannerImpl", + "org.apache.xerces.impl.XML11EntityScanner", + "org.apache.xerces.impl.dtd.DTDGrammar", + "org.apache.xerces.impl.dv.dtd.IDREFDatatypeValidator", + "com.att.eelf.configuration.SLF4jWrapper", + "org.apache.xerces.impl.dv.dtd.DTDDVFactoryImpl", + "org.apache.xerces.impl.dtd.XMLContentSpec", + "org.openecomp.mso.logger.MsoLogger", + "org.apache.xerces.xs.AttributePSVI", + "org.apache.xerces.impl.dtd.DTDGrammarBucket", + "org.apache.xerces.impl.msg.XMLMessageFormatter", + "org.apache.xerces.xni.parser.XMLDocumentScanner", + "org.apache.xerces.impl.XMLVersionDetector", + "org.apache.xerces.impl.XMLDocumentScannerImpl", + "org.apache.xerces.xni.parser.XMLPullParserConfiguration", + "org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$Dispatcher", + "org.apache.xerces.impl.xs.XMLSchemaValidator", + "org.apache.xerces.xni.grammars.XMLDTDDescription", + "org.jboss.resteasy.logging.impl.Slf4jLogger", + "org.apache.xerces.xni.QName", + "org.apache.xerces.jaxp.TeeXMLDocumentFilterImpl", + "org.apache.xerces.util.XMLAttributesImpl", + "org.apache.xerces.impl.XMLEntityManager$InternalEntity", + "org.apache.xerces.impl.RevalidationHandler", + "org.jboss.resteasy.spi.HeaderValueProcessor", + "org.apache.xerces.util.AugmentationsImpl$LargeContainer", + "org.apache.xerces.impl.dtd.BalancedDTDGrammar", + "org.apache.xerces.xni.XMLDTDHandler", + "org.apache.xerces.impl.dtd.XML11DTDProcessor", + "org.apache.xerces.parsers.XML11Configuration", + "org.apache.xerces.impl.dtd.XMLDTDValidatorFilter", + "com.att.eelf.i18n.EELFResourceManager", + "org.jboss.resteasy.plugins.delegates.MediaTypeHeaderDelegate", + "org.jboss.resteasy.core.MediaTypeMap$Typed", + "org.openecomp.mso.logger.MessageEnum", + "org.openecomp.mso.logger.MsoLogger$ResponseCode", + "org.openecomp.mso.logger.MsoLogger$StatusCode", + "com.att.eelf.configuration.EELFManager", + "org.jboss.resteasy.spi.HttpResponse", + "org.apache.xerces.impl.validation.EntityState", + "org.apache.xerces.impl.XMLEntityManager$ExternalEntity", + "org.apache.xerces.util.ParserConfigurationSettings", + "org.apache.xerces.impl.dv.ObjectFactory$ConfigurationError", + "com.att.eelf.i18n.EELFResourceManager$1", + "org.apache.xerces.impl.dtd.XML11DTDValidator" + ); + } + + private static void resetClasses() { + org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(MsoLoggingServletESTestscaffolding.class.getClassLoader()); + + org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( + "com.att.eelf.i18n.EELFResourceManager", + "org.openecomp.mso.logger.MessageEnum", + "org.openecomp.mso.logger.MsoLogger$Catalog", + "org.openecomp.mso.logger.MsoLogger", + "com.att.eelf.i18n.EELFMsgs", + "com.att.eelf.i18n.EELFResourceManager$RESOURCE_TYPES", + "org.apache.xerces.jaxp.SAXParserFactoryImpl", + "org.apache.xerces.jaxp.SAXParserImpl", + "org.apache.xerces.parsers.XMLParser", + "org.apache.xerces.parsers.AbstractSAXParser", + "org.apache.xerces.parsers.SAXParser", + "org.apache.xerces.parsers.ObjectFactory", + "org.apache.xerces.util.ParserConfigurationSettings", + "org.apache.xerces.parsers.XML11Configuration", + "org.apache.xerces.parsers.XIncludeAwareParserConfiguration", + "org.apache.xerces.util.SymbolTable", + "org.apache.xerces.impl.XMLEntityManager", + "org.apache.xerces.util.AugmentationsImpl$SmallContainer", + "org.apache.xerces.impl.XMLEntityManager$ByteBufferPool", + "org.apache.xerces.impl.XMLEntityManager$CharacterBufferPool", + "org.apache.xerces.impl.XMLEntityScanner$1", + "org.apache.xerces.impl.XMLEntityScanner", + "org.apache.xerces.impl.XMLErrorReporter", + "org.apache.xerces.impl.XMLScanner", + "org.apache.xerces.impl.XMLDocumentFragmentScannerImpl", + "org.apache.xerces.impl.XMLDocumentScannerImpl", + "org.apache.xerces.util.XMLStringBuffer", + "org.apache.xerces.util.XMLAttributesImpl", + "org.apache.xerces.impl.XMLDTDScannerImpl", + "org.apache.xerces.impl.dtd.XMLDTDProcessor", + "org.apache.xerces.impl.dtd.XMLDTDValidator", + "org.apache.xerces.impl.validation.ValidationState", + "org.apache.xerces.impl.dtd.XMLElementDecl", + "org.apache.xerces.impl.dtd.XMLSimpleType", + "org.apache.xerces.impl.dv.DTDDVFactory", + "org.apache.xerces.impl.dv.ObjectFactory", + "org.apache.xerces.impl.dv.dtd.DTDDVFactoryImpl", + "org.apache.xerces.impl.XMLVersionDetector", + "org.apache.xerces.impl.msg.XMLMessageFormatter", + "org.apache.xerces.impl.io.UTF8Reader", + "org.apache.xerces.util.XMLSymbols", + "org.apache.xerces.xni.NamespaceContext", + "org.apache.xerces.util.XMLChar", + "org.apache.xerces.impl.Constants", + "com.att.eelf.configuration.EELFLogger$Level", + "com.att.eelf.configuration.EELFManager", + "org.jboss.resteasy.logging.Logger$LoggerType", + "org.jboss.resteasy.logging.Logger", + "org.jboss.resteasy.spi.ResteasyProviderFactory", + "org.jboss.resteasy.core.MediaTypeMap", + "org.jboss.resteasy.core.interception.LegacyPrecedence", + "org.jboss.resteasy.plugins.delegates.MediaTypeHeaderDelegate", + "org.jboss.resteasy.plugins.delegates.NewCookieHeaderDelegate", + "org.jboss.resteasy.specimpl.MultivaluedTreeMap", + "org.jboss.resteasy.util.CaseInsensitiveMap$CaseInsensitiveComparator", + "org.jboss.resteasy.util.CaseInsensitiveMap", + "org.jboss.resteasy.core.Headers", + "org.openecomp.mso.logger.MsoLoggingServlet" + ); + } +} diff --git a/common/src/test/java/org/openecomp/mso/properties/AbstractMsoPropertiesESTest.java b/common/src/test/java/org/openecomp/mso/properties/AbstractMsoPropertiesESTest.java new file mode 100644 index 0000000000..535d929807 --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/properties/AbstractMsoPropertiesESTest.java @@ -0,0 +1,151 @@ +/* + * This file was automatically generated by EvoSuite + * Mon Nov 14 09:09:20 GMT 2016 + */ + +package org.openecomp.mso.properties; + +import static org.evosuite.runtime.EvoAssertions.verifyException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.FileNotFoundException; + +import org.evosuite.runtime.EvoRunner; +import org.evosuite.runtime.EvoRunnerParameters; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) +public class AbstractMsoPropertiesESTest extends AbstractMsoPropertiesESTestscaffolding { + + @Test(timeout = 4000) + public void test00() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + String string0 = msoJavaProperties0.toString(); + assertEquals("Config file null(Timer:0mins):\n\n\n", string0); + } + + @Test(timeout = 4000) + public void test01() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + MsoJavaProperties msoJavaProperties1 = msoJavaProperties0.clone(); + msoJavaProperties1.propertiesFileName = "+"; + msoJavaProperties1.getPropertiesFileName(); + assertEquals(0, msoJavaProperties1.getAutomaticRefreshInMinutes()); + } + + @Test(timeout = 4000) + public void test02() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + MsoJavaProperties msoJavaProperties1 = msoJavaProperties0.clone(); + msoJavaProperties1.propertiesFileName = ""; + msoJavaProperties1.getPropertiesFileName(); + assertEquals(0, msoJavaProperties1.getAutomaticRefreshInMinutes()); + } + + @Test(timeout = 4000) + public void test03() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + msoJavaProperties0.automaticRefreshInMinutes = (-1447); + int int0 = msoJavaProperties0.getAutomaticRefreshInMinutes(); + assertEquals((-1447), int0); + } + + @Test(timeout = 4000) + public void test04() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + msoJavaProperties0.equals(msoJavaProperties0); + assertEquals(0, msoJavaProperties0.getAutomaticRefreshInMinutes()); + } + + @Test(timeout = 4000) + public void test05() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + msoJavaProperties0.equals("X<0P%qxWR fu\""); + assertEquals(0, msoJavaProperties0.getAutomaticRefreshInMinutes()); + } + + @Test(timeout = 4000) + public void test06() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + MsoJavaProperties msoJavaProperties1 = (MsoJavaProperties)msoJavaProperties0.clone(); + assertEquals(0, msoJavaProperties1.getAutomaticRefreshInMinutes()); + } + + @Test(timeout = 4000) + public void test07() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + msoJavaProperties0.automaticRefreshInMinutes = (-1447); + MsoJavaProperties msoJavaProperties1 = (MsoJavaProperties)msoJavaProperties0.clone(); + assertTrue(msoJavaProperties1.equals((Object)msoJavaProperties0)); + } + + /** + * TODO: fails when run using maven, but succeeds when run using eclipse + * @throws Throwable + */ + @Ignore + @Test(timeout = 4000) + public void test08() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + // Undeclared exception! + try { + msoJavaProperties0.reloadPropertiesFile(); + fail("Expecting exception: NullPointerException"); + + } catch(NullPointerException e) { + // + // no message in exception (getMessage() returned null) + // + verifyException("org.evosuite.runtime.mock.java.io.MockFileInputStream", e); + } + } + + @Test(timeout = 4000) + public void test09() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + msoJavaProperties0.propertiesFileName = "ASDC_ARTIFACT_ALREADY_DEPLOYED"; + try { + msoJavaProperties0.reloadPropertiesFile(); + fail("Expecting exception: FileNotFoundException"); + + } catch(FileNotFoundException e) { + // + // no message in exception (getMessage() returned null) + // + verifyException("org.evosuite.runtime.mock.java.io.MockFileInputStream", e); + } + } + + @Test(timeout = 4000) + public void test10() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + try { + msoJavaProperties0.loadPropertiesFile("Trying to reset value handler for type ["); + fail("Expecting exception: FileNotFoundException"); + + } catch(FileNotFoundException e) { + // + // no message in exception (getMessage() returned null) + // + verifyException("org.evosuite.runtime.mock.java.io.MockFileInputStream", e); + } + } + + @Test(timeout = 4000) + public void test11() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + msoJavaProperties0.getPropertiesFileName(); + assertEquals(0, msoJavaProperties0.getAutomaticRefreshInMinutes()); + } + + @Test(timeout = 4000) + public void test12() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + int int0 = msoJavaProperties0.getAutomaticRefreshInMinutes(); + assertEquals(0, int0); + } +} diff --git a/common/src/test/java/org/openecomp/mso/properties/AbstractMsoPropertiesESTestscaffolding.java b/common/src/test/java/org/openecomp/mso/properties/AbstractMsoPropertiesESTestscaffolding.java new file mode 100644 index 0000000000..4224f01dc0 --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/properties/AbstractMsoPropertiesESTestscaffolding.java @@ -0,0 +1,120 @@ +/** + * Scaffolding file used to store all the setups needed to run + * tests automatically generated by EvoSuite + * Mon Nov 14 09:09:20 GMT 2016 + */ + +package org.openecomp.mso.properties; + +import org.evosuite.runtime.annotation.EvoSuiteClassExclude; +import org.junit.BeforeClass; +import org.junit.Before; +import org.junit.After; +import org.junit.AfterClass; +import org.evosuite.runtime.sandbox.Sandbox; + +@EvoSuiteClassExclude +public class AbstractMsoPropertiesESTestscaffolding { + + @org.junit.Rule + public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); + + private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); + + private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); + + @BeforeClass + public static void initEvoSuiteFramework() { + org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.mso.properties.AbstractMsoProperties"; + org.evosuite.runtime.GuiSupport.initialize(); + org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; + org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; + org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; + org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; + org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); + org.evosuite.runtime.classhandling.JDKClassResetter.init(); + initializeClasses(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + } + + @AfterClass + public static void clearEvoSuiteFramework(){ + Sandbox.resetDefaultSecurityManager(); + java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); + } + + @Before + public void initTestCase(){ + threadStopper.storeCurrentThreads(); + threadStopper.startRecordingTime(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); + org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); + + org.evosuite.runtime.GuiSupport.setHeadless(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + org.evosuite.runtime.agent.InstrumentingAgent.activate(); + } + + @After + public void doneWithTestCase(){ + threadStopper.killAndJoinClientThreads(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); + org.evosuite.runtime.classhandling.JDKClassResetter.reset(); + resetClasses(); + org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); + org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); + org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); + } + + + private static void initializeClasses() { + org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(AbstractMsoPropertiesESTestscaffolding.class.getClassLoader() , + "org.openecomp.mso.properties.AbstractMsoProperties", + "org.openecomp.mso.logger.MsoLogger", + "org.openecomp.mso.logger.MessageEnum", + "com.att.eelf.i18n.EELFResolvableErrorEnum", + "org.openecomp.mso.logger.MsoLogger$ResponseCode", + "org.openecomp.mso.entity.MsoRequest", + "org.openecomp.mso.logger.MsoLogger$StatusCode", + "com.att.eelf.i18n.EELFResourceManager$RESOURCE_TYPES", + "com.att.eelf.configuration.EELFManager", + "org.openecomp.mso.logger.MsoLogger$ErrorCode", + "com.att.eelf.configuration.EELFLogger", + "com.att.eelf.i18n.EELFMsgs", + "com.att.eelf.configuration.EELFLogger$Level", + "org.openecomp.mso.properties.MsoJavaProperties", + "org.openecomp.mso.logger.MsoLogger$Catalog", + "com.att.eelf.configuration.SLF4jWrapper", + "com.att.eelf.i18n.EELFResourceManager" + ); + } + + private static void resetClasses() { + org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(AbstractMsoPropertiesESTestscaffolding.class.getClassLoader()); + + org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( + "org.openecomp.mso.logger.MsoLogger$Catalog", + "org.codehaus.jackson.map.introspect.AnnotatedClass", + "org.codehaus.jackson.map.introspect.BasicClassIntrospector", + "org.codehaus.jackson.annotate.JsonAutoDetect$Visibility", + "org.codehaus.jackson.annotate.JsonMethod", + "org.codehaus.jackson.map.introspect.VisibilityChecker$Std", + "org.codehaus.jackson.map.ObjectMapper", + "org.codehaus.jackson.JsonParser$Feature", + "org.codehaus.jackson.JsonGenerator$Feature", + "org.codehaus.jackson.JsonFactory", + "org.codehaus.jackson.sym.CharsToNameCanonicalizer", + "org.codehaus.jackson.sym.BytesToNameCanonicalizer", + "org.codehaus.jackson.map.type.TypeFactory", + "org.openecomp.mso.utils.CryptoUtils", + "org.openecomp.mso.logger.MsoLogger", + "com.att.eelf.i18n.EELFResourceManager", + "com.att.eelf.i18n.EELFMsgs", + "com.att.eelf.i18n.EELFResourceManager$RESOURCE_TYPES", + "com.att.eelf.configuration.EELFLogger$Level", + "com.att.eelf.configuration.EELFManager", + "org.openecomp.mso.logger.MessageEnum", + "org.openecomp.mso.properties.AbstractMsoProperties" + ); + } +} diff --git a/common/src/test/java/org/openecomp/mso/properties/MsoJavaPropertiesESTest.java b/common/src/test/java/org/openecomp/mso/properties/MsoJavaPropertiesESTest.java new file mode 100644 index 0000000000..d64f63fb2c --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/properties/MsoJavaPropertiesESTest.java @@ -0,0 +1,358 @@ +/* + * This file was automatically generated by EvoSuite + * Thu Nov 10 08:35:35 GMT 2016 + */ + +package org.openecomp.mso.properties; + +import static org.evosuite.runtime.EvoAssertions.verifyException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.FileNotFoundException; + +import org.evosuite.runtime.EvoRunner; +import org.evosuite.runtime.EvoRunnerParameters; +import org.evosuite.runtime.PrivateAccess; +import org.evosuite.runtime.testdata.FileSystemHandling; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.openecomp.mso.logger.MsoLogger; + +@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) +public class MsoJavaPropertiesESTest extends MsoJavaPropertiesESTestscaffolding { + + @Test(timeout = 4000) + public void test00() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + msoJavaProperties0.setProperty("", "J6"); + msoJavaProperties0.hashCode(); + } + + @Test(timeout = 4000) + public void test02() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + String string0 = msoJavaProperties0.getProperty("IK#uRP]", (String) null); + assertNull(string0); + } + + @Test(timeout = 4000) + public void test03() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + String string0 = msoJavaProperties0.getProperty("", ""); + assertNotNull(string0); + assertEquals("", string0); + } + + @Test(timeout = 4000) + public void test04() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + int int0 = msoJavaProperties0.getIntProperty("RA_VNF_NOT_EXIST", (-1417)); + assertEquals((-1417), int0); + } + + @Test(timeout = 4000) + public void test05() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + String string0 = msoJavaProperties0.getEncryptedProperty("", "", ""); + assertEquals("", string0); + assertNotNull(string0); + } + + @Test(timeout = 4000) + public void test06() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + msoJavaProperties0.automaticRefreshInMinutes = 1821; + MsoJavaProperties msoJavaProperties1 = msoJavaProperties0.clone(); + assertNotSame(msoJavaProperties1, msoJavaProperties0); + assertEquals(1821, msoJavaProperties1.getAutomaticRefreshInMinutes()); + } + + @Test(timeout = 4000) + public void test07() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + msoJavaProperties0.automaticRefreshInMinutes = (-78); + MsoJavaProperties msoJavaProperties1 = msoJavaProperties0.clone(); + assertNotSame(msoJavaProperties1, msoJavaProperties0); + assertEquals(-78, msoJavaProperties1.getAutomaticRefreshInMinutes()); + } + + @Test(timeout = 4000) + public void test08() throws Throwable { + FileSystemHandling fileSystemHandling0 = new FileSystemHandling(); + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + PrivateAccess.setVariable((Class<MsoJavaProperties>) MsoJavaProperties.class, msoJavaProperties0, "msoProperties", (Object) null); + msoJavaProperties0.hashCode(); + msoJavaProperties0.hashCode(); + // Undeclared exception! + try { + msoJavaProperties0.size(); + fail("Expecting exception: NullPointerException"); + + } catch(NullPointerException e) { + // + // no message in exception (getMessage() returned null) + // + verifyException("org.openecomp.mso.properties.MsoJavaProperties", e); + } + } + + @Test(timeout = 4000) + public void test09() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + // Undeclared exception! + try { + msoJavaProperties0.setProperty((String) null, "+UaYo-~&{QxdaN(c"); + fail("Expecting exception: NullPointerException"); + + } catch(NullPointerException e) { + // + // no message in exception (getMessage() returned null) + // + } + } + + @Test(timeout = 4000) + public void test11() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + MsoJavaProperties msoJavaProperties1 = msoJavaProperties0.clone(); + msoJavaProperties1.propertiesFileName = ""; + try { + msoJavaProperties1.reloadPropertiesFile(); + fail("Expecting exception: FileNotFoundException"); + + } catch(FileNotFoundException e) { + // + // no message in exception (getMessage() returned null) + // + verifyException("org.evosuite.runtime.mock.java.io.MockFileInputStream", e); + } + } + + /** + * TODO: fails when run using maven, but succeeds when run using eclipse + */ + @Ignore + @Test(timeout = 4000) + public void test12() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + // Undeclared exception! + try { + msoJavaProperties0.loadPropertiesFile((String) null); + fail("Expecting exception: NullPointerException"); + + } catch(NullPointerException e) { + // + // no message in exception (getMessage() returned null) + // + verifyException("org.evosuite.runtime.mock.java.io.MockFileInputStream", e); + } + } + + @Test(timeout = 4000) + public void test13() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + try { + msoJavaProperties0.loadPropertiesFile(""); + fail("Expecting exception: FileNotFoundException"); + + } catch(FileNotFoundException e) { + // + // no message in exception (getMessage() returned null) + // + verifyException("org.evosuite.runtime.mock.java.io.MockFileInputStream", e); + } + } + + @Test(timeout = 4000) + public void test14() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + // Undeclared exception! + try { + msoJavaProperties0.getIntProperty((String) null, 0); + fail("Expecting exception: NullPointerException"); + + } catch(NullPointerException e) { + // + // no message in exception (getMessage() returned null) + // + } + } + + @Test(timeout = 4000) + public void test15() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + msoJavaProperties0.setProperty("APIH_READ_VNFOUTPUT_CLOB_EXCEPTION", ""); + // Undeclared exception! + try { + msoJavaProperties0.getEncryptedProperty("APIH_READ_VNFOUTPUT_CLOB_EXCEPTION", "", "k$&Fq}"); + fail("Expecting exception: NumberFormatException"); + + } catch(NumberFormatException e) { + // + // For input string: \"k$\" + // + verifyException("java.lang.NumberFormatException", e); + } + } + + @Test(timeout = 4000) + public void test16() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + MsoJavaProperties msoJavaProperties1 = msoJavaProperties0.clone(); + msoJavaProperties1.clone(); + msoJavaProperties0.hashCode(); + MsoJavaProperties msoJavaProperties2 = msoJavaProperties1.clone(); + PrivateAccess.setVariable((Class<MsoJavaProperties>) MsoJavaProperties.class, msoJavaProperties0, "msoProperties", (Object) null); + msoJavaProperties1.equals(msoJavaProperties2); + MsoLogger msoLogger0 = AbstractMsoProperties.LOGGER; + // Undeclared exception! + try { + msoJavaProperties0.clone(); + fail("Expecting exception: NullPointerException"); + + } catch(NullPointerException e) { + // + // no message in exception (getMessage() returned null) + // + verifyException("java.util.Hashtable", e); + } + } + + @Test(timeout = 4000) + public void test18() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + int int0 = msoJavaProperties0.getIntProperty("", 0); + assertEquals(0, int0); + } + + @Test(timeout = 4000) + public void test19() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + msoJavaProperties0.setProperty("-6;qct1", ""); + String string0 = msoJavaProperties0.toString(); + assertEquals("Config file null(Timer:0mins):\n-6;qct1=\n\n\n", string0); + } + + @Test(timeout = 4000) + public void test20() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + boolean boolean0 = msoJavaProperties0.equals("APIH_READ_VNFOUTPUT_CLOB_EXCEPTION"); + assertFalse(boolean0); + } + + @Test(timeout = 4000) + public void test21() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + boolean boolean0 = msoJavaProperties0.equals((Object) null); + assertFalse(boolean0); + } + + @Test(timeout = 4000) + public void test22() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + boolean boolean0 = msoJavaProperties0.equals(msoJavaProperties0); + assertTrue(boolean0); + } + + @Test(timeout = 4000) + public void test24() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + msoJavaProperties0.setProperty("APIH_READ_VNFOUTPUT_CLOB_EXCEPTION", ""); + // Undeclared exception! + try { + msoJavaProperties0.getEncryptedProperty("APIH_READ_VNFOUTPUT_CLOB_EXCEPTION", ".", ""); + fail("Expecting exception: IllegalArgumentException"); + + } catch(IllegalArgumentException e) { + // + // Empty key + // + verifyException("javax.crypto.spec.SecretKeySpec", e); + } + } + + @Test(timeout = 4000) + public void test25() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + String string0 = msoJavaProperties0.getEncryptedProperty("YhmJSc|~L0$,?/oh", (String) null, "YhmJSc|~L0$,?/oh"); + assertNull(string0); + } + + @Test(timeout = 4000) + public void test26() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + msoJavaProperties0.setProperty("M;WrYY%E,;sa&4F", "M;WrYY%E,;sa&4F"); + boolean boolean0 = msoJavaProperties0.getBooleanProperty("M;WrYY%E,;sa&4F", false); + assertFalse(boolean0); + } + + @Test(timeout = 4000) + public void test27() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + boolean boolean0 = msoJavaProperties0.getBooleanProperty("", true); + assertTrue(boolean0); + } + + @Test(timeout = 4000) + public void test28() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + msoJavaProperties0.setProperty("M;WrYY%E,;sa&4F", "M;WrYY%E,;sa&4F"); + int int0 = msoJavaProperties0.getIntProperty("M;WrYY%E,;sa&4F", 0); + assertEquals(0, int0); + } + + @Test(timeout = 4000) + public void test29() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + msoJavaProperties0.setProperty("", "J6"); + String string0 = msoJavaProperties0.getProperty("", "mso.properties.reload.time.minutes"); + assertNotNull(string0); + assertEquals("J6", string0); + } + /** + * TODO: fails when run using maven, but succeeds when run using eclipse + */ + @Ignore + @Test(timeout = 4000) + public void test30() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + // Undeclared exception! + try { + msoJavaProperties0.reloadPropertiesFile(); + fail("Expecting exception: NullPointerException"); + + } catch(NullPointerException e) { + // + // no message in exception (getMessage() returned null) + // + verifyException("org.evosuite.runtime.mock.java.io.MockFileInputStream", e); + } + } + + @Test(timeout = 4000) + public void test31() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + MsoJavaProperties msoJavaProperties1 = msoJavaProperties0.clone(); + assertTrue(msoJavaProperties1.equals((Object)msoJavaProperties0)); + + msoJavaProperties0.setProperty("", ""); + boolean boolean0 = msoJavaProperties0.equals(msoJavaProperties1); + assertFalse(boolean0); + assertFalse(msoJavaProperties1.equals((Object)msoJavaProperties0)); + } + + @Test(timeout = 4000) + public void test32() throws Throwable { + MsoJavaProperties msoJavaProperties0 = new MsoJavaProperties(); + int int0 = msoJavaProperties0.size(); + assertEquals(0, int0); + } +} diff --git a/common/src/test/java/org/openecomp/mso/properties/MsoJavaPropertiesESTestscaffolding.java b/common/src/test/java/org/openecomp/mso/properties/MsoJavaPropertiesESTestscaffolding.java new file mode 100644 index 0000000000..da13dc1d3d --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/properties/MsoJavaPropertiesESTestscaffolding.java @@ -0,0 +1,110 @@ +/** + * Scaffolding file used to store all the setups needed to run + * tests automatically generated by EvoSuite + * Mon Nov 14 07:59:01 GMT 2016 + */ + +package org.openecomp.mso.properties; + +import org.evosuite.runtime.annotation.EvoSuiteClassExclude; +import org.junit.BeforeClass; +import org.junit.Before; +import org.junit.After; +import org.junit.AfterClass; +import org.evosuite.runtime.sandbox.Sandbox; + +@EvoSuiteClassExclude +public class MsoJavaPropertiesESTestscaffolding { + + @org.junit.Rule + public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); + + private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); + + private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); + + @BeforeClass + public static void initEvoSuiteFramework() { + org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.mso.properties.MsoJavaProperties"; + org.evosuite.runtime.GuiSupport.initialize(); + org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; + org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; + org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; + org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; + org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); + org.evosuite.runtime.classhandling.JDKClassResetter.init(); + initializeClasses(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + } + + @AfterClass + public static void clearEvoSuiteFramework(){ + Sandbox.resetDefaultSecurityManager(); + java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); + } + + @Before + public void initTestCase(){ + threadStopper.storeCurrentThreads(); + threadStopper.startRecordingTime(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); + org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); + + org.evosuite.runtime.GuiSupport.setHeadless(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + org.evosuite.runtime.agent.InstrumentingAgent.activate(); + } + + @After + public void doneWithTestCase(){ + threadStopper.killAndJoinClientThreads(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); + org.evosuite.runtime.classhandling.JDKClassResetter.reset(); + resetClasses(); + org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); + org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); + org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); + } + + + private static void initializeClasses() { + org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(MsoJavaPropertiesESTestscaffolding.class.getClassLoader() , + "org.openecomp.mso.properties.AbstractMsoProperties", + "org.openecomp.mso.logger.MsoLogger", + "org.openecomp.mso.logger.MessageEnum", + "com.att.eelf.i18n.EELFResolvableErrorEnum", + "org.openecomp.mso.logger.MsoLogger$ResponseCode", + "org.openecomp.mso.utils.CryptoUtils", + "org.openecomp.mso.entity.MsoRequest", + "org.openecomp.mso.logger.MsoLogger$StatusCode", + "com.att.eelf.i18n.EELFResourceManager$RESOURCE_TYPES", + "com.att.eelf.configuration.EELFManager", + "org.openecomp.mso.logger.MsoLogger$ErrorCode", + "com.att.eelf.configuration.EELFLogger", + "com.att.eelf.i18n.EELFMsgs", + "com.att.eelf.configuration.EELFLogger$Level", + "org.openecomp.mso.properties.MsoJavaProperties", + "org.openecomp.mso.logger.MsoLogger$Catalog", + "com.att.eelf.configuration.SLF4jWrapper", + "com.att.eelf.i18n.EELFResourceManager$1", + "com.att.eelf.i18n.EELFResourceManager" + ); + } + + private static void resetClasses() { + org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(MsoJavaPropertiesESTestscaffolding.class.getClassLoader()); + + org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( + "org.openecomp.mso.logger.MsoLogger$Catalog", + "org.openecomp.mso.logger.MsoLogger", + "com.att.eelf.i18n.EELFResourceManager", + "com.att.eelf.i18n.EELFMsgs", + "com.att.eelf.i18n.EELFResourceManager$RESOURCE_TYPES", + "com.att.eelf.configuration.EELFLogger$Level", + "com.att.eelf.configuration.EELFManager", + "org.openecomp.mso.logger.MessageEnum", + "org.openecomp.mso.properties.AbstractMsoProperties", + "org.openecomp.mso.utils.CryptoUtils" + ); + } +} diff --git a/common/src/test/java/org/openecomp/mso/properties/MsoJsonPropertiesESTest.java b/common/src/test/java/org/openecomp/mso/properties/MsoJsonPropertiesESTest.java new file mode 100644 index 0000000000..0243c13c7f --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/properties/MsoJsonPropertiesESTest.java @@ -0,0 +1,35 @@ +/* + * This file was automatically generated by EvoSuite + * Mon Nov 14 09:04:39 GMT 2016 + */ + +package org.openecomp.mso.properties; + +import static org.evosuite.runtime.EvoAssertions.verifyException; +import static org.junit.Assert.fail; + +import org.evosuite.runtime.EvoRunner; +import org.evosuite.runtime.EvoRunnerParameters; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) +public class MsoJsonPropertiesESTest { + + @Ignore + @Test(timeout = 4000) + public void test0() throws Throwable { + MsoJsonProperties msoJsonProperties0 = null; + try { + msoJsonProperties0 = new MsoJsonProperties(); + fail("Expecting exception: VerifyError"); + + } catch(VerifyError e) { + // + // (class: org/codehaus/jackson/map/MapperConfig, method: <clinit> signature: ()V) Bad type in putfield/putstatic + // + verifyException("org.codehaus.jackson.map.ObjectMapper", e); + } + } +} diff --git a/common/src/test/java/org/openecomp/mso/properties/MsoPropertiesExceptionESTest.java b/common/src/test/java/org/openecomp/mso/properties/MsoPropertiesExceptionESTest.java new file mode 100644 index 0000000000..c53dd85fb0 --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/properties/MsoPropertiesExceptionESTest.java @@ -0,0 +1,24 @@ +/* + * This file was automatically generated by EvoSuite + * Mon Nov 14 09:10:06 GMT 2016 + */ + +package org.openecomp.mso.properties; + +import org.junit.Test; +import static org.junit.Assert.*; + +import org.evosuite.runtime.EvoRunner; +import org.evosuite.runtime.EvoRunnerParameters; +import org.junit.runner.RunWith; + +@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) +public class MsoPropertiesExceptionESTest extends MsoPropertiesExceptionESTestscaffolding { + + @Test(timeout = 4000) + public void test0() throws Throwable { + MsoPropertiesException msoPropertiesException0 = new MsoPropertiesException(""); + MsoPropertiesException msoPropertiesException1 = new MsoPropertiesException("l6G(", (Throwable) msoPropertiesException0); + assertFalse(msoPropertiesException1.equals((Object)msoPropertiesException0)); + } +} diff --git a/common/src/test/java/org/openecomp/mso/properties/MsoPropertiesExceptionESTestscaffolding.java b/common/src/test/java/org/openecomp/mso/properties/MsoPropertiesExceptionESTestscaffolding.java new file mode 100644 index 0000000000..379956310b --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/properties/MsoPropertiesExceptionESTestscaffolding.java @@ -0,0 +1,83 @@ +/** + * Scaffolding file used to store all the setups needed to run + * tests automatically generated by EvoSuite + * Mon Nov 14 09:10:06 GMT 2016 + */ + +package org.openecomp.mso.properties; + +import org.evosuite.runtime.annotation.EvoSuiteClassExclude; +import org.junit.BeforeClass; +import org.junit.Before; +import org.junit.After; +import org.junit.AfterClass; +import org.evosuite.runtime.sandbox.Sandbox; + +@EvoSuiteClassExclude +public class MsoPropertiesExceptionESTestscaffolding { + + @org.junit.Rule + public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); + + private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); + + private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); + + @BeforeClass + public static void initEvoSuiteFramework() { + org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.mso.properties.MsoPropertiesException"; + org.evosuite.runtime.GuiSupport.initialize(); + org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; + org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; + org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; + org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; + org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); + org.evosuite.runtime.classhandling.JDKClassResetter.init(); + initializeClasses(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + } + + @AfterClass + public static void clearEvoSuiteFramework(){ + Sandbox.resetDefaultSecurityManager(); + java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); + } + + @Before + public void initTestCase(){ + threadStopper.storeCurrentThreads(); + threadStopper.startRecordingTime(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); + org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); + + org.evosuite.runtime.GuiSupport.setHeadless(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + org.evosuite.runtime.agent.InstrumentingAgent.activate(); + } + + @After + public void doneWithTestCase(){ + threadStopper.killAndJoinClientThreads(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); + org.evosuite.runtime.classhandling.JDKClassResetter.reset(); + resetClasses(); + org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); + org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); + org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); + } + + + private static void initializeClasses() { + org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(MsoPropertiesExceptionESTestscaffolding.class.getClassLoader() , + "org.openecomp.mso.properties.MsoPropertiesException" + ); + } + + private static void resetClasses() { + org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(MsoPropertiesExceptionESTestscaffolding.class.getClassLoader()); + + org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( + "org.openecomp.mso.properties.MsoPropertiesException" + ); + } +} diff --git a/common/src/test/java/org/openecomp/mso/properties/MsoPropertiesFactoryESTest.java b/common/src/test/java/org/openecomp/mso/properties/MsoPropertiesFactoryESTest.java new file mode 100644 index 0000000000..7ab574569c --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/properties/MsoPropertiesFactoryESTest.java @@ -0,0 +1,71 @@ +/* + * This file was automatically generated by EvoSuite + * Mon Nov 14 09:02:51 GMT 2016 + */ + +package org.openecomp.mso.properties; + +import org.junit.Test; +import static org.junit.Assert.*; +import static org.evosuite.runtime.EvoAssertions.*; + +import org.evosuite.runtime.EvoRunner; +import org.evosuite.runtime.EvoRunnerParameters; +import org.evosuite.runtime.PrivateAccess; +import org.junit.runner.RunWith; + +@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) +public class MsoPropertiesFactoryESTest { + + @Test(timeout = 4000) + public void test0() throws Throwable { + MsoPropertiesFactory msoPropertiesFactory0 = new MsoPropertiesFactory(); + // Undeclared exception! + try { + msoPropertiesFactory0.changeMsoPropertiesFilePath((String) null, "Unable to load the MSO properties file because format is not recognized (only .json or .properties): "); + fail("Expecting exception: NullPointerException"); + + } catch(NullPointerException e) { + // + // no message in exception (getMessage() returned null) + // + } + } + + @Test(timeout = 4000) + public void test1() throws Throwable { + MsoPropertiesFactory msoPropertiesFactory0 = new MsoPropertiesFactory(); + msoPropertiesFactory0.removeAllMsoProperties(); + } + + @Test(timeout = 4000) + public void test2() throws Throwable { + MsoPropertiesFactory msoPropertiesFactory0 = new MsoPropertiesFactory(); + try { + msoPropertiesFactory0.getMsoJavaProperties("iz/`I"); + fail("Expecting exception: Exception"); + + } catch(Exception e) { + // + // Mso properties not found in cache:iz/`I + // + verifyException("org.openecomp.mso.properties.MsoPropertiesFactory", e); + } + } + + @Test(timeout = 4000) + public void test3() throws Throwable { + MsoPropertiesFactory msoPropertiesFactory0 = new MsoPropertiesFactory(); + MsoPropertiesParameters msoPropertiesParameters0 = new MsoPropertiesParameters(); + try { + PrivateAccess.callMethod((Class<MsoPropertiesFactory>) MsoPropertiesFactory.class, msoPropertiesFactory0, "createObjectType", (Object) msoPropertiesParameters0, (Class<?>) MsoPropertiesParameters.class, (Object) ":8nnlF[sGvCub6J", (Class<?>) String.class); + fail("Expecting exception: Exception"); + + } catch(Exception e) { + // + // Unable to load the MSO properties file because format is not recognized (only .json or .properties): :8nnlF[sGvCub6J + // + verifyException("org.openecomp.mso.properties.MsoPropertiesFactory", e); + } + } +} diff --git a/common/src/test/java/org/openecomp/mso/properties/MsoPropertiesParametersESTest.java b/common/src/test/java/org/openecomp/mso/properties/MsoPropertiesParametersESTest.java new file mode 100644 index 0000000000..9579b3b367 --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/properties/MsoPropertiesParametersESTest.java @@ -0,0 +1,20 @@ +/* + * This file was automatically generated by EvoSuite + * Mon Nov 14 09:09:37 GMT 2016 + */ + +package org.openecomp.mso.properties; + +import org.junit.Test; +import org.evosuite.runtime.EvoRunner; +import org.evosuite.runtime.EvoRunnerParameters; +import org.junit.runner.RunWith; + +@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) +public class MsoPropertiesParametersESTest extends MsoPropertiesParametersESTestscaffolding { + + @Test(timeout = 4000) + public void test0() throws Throwable { + MsoPropertiesParameters msoPropertiesParameters0 = new MsoPropertiesParameters(); + } +} diff --git a/common/src/test/java/org/openecomp/mso/properties/MsoPropertiesParametersESTestscaffolding.java b/common/src/test/java/org/openecomp/mso/properties/MsoPropertiesParametersESTestscaffolding.java new file mode 100644 index 0000000000..fec0b9ecf1 --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/properties/MsoPropertiesParametersESTestscaffolding.java @@ -0,0 +1,129 @@ +/** + * Scaffolding file used to store all the setups needed to run + * tests automatically generated by EvoSuite + * Mon Nov 14 09:09:37 GMT 2016 + */ + +package org.openecomp.mso.properties; + +import org.evosuite.runtime.annotation.EvoSuiteClassExclude; +import org.junit.BeforeClass; +import org.junit.Before; +import org.junit.After; +import org.junit.AfterClass; +import org.evosuite.runtime.sandbox.Sandbox; + +@EvoSuiteClassExclude +public class MsoPropertiesParametersESTestscaffolding { + + @org.junit.Rule + public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); + + private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); + + private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); + + @BeforeClass + public static void initEvoSuiteFramework() { + org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.mso.properties.MsoPropertiesParameters"; + org.evosuite.runtime.GuiSupport.initialize(); + org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; + org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; + org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; + org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; + org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); + org.evosuite.runtime.classhandling.JDKClassResetter.init(); + initializeClasses(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + } + + @AfterClass + public static void clearEvoSuiteFramework(){ + Sandbox.resetDefaultSecurityManager(); + java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); + } + + @Before + public void initTestCase(){ + threadStopper.storeCurrentThreads(); + threadStopper.startRecordingTime(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); + org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); + + org.evosuite.runtime.GuiSupport.setHeadless(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + org.evosuite.runtime.agent.InstrumentingAgent.activate(); + } + + @After + public void doneWithTestCase(){ + threadStopper.killAndJoinClientThreads(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); + org.evosuite.runtime.classhandling.JDKClassResetter.reset(); + resetClasses(); + org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); + org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); + org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); + } + + + private static void initializeClasses() { + org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(MsoPropertiesParametersESTestscaffolding.class.getClassLoader() , + "org.openecomp.mso.properties.MsoPropertiesParameters" + ); + } + + private static void resetClasses() { + org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(MsoPropertiesParametersESTestscaffolding.class.getClassLoader()); + + org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( + "org.openecomp.mso.logger.MsoLogger$Catalog", + "org.openecomp.mso.logger.MsoLogger", + "com.att.eelf.i18n.EELFResourceManager", + "com.att.eelf.i18n.EELFMsgs", + "com.att.eelf.i18n.EELFResourceManager$RESOURCE_TYPES", + "org.apache.xerces.jaxp.SAXParserFactoryImpl", + "org.apache.xerces.jaxp.SAXParserImpl", + "org.apache.xerces.parsers.XMLParser", + "org.apache.xerces.parsers.AbstractSAXParser", + "org.apache.xerces.parsers.SAXParser", + "org.apache.xerces.parsers.ObjectFactory", + "org.apache.xerces.util.ParserConfigurationSettings", + "org.apache.xerces.parsers.XML11Configuration", + "org.apache.xerces.parsers.XIncludeAwareParserConfiguration", + "org.apache.xerces.util.SymbolTable", + "org.apache.xerces.impl.XMLEntityManager", + "org.apache.xerces.util.AugmentationsImpl$SmallContainer", + "org.apache.xerces.impl.XMLEntityManager$ByteBufferPool", + "org.apache.xerces.impl.XMLEntityManager$CharacterBufferPool", + "org.apache.xerces.impl.XMLEntityScanner$1", + "org.apache.xerces.impl.XMLEntityScanner", + "org.apache.xerces.impl.XMLErrorReporter", + "org.apache.xerces.impl.XMLScanner", + "org.apache.xerces.impl.XMLDocumentFragmentScannerImpl", + "org.apache.xerces.impl.XMLDocumentScannerImpl", + "org.apache.xerces.util.XMLStringBuffer", + "org.apache.xerces.util.XMLAttributesImpl", + "org.apache.xerces.impl.XMLDTDScannerImpl", + "org.apache.xerces.impl.dtd.XMLDTDProcessor", + "org.apache.xerces.impl.dtd.XMLDTDValidator", + "org.apache.xerces.impl.validation.ValidationState", + "org.apache.xerces.impl.dtd.XMLElementDecl", + "org.apache.xerces.impl.dtd.XMLSimpleType", + "org.apache.xerces.impl.dv.DTDDVFactory", + "org.apache.xerces.impl.dv.ObjectFactory", + "org.apache.xerces.impl.dv.dtd.DTDDVFactoryImpl", + "org.apache.xerces.impl.XMLVersionDetector", + "org.apache.xerces.impl.msg.XMLMessageFormatter", + "org.apache.xerces.impl.io.UTF8Reader", + "org.apache.xerces.util.XMLSymbols", + "org.apache.xerces.xni.NamespaceContext", + "org.apache.xerces.util.XMLChar", + "org.apache.xerces.impl.Constants", + "com.att.eelf.configuration.EELFLogger$Level", + "com.att.eelf.configuration.EELFManager", + "org.openecomp.mso.logger.MessageEnum", + "org.openecomp.mso.properties.AbstractMsoProperties" + ); + } +} diff --git a/common/src/test/java/org/openecomp/mso/properties/MsoPropertyInitializerESTest.java b/common/src/test/java/org/openecomp/mso/properties/MsoPropertyInitializerESTest.java new file mode 100644 index 0000000000..a7efa76b1b --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/properties/MsoPropertyInitializerESTest.java @@ -0,0 +1,20 @@ +/* + * This file was automatically generated by EvoSuite + * Mon Nov 14 08:01:07 GMT 2016 + */ + +package org.openecomp.mso.properties; + +import org.junit.Test; +import org.evosuite.runtime.EvoRunner; +import org.evosuite.runtime.EvoRunnerParameters; +import org.junit.runner.RunWith; + +@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) +public class MsoPropertyInitializerESTest extends MsoPropertyInitializerESTestscaffolding { + + @Test(timeout = 4000) + public void test0() throws Throwable { + MsoPropertyInitializer msoPropertyInitializer0 = new MsoPropertyInitializer(); + } +} diff --git a/common/src/test/java/org/openecomp/mso/properties/MsoPropertyInitializerESTestscaffolding.java b/common/src/test/java/org/openecomp/mso/properties/MsoPropertyInitializerESTestscaffolding.java new file mode 100644 index 0000000000..9a056fb576 --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/properties/MsoPropertyInitializerESTestscaffolding.java @@ -0,0 +1,284 @@ +/** + * Scaffolding file used to store all the setups needed to run + * tests automatically generated by EvoSuite + * Mon Nov 14 08:01:07 GMT 2016 + */ + +package org.openecomp.mso.properties; + +import org.evosuite.runtime.annotation.EvoSuiteClassExclude; +import org.junit.BeforeClass; +import org.junit.Before; +import org.junit.After; +import org.junit.AfterClass; +import org.evosuite.runtime.sandbox.Sandbox; + +@EvoSuiteClassExclude +public class MsoPropertyInitializerESTestscaffolding { + + @org.junit.Rule + public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); + + private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); + + private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); + + @BeforeClass + public static void initEvoSuiteFramework() { + org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.mso.properties.MsoPropertyInitializer"; + org.evosuite.runtime.GuiSupport.initialize(); + org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; + org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; + org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; + org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; + org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); + org.evosuite.runtime.classhandling.JDKClassResetter.init(); + initializeClasses(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + } + + @AfterClass + public static void clearEvoSuiteFramework(){ + Sandbox.resetDefaultSecurityManager(); + java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); + } + + @Before + public void initTestCase(){ + threadStopper.storeCurrentThreads(); + threadStopper.startRecordingTime(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); + org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); + + org.evosuite.runtime.GuiSupport.setHeadless(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + org.evosuite.runtime.agent.InstrumentingAgent.activate(); + } + + @After + public void doneWithTestCase(){ + threadStopper.killAndJoinClientThreads(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); + org.evosuite.runtime.classhandling.JDKClassResetter.reset(); + resetClasses(); + org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); + org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); + org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); + } + + + private static void initializeClasses() { + org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(MsoPropertyInitializerESTestscaffolding.class.getClassLoader() , + "org.openecomp.mso.properties.AbstractMsoProperties", + "org.apache.xerces.xni.parser.XMLDTDContentModelFilter", + "org.apache.xerces.xs.PSVIProvider", + "org.apache.xerces.impl.XMLEntityManager$ByteBufferPool", + "org.apache.xerces.impl.dtd.XMLEntityDecl", + "org.apache.xerces.xs.ItemPSVI", + "org.apache.xerces.xni.parser.XMLEntityResolver", + "org.apache.xerces.impl.dtd.XMLNSDTDValidator", + "org.apache.xerces.impl.XMLDTDScannerImpl", + "org.apache.xerces.parsers.ObjectFactory", + "org.apache.xerces.xni.parser.XMLConfigurationException", + "org.apache.xerces.impl.XML11NSDocumentScannerImpl", + "org.apache.xerces.impl.XMLEntityManager$CharacterBufferPool", + "org.apache.xerces.parsers.SAXParser", + "com.att.eelf.i18n.EELFResolvableErrorEnum", + "org.apache.xerces.xni.XMLResourceIdentifier", + "org.apache.xerces.impl.XMLEntityManager$RewindableInputStream", + "org.apache.xerces.impl.XMLEntityManager", + "org.apache.xerces.impl.dtd.XMLDTDDescription", + "org.apache.xerces.xni.parser.XMLInputSource", + "com.att.eelf.i18n.EELFMsgs", + "org.apache.xerces.xni.parser.XMLComponentManager", + "com.att.eelf.configuration.EELFLogger$Level", + "org.apache.xerces.impl.io.UTF8Reader", + "org.apache.xerces.impl.dv.InvalidDatatypeValueException", + "org.apache.xerces.jaxp.UnparsedEntityHandler", + "org.apache.xerces.parsers.AbstractXMLDocumentParser", + "org.apache.xerces.impl.XMLScanner", + "org.apache.xerces.impl.dtd.XMLSimpleType", + "org.apache.xerces.impl.XML11DocumentScannerImpl", + "org.apache.xerces.xni.parser.XMLParseException", + "org.apache.xerces.util.AugmentationsImpl$AugmentationsItemsContainer", + "org.apache.xerces.impl.XMLEntityScanner", + "org.apache.xerces.util.URI$MalformedURIException", + "org.apache.xerces.util.XMLChar", + "org.apache.xerces.impl.XMLNSDocumentScannerImpl", + "org.apache.xerces.impl.XML11DTDScannerImpl", + "org.apache.xerces.util.URI", + "org.apache.xerces.xni.parser.XMLDocumentFilter", + "org.apache.xerces.xni.parser.XMLDTDSource", + "org.apache.xerces.impl.dtd.XMLElementDecl", + "org.apache.xerces.impl.dtd.XMLAttributeDecl", + "com.att.eelf.i18n.EELFResourceManager$RESOURCE_TYPES", + "org.apache.xerces.xni.grammars.Grammar", + "org.apache.xerces.parsers.XMLParser", + "org.apache.xerces.impl.dtd.models.ContentModelValidator", + "com.att.eelf.configuration.EELFLogger", + "org.apache.xerces.xni.grammars.XMLGrammarLoader", + "org.apache.xerces.xni.XMLDocumentHandler", + "org.openecomp.mso.properties.MsoJavaProperties", + "org.apache.xerces.util.SymbolTable", + "org.apache.xerces.impl.io.UCSReader", + "org.apache.xerces.impl.XMLEntityManager$CharacterBuffer", + "org.apache.xerces.impl.io.Latin1Reader", + "org.apache.xerces.impl.dv.ValidationContext", + "org.apache.xerces.impl.dtd.XMLDTDValidator", + "org.apache.xerces.impl.dtd.XML11NSDTDValidator", + "org.apache.xerces.impl.validation.ValidationState", + "org.apache.xerces.impl.XMLEntityManager$Entity", + "org.apache.xerces.util.XMLResourceIdentifierImpl", + "org.apache.xerces.util.AugmentationsImpl", + "org.apache.xerces.impl.dv.ObjectFactory", + "org.apache.xerces.impl.dv.DatatypeValidator", + "org.apache.xerces.xni.NamespaceContext", + "org.apache.xerces.impl.dtd.XMLDTDLoader", + "org.apache.xerces.jaxp.SAXParserImpl", + "org.apache.xerces.util.XMLSymbols", + "org.apache.xerces.parsers.ObjectFactory$ConfigurationError", + "org.apache.xerces.xni.grammars.XMLGrammarDescription", + "org.apache.xerces.xni.parser.XMLErrorHandler", + "org.apache.xerces.impl.io.ASCIIReader", + "org.apache.xerces.util.MessageFormatter", + "org.openecomp.mso.properties.MsoPropertiesParameters", + "org.apache.xerces.impl.dtd.XMLDTDProcessor", + "org.apache.xerces.impl.XMLDocumentFragmentScannerImpl", + "org.apache.xerces.xni.parser.XMLDTDScanner", + "org.openecomp.mso.logger.MsoLogger$ErrorCode", + "org.apache.xerces.xni.XMLAttributes", + "org.apache.xerces.impl.io.MalformedByteSequenceException", + "org.apache.xerces.impl.Constants$ArrayEnumeration", + "org.apache.xerces.impl.XML11EntityScanner", + "org.apache.xerces.impl.dtd.DTDGrammar", + "org.apache.xerces.impl.dv.DTDDVFactory", + "com.att.eelf.configuration.SLF4jWrapper", + "org.openecomp.mso.properties.MsoPropertiesException", + "org.apache.xerces.impl.validation.ValidationManager", + "org.apache.xerces.impl.dv.dtd.DTDDVFactoryImpl", + "org.apache.xerces.xni.XNIException", + "org.apache.xerces.impl.dtd.XMLContentSpec", + "org.openecomp.mso.logger.MsoLogger", + "org.apache.xerces.xs.AttributePSVI", + "org.apache.xerces.impl.dtd.DTDGrammarBucket", + "org.apache.xerces.impl.msg.XMLMessageFormatter", + "org.apache.xerces.xni.parser.XMLDocumentScanner", + "org.apache.xerces.impl.XMLVersionDetector", + "org.apache.xerces.impl.XMLDocumentScannerImpl", + "org.apache.xerces.xni.parser.XMLPullParserConfiguration", + "org.apache.xerces.xni.parser.XMLDocumentSource", + "org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$Dispatcher", + "org.openecomp.mso.properties.MsoPropertiesFactory", + "org.apache.xerces.xni.XMLDTDContentModelHandler", + "org.apache.xerces.impl.xs.XMLSchemaValidator", + "org.openecomp.mso.logger.MsoLogger$Catalog", + "org.apache.xerces.xni.grammars.XMLDTDDescription", + "org.apache.xerces.util.AugmentationsImpl$SmallContainer", + "org.apache.xerces.impl.XMLErrorReporter", + "org.apache.xerces.xni.QName", + "org.apache.xerces.jaxp.TeeXMLDocumentFilterImpl", + "org.apache.xerces.util.XMLAttributesImpl", + "org.apache.xerces.impl.Constants", + "org.apache.xerces.util.XMLStringBuffer", + "org.apache.xerces.impl.XMLEntityManager$InternalEntity", + "org.apache.xerces.jaxp.JAXPConstants", + "org.openecomp.mso.properties.MsoPropertiesParameters$MsoPropertiesType", + "org.apache.xerces.impl.RevalidationHandler", + "org.apache.xerces.xni.parser.XMLParserConfiguration", + "org.apache.xerces.xni.XMLString", + "org.apache.xerces.impl.dv.DVFactoryException", + "org.apache.xerces.impl.dv.DatatypeException", + "org.apache.xerces.parsers.XML11Configurable", + "org.apache.xerces.util.AugmentationsImpl$LargeContainer", + "org.apache.xerces.impl.dtd.BalancedDTDGrammar", + "org.apache.xerces.parsers.XIncludeAwareParserConfiguration", + "org.apache.xerces.xni.XMLDTDHandler", + "org.apache.xerces.impl.dtd.XML11DTDProcessor", + "org.apache.xerces.parsers.XML11Configuration", + "org.apache.xerces.impl.dtd.XMLDTDValidatorFilter", + "org.apache.xerces.impl.xs.identity.FieldActivator", + "org.apache.xerces.impl.XMLEntityScanner$1", + "com.att.eelf.i18n.EELFResourceManager", + "org.apache.xerces.jaxp.SAXParserFactoryImpl", + "org.apache.xerces.xs.ElementPSVI", + "org.apache.xerces.parsers.AbstractSAXParser", + "org.apache.xerces.xni.parser.XMLDTDFilter", + "org.apache.xerces.xni.parser.XMLDTDContentModelSource", + "org.openecomp.mso.logger.MessageEnum", + "org.openecomp.mso.logger.MsoLogger$ResponseCode", + "org.openecomp.mso.properties.MsoJsonProperties", + "org.openecomp.mso.entity.MsoRequest", + "org.openecomp.mso.properties.MsoPropertyInitializer", + "org.openecomp.mso.logger.MsoLogger$StatusCode", + "org.apache.xerces.xni.XMLLocator", + "com.att.eelf.configuration.EELFManager", + "org.apache.xerces.impl.validation.EntityState", + "org.apache.xerces.impl.XMLEntityManager$ExternalEntity", + "org.apache.xerces.util.ParserConfigurationSettings", + "org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser", + "org.apache.xerces.xni.Augmentations", + "org.apache.xerces.impl.XMLEntityHandler", + "org.apache.xerces.impl.dv.ObjectFactory$ConfigurationError", + "org.apache.xerces.xni.parser.XMLComponent", + "com.att.eelf.i18n.EELFResourceManager$1", + "org.apache.xerces.impl.dtd.XML11DTDValidator", + "org.apache.xerces.impl.XMLEntityManager$ScannedEntity", + "org.apache.xerces.jaxp.JAXPValidatorComponent" + ); + } + + private static void resetClasses() { + org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(MsoPropertyInitializerESTestscaffolding.class.getClassLoader()); + + org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( + "com.att.eelf.i18n.EELFResourceManager", + "org.openecomp.mso.logger.MessageEnum", + "org.openecomp.mso.logger.MsoLogger$Catalog", + "org.openecomp.mso.logger.MsoLogger$ErrorCode", + "org.openecomp.mso.logger.MsoLogger", + "com.att.eelf.i18n.EELFMsgs", + "com.att.eelf.i18n.EELFResourceManager$RESOURCE_TYPES", + "org.apache.xerces.jaxp.SAXParserFactoryImpl", + "org.apache.xerces.jaxp.SAXParserImpl", + "org.apache.xerces.parsers.XMLParser", + "org.apache.xerces.parsers.AbstractSAXParser", + "org.apache.xerces.parsers.SAXParser", + "org.apache.xerces.parsers.ObjectFactory", + "org.apache.xerces.util.ParserConfigurationSettings", + "org.apache.xerces.parsers.XML11Configuration", + "org.apache.xerces.parsers.XIncludeAwareParserConfiguration", + "org.apache.xerces.util.SymbolTable", + "org.apache.xerces.impl.XMLEntityManager", + "org.apache.xerces.util.AugmentationsImpl$SmallContainer", + "org.apache.xerces.impl.XMLEntityManager$ByteBufferPool", + "org.apache.xerces.impl.XMLEntityManager$CharacterBufferPool", + "org.apache.xerces.impl.XMLEntityScanner$1", + "org.apache.xerces.impl.XMLEntityScanner", + "org.apache.xerces.impl.XMLErrorReporter", + "org.apache.xerces.impl.XMLScanner", + "org.apache.xerces.impl.XMLDocumentFragmentScannerImpl", + "org.apache.xerces.impl.XMLDocumentScannerImpl", + "org.apache.xerces.util.XMLStringBuffer", + "org.apache.xerces.util.XMLAttributesImpl", + "org.apache.xerces.impl.XMLDTDScannerImpl", + "org.apache.xerces.impl.dtd.XMLDTDProcessor", + "org.apache.xerces.impl.dtd.XMLDTDValidator", + "org.apache.xerces.impl.validation.ValidationState", + "org.apache.xerces.impl.dtd.XMLElementDecl", + "org.apache.xerces.impl.dtd.XMLSimpleType", + "org.apache.xerces.impl.dv.DTDDVFactory", + "org.apache.xerces.impl.dv.ObjectFactory", + "org.apache.xerces.impl.dv.dtd.DTDDVFactoryImpl", + "org.apache.xerces.impl.XMLVersionDetector", + "org.apache.xerces.impl.msg.XMLMessageFormatter", + "org.apache.xerces.impl.io.UTF8Reader", + "org.apache.xerces.util.XMLSymbols", + "org.apache.xerces.xni.NamespaceContext", + "org.apache.xerces.util.XMLChar", + "org.apache.xerces.impl.Constants", + "com.att.eelf.configuration.EELFLogger$Level", + "com.att.eelf.configuration.EELFManager", + "org.openecomp.mso.properties.MsoPropertiesFactory" + ); + } +} diff --git a/common/src/test/java/org/openecomp/mso/utils/CheckResultsESTest.java b/common/src/test/java/org/openecomp/mso/utils/CheckResultsESTest.java new file mode 100644 index 0000000000..212fe95407 --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/utils/CheckResultsESTest.java @@ -0,0 +1,124 @@ +/* + * This file was automatically generated by EvoSuite + * Mon Nov 14 08:02:57 GMT 2016 + */ + +package org.openecomp.mso.utils; + +import org.junit.Test; +import static org.junit.Assert.*; + +import java.util.List; +import org.evosuite.runtime.EvoRunner; +import org.evosuite.runtime.EvoRunnerParameters; +import org.evosuite.runtime.PrivateAccess; +import org.junit.runner.RunWith; + +@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) +public class CheckResultsESTest extends CheckResultsESTestscaffolding { + + @Test(timeout = 4000) + public void test00() throws Throwable { + CheckResults checkResults0 = new CheckResults(); + checkResults0.addHostCheckResult("GP<QUZyf\"vf-sD", (-1), ""); + } + + @Test(timeout = 4000) + public void test01() throws Throwable { + CheckResults checkResults0 = new CheckResults(); + PrivateAccess.setVariable((Class<CheckResults>) CheckResults.class, checkResults0, "results", (Object) null); + List<CheckResults.CheckResult> list0 = checkResults0.getResults(); + assertNull(list0); + } + + @Test(timeout = 4000) + public void test02() throws Throwable { + CheckResults.CheckResult checkResults_CheckResult0 = new CheckResults.CheckResult(); + checkResults_CheckResult0.setOutput("xp"); + assertEquals(0, checkResults_CheckResult0.getState()); + } + + @Test(timeout = 4000) + public void test03() throws Throwable { + CheckResults.CheckResult checkResults_CheckResult0 = new CheckResults.CheckResult(); + checkResults_CheckResult0.setType("2"); + assertEquals(0, checkResults_CheckResult0.getState()); + } + + @Test(timeout = 4000) + public void test04() throws Throwable { + CheckResults.CheckResult checkResults_CheckResult0 = new CheckResults.CheckResult(); + checkResults_CheckResult0.setState(1); + assertEquals(1, checkResults_CheckResult0.getState()); + } + + @Test(timeout = 4000) + public void test05() throws Throwable { + CheckResults.CheckResult checkResults_CheckResult0 = new CheckResults.CheckResult(); + checkResults_CheckResult0.setServicename("9~"); + assertEquals(0, checkResults_CheckResult0.getState()); + } + + @Test(timeout = 4000) + public void test06() throws Throwable { + CheckResults.CheckResult checkResults_CheckResult0 = new CheckResults.CheckResult(); + checkResults_CheckResult0.setHostname((String) null); + assertNull(checkResults_CheckResult0.getServicename()); + } + + @Test(timeout = 4000) + public void test07() throws Throwable { + CheckResults checkResults0 = new CheckResults(); + checkResults0.addHostCheckResult("GP<QUZyf\"vf-sD", 0, "GP<QUZyf\"vf-sD"); + List<CheckResults.CheckResult> list0 = checkResults0.getResults(); + assertEquals(1, list0.size()); + } + + @Test(timeout = 4000) + public void test08() throws Throwable { + CheckResults checkResults0 = new CheckResults(); + List<CheckResults.CheckResult> list0 = checkResults0.getResults(); + assertTrue(list0.isEmpty()); + } + + @Test(timeout = 4000) + public void test09() throws Throwable { + CheckResults.CheckResult checkResults_CheckResult0 = new CheckResults.CheckResult(); + String string0 = checkResults_CheckResult0.getServicename(); + assertNull(string0); + } + + @Test(timeout = 4000) + public void test10() throws Throwable { + CheckResults.CheckResult checkResults_CheckResult0 = new CheckResults.CheckResult(); + int int0 = checkResults_CheckResult0.getState(); + assertEquals(0, int0); + } + + @Test(timeout = 4000) + public void test11() throws Throwable { + CheckResults.CheckResult checkResults_CheckResult0 = new CheckResults.CheckResult(); + String string0 = checkResults_CheckResult0.getHostname(); + assertNull(string0); + } + + @Test(timeout = 4000) + public void test12() throws Throwable { + CheckResults.CheckResult checkResults_CheckResult0 = new CheckResults.CheckResult(); + String string0 = checkResults_CheckResult0.getType(); + assertNull(string0); + } + + @Test(timeout = 4000) + public void test13() throws Throwable { + CheckResults checkResults0 = new CheckResults(); + checkResults0.addServiceCheckResult("", "Ifp73+/", 0, " "); + } + + @Test(timeout = 4000) + public void test14() throws Throwable { + CheckResults.CheckResult checkResults_CheckResult0 = new CheckResults.CheckResult(); + String string0 = checkResults_CheckResult0.getOutput(); + assertNull(string0); + } +} diff --git a/common/src/test/java/org/openecomp/mso/utils/CheckResultsESTestscaffolding.java b/common/src/test/java/org/openecomp/mso/utils/CheckResultsESTestscaffolding.java new file mode 100644 index 0000000000..a4fea268c1 --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/utils/CheckResultsESTestscaffolding.java @@ -0,0 +1,79 @@ +/** + * Scaffolding file used to store all the setups needed to run + * tests automatically generated by EvoSuite + * Mon Nov 14 08:02:57 GMT 2016 + */ + +package org.openecomp.mso.utils; + +import org.evosuite.runtime.annotation.EvoSuiteClassExclude; +import org.junit.BeforeClass; +import org.junit.Before; +import org.junit.After; +import org.junit.AfterClass; +import org.evosuite.runtime.sandbox.Sandbox; + +@EvoSuiteClassExclude +public class CheckResultsESTestscaffolding { + + @org.junit.Rule + public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); + + private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); + + private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); + + @BeforeClass + public static void initEvoSuiteFramework() { + org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.mso.utils.CheckResults"; + org.evosuite.runtime.GuiSupport.initialize(); + org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; + org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; + org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; + org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; + org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); + org.evosuite.runtime.classhandling.JDKClassResetter.init(); + initializeClasses(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + } + + @AfterClass + public static void clearEvoSuiteFramework(){ + Sandbox.resetDefaultSecurityManager(); + java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); + } + + @Before + public void initTestCase(){ + threadStopper.storeCurrentThreads(); + threadStopper.startRecordingTime(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); + org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); + + org.evosuite.runtime.GuiSupport.setHeadless(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + org.evosuite.runtime.agent.InstrumentingAgent.activate(); + } + + @After + public void doneWithTestCase(){ + threadStopper.killAndJoinClientThreads(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); + org.evosuite.runtime.classhandling.JDKClassResetter.reset(); + resetClasses(); + org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); + org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); + org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); + } + + + private static void initializeClasses() { + org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(CheckResultsESTestscaffolding.class.getClassLoader() , + "org.openecomp.mso.utils.CheckResults$CheckResult", + "org.openecomp.mso.utils.CheckResults" + ); + } + + private static void resetClasses() { + } +} diff --git a/common/src/test/java/org/openecomp/mso/utils/CheckResultsTest.java b/common/src/test/java/org/openecomp/mso/utils/CheckResultsTest.java new file mode 100644 index 0000000000..e178e4cf9c --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/utils/CheckResultsTest.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.utils; + +import java.util.List; + +import org.junit.Test; + +import org.openecomp.mso.utils.CheckResults.CheckResult; + +public class CheckResultsTest { + + /** + * Test method for {@link org.openecomp.mso.utils.CheckResults#getResults()}. + */ + @Test + public final void testGetResults () { + CheckResults cr = new CheckResults (); + cr.addHostCheckResult ("host1", 0, "output"); + cr.addHostCheckResult ("host2", 2, "output2"); + cr.addServiceCheckResult ("host1", "service1", 0, "outputServ"); + cr.addServiceCheckResult ("host1", "service2", 2, "outputServ2"); + cr.addServiceCheckResult ("host2", "service1", 0, "output2Serv"); + cr.addServiceCheckResult ("host2", "service2", 2, "output2Serv2"); + List <CheckResult> res = cr.getResults (); + assert(res.size () == 6); + assert(res.get (0).getHostname ().equals ("host1")); + assert(res.get (1).getHostname ().equals ("host2")); + assert(res.get (2).getHostname ().equals ("host1")); + assert(res.get (3).getHostname ().equals ("host1")); + assert(res.get (4).getHostname ().equals ("host2")); + assert(res.get (5).getHostname ().equals ("host2")); + assert(res.get (0).getServicename () == null); + assert(res.get (3).getServicename ().equals ("service2")); + assert(res.get (5).getState () == 2); + } + +} diff --git a/common/src/test/java/org/openecomp/mso/utils/CryptoUtilsESTest.java b/common/src/test/java/org/openecomp/mso/utils/CryptoUtilsESTest.java new file mode 100644 index 0000000000..397db374bb --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/utils/CryptoUtilsESTest.java @@ -0,0 +1,175 @@ +/* + * This file was automatically generated by EvoSuite + * Mon Nov 14 09:07:10 GMT 2016 + */ + +package org.openecomp.mso.utils; + +import org.junit.Test; +import static org.junit.Assert.*; +import static org.evosuite.runtime.EvoAssertions.*; + +import javax.crypto.BadPaddingException; +import javax.crypto.IllegalBlockSizeException; +import org.evosuite.runtime.EvoRunner; +import org.evosuite.runtime.EvoRunnerParameters; +import org.junit.runner.RunWith; + +@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) +public class CryptoUtilsESTest extends CryptoUtilsESTestscaffolding { + + @Test(timeout = 4000) + public void test00() throws Throwable { + CryptoUtils.decrypt("E08682BE5F2B18A6E8437A15B110D418E08682BE5F2B18A6E8437A15B110D4180143DB63EE66B0CDFF9F69917680151E", "00000000000000000000000000000000"); + } + + @Test(timeout = 4000) + public void test01() throws Throwable { + byte[] byteArray0 = new byte[0]; + CryptoUtils.byteArrayToHexString(byteArray0); + } + + @Test(timeout = 4000) + public void test02() throws Throwable { + // Undeclared exception! + try { + CryptoUtils.encrypt("AES", "w^p&|^Cvs@K.@@"); + fail("Expecting exception: NumberFormatException"); + + } catch(NumberFormatException e) { + // + // For input string: \"w^\" + // + verifyException("java.lang.NumberFormatException", e); + } + } + + @Test(timeout = 4000) + public void test03() throws Throwable { + // Undeclared exception! + try { + CryptoUtils.encrypt((String) null, "B2000000000000000000000000000000"); + fail("Expecting exception: NullPointerException"); + + } catch(NullPointerException e) { + // + // no message in exception (getMessage() returned null) + // + verifyException("org.openecomp.mso.utils.CryptoUtils", e); + } + } + + @Test(timeout = 4000) + public void test04() throws Throwable { + try { + CryptoUtils.decrypt("B20000000000000000000000000000000000000000000000", "B20000000000000000000000000000000000000000000000"); + fail("Expecting exception: IllegalBlockSizeException"); + + } catch(IllegalBlockSizeException e) { + } + } + + @Test(timeout = 4000) + public void test05() throws Throwable { + try { + CryptoUtils.decrypt("0000C200000000000000000000000000", "0000C200000000000000000000000000"); + fail("Expecting exception: BadPaddingException"); + + } catch(BadPaddingException e) { + } + } + + @Test(timeout = 4000) + public void test06() throws Throwable { + // Undeclared exception! + try { + CryptoUtils.decrypt("s.", "s."); + fail("Expecting exception: NumberFormatException"); + + } catch(NumberFormatException e) { + // + // For input string: \"s.\" + // + verifyException("java.lang.NumberFormatException", e); + } + } + + @Test(timeout = 4000) + public void test07() throws Throwable { + // Undeclared exception! + try { + CryptoUtils.decrypt("", ""); + fail("Expecting exception: IllegalArgumentException"); + + } catch(IllegalArgumentException e) { + // + // Empty key + // + verifyException("javax.crypto.spec.SecretKeySpec", e); + } + } + + @Test(timeout = 4000) + public void test08() throws Throwable { + // Undeclared exception! + try { + CryptoUtils.byteArrayToHexString((byte[]) null); + fail("Expecting exception: NullPointerException"); + + } catch(NullPointerException e) { + // + // no message in exception (getMessage() returned null) + // + verifyException("org.openecomp.mso.utils.CryptoUtils", e); + } + } + + @Test(timeout = 4000) + public void test09() throws Throwable { + byte[] byteArray0 = new byte[16]; + byteArray0[0] = (byte) (-78); + String string0 = CryptoUtils.byteArrayToHexString(byteArray0); + assertEquals("B2000000000000000000000000000000", string0); + } + + @Test(timeout = 4000) + public void test10() throws Throwable { + String string0 = CryptoUtils.encrypt("00000000000000000000000000000000", "00000000000000000000000000000000"); + assertEquals("E08682BE5F2B18A6E8437A15B110D418E08682BE5F2B18A6E8437A15B110D4180143DB63EE66B0CDFF9F69917680151E", string0); + } + + @Test(timeout = 4000) + public void test11() throws Throwable { + // Undeclared exception! + try { + CryptoUtils.encrypt("", ""); + fail("Expecting exception: IllegalArgumentException"); + + } catch(IllegalArgumentException e) { + // + // Empty key + // + verifyException("javax.crypto.spec.SecretKeySpec", e); + } + } + + @Test(timeout = 4000) + public void test12() throws Throwable { + CryptoUtils cryptoUtils0 = new CryptoUtils(); + } + + @Test(timeout = 4000) + public void test13() throws Throwable { + // Undeclared exception! + try { + CryptoUtils.decrypt((String) null, "00000000000000000000000000000000"); + fail("Expecting exception: NullPointerException"); + + } catch(NullPointerException e) { + // + // no message in exception (getMessage() returned null) + // + verifyException("org.openecomp.mso.utils.CryptoUtils", e); + } + } +} diff --git a/common/src/test/java/org/openecomp/mso/utils/CryptoUtilsESTestscaffolding.java b/common/src/test/java/org/openecomp/mso/utils/CryptoUtilsESTestscaffolding.java new file mode 100644 index 0000000000..09574153c7 --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/utils/CryptoUtilsESTestscaffolding.java @@ -0,0 +1,83 @@ +/** + * Scaffolding file used to store all the setups needed to run + * tests automatically generated by EvoSuite + * Mon Nov 14 09:07:10 GMT 2016 + */ + +package org.openecomp.mso.utils; + +import org.evosuite.runtime.annotation.EvoSuiteClassExclude; +import org.junit.BeforeClass; +import org.junit.Before; +import org.junit.After; +import org.junit.AfterClass; +import org.evosuite.runtime.sandbox.Sandbox; + +@EvoSuiteClassExclude +public class CryptoUtilsESTestscaffolding { + + @org.junit.Rule + public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); + + private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); + + private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); + + @BeforeClass + public static void initEvoSuiteFramework() { + org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.mso.utils.CryptoUtils"; + org.evosuite.runtime.GuiSupport.initialize(); + org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; + org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; + org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; + org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; + org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); + org.evosuite.runtime.classhandling.JDKClassResetter.init(); + initializeClasses(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + } + + @AfterClass + public static void clearEvoSuiteFramework(){ + Sandbox.resetDefaultSecurityManager(); + java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); + } + + @Before + public void initTestCase(){ + threadStopper.storeCurrentThreads(); + threadStopper.startRecordingTime(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); + org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); + + org.evosuite.runtime.GuiSupport.setHeadless(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + org.evosuite.runtime.agent.InstrumentingAgent.activate(); + } + + @After + public void doneWithTestCase(){ + threadStopper.killAndJoinClientThreads(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); + org.evosuite.runtime.classhandling.JDKClassResetter.reset(); + resetClasses(); + org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); + org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); + org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); + } + + + private static void initializeClasses() { + org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(CryptoUtilsESTestscaffolding.class.getClassLoader() , + "org.openecomp.mso.utils.CryptoUtils" + ); + } + + private static void resetClasses() { + org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(CryptoUtilsESTestscaffolding.class.getClassLoader()); + + org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( + "org.openecomp.mso.utils.CryptoUtils" + ); + } +} diff --git a/common/src/test/java/org/openecomp/mso/utils/UUIDCheckerESTest.java b/common/src/test/java/org/openecomp/mso/utils/UUIDCheckerESTest.java new file mode 100644 index 0000000000..fa8517e3db --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/utils/UUIDCheckerESTest.java @@ -0,0 +1,34 @@ +/* + * This file was automatically generated by EvoSuite + * Mon Nov 14 08:02:03 GMT 2016 + */ + +package org.openecomp.mso.utils; + +import org.junit.Test; +import static org.junit.Assert.*; +import static org.evosuite.shaded.org.mockito.Mockito.*; + +import org.openecomp.mso.logger.MsoLogger; +import org.evosuite.runtime.EvoRunner; +import org.evosuite.runtime.EvoRunnerParameters; +import org.evosuite.runtime.PrivateAccess; +import org.evosuite.runtime.ViolatedAssumptionAnswer; +import org.junit.runner.RunWith; + +@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) +public class UUIDCheckerESTest extends UUIDCheckerESTestscaffolding { + + @Test(timeout = 4000) + public void test0() throws Throwable { + MsoLogger msoLogger0 = mock(MsoLogger.class, new ViolatedAssumptionAnswer()); + String string0 = UUIDChecker.generateServiceInstanceID(msoLogger0); + assertEquals("00000000-0100-4000-8200-000003000000", string0); + } + + @Test(timeout = 4000) + public void test1() throws Throwable { + UUIDChecker uUIDChecker0 = (UUIDChecker)PrivateAccess.callDefaultConstructorOfTheClassUnderTest(); + assertNotNull(uUIDChecker0); + } +} diff --git a/common/src/test/java/org/openecomp/mso/utils/UUIDCheckerESTestscaffolding.java b/common/src/test/java/org/openecomp/mso/utils/UUIDCheckerESTestscaffolding.java new file mode 100644 index 0000000000..15397cb165 --- /dev/null +++ b/common/src/test/java/org/openecomp/mso/utils/UUIDCheckerESTestscaffolding.java @@ -0,0 +1,94 @@ +/** + * Scaffolding file used to store all the setups needed to run + * tests automatically generated by EvoSuite + * Mon Nov 14 08:02:03 GMT 2016 + */ + +package org.openecomp.mso.utils; + +import org.evosuite.runtime.annotation.EvoSuiteClassExclude; +import org.junit.BeforeClass; +import org.junit.Before; +import org.junit.After; +import org.junit.AfterClass; +import org.evosuite.runtime.sandbox.Sandbox; + +@EvoSuiteClassExclude +public class UUIDCheckerESTestscaffolding { + + @org.junit.Rule + public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); + + private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); + + private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); + + @BeforeClass + public static void initEvoSuiteFramework() { + org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.mso.utils.UUIDChecker"; + org.evosuite.runtime.GuiSupport.initialize(); + org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; + org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; + org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; + org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; + org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); + org.evosuite.runtime.classhandling.JDKClassResetter.init(); + initializeClasses(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + } + + @AfterClass + public static void clearEvoSuiteFramework(){ + Sandbox.resetDefaultSecurityManager(); + java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); + } + + @Before + public void initTestCase(){ + threadStopper.storeCurrentThreads(); + threadStopper.startRecordingTime(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); + org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); + + org.evosuite.runtime.GuiSupport.setHeadless(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + org.evosuite.runtime.agent.InstrumentingAgent.activate(); + } + + @After + public void doneWithTestCase(){ + threadStopper.killAndJoinClientThreads(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); + org.evosuite.runtime.classhandling.JDKClassResetter.reset(); + resetClasses(); + org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); + org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); + org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); + } + + + private static void initializeClasses() { + org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(UUIDCheckerESTestscaffolding.class.getClassLoader() , + "org.openecomp.mso.logger.MsoLogger", + "org.openecomp.mso.logger.MessageEnum", + "com.att.eelf.i18n.EELFResolvableErrorEnum", + "org.openecomp.mso.logger.MsoLogger$ResponseCode", + "org.openecomp.mso.logger.MsoLogger$Catalog", + "org.openecomp.mso.entity.MsoRequest", + "org.openecomp.mso.logger.MsoLogger$StatusCode", + "com.att.eelf.i18n.EELFResourceManager", + "org.openecomp.mso.logger.MsoLogger$ErrorCode", + "org.openecomp.mso.utils.UUIDChecker" + ); + } + + private static void resetClasses() { + org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(UUIDCheckerESTestscaffolding.class.getClassLoader()); + + org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( + "com.att.eelf.i18n.EELFResourceManager", + "org.openecomp.mso.logger.MessageEnum", + "org.openecomp.mso.logger.MsoLogger" + ); + } +} diff --git a/common/src/test/resources/logback-test.xml b/common/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..b1888ac986 --- /dev/null +++ b/common/src/test/resources/logback-test.xml @@ -0,0 +1,171 @@ +<!-- + ============LICENSE_START======================================================= + ECOMP MSO + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ============LICENSE_END========================================================= + --> + +<configuration scan="false" debug="true"> + <!--<jmxConfigurator /> --> + <!-- directory path for all other type logs --> + <property name="logDir" value="./target" /> + + <!-- directory path for debugging type logs --> + <property name="debugDir" value="./target" /> + + <!-- specify the component name + <ECOMP-component-name>::= "MSO" | "DCAE" | "ASDC " | "AAI" |"Policy" | "SDNC" | "AC" --> + <property name="componentName" value="MSO"></property> + <property name="subComponentName" value="Test"></property> + <!-- log file names --> + <property name="errorLogName" value="error" /> + <property name="metricsLogName" value="metrics" /> + <property name="auditLogName" value="audit" /> + <property name="debugLogName" value="debug" /> + + <property name="errorPattern" value="%d{"yyyy-MM-dd'T'HH:mm:ss.SSSXXX", UTC}|%X{RequestId}|%thread|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%.-5level|%X{ErrorCode}|%X{ErrorDesc}|%msg%n" /> + <property name="debugPattern" value="%d{"yyyy-MM-dd'T'HH:mm:ss.SSSXXX", UTC}|%X{RequestId}|%msg%n" /> + + <property name="auditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread||%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDesc}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{Timer}|%X{ServerFQDN}|%X{RemoteHost}||||||||%msg%n" /> + <property name="metricPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread||%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDesc}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{Timer}|%X{ServerFQDN}|%X{RemoteHost}||||%X{TargetVirtualEntity}|||||%msg%n" /> + + <property name="logDirectory" value="${logDir}/${componentName}/${subComponentName}" /> + <property name="debugLogDirectory" value="${debugDir}/${componentName}/${subComponentName}" /> + + + <!-- Example evaluator filter applied against console appender --> + <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> + <encoder> + <pattern>${defaultPattern}</pattern> + </encoder> + </appender> + + <!-- ============================================================================ --> + <!-- EELF Appenders --> + <!-- ============================================================================ --> + + <!-- The EELFAppender is used to record events to the general application + log --> + + <!-- EELF Audit Appender. This appender is used to record audit engine + related logging events. The audit logger and appender are specializations + of the EELF application root logger and appender. This can be used to segregate + Policy engine events from other components, or it can be eliminated to record + these events as part of the application root log. --> + + <appender name="EELFAudit" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <file>${logDirectory}/${auditLogName}${jboss.server.name}.log</file> + <rollingPolicy + class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> + <fileNamePattern>${logDirectory}/${auditLogName}${jboss.server.name}.log.%d</fileNamePattern> + <!--<maxHistory>30</maxHistory>--> + </rollingPolicy> + <encoder> + <pattern>${auditPattern}</pattern> + </encoder> + </appender> + <appender name="asyncEELFAudit" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>500</queueSize> + <discardingThreshold>0</discardingThreshold> + <appender-ref ref="EELFAudit" /> + </appender> + +<appender name="EELFMetrics" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <file>${logDirectory}/${metricsLogName}${jboss.server.name}.log</file> + <rollingPolicy + class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> + <fileNamePattern>${logDirectory}/${metricsLogName}${jboss.server.name}.log.%d</fileNamePattern> + <!--<maxHistory>30</maxHistory>--> + </rollingPolicy> + <encoder> + <!-- <pattern>"%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} - + %msg%n"</pattern> --> + <pattern>${metricPattern}</pattern> + </encoder> + </appender> + + + <appender name="asyncEELFMetrics" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>500</queueSize> + <discardingThreshold>0</discardingThreshold> + <appender-ref ref="EELFMetrics"/> + </appender> + + <appender name="EELFError" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <file>${logDirectory}/${errorLogName}${jboss.server.name}.log</file> + <rollingPolicy + class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> + <fileNamePattern>${logDirectory}/${errorLogName}${jboss.server.name}.log.%d</fileNamePattern> + <!--<maxHistory>30</maxHistory>--> + </rollingPolicy> + <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> + <level>INFO</level> + </filter> + <encoder> + <pattern>${errorPattern}</pattern> + </encoder> + </appender> + + <appender name="asyncEELFError" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>500</queueSize> + <discardingThreshold>0</discardingThreshold> + <appender-ref ref="EELFError"/> + </appender> + + <appender name="EELFDebug" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <file>${debugLogDirectory}/${debugLogName}${jboss.server.name}.log</file> + <rollingPolicy + class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> + <fileNamePattern>${debugLogDirectory}/${debugLogName}${jboss.server.name}.log.%d</fileNamePattern> + <!--<maxHistory>30</maxHistory>--> + </rollingPolicy> + <encoder> + <pattern>${debugPattern}</pattern> + </encoder> + </appender> + + <appender name="asyncEELFDebug" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>500</queueSize> + <discardingThreshold>0</discardingThreshold> + <appender-ref ref="EELFDebug" /> + <includeCallerData>true</includeCallerData> + </appender> + + + <!-- ============================================================================ --> + <!-- EELF loggers --> + <!-- ============================================================================ --> + + <logger name="com.att.eelf.audit" level="info" additivity="false"> + <appender-ref ref="asyncEELFAudit" /> + </logger> + + <logger name="com.att.eelf.metrics" level="info" additivity="false"> + <appender-ref ref="asyncEELFMetrics" /> + </logger> + + <logger name="com.att.eelf.error" level="debug" additivity="false"> + <appender-ref ref="asyncEELFError" /> + </logger> + <root level="INFO"> + <appender-ref ref="asyncEELFDebug" /> + </root> + +</configuration> diff --git a/common/src/test/resources/mso-bad.json b/common/src/test/resources/mso-bad.json new file mode 100644 index 0000000000..9c3d26b4eb --- /dev/null +++ b/common/src/test/resources/mso-bad.json @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +{ + "asdc-connections":{, + "asdc-controller1":{ + "asdcUser": "user1", + "asdcConsumerGroup": "consumer1", + "asdcConsumerId": "consumer1", + "asdcEnvironmentName": "PROD", + "asdcAddress": "localhost:8443", + "asdcPassword": "1c551b8b5ab91fcd5a0907b11c304199" + }, + "asdc-controller2":{ + "asdcUser": "user2", + "asdcConsumerGroup": "consumer2", + "asdcConsumerId": "consumer2", + "asdcEnvironmentName": "E2E", + "asdcAddress": "localhost:8443", + "asdcPassword": "1c551b8b5ab91fcd5a0907b11c304199" + } + } +} diff --git a/common/src/test/resources/mso.json b/common/src/test/resources/mso.json new file mode 100644 index 0000000000..e8ee4a9185 --- /dev/null +++ b/common/src/test/resources/mso.json @@ -0,0 +1,21 @@ +{ + "asdc-connections":{ + "asdc-controller1":{ + "asdcUser": "user1", + "asdcConsumerGroup": "consumer1", + "asdcConsumerId": "consumer1", + "asdcEnvironmentName": "PROD", + "asdcAddress": "localhost:8443", + "asdcPassword": "1c551b8b5ab91fcd5a0907b11c304199" + }, + "asdc-controller2":{ + "asdcUser": "user2", + "asdcConsumerGroup": "consumer2", + "asdcConsumerId": "consumer2", + "asdcEnvironmentName": "E2E", + "asdcAddress": "localhost:8443", + "asdcPassword": "1c551b8b5ab91fcd5a0907b11c304199" + } + }, + "mso.properties.reload.time.minutes":2 +} diff --git a/common/src/test/resources/mso.nrdp-alarms.properties b/common/src/test/resources/mso.nrdp-alarms.properties new file mode 100644 index 0000000000..8e7f8ed19e --- /dev/null +++ b/common/src/test/resources/mso.nrdp-alarms.properties @@ -0,0 +1,23 @@ +### +# ============LICENSE_START======================================================= +# ECOMP MSO +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +### + +mso.alarms.nrdp.enabled=false +mso.alarms.nrdp.url=http://localhost:80 +mso.alarms.nrdp.token=83c9bb2734dd1a003e440128aa82f10c diff --git a/common/src/test/resources/mso.properties b/common/src/test/resources/mso.properties new file mode 100644 index 0000000000..bb0e4ebf0d --- /dev/null +++ b/common/src/test/resources/mso.properties @@ -0,0 +1,28 @@ +### +# ============LICENSE_START======================================================= +# ECOMP MSO +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +### + +mso.properties.reload.time.minutes=2 +ecomp.mso.cloud.1.cloudId=MT +ecomp.mso.cloud.1.keystoneUrl=http://localhost:5000/v2.0 +ecomp.mso.cloud.1.msoId=John +ecomp.mso.cloud.1.publicNetId=FD205490A48D48475607C36B9AD902BF +ecomp.mso.cloud.1.test=1234 +ecomp.mso.cloud.1.boolean=true +ecomp.mso.cloud.1.enum=enum1 diff --git a/common/src/test/resources/mso2.json b/common/src/test/resources/mso2.json new file mode 100644 index 0000000000..006fda9ac4 --- /dev/null +++ b/common/src/test/resources/mso2.json @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +{ + "asdc-connections":{ + "asdc-controller1":{ + "asdcUser": "user1B", + "asdcConsumerGroup": "consumer1", + "asdcConsumerId": "consumer1", + "asdcEnvironmentName": "PROD", + "asdcAddress": "localhost:8443", + "asdcPassword": "1c551b8b5ab91fcd5a0907b11c304199" + }, + "asdc-controller2":{ + "asdcUser": "user2B", + "asdcConsumerGroup": "consumer2", + "asdcConsumerId": "consumer2", + "asdcEnvironmentName": "E2E", + "asdcAddress": "localhost:8443", + "asdcPassword": "1c551b8b5ab91fcd5a0907b11c304199" + } + } + +} diff --git a/common/src/test/resources/mso2.properties b/common/src/test/resources/mso2.properties new file mode 100644 index 0000000000..423346e953 --- /dev/null +++ b/common/src/test/resources/mso2.properties @@ -0,0 +1,22 @@ +### +# ============LICENSE_START======================================================= +# ECOMP MSO +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +### + +mso.properties.reload.time.minutes=1 +ecomp.mso.cloud.1.cloudId=MT2 |