how can i make the transaction active in restful project - java

Using Spring, JPA, Restful Web Service and JSon. And Error is here.
Exception Description: No transaction is currently active
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionWrapper.throwCheckTransactionFailedException(EntityTransactionWrapper.java:87) [eclipselink-2.5.1.jar:2.5.1.v20130918-f2b9fc5]
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionWrapper.checkForTransaction(EntityTransactionWrapper.java:50) [eclipselink-2.5.1.jar:2.5.1.v20130918-f2b9fc5]
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.checkForTransaction(EntityManagerImpl.java:2041) [eclipselink-2.5.1.jar:2.5.1.v20130918-f2b9fc5]
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.flush(EntityManagerImpl.java:863) [eclipselink-2.5.1.jar:2.5.1.v20130918-f2b9fc5]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.6.0_25]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.6.0_25]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.6.0_25]
at java.lang.reflect.Method.invoke(Unknown Source) [rt.jar:1.6.0_25]
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:365) [spring-orm.jar:3.1.1.RELEASE]
at $Proxy24.flush(Unknown Source) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.6.0_25]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.6.0_25]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.6.0_25]
at java.lang.reflect.Method.invoke(Unknown Source) [rt.jar:1.6.0_25]
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240) [spring-orm.jar:3.1.1.RELEASE]
at $Proxy24.flush(Unknown Source) at com.hs.rest.springController.user.persistance.UserDAO.insertUser(UserDAO.java:62) [classes:]
at com.hs.rest.springController.user.service.UserService.addNewUser(UserService.java:65) [classes:]
at com.hs.rest.springController.StateController.getDefaultMovie(StateController.java:28) [classes:]
My Restservice Controller class
#Controller
public class StateController {
private static final Logger logger = Logger.getLogger(StateController.class);
#Resource(name = "UserService")
private IUserService userService;
#RequestMapping(value = "/movie", method = RequestMethod.GET)
public #ResponseBody
User getDefaultMovie() {
logger.debug("getDefaultMovie() Method is started !");
System.out.println("getDefaultMovie() Method is started !");
User user = new User();
user.setName("TEST");
userService.addNewUser(user);
logger.debug("getDefaultMovie() Method is finished ! " + user.getName());
System.out.println("getDefaultMovie() Method is finished ! " + user.getName());
return user;
}
}
Services class
#Service("UserService")
public class UserService implements IUserService {
private Logger logger = Logger.getLogger(this.getClass());
#Resource(name = "UserDAO")
private IUserDAO userDAO;
#Transactional(propagation = Propagation.REQUIRED)
public void addNewUser(User user) {
try {
logger.debug("insertUser() method has been started.");
user = userDAO.insertUser(user);
logger.debug("insertUser() method has been finished.");
} catch (DAOException e) {
logger.error("insertUser() method has been failed.");
throw new SystemException(e.getErrorCode(), "Faield to add new User.", e);
}
}
}
Configuration setup is here.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns"
id="WebApp_ID" version="3.0">
<display-name>restful</display-name>
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.hs.rest</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-beans.xml</param-value>
</context-param>
My question is how can i make the transaction active.
pls, help me. And sorry for my eng and question experience. :)

Make sure you have #Transactional on your services.

Related

No bean named 'springSecurityFilterChain' available

I am getting error
No bean named 'springSecurityFilterChain' available
when I don't include spring security configuration my code works fine. This project is created using spring annotation based configuration. When I created project using Maven pom.xml, web.xml, MvcConfiguration automatically gets created. Now I want to implement Spring-security with the same project and configuration. My configuration files are shown below.
MvcConfiguration.java
#Configuration
#ComponentScan(basePackages="com.mywebsite.emusicstore")
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter
{
#Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver resolver=new CommonsMultipartResolver();
Long maxUploadSize = 2048000L;
resolver.setMaxUploadSize(maxUploadSize);
return resolver;
} }
SpringSecurity.java
#Configuration
#EnableWebSecurity
public class SpringSecurity extends WebSecurityConfigurerAdapter{
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/admin**").access("ROLE_USER")
.and().formLogin().loginPage("/login").defaultSuccessUrl("/admin/").failureUrl("/login?error").usernameParameter("username").passwordParameter("password")
.and().logout().logoutSuccessUrl("/login?logout");
//http.csrf().disable();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
HibernateConfig hc = new HibernateConfig();
String authoritiesByUsernameQuery = "SELECT username,authorities FROM authorities WHERE username = ?";
String usersByUsernameQuery = "SELECT username,password,enabled FROM users WHERE username = ?";
auth.jdbcAuthentication().dataSource(hc.dataSource()).authoritiesByUsernameQuery(authoritiesByUsernameQuery).usersByUsernameQuery(usersByUsernameQuery);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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>emusicstore</display-name>
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>SpringDispatcher</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.mywebsite.emusicstore</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<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>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
Error
SEVERE: Exception starting filter springSecurityFilterChain
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean
named 'springSecurityFilterChain' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1207)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1086)
at org.springframework.web.filter.DelegatingFilterProxy.initDelegate(DelegatingFilterProxy.java:327)
at org.springframework.web.filter.DelegatingFilterProxy.initFilterBean(DelegatingFilterProxy.java:235)
at org.springframework.web.filter.GenericFilterBean.init(GenericFilterBean.java:236)
at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:279)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:260)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:105)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4598)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5223)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:155)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1404)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1394)
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)
Please add this class as well.
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer{
}

Swagger.json is not generated in Jersey + Tomcat8

pom.xml
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-jersey2-jaxrs</artifactId>
<version>1.5.7</version>
<exclusions>
<exclusion>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
</exclusion>
</exclusions>
</dependency>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>io.swagger.jaxrs.listing,
rs
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/webapi/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Jersey2Config</servlet-name>
<servlet-class>io.swagger.jersey.config.JerseyJaxrsConfig</servlet-class>
<init-param>
<param-name>api.version</param-name>
<param-value>1.0</param-value>
</init-param>
<init-param>
<param-name>swagger.api.title</param-name>
<param-value>Swagger APIzz</param-value>
</init-param>
<init-param>
<param-name>swagger.api.basepath</param-name>
<param-value>http://localhost:8080/SwaggerExample/webapi</param-value>
</init-param>
<init-param>
<param-name>swagger.pretty.print</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>swagger.scan</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
</web-app>
SwaggerExample is context root
PeopleRestService.java is present inside rs package
#Path( "/people" )
#Api( value = "/", description = "Manage people" )
public class PeopleRestService {
private static PeopleService peopleService;
static{
peopleService = new PeopleService();
}
#Produces( { MediaType.APPLICATION_JSON } )
#GET
#ApiOperation( value = "List all people", notes = "List all people using paging", response = Person.class, responseContainer = "List")
public Collection< Person > getPeople( #ApiParam( value = "Page to fetch", required = true ) #QueryParam( "page") #DefaultValue( "1" ) final int page ) {
System.out.println("inside service........");
return peopleService.getPeople( page, 100 );
}
}
Above code is able get the data via webservice but on accessing swagger.json, it is giving 404
http://localhost:8080/SwaggerExample/webapi/people : is working fine
http://localhost:8080/SwaggerExample/webapi/swagger.json : is giving 404
In web.xml replace
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>io.swagger.jaxrs.listing,
rs
</param-value>
</init-param>
with
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>
services.ConfigApplication
</param-value>
</init-param>
and register class explicitly
class ConfigApplication extends ResourceConfig{
public ConfigApplication(){
register(ApiListingResource.class);
register(SwaggerSerializers.class);
register(PeopleRestService.class);
}
}
If you can see your API on the swagger UI, it mean swagger UI knows where your swagger.json is, in my case I went to the index.html and searched for swagger.json.
I found this code
var url = window.location.search.match(/url=([^&]+)/);
if (url && url.length > 1) {
url = decodeURIComponent(url[1]);
} else {
url = "/my-app-name/app/swagger.json"; << this
}
Edit 1:
In newer versions you will find something like
const ui = SwaggerUIBundle({
url: "http://petstore.swagger.io/v2/swagger.json", << this
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
I guess you will also have to replace your init-param accordingly so you could access it remotely.
<param-value>http://localhost:8080/SwaggerExample/webapi</param-value>
to a relative path
<param-value>/SwaggerExample/webapi</param-value>

JavaConfig No bean named 'springSecurityFilterChain' is defined

I followed tutorial on http://shazsterblog.blogspot.com.es/2014/07/spring-security-custom-filterchainproxy.html to create a security filter using Java configuration instead of XML.
The bean is not being created and the application fails to load:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:575)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1111)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:276)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1123)
at org.springframework.web.filter.DelegatingFilterProxy.initDelegate(DelegatingFilterProxy.java:323)
at org.springframework.web.filter.DelegatingFilterProxy.initFilterBean(DelegatingFilterProxy.java:235)
at org.springframework.web.filter.GenericFilterBean.init(GenericFilterBean.java:194)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:234)
at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:332)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:90)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:3783)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4409)
at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeployInternal(TomcatDeployment.java:313)
at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeploy(TomcatDeployment.java:145)
at org.jboss.web.deployers.AbstractWarDeployment.start(AbstractWarDeployment.java:461)
at org.jboss.web.deployers.WebModule.startModule(WebModule.java:122)
at org.jboss.web.deployers.WebModule.start(WebModule.java:97)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:157)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:96)
This is the 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.config.SecurityConfig</param-value>
</context-param>
<servlet>
<servlet-name>Dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>dispatchOptionsRequest</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Dispatcher</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/application-context.xml</param-value>
</context-param>
<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>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>test</realm-name>
</login-config>
<security-role>
<role-name>ADMIN</role-name>
</security-role>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<security-constraint>
<web-resource-collection>
<web-resource-name>COMUN</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>ADMIN</role-name>
</auth-constraint>
</security-constraint>
</web-app>
This is the SecurityConfig class:
#Configuration
#EnableWebMvc
public class SecurityConfig extends WebMvcConfigurerAdapter implements ResourceLoaderAware{
private ResourceLoader resourceLoader;
#Bean
public FilterChainProxy springSecurityFilterChain() throws Exception {
AuthenticationManager am = authenticationManager();
SecurityContextPersistenceFilter sif = getSecurityContextPersistenceFilter();
J2eePreAuthenticatedProcessingFilter j2eePreAuthFilter = getJ2eePreAuthenticatedProcessingFilter(am);
LogoutFilter logoutFilter = getLogoutFilter();
ExceptionTranslationFilter etf = getExceptionTranslationFilter();
FilterSecurityInterceptor fsi = getFilterSecurityInterceptor(am);
FilterChainProxy fcp = new FilterChainProxy(new DefaultSecurityFilterChain(
new AntPathRequestMatcher("/**"),
sif, j2eePreAuthFilter, logoutFilter, etf, fsi
));
return fcp;
}
private FilterSecurityInterceptor getFilterSecurityInterceptor(AuthenticationManager am) {
AccessDecisionVoter<Object> roleVoter = new RoleVoter();
List<AccessDecisionVoter> decisionVoters = new LinkedList<AccessDecisionVoter>();
decisionVoters.add(roleVoter);
AffirmativeBased httpRequestAccessDecisionManager = new AffirmativeBased(decisionVoters);
httpRequestAccessDecisionManager.setAllowIfAllAbstainDecisions(false);
FilterSecurityInterceptor filterSecurityInterceptor = new FilterSecurityInterceptor();
filterSecurityInterceptor.setAuthenticationManager(am);
filterSecurityInterceptor.setAccessDecisionManager(httpRequestAccessDecisionManager);
LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();
List<ConfigAttribute> configs = new ArrayList<ConfigAttribute>();
configs.add(new org.springframework.security.access.SecurityConfig("hasRole(ADMIN)"));
requestMap.put(new AntPathRequestMatcher("/**"), configs);
FilterInvocationSecurityMetadataSource filterInvocationSecurityMetadataSource = new ExpressionBasedFilterInvocationSecurityMetadataSource(
requestMap, new DefaultWebSecurityExpressionHandler());
filterSecurityInterceptor
.setSecurityMetadataSource(filterInvocationSecurityMetadataSource);
return filterSecurityInterceptor;
}
private LogoutFilter getLogoutFilter() {
org.springframework.security.web.authentication.logout.LogoutFilter logoutFilter = new LogoutFilter("/", new SecurityContextLogoutHandler());
return logoutFilter;
}
private ExceptionTranslationFilter getExceptionTranslationFilter() {
ExceptionTranslationFilter exceptionTranslationFilter = new ExceptionTranslationFilter(
new Http403ForbiddenEntryPoint());
return exceptionTranslationFilter;
}
private SecurityContextPersistenceFilter getSecurityContextPersistenceFilter() {
return new org.springframework.security.web.context.SecurityContextPersistenceFilter();
}
private J2eePreAuthenticatedProcessingFilter getJ2eePreAuthenticatedProcessingFilter(AuthenticationManager am) throws Exception {
WebXmlMappableAttributesRetriever mappableRolesRetriever = new WebXmlMappableAttributesRetriever();
mappableRolesRetriever.setResourceLoader(this.resourceLoader);
mappableRolesRetriever.afterPropertiesSet();
SimpleAttributes2GrantedAuthoritiesMapper userRoles2GrantedAuthoritiesMapper = new SimpleAttributes2GrantedAuthoritiesMapper();
userRoles2GrantedAuthoritiesMapper.setConvertAttributeToUpperCase(true);
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource j2eeBasedPreAuthenticatedWebAuthenticationDetailsSource
= new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
j2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.setMappableRolesRetriever(mappableRolesRetriever);
j2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.setUserRoles2GrantedAuthoritiesMapper(userRoles2GrantedAuthoritiesMapper);
J2eePreAuthenticatedProcessingFilter j2eePreAuthenticatedProcessingFilter = new J2eePreAuthenticatedProcessingFilter();
j2eePreAuthenticatedProcessingFilter.setAuthenticationManager(am);
j2eePreAuthenticatedProcessingFilter.setAuthenticationDetailsSource(j2eeBasedPreAuthenticatedWebAuthenticationDetailsSource);
return j2eePreAuthenticatedProcessingFilter;
}
#Bean
public AuthenticationManager authenticationManager() throws Exception {
PreAuthenticatedGrantedAuthoritiesUserDetailsService preAuthenticatedGrantedAuthoritiesUserDetailsService = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();;
PreAuthenticatedAuthenticationProvider preAuthenticatedAuthenticationProvider = new PreAuthenticatedAuthenticationProvider();
preAuthenticatedAuthenticationProvider.setPreAuthenticatedUserDetailsService(preAuthenticatedGrantedAuthoritiesUserDetailsService);
List<AuthenticationProvider> lProviders = new LinkedList<AuthenticationProvider>();
lProviders.add(preAuthenticatedAuthenticationProvider);
AuthenticationManager am = new ProviderManager(lProviders);
return am;
}
#Override
public void setResourceLoader(ResourceLoader arg0) {
this.resourceLoader = arg0;
}
}
Any help please?
Bit different from the example and simplified for this case, the filter class is created if its package is set on component-scan
The following part of the web.xml is not needed:
<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.config.SecurityConfig</param-value>
</context-param>
The web.xml defines the application context which will scan the class and create an instance of the filter. Later the instance is used in the web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/application-context-${environment}.xml</param-value>
</context-param>
If the ${environment} variable is "DEV", it uses an application context that has the security defined in XML, if the ${environment} variable is "PRO", it uses the following application context which has the logic defined in Java:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd>
<context:component-scan base-package="com.config" />
</beans>
The filter only needs created in PRO so it needs the component-scan only for its package from within the application-context used in PRO.

Http 404 Spring java config

Hello i have problem with java config in spring. I was trying to complete it by learning from mutliple tutorials but still i have something wrong. Any clue ?
error
AppConfig.java
package org.spring.mvc.libraryDemo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
/**
* Created by wiktor on 28.12.2015.
*/
#Configuration //adnotacja oznaczajaca plik konfiguracyjny
#EnableWebMvc
#ComponentScan(basePackages = "org.spring.mvc.libraryDemo") //enable skan komponentow
#Import({AppConfig.class}) //na co musi jeszcze uwazac Spring
public class AppConfig {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
SpringConfigInit
package org.spring.mvc.libraryDemo.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringConfigInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Controller
package org.spring.mvc.libraryDemo.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Created by wiktor on 28.12.2015.
*/
#Controller
public class HomeController {
#RequestMapping(value="/",method= RequestMethod.GET)
public String sayHello(ModelMap modelMap)
{
modelMap.addAttribute("greeting","witaj");
return "index";
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
With this type of servlet mapping, I think you will find your app at http://localhost:8080/{warfile name}/, not at http://localhost:8080/
You are mixing up two approaches here (as seen is your web.xml):
ContextLoaderListener with /WEB-INF/applicationContext.xml : this means that your spring application will be configured by the xml stuff in applicationContext.xml.
But obviously you want to use the Java Config, that is the beans defined under #Configuration annotated classes. To enable this, one way is to change your web xml for something like this:
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<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>SpringRootConfig</param-value>
</init-param>
</servlet>
AnnotationConfigWebApplicationContext is the key here. That will scan your classpath and take the #Configuration stuff into account.
<?xml version="1.0" encoding="UTF-8"?>
<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">
<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>org.spring.mvc.libraryDemo.config.AppConfig</param-value>
</context-param>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>

Wildfly resteasy javax.ws.rs.NotFoundException

i know that this post is duplicate and there are a lot of solutions yet, but i wasn't able to use them to resolve the problem.
I am trying to use spring + wildflyAS + resteasy. I have problems with resteasy integration, here is error which i am getting while trying to access controller:
javax.ws.rs.NotFoundException: Could not find resource for full path: http://localhost:8080/BQP/rest/student/test/1/pass/1
Controller:
#Controller
#RequestMapping(value = "student")
public class StudentController {
#Autowired
StudentService studentService;
public StudentController() {
}
#RequestMapping(value = "/test/{id}/pass/{testId}", method = RequestMethod.GET, produces = "application/json")
public
#ResponseBody
Response getCurrentTest(#PathVariable("id") String id,#PathVariable("testId") String testId){
TestDTO testDTO = studentService.getCurrentTest(id,testId);
return Response.status(200).entity(testDTO).build();
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<display-name>BQP</display-name>
<!--Spring-->
<servlet>
<servlet-name>Spring MVC Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc-context.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Spring MVC Servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<!--/Spring-->
<!--RestEASY-->
<servlet>
<servlet-name>Resteasy</servlet-name>
<servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Resteasy</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.bionic.rest.ApplicationConfiguration</param-value>
</context-param>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/rest</param-value>
</context-param>
<listener>
<listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
<!--/RestEASY-->
ApplicationConfiguration:
package com.bionic.rest;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
public class ApplicationConfiguration extends Application {
private Set<Object> singletons = new HashSet<Object>();
private Set<Class<?>> empty = new HashSet<Class<?>>();
public ApplicationConfiguration() {
singletons.add(new StudentController());
}
#Override
public Set<Class<?>> getClasses() {
return empty;
}
#Override
public Set<Object> getSingletons() {
return singletons;
}
}
Moreover, i can access this controller without /rest in url.

Categories

Resources