Multiple Contexts For Request Scope? - tomcat7

I am attempting to use Weld with Tomcat7 and Jersey, and in my log files I am seeing this:
org.jboss.weld.exceptions.IllegalStateException: WELD-001304: More than one context active for scope type javax.enterprise.context.RequestScoped
The application deploys properly and I only see this when attempting to hit on my Jersey endpoints.
Here is the pertinent parts of the pom.xml
<!-- Jersey Deps -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-bean-validation</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
</dependency>
<!-- CDI Deps -->
<dependency>
<groupId>org.jboss.weld.servlet</groupId>
<artifactId>weld-servlet</artifactId>
<version>2.3.2.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext.cdi</groupId>
<artifactId>jersey-weld2-se</artifactId>
</dependency>
And here's my "MainApplication" that extends ResourceConfig:
public class MainApplication extends ResourceConfig {
public MainApplication() {
packages(true, "com.example.api");
property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);
property(ServerProperties.BV_DISABLE_VALIDATE_ON_EXECUTABLE_OVERRIDE_CHECK, true);
}
}
Here's my web.xml (the servlet section):
<servlet>
<servlet-name>Jersey Servlet Container</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>net.di2e.isfr.foldr.MainApplication</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Servlet Container</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
I am uber-confsued what could be going wrong.

Related

JAVA Migration from jdk1.7 and weblogic 12c to jdk 1.8 and weblogic 14c

i ve migrate a web application from weblogic 12c and jdk1.7 to weblogic 14c and jdk1.8. The web application use jax-re for rest services and has the following custom JacksonContextProvider for mapping json:
package eu.sia.mdp.backoffice.common;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
/**
* ObjectMapper settings
*
* #author g.palladino
*
*/
#Provider
#Produces(MediaType.APPLICATION_JSON)
public class JacksonContextResolver implements ContextResolver<ObjectMapper> {
private final ObjectMapper objectMapper;
private static final Logger log = LoggerFactory.getLogger( JacksonContextResolver.class );
public JacksonContextResolver() {
this.objectMapper = new ObjectMapper().setSerializationInclusion(Include.NON_NULL);
// DATEFORMAT DF = NEW SIMPLEDATEFORMAT("YYYY-MM-DD HH:MM:SS.SSSZ");
// this.objectMapper.setDateFormat(df);
this.objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
this.objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
this.objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT,true);
this.objectMapper.getSerializationConfig().getDateFormat().setTimeZone(TimeZone.getTimeZone("CET"));
}
#Override
public ObjectMapper getContext(Class<?> objectType) {
return null;
}
}
the application, for the webservices, use the jax-rs 2.0.1 and jersey 2.29 provided by server weblogic 14.1.1 (14c). In version built with jdk1.7 and deployed on server weblogic 12c the libraries was not provided by the server but put in pom file without scope provided and the custom ContextResolver was worked fine. Now, with provided libraries, the custom ContextResolver is completely ignored and the webservices return json in a format that is not as i want, for example the dates was in the format 'yyyy-MM-ddTHH:mm:ss.SSSZ' (2022-12-16T11:33:21.123 0100' and now I receive the dates in the format 'yyyy-MM-ddTHH:mm:ss.SSSZ [UTC]' (2022-12-16T11:33:21.123Z [UTC]) and if pass this date to a rest service in my application i have the type mismatch error. Seems that is used the server's ObjectMapper.
could someone help me figure out how to configure the weblogic.xml and/or web.xml files to pass the jax-rs and jersey libraries without provided scope in order to then use the custom ObjectMapper in the class JacksonContextResolver implements ContextResolver ObjectMapper and not the server ObjectMapper???
the current server is Weblogic 14.1.1.
pom file:
<!-- JAX-RS -->
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
<scope>provided</scope>
</dependency>
<!--<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1.1</version>
<scope>provided</scope>
</dependency>-->
<!-- CDI -->
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
<!-- Jersey -->
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>${jersey.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-bean-validation</artifactId>
<version>${jersey.version}</version>
<scope>provided</scope>
</dependency>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
metadata-complete="false">
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>eu.sia.mdp.backoffice</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.tracing</param-name>
<param-value>ALL</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
<mime-mapping>
<extension>json</extension>
<mime-type>application/json</mime-type>
</mime-mapping>
<resource-ref>
<description>Database MP</description>
<res-ref-name>jdbc/MPDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
weblogic.xml
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-web-app xmlns="...">
<container-descriptor>
<prefer-application-packages>
<package-name>org.slf4j.*</package-name>
<package-name>org.apache.commons.logging.*</package-name>
<package-name>com.sun.jersey.*</package-name>
<!--<package-name>org.glassfish.jersey.*</package-name>
<package-name>org.glassfish.hk2.*</package-name>-->
<package-name>org.jvnet.hk2.*</package-name>
<!--<package-name>jersey.repackaged.org.objectweb.asm.*</package-name>-->
<package-name>org.objectweb.asm.*</package-name>
<package-name>com.sun.ws.rs.ext.*</package-name>
<!--<package-name>javax.ws.rs.*</package-name>
<package-name>javax.validation.*</package-name>-->
<package-name>org.hibernate.validator.*</package-name>
</prefer-application-packages>
<prefer-application-resources>
<resource-name>org/slf4j/impl/StaticLoggerBinder.class</resource-name>
<resource-name>org.hibernate.validator.*</resource-name>
<resource-name>javax.validation.*</resource-name>
</prefer-application-resources>
</container-descriptor>
<context-root>mdp-portale-bo</context-root>
<library-ref>
<library-name>jax-rs</library-name>
<specification-version>2.0</specification-version>
<exact-match>false</exact-match>
</library-ref>
<resource-description>
<res-ref-name>jdbc/MDPDB</res-ref-name>
<jndi-name>jdbc/MDPDB</jndi-name>
</resource-description>
</weblogic-web-app>
Thanks

#RequestMapping does not redirect me to my url

I am entering Spring MVC but it does not redirect me to the url with the RequestMappin, it only does it with the main page but with the others if I add it manual it does not execute, what can I have wrong?
the url that I use to enter login is http://localhost:8080/spring-mvc/login
#WebServlet(urlPatterns = "/login.do") <------------------This work
public class LoginServlet extends HttpServlet {
private LoginService service = new LoginService();
#Controller
public class LoginController { <!---------------------------This not-->
#RequestMapping(value="/login")
#ResponseBody
public String decirHola() {
return "Hola a todos";
}
<welcome-file-list>
<welcome-file>login.do</welcome-file>
</welcome-file-list>
<servlet>
`<servlet-name>dispatcher</servlet-name>`
` <servlet-class>`
` org.springframework.web.servlet.DispatcherServlet`
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/todo-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
``` <servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/spring-mvc/*</url-pattern>
</servlet-mapping>
<!-- pom -->
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.2.RELEASE</version>
</dependency>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>`

How Spring Data REST return hibernate-JPA validation & server internal errors in json not stack trace

I want to get JPA validation and server internal error on JSON format and not stack trace,
Using Spring JPA data rest
MyEntity Repository
#RepositoryRestResource(path = "entity")
public interface MyEntityRepo extends CrudRepository<MyEntity, Long> {}
When post without name, address property i expect NOT NULL validation error.
curl -i -X POST -H "Content-Type: application/json" -d '{"name":"not passed and #NotNull","address":"not passed and #NotNull","city":"city","area":"area"}' http://localhost:8080/clinicfinder/api/entity
Current return :
HTTP Status 500 - Request processing failed; nested exception is org.springframework.data.rest.core.RepositoryConstraintViolationException:Validation failed
org.springframework.data.rest.core.event.ValidatingRepositoryEventListener.validate(ValidatingRepositoryEventListener.java:179)
org.springframework.data.rest.core.event.ValidatingRepositoryEventListener.onBeforeCreate(ValidatingRepositoryEventListener.java:96)
org.springframework.data.rest.core.event.AbstractRepositoryEventListener.onApplicationEvent(AbstractRepositoryEventListener.java:50)
org.springframework.data.rest.core.event.AbstractRepositoryEventListener.onApplicationEvent(AbstractRepositoryEventListener.java:29)
org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167)
org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:383)
org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:337)
org.springframework.data.rest.webmvc.RepositoryEntityController.createAndReturn(RepositoryEntityController.java:484)
org.springframework.data.rest.webmvc.RepositoryEntityController.postCollectionResource(RepositoryEntityController.java:272)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:483)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Needed Return:
response 404, {"errors":[{"entity":"MyEntity","message":"may not be null","invalidValue":"null","property":"name"},{"entity":"MyEntity","message":"may not be null","invalidValue":"null","property":"address"}]}
Pom
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.6</maven.compiler.source>
<maven.compiler.target>1.6</maven.compiler.target>
<spring.data.jpa.version>1.11.1.RELEASE</spring.data.jpa.version>
<spring.data.rest.webmvc.version>2.6.1.RELEASE</spring.data.rest.webmvc.version>
</properties>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!-- Spring Rest Repository -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring.data.jpa.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
<version>${spring.data.rest.webmvc.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
web.xml
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml</param-value>
</context-param>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>org.springframework.data.rest.webmvc.RepositoryRestDispatcherServlet</servlet-class>
<init-param>
<param-name>throwExceptionIfNoHandlerFound</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>
According to this Answer:
Add this lines to Spring-config.xml
<context:annotation-config/>
<bean class="path.to.config.RestValidationConfiguration" />
#Configuration
public class RestValidationConfiguration extends RepositoryRestConfigurerAdapter {
#Bean
#Primary
/**
* Create a validator to use in bean validation - primary to be able to
* Autowire without qualifier
*/
Validator validator() {
return new LocalValidatorFactoryBean();
}
#Override
public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener validatingListener) {
Validator validator = validator();
// bean validation always before save and create
validatingListener.addValidator("beforeCreate", validator);
validatingListener.addValidator("beforeSave", validator);
}
}
But server keep returning Stack trace no JSON error format.
Any help will be appreciated, Thanks.
Thanks #Alan Hay, for suggest this Answer which working with me.

I have an application to run with spring boot. I need to use hibernate with it. I get this exception

I have an application to run with spring boot. I need to use hibernate with it. I get this exception. I'm not sure about the configuration files I should have. Since I have searched so much and new to spring: I have pom.xml, and I don't know whether I should have web.xml or not. I need to get it work as soon as possible. this is my exception thrown:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'userController' defined in file
[C:\Users\Mehrnaz\JEEKeplerWorkspace\rest-stack\target\classes\com\jl\crm\contoller\UserController.class]:
Unsatisfied dependency expressed through constructor argument with index 0 of type
[com.jl.crm.services.CrmService]: : Error creating bean with name 'jpaCrmService' defined in file
[C:\Users\Mehrnaz\JEEKeplerWorkspace\rest-stack\target\classes\com\jl\crm\services\JpaCrmService.class]:
Unsatisfied dependency expressed through constructor argument with index 0 of type
[com.jl.crm.repository.CustomerRepository]: : No qualifying bean of type
[com.jl.crm.repository.CustomerRepository] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {};
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [com.jl.crm.repository.CustomerRepository]
found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {};
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'jpaCrmService' defined in file
[C:\Users\Mehrnaz\JEEKeplerWorkspace\rest-stack\target\classes\com\jl\crm\services\JpaCrmService.class]:
Unsatisfied dependency expressed through constructor argument with index 0 of type
[com.jl.crm.repository.CustomerRepository]: : No qualifying bean of type
[com.jl.crm.repository.CustomerRepository] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency.
=======
my pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>rest-stack</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.springframework.hateoas</groupId>
<artifactId>spring-hateoas</artifactId>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- other project -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring3</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.1.Final</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
my web.xml:
<?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">
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.jl.crm.services.ServiceConfiguration</param-value>
</context-param>
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<servlet-name>appServlet</servlet-name>
</filter-mapping>
<servlet>
<servlet-name>appServlet</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>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
I have log4j.properties:
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
# Root logger option
log4j.rootLogger=DEBUG,stdout
and Application.properties:
#
## Database configuration
#
spring.datasource.url= jdbc:mysql://localhost:3307/spring
spring.datasource.username= spring
spring.datasource.password= spring
spring.datasource.driverClassName= com.mysql.jdbc.Driver
spring.view.prefix=/WEB-INF/jsp/
spring.view.suffix=.jsp
this is service.configuration class, that I think may have problem:
#ComponentScan
#Configuration
#EnableJpaRepositories
public class ServiceConfiguration {
public static final String CRM_NAME = "crm";
/**
* The root directory to which all uploads for the application are uploaded.
*/
public static final File CRM_STORAGE_DIRECTORY = new File(
System.getProperty("user.home"), CRM_NAME);
/**
* Things are first uploaded by the application server to this directory. it's a sort
* of staging directory
*/
public static final File CRM_STORAGE_UPLOADS_DIRECTORY = new File(CRM_STORAGE_DIRECTORY, "uploads");
/**
* When a profile photo is uploaded, the resultant, completely uploaded image is
* stored in this directory
*/
public static final File CRM_STORAGE_PROFILES_DIRECTORY = new File(CRM_STORAGE_DIRECTORY, "profiles");
#PostConstruct
protected void setupStorage() throws Throwable {
File[] files = {CRM_STORAGE_DIRECTORY, CRM_STORAGE_UPLOADS_DIRECTORY, CRM_STORAGE_PROFILES_DIRECTORY};
for (File f : files) {
if (!f.exists() && !f.mkdirs()) {
String msg = String.format("you must create the profile photos directory ('%s') " +
"and make it accessible to this process. Unable to do so from this process.", f.getAbsolutePath());
throw new RuntimeException(msg);
}
}
}
#Bean
LocalContainerEntityManagerFactoryBean entityManagerFactory( JpaVendorAdapter adapter, DataSource dataSource) {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setPackagesToScan(User.class.getPackage().getName());
emf.setDataSource(dataSource);
emf.setJpaVendorAdapter(adapter);
return emf;
}
#Bean
PlatformTransactionManager transactionManager( EntityManagerFactory emf) {
return new JpaTransactionManager(emf);
}
#Configuration
#Profile({"default", "test"})
static class DefaultDataSourceConfiguration {
private Log log = LogFactory.getLog(getClass());
#PostConstruct
protected void setupTestProfileImages() throws Exception {
long userId = 5;
File profilePhotoForUser5 = new File(ServiceConfiguration.CRM_STORAGE_PROFILES_DIRECTORY, Long.toString(userId));
if (!profilePhotoForUser5.exists()) {
// copy the profile photo back
String pathForProfilePhoto = "/sample-photos/spring-dog-2.png";
ClassPathResource classPathResource = new ClassPathResource(pathForProfilePhoto);
Assert.isTrue(classPathResource.exists(), "the resource " + pathForProfilePhoto + " does not exist");
OutputStream outputStream = new FileOutputStream(profilePhotoForUser5);
InputStream inputStream = classPathResource.getInputStream();
try {
IOUtils.copy(inputStream, outputStream);
} finally {
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
}
log.debug("setup photo " + profilePhotoForUser5.getAbsolutePath() + " for the sample user #" + Long.toString(userId) + "'s profile photo.");
}
if (!profilePhotoForUser5.exists()) {
throw new RuntimeException("couldn't setup profile photos at " + profilePhotoForUser5.getAbsolutePath() + ".");
}
}
}
}
#ComponentScan
#Configuration(basePackages = {"<Specify your base package here>"})
#EnableJpaRepositories
public class ServiceConfiguration {
---
}
you missed base package name for the componentscan annotation.

Access to the specified resource has been forbidden in simple Spring webservice Demo

I have created simple spring security demo with REST webservice.
I have spent lot of hours on It.Need strong pointers regarding simple working spring security for rest webservice with latest versions.
My Controller is
#Controller
public class RestContoller {
#RequestMapping(value = "/countryJSONProduce", method = RequestMethod.GET)
public ResponseEntity<CountryDetail> getCountryJSON() {
CountryDetail countryDetail = new CountryDetail("Values");
ResponseEntity<CountryDetail> rentity = new ResponseEntity<CountryDetail>(countryDetail, HttpStatus.OK);
return rentity;
}
#RequestMapping(value = "/countryJSONConsume", consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
public String consumeJSON(#RequestBody CountryDetail countryDetail) {
System.out.println("Country Detail Example");
return "home";
}
}
web.xml is
<servlet>
<servlet-name>springrest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>springrest</servlet-name>
<url-pattern>/hello/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</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>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-security.xml
/WEB-INF/springrest-servlet.xml
</param-value>
</context-param>
my pom.xml is
<properties>
<spring.version>4.1.0.RELEASE</spring.version>
<springsecurity.version>4.0.2.RELEASE</springsecurity.version>
</properties>
<dependencies>
<!-- for Jsp use -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!-- Spring mvc and Core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring mvc and Core -->
<!-- JSON Response Spring Framework 4.1, the minimum jackson version should
be 2.1 -->
<!-- Compatiable Spring Framework 4.1 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
<!-- Spring Authentication Start -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${springsecurity.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${springsecurity.version}</version>
</dependency>
<!-- Spring Authentication End -->
</dependencies>
When I Run the code sometimes it shows popup in my Eclipse Mars INTENAL
browser for user and password.when i put my credentials it will goes to
localhost:8080/SpringMavenRest2/ welcome page ok.when I hit the
url localhost:8080/SpringMavenRest2/hello/countryJSONProduce
which is calling my first service.. it is showing the Error :Access to
the specified resource has been forbidden.403
Even I put user name and
password as basic auth.Now I am testing this second url FROM CHROME
POSTMAN CLIENT.
I am using this configuration Java 1.8 ,Tomcat 8.0
spring.version4.1.0.RELEASE ,springsecurity.version 4.0.2.RELEASE.
and maven 3.3
Its
working well without authentication.Could you give any best referenced demo
for spring security with basic authentication. I have refered this also
http://www.mkyong.com/spring-security/spring-security-hello-world-example/
Try this :
<security:intercept-url pattern="/hello/**" access="hasRole('ROLE_USER'') "/>
and / or
<security:intercept-url pattern="/**" access="hasAnyRole('IS_AUTHENTICATED_ANONYMOUSLY','ROLE_USER')"/>

Resources