two contexts one server jetty - java

i have two jetty embedded servers,
localhost:9001/WebApp1 and localhost:9002/WebApp2,
as you can see they're on different ports.
I'd like them to share the same port during creation of server
is it possible? (BTW they are two separate jar files as well).
so can i do something like this instead
localhost:9001/WebApp1 and localhost:9001/WebApp2
or am I stuck with producing war files then having them
contained by a tomcat/glassfish server
during creation of server i usually see this
ContextHandler context = new ContextHandler();
context.setContextPath("/WebApp1");
context.setHandler(new WebApp1());
Server server = new Server(9001);
server.setHandler(context);
server.start();
server.join();
on second app i'd like to have something that looks like this
ContextHandler context = new ContextHandler();
context.setContextPath("/WebApp2");
context.setHandler(new WebApp2());
Server server = getExistingServer(9001);
server.addHandler(context);
i see that there is such method server.getHandlers(); which returns an array of handlers how do i add new handler to the existing list, or get the existing jetty server running at port 9001

Jetty is a standard servlet container and can of course handle different contexts.
See section Embedding Contexts in Chapter 24 of the Jetty documentation.
Here is the ManyContexts example (part of Jetty docs):
public class ManyContexts
{
public static void main( String[] args ) throws Exception
{
Server server = new Server(8080);
ContextHandler context = new ContextHandler("/");
context.setContextPath("/");
context.setHandler(new HelloHandler("Root Hello"));
ContextHandler contextFR = new ContextHandler("/fr");
contextFR.setHandler(new HelloHandler("Bonjoir"));
ContextHandler contextIT = new ContextHandler("/it");
contextIT.setHandler(new HelloHandler("Bongiorno"));
ContextHandler contextV = new ContextHandler("/");
contextV.setVirtualHosts(new String[] { "127.0.0.2" });
contextV.setHandler(new HelloHandler("Virtual Hello"));
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(new Handler[] { context, contextFR, contextIT, contextV });
server.setHandler(contexts);
server.start();
server.join();
}
}

Related

Jetty Server blocks when setting handler

I am trying to setup a Jetty Server with Servlet Contexts and it blocks when calling server.setHandler(context). If I run the code snippet from below, which is actually following the example from http://www.eclipse.org/jetty/documentation/9.3.x/embedding-jetty.html#_embedding_servletcontexts , it only prints one "a" and then blocks.
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
Server server = new Server(8070);
log.info("a");
server.setHandler(context);
log.info("a");
context.addServlet(EventServer.class, "/response");
context.addServlet(NotificationServer.class, "/notification");
log.info("a");
context.addEventListener(new ConfigureService());
context.addEventListener(new NotificationService());
try {
server.start();
log.info("Jetty-Server Started");
server.join();
} catch (Exception e) {
log.error(ExceptionUtils.getFullStackTrace(e));
} finally {
server.destroy();
}
Any idea why it does not execute the rest of the code and blocks when setting the handler?
It turns out that you can't actually run the jetty-server and jetty-servlet while them being different versions and this will cause the block when setting the handler.

Restlet - how to expose a resource with both HTTP/HTTPS?

Using restlet 2.3.1. I've a resource exposed via HTTP. Is it possible to expose it via HTTPS as well? The following snippet show how my server looks like today:
final Router router = new Router();
Filter filter = new Filter(){};
filter.setNext( DaemonsResource.class );
router.attach( "daemons/{p1}", filter );
Application myApp = new Application()
{
#Override
public org.restlet.Restlet createInboundRoot()
{
router.setContext(getContext());
return router;
};
};
Component component = new Component();
component.getDefaultHost().attach( "/", myApp );
new Server( Protocol.HTTP, port, component ).start();
I already got the crt from the CA, and built the keystore upon it.
Thanks!
Try something like :
Component component = new Component();
Server server = component.getServers().add(Protocol.HTTPS, 8082);
component.getDefaultHost().attach( "/", myApp );
component.start();
See restlet tutorials
To set your keystore, etc.,
Series<Parameter> parameters = server.getContext().getParameters();
parameters.add("keystorePath","add_keystore_file_path_here"));
parameters.add("keystorePassword", "mypassword");
parameters.add("keyPassword", "mypassword");
parameters.add("keystoreType", "PKCS12");
// Start the component.
component.start();
see restlet mailing list This message is a bit outdated but the parameters should still be the same

How to gracefully shutdown embeded jetty

I have an application runs on an embedded jetty server. Now i want to start/stop the server as a service.
I use a script to start the server.
java $JAVA_OPTS -DREQ_JAVA_VERSION=$JAVA_VERSION -jar myjetty.jar
Main Class
Server server = new Server();
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(PORT);
server.addConnector(connector);
HandlerCollection handlers = new HandlerCollection();
NCSARequestLog requestLog = new NCSARequestLog();
requestLog.setFilename(home + "/logs/access_" + logFileDateFormat
+ ".log");
requestLog.setFilenameDateFormat(logFileDateFormat);
requestLog.setRetainDays(10);
requestLog.setAppend(true);
requestLog.setExtended(false);
requestLog.setLogCookies(false);
requestLog.setLogTimeZone(TimeZone.getDefault().getID());
RequestLogHandler requestLogHandler = new RequestLogHandler();
requestLogHandler.setRequestLog(requestLog);
handlers.addHandler(requestLogHandler);
server.setHandler(handlers);
server.start();
server.join();
This starts the server.Stopping and/or Restarting an embedded Jetty instance via web call can be used to stop server but,
How to stop the server from the script? and what changes should i make to shout down server in the main class.
Since Jetty 7.5.x you can use org.eclipse.jetty.server.handler.ShutdownHandler in your code:
Server server = new Server(8080);
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[]
{ someOtherHandler, new ShutdownHandler("secret_password", false, true) });
server.setHandler(handlers);
server.start();
... which will allow you to shut down your jetty by issuing the following http POST request:
curl -X POST http://localhost:8080/shutdown?token=secret_password
You can call setStopTimeout(long timeout) to shutdown Jetty in a relatively graceful way. A statisticsHandler must be configured when calling this method.
Referencing: Jetty Server.class setStopTimeout(long)
e.g.
YourServletHandler servletHandler = new YourServletHandler();
StatisticsHandler statsHandler = new StatisticsHandler();
statsHandler.setHandler(servletHandler);
Server server = new Server(80);
server.setHandler(statsHandler);
server.setStopTimeout(3000L);
//...
server.start();
//...
server.stop();
There is no predefined solution to shut-down the Jetty server. The only ordered way to shut-down the Jetty server is to call the method stop() on the running server instance. You must implement the way how this method is called yourself.
You could achieve this (for example) by...
implementing an RMI server thread and invoke the method from a RMI client
implementing a JMX MBean and from a client call a method on that MBean
implementing a custom handler like described in the link you have posted
If you only want to find a way which does not depend on additional tools like curl, than you could solve it for example like below (it's your own code with small modifications)
public class MyJetty {
public static void main(String[] args) throws Exception {
int PORT = 9103;
String home = System.getProperty("user.home");
String logFileDateFormat = "yyyy_MM_dd";
// execute a request to http://localhost:9103/stop
// instead of `curl -v http://localhost:9103/stop`
if (args.length == 1 && "stop".equalsIgnoreCase(args[0])) {
URL url = new URL("http", "localhost", PORT, "/stop");
try (InputStream in = url.openStream()) {
int r;
while ((r = in.read()) != -1) {
System.out.write(r);
}
return;
} catch (IOException ex) {
System.err.println("stop Jetty failed: " + ex.getMessage());
}
}
Server server = new Server();
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(PORT);
server.addConnector(connector);
HandlerCollection handlers = new HandlerCollection();
NCSARequestLog requestLog = new NCSARequestLog();
requestLog.setFilename(home + "/logs/access_" + logFileDateFormat + ".log");
requestLog.setFilenameDateFormat(logFileDateFormat);
requestLog.setRetainDays(10);
requestLog.setAppend(true);
requestLog.setExtended(false);
requestLog.setLogCookies(false);
requestLog.setLogTimeZone(TimeZone.getDefault().getID());
RequestLogHandler requestLogHandler = new RequestLogHandler();
requestLogHandler.setRequestLog(requestLog);
handlers.addHandler(requestLogHandler);
// the class YourHandler is the one from your link
handlers.addHandler(new YourHandler(server));
server.setHandler(handlers);
server.start();
server.join();
}
}
start the server with java MyJetty
stop the server with java MyJetty stop
I don't know why (or if it is a bug) but in my case I had to set shutdownAtStart argument to false to get it working. If I set it as true the Server connector never starts, so it doesn't attend external requests like http://localhost:8888/shutdown?token=secret
new ShutdownHandler("secret", false, false);

jetty server 9.1 multiple embeded ports and application in same server instance

I should use one Server object, and need to open multiple ports and multiple application(WAR files).
Ex, one server object,
8080 addition.war
8081 subraction.war
etc.
I'm using Jetty server 9.1.0
How can I do this?
To accomplish this, you need:
Each ServerConnector should have a unique name declared via ServerConnector.setName(String)
When you define your WebAppContext, declare a set of virtual hosts that take a named virtual host syntax "#{name}", where the {name} is the same one you chose for the connector. (Note: A virtualhost without the "#" sign is a traditional virtualhost based on hostnames)
Like this ...
package jetty.demo;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.webapp.WebAppContext;
public class ConnectorSpecificContexts
{
public static void main(String[] args)
{
Server server = new Server();
ServerConnector connectorA = new ServerConnector(server);
connectorA.setPort(8080);
connectorA.setName("connA"); // connector name A
ServerConnector connectorB = new ServerConnector(server);
connectorB.setPort(9090);
connectorB.setName("connB"); // connector name B
server.addConnector(connectorA);
server.addConnector(connectorB);
// Basic handler collection
HandlerCollection contexts = new HandlerCollection();
server.setHandler(contexts);
// WebApp A
WebAppContext appA = new WebAppContext();
appA.setContextPath("/a");
appA.setWar("./webapps/webapp-a.war");
appA.setVirtualHosts(new String[]{"#connA"}); // connector name A
contexts.addHandler(appA);
// WebApp B
WebAppContext appB = new WebAppContext();
appB.setContextPath("/b");
appB.setWar("./webapps/webapp-b.war");
appB.setVirtualHosts(new String[]{"#connB"}); // connector name B
contexts.addHandler(appB);
try
{
server.start(); // start server thread
server.join(); // wait for server thread to end
}
catch (Throwable t)
{
t.printStackTrace(System.err);
}
}
}

Is there a way to set context-params programmatically in embedded jetty?

Looking at the following example of an embedded Jetty Example:
http://musingsofaprogrammingaddict.blogspot.com.au/2009/12/running-jsf-2-on-embedded-jetty.html
The following code sample is given (below.
The author then goes on an gives an example of referring to context params in a web.xml file. eg
...
<context-param>
<param-name>com.sun.faces.expressionFactory</param-name>
<param-value>com.sun.el.ExpressionFactoryImpl</param-value>
</context-param>
...
My question is - if I want to do everything in a Java class - is there a way to set context-params programmatically?
public class JettyRunner {
public static void main(String[] args) throws Exception {
Server server = new Server();
Connector connector = new SelectChannelConnector();
connector.setPort(8080);
connector.setHost("127.0.0.1");
server.addConnector(connector);
WebAppContext wac = new AliasEnhancedWebAppContext();
wac.setContextPath("/myapp");
wac.setBaseResource(
new ResourceCollection(
new String[] {"./src/main/webapp", "./target"}));
wac.setResourceAlias("/WEB-INF/classes/", "/classes/");
server.setHandler(wac);
server.setStopAtShutdown(true);
server.start();
server.join();
}
}
In your case
wac.setInitParameter("com.sun.faces.expressionFactory",
"com.sun.el.ExpressionFactoryImpl")
will do.
ServletContextHandler context = new ServletContextHandler(
ServletContextHandler.SESSIONS);
context.setContextPath("/");
above code should work for you.

Categories