I have a rest jersey application like this
#ApplicationPath("/rest")
public class HelloApp extends Application
{
public HelloApp() throws Exception {
//also tried throwing Runtimeexcpetion
throw new Exception();
}
#Override
public Set<Class<?>> getClasses()
{
Set<Class<?>> s = new HashSet<Class<?>>();
s.add(HelloWorldService.class);
return s;
}
}
This is the web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0" 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-app_3_0.xsd">
<display-name>REST Web Application Demo</display-name>
<servlet>
<servlet-name>jersey.hello</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>rest.demo.HelloApp</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey.hello</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
I packaged the above to a war file and then used in the following tomcat embedded program
public class WarExample {
public static void main(String[] args) throws ServletException, LifecycleException {
Tomcat tomcat = new Tomcat();
tomcat.setBaseDir("temp");
tomcat.setPort(8080);
String contextPath = "/";
String warFilePath = "path to war file";
tomcat.getHost().setAppBase(".");
Context context = tomcat.addWebapp(contextPath, warFilePath);
context.addLifecycleListener(new LifecycleListener() {
public void lifecycleEvent(LifecycleEvent event) {
System.out.println(event.getLifecycle().getStateName());
//do something if event.getLifecycle().getState() == LifecycleState.FAILED
}
});
tomcat.start();
tomcat.getServer().await();
}
}
I added a lifecycle listener to context that is returned by adding war as webapp. I am getting Starting and Started states but not seeing any other states here.
Even though i am throwing an exception/runtimeexception from my jersey rest application why is tomcat embedded still not throwing failed state.
i had to add this for tomcat to publish failed state
final Host host = tomcat.getHost();
if (host instanceof StandardHost) {
((StandardHost) tomcat.getHost()).setFailCtxIfServletStartFails(true);
}
Related
Even if the <load-on-startup>1</load-on-startup> the servlet does not auto-load
<servlet>
<servlet-name>RestletServlet</servlet-name>
<servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class>
<init-param>
<param-name>org.restlet.application</param-name>
<param-value>com.mycompany.MyRestletApplication</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
public class MyRestletApplication extends Application {
#Override
public Restlet createInboundRoot() {
String process = ManagementFactory.getRuntimeMXBean().getName();
System.out.println("Started with Process id: " + process);
Router router = new Router(getContext());
router.attachDefault(ServerResource.class);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("Terminating database");
}));
return router;
}
}
What could be missing here?
I am trying to register an interceptor for my rest application. The purpouse of this interceptor is to get a token inside the request to validate if the request is valid or not.
I have created a custom tag to achieve this:
#Provider
#Secured
public class AuthenticationFilter implements ContainerRequestFilter{
private static final Logger LOGGER = Logger.getLogger(AuthenticationFilter.class);
UserDAO userDAO = (UserDAO) SpringApplicationContext.getBean("userDAO");
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// Get the HTTP Authorization header from the request
String authorizationHeader =
requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
// Check if the HTTP Authorization header is present and formatted correctly
if (authorizationHeader == null || !authorizationHeader.startsWith("BSC")) {
if (authorizationHeader== null){
LOGGER.error("No authorization header");
} else{
LOGGER.error("Authorization header: " + authorizationHeader);
}
throw new NotAuthorizedException("Authorization header must be provided");
}
// Extract the token from the HTTP Authorization header
String token = authorizationHeader.substring("BSC".length());
// Validate the token
boolean ok = validateToken(token);
if (!ok){
LOGGER.error("Not authorized, passed token: " + token);
throw new NotAuthorizedException("Not authorized");
}
}
private boolean validateToken(String token){
boolean ok = userDAO.validateToken(token);
if (ok){
userDAO.updateToken(token);
}else{
userDAO.deleteToken(token);
}
return ok;
}
}
#NameBinding
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.TYPE, ElementType.METHOD})
public #interface Secured {
}
All of the methods with the #Secured tag must pass throught the interceptor.
I have registered the interceptor and the rest service in a class that extends Application:
public class RestApplication extends Application{
private Set<Object> singletons = new HashSet<Object>();
public RestApplication() {
singletons.add(new RestService());
singletons.add(new AuthenticationFilter());
}
#Override
public Set<Object> getSingletons() {
return singletons;
}
}
Then in my web.xml I have registered this class:
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Manufacturing</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>
com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.everis.manufacturing.application.RestApplication</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
But it not seems to work, I am calling a service that have the #Secured tag but it isnĀ“t calling the interceptor.
Thanks in advance!
try changing the class RestApplication to extend ResourceConfig instead of Application.
Below is my web.xml
<servlet>
<servlet-name>DispatcherName</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/spring/webmvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
Is there any way that I can get the servlet-name "DispatcherName" in my application controller?
I want this to access the controller objects from the XMLWebApplicationContext & to do that I need the RequestDispatcher Name.
Till now this is what I've tried:
webApplicationContext=WebApplicationContextUtils.getWebApplicationContext(GetServletContextWebListner.getServletContext());
XmlWebApplicationContext xmlWebApplicationContext = (XmlWebApplicationContext)GetServletContextWebListner.getServletContext().getAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT."+webApplicationContext.getApplicationName().replace("/", ""));
and tried this too
#WebListener
public class GetServletContextWebListner implements ServletContextListener {
private static ServletContext servletContext;
public static ServletContext getServletContext() {
return servletContext;
}
#Override
public void contextInitialized(ServletContextEvent sce) {
servletContext = sce.getServletContext();
}
#Override
public void contextDestroyed(ServletContextEvent sce) {
servletContext = null;
}
}
and
(XmlWebApplicationContext)GetServletContextWebListner.getServletContext().getServletContextName()
Since I'm not able to get the servlet name, I'm using the getApplicationName() but this may vary with the servlet name.
in you controller, you may try :
request.getServletContext().getServletContextName()
Or
RequestContextUtils.getWebApplicationContext(request).getDisplayName()
I can't fathom why this isn't working. Inside a Jersey resource method I make an asynchronous call, but the code blocks and never returns. Testing with curl, my terminal just hangs. From application logs, I can tell the request got intercepted and the code was executed.
Using Jersey 2.8 with maven tomcat7 plugin.
I also tried using an Executor Service instead of creating the thread directly, this is how I'd prefer to do it. Changed to creating a thread directly to be close to the documentation.
Jersey code:
#Path("/trade")
public class TradeEndpoint {
// TODO: make this configurable!!
private ExecutorService threadPool = Executors.newFixedThreadPool(10);
private static MyService myService;
static {
//issues getting Spring working, so get it like this
orderFillService = Bootstrapper.getOrderFillService();
}
#GET
public String getFoo() {
return "Foo";
}
#POST
#Path("limit")
#Consumes({ MediaType.APPLICATION_JSON })
public void limitOrder(#Suspended final AsyncResponse response, Model model) {
System.out.println(model);
new Thread( new Runnable() {
public void run() {
myService.doStuff(model);
}
}).start();
System.out.println("SUBMITTED");
}
Web.xml
<web-app version="2.5" 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-app_2_5.xsd">
<servlet>
<servlet-name>web</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.foo.conf.Application</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>web</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
I'm trying to build a java websocket server. I've written a simple server endpoint:
#ServerEndpoint(value = "/test")
public class EndPoint {
static Queue<Session> queue = new ConcurrentLinkedQueue<Session>();
public static void send(int a, int b) {
try {
for(Session session : queue) {
session.getBasicRemote().sendText("a = " + a + ",b=" + b);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
#OnOpen
public void openConnection(Session session) {
queue.add(session);
}
#OnClose
public void closeConnection(Session session) {
queue.remove(session);
}
#OnError
public void error(Session session, Throwable t) {
queue.remove(session);
}
}
My web.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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-app_2_5.xsd">
</web-app>
When I hit ws://localhost:8080/websocket-1.0/test from Javascript, I get a 404 response. I'm using tomcat 8 to deploy this. What am I missing here?
1) Use latest version of Tomcat 7.0.x or latest version of Tomcat 8.0.x
2) Make sure your war contains only the ServerEndpoint classes and an empty web.xml. Tomcat automatically scans and loads the classes annotated with ServerEndpoint annotation
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1"
metadata-complete="true">
</web-app>
3) Verify that catalina.out has the following log msg and there are no exceptions.
org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive /usr/local/tomcat/apache-tomcat-8.0.12/webapps/.war
According to this link https://tyrus.java.net/documentation/1.4/index/websocket-api.html and my expereince the endpoint should match the ws: url
E.g.
#ServerEndpoint(value = "/test")
ws://localhost:8080/test
or
#ServerEndpoint(value = "/websocket-1.0//test")
ws://localhost:8080/websocket-1.0/test