I need to run my own logic after the jetty embedded server starts. I'm not starting it from the main class due to classloader issues. An ideal solution seemed to be running my server logic from a servlet initialization. But the init function and also the constructor is not called after the jetty server start. An instance of the servlet is being created during the first HTTP request. Is it possible to tell jetty to initialize my servlet instantly or do I really need to load all classes with my custom classloader and then start the jetty server?
This is the main class:
public class ServerLauncher {
public static void main(String[] args) {
JettyServerLauncher.launchHttp("target/server.war", "0.0.0.0", 8080);
// Starting my own logic here is causing classloader issues, because WebSocket classes are loaded by other classloader than my classes, that is the reason why I moved it into the servlet
}
}
This is my jetty embedded server launcher:
import org.eclipse.jetty.annotations.AnnotationConfiguration;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.plus.webapp.EnvConfiguration;
import org.eclipse.jetty.plus.webapp.PlusConfiguration;
import org.eclipse.jetty.server.*;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.webapp.*;
import java.io.File;
public class JettyServerLauncher {
private static boolean isHttps;
private static File keyStoreFile;
private static String warPath;
private static String host;
private static int httpPort;
private static int httpsPort;
private static String keyStorePath;
private static String keyStorePass;
private static boolean needClientAuth;
public static void launchHttp(String warPath, String host, int httpPort) {
JettyServerLauncher.isHttps = false;
JettyServerLauncher.warPath = warPath;
JettyServerLauncher.host = host;
JettyServerLauncher.httpPort = httpPort;
launch();
}
public static void launchHttps(String warPath, String host, String keyStorePath, String keyStorePass, int httpPort, int httpsPort, boolean needClientAuth) {
JettyServerLauncher.isHttps = true;
JettyServerLauncher.warPath = warPath;
JettyServerLauncher.host = host;
JettyServerLauncher.httpPort = httpPort;
JettyServerLauncher.httpsPort = httpsPort;
JettyServerLauncher.keyStorePath = keyStorePath;
JettyServerLauncher.keyStorePass = keyStorePass;
JettyServerLauncher.needClientAuth = needClientAuth;
launch();
}
private static void launch() {
Server server = null;
try {
System.out.println("Initializing jetty server...");
if (isHttps) loadKeyStores(keyStorePath);
// Create jetty server
server = new Server(httpPort);
// Setup connectors
Connector httpConnector = createHttpConnector(server, host, httpPort, httpsPort);
if (isHttps) {
Connector httpsConnector = createHttpsConnector(server, host, httpsPort, keyStoreFile, keyStorePass, needClientAuth);
server.setConnectors(new Connector[]{httpConnector, httpsConnector});
} else {
server.setConnectors(new Connector[]{httpConnector});
}
// Add handlers for requests to collection of handlers
HandlerCollection handlers = new ContextHandlerCollection();
//handlers.addHandler(new SecuredRedirectHandler());
handlers.addHandler(createWebApp(warPath));
server.setHandler(handlers);
server.dump();
System.out.println("Starting jetty websocket and web server...");
server.start();
server.join();
} catch (Throwable t) {
t.printStackTrace();
System.err.println("Server initialization failed!");
System.out.println("Stopping the server...");
try {
server.stop();
} catch (Exception ignored) {}
}
}
private static WebAppContext createWebApp(String warPath) {
WebAppContext webApp = new WebAppContext();
webApp.setContextPath("/");
webApp.setWar(new File(warPath).getAbsolutePath());
webApp.setThrowUnavailableOnStartupException(true);
// Enable support for JSR-356 javax.websocket
webApp.setAttribute("org.eclipse.jetty.websocket.jsr356", Boolean.TRUE);
// Jetty will scan project for configuration files... This is very important for loading websocket endpoints by annotation automatically
webApp.setConfigurations(new Configuration[] {
new AnnotationConfiguration(),
new WebInfConfiguration(),
new WebXmlConfiguration(),
new MetaInfConfiguration(),
new FragmentConfiguration(),
new EnvConfiguration(),
new PlusConfiguration(),
new JettyWebXmlConfiguration()
});
return webApp;
}
private static Connector createHttpConnector(Server server, String host, int httpPort, int httpsPort) {
HttpConfiguration httpConf = new HttpConfiguration();
httpConf.setSendServerVersion(false);
if (isHttps) httpConf.setSecurePort(httpsPort);
ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(httpConf));
connector.setPort(httpPort);
connector.setHost(host);
return connector;
}
private static Connector createHttpsConnector(Server server, String host, int httpsPort, File keyStoreFile, String keyStorePass, boolean needClientAuth) {
SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
sslContextFactory.setKeyStorePath(keyStoreFile.getAbsolutePath());
sslContextFactory.setKeyStorePassword(keyStorePass);
sslContextFactory.setNeedClientAuth(needClientAuth);
// Setup HTTPS Configuration
HttpConfiguration httpsConf = new HttpConfiguration();
httpsConf.setSendServerVersion(false);
httpsConf.setSecureScheme("https");
httpsConf.setSecurePort(httpsPort);
httpsConf.setOutputBufferSize(32768);
httpsConf.setRequestHeaderSize(8192);
httpsConf.setResponseHeaderSize(8192);
httpsConf.addCustomizer(new SecureRequestCustomizer()); // adds ssl info to request object
// Establish the HTTPS ServerConnector
ServerConnector httpsConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConf));
httpsConnector.setPort(httpsPort);
httpsConnector.setHost(host);
return httpsConnector;
}
private static void loadKeyStores(String keyStorePath) {
keyStoreFile = new File(keyStorePath);
if (!keyStoreFile.exists()) {
throw new RuntimeException("Key store file does not exist on path '"+keyStoreFile.getAbsolutePath()+"'");
}
}
}
This is my servlet:
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
#WebServlet(displayName = "MyServlet", urlPatterns = { "/*" })
public class MyServlet extends HttpServlet {
#Override
public void init() {
// start new Thread with my server logic here (avoid classloader issues)
// but at least one HTTP request is needed to start it from this place
}
#Override
public void destroy() {}
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
// handle http requests
}
}
I found this on google, but I don't know how to use it in my case. https://www.eclipse.org/lists/jetty-users/msg02109.html
Thank you for your help.
If you just want the servlet to init on startup, then use the annotation ...
#WebServlet(
displayName = "MyServlet",
urlPatterns = { "/*" },
loadOnStartup = 1
)
Alternatively, you could register a javax.servlet.ServletContextListener that does the contextInitialized(ServletContextEvent sce) behavior you need.
Tip: if you define a custom the ServletContextListener for embedded use, you can just add it to the WebAppContext from outside of the WAR you are using.
Example:
webApp.getServletHandler()
.addListener(new ListenerHolder(MyContextListener.class));
Also, this block of code is wrong and shows you copy/pasted from an old code snippet (this technique is from circa Jetty 9.0.0 thru 9.2.16)
webApp.setConfigurations(new Configuration[] {
new AnnotationConfiguration(),
new WebInfConfiguration(),
new WebXmlConfiguration(),
new MetaInfConfiguration(),
new FragmentConfiguration(),
new EnvConfiguration(),
new PlusConfiguration(),
new JettyWebXmlConfiguration()
});
In Jetty 9.4.x you never directly configure the webApp.setConfigurations() like that, use the Configuration.ClassList defined on the server instead ...
From: 9.4.44.v20210927 - embedded/LikeJettyXml.java
Configuration.ClassList classlist = Configuration.ClassList
.setServerDefault(server);
classlist.addAfter(
"org.eclipse.jetty.webapp.FragmentConfiguration",
"org.eclipse.jetty.plus.webapp.EnvConfiguration",
"org.eclipse.jetty.plus.webapp.PlusConfiguration");
classlist.addBefore(
"org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
"org.eclipse.jetty.annotations.AnnotationConfiguration");
Starting in Jetty 10.0.0, you never specify the Configuration classes, or their order, as the existence of the support JAR is enough, and internally in Jetty 10 the order is resolved properly.
But if you need to add Configurations (due to non-standard deployment concerns where the Java ServiceLoader doesn't work), then you still configure the additional Configurations on the server object (but without worrying about the correct order for those configurations)
From 10.0.7 - embedded/demos/LikeJettyXml.java
Configurations.setServerDefault(server).add(
new EnvConfiguration(),
new PlusConfiguration(),
new AnnotationConfiguration()
);
Can't figure out how to make an object created at jersey-server start accessible in jersey resources. Basically, what i want to do is to inject a Database context into jersey resources.
JerseyServer:
public boolean startServer(String keyStoreServer, String trustStoreServer) {
//Check if GraphDb is setup
if (gdbLogic == null) {
//FIXME - maybe throw an exception here?
return false;
}
// create a resource config that scans for JAX-RS resources and providers
// in org.developer_recommender.server package
final org.glassfish.jersey.server.ResourceConfig rc = new org.glassfish.jersey.server.ResourceConfig().packages("org.developer_recommender.server").register(createMoxyJsonResolver());
WebappContext context = new WebappContext("context");
ServletRegistration registration = context.addServlet("ServletContainer", ServletContainer.class);
//TODO: value setzen
registration.setInitParameter("jersey.config.server.provider.packages", "org.developer_recommender.server.service;org.developer_recommender.server.auth");
registration.setInitParameter(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, SecurityFilter.class.getName());
SSLContextConfigurator sslContext = new SSLContextConfigurator();
sslContext.setKeyStoreFile(keyStoreServer);
sslContext.setTrustStoreFile(trustStoreServer);
//TODO -
sslContext.setKeyStorePass("123456");
sslContext.setTrustStorePass("123456");
// create and start a new instance of grizzly http server
// exposing the Jersey application at BASE_URI
HttpServer server = null;
try{
SSLEngineConfigurator sslec = new SSLEngineConfigurator(sslContext).setClientMode(false).setNeedClientAuth(true);
server = GrizzlyHttpServerFactory.createHttpServer(getBaseURI()/*URI.create(BASE_URI)*/, rc, true , sslec);
System.out.println("Jersey app started. Try out " + BASE_URI);
context.deploy(server);
return true;
} catch(Exception e ){
System.out.println(e.getMessage());
}
return false;
Service:
public class Service {
#Inject
protected GDBLogic gbdLogic;
}
So i want the instance of GDBLogic in startServer to be accessible in Jersey Resources. Any advice on how to achieve this?
I don't want to use a static field for GDBLogic to achieve this, cause we will have a minimum of two different Database configurations.
You need to set up the instance binding in order to get the injection to work. You can do that by adding an HK2 abstract binder to your resource config:
final ResourceConfig rc = new ResourceConfig()
.packages("org.developer_recommender.server")
.register(createMoxyJsonResolver())
.register(new AbstractBinder()
{
#Override
protected void configure()
{
bind(gdbLogic).to(GDBLogic.class);
}
});
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();
}
}
With the following code, how can I deploy a WAR application located on the classpath ?
private Server s;
#BeforeClass
public static void setUp() throws Exception {
// Start http server
Random r = new Random();
int port = 1024 + r.nextInt(8976);
s = new Server(new InetSocketAddress("127.0.0.1", port));
// Add my WAR for deployment here ...
s.start();
}
Jetty 8.0.1
JDK 6
Something like
WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/");
webapp.setWar(warURL);
server.setHandler(webapp);
The war does not have to be on the class path.
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.