Guice 3.0 with Jersey and Async Servlets - java

Trying to build an application that uses #Suspended and AsyncResponse but cannot get it to work, my app works fine without the use of AsyncResponse.
Below is the stacktrace
Sep 30, 2014 4:40:07 PM org.apache.catalina.core.StandardContext filterStart
SEVERE: Exception starting filter guiceFilter
com.sun.jersey.spi.inject.Errors$ErrorMessagesException
at com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)
at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199)
at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:795)
at com.sun.jersey.guice.spi.container.servlet.GuiceContainer.initiate(GuiceContainer.java:121)
at com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:321)
at com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:207)
at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:376)
at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:559)
at javax.servlet.GenericServlet.init(GenericServlet.java:160)
at com.google.inject.servlet.ServletDefinition.init(ServletDefinition.java:117)
at com.google.inject.servlet.ManagedServletPipeline.init(ManagedServletPipeline.java:82)
at com.google.inject.servlet.ManagedFilterPipeline.initPipeline(ManagedFilterPipeline.java:102)
at com.google.inject.servlet.GuiceFilter.init(GuiceFilter.java:172)
at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:281)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:262)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:107)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4775)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5452)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)

I don't quite understand your error, but AFAIK Guice does not support async servlets: https://github.com/google/guice/issues/650
Follows my Jersey setup with Guice, in case it's usefull.
The module I need to install on Guice:
import javax.inject.Singleton;
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import com.sun.jersey.guice.JerseyServletModule;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
import com.company.internal.app.ws.example.HelloWorld;
public class ApplicationRestModule extends JerseyServletModule {
#Override
protected void configureServlets() {
super.configureServlets();
serve("/rest/*").with(GuiceContainer.class);
// Binding services
bind(HelloWorld.class);
bind(JacksonJsonProvider.class).in(Singleton.class);
}
}
A service example:
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
#Path("/hello")
public class HelloWorld {
#GET
#Path("/echo/{input}")
#Produces("text/plain")
public String ping(#PathParam("input") String input) {
return input;
}
#POST
#Produces("application/json")
#Consumes("application/json")
#Path("/jsonBean")
public Response modifyJson(JsonBean input) {
input.setVal2(input.getVal1());
return Response.ok().entity(input).build();
}
}
Hope it helps!

Related

Can't create RestTemplate() instance from spring-web

I am using tomcat web application and rest webservice
when I insert data I get exception !
My class CustomerProxy:
package com.rayanen.java.se.cmsd.proxy;
import com.rayanen.java.se.cmsd.dto.CustomerDTO;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import javax.faces.context.FacesContext;
#Component
public class CustomerProxy implements ICustomerProxy{
#Override
public void insertCustomer(CustomerDTO customerDTO) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders requestHeaders = new HttpHeaders();
String headerValue = FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap().get("cookie");
requestHeaders.add("Cookie", headerValue);
HttpEntity requestEntity = new HttpEntity(customerDTO, requestHeaders);
ResponseEntity response = restTemplate.exchange(
"http://localhost:8080/ws/customer/insert",
HttpMethod.POST,
requestEntity,
CustomerDTO.class);
/*return response.getBody();*/
}
}
class CustomerRestController :
package com.rayanen.java.se.cmsd.ws;
import com.rayanen.java.se.cmsd.dto.CustomerDTO;
import com.rayanen.java.se.cmsd.exceptions.*;
import com.rayanen.java.se.cmsd.facade.facadeimpl.CustomerFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping(value = "/customer")
public class CustomerRestController {
#Autowired
private CustomerFacade customerFacade;
#RequestMapping(method = RequestMethod.POST, value = "/insert")
ResponseEntity insert(#RequestBody CustomerDTO customerDTO){
try {
customerFacade.save(customerDTO);
} catch (StoreFailedException e) {
e.printStackTrace();
} catch (CustomerIDDuplicateException e) {
e.printStackTrace();
} catch (EmailNotValidException e) {
e.printStackTrace();
} catch (CustomerIDNotValidExeption customerIDNotValidExeption) {
customerIDNotValidExeption.printStackTrace();
} catch (LastNameNotValidException e) {
e.printStackTrace();
} catch (NameNotValidException e) {
e.printStackTrace();
}
return new ResponseEntity(HttpStatus.OK);
}
}
class CustomerBean :
package com.rayanen.java.se.cmsd.webui;
import com.rayanen.java.se.cmsd.dto.CustomerDTO;
import com.rayanen.java.se.cmsd.exceptions.*;
import com.rayanen.java.se.cmsd.facade.facadeimpl.CustomerFacade;
import com.rayanen.java.se.cmsd.proxy.ICustomerProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import java.io.Serializable;
#Component
#Scope("view")
public class CustomerBean implements Serializable{
private CustomerDTO customerDTO = new CustomerDTO();
private String lable;
#Autowired
private CustomerFacade customerFacade;
#Autowired
private ICustomerProxy iCustomerProxy;
public String getLable() {
return lable;
}
public void setLable(String lable) {
this.lable = lable;
}
public CustomerDTO getCustomerDTO() {
return customerDTO;
}
public void setCustomerDTO(CustomerDTO customerDTO) {
this.customerDTO = customerDTO;
}
public void insert(ActionEvent actionEvent){
lable = customerDTO.getName() + "; " + customerDTO.getLastName();
iCustomerProxy.insertCustomer(customerDTO);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Added Successfully", ""));
}
}
and the Exeption after inserting data that I debug and Find out Exception is for this :
RestTemplate restTemplate = new RestTemplate();
20-Nov-2017 23:06:04.211 WARNING [http-nio-8080-exec-5]
com.sun.faces.lifecycle.InvokeApplicationPhase.execute
/customer/insert.xhtml #43,134
actionListener="#{customerBean.insert}":
java.lang.NoClassDefFoundError:
org/springframework/core/KotlinDetector javax.el.ELException:
/customer/insert.xhtml #43,134
actionListener="#{customerBean.insert}":
java.lang.NoClassDefFoundError:
org/springframework/core/KotlinDetector at
com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:111)
at
javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:147)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at
javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:813)
at javax.faces.component.UICommand.broadcast(UICommand.java:300) at
javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at
javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at
com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at
com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
com.rayanen.java.se.cmsd.webui.LoginFilter.doFilter(LoginFilter.java:30)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748) Caused by:
java.lang.NoClassDefFoundError:
org/springframework/core/KotlinDetector at
org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.registerWellKnownModulesIfAvailable(Jackson2ObjectMapperBuilder.java:766)
at
org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.configure(Jackson2ObjectMapperBuilder.java:619)
at
org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.build(Jackson2ObjectMapperBuilder.java:602)
at
org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.(MappingJackson2HttpMessageConverter.java:59)
at
org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter.(AllEncompassingFormHttpMessageConverter.java:67)
at
org.springframework.web.client.RestTemplate.(RestTemplate.java:171)
at
com.rayanen.java.se.cmsd.proxy.CustomerProxy.insertCustomer(CustomerProxy.java:22)
at
com.rayanen.java.se.cmsd.webui.CustomerBean.insert(CustomerBean.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498) at
org.apache.el.parser.AstValue.invoke(AstValue.java:247) at
org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
at
com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
... 34 more Caused by: java.lang.ClassNotFoundException:
org.springframework.core.KotlinDetector at
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1333)
at
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1167)
... 49 more
Any help would be appreciated.
Yup, as #Kayaman pointed out in comments, adding spring core dependency should solves it.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
The problem was for my other dependencies version
I changed them and problem solved

Shiro using spring gives " Shiro INI configuration was either not found or discovered to be empty/unconfigured."

I was able to get shiro running with shiro.ini and spring but I want to use shiro annotations and so i was trying to go for shiro-spring without ini file. but this is giving me hard time,
Error:
org.apache.shiro.config.ConfigurationException: Shiro INI configuration was either not found or discovered to be empty/unconfigured.
at org.apache.shiro.web.env.IniWebEnvironment.init(IniWebEnvironment.java:87)
at org.apache.shiro.util.LifecycleUtils.init(LifecycleUtils.java:45)
at org.apache.shiro.util.LifecycleUtils.init(LifecycleUtils.java:40)
at org.apache.shiro.web.env.EnvironmentLoader.createEnvironment(EnvironmentLoader.java:226)
at org.apache.shiro.web.env.EnvironmentLoader.initEnvironment(EnvironmentLoader.java:138)
at org.apache.shiro.web.env.EnvironmentLoaderListener.contextInitialized(EnvironmentLoaderListener.java:58)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4742)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5206)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1439)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1429)
at java.util.concurrent.FutureTask.run(Unknown Source)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:953)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:872)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1439)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1429)
at java.util.concurrent.FutureTask.run(Unknown Source)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:953)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:793)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.startup.Catalina.start(Catalina.java:655)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:355)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:495)
Apr 09, 2017 4:15:32 PM org.apache.catalina.core.StandardContext startInternal
Code: Spring config:
package com.studentshare.config;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.studentshare")
public class AppConfig {
#Bean
public JdbcRealm myRealm() {
JdbcRealm jdbcRealm = new JdbcRealm();
jdbcRealm.setAuthenticationQuery("select password from unishare.users where user_name = ?");
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setServerName("localhost");
dataSource.setUser("root");
dataSource.setPassword("root");
dataSource.setDatabaseName("unishare");
jdbcRealm.setDataSource(dataSource);
jdbcRealm.setCredentialsMatcher(new HashedCredentialsMatcher());
return jdbcRealm;
}
#Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
#Bean
public DefaultWebSecurityManager securityManager(#Autowired JdbcRealm myRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(myRealm);
return securityManager;
}
#Bean
public BasicHttpAuthenticationFilter myAuthBasic(){
return new BasicHttpAuthenticationFilter();
}
#Bean
public ShiroFilterFactoryBean ShiroFilter(#Autowired DefaultWebSecurityManager securityManager,#Autowired BasicHttpAuthenticationFilter myAuthBasic) {
ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
shiroFilter.setSecurityManager(securityManager);
Map<String, Filter> filters = new HashMap<>();
filters.put("myAuthcBasic", myAuthBasic);
shiroFilter.setFilters(filters);
/*Map<String, String> filterChainDefinitionMap = new HashMap<>();
filterChainDefinitionMap.put("/", "authcBasic");*/
shiroFilter.setFilterChainDefinitions("/ = myAuthcBasic");//p(filterChainDefinitionMap);
return shiroFilter;
}
#DependsOn("lifecycleBeanPostProcessor")
#Bean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
return new DefaultAdvisorAutoProxyCreator();
}
}
Web configuration:
package com.studentshare.config;
import java.util.EnumSet;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.apache.shiro.web.env.EnvironmentLoaderListener;
import org.apache.shiro.web.servlet.ShiroFilter;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected Class[] getServletConfigClasses() {
return null;
}
#Override
protected Filter[] getServletFilters() {
return new Filter[] { new ShiroFilter() };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.addListener(EnvironmentLoaderListener.class);
EnumSet<DispatcherType> shiroDispatchers = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
DispatcherType.INCLUDE, DispatcherType.ERROR);
FilterRegistration shiroFilter = servletContext.addFilter("ShiroFilter", DelegatingFilterProxy.class);
shiroFilter.setInitParameter("targetFilterLifecycle", "true");
shiroFilter.addMappingForUrlPatterns(shiroDispatchers, false,
"/*");
}
}
Take a look at the 1.4+ release, the Spring integration has been updated (for Spring, and Spring Boot).
But for your specific problem, it looks like you are trying to use a the EnvironmentLoaderListener. When using Spring, you will need to let Spring handle the lifecycle of loading your components.
For an example see: https://github.com/apache/shiro/blob/1.3.x/samples/spring-hibernate/src/main/webapp/WEB-INF/web.xml

How to return text_html type response in Jersey

I am developing a REST API using jersey jax-RS. This consumes data in JSON format and produces the output in html format.
When I set the MediaType for #Produces as TEXT_HTML and #Consumes as #APPLICATON_JSON and requested the 'GET' query on POSTMAN REST client, it gave me the following error:
org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Jersey Web Application] in context with path [/try2] threw exception [org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=text/html, type=class java.util.ArrayList, genericType=java.util.List<org.sc.try2.model.Event>.] with root cause
org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=text/html, type=class java.util.ArrayList, genericType=java.util.List<org.sc.try2.model.Event>.
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:247)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:103)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:88)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1154)
at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:613)
at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:375)
at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:365)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:272)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:297)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:252)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1025)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:372)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:382)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:345)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:220)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
My codes :
StudentResource.java
package org.sc.try2.resources;
//import java.awt.Event;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
//import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.sc.try2.model.Student;
import org.sc.try2.service.StudentService;
#Path("/students")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.TEXT_HTML)
public class StudentResource {
StudentService studentService = new StudentService();
//EventService es = new EventService();
#GET
#Path("/{studentEmail}/viewAll")
public List<Student> getStudents(#PathParam("studentEmail") String emailID){
System.out.println("cmn in this method of StudentResource........ ");
return studentService.getAllStudents(emailID);
}
#GET
#Path("/{studentEmail}/viewMyProfile")
public Student getStudent(#PathParam("studentEmail") String emailID){
System.out.println("cmn in this method of StudentResource........ ");
return studentService.getStudent(emailID);
}
#Path("/{studentEmail}/events")
public AllEventsResource getEvents(){
System.out.println("cmn in this method of StudentResource ");
return new AllEventsResource();
}
#Path("/{studentEmail}/myevents")
public EventResource getStudentEvents(){
return new EventResource();
}
#PUT
#Path("/{studentEmail}/updateProfile")
public String updateStudent(#PathParam("studentEmail") String emailID,Student student){
//student.setEmailID(emailID);
return studentService.updateStudent(emailID,student);
}
#DELETE
#Path("/{studentEmail}/deleteStudent/{delEmail}")
public String deleteStudent(#PathParam("studentEmail") String emailID,#PathParam("delEmail") String delEmail){
return studentService.removeStudent(emailID,delEmail);
}
}
EventsResource.java
package org.sc.try2.resources;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.sc.try2.model.Event;
import org.sc.try2.service.EventService;
#Path("/")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.TEXT_HTML)
public class EventResource {
EventService es = new EventService();
#GET
public List<Event> getMyEvents(#PathParam("studentEmail") String emailID){
System.out.println("cmn in this method of EventsResource ");
return es.getAllEventsForStudent(emailID);
}
#POST
public String addEvent(#PathParam("studentEmail") String email,Event event){
System.out.println("here in res add evnt..");
return es.addEvent(email,event);
}
#PUT
#Path("/{eventId}")
public String updateEvent(#PathParam("studentEmail") String email,#PathParam("eventId") long id,Event event){
event.seteID(id);
return es.updateEvent(email,id,event);
}
#DELETE
#Path("/{eventId}")
public String deleteEvent(#PathParam("studentEmail") String email,#PathParam("eventId") long id){
return es.removeEvent(email,id);
}
}
On searching about this on the internet, I did not come across any useful solution except it was mentioned to download the genson jar and add it. After adding it as external jar in Eclipse (Java EE) MAVEN Project, it still gave the same exception which I guess is due to the fact that this jar is for json MediaType and is not used in the context of html content type.
Basically, I want to produce the content as HTML. How can I do it? I am entirely new to Jersey and the concept of REST API.

Issue while accessing post method in CXF rest service

i am trying to create a simple Restful web service and client using CXF 3.1.2 as below,
Service:
package com.rs.sample;
import javax.jws.WebService;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
public class GenServiceImpl {
#GET
#Produces(MediaType.TEXT_PLAIN)
#Consumes(MediaType.TEXT_PLAIN)
#Path("/login/{ext}")
public String login(#PathParam("ext") Integer ext) {
return "LoggedIn";
}
#POST
#Produces(MediaType.TEXT_PLAIN)
#Consumes(MediaType.TEXT_PLAIN)
#Path("/logout/{ext}")
public String logout(#PathParam("ext") Integer ext) {
return "LoggedOut";
}
}
Client:
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.cxf.jaxrs.client.WebClient;
public class TestClient {
static final String REST_URI = "http://localhost:8080/RestfulSample/Restful";
public static void main(String[] args) {
WebClient client = WebClient.create(REST_URI);
/*
//Get
client.path("login").path(new Integer(1234)).accept(MediaType.TEXT_PLAIN);
String loginResponse = client.get(String.class);
System.out.println(loginResponse); */
//Post
client.path("logout").accept(MediaType.TEXT_PLAIN);
String logoutResponse = client.post("1024").toString();
System.out.println(logoutResponse);
}
Here i have no problem in accesing login(Get) method and it is working as expected.
But when i tried to access logout(Post) method i am getting the below error,
WARNING: No operation matching request path "/RestfulSample/Restful/agentLogout" is found, Relative Path: /agentLogout, HTTP Method: POST, ContentType: application/xml, Accept: text/plain,. Please enable FINE/TRACE log level for more details.
Nov 04, 2015 3:49:32 PM org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper toResponse
WARNING: javax.ws.rs.ClientErrorException: HTTP 404 Not Found
at org.apache.cxf.jaxrs.utils.SpecExceptions.toHttpException(SpecExceptions.java:117)
at org.apache.cxf.jaxrs.utils.ExceptionUtils.toHttpException(ExceptionUtils.java:162)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.findTargetMethod(JAXRSUtils.java:528)
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.processRequest(JAXRSInInterceptor.java:177)
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.handleMessage(JAXRSInInterceptor.java:77)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:251)
at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:234)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:208)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:160)
at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:171)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:293)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:212)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:268)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Could you please correct my mistake
Thanks,
#Path("/logout/{ext}"). You need another path segment after /logout. Whatever the value of {ext} should be
client.post("1024") is the body of the request. #PathParam is for the URI, so you need to add 1024 to the URI path, i.e. path("logout").path("1024"). Right now without the 1024 in the path, the endpoint doesn't exist (hence 404).
If you want to put the data in the POST body, then change it to #Path("/logout"), take out the #PathParam, and make the method param type String. You will need to parse it yourself

Unable to get basic implementation of Freemarker working

I am trying to configure a Freemarker template from a Servlet like so:
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
#WebServlet("/Controller")
public class Controller extends HttpServlet {
// class fields
private static final long serialVersionUID = 1L;
private static final String views = "/WEB-INF/views/";
public Controller(){
}
// used to handle any get requests i.e. webpage navigation
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Configuration conf = new Configuration();
conf.setClassForTemplateLoading(Controller.class, views);
conf.setDefaultEncoding("UTF-8");
Template indexTemplate = conf.getTemplate("index.ftl");
StringWriter writer = new StringWriter();
Map<String, Object> indexMap = new HashMap<String, Object>();
indexMap.put("name", "Chris");
try {
indexTemplate.process(indexMap, writer);
} catch (TemplateException e) {
e.printStackTrace();
}
System.out.println(writer);
}
}
But I get the following error when I startup the Tomcat server:
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/webapp]]
at java.util.concurrent.FutureTask.report(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1122)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:819)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/webapp]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
... 6 more
Here is the file structure:
What am I doing wrong here?

Categories

Resources