How to send parameters to the started application java - java

I am trying to develop simple standalone java app. I am using jetty.
Starting embedded server:
String WEBAPPDIR = "web/";
Server server = new Server(8080);
String CONTEXTPATH = "/";
Server.setHandler(new WebAppContext(WEBAPPDIR, CONTEXTPATH));
server.start();
How i can put/send parameters to this app, which is launched at this moment, from external environment (for example, bash)

public class Echo {
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
}
You can pass arguments into your main function. If you are starting jetty from your own application, you would access the args before starting the server.
public class SimplestServer
{
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
server.start();
server.join();
}
}

Related

Add variable to Java OPCUA server

I would like to use a java OPC UA server with the prosys OPCUA SDK.
I'm able to start a server with the SimpleServer program but I don't understand how to host variable in this server as boolean, integer...
Here the code I'm using from the package, it start a server but it is empty.
public class SimpleServer {
public static void main(String[] args) throws Exception {
UaServer server = new UaServer();
if (System.getProperty("java.version").startsWith("1.6")) {
server.setEnableIPv6(false);
}
server.setPort(Protocol.OpcTcp, 52530);
server.setServerName("OPCUA/SimpleServer");
server.setBindAddresses(EndpointUtil.getInetAddresses(server.isEnableIPv6()));
server.getSecurityModes().add(SecurityMode.NONE);
server.getSecurityModes().addAll(SecurityMode.combinations(
EnumSet.of(MessageSecurityMode.Sign, MessageSecurityMode.SignAndEncrypt), SecurityPolicy.ALL_SECURE_104));
server.addUserTokenPolicy(UserTokenPolicies.ANONYMOUS);
server.setCertificateValidator(new DefaultCertificateValidator(new PkiDirectoryCertificateStore()));
initializeApplicationIdentity(server);
// Starts the server
server.start();
// Prints connection address that clients can use.
System.out.println("Server started, connection address:");
System.out.println(server.getEndpoints()[0].getEndpointUrl());
//I think the variable should be add here
// Wait for shutdown
System.out.println("Enter 'x' to shutdown");
Scanner sc = new Scanner(System.in);
sc.nextLine(); // blocks until input given
System.out.println("Shutting down..");
server.shutdown(2, new LocalizedText("Shutdown by user"));
System.out.println("Server stopped.");
}
/**
* Define a minimal ApplicationIdentity.
*/
private static void initializeApplicationIdentity(UaServer server)
throws SecureIdentityException, IOException, UnknownHostException {
ApplicationDescription appDescription = new ApplicationDescription();
appDescription.setApplicationName(new LocalizedText("SimpleServer", Locale.ENGLISH));
appDescription.setApplicationUri("urn:localhost:UA:SimpleServer");
appDescription.setProductUri("urn:prosysopc.com:UA:SimpleServer");
appDescription.setApplicationType(ApplicationType.Server);
File privateKeyPath = new File("PKI/CA/private");
String organization = "Sample Organization";
String privateKeyPassword = "opcua";
ApplicationIdentity identity = ApplicationIdentity.loadOrCreateCertificate(appDescription, organization,
privateKeyPassword, privateKeyPath, true);
server.setApplicationIdentity(identity);
}
} ```
Please, take a look at the SampleConsoleServer project which is a more complete server. And read the Tutorial that explains the details.

httpClient connection not closing

Version
vert.x core: 3.3.0
Context
Am just trying to run http client in core examples io.vertx.example.core.http.simple.Client.
While running this example its found that the established connection not closing after completion of request.
Server side I didnt see any issue. Since while trying with jmeter and server its working fine. So I think that the problem is in the HttpClient.
Anyone can help me on this?
Thanks in advance.
Steps to reproduce
running io.vertx.example.core.http.simple.Server code
running io.vertx.example.core.http.simple.Client code
Extra
The following shown even after the request and response is ended. while giving
LINUX
lsof -i -P
java 32551 USER 223u IPv4 16264097 0t0 TCP localhost:8080->localhost:26980 (ESTABLISHED)
java 32634 USER 218u IPv4 16264087 0t0 TCP localhost:26980->localhost:8080 (ESTABLISHED)
WINDOWS
TCP 127.0.0.1:8080 FSSCHND12957:56893 ESTABLISHED
TCP 127.0.0.1:56893 FSSCHND12957:8080 ESTABLISHED
Tried in both LINUX and WINDOWS system.
Client Code
package io.vertx.example.core.http.simple;
import io.vertx.core.AbstractVerticle;
import io.vertx.example.util.Runner;
/*
#author Tim Fox
*/
public class Client extends AbstractVerticle {
// Convenience method so you can run it in your IDE
public static void main(String[] args) {
Runner.runExample(Client.class);
}
#Override
public void start() throws Exception {
vertx.createHttpClient().getNow(8080, "localhost", "/", resp -> {
System.out.println("Got response " + resp.statusCode());
resp.bodyHandler(body -> {
System.out.println("Got data " + body.toString("ISO-8859-1"));
});
});
}
}
Server Code
package io.vertx.example.core.http.simple;
import io.vertx.core.AbstractVerticle;
import io.vertx.example.util.Runner;
/*
#author Tim Fox
*/
public class Server extends AbstractVerticle {
// Convenience method so you can run it in your IDE
public static void main(String[] args) {
Runner.runExample(Server.class);
}
#Override
public void start() throws Exception {
vertx.createHttpServer().requestHandler(req -> {
req.response().putHeader("content-type", "text/html").end("
Hello from vert.x!
");
}).listen(8080);
}
}
We have to close the httpClient which we normally do in java. Only end() is not closing the connection. httpClient.close() is required.... This solved my issue..
Modified code:
public class Client extends AbstractVerticle {
// Convenience method so you can run it in your IDE
public static void main(String[] args) {
Runner.runExample(Client.class);
}
#Override
public void start() throws Exception {
HttpClient httpClient = vertx.createHttpClient().getNow(8080, "localhost", "/", resp -> {
System.out.println("Got response " + resp.statusCode());
resp.bodyHandler(body -> {
System.out.println("Got data " + body.toString("ISO-8859-1"));
httpClient.close();
});
});
}
}

Java web.xml location for embedded jetty

I'm trying to understand the way we should configure the web application.
Now i have a simple gradle project with embedded jetty
Dependencies:
dependencies {
compile('org.eclipse.jetty:jetty-servlet:9.3.10.v20160621')
compile('org.eclipse.jetty:jetty-webapp:9.3.10.v20160621')
testCompile group: 'junit', name: 'junit', version: '4.11'
}
Application main:
package test;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
public class App {
public static void main(String[] args) throws Exception {
System.out.println(">> Running");
WebAppContext webAppContext = new WebAppContext();
webAppContext.setDescriptor("src/main/resources/WEB-INF/web.xml");
webAppContext.setResourceBase("/");
webAppContext.setContextPath("/");
Server server = new Server(8080);
server.setHandler(webAppContext);
server.start();
server.join();
}
}
In web.xml I defined only ServletContextListener implementation to find if it was catched with application.
My problem is: webAppContext.setDescriptor("src/main/resources/WEB-INF/web.xml")
Jetty can find web.xml only with this weird location path.
Why do I need to target it from project folder?
If I run jar task with gradle the wouldn't be any src directory inside the jar.
Is exist a way to something like: App.class.getResource("/WEB-INF/web.xml") and load web.xml related to classpath?
Seems it was some class loaders issue.
After some further searches I ended with next solution:
public class App {
private static final String WEBAPP_RESOURCES_LOCATION = "webapp";
public static void main(String[] args) throws Exception {
System.out.println(">> Running");
WebAppContext webAppContext = new WebAppContext();
webAppContext.setContextPath("/");
URL webAppDir = Thread.currentThread().getContextClassLoader().getResource(WEBAPP_RESOURCES_LOCATION);
webAppContext.setResourceBase(webAppDir.toURI().toString());
// if setDescriptor set null or don't used jetty looking for /WEB-INF/web.xml under resource base
// webAppContext.setDescriptor(webAppDir.toURI().toString() + "web.xml");
Server server = new Server(8080);
server.setHandler(webAppContext);
server.start();
server.join();
}
}
An the layout:
Thanks github user arey for the examle examle
your web.xml should be in
src/main/webapp/WEB-INF
UPD: sorry, pressed submit before finalising the post.
above works for me and then I can run the test like:
Server server; //jetty server
private static Integer portNum = 9999;
private static String ENDPOINT_URL = "http://localhost:" + portNum + "/appName/";
#Before
public void startJetty() throws Exception{
server = new Server(portNum);
server.setStopAtShutdown(true);
WebAppContext webAppContext = new WebAppContext();
webAppContext.setContextPath("/appName");
webAppContext.setResourceBase("src/main/webapp");
webAppContext.setClassLoader(getClass().getClassLoader());
server.setHandler(webAppContext);
server.start();
}
#After
public void stopJetty(){
try {
server.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
#Test
public void serverNotNull(){
assertNotNull("jetty must be initialised", server);
}

KryoNet: Client disconnects immediately after connecting

This seems to be a popular problem, but I'm still having trouble finding a solution even after spending a lot of time troubleshooting. I'm hoping there's an updated solution.
I'm setting up a simple Server and Client with the KryoNet Java networking library. My problem is that my client disconnects immediately after connecting to the server.
Here is my code:
Server
public class TheServer extends Listener {
static Server server;
static final int PORT = 8215;
public static void main(String[] args) throws IOException {
server = new Server();
server.start();
server.bind(PORT);
server.addListener(new TheServer());
System.out.println("server started on " + PORT);
}
public void connected(Connection c) {
System.out.println("connected: " + c.getID());
}
public void disconnected(Connection c) {
System.out.println("disconnected: " + c.getID());
}
}
Client
public class TheClient extends Listener {
static Client client;
static final String IP = "localhost";
static final int PORT = 8215;
public static void main(String[] args) throws IOException {
client = new Client();
client.start();
client.connect(5000, IP, PORT);
client.addListener(new TheClient());
//client.setKeepAliveTCP(2000);
}
}
After running TheServer and then TheClient, my console prints:
server started on 8215
connected: 1
disconnected: 1
Note that the time between the connection and disconnection is almost immediate, certainly less than the connection timeout time I set. Also note that I commented out the setKeepAliveTCP() method because while I do not think it is necessary, I inserted it to see if it would work.
After some more digging around, I found that starting the client with:
new Thread(client).start()
instead of
client.start()
fixes the problem.
"Starting with r122, client update threads were made into daemon threads, causing the child processes to close as soon as they finish initializing."

Custom gRPC command for Dropwizard exits immediately

I've created an application using Dropwizard that starts a gRPC server. I do not use the regular server, and want to start my application using java -jar my-fat.jar grpc config.yml instead.
I've come as far as to add the command as the only available command during startup by overriding the corresponding method in the application class:
public class App extends Application<Configuration> {
public static void main(String[] args) throws Exception {
new App().run(args);
}
#Override
protected void addDefaultCommands(final Bootstrap<Configuration> bootstrap) {
bootstrap.addCommand(new GrpcCommand(this));
}
}
I can launch my application using java -jar my-fat.jar grpc config.yml. My command looks like this:
public class GrpcCommand extends EnvironmentCommand<Configuration> {
public GrpcCommand(Application<Configuration> application) {
this(application, "grpc", "Runs the Dropwizard application as a gRPC server");
}
/**
* Creates a new environment command.
*
* #param application the application providing this command
* #param name the name of the command, used for command line invocation
* #param description a description of the command's purpose
*/
protected GrpcCommand(final Application<Configuration> application, final String name, final String description) {
super(application, name, description);
}
#Override
protected void run(final Environment environment, final Namespace namespace, final Configuration configuration) throws Exception {
final var certificateService = AzureCertificateService.createWithClients(
AzureSecretClient.create(configuration.getKeyVaultConfiguration()),
AzureCertificateClient.create(configuration.getKeyVaultConfiguration())
);
final var validationService = CertificateValidationService.create(certificateService);
final var signingService = CertificateSigningService.create(certificateService);
final Pair<X509Certificate, KeyPair> certificate = certificateService.getSigningCertificateWithKeyPair();
final BaseApiImpl baseApi = new BaseApiImpl(validationService, signingService);
final GrpcServer grpcServer = GrpcServer.newBuilder()
.withBaseApi(baseApi)
.withConfiguration(configuration.getGrpcConfiguration())
.withCertificate(certificate.getLeft())
.withPrivateKey(certificate.getRight().getPrivate())
.build();
new Thread(() -> {
try {
grpcServer.start();
} catch (Exception e) {
e.printStackTrace();
}
}).run();
environment.healthChecks().register("grpc-server", new GrpcServerHealthCheck(grpcServer));
}
}
The way that thread is started is not for production use, I'm just trying to get forward. The start method for the GrpcServer class:
#Override
public void start() throws Exception {
final NettyServerBuilder nettyServerBuilder = NettyServerBuilder.forPort(configuration.getPort())
.addService(baseApi)
.intercept(new OriginInterceptor());
if (certificate != null && privateKey != null) {
LOG.info("Got certificate and private key, enabling SSL");
nettyServerBuilder.sslContext(buildSslContext());
}
server = nettyServerBuilder
.build()
.start();
LOG.info("Server started at port {}", server.getPort());
}
And I see the message GrpcServer: Server started at port 50441 in my log when I start. However, the application does not stay open. What am I missing? Shouldn't my use of the thread create a thread that stops the application from exiting? How can I keep the application running after the gRPC server has started?
When I disabled the server command, Jetty isn't started either (of course), which kept the application alive previously.
I found the simplest solution in the gRPC Hello World Example.
My start method now looks like this:
public void start() throws Exception {
// Everything else as above
Runtime.getRuntime().addShutdownHook(new Thread(GrpcServer.this::stop));
LOG.info("Server started at port {}", server.getPort());
blockUntilShutdown();
}
private void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}

Categories