Skip to content

Commit

Permalink
spotless
Browse files Browse the repository at this point in the history
  • Loading branch information
SylvainJuge committed Sep 17, 2024
1 parent f6667dd commit eab01e9
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 78 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.contrib.jmxscraper;

import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;

@SuppressWarnings("all")
public class TestApp implements TestAppMXBean {
Expand All @@ -14,7 +19,7 @@ public class TestApp implements TestAppMXBean {

public static void main(String[] args) {
TestApp app = TestApp.start();
while(app.isRunning()){
while (app.isRunning()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Expand All @@ -23,10 +28,9 @@ public static void main(String[] args) {
}
}

private TestApp() {
}
private TestApp() {}

static TestApp start(){
static TestApp start() {
TestApp app = new TestApp();
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
try {
Expand All @@ -40,7 +44,6 @@ static TestApp start(){
return app;
}


@Override
public int getIntValue() {
return 42;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.contrib.jmxscraper;

@SuppressWarnings("unused")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
package io.opentelemetry.contrib.jmxscraper;
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.contrib.jmxscraper.client;

import static org.assertj.core.api.Assertions.assertThat;

import io.opentelemetry.contrib.jmxscraper.TestApp;
import java.io.Closeable;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
Expand Down Expand Up @@ -53,12 +59,9 @@ static void afterAll() {
}
}


@Test
void noAuth() {
try (AppContainer app = new AppContainer()
.withJmxPort(9990)
.start()) {
try (AppContainer app = new AppContainer().withJmxPort(9990).start()) {
testConnector(() -> JmxRemoteClient.createNew(app.getHost(), app.getPort()).connect());
}
}
Expand All @@ -67,15 +70,13 @@ void noAuth() {
void loginPwdAuth() {
String login = "user";
String pwd = "t0p!Secret";
try (AppContainer app = new AppContainer()
.withJmxPort(9999)
.withUserAuth(login, pwd)
.start()) {
testConnector(() -> JmxRemoteClient.createNew(app.getHost(), app.getPort())
.userCredentials(login, pwd)
.connect());
try (AppContainer app = new AppContainer().withJmxPort(9999).withUserAuth(login, pwd).start()) {
testConnector(
() ->
JmxRemoteClient.createNew(app.getHost(), app.getPort())
.userCredentials(login, pwd)
.connect());
}

}

@Test
Expand All @@ -95,20 +96,20 @@ private static void testConnector(ConnectorSupplier connectorSupplier) {
try (JMXConnector connector = connectorSupplier.get()) {
assertThat(connector.getMBeanServerConnection())
.isNotNull()
.satisfies(connection -> {
try {
ObjectName name = new ObjectName(TestApp.OBJECT_NAME);
Object value = connection.getAttribute(name, "IntValue");
assertThat(value).isEqualTo(42);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
.satisfies(
connection -> {
try {
ObjectName name = new ObjectName(TestApp.OBJECT_NAME);
Object value = connection.getAttribute(name, "IntValue");
assertThat(value).isEqualTo(42);
} catch (Exception e) {
throw new RuntimeException(e);
}
});

} catch (IOException e) {
throw new RuntimeException(e);
}

}

private interface ConnectorSupplier {
Expand All @@ -131,19 +132,18 @@ private AppContainer() {
// SSL registry : com.sun.management.jmxremote.registry.ssl
// client side ssl auth: com.sun.management.jmxremote.ssl.need.client.auth


String appJar = System.getProperty("app.jar.path");
assertThat(Paths.get(appJar))
.isNotEmptyFile()
.isReadable();

this.appContainer = new GenericContainer<>("openjdk:8u272-jre-slim")
.withCopyFileToContainer(MountableFile.forHostPath(appJar), "/app.jar")
.withLogConsumer(new Slf4jLogConsumer(logger))
.withNetwork(network)
.waitingFor(Wait.forLogMessage(TestApp.APP_STARTED_MSG + "\\n", 1)
.withStartupTimeout(Duration.ofSeconds(5)))
.withCommand("java", "-jar", "/app.jar");
assertThat(Paths.get(appJar)).isNotEmptyFile().isReadable();

this.appContainer =
new GenericContainer<>("openjdk:8u272-jre-slim")
.withCopyFileToContainer(MountableFile.forHostPath(appJar), "/app.jar")
.withLogConsumer(new Slf4jLogConsumer(logger))
.withNetwork(network)
.waitingFor(
Wait.forLogMessage(TestApp.APP_STARTED_MSG + "\\n", 1)
.withStartupTimeout(Duration.ofSeconds(5)))
.withCommand("java", "-jar", "/app.jar");
}

@CanIgnoreReturnValue
Expand Down Expand Up @@ -177,20 +177,19 @@ AppContainer start() {
properties.put("com.sun.management.jmxremote.access.file", "/jmx.access");
}

String confArgs = properties.entrySet()
.stream()
.map(e -> {
String s = "-D" + e.getKey();
if (!e.getValue().isEmpty()) {
s += "=" + e.getValue();
}
return s;
})
.collect(Collectors.joining(" "));

appContainer
.withEnv("JAVA_TOOL_OPTIONS", confArgs)
.start();
String confArgs =
properties.entrySet().stream()
.map(
e -> {
String s = "-D" + e.getKey();
if (!e.getValue().isEmpty()) {
s += "=" + e.getValue();
}
return s;
})
.collect(Collectors.joining(" "));

appContainer.withEnv("JAVA_TOOL_OPTIONS", confArgs).start();

logger.info("Test application JMX port mapped to {}:{}", getHost(), getPort());

Expand Down Expand Up @@ -238,5 +237,4 @@ private static void writeLine(Path path, String line) throws IOException {
Files.write(path, line.getBytes(StandardCharsets.UTF_8));
}
}

}
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.contrib.jmxscraper.client;

import java.io.IOException;
Expand All @@ -6,6 +11,8 @@
import java.security.Security;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
Expand All @@ -15,12 +22,10 @@
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.sasl.RealmCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JmxRemoteClient {

private static final Logger logger = LoggerFactory.getLogger(JmxRemoteClient.class);
private static final Logger logger = Logger.getLogger(JmxRemoteClient.class.getName());

private final String host;
private final int port;
Expand Down Expand Up @@ -78,22 +83,23 @@ public JMXConnector connect() throws IOException {

env.put(
"jmx.remote.sasl.callback.handler",
(CallbackHandler) callbacks -> {
for (Callback callback : callbacks) {
if (callback instanceof NameCallback) {
((NameCallback) callback).setName(userName);
} else if (callback instanceof PasswordCallback) {
char[] pwd = password == null ? null : password.toCharArray();
((PasswordCallback) callback).setPassword(pwd);
} else if (callback instanceof RealmCallback) {
((RealmCallback) callback).setText(realm);
} else {
throw new UnsupportedCallbackException(callback);
}
}
});
(CallbackHandler)
callbacks -> {
for (Callback callback : callbacks) {
if (callback instanceof NameCallback) {
((NameCallback) callback).setName(userName);
} else if (callback instanceof PasswordCallback) {
char[] pwd = password == null ? null : password.toCharArray();
((PasswordCallback) callback).setPassword(pwd);
} else if (callback instanceof RealmCallback) {
((RealmCallback) callback).setText(realm);
} else {
throw new UnsupportedCallbackException(callback);
}
}
});
} catch (final ReflectiveOperationException e) {
logger.warn("SASL unsupported in current environment: " + e.getMessage(), e);
logger.log(Level.WARNING, "SASL unsupported in current environment: " + e.getMessage(), e);
}

JMXServiceURL url = buildUrl(host, port);
Expand All @@ -117,15 +123,12 @@ private static JMXServiceURL buildUrl(String host, int port) {
if (host != null) {
sb.append(host);
}
sb.append(":")
.append(port)
.append("/jmxrmi");
sb.append(":").append(port).append("/jmxrmi");

try {
return new JMXServiceURL(sb.toString());
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url", e);
}
}

}

0 comments on commit eab01e9

Please sign in to comment.