From 37181837935f5e94fd02b32da0df966b498dd968 Mon Sep 17 00:00:00 2001 From: Carsten Lund Date: Mon, 13 Mar 2017 13:51:35 +0000 Subject: [DCAE-15] Changes related to version 1.1 See Jira for details Change-Id: I225aa7a8952da4ddb0a93ac238aa79c8993f72b8 Signed-off-by: Carsten Lund --- operation-utils/.classpath | 2 + operation-utils/META-INF/MANIFEST.MF | 1 + operation-utils/operation-utils.iml | 30 + operation-utils/pom.xml | 111 +-- .../logger/GenericMessagesMessageEnum.java | 25 + .../entity/EcompSubComponentInstance.java | 7 +- .../java/org/openecomp/logger/EcompException.java | 53 ++ .../java/org/openecomp/logger/EcompLogger.java | 920 +++++++++++++-------- .../org/openecomp/logger/GenericMessageEnum.java | 38 - .../java/org/openecomp/logger/LogCategoryEnum.java | 30 + .../java/org/openecomp/logger/StatusCodeEnum.java | 27 + .../main/java/org/openecomp/logger/Stopwatch.java | 253 ++++++ .../main/java/org/openecomp/utils/YamlToJava.java | 125 ++- .../openecomp/logger/GenericMessages.properties | 72 ++ .../src/main/resources/GenericMessages.properties | 13 +- .../src/main/resources/GenericMessages.yaml | 99 ++- operation-utils/src/main/resources/logback.xml | 351 ++++++++ .../src/main/resources/messageEnum.java_template | 4 +- .../src/main/resources/operationEnum.java_template | 17 +- .../src/main/resources/properties_template | 4 +- 20 files changed, 1690 insertions(+), 492 deletions(-) create mode 100644 operation-utils/operation-utils.iml create mode 100644 operation-utils/src/main/java-gen/org/openecomp/logger/GenericMessagesMessageEnum.java create mode 100644 operation-utils/src/main/java/org/openecomp/logger/EcompException.java delete mode 100644 operation-utils/src/main/java/org/openecomp/logger/GenericMessageEnum.java create mode 100644 operation-utils/src/main/java/org/openecomp/logger/LogCategoryEnum.java create mode 100644 operation-utils/src/main/java/org/openecomp/logger/StatusCodeEnum.java create mode 100644 operation-utils/src/main/java/org/openecomp/logger/Stopwatch.java create mode 100644 operation-utils/src/main/resources-gen/org/openecomp/logger/GenericMessages.properties create mode 100644 operation-utils/src/main/resources/logback.xml diff --git a/operation-utils/.classpath b/operation-utils/.classpath index 1ab68f0..329c766 100644 --- a/operation-utils/.classpath +++ b/operation-utils/.classpath @@ -11,6 +11,8 @@ + + diff --git a/operation-utils/META-INF/MANIFEST.MF b/operation-utils/META-INF/MANIFEST.MF index 65b7caa..8dfed08 100644 --- a/operation-utils/META-INF/MANIFEST.MF +++ b/operation-utils/META-INF/MANIFEST.MF @@ -6,3 +6,4 @@ Bundle-Version: 0.1.0.qualifier Export-Package: org.openecomp.entity, org.openecomp.logger, org.openecomp.utils +Require-Bundle: javax.servlet diff --git a/operation-utils/operation-utils.iml b/operation-utils/operation-utils.iml new file mode 100644 index 0000000..e3b64a3 --- /dev/null +++ b/operation-utils/operation-utils.iml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/operation-utils/pom.xml b/operation-utils/pom.xml index 8500896..ebc5aa2 100644 --- a/operation-utils/pom.xml +++ b/operation-utils/pom.xml @@ -3,7 +3,6 @@ 4.0.0 org.openecomp.dcae.operation.utils operation-utils - 1.1.0-SNAPSHOT UTF-8 @@ -11,42 +10,21 @@ 1.7 https://nexus.onap.org - - + + - - - org.apache.maven.plugins - maven-site-plugin - 3.6 - - - org.apache.maven.wagon - wagon-webdav-jackrabbit - 2.10 - - - - - + - com.blackducksoftware.integration - hub-maven-plugin - 1.4.0 - false - - ${project.name} - ${project.basedir} - - - - create-bdio-file - package - - createHubOutput - - - + org.apache.maven.plugins + maven-site-plugin + 3.6 + + + org.apache.maven.wagon + wagon-webdav-jackrabbit + 2.10 + + @@ -61,30 +39,69 @@ + + + org.codehaus.mojo + build-helper-maven-plugin + 1.10 + + + add-source + generate-sources + + add-source + + + + src/main/java + src/main/java-gen + + + + + add-resource + generate-resources + + add-resource + + + + + src/main/resources + + + src/main/resources-gen + + + + + + + + + javax.servlet + javax.servlet-api + 3.1.0 + com.att.eelf eelf-core - 0.0.1 + 1.0.0 org.slf4j slf4j-api 1.7.6 - - org.yaml snakeyaml 1.15 - - - org.openecomp.ncomp.utils ncomp-utils-java @@ -97,10 +114,10 @@ - - org.openecomp.ncomp.maven - ncomp-maven-base - 1.1.0-SNAPSHOT - ../../dcae-org.openecomp.ncomp.maven/ncomp-maven-base - + + org.openecomp.ncomp.maven + ncomp-maven-base + 1.1.0-SNAPSHOT + ../../dcae-org.openecomp.ncomp.maven/ncomp-maven-base + diff --git a/operation-utils/src/main/java-gen/org/openecomp/logger/GenericMessagesMessageEnum.java b/operation-utils/src/main/java-gen/org/openecomp/logger/GenericMessagesMessageEnum.java new file mode 100644 index 0000000..060a196 --- /dev/null +++ b/operation-utils/src/main/java-gen/org/openecomp/logger/GenericMessagesMessageEnum.java @@ -0,0 +1,25 @@ + +package org.openecomp.logger; + +import com.att.eelf.i18n.EELFResourceManager; +import org.openecomp.logger.EcompMessageEnum; + +public enum GenericMessagesMessageEnum implements EcompMessageEnum { + + ECOMP_GENERAL_EXCEPTION, + ECOMP_GENERAL_ERROR, + ECOMP_GENERAL_INFO, + ECOMP_GENERAL_WARNING, + ECOMP_REMOTE_CALL_OK, + ECOMP_REQUEST_OK, + ECOMP_REMOTE_CALL_ERROR, + ECOMP_REQUEST_ERROR, + ECOMP_MISSING_REQUESTID, + ECOMP_LOGGER_NON_EMPTY_STACK, + ECOMP_LOGGER_POP_ON_EMPTY_STACK, + ECOMP_LOGGER_TOP_ON_EMPTY_STACK; + + static { + EELFResourceManager.loadMessageBundle("org/openecomp/logger/GenericMessages"); + } +} diff --git a/operation-utils/src/main/java/org/openecomp/entity/EcompSubComponentInstance.java b/operation-utils/src/main/java/org/openecomp/entity/EcompSubComponentInstance.java index 9b54bdd..2654dea 100644 --- a/operation-utils/src/main/java/org/openecomp/entity/EcompSubComponentInstance.java +++ b/operation-utils/src/main/java/org/openecomp/entity/EcompSubComponentInstance.java @@ -47,7 +47,8 @@ public class EcompSubComponentInstance { return uuid; } - public static void initialize() { + public static void initialize(String instanceID) { + uuid = instanceID; if (serverIP == null || serverName == null || ("").equals(serverIP) || ("").equals(serverName)) { try { InetAddress server = InetAddress.getLocalHost(); @@ -60,4 +61,8 @@ public class EcompSubComponentInstance { } } } + + public static void initialize() { + initialize(UUID.randomUUID().toString()); + } } diff --git a/operation-utils/src/main/java/org/openecomp/logger/EcompException.java b/operation-utils/src/main/java/org/openecomp/logger/EcompException.java new file mode 100644 index 0000000..712c1ed --- /dev/null +++ b/operation-utils/src/main/java/org/openecomp/logger/EcompException.java @@ -0,0 +1,53 @@ + +/*- + * ============LICENSE_START========================================== + * OPENECOMP - DCAE + * =================================================================== + * 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.logger; + +import com.att.eelf.i18n.EELFResourceManager; + +public class EcompException extends RuntimeException { + public EcompMessageEnum msgEnum; + public String[] args; + static final long serialVersionUID = -4904961953794640177L; + + protected EcompException(EcompMessageEnum msgEnum, String message) { + super(message); + this.msgEnum = msgEnum; + } + + protected EcompException(EcompMessageEnum msgEnum, String message, Throwable t) { + super(message, t); + this.msgEnum = msgEnum; + } + + public static EcompException create(EcompMessageEnum msgEnum, String... args) { + EcompException e = new EcompException(msgEnum, EELFResourceManager.format(msgEnum, args)); + e.args = args; + return e; + } + + public static EcompException create(EcompMessageEnum msgEnum, Throwable t, String... args) { + EcompException e = new EcompException(msgEnum, EELFResourceManager.format(msgEnum, args), t); + e.args = args; + return e; + } + +} diff --git a/operation-utils/src/main/java/org/openecomp/logger/EcompLogger.java b/operation-utils/src/main/java/org/openecomp/logger/EcompLogger.java index 254b06e..476c0c3 100644 --- a/operation-utils/src/main/java/org/openecomp/logger/EcompLogger.java +++ b/operation-utils/src/main/java/org/openecomp/logger/EcompLogger.java @@ -19,16 +19,16 @@ * ============LICENSE_END============================================ */ - package org.openecomp.logger; - - import java.io.PrintWriter; import java.io.StringWriter; import java.util.Date; import java.util.UUID; -import java.util.logging.Logger; + +import javax.servlet.http.HttpServletRequest; + +import com.att.eelf.i18n.EELFResourceManager; import org.slf4j.MDC; @@ -36,20 +36,10 @@ import org.openecomp.entity.EcompOperation; import org.openecomp.entity.EcompOperationEnum; import org.openecomp.entity.EcompSubComponentInstance; import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; import com.att.eelf.configuration.SLF4jWrapper; -/** - * 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 "[| 0) + c = s.toUpperCase().charAt(0); + switch (c) { + case 'I': + return LogCategoryEnum.INFO; + case 'W': + return LogCategoryEnum.WARN; + case 'E': + return LogCategoryEnum.ERROR; + case 'F': + return LogCategoryEnum.FATAL; + } + return LogCategoryEnum.WARN; + } + + @SuppressWarnings("unused") + private void setStart() { + MDC.put("startTime", Long.toString(new Date().getTime())); + } + + @SuppressWarnings("unused") + private void setTimer() { + Date d = new Date(Long.parseLong(MDC.get("startTime"))); + MDC.put(TIMER, Long.toString(new Date().getTime() - d.getTime())); + } + + // endregion + + // region Helpers + + private void prepareMsg(LogCategoryEnum logCategoryEnum, EcompMessageEnum msg) { + prepareMsg(getSeverityLevel(logCategoryEnum), null, null, msg); + } + + private void prepareMsg(String loggingLevel, EcompMessageEnum msg) { + prepareMsg(loggingLevel, null, null, msg); + } + + private void prepareMsg(String loggingLevel, String serviceNamep, String timer, EcompMessageEnum msg) { + String reqId = MDC.get(REQUEST_ID); + String svcId = MDC.get(SERVICE_INSTANCE_ID); + + if (reqId == null || reqId.isEmpty()) { + MDC.put(REQUEST_ID, UUID.randomUUID().toString()); + } + + if (svcId == null || svcId.isEmpty()) { + MDC.put(SERVICE_INSTANCE_ID, DUMMY_SERVICE_INSTANCE_VALUE); + } + + if (timer != null) { + MDC.put(TIMER, timer); + } else { + MDC.remove(TIMER); + } + + String instance = MDC.get(INSTANCE_UUID); + if (instance == null || instance.isEmpty()) { + MDC.put(INSTANCE_UUID, EcompSubComponentInstance.getUuid()); + } + + MDC.put(ALERT_SEVERITY, getSeverityLevel(loggingLevel)); + MDC.put(SERVER_IP, EcompSubComponentInstance.getServerIP()); + MDC.put(FQDN, EcompSubComponentInstance.getServerName()); + + if (null != msg) { + MDC.put(RESPONSE_CODE, EELFResourceManager.getIdentifier(msg)); + MDC.put(RESPONSE_DESCRIPTION, EELFResourceManager.getDescription(msg)); + } + } + + private void prepareMsg(String loggingLevel) { + prepareMsg(loggingLevel, null, null, null); + } + + 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 getSeverityLevel(LogCategoryEnum logCategoryEnum) { + String severity; + // According to the Nagios alerting: 0=OK; 1=WARNING; 2=UNKOWN; + // 3=CRITICAL + switch (logCategoryEnum) { + case FATAL: + severity = "2"; + break; + case ERROR: + severity = "3"; + break; + case WARN: + severity = "1"; + break; + default: + severity = "0"; + break; + } + return severity; + } + + private String normalize(String input) { + if (input == null) { + return null; + } + String result = input.replace('|', '!'); + result = result.replace("\n", " - "); + return result; + } + + private String[] normalizeArray(String[] args) { + for (int i = 0; i < args.length; i++) { + args[i] = normalize(args[i]); + } + return args; } + private String getNormalizedStackTrace(Throwable t) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + t.printStackTrace(pw); + return sw.toString().replace('|', '!').replace("\n", " - "); + } + + // endregion + public void newRequestId() { String uuid = UUID.randomUUID().toString(); - MDC.put (REQUEST_ID, uuid); + MDC.put(REQUEST_ID, uuid); } - - public void setRequestId(String requestId) { - MDC.put (REQUEST_ID, requestId); + public boolean isDebugEnabled() { + return errorLogger.isDebugEnabled(); } - + public void setRemoteHost(String remote) { - MDC.put (REMOTE_HOST, remote); + MDC.put(REMOTE_HOST, remote); } - + public void setInstanceId(String instance) { - MDC.put (INSTANCE_UUID, instance); + MDC.put(INSTANCE_UUID, instance); + } + + static boolean isNullOrEmpty(String value) { + return (value == null || value.isEmpty()) ? true : false; } + public void missingRequestId(HttpServletRequest request) { + warn(GenericMessagesMessageEnum.ECOMP_MISSING_REQUESTID, request.getRemoteHost()); + } + + public String getRequestId() { + return MDC.get(REQUEST_ID); + } + + @Override + public String toString() { + return MDC.getCopyOfContextMap().toString(); + } } diff --git a/operation-utils/src/main/java/org/openecomp/logger/GenericMessageEnum.java b/operation-utils/src/main/java/org/openecomp/logger/GenericMessageEnum.java deleted file mode 100644 index deed808..0000000 --- a/operation-utils/src/main/java/org/openecomp/logger/GenericMessageEnum.java +++ /dev/null @@ -1,38 +0,0 @@ - -/*- - * ============LICENSE_START========================================== - * OPENECOMP - DCAE - * =================================================================== - * 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.logger; - -import com.att.eelf.i18n.EELFResourceManager; - -public enum GenericMessageEnum implements EcompMessageEnum { - GENERAL_INFO, - GENERAL_WARNING, - GENERAL_ERROR, - GENERAL_EXCEPTION, - AUDIT_BEGIN, - AUDIT_END, - METRICS_BEGIN, - METRICS_END; - static { - EELFResourceManager.loadMessageBundle("GenericMessages"); - } -} diff --git a/operation-utils/src/main/java/org/openecomp/logger/LogCategoryEnum.java b/operation-utils/src/main/java/org/openecomp/logger/LogCategoryEnum.java new file mode 100644 index 0000000..dcc69e0 --- /dev/null +++ b/operation-utils/src/main/java/org/openecomp/logger/LogCategoryEnum.java @@ -0,0 +1,30 @@ + +/*- + * ============LICENSE_START========================================== + * OPENECOMP - DCAE + * =================================================================== + * 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.logger; + +public enum LogCategoryEnum { + //0=INFO, 1=WARN, 2=ERROR, 3=FATAL + INFO, + WARN, + ERROR, + FATAL +} diff --git a/operation-utils/src/main/java/org/openecomp/logger/StatusCodeEnum.java b/operation-utils/src/main/java/org/openecomp/logger/StatusCodeEnum.java new file mode 100644 index 0000000..53b549b --- /dev/null +++ b/operation-utils/src/main/java/org/openecomp/logger/StatusCodeEnum.java @@ -0,0 +1,27 @@ + +/*- + * ============LICENSE_START========================================== + * OPENECOMP - DCAE + * =================================================================== + * 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.logger; + +public enum StatusCodeEnum { + COMPLETE, + ERROR +} diff --git a/operation-utils/src/main/java/org/openecomp/logger/Stopwatch.java b/operation-utils/src/main/java/org/openecomp/logger/Stopwatch.java new file mode 100644 index 0000000..e86713d --- /dev/null +++ b/operation-utils/src/main/java/org/openecomp/logger/Stopwatch.java @@ -0,0 +1,253 @@ + +/*- + * ============LICENSE_START========================================== + * OPENECOMP - DCAE + * =================================================================== + * 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.logger; + +import static com.att.eelf.configuration.Configuration.MDC_BEGIN_TIMESTAMP; +import static com.att.eelf.configuration.Configuration.MDC_ELAPSED_TIME; +import static com.att.eelf.configuration.Configuration.MDC_END_TIMESTAMP; +import static com.att.eelf.configuration.Configuration.MDC_TARGET_ENTITY; +import static com.att.eelf.configuration.Configuration.MDC_TARGET_SERVICE_NAME; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; + +import org.slf4j.MDC; + + +/** + * This class is used to time events to determine their duration. The stop watch allows for the same types of operations + * as a real stop watch, that is, it allows the timing to be stopped, started, cleared, and read. The accumulated time + * is the total of all times between start and stop events. The watch can be repeatedly stopped and restarted, and will + * accumulate all durations between start/stop pairs. + */ +public class Stopwatch { + + public static String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; + public static final TimeZone utc = TimeZone.getTimeZone("UTC"); + public static final SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT); + public static EcompLogger ecompLogger = EcompLogger.getEcompLogger(); + + /** + * This is the object that maintains our state on the thread local storage + */ + public static class StopwatchState { + /** + * The accumulated duration + */ + private long duration; + + /** + * Indicates that the watch is running + */ + private boolean running = false; + + /** + * The last recorded start time + */ + private long startTime; + + public String target; + + public String op; + + @Override + public String toString() { + return "StopwatchState [duration=" + duration + ", running=" + running + ", startTime=" + startTime + "]"; + } + + } + + public static class StopwatchStateStack { + private List l = new ArrayList(); + + public StopwatchState top() { +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": top 1 " + l); + if (l.size() == 0) { + ecompLogger.warn(GenericMessagesMessageEnum.ECOMP_LOGGER_TOP_ON_EMPTY_STACK); +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": top empty"); + push(null,null); + } +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": top 2 " + l); + return l.get(l.size()-1); + } + + public void push(String targetEntity, String target) { + l.add(new StopwatchState()); + top().op = targetEntity; + top().target = target; +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": push 2 " + l); + } + + public void pop() { +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": pop 1 " + l); + if (l.size() == 0) { + ecompLogger.warn(GenericMessagesMessageEnum.ECOMP_LOGGER_POP_ON_EMPTY_STACK); + return; + } + l.remove(l.size()-1); + } + + public void clear() { +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": clear 1" + l); + l.clear(); + } + } + + /** + * Thread local storage wrapper + */ + private static ThreadLocal tls = new ThreadLocal<>(); + + static { + isoFormatter.setTimeZone(utc); + } + + /** + * Looks up the Thread Local storage object containing the Stopwatch state, and creates it if it does not already + * exist. + * + * @return The state object + */ + private static StopwatchStateStack getState() { + StopwatchStateStack state = tls.get(); + if (state == null) { + state = new StopwatchStateStack(); + tls.set(state); + } + return state; + } + + /** + * Clears (and possibly stops) the watch. + */ + public static void clear() { + getState().clear(); + } + + /** + * The accumulated duration of the watch (in nano-seconds) + * + * @return The accumulated time + */ + public static long getDuration() { + StopwatchState state = getState().top(); + return state.duration; + } + + /** + * Determines if the stopwatch is currently running or not + * + * @return True if the watch is running + */ + public static boolean isRunning() { + StopwatchState state = getState().top(); + return state.running; + } + + /** + * Starts the watch if not already running. + */ + public static void start() { + StopwatchState state = getState().top(); + if (!state.running) { + state.running = true; + state.startTime = System.currentTimeMillis(); + MDC.put(MDC_BEGIN_TIMESTAMP, isoFormatter.format(new Date(state.startTime))); + } + } + + /** + * Stops the accumulation of time on the watch if running + */ + public static void stop() { + StopwatchState state = getState().top(); + if (state.running) { + long stopTime = System.currentTimeMillis(); + state.duration += (stopTime - state.startTime); + state.running = false; + MDC.put(MDC_END_TIMESTAMP,isoFormatter.format(new Date(stopTime))); + MDC.put(MDC_ELAPSED_TIME, String.valueOf(state.duration)); + } + if (!EcompLogger.isNullOrEmpty(state.target)) + MDC.put(MDC_TARGET_ENTITY, state.target); + if (state.op != null) + MDC.put(MDC_TARGET_SERVICE_NAME, state.op); + } + + /** + * Gets the amount of time since the stop watch was last started without stopping the watch or accumulating the + * previous time . + */ + public static double getCurrentDuration() { + StopwatchState state = getState().top(); + if (state.running) { + return (System.currentTimeMillis() - state.startTime); + } + return 0L; + } + + public static void pushNewWatch(String targetEntity, String target) { +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": pushNewWatch 1" + getState().l); + getState().push(targetEntity,target); +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": pushNewWatch 2" + getState().l); + } + + public static void popWatch() { + stop(); + getState().pop(); + } + + public static void clearAndStart() { +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + " clearAndStart 1" + getState().l); + clear(); +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": clearAndStart 2" + getState().l); + pushAndStart(null,null); +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": clearAndStart 3" + getState().l); + } + + public static void stopAndPop() { +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": stopAndPop 1" + getState().l); + stop(); +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": stopAndPop 2" + getState().l); + popWatch(); +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": stopAndPop 3" + getState().l); + } + + public static void pushAndStart(String targetEntity, String target) { +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": pushAndStart 1" + getState().l); + pushNewWatch(targetEntity,target); +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": pushAndStart 2" + getState().l); + start(); +// System.out.println("WWWWWW: " + Thread.currentThread().getName() + ": pushAndStart 3" + getState().l); + } + + public static boolean emptyStack() { + return getState().l.size() == 0; + } + + public static String getTopTarget() { + return getState().top().target; + } +} diff --git a/operation-utils/src/main/java/org/openecomp/utils/YamlToJava.java b/operation-utils/src/main/java/org/openecomp/utils/YamlToJava.java index 4577e06..fb3b1f4 100644 --- a/operation-utils/src/main/java/org/openecomp/utils/YamlToJava.java +++ b/operation-utils/src/main/java/org/openecomp/utils/YamlToJava.java @@ -42,51 +42,62 @@ import org.openecomp.ncomp.utils.PropertyUtil; import org.openecomp.ncomp.webservice.utils.FileUtils; public class YamlToJava { - -// package org.openecomp.operation.logging.usecases; -// -// import org.openecomp.logger.EcompMessageEnum; -// import com.att.eelf.i18n.EELFResourceManager; -// -// public enum MyMessageEnum implements EcompMessageEnum { -// // Api Handler Messages -// FOOBAR; -// -// static { -// EELFResourceManager.loadMessageBundle("foobar"); -// } -// } - + + // package org.openecomp.operation.logging.usecases; + // + // import org.openecomp.logger.EcompMessageEnum; + // import com.att.eelf.i18n.EELFResourceManager; + // + // public enum MyMessageEnum implements EcompMessageEnum { + // // Api Handler Messages + // FOOBAR; + // + // static { + // EELFResourceManager.loadMessageBundle("foobar"); + // } + // } + + static public void convert(String yamlFileName, String outputDir, String packageName) { + convert(yamlFileName, outputDir, outputDir, packageName); + } + @SuppressWarnings("unchecked") - static public void convert(String yamlFileName, String outputSourceRootDir, String packageName) { + static public void convert(String yamlFileName, String propertiesOutputDirectory, String enumOutputDirectory, + String packageName) { try { - if (! (new File(yamlFileName).exists())) { + System.out.println("Enterting YAML Convert)"); + if (!(new File(yamlFileName).exists())) { System.err.println(yamlFileName + " does not exists"); return; } DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); Yaml y = new Yaml(options); - Map m = (Map) y.load(FileUtils.filename2stream(yamlFileName, null)); + Map m = (Map) y.load(FileUtils.filename2stream(yamlFileName, null)); File f = new File(yamlFileName); String name = f.getName().replace(".yaml", ""); m.put("name", name); m.put("packageName", packageName); - String ofile1 = outputSourceRootDir + "/" + name + ".properties"; + String resourcePath = packageName.replace('.', '/'); + m.put("resourcePath", resourcePath); + String ofile1 = propertiesOutputDirectory + "/" + name + ".properties"; + System.out.println("Properties file path => " + ofile1); OutputStreamWriter w; SimpleTemplateEngine engine = new SimpleTemplateEngine(); if (m.containsKey("messages")) { w = FileUtils.filename2writer(ofile1); w.append(engine.createTemplate(getTemplate("properties_template")).make(m).toString()); w.close(); - String ofile2 = outputSourceRootDir + "/" + name + "MessageEnum.java"; + String ofile2 = enumOutputDirectory + "/" + name + "MessageEnum.java"; + System.out.println("Message Enum file path => " + ofile2); w = FileUtils.filename2writer(ofile2); w.append(engine.createTemplate(getTemplate("messageEnum.java_template")).make(m).toString()); w.close(); } if (m.containsKey("operations")) { - String ofile3 = outputSourceRootDir + "/" + name + "OperationEnum.java"; + String ofile3 = enumOutputDirectory + "/" + name + "OperationEnum.java"; w = FileUtils.filename2writer(ofile3); + System.out.println("Operation Enum file path => " + ofile3); w.append(engine.createTemplate(getTemplate("operationEnum.java_template")).make(m).toString()); w.close(); } @@ -104,31 +115,63 @@ public class YamlToJava { ByteArrayOutputStream o = new ByteArrayOutputStream(); FileUtils.copyStream(in, o); return o.toString(); -} + } public static void main(String[] args) throws IOException { - Properties props = new Properties(); - String pname = "GenericMessages.properties"; - String fname = "src/main/resources/GenericMessages.yaml"; - props.load(YamlToJava.class.getClassLoader().getResourceAsStream(pname)); + for (int i = 0; i < args.length; i++) { + System.out.println(" Argument " + Integer.toString(i) + " ==> " + args[i]); + } + + switch (args.length) { + case 1: + String baseDir = findBaseDir(args[0]); + Map m = file2yaml(args[0]); + String javaDest = (String) (m.containsKey("java-root") ? m.get("java-root") : "src/main/java-gen"); + String resourcesDest = (String) (m.containsKey("resources-root") ? m.get("resources-root") + : "src/main/resources-gen"); + if (! javaDest.startsWith("/")) javaDest = baseDir + "/" + javaDest; + if (! resourcesDest.startsWith("/")) resourcesDest = baseDir + "/" + resourcesDest; + String packageName = (String) m.get("package-name"); + if (packageName == null) { + System.err.println("No package-name attribute in: " + args[0]); + System.exit(2); + } + String packageDir = "/" + packageName.replace(".", "/"); + convert(args[0], resourcesDest + packageDir, javaDest + packageDir, packageName); + break; + case 4: + convert(args[0], args[1], args[2], args[3]); + break; + case 5: + convert(args[1], args[2], args[3], args[4]); + break; + default: + System.err.println("Invalid arguments, expected --> yamlFileName"); + System.exit(2); + } + } + + private static String findBaseDir(String filename) { + File f = new File(filename); + f = f.getParentFile(); + while (f != null) { + File pom = new File(f,"pom.xml"); + if (pom.exists()) return f.getAbsolutePath(); + f = f.getParentFile(); + } + return "."; + } + + @SuppressWarnings("unchecked") + private static Map file2yaml(String yamlFileName) { + if (!(new File(yamlFileName).exists())) { + System.err.println(yamlFileName + " does not exists"); + System.exit(2); + } DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); Yaml y = new Yaml(options); - JSONObject j = new JSONObject(); - for (Object k : props.keySet()) { - String a[] = props.getProperty((String) k).split("\\|"); - JSONObject j1 = new JSONObject(); - j.put((String) k, j1); - j1.put("errorCode", a[0]); - j1.put("messageFormat", a[1]); - j1.put("resolution", a[2]); - j1.put("description", a[3].trim()); - } - - Object data = y.load(j.toString()); - OutputStreamWriter w = FileUtils.filename2writer(fname); - w.append(y.dump(data) + "\n"); - w.close(); + return (Map) y.load(FileUtils.filename2stream(yamlFileName, null)); } } diff --git a/operation-utils/src/main/resources-gen/org/openecomp/logger/GenericMessages.properties b/operation-utils/src/main/resources-gen/org/openecomp/logger/GenericMessages.properties new file mode 100644 index 0000000..ae5ee3d --- /dev/null +++ b/operation-utils/src/main/resources-gen/org/openecomp/logger/GenericMessages.properties @@ -0,0 +1,72 @@ + +ECOMP_GENERAL_EXCEPTION=\ + ECOMP-GENERAL-EXCEPTION-5404W|\ + {0}|\ + Please check other logs for more detailed info|\ + General exception + +ECOMP_GENERAL_ERROR=\ + ECOMP-GENERAL-ERROR-5403E|\ + {0}|\ + Please check other logs for more detailed info|\ + General error + +ECOMP_GENERAL_INFO=\ + ECOMP-GENERAL-INFO-5401I|\ + {0}|\ + Please check other logs for more detailed info|\ + General info + +ECOMP_GENERAL_WARNING=\ + ECOMP-GENERAL-WARNING-5402W|\ + {0}|\ + Please check other logs for more detailed info|\ + General warning + +ECOMP_REMOTE_CALL_OK=\ + ECOMP-REMOTE-CALL-OK-2000I|\ + |\ + No resolution needed|\ + Remote Call Succeess + +ECOMP_REQUEST_OK=\ + ECOMP-REQUEST-OK-2000I|\ + |\ + No resolution needed|\ + Request Success + +ECOMP_REMOTE_CALL_ERROR=\ + ECOMP-REMOTE-CALL-ERROR-4000W|\ + {0}|\ + No resolution needed|\ + Remote Call Failed + +ECOMP_REQUEST_ERROR=\ + ECOMP-REQUEST-ERROR-4000I|\ + {0}|\ + No resolution needed|\ + Request Failed + +ECOMP_MISSING_REQUESTID=\ + ECOMP-MISSING-REQUESTID-3401W|\ + Missing request id from {0}|\ + Need to get north bound entity to provide request ID per ECOMP logging requirements|\ + Got a north bound request that was missing a request ID. + +ECOMP_LOGGER_NON_EMPTY_STACK=\ + ECOMP-LOGGER-NON-EMPTY-STACK-4401W|\ + |\ + Development bug.|\ + Component recorded an Audit End with an non empty stack + +ECOMP_LOGGER_POP_ON_EMPTY_STACK=\ + ECOMP-LOGGER-POP-ON-EMPTY-STACK-4402W|\ + |\ + Development bug.|\ + Component performed a Pop on empty stack + +ECOMP_LOGGER_TOP_ON_EMPTY_STACK=\ + ECOMP-LOGGER-TOP-ON-EMPTY-STACK-4403W|\ + |\ + Development bug.|\ + Component performed a Top on empty stack diff --git a/operation-utils/src/main/resources/GenericMessages.properties b/operation-utils/src/main/resources/GenericMessages.properties index b7322f8..d3dc81a 100644 --- a/operation-utils/src/main/resources/GenericMessages.properties +++ b/operation-utils/src/main/resources/GenericMessages.properties @@ -41,7 +41,12 @@ GENERAL_ERROR=\ ECOMP-GENERAL-ERROR-5403|\ {0}|\ Please check other logs for more detailed info|\ - General error + General error +GENERAL_EXCEPTION=\ + ECOMP-GENERAL-ERROR-5404|\ + {0}|\ + Please check other logs for more detailed info|\ + General exception AUDIT_BEGIN=\ ECOMP-GENERAL-5403|\ Entering method|\ @@ -62,4 +67,8 @@ METRICS_END=\ Exiting method|\ No resolution needed|\ Exiting method - +MISSING_REQUESTID=\ + ECOMP-MISSING_REQUESTID-5404|\ + from {0}|\ + No resolution needed|\ + missing request id diff --git a/operation-utils/src/main/resources/GenericMessages.yaml b/operation-utils/src/main/resources/GenericMessages.yaml index df592e2..71624d6 100644 --- a/operation-utils/src/main/resources/GenericMessages.yaml +++ b/operation-utils/src/main/resources/GenericMessages.yaml @@ -1,36 +1,65 @@ -GENERAL_ERROR: - errorCode: ECOMP-GENERAL-ERROR-5403 - messageFormat: '{0}' - resolution: Please check other logs for more detailed info - description: General error -GENERAL_INFO: - errorCode: ECOMP-GENERAL-INFO-5401 - messageFormat: '{0}' - resolution: Please check other logs for more detailed info - description: General info -GENERAL_WARNING: - errorCode: ECOMP-GENERAL-WARNING-5402 - messageFormat: '{0}' - resolution: Please check other logs for more detailed info - description: General warning -METRICS_END: - errorCode: ECOMP-GENERAL-5404 - messageFormat: Exiting method - resolution: No resolution needed - description: Exiting method -AUDIT_END: - errorCode: ECOMP-GENERAL-5404 - messageFormat: Exiting method - resolution: No resolution needed - description: Exiting method -AUDIT_BEGIN: - errorCode: ECOMP-GENERAL-5403 - messageFormat: Entering method - resolution: No resolution needed - description: Entering method -METRICS_BEGIN: - errorCode: ECOMP-GENERAL-5403 - messageFormat: Entering method - resolution: No resolution needed - description: Entering method +package-name: org.openecomp.logger +java-root: src/main/java-gen +resources-root: src/main/resources-gen +messages: + ECOMP-GENERAL-EXCEPTION: + errorCode: 5404W + messageFormat: "{0}" + resolution: Please check other logs for more detailed info + description: General exception + ECOMP-GENERAL-ERROR: + errorCode: 5403E + messageFormat: "{0}" + resolution: Please check other logs for more detailed info + description: General error + ECOMP-GENERAL-INFO: + errorCode: 5401I + messageFormat: "{0}" + resolution: Please check other logs for more detailed info + description: General info + ECOMP-GENERAL-WARNING: + errorCode: 5402W + messageFormat: "{0}" + resolution: Please check other logs for more detailed info + description: General warning + ECOMP-REMOTE-CALL-OK: + errorCode: 2000I + messageFormat: "" + resolution: No resolution needed + description: Remote Call Succeess + ECOMP-REQUEST-OK: + errorCode: 2000I + messageFormat: "" + resolution: No resolution needed + description: Request Success + ECOMP-REMOTE-CALL-ERROR: + errorCode: 4000W + messageFormat: "{0}" + resolution: No resolution needed + description: Remote Call Failed + ECOMP-REQUEST-ERROR: + errorCode: 4000I + messageFormat: "{0}" + resolution: No resolution needed + description: Request Failed + ECOMP-MISSING-REQUESTID: + errorCode: 3401W + messageFormat: Missing request id from {0} + resolution: Need to get north bound entity to provide request ID per ECOMP logging requirements + description: Got a north bound request that was missing a request ID. + ECOMP-LOGGER-NON-EMPTY-STACK: + errorCode: 4401W + messageFormat: "" + resolution: Development bug. + description: Component recorded an Audit End with an non empty stack + ECOMP-LOGGER-POP-ON-EMPTY-STACK: + errorCode: 4402W + messageFormat: "" + resolution: Development bug. + description: Component performed a Pop on empty stack + ECOMP-LOGGER-TOP-ON-EMPTY-STACK: + errorCode: 4403W + messageFormat: "" + resolution: Development bug. + description: Component performed a Top on empty stack \ No newline at end of file diff --git a/operation-utils/src/main/resources/logback.xml b/operation-utils/src/main/resources/logback.xml new file mode 100644 index 0000000..5dde533 --- /dev/null +++ b/operation-utils/src/main/resources/logback.xml @@ -0,0 +1,351 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ${defaultPattern} + + + + + + + + + + + + ${logDirectory}/${generalLogName}.log + + ${logDirectory}/${generalLogName}.%i.log.zip + + 1 + 20 + + + 2500KB + + + ${defaultPattern} + + + + + 256 + + + + + + ${logDirectory}/${securityLogName}.log + + ${logDirectory}/${securityLogName}.%i.log.zip + + 1 + 20 + + + 2500KB + + + ${defaultPattern} + + + + + 256 + 0 + + + + + + ${logDirectory}/${performanceLogName}.log + + ${logDirectory}/${performanceLogName}.%i.log.zip + + 1 + 20 + + + 2500KB + + + ${defaultPattern} + + + + 256 + + + + + + ${logDirectory}/${serverLogName}.log + + ${logDirectory}/${serverLogName}.%i.log.zip + + 1 + 20 + + + 2500KB + + + ${defaultPattern} + + + + 256 + + + + + + + ${logDirectory}/${policyLogName}.log + + ${logDirectory}/${policyLogName}.%i.log.zip + + 1 + 20 + + + 2500KB + + + ${defaultPattern} + + + + 256 + + + + + + + + ${logDirectory}/${auditLogName}.log + + ${logDirectory}/${auditLogName}.%i.log.zip + + 1 + 20 + + + 2500KB + + + ${auditLoggerPattern} + + + + 256 + + + + + ${logDirectory}/${metricsLogName}.log + + ${logDirectory}/${metricsLogName}.%i.log.zip + + 1 + 20 + + + 2500KB + + + + ${metricsLoggerPattern} + + + + + + 256 + + + + + ${logDirectory}/${errorLogName}.log + + ${logDirectory}/${errorLogName}.%i.log.zip + + 1 + 20 + + + 2500KB + + + ${errorLoggerPattern} + + + + + 256 + + + + + ${debugLogDirectory}/${debugLogName}.log + + ${debugLogDirectory}/${debugLogName}.%i.log.zip + + 1 + 20 + + + 2500KB + + + ${debugLoggerPattern} + + + + + 256 + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/operation-utils/src/main/resources/messageEnum.java_template b/operation-utils/src/main/resources/messageEnum.java_template index e0b3c12..d6c7884 100644 --- a/operation-utils/src/main/resources/messageEnum.java_template +++ b/operation-utils/src/main/resources/messageEnum.java_template @@ -9,10 +9,10 @@ public enum ${name}MessageEnum implements EcompMessageEnum { def last messages.each { n, v -> last = n } messages.each { n, v -> %> - $n${n==last ? ";" : ","}\ + ${n.replace('-','_')}${n==last ? ";" : ","}\ <% } %> static { - EELFResourceManager.loadMessageBundle("${packageName}.$name"); + EELFResourceManager.loadMessageBundle("${resourcePath}/$name"); } } diff --git a/operation-utils/src/main/resources/operationEnum.java_template b/operation-utils/src/main/resources/operationEnum.java_template index 9ec9d3d..4bf3ec0 100644 --- a/operation-utils/src/main/resources/operationEnum.java_template +++ b/operation-utils/src/main/resources/operationEnum.java_template @@ -8,6 +8,19 @@ public enum ${name}OperationEnum implements EcompOperationEnum { def last operations.each { n, v -> last = n } operations.each { n, v -> %> - $n${n==last ? ";" : ","}\ -<% } %> + ${n.replaceAll('[-&@#:]','_')}("$n")${n==last ? "" : ","}\ +<% } %> ; + + + private String n; + + private ${name}OperationEnum(String n) { + this.n = n; + } + + @Override + public String toString() { + return n; + } + } diff --git a/operation-utils/src/main/resources/properties_template b/operation-utils/src/main/resources/properties_template index 76b2b48..fa25ca5 100644 --- a/operation-utils/src/main/resources/properties_template +++ b/operation-utils/src/main/resources/properties_template @@ -1,8 +1,8 @@ <% messages.each { n, v -> %> -$n=\\ - $v.errorCode|\\ +${n.replace('-','_')}=\\ + $n-$v.errorCode|\\ $v.messageFormat|\\ $v.resolution|\\ $v.description -- cgit 1.2.3-korg