Why is HttpEntity causing an HTTP Status 415 error in Spring? - spring

This has been bugging me for days and I'm turning to the community for help. I've been trying to access the request body and headers using the HttpEntity as suggested by the Spring 3 docs. Every time I introduce the HttpEntity as a parameter, I always get the following error:
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().
So, this works:
#RequestMapping("/handle")
public HttpEntity<String> handle() { //
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("MyResponseHeader", "MyValue");
return new HttpEntity<String>("Hello World", responseHeaders);
}
But, this does not:
#RequestMapping("/handle")
public HttpEntity<String> handle(HttpEntity<String> requestEntity) { //
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("MyResponseHeader", "MyValue");
return new HttpEntity<String>("Hello World", responseHeaders);
}
I'm not using <mvc:annotation-driven>. I'm using good ol' <context:annotation-driven> but I've tried adding to my config as suggested here without any luck. I've also dabbled with creating a bean post processor without any luck. I think I'm running out of ideas/Google searches.
Here's my current Spring config:
<?xml version="1.0" encoding="windows-1252"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.gn" />
<tx:annotation-driven />
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:gn.properties" />
<!-- values come from resources/properties/jdbc.properties -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!--bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<util:list>
<bean id="byteArrayMessageConverter" class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
</bean>
</util:list>
</property>
</bean-->
<!--bean id="encodingPostProcessor" class="com.glowpinion.core.postprocessor.EncodingPostProcessor" /-->
Thanks!

You need to send a POST request so that there is a body to parse into an HttpEntity.
I would also recommend using the method attribute of the RequestMapping annotation so that you can specify which HTTP methods your mapping controller method handles.
#RequestMapping(value = "/handle" method = RequestMethod.POST)
public HttpEntity<String> handle(HttpEntity<String> requestEntity) {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("MyResponseHeader", "MyValue");
return new HttpEntity<String>("Hello World", responseHeaders);
}
I believe you could also do something like this to deal with the request body as a String:
#RequestMapping(value = "/handle" method = RequestMethod.POST)
public String handle(#RequestBody String body) {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("MyResponseHeader", "MyValue");
return new HttpEntity<String>("Hello World", responseHeaders);
}

Have you tried adding the #ResponseBody annotation to your methods?

Related

Hazelcast client spring configuration

I have createed a Hazelcast manager which uses spring, hibernate, jpa. I can start my hazelcast instance.
The problem I have is I dont know how to configure a hazelcast client using spring config. I want to use in some other server component a hazelcast-client
I really have no idea how to start
any help would be appreciated
Below is my spring config for hazelcast server
Johan
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:hz="http://www.hazelcast.com/schema/spring"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.hazelcast.com/schema/spring
http://www.hazelcast.com/schema/spring/hazelcast-spring.xsd">
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>file:${ecs.config.path}/ecs.properties</value>
<value>classpath*:config/ecs.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="ignoreResourceNotFound" value="true" />
</bean>
<context:component-scan base-package="nl.ict.psa.ecs.hazelcast.dao,nl.ict.psa.ecs.hazelcast.mapstores,nl.ict.psa.ecs.hazelcast.service" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${datasource.driverClassName}" />
<property name="url" value="${datasource.url}" />
<property name="username" value="${datasource.username}"/>
<property name="password" value="${datasource.password}"/>
</bean>
<bean id="hazelcast" class="com.hazelcast.core.Hazelcast"/>
<bean id="entityManagerFactoryBean"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="PU" />
<property name="packagesToScan">
<list>
<value>nl.ict.psa.hazelcast.model.ecs</value>
<value>nl.ict.psa.hazelcast.model.ecs.ocr</value>
</list>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.archive.autodetection">class</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryBean" />
</bean>
<bean id="transpInfo" class="nl.ict.psa.ecs.hazelcast.mapstores.TranspInfoMapStore"/>
<hz:hazelcast id="instance">
<hz:config>
<hz:network port="5701" port-auto-increment="true">
<hz:join>
<hz:multicast enabled="false"/>
</hz:join>
</hz:network>
<hz:map name="transp" read-backup-data="true">
<hz:map-store enabled="true" write-delay-seconds="60"
initial-mode="LAZY"
implementation="transpInfo"/>
</hz:map>
</hz:config>
</hz:hazelcast>
</beans>
Configured Multiple Ip's Using Pragmatically.
#Bean
public ClientConfig clientConfig() {
ClientConfig clientConfig = new ClientConfig();
ClientNetworkConfig networkConfig = clientConfig.getNetworkConfig();
networkConfig.addAddress("172.17.0.4:5701", "172.17.0.6:5701")
.setSmartRouting(true)
.addOutboundPortDefinition("34700-34710")
.setRedoOperation(true)
.setConnectionTimeout(5000)
.setConnectionAttemptLimit(5);
return clientConfig;
}
#Bean
public HazelcastInstance hazelcastInstance(ClientConfig clientConfig) {
return HazelcastClient.newHazelcastClient(clientConfig);
}
I would suggest to must read. http://docs.hazelcast.org/docs/latest/manual/html-single/index.html#configuring-client-connection-strategy
Something like this (from https://github.com/neilstevenson/spring-boot-autoconfigure-test/tree/master/hazelcast-imdg-client)
#Configuration
#ConditionalOnMissingBean(ClientConfig.class)
static class HazelcastClientConfigConfiguration {
#Bean
public ClientConfig clientConfig() throws Exception {
return new XmlClientConfigBuilder().build();
}
}
#Configuration
#ConditionalOnMissingBean(HazelcastInstance.class)
static class HazelcastClientConfiguration {
#Bean
public HazelcastInstance hazelcastInstance(ClientConfig clientConfig) {
return HazelcastClient.newHazelcastClient(clientConfig);
}
}
Try to avoid XML, Spring is moving away from it.

Spring #ExceptionHandler not working

I am trying to handle an exception using #ExceptionHandler but it is not working and I don't know why. The thing is right now I am getting this response from my web service: {"message":"The date provided 2013-02-30 is invalid","code":500,"ids":null}. And I want that to be a 400 exception instead of 500.
Here is my code:
#Controller
public class WsController {
#RequestMapping(value={"/getDeletedUsers"}, method=RequestMethod.GET)
public List<Integer> getDeletedUsers(#RequestParam(value = "date", required = true) String dateStr) throws WebServiceException {
if (dateStr == null) {
throw new WebServiceException("The date provided is null");
} else if (StringUtils.isEmpty(dateStr)) {
throw new WebServiceException("The date provided is empty");
} else {
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.applyPattern("yyyy-MM-dd");
sdf.setLenient(false);
try {
sdf.parse(dateStr);
} catch (ParseException e) {
throw new WebServiceException("The date provided " + dateStr + " is invalid");
}
return service.getDeletedUsers(dateStr);
}
}
#ExceptionHandler(WebServiceException.class)
public void handleWebServiceException() {
System.out.println("PLEASE DO SOMETHING!");
}
}
public class WebServiceException extends Exception {
//Constructors and serialVersionUID
}
disparcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<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:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
<property name="searchContextAttributes" value="true"/>
<property name="contextOverride" value="true"/>
<property name="ignoreResourceNotFound" value="true"/>
<property name="locations">
<list>
<value>classpath:application.properties</value>
<value>file:c://rt//properties//webservices-application.properties</value>
</list>
</property>
</bean>
<import resource="classpath:keepalive.xml" />
<import resource="classpath:controller.xml" />
<bean id="exceptionResolver" class="com.company.project.webservices.spring.ExceptionResolver"/>
<bean id="error" class="com.company.project.webservices.spring.ErrorView"/>
<bean id="readOnlyModeError" class="com.company.project.webservices.spring.ReadOnlyModeErrorView"/>
<bean id="methodUnavailableError" class="com.company.project.webservices.spring.MethodUnavailableErrorView"/>
<bean id="badRequestError" class="com.company.project.webservices.spring.BadRequestErrorView"/>
<!-- View Resolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json"/>
</map>
</property>
<!-- Ticket-3245 Spring 60 -->
<property name="defaultContentType" value="application/json" />
<property name="useNotAcceptableStatusCode" value="true"/>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
<property name="order" value="2" />
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
</list>
</property>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
<!-- Dispatches requests mapped to POJO #Controllers implementations -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<util:list id="beanList">
<ref bean="jsonHttpMessageConverter"/>
</util:list>
</property>
</bean>
<bean id="jsonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="useDefaultSuffixPattern" value="false"/>
</bean>
<!-- Dispatches requests mapped to non-annotated controllers -->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
<context:annotation-config/>
<context:component-scan base-package="com.company.project" />
When I try to debug the handleWebServiceException method it doesn't even stop there.
Any tips will be appreciated.
As jny suggested, I took a look at the dispatcher-servlet.xml and realized that there was a exceptionResolver bean that I haven't seen that looks like this:
public class ExceptionResolver extends AbstractHandlerExceptionResolver {
private static Log logger = LogFactory.getLog(ExceptionResolver.class);
#Override
protected ModelAndView doResolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
ModelAndView mv = null;
if (ex instanceof ReadOnlyModeException) {
mv = new ModelAndView("readOnlyModeError");
} else if (ex instanceof MethodUnavailableException) {
mv = new ModelAndView("methodUnavailableError");
} else if (ex instanceof BadRequestException) {
mv = new ModelAndView("badRequestError");
} else {
logger.error("caught an exception: ", ex);
mv = new ModelAndView("error");
}
ResultBean resultBean = new ResultBean();
resultBean.setCode(500);
resultBean.setMessage(ex.getMessage());
mv.addObject("result", resultBean);
return mv;
}
}
And there I was able to make the suitable changes.
Thanks again to jny for the hint.

Spring xml in response via JAXB

I am using spring 3.1, and my application is already set up to send and receive data in json format. Now I need to provide one request API that should return the same data but in xml format.
Please help me with this stuff or tell what I am doing wrong. I tried JAXB, but instead of xml I receive "406 Not Acceptable".
My requests API:
/**
* Gets objects in json format
*/
#RequestMapping(value = "/objects/json", method = RequestMethod.GET)
#ResponseBody
public List<MyObjectTO> getAll() {
List<MyObjectTO> objectsList = new ArrayList<MyObjectTO>();
//forming objects
return objectsList;
}
/**
* Gets objects in xml format
*/
#RequestMapping(value = "/objects/xml", method = RequestMethod.GET,headers={"Accept=application/xml"})
#ResponseBody
public ResponseList getAll() {
ResponseList objectsList = new ResponseList ();
//the same formation
return objectsList;
}
Context
<?xml version="1.0" encoding="UTF-8"?>
<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:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.kenshoo.urlbuilder"/>
<mvc:annotation-driven/>
<mvc:view-controller path="/mainpage" view-name="mainpage"/>
<util:properties id="addProps" location="classpath:config/addProps.properties"/>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="alwaysUseFullPath" value="true"/>
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="alwaysUseFullPath" value="true"/>
</bean>
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="html" value="text/html"/>
<entry key="json" value="application/json"/>
<entry key="pdf" value="application/pdf"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="cache" value="true"/>
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
</list>
</property>
</bean>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
</beans>
My changes: Added message converters to AnnotationMethodHandlerAdapter and inserted JAXB marshaller. But after this got response "406 Not Acceptable":
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="alwaysUseFullPath" value="true"/>
<property name="messageConverters">
<list>
<ref bean="marshallingConverter" />
</list>
</property>
</bean>
<bean id="marshallingConverter" class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="jaxbMarshaller" />
<property name="unmarshaller" ref="jaxbMarshaller" />
<property name="supportedMediaTypes" value="application/xml"/>
</bean>
<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.ResponseList</value>
</list>
</property>
</bean>
I would appreciate any help, thanks.
UPDATE
ResponseList structure:
public class ResponseList {
private List<FirstLevel> firstLevelObjects;
public List<FirstLevel> getFirstLevelObjects() {
return firstLevelObjects;
}
public void setFirstLevelObjects(List<FirstLevel> firstLevelObjects) {
this.firstLevelObjects= firstLevelObjects;
}
}
FirstLevel structure:
public class FirstLevel {
List<SecondLevel> secondLevelObjects;
boolean isConditional;
String beforeStart;
ConditionType type;//enum object
//...getters and setters
}
I lost hope with Castor, so tried once more with JAXB. Changed post
with details for JAXB. The same issues - I got Not Acceptable when
trying to request xml. Can you help me?
All you should need to do for JAXB is to add an #XmlRootElement annotation to your ResponseList class.
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class ResponseList {
private List<FirstLevel> firstLevelObjects;
public List<FirstLevel> getFirstLevelObjects() {
return firstLevelObjects;
}
public void setFirstLevelObjects(List<FirstLevel> firstLevelObjects) {
this.firstLevelObjects= firstLevelObjects;
}
}

Can't use #Autowired in desktop application

i am trying to use spring in desktop application, but i am facing a problem with autowiring in action methods of my JPanel.
i am loading the applicationContext in my main method as follows:
public static void main(String[] args) {
new ClassPathXmlApplicationContext(
"classpath:/META-INF/spring/applicationContext.xml");
MainFrame frame = new MainFrame();
Signup signup = new Signup();
frame.add(signup);
frame.setResizable(false);
frame.setTitle("Please input your data");
frame.setBounds(100, 100, 450, 180);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
and i can see that it's loaded with no problems.
my panel code:
#Component
public class Signup extends JPanel {
#Autowired
private UserDao userDao;
public Signup() {
JButton btn_submit = new JButton("Submit");
btn_submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
registerUser();
}
});
}
private void registerUser() {
User newUser = new User();
newUser.setName(username);
newUser.setSalary(salary);
userDao.addUser(newUser);
}
}
the context:component-scan is configured properly, and i am using context:annotation-config too but i always gets NullPointerException in userDao.addUser(newUser);
which means that the Dependency Injection is not working as it should.
please advise how to fix this issue.
UPDATE: applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="${project.groupId}" />
<context:annotation-config />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:messages/application.properties</value>
</list>
</property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="${project.groupId}.domain" />
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.DerbyDialect
hibernate.show_sql=false
hibernate.format_sql=false
hibernate.hbm2ddl.auto=validate
</value>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="url" value="jdbc:derby:test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
</beans>
If you are going to configure Spring in a desktop environment, then you must be the one to work with the ApplicationContext.
For example, if you want to get a hold of your Signup class that you have posted here, you would do something like this in your main method:
public static void main(String[] args) {
ApplicationContext appContext = new ClassPathXmlApplicationContext(
"classpath:/META-INF/spring/applicationContext.xml");
Signup signup = appContext.getBean(Signup.class);
//use signup here...
}
Using new Signup() to get a new instance of the Signup class, which won't work the way you want, because you want it to be a Spring managed class! (Actually, you could get it to work that way, but that is beyond my answer here)

Spring Security LDAP - login problem (ProviderNotFoundException)

I have problem with LDAP Spring Security, I'm trying to authorise against the LDAP server. I have the spring configuration xml file (security-config.xml) like this:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">
<bean id="contextSource" class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
<constructor-arg value="ldap://111.111.111.111"/>
<property name="userDn" value="cn=auth-user,ou=System,dc=foo,dc=com"/>
<property name="password" value="fooPwd"/>
</bean>
<bean id="ldapAuthProvider" class="org.springframework.security.providers.ldap.LdapAuthenticationProvider">
<constructor-arg>
<bean class="org.springframework.security.providers.ldap.authenticator.BindAuthenticator">
<constructor-arg ref="contextSource"/>
<property name="userSearch">
<bean id="userSearch" class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
<constructor-arg index="0" value="ou=people"/>
<constructor-arg index="1" value="(uid={0})"/>
<constructor-arg index="2" ref="contextSource" />
</bean>
</property>
</bean>
</constructor-arg>
<constructor-arg>
<bean class="com.company.name.services.UserAuthoritiesPopulator" />
</constructor-arg>
</bean>
</beans>
In the login controller (LoginController.java) I'm authorising like this:
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String loginPPost(String username, String password, Model model, HttpServletRequest req, HttpServletResponse res) throws SQLException {
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
Authentication authentication = authenticationManager.authenticate(authRequest);
SecurityContextHolder.getContext().setAuthentication(authentication);
...
}
The method "authenticationManager.authenticate(authRequest)" throws this exception:
org.springframework.security.providers.ProviderNotFoundException: No AuthenticationProvider found for org.springframework.security.providers.UsernamePasswordAuthenticationToken
at org.springframework.security.providers.ProviderManager.doAuthentication(ProviderManager.java:214)
at org.springframework.security.AbstractAuthenticationManager.authenticate(AbstractAuthenticationManager.java:46)
Does anybody know how to solve this problem? Should I use different method for authorisation? Or is my configuration bad?
Thanks for any help,
Mateo
You must add the tag 'sec:custom-authentication-provider' in your authentication provider bean:
<bean id="ldapAuthProvider" class="org.springframework.security.providers.ldap.LdapAuthenticationProvider">
<sec:custom-authentication-provider/>
...
</bean>
You can find an example that use Crowd instead of LDAP on my blog:
http://aloiscochard.blogspot.com/2009/12/integrating-spring-security-with-ntlm_19.html

Resources