<dataFormats>
<json id="json" library="Jackson"
unmarshalTypeName="com.foo.MyPojo" disableFeatures="FAIL_ON_UNKNOWN_PROPERTIES"/>
</dataFormats>
I want to disbleFeature Fail on unknown property of jackson but I think it is available only in camel vs2.15.0 and greater.
How can i implement following using spring dsl:
dataFormat.getObjectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
I'm not sure, or may be did not understand you right. But try this thing:
<bean id="format" class="org.apache.camel.component.jackson.JacksonDataFormat"/>
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="format"/>
<property name="targetMethod" value="disableFeature"/>
<property name="arguments">
<list>
<value type="com.fasterxml.jackson.databind.DeserializationFeature">FAIL_ON_UNKNOWN_PROPERTIES</value>
</list>
</property>
</bean>
With JSON:
Use JsonIgnoreProperties with attribute "value". For instance:
#JsonIgnoreProperties(ignoreUnknown = true, value={"dataIgnored"})
When BeanDeserializerBuild is instanced, use those attributes.
Related
We are able to fetch access token using attached code snapshot but didn't find any way to set connection timeout as we do with spring restTemplate.Is there any way to set a connection timeout with OAuth2RestTemplate.
<bean id="bean" class="com.test.Provider">
<constructor-arg name="context" ref="context" />
<constructor-arg name="detail" ref="resourceDetails" />
</bean>
<bean id="context" class="org.springframework.security.oauth2.client.DefaultOAuth2ClientContext">
<constructor-arg name="accessTokenRequest" ref="request" />
</bean>
<bean id="request" class="org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest"/>
<bean id="resourceDetails" class="org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails"/>
A little late to the party, but in case you're wondering how to do this with springboot, this is a way:
#Bean
protected OAuth2RestTemplate oauth2RestTemplate(ClientHttpRequestFactory clientHttpRequestFactory) {
OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(oAuthDetails());
oAuth2RestTemplate.setRequestFactory(clientHttpRequestFactory);
return oAuth2RestTemplate;
}
#Bean
protected ClientHttpRequestFactory requestFactory() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(10000); //timeout in milliseconds
requestFactory.setReadTimeout(10000); //timeout in milliseconds
return requestFactory;
}
Where oAuthDetails() is a method that reads the oauth configuration properties, similar to this:
#Bean
#ConfigurationProperties("path.to.your.oauth.properties.on.yml")
protected ClientCredentialsResourceDetails oAuthDetails() {
return new ClientCredentialsResourceDetails();
}
If I'm right, the way you give the connection timeout to the Spring RestTemplate as a constructor argument is through giving a ClientHttpRequestFactory as an argument to the constructor
RestTemplate(ClientHttpRequestFactory requestFactory)
Using for example the HttpComponentsClientHttpRequestFactory, one can set the connection timeout to the RestClient in XML as follows
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<constructor-arg name="requestFactory">
<bean id="requestFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<property name="connectTimeout" value="2000" />
<property name="readTimeout" value="10000" />
</bean>
</constructor-arg>
</bean>
RestTemplate also offers a way to set the requestFactory property through a setter, which it inherits from InterceptingHttpAccessor, and in fact the constructor itself seems to use that setter to set the requestFactory given as constructor argument.
Thus, you can set the requestFactory for the OAuth2RestTemplate through the setter. In XML:
<bean id="oauth2RestTemplate" class="org.springframework.security.oauth2.client.OAuth2RestTemplate">
<constructor-arg name="resource" ref="resourceDetails" />
<constructor-arg name="context" ref="context" />
<property name="requestFactory">
<bean id="requestFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<property name="connectTimeout" value="2000" />
<property name="readTimeout" value="10000" />
</bean>
</property>
</bean>
Or, in your case, you can for example give your class com.test.Provider a constructor argument requestFactory and then use that to set the request factory in the OAuth2RestTemplate as follows:
XML:
<bean id="bean" class="com.test.Provider">
<constructor-arg name="context" ref="context" />
<constructor-arg name="resourceDetails" ref="resourceDetails" />
<constructor-arg name="requestFactory">
<bean id="requestFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<property name="connectTimeout" value="2000" />
<property name="readTimeout" value="10000" />
</bean>
</constructor-arg>
</bean>
And in your code set
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(this.resourceDetails, this.context);
restTemplate.setRequestFactory(this.requestFactory);
String tokenString = restTemplate.getAccessToken().getValue();
after setting the value of this.requestFactory in the constructor.
PS. I would prefer to create a single OAuth2RestTemplate for the entire class as a private field and reuse it in that class, unless you have a reason to create a new one for each request. You could create it in the constructor, as you are giving the context and details as constructor arguments, or then in a post-construct/init-method. Or even give it as a constructor-argument or as a property to your class in the XML, in case the context and resourceDetails are not used outside the restTemplate.
EDIT
After doing some more research, it seems that the problem might be harder than I thought. OAuth2RestTemplate uses an AccessTokenProvider to get the access tokens, by default it uses a chain of AccessTokenProviders through a instance of AccessTokenProviderChain in order to support the different types of grant types. It seems that each of these uses their own RestTemplate to send the requests to obtain the access token. Unfortunately, it seems that OAuth2RestTemplate doesn't offer a simple way to set the requestFactory of the default AccessTokenProviders' restTemplates.
So, if the solution that I proposed above is not working (which I suspect), I would use the following approach which I believe to work.
All the default AccessTokenProviders in Spring Security Oauth2 extend the class OAuth2AccessTokenSupport, which also is the class that creates the internal RestTemplate. Fortunately, this class offers a setter to set the requestFactory of the internal RestTemplate. So, one can create for example an instance of a ClientCredentialsAccessTokenProvider and give set the requestFactory through the setRequestFactory(...) method. In XML:
<bean id="clientCredentialsAccessTokenProvider class="org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsAccessTokenProvider">
<property name="requestFactory">
<bean id="requestFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<property name="connectTimeout" value="2000" />
<property name="readTimeout" value="10000" />
</bean>
</property>
</bean>
For some reason the OAuth2RestTemplate doesn't offer a way to access the default AccessTokenProviders, but one can set them through the setAccessTokenProvider(AccessTokenProvider accessTokenProvider) setter. To replicate the original default behaviour of the OAuth2RestTemplate, one would have to give an instance of a AccessTokenProviderChain, together with four default AccessTokenProviders and set their requestFactories. However, as you know that the accessed resource is of type ClientCredentialsResourceDetails, it suffices to set a single ClientCredentialsAccessTokenProvider in the setAccessTokenProvider(...) setter and set the requestFactory of the ClientCredentialsAccessTokenProvider.
So we would get the following code:
XML:
<bean id="bean" class="com.test.Provider">
<constructor-arg name="context" ref="context" />
<constructor-arg name="resourceDetails" ref="resourceDetails" />
<constructor-arg name="accessTokenProvider" ref="clientCredentialsAccessTokenProvider" />
</bean>
<bean id="clientCredentialsAccessTokenProvider" class="org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsAccessTokenProvider">
<property name="requestFactory">
<bean id="requestFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<property name="connectTimeout" value="2000" />
<property name="readTimeout" value="10000" />
</bean>
</property>
</bean>
And in your code, set the AccessTokenProvider:
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(this.resourceDetails, this.context);
restTemplate.setAccessTokenProvider(this.accessTokenProvider);
String tokenString = restTemplate.getAccessToken().getValue();
after setting the value of this.accessTokenProvider in the constructor. If you decide to create the OAuth2RestTemplate in the XML, you can write
<bean id="oauth2RestTemplate" class="org.springframework.security.oauth2.client.OAuth2RestTemplate">
<constructor-arg name="resource" ref="resourceDetails" />
<constructor-arg name="context" ref="context" />
<property name="accessTokenProvider" ref="clientCredentialsAccessTokenProvider" />
</bean>
where the bean "clientCredentialsAccessTokenProvider" is defined as above.
Hope that this works.
One issue with above solution is that ClientCredentialsAccessTokenProvider uses a bit enhanced requestFactory:
private ClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory() {
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
super.prepareConnection(connection, httpMethod);
connection.setInstanceFollowRedirects(false);
connection.setUseCaches(false);
...
}
...
};
So in order to preserve the original functionality you should set up the same implementation of the factory.
I want to write data to CSV file & have successfully written that but now I want to insert header & break line where ever needed.
Below is the code fro my itemWriter...
<property name="resource" value="file:csv/examResult.txt" />
<property name="lineAggregator">
<!-- An Aggregator which converts an object into delimited list of strings -->
<bean
class="org.springframework.batch.item.file.transform.DelimitedLineAggregator">
<property name="delimiter" value="|" />
<property name="fieldExtractor">
<!-- Extractor which returns the value of beans property through reflection -->
<bean
class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
<property name="names" value="studentName, percentage, dob" />
</bean>
</property>
</bean>
</property>
</bean>
I used CAS server 4.0 and cas-overlay-server-demo. the return value of my server is as following:
<cas:serviceResponse xmlns:cas="xxx">
<cas:authenticationSuccess>
<cas:user>try</cas:user>
</cas:authenticationSuccess>
</cas:serviceResponse>
I want to add <cas:attributes> to this return result. I have following code in deployerConfigContext.xml:
primaryAuthenticationHandler:
<bean id="primaryAuthenticationHandler" class="org.jasig.cas.authentication.AcceptUsersAuthenticationHandler">
<property name="users">
<map>
<entry key="test" value="1234"/>
</map>
</property>
</bean>
primaryPrincipalResolver:
<bean id="primaryPrincipalResolver"
class="org.jasig.cas.authentication.principal.PersonDirectoryPrincipalResolver" >
<property name="attributeRepository" ref="attributeRepository" />
</bean>
attributeRepository:
<bean id="attributeRepository" class="org.jasig.services.persondir.support.StubPersonAttributeDao"
p:backingMap-ref="attrRepoBackingMap" />
<util:map id="attrRepoBackingMap">
<entry key="uid" value="uid" />
<entry key="prénom" value="eduPersonAffiliation" />
<entry key="groupMembership" value="groupMembership" />
</util:map>
I think I have add the the code right. StubPersonAttributeDao will help me to add attributes: uid and prénom and groupMembership. BUT, I still do not get any attibutes. Is there anything wrong in the code?
You probably need to authorize your application in CAS service registry to release attributes. By default, nothing is allowed. See http://apereo.github.io/cas/4.0.x/integration/Attribute-Release.html
I have the following configuration :
<property name="defaultViews">
<list>
<!-- JSON View -->
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
<!-- XML View -->
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="autodetectAnnotations" value="true" />
</bean>
</constructor-arg>
</bean>
</list>
</property>
It creates a json, but the root name is not what i want
#XStreamAlias("house")
#JsonAutoDetect
#JsonRootName(value = "house")
public class TableHouse {
private Long value;
.....
}
For the xml it works fine, however for the json it does not pick up the #JsonRootName.. and outputs json with class name as root...
Any ideas?
You have to enable root-level wrapping. See How do I rename the root key of a JSON with Java Jackson? to have an idea on how to use JsonRootName properly.
I am doing unit testing and I expect that all data committed to the MySQL database will be rolled back... but this isn't the case. The data is being committed, even though my log was showing that the rollback was happening. I've been wrestling with this for a couple days so my setup has changed quite a bit, here's my current setup.
LoginDAOTest.java:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"file:web/WEB-INF/applicationContext-test.xml", "file:web/WEB-INF/dispatcher-servlet-test.xml"})
#TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
public class UserServiceTest {
private UserService userService;
#Test
public void should_return_true_when_user_is_logged_in ()
throws Exception
{
String[] usernames = {"a","b","c","d"};
for (String username : usernames)
{
userService.logUserIn(username);
assertThat(userService.isUserLoggedIn(username), is(equalTo(true)));
}
}
ApplicationContext-Text.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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/******"/>
<property name="username" value="*****"/>
<property name="password" value="*****"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="userService" class="Service.UserService">
<property name="userDAO" ref="userDAO"/>
</bean>
<bean id="userDAO" class="DAO.UserDAO">
<property name="hibernateTemplate" ref="hibernateTemplate"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>/himapping/User.hbm.xml</value>
<value>/himapping/setup.hbm.xml</value>
<value>/himapping/UserHistory.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory"/>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
</beans>
I have been reading about the issue, and I've already checked to ensure that the MySQL database tables are setup to use InnoDB. Also I have been able to successfully implement rolling back of transactions outside of my testing suite. So this must be some sort of incorrect setup on my part.
Any help would be greatly appreciated :)
The problem turned out to be that the connection was auto-committing BEFORE the transaction could be rolled back. I had to change my dataSource bean to include a defaultAutoCommit property:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="Ecosim07"/>
<property name="defaultAutoCommit" value="false" />
</bean>
For me defaultAutoCommit and #Transactional didn't help. I had to change db type to InnoDB
Another way to fix your problem:
Instead of using:
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
, which creates a MyISAM table by default, hence not supporting transactions
Try using
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
, which creates InnoDB tables, and thus supports transactions.
This must be used
#TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
#TestExecutionListeners({ TransactionalTestExecutionListener.class })
#Transactional
TransactionalTestExecutionListener contains isRollback() which rollbacks the
transaction after the test method.
I hope I am right and that this is a simple one. You are missing the #Transactional annotation on your test class. This means that the test method itself isn't run in a transaction and thus there is nothing to roll back. Hope this helps.