jetty interview questions
Top jetty frequently asked interview questions
I am currently setting the port via a jetty.xml
file and I've been trying to figure out from the new documentation how to actually define an httpConnector
through the Maven plugin's configuration. The docs on Eclipse's site seem a bit vague on it and I've been trying to figure this out for a while, thus ending up using a jetty.xml
. I'd like to find out the proper way to do this now.
I'm currently using org.eclipse.jetty:jetty-maven-plugin:9.2.1.v20140609
.
Please advise! Many thanks in advance!
Source: (StackOverflow)
I'm trying to create a simple webapp without any XML configuration using Spring 3.1 and an embedded Jetty 8 server.
However, I'm struggling to get Jetty to recognise my implementaton of the Spring WebApplicationInitializer interface.
Project structure:
src
+- main
+- java
| +- JettyServer.java
| +- Initializer.java
|
+- webapp
+- web.xml (objective is to remove this - see below).
The Initializer class above is a simple implementation of WebApplicationInitializer:
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.springframework.web.WebApplicationInitializer;
public class Initializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
System.out.println("onStartup");
}
}
Likewise JettyServer is a simple implementation of an embedded Jetty server:
import org.eclipse.jetty.annotations.AnnotationConfiguration;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.WebAppContext;
public class JettyServer {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
WebAppContext webAppContext = new WebAppContext();
webAppContext.setResourceBase("src/main/webapp");
webAppContext.setContextPath("/");
webAppContext.setConfigurations(new Configuration[] { new AnnotationConfiguration() });
webAppContext.setParentLoaderPriority(true);
server.setHandler(webAppContext);
server.start();
server.join();
}
}
My understanding is that on startup Jetty will use AnnotationConfiguration to scan for
annotated implementations of ServletContainerInitializer; it should find Initializer and wire it in...
However, when I start the Jetty server (from within Eclipse) I see the following on the command-line:
2012-11-04 16:59:04.552:INFO:oejs.Server:jetty-8.1.7.v20120910
2012-11-04 16:59:05.046:INFO:/:No Spring WebApplicationInitializer types detected on classpath
2012-11-04 16:59:05.046:INFO:oejsh.ContextHandler:started o.e.j.w.WebAppContext{/,file:/Users/duncan/Coding/spring-mvc-embedded-jetty-test/src/main/webapp/}
2012-11-04 16:59:05.117:INFO:oejs.AbstractConnector:Started SelectChannelConnector@0.0.0.0:8080
The important bit is this:
No Spring WebApplicationInitializer types detected on classpath
Note that src/main/java is defined as a source folder in Eclipse, so should be on the classpath. Also note that the Dynamic Web Module Facet is set to 3.0.
I'm sure there's a simple explanation, but I'm struggling to see the wood for the trees! I suspect the key is with the following line:
...
webAppContext.setResourceBase("src/main/webapp");
...
This makes sense with a 2.5 servlet using web.xml (see below), but what should it be when using AnnotationConfiguration?
NB: Everything fires up correctly if I change the Configurations to the following:
...
webAppContext.setConfigurations(new Configuration[] { new WebXmlConfiguration() });
...
In this case it finds the web.xml under src/main/webapp and uses it to wire the servlet using DispatcherServlet and AnnotationConfigWebApplicationContext in the usual way (completely bypassing the WebApplicationInitializer implementation above).
This feels very much like a classpath problem, but I'm struggling to understand quite how Jetty associates itself with implementations of WebApplicationInitializer - any suggestions would be most appreciated!
For info, I'm using the following:
Spring 3.1.1
Jetty 8.1.7
STS 3.1.0
Source: (StackOverflow)
What is the main difference between Jetty and Netty?
Netty is part of Jboss, but is it the default web server container?
Does Netty support Servlets 3.0?
Source: (StackOverflow)
I'm wondering about the downsides of each servers in respect to a production environement. Did anyone have big problems with one of the features? Performance, etc. I also quicky took a look at the new Glassfish, does it match up the simple servlet containers (it seems to have a good management interface at least)?
Source: (StackOverflow)
I'm trying to make an "executable" war file (java -jar myWarFile.war
) that will start up a Jetty webserver that hosts the webapp contained in the WAR file I executed.
I found a page that described how to make what I'm looking for:
However, following that advice along with how I think I'm supposed to make an executable jar (war) isn't working.
I have an Ant task creating a WAR file with a manifest that looks like:
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.1
Created-By: 1.5.0_18-b02 (Sun Microsystems Inc.)
Main-Class: Start
The contents of the WAR file look like:
> Start.class
> jsp
> build.jsp
> META-INF
> MANIFEST.MF
> WEB-INF
> lib
> jetty-6.1.22.jar
> jetty-util.6.1.22.jar
When I try to execute the WAR file, the error is:
Exception in thread "main" java.lang.NoClassDefFoundError: org/mortbay/jetty/Handler
Caused by: java.lang.ClassNotFoundException: org.mortbay.jetty.Handler
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: Start. Program will exit.
There appears to be two errors here: one where it seems the JAR files can't be found, and one where the Start
class can't be found.
To fix the first one, I put the Jetty JAR files in the base of the WAR file and tried again -- same error. I also tried adding the WEB-INF/lib/<specific-JAR-files>
to the Class-Path
attribute of the manifest. That did not work either.
Does anyone have any insight as to what I'm doing right/wrong and how I can get this executable WAR file up and running?
Source: (StackOverflow)
I am writing a web application using ring and clojure. I am using the jetty adapter for the development server and emacs/SLIME for IDE. While wrap-reload does help, run-jetty blocks my slime session and I would like to be able to start/stop it at will without having to run it in a separate terminal session. Ideally, I would like to define a server agent and functions start-server and stop-server that would start/stop the server inside the agent. Is this possible?
Source: (StackOverflow)
I made an RCP plugin with embedded Jetty as following:
1) In plugin.xml -> Dependencies, I have added the following:
org.eclipse.equinox.http.jetty
org.eclipse.equinox.http.registry
org.mortbay.jetty.server
javax.servlet
2) In plugin.xml -> Extensions, I have added a Servlet extension point (org.eclipse.equinox.http.registry.servlet)
class: TemperatureServlet
alias:/temperature
The TemperatureServlet looks like this:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TemperatureServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("doGet Called");
resp.sendRedirect("Convertor.jsp");
}
}
The file Convertor.jsp looks like this:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<f:view>
<h:form>
<h:panelGrid columns="2">
<h:outputLabel value="Celsius"></h:outputLabel>
<h:inputText value="#{temperatureConvertor.celsius}"></h:inputText>
</h:panelGrid>
<h:commandButton action="#{temperatureConvertor.celsiusToFahrenheit}" value="Calculate"></h:commandButton>
<h:commandButton action="#{temperatureConvertor.reset}" value="Reset"></h:commandButton>
<h:messages layout="table"></h:messages>
</h:form>
<h:panelGroup rendered="#{temperatureConvertor.initial!=true}">
<h3> Result </h3>
<h:outputLabel value="Fahrenheit "></h:outputLabel>
<h:outputLabel value="#{temperatureConvertor.fahrenheit}"></h:outputLabel>
</h:panelGroup>
</f:view>
</body>
</html>
The file faces-config.xml contains:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
<managed-bean>
<managed-bean-name>temperatureConvertor</managed-bean-name>
<managed-bean-class>hellojsf.TemperatureConvertor</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
</faces-config>
My plugin has the following hierarchy:
plugin-name
---src
------class package
---------Activator.java
---------Application.java
---------ApplicationActionBarAdvisor.java
---------ApplicationWorkbenchWindowAdvisor.java
---------Perspective.java
---------TemperatureConvertor.java
---------TemperatureServlet.java
---META-INF
------MANIFEST.MF
---resources
-------WebContent
----------WEB-INF
-------------faces-config.xml
-------------web.xml
----------Convertor.jsp
---plugin.xml
In Activator class, method start(), I have started the web server like this:
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
Bundle bundle = Platform.getBundle("org.eclipse.equinox.http.registry");
if (bundle.getState() == Bundle.RESOLVED) {
bundle.start(Bundle.START_TRANSIENT);
}
Dictionary settings = new Hashtable();
settings.put("http.enabled", Boolean.TRUE);
settings.put("http.port", 8080);
settings.put("http.host", "0.0.0.0");
settings.put("https.enabled", Boolean.FALSE);
settings.put("context.path", "/");
settings.put("context.sessioninactiveinterval", 1800);
try {
JettyConfigurator.startServer(PLUGIN_ID + ".jetty", settings);
} catch (Exception e) {
e.printStackTrace();
}
}
To this plugin I have added also the following libraries:
- JSTL: javax.servlet.jsp.jstl-1.2.1-javadoc.jar;
javax.servlet.jsp.jstl-api-1.2.1-javadoc.jar
- JSF 2.0 (Apache MyFaces JSF Core-2.0 API 2.0.2)
After I launch the application, if I type in my browser
localhost:8080/temperature
It doesn't know where to find Convertor.jsp.
My question is: how can I configure this plugin to know the resource location WebContent and the most important, how can I configure the plugin to know how to process JSFs and to know about the faces-config.xml and web.xml.
Can I, for example, when I define the extension org.eclipse.equinox.http.registry.servlets, do something like this?
class: javax.faces.webapp.FacesServlet
alis: /*.jsp
(all the files *.jsp to be processed by the FacesServlet)?
Thank you very much and sorry if the questions are silly, but I am new in this area of RCP plugins, Jetty and JSF.
Source: (StackOverflow)
I'm trying to build a simple demo app with embedded Jetty that serves static files from a "html" directory that's a subdirectory of the current working directory. The idea is that the directory with the demo jar and content can be moved to a new location and still work.
I've tried variations of the following, but I keep getting 404s.
ServletContextHandler context =
new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
context.getInitParams().put(
"org.eclipse.jetty.servlet.Default.resourceBase", "html");
context.addServlet(new ServletHolder(new DefaultServlet()), "/html");
Server jetty = new Server(8080);
jetty.setHandler(context);
jetty.start();
Any ideas?
Update: Here's a solution as documented in the Jetty tutorial. As mentioned in the correct answer, it uses a ResourceHandler
instead of a ServletContextHandler
:
Server server = new Server();
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(8080);
server.addConnector(connector);
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setDirectoriesListed(true);
resource_handler.setWelcomeFiles(new String[]{ "index.html" });
resource_handler.setResourceBase(".");
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
server.setHandler(handlers);
server.start();
server.join();
Source: (StackOverflow)
I am new to Solr, after installing it in ubuntu 8.10, when I was trying exampledocs to index , as per this link, I got this error:
HTTP ERROR: 404 missing core name in path
This is in Jetty.
What shall I do, in order to solve this?
Source: (StackOverflow)
As someone new to the Java EE ecosystem, I'm confused with these products which share a tremendous amount of keywords. And half of them come from Apache software foundation.
Can someone address me with a brief distinctive explanation for each of them?
Source: (StackOverflow)
Is it possible to use only the command line to Run jetty
with only a specified war
file and Context Path.
Something like :
java -jar $jettyHome/start.jar -Dwar.location=myApp.war -DcontextPath=/myApp OPTIONS=default,plus,jsp
Source: (StackOverflow)
I'm trying to deploy a JSP-page on Jetty, using the Jetty WTP plugin for Eclipse. But I get the error below. It looks like Jetty can't find javac
. Is there any settings I have to do for the Jetty WTP plugin in Eclipse or how do I fix this?
The JSP page works fine if I export my project as a .war
-file to jetty\webapps
and then start Jetty manually using java -jar start.jar
. But it doesn't work if I deploy using the Jetty WTP plugin for Eclipse as described.
I have my JAVA_HOME
set to C:\Program Files (x86)\Java\jdk1.7.0_01
and I use Jetty 8.0.4 on Windows 7.
Servlets is working fine with the current setup. Any suggestions on how to solve this for JSP pages?
HTTP ERROR 500
Problem accessing /MyJavaWeb/formProcess. Reason:
PWC6345: There is an error in invoking javac. A full JDK (not just JRE) is required
Caused by:
org.apache.jasper.JasperException: PWC6345: There is an error in invoking javac. A full JDK (not just JRE) is required
at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:92)
at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:378)
at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:119)
at org.apache.jasper.compiler.Jsr199JavaCompiler.compile(Jsr199JavaCompiler.java:208)
at org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:384)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:453)
at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:625)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:492)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:378)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:558)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:488)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:520)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:233)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:973)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:417)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:192)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:907)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:271)
at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:98)
at com.example.FormProcessServlet.doPost(FormProcessServlet.java:39)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:755)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:558)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:488)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:483)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:233)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:973)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:417)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:192)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:907)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:250)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:149)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:110)
at org.eclipse.jetty.server.Server.handle(Server.java:346)
at org.eclipse.jetty.server.HttpConnection.handleRequest(HttpConnection.java:442)
at org.eclipse.jetty.server.HttpConnection$RequestHandler.content(HttpConnection.java:941)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:801)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:224)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:51)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:586)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:44)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:598)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:533)
at java.lang.Thread.run(Unknown Source)
Source: (StackOverflow)
So, I've come to the conclusion that Apache HttpComponents 4 is one of the most overwrought APIs I've ever come across. Things that seem like they should be simple are taking hundreds of lines of code (and I'm still not sure resources get cleaned up correctly).
Plus it wants me to do things like:
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
qparams.add(new BasicNameValuePair("q", "httpclient"));
qparams.add(new BasicNameValuePair("btnG", "Google Search"));
qparams.add(new BasicNameValuePair("aq", "f"));
qparams.add(new BasicNameValuePair("oq", null));
URI uri = URIUtils.createURI("http", "www.google.com", -1, "/search",
URLEncodedUtils.format(qparams, "UTF-8"), null);
Which, just... no. I know it's Java, and we're not into the whole brevity thing, but that's a little much. Not to mention the jars are up to 700KB.
Anyway, enough ranting, I wanted to see what kind of experiences people have had with other HTTP client libraries?
The ones I'm aware of are: Jetty, hotpotato, and AsyncHttpClient.
This is for server-side use, I'm mostly interested in performance for many concurrent gets and large file transfers.
Any recommendations?
PS I know the venerable HttpClient 3.1 is still there, but I'd like to use something that's supported.
Update
@oleg: this is what the docs suggest:
HttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet("http://www.apache.org/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
instream.read();
} catch (IOException ex) {
throw ex;
} catch (RuntimeException ex) {
httpget.abort();
throw ex;
} finally {
try { instream.close(); } catch (Exception ignore) {}
}
}
} finally {
httpclient.getConnectionManager().shutdown();
}
I still get unexpected errors when consuming entity content when using ThreadSafeClientConnManager
. I'm sure it's my fault, but at this point I don't really want to have to figure it out.
Hey, I don't mean to disparage anyone's work here, but I've been making a good-faith effort to use HttpComponents since 4.0 came out and it's just not working for me.
Source: (StackOverflow)
When an unauthenticated client requests a URL that requires a non-anonymous access level as defined in security-config.xml
, spring security sends an HTTP redirect to our login page (e.g. /login
). That's fine.
The issue is that absent an existing session (identified by a cookie provided in the client's request), spring-security issues a redirect that also specifies the client's new session in the URL, e.g. /login;jsessionid=8o7pglapojus
.
Many containers support this (apparently it works fine in tomcat?), but it appears that Jetty (which is what we're using right now) does not -- the redirected URL comes through to our URL router completely intact (including the jsessionid
"parameter"), and the named session is not associated with the /login
request by jetty/spring-security (i.e. a totally new session ID is provided in the Set-Cookie header of the response to the /login
request).
We can work around this by matching /login.*
in our routes, but I'm curious if there's any way to prevent the emission of the session id in the authentication redirect to begin with.
Source: (StackOverflow)