diff --git a/agent/src/main/java/com/microsoft/applicationinsights/agent/internal/config/builder/XmlAgentConfigurationBuilder.java b/agent/src/main/java/com/microsoft/applicationinsights/agent/internal/config/builder/XmlAgentConfigurationBuilder.java index 16a5a5e20d9..c6061a1e8c7 100644 --- a/agent/src/main/java/com/microsoft/applicationinsights/agent/internal/config/builder/XmlAgentConfigurationBuilder.java +++ b/agent/src/main/java/com/microsoft/applicationinsights/agent/internal/config/builder/XmlAgentConfigurationBuilder.java @@ -239,20 +239,22 @@ private void addMethods(ClassInstrumentationData classData, Element classNode) { private Element getTopTag(File configurationFile) throws ParserConfigurationException, IOException, SAXException { DocumentBuilder builder = createDocumentBuilder(); - Document doc = builder.parse(new FileInputStream(configurationFile)); - doc.getDocumentElement().normalize(); + try (final FileInputStream fis = new FileInputStream(configurationFile)) { + Document doc = builder.parse(fis); + doc.getDocumentElement().normalize(); - NodeList topTags = doc.getElementsByTagName(MAIN_TAG); - if (topTags == null || topTags.getLength() == 0) { - return null; - } + NodeList topTags = doc.getElementsByTagName(MAIN_TAG); + if (topTags == null || topTags.getLength() == 0) { + return null; + } - Node topNodeTag = topTags.item(0); - if (topNodeTag.getNodeType() != Node.ELEMENT_NODE) { - return null; - } + Node topNodeTag = topTags.item(0); + if (topNodeTag.getNodeType() != Node.ELEMENT_NODE) { + return null; + } - return (Element) topNodeTag; + return (Element) topNodeTag; + } } private DocumentBuilder createDocumentBuilder() throws ParserConfigurationException { diff --git a/azure-application-insights-spring-boot-starter/src/main/java/com/microsoft/applicationinsights/autoconfigure/HeartBeatProvider/SpringBootHeartBeatProvider.java b/azure-application-insights-spring-boot-starter/src/main/java/com/microsoft/applicationinsights/autoconfigure/HeartBeatProvider/SpringBootHeartBeatProvider.java index 60c447a5a16..4104c822c8a 100644 --- a/azure-application-insights-spring-boot-starter/src/main/java/com/microsoft/applicationinsights/autoconfigure/HeartBeatProvider/SpringBootHeartBeatProvider.java +++ b/azure-application-insights-spring-boot-starter/src/main/java/com/microsoft/applicationinsights/autoconfigure/HeartBeatProvider/SpringBootHeartBeatProvider.java @@ -88,8 +88,9 @@ public Boolean call() { } } catch (Exception e) { - InternalLogger.INSTANCE.warn("Failed to obtain heartbeat property, stack trace" - + "is: %s", ExceptionUtils.getStackTrace(e)); + if (InternalLogger.INSTANCE.isWarnEnabled()) { + InternalLogger.INSTANCE.warn("Failed to obtain heartbeat property: %s", ExceptionUtils.getStackTrace(e)); + } } } return hasSetValues; diff --git a/core/src/main/java/com/microsoft/applicationinsights/TelemetryClient.java b/core/src/main/java/com/microsoft/applicationinsights/TelemetryClient.java index dcf6b7c8463..dc078532f87 100644 --- a/core/src/main/java/com/microsoft/applicationinsights/TelemetryClient.java +++ b/core/src/main/java/com/microsoft/applicationinsights/TelemetryClient.java @@ -520,6 +520,11 @@ private TelemetryContext createInitializedContext() { ctx.getCloud().setRole(roleName); } for (ContextInitializer init : configuration.getContextInitializers()) { + if (init == null) { // since collection reference is exposed, we need a null check here + InternalLogger.INSTANCE.warn("Found null ContextInitializer in configuration. Skipping..."); + continue; + } + try { init.initialize(ctx); } catch (ThreadDeath td) { @@ -527,9 +532,7 @@ private TelemetryContext createInitializedContext() { } catch (Throwable t) { try { if (InternalLogger.INSTANCE.isErrorEnabled()) { - InternalLogger.INSTANCE.error("Exception in context initializer%s: %s", - init == null ? " (context initializer is null)" : ", "+init.getClass().getSimpleName(), - ExceptionUtils.getStackTrace(t)); + InternalLogger.INSTANCE.error("Exception in context initializer, %s: %s", init.getClass().getSimpleName(), ExceptionUtils.getStackTrace(t)); } } catch (ThreadDeath td) { throw td; diff --git a/core/src/main/java/com/microsoft/applicationinsights/internal/channel/common/SenderThreadLocalBackOffData.java b/core/src/main/java/com/microsoft/applicationinsights/internal/channel/common/SenderThreadLocalBackOffData.java index 5399265827d..82888784572 100644 --- a/core/src/main/java/com/microsoft/applicationinsights/internal/channel/common/SenderThreadLocalBackOffData.java +++ b/core/src/main/java/com/microsoft/applicationinsights/internal/channel/common/SenderThreadLocalBackOffData.java @@ -53,9 +53,9 @@ final class SenderThreadLocalBackOffData { * @param addMilliseconds The amount of seconds that will be added to the 'large' intervals to distinct between sender threads. */ public SenderThreadLocalBackOffData(long[] backOffTimeoutsInMillis, long addMilliseconds) { - Preconditions.checkNotNull(backOffTimeoutsInMillis, "backOffTimeoutsInSeconds must be not null"); - Preconditions.checkArgument(backOffTimeoutsInMillis.length > 0, "backOffTimeoutsInSeconds must not be empty"); - Preconditions.checkArgument(addMilliseconds >= 0, "addSeconds must not be >= 0"); + Preconditions.checkNotNull(backOffTimeoutsInMillis, "backOffTimeoutsInMillis must be not null"); + Preconditions.checkArgument(backOffTimeoutsInMillis.length > 0, "backOffTimeoutsInMillis must not be empty"); + Preconditions.checkArgument(addMilliseconds >= 0, "addMilliseconds must not be >= 0"); currentBackOffIndex = -1; instanceIsActive = true; diff --git a/core/src/main/java/com/microsoft/applicationinsights/internal/channel/common/SenderThreadsBackOffManager.java b/core/src/main/java/com/microsoft/applicationinsights/internal/channel/common/SenderThreadsBackOffManager.java index 595a8cdc10c..ace711013b5 100644 --- a/core/src/main/java/com/microsoft/applicationinsights/internal/channel/common/SenderThreadsBackOffManager.java +++ b/core/src/main/java/com/microsoft/applicationinsights/internal/channel/common/SenderThreadsBackOffManager.java @@ -83,8 +83,7 @@ public synchronized void stopAllSendersBackOffActivities() { @Override protected SenderThreadLocalBackOffData initialValue() { - int addSeconds = threadsSecondsDifference.incrementAndGet(); - senderThreadLocalData = new SenderThreadLocalBackOffData(backOffTimeoutsInMilliseconds, addSeconds * 1000); + senderThreadLocalData = new SenderThreadLocalBackOffData(backOffTimeoutsInMilliseconds, threadsSecondsDifference.incrementAndGet() * 1000L); registerSenderData(senderThreadLocalData); return senderThreadLocalData; } diff --git a/core/src/main/java/com/microsoft/applicationinsights/internal/channel/common/TransmissionFileSystemOutput.java b/core/src/main/java/com/microsoft/applicationinsights/internal/channel/common/TransmissionFileSystemOutput.java index 5e7a55beb0d..475b701a323 100644 --- a/core/src/main/java/com/microsoft/applicationinsights/internal/channel/common/TransmissionFileSystemOutput.java +++ b/core/src/main/java/com/microsoft/applicationinsights/internal/channel/common/TransmissionFileSystemOutput.java @@ -109,7 +109,7 @@ public TransmissionFileSystemOutput(String folderPath, String maxTransmissionSto DEFAULT_CAPACITY_MEGABYTES, MAX_TRANSMISSION_STORAGE_CAPACITY_NAME, maxTransmissionStorageCapacity); - capacityInBytes = capacityEnforcer.getCurrentValue() * 1024 * 1024; + capacityInBytes = capacityEnforcer.getCurrentValue() * 1024L * 1024L; folder = new File(folderPath); @@ -212,7 +212,7 @@ public Transmission fetchOldestFile() { } public void setCapacity(int suggestedCapacity) { - this.capacityInBytes = capacityEnforcer.normalizeValue(suggestedCapacity) * 1024 * 1024; + this.capacityInBytes = capacityEnforcer.normalizeValue(suggestedCapacity) * 1024L * 1024L; } private List sortOldestLastAndTrim(Collection transmissions, int limit) { diff --git a/core/src/main/java/com/microsoft/applicationinsights/internal/channel/sampling/FixedRateTelemetrySampler.java b/core/src/main/java/com/microsoft/applicationinsights/internal/channel/sampling/FixedRateTelemetrySampler.java index 3ca0228eb6e..db424ea8d8a 100644 --- a/core/src/main/java/com/microsoft/applicationinsights/internal/channel/sampling/FixedRateTelemetrySampler.java +++ b/core/src/main/java/com/microsoft/applicationinsights/internal/channel/sampling/FixedRateTelemetrySampler.java @@ -89,7 +89,7 @@ public void setSamplingPercentage(Double samplingPercentage) { @Override public boolean isSampledIn(Telemetry telemetry) { - Double currentSamplingPercentage = samplingPercentage.get(); + double currentSamplingPercentage = samplingPercentage.get(); if (currentSamplingPercentage < 100.0 - 1.0E-12) { if (telemetry instanceof SupportSampling) { diff --git a/core/src/main/java/com/microsoft/applicationinsights/internal/heartbeat/DefaultHeartBeatPropertyProvider.java b/core/src/main/java/com/microsoft/applicationinsights/internal/heartbeat/DefaultHeartBeatPropertyProvider.java index 0ff3df607ca..3d17432f43c 100644 --- a/core/src/main/java/com/microsoft/applicationinsights/internal/heartbeat/DefaultHeartBeatPropertyProvider.java +++ b/core/src/main/java/com/microsoft/applicationinsights/internal/heartbeat/DefaultHeartBeatPropertyProvider.java @@ -97,8 +97,9 @@ public Boolean call() { } } catch (Exception e) { - InternalLogger.INSTANCE.warn("Failed to obtain heartbeat property, stack trace" - + "is: %s", ExceptionUtils.getStackTrace(e)); + if (InternalLogger.INSTANCE.isWarnEnabled()) { + InternalLogger.INSTANCE.warn("Failed to obtain heartbeat property: %s", ExceptionUtils.getStackTrace(e)); + } } } return hasSetValues; diff --git a/core/src/main/java/com/microsoft/applicationinsights/internal/heartbeat/WebAppsHeartbeatProvider.java b/core/src/main/java/com/microsoft/applicationinsights/internal/heartbeat/WebAppsHeartbeatProvider.java index 89454624ab0..ae4bb5746d9 100644 --- a/core/src/main/java/com/microsoft/applicationinsights/internal/heartbeat/WebAppsHeartbeatProvider.java +++ b/core/src/main/java/com/microsoft/applicationinsights/internal/heartbeat/WebAppsHeartbeatProvider.java @@ -107,8 +107,9 @@ public Boolean call() { } } catch (Exception e) { - InternalLogger.INSTANCE.warn("Failed to obtain heartbeat property, stack trace" - + "is: %s", ExceptionUtils.getStackTrace(e)); + if (InternalLogger.INSTANCE.isWarnEnabled()) { + InternalLogger.INSTANCE.warn("Failed to obtain heartbeat property: %s", ExceptionUtils.getStackTrace(e)); + } } } return hasSetValues; diff --git a/core/src/main/java/com/microsoft/applicationinsights/internal/perfcounter/JniPCConnector.java b/core/src/main/java/com/microsoft/applicationinsights/internal/perfcounter/JniPCConnector.java index 45ee4adcdd7..569d6c6f98b 100644 --- a/core/src/main/java/com/microsoft/applicationinsights/internal/perfcounter/JniPCConnector.java +++ b/core/src/main/java/com/microsoft/applicationinsights/internal/perfcounter/JniPCConnector.java @@ -209,12 +209,10 @@ private static void extractToLocalFolder(File dllOnDisk, String libraryToLoad) t InternalLogger.INSTANCE.trace("Successfully extracted '%s' to local folder", libraryToLoad); } finally { - if (in != null) { - try { - in.close(); - } catch (IOException e) { - InternalLogger.INSTANCE.error("Failed to close input stream for dll extraction: %s", e.toString()); - } + try { + in.close(); + } catch (IOException e) { + InternalLogger.INSTANCE.error("Failed to close input stream for dll extraction: %s", e.toString()); } if (out != null) { try { diff --git a/core/src/main/java/com/microsoft/applicationinsights/internal/shutdown/SDKShutdownActivity.java b/core/src/main/java/com/microsoft/applicationinsights/internal/shutdown/SDKShutdownActivity.java index e4461e40a9e..93845ee90fb 100644 --- a/core/src/main/java/com/microsoft/applicationinsights/internal/shutdown/SDKShutdownActivity.java +++ b/core/src/main/java/com/microsoft/applicationinsights/internal/shutdown/SDKShutdownActivity.java @@ -24,7 +24,6 @@ import java.io.Closeable; import java.util.List; import java.util.ArrayList; -import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; @@ -214,15 +213,17 @@ public void stopAll() { private SDKShutdownAction getShutdownAction() { if (shutdownAction == null) { - synchronized (this) { + synchronized (INSTANCE) { if (shutdownAction == null) { try { - shutdownAction = new SDKShutdownAction(); - Thread t = new Thread(shutdownAction, SDKShutdownActivity.class.getSimpleName()+"-ShutdownHook"); + SDKShutdownAction action = new SDKShutdownAction(); + Thread t = new Thread(action, SDKShutdownActivity.class.getSimpleName()+"-ShutdownHook"); Runtime.getRuntime().addShutdownHook(t); + shutdownAction = action; } catch (Exception e) { - InternalLogger.INSTANCE.error("Error while adding shutdown hook in getShutDownThread call"); - InternalLogger.INSTANCE.trace("Stack trace generated is %s", ExceptionUtils.getStackTrace(e)); + if (InternalLogger.INSTANCE.isErrorEnabled()) { + InternalLogger.INSTANCE.error("Error while adding shutdown hook in getShutDownThread call: %s", ExceptionUtils.getStackTrace(e)); + } } } } diff --git a/core/src/main/java/com/microsoft/applicationinsights/internal/system/SystemInformation.java b/core/src/main/java/com/microsoft/applicationinsights/internal/system/SystemInformation.java index 896aab39b94..c70a7e8ff37 100644 --- a/core/src/main/java/com/microsoft/applicationinsights/internal/system/SystemInformation.java +++ b/core/src/main/java/com/microsoft/applicationinsights/internal/system/SystemInformation.java @@ -36,10 +36,9 @@ public enum SystemInformation { private final static String DEFAULT_PROCESS_NAME = "Java_Process"; - private String processId; + private final String processId = initializeProcessId(); public String getProcessId() { - setProcessId(); return processId; } @@ -51,11 +50,7 @@ public boolean isUnix() { return SystemUtils.IS_OS_UNIX; } - private synchronized void setProcessId() { - if (!Strings.isNullOrEmpty(processId)) { - return; - } - + private String initializeProcessId() { String rawName = ManagementFactory.getRuntimeMXBean().getName(); if (!Strings.isNullOrEmpty(rawName)) { int i = rawName.indexOf("@"); @@ -63,8 +58,7 @@ private synchronized void setProcessId() { String processIdAsString = rawName.substring(0, i); try { Integer.parseInt(processIdAsString); - processId = processIdAsString; - return; + return processIdAsString; } catch (Exception e) { InternalLogger.INSTANCE.error("Failed to fetch process id: '%s'", e.toString()); } @@ -72,6 +66,6 @@ private synchronized void setProcessId() { } // Default - processId = DEFAULT_PROCESS_NAME; + return DEFAULT_PROCESS_NAME; } } diff --git a/core/src/main/java/com/microsoft/applicationinsights/telemetry/Duration.java b/core/src/main/java/com/microsoft/applicationinsights/telemetry/Duration.java index b53afa50396..59221f4de96 100644 --- a/core/src/main/java/com/microsoft/applicationinsights/telemetry/Duration.java +++ b/core/src/main/java/com/microsoft/applicationinsights/telemetry/Duration.java @@ -127,10 +127,10 @@ public int getMilliseconds() { * @return The total milliseconds of the duration. */ public long getTotalMilliseconds() { - return (days * SECONDS_IN_ONE_DAY * 1000) + - (hours * SECONDS_IN_ONE_HOUR * 1000) + - (minutes * SECONDS_IN_ONE_MINUTE * 1000) + - (seconds * 1000) + milliseconds; + return (days * SECONDS_IN_ONE_DAY * 1000L) + + (hours * SECONDS_IN_ONE_HOUR * 1000L) + + (minutes * SECONDS_IN_ONE_MINUTE * 1000L) + + (seconds * 1000L) + milliseconds; } @Override diff --git a/web/src/main/java/com/microsoft/applicationinsights/web/extensibility/initializers/WebOperationNameTelemetryInitializer.java b/web/src/main/java/com/microsoft/applicationinsights/web/extensibility/initializers/WebOperationNameTelemetryInitializer.java index ef4922d8360..8fedd31a17c 100644 --- a/web/src/main/java/com/microsoft/applicationinsights/web/extensibility/initializers/WebOperationNameTelemetryInitializer.java +++ b/web/src/main/java/com/microsoft/applicationinsights/web/extensibility/initializers/WebOperationNameTelemetryInitializer.java @@ -50,14 +50,14 @@ protected void onInitializeTelemetry(Telemetry telemetry) { // region Private private void updateRequestNameIfRequestTelemetry(Telemetry telemetry, String operationName) { - if (!(telemetry instanceof RequestTelemetry)) { + if (!(telemetry instanceof RequestTelemetry)) { // null instanceof Object == false return; } RequestTelemetry requestTelemetry = (RequestTelemetry)telemetry; // We only update the request telemetry name if not already provided by the user. - if (requestTelemetry != null && CommonUtils.isNullOrEmpty(requestTelemetry.getName())) { + if (CommonUtils.isNullOrEmpty(requestTelemetry.getName())) { requestTelemetry.setName(operationName); } }