Rest Service HttpStatus code 400 GET /user/%7Bid%7D - spring

I'm simply trying to get userdata via controller service interface But I'm always getting
[WARN] 400 - GET /user/%7Bid%7D (127.0.0.1) 1403 bytes
My Controller:
#Controller
#RequestMapping(value ="/user")
public class AdminSpringController {
#RequestMapping( value = "/{id}", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public #ResponseBody GWTUser getUser(#PathVariable Integer id) throws NotFoundException {
...
}
}
My Service, it's a restygwt interface:
#Path("/user")
public interface UserAdminRestService extends RestService {
#GET
#Path("/{id}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public void getUser(Integer id, MethodCallback<GWTUser> callback);
}
My servlet:
<servlet>
<servlet-name>userService</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/servlet/userService-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>userService</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
My servlet.xml
<context:component-scan base-package="com.app.admin.controller" />
<tx:annotation-driven />
<mvc:annotation-driven />
<!--This tag allows for mapping the DispatcherServlet to "/" (all extensions etc) -->
<mvc:default-servlet-handler/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
I Already have a method (user/users which returns all users, it's working fine but I think the problem is with my {id} (parameter variable), because it seems that my service or something parses my {id} as you can see at my error /user/%7Bid%7D. Thx for any help.

Missing #PathParam("id") in the service interface was the problem.
public void getUser(#PathParam("id") Integer id, MethodCallback<GWTUser> callback);
And for example UPDATE:
#PUT
#Path("/update")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public void update(GWTUser user, MethodCallback<UserServiceResponse> callback);
you need to set the RequestBody
#RequestMapping( value = "/update", method = RequestMethod.PUT)
#ResponseStatus(HttpStatus.OK)
public void update(#RequestBody GWTUser gwtUser) {

Related

spring #autowired NullPointerException from one Controller to another

I work with Spring and I want to call from one Controller to another Controller.
This is my application-context file
<context:annotation-config />
<context:component-scan base-package="com.renfe.cme.mybatis,renfe.informes.resumenjornadas" />
<bean id="resumenMensualJornadasBO" class="renfe.informes.resumenjornadas.ResumenMensualJornadasBO">
</bean>
I call the first Controller from a servlet
ResumenMensualJornadasServlet resumenMensualJornadasServlet = new ResumenMensualJornadasServlet();
resumenMensualJornadasServlet.llamarController(req);
This is ResumenMensualJornadasServlet
#Controller
public class ResumenMensualJornadasServlet
{
#Autowired
private ResumenMensualJornadasBO resumenMensualJornadasBO;
public void llamarController(HttpServletRequest req) throws Exception{
this.resumenMensualJornadasBO.cargarParametrosInforme(req);
}
}
ResumenMensualJornadasBO.java is
#Component
public class ResumenMensualJornadasBO
{
#Autowired
private ResumenMensualJornadasManager resumenMensualJornadasManager;
public void cargarParametrosInforme(HttpServletRequest req) throws Exception
{
String matricula = StringUtils.recuperarParametro(req, "matricula");
String fechaDesde = StringUtils.recuperarParametro(req, "fechadesde");
String fechaHasta = StringUtils.recuperarParametro(req, "fechahasta");
resumenMensualJornadasManager.obtenerDatos(matricula, fechaDesde, fechaHasta);
}
}
I get NullPointerException when I call
this.resumenMensualJornadasBO.cargarParametrosInforme(req);
How can I fix the error in #Autowired?
EDITED
In the web.xml I have
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:com/renfe/cme/recursos/spring/applicationContext-*.xml</param-value>
<description>Spring files location</description>
</context-param>
How can I get the bean from this context?

Spring interceptor not invoked

I am using spring and resteasy integration for exposing some REST based services. I am planning to use interceptors for logging and authentication but facing issues with interceptor invocation.
Controller class (using #Path for rest services)
#Controller
#Path("/v1.0/create")
public class ContollerClass{
#POST
#Path("/artifact")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public String someMethod(SampleVO sampleVO,#Context HttpServletRequest request) {
// Some functionality
}
acctrest-servlet.xml :
<context:component-scan base-package="com.comp.abc.xyz" />
<import resource="classpath:springmvc-resteasy.xml" />
<mvc:interceptors>
<bean class="com.comp.abc.xyz.interceptor.AuthenticationInterceptor" />
</mvc:interceptors>
Interceptor :
public class AuthenticationInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2) throws Exception {
System.out.println("pre handle ************************");
log.info("before handler execution");
String requestID = Long.toString(System.currentTimeMillis());
log.debug("request ID is {} :: ", requestID);
return true;
}
Web.xml
<servlet>
<servlet-name>acctrest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>acctrest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
Except the interceptor invocation, rest of the flow is working fine.

Spring Security with Java EE Restful Service

I have created a Java EE 6 restfull service and tried to integrate that with Spring Security. But, all the time I get different weird exceptions. Which doesn't make any sense or may be make sense but at least not for me.
Direction structure of my application is something like this:
com.security
UserDetailsSecurityConfig.java
com.service
ApplicationConfig.java
UserFacadeREST.java
com.config
AppConfig.java
My entities are auto generated so no error seems to be there. But, yes the three files seems fishy to me as UserFacadeREST is working fine when I don't integrate my application with Spring Security.
com.UserDetailsSecurityConfig.java
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(securedEnabled = true)
public class UserDetailsSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService( userDetailsService() );
}
#Override
protected void configure( HttpSecurity http ) throws Exception {
http
.httpBasic().and()
.sessionManagement().sessionCreationPolicy( SessionCreationPolicy.STATELESS ).and()
.authorizeRequests().antMatchers("/**").hasRole( "USER" );
}
#Bean
public UserDetailsService userDetailsService() {
return new UserDetailsService() {
#Override
public UserDetails loadUserByUsername( final String username )
throws UsernameNotFoundException {
if( username.equals( "admin" ) ) {
return new User( username, "password", true, true, true, true,
Arrays.asList(
new SimpleGrantedAuthority("ROLE_USER" ),
new SimpleGrantedAuthority( "ROLE_ADMIN" )
)
);
} else if ( username.equals( "user" ) ) {
return new User( username, "password", true, true, true, true,
Arrays.asList(
new SimpleGrantedAuthority( "ROLE_USER" )
)
);
}
return null;
}
};
}
}
com.service.ApplicationConfig.java
#javax.ws.rs.ApplicationPath("webresources")
public class ApplicationConfig extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
addRestResourceClasses(resources);
return resources;
}
/**
* Do not modify addRestResourceClasses() method.
* It is automatically populated with
* all resources defined in the project.
* If required, comment out calling this method in getClasses().
*/
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(com.service.UserFacadeREST.class);
}
}
com.service.UserFacadeREST.java
#Stateless
#Path("user")
public class UserFacadeREST extends AbstractFacade<UpUser> {
#PersistenceContext(unitName = "PU")
private EntityManager em;
public UserFacadeREST() {
super(User.class);
}
#POST
#Override
#Consumes({"application/xml", "application/json"})
public void create(User entity) {
super.create(entity);
}
#GET
#Path("count")
#Produces("text/plain")
public String countREST() {
return String.valueOf(super.count());
}
}
com.config.AppConfig.java
#Configuration
#Import( UserDetailsSecurityConfig.class )
public class AppConfig {
#Bean
public ApplicationConfig applicationConfig() {
return new ApplicationConfig();
}
#Bean
public UserFacadeREST userRestService() {
return new UserFacadeREST();
}
}
In whole code I have made few changes for hit and trial. And currently, I am getting an exception.
java.lang.IllegalStateException: No WebApplicationContext found: no
ContextLoaderListener registered?
Before that I was getting another exception which was
WebSecurityConfigurers must be unique. Order of 100 was already used
I am not getting what I am doing wrong in integrating Spring Security with Java EE 6. I am new to Spring so may be I am doing a blunder which seems obvious to me.
My web.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
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"
id="rest-sec" version="3.0">
<display-name>rest</display-name>
<!-- Spring security -->
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>etagFilter</filter-name>
<filter-class>org.springframework.web.filter.ShallowEtagHeaderFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>etagFilter</filter-name>
<url-pattern>/api/*</url-pattern>
</filter-mapping>
<!-- rest -->
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.labs.entities</param-value> <!-- won't find anything -->
</init-param>
<init-param>
<param-name>dispatchOptionsRequest</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<!-- Disables servlet container welcome file handling. Needed for compatibility
with Servlet 3.0 and Tomcat 7.0 -->
<welcome-file-list>
<welcome-file />
</welcome-file-list>
</web-app>
java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered?
You need to tell the filter where to look for your context (it's default is to look in a place that is not used by the servlet you created). In your filter add an init param:
<init-param>
<param-name>contextAttribute</param-name>
<param-value>org.springframework.web.servlet.FrameworkServlet.CONTEXT.spring</param-value>
</init-param>
WebSecurityConfigurers must be unique. Order of 100 was already used
Do you have 2 beans of type WebSecurityConfigurerAdapter? Or is your UserDetailsSecurityConfig being loaded twice?

Not being able to find my mapping anymore (spring - controller)

I am not being able to find my mapping anymore (I made it work. But then, I made changes, but probably due to cache, I didn't realize when it stopped working :-( ). It gives 404 error now when I click on submit on the form. Any help would be appreciated. Thank you in advance!
web.xml:
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
JSP:
<form:form method="POST" action="/app/app/studentSearchById" commandName="student">
Controller:
#Controller
// #RequestMapping("/studentSearch")
public class StudentSearchController {
// #Autowired
//StudentService userService = new StudentService();
// #RequestMapping(value="/StudentSearchById", method = RequestMethod.GET)
// public ModelAndView searchById(#PathVariable Long studentId) {
#RequestMapping(value = "/studentSearchById", method = RequestMethod.POST)
public ModelAndView searchById(#ModelAttribute("student") Student student, Map<String, Object> map,
HttpServletRequest request) {
StudentService userService = new StudentService();
Student studentFound = userService.findStudent(student.getStudentId());
ModelAndView modelAndView = new ModelAndView();
// modelAndView.addObject("students", studentFound);
return modelAndView;
}
Thank you a lot in advance!
When you are using stereotype annotation (#Controller , #Service, #Repository) then its better to use context: component-scan tag to say that Spring has to scan packages searching the annotation and register beans within the application context.
I spent hours on this... just after posting, I figured out...
I had changed the line on my spring-servlet.xml. Putting the line as before, it worked:
<context:component-scan base-package="my.controller.package" />

Autowiring in servlet

i want to use spring autowiring in servlet so here's my code:
#Configurable
public class ImageServlet extends HttpServlet {
#Autowired
private SystemPropertyDao systemPropertyDao;
#Override
public void init() throws ServletException {
String imagePath = systemPropertyDao.findByID(StaticParam.CONTENT_FOLDER);
}
while the SystemPropertyDao is annotated with #Repository
and my applicationContext.xml:
<context:component-scan base-package="com.basepackage" />
<mvc:annotation-driven />
<context:annotation-config />
<context:spring-configured/>
web.xml:
<servlet>
<servlet-name>imageServlet</servlet-name>
<servlet-class>com.xeno.basepackage.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>imageServlet</servlet-name>
<url-pattern>/myimages/*</url-pattern>
</servlet-mapping>
sometimes the autowiring works and sometimes it doesn't (the reference to the spring bean systemPropertyDao is null), can anyone please tell me if i am missing something?
I followed the solution in the following link, and it works fine:
Access Spring beans from a servlet in JBoss
public class MyServlet extends HttpServlet {
#Autowired
private MyService myService;
public void init(ServletConfig config) {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
config.getServletContext());
}
}
Remove the #Configurable annotation from your servlet and add:
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext (this);
at the first line of your init() method.

Resources