Bean Required for Spring MVC xml file for Amazon S3 - spring

What should be the beans in xml file for this same java based configuration?
#Configuration
#ComponentScan(basePackageClasses = Application.class, excludeFilters = #Filter({Controller.class, Configuration.class}))
public class ApplicationConfig {
#Value("${aws_access_key_id}")
private String awsId;
#Value("${aws_secret_access_key}")
private String awsKey;
#Bean
public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setLocations(new Resource[] {
new ClassPathResource("/amazon.properties")
});
return ppc;
}
#Bean
public AWSCredentials credential() {
return new BasicAWSCredentials(awsId, awsKey);
}
#Bean
public AmazonS3 s3client() {
return new AmazonS3Client(credential());
}
}

<context:property-placeholder
ignore-resource-not-found="true" ignore-unresolvable="true"
system-properties-mode="OVERRIDE" order="0"
location="classpath:amazon.properties"/>
<bean id="credential" class="com.amazonaws.auth.BasicAWSCredentials">
<constructor-arg name="accessKey" value="${aws_access_key_id}"/>
<constructor-arg name="secretKey" value="${aws_secret_access_key}"/>
</bean>
<bean id="s3client" class="com.amazonaws.services.s3.AmazonS3Client">
<constructor-arg ref="credential"/>
</bean>

Related

Spring #Autowire retuning null while creating an object

I am new to this Spring and trying to learn it.
I am using basic auth jersey and using spring to inject my db props and instantiate the class. However I am getting null pointer exception when I try this with a REST call using postman.
Below is code snippet
AppContx.xml
<context:annotation-config />
<context:component-scan base-package="com.rest" />
<bean id="userDao" class="com.rest.dao.UserDao">
<property name="dataSource" ref="ds" />
</bean>
<bean id="ds" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/Weber" />
<property name="resourceRef" value="true" />
</bean>
Filter
#Provider
public class AuthenticationFilter implements ContainerRequestFilter {
/*ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
IuserDao userDao = (IuserDao) ctx.getBean("userDao");*/
#Autowired
UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public UserDao getUserDao() {
return userDao;
}
if (userDao.getUSerForAuthentication(password, username) == 1) {
String userRole = "ADMIN";
if (rolesSet.contains(userRole)) {
isAllowed = true;
}
DAO
#Autowired
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
I am successfully able to inject DB properties to my data source using #Autowired but I am unable to instantiate the UserDao in my Filter class.
Thank You
Mark

Convert JMS out bound channel adapter to equavalent Spring Integration DSL in java 1.7

How can I convert <int-jms:outbound-channel-adapter channel="topicChannel" destination="requestQueue"/> to equivalent Spring Integration DSL in java 1.7
Below is the ActiveMQ configuration:
<bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
<property name="targetConnectionFactory">
<bean class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://localhost:61616"/>
</bean>
</property>
<property name="sessionCacheSize" value="10"/>
</bean>
<bean id="requestQueue" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="queue.demo"/>
</bean>
#Bean
public ActiveMQQueue requestQueue() {
return new ActiveMQQueue("queue.demo");
}
etc.
You can configure the sender like this:
#Configuration
#ComponentScan(basePackages = { "com.sample.dispatcher" })
public class DispatcherConfig {
public static final String JOB_TOPIC = "jobTopic";
#Bean
#ServiceActivator(inputChannel = JOB_TOPIC)
public MessageHandler outboundJmsAdapter(JmsTemplate template) {
JmsSendingMessageHandler handler = new JmsSendingMessageHandler(template);
handler.setDestinationName(JOB_TOPIC);
return handler;
}
#Bean(name = JOB_TOPIC)
public MessageChannel jobTopic() {
return new PublishSubscribeChannel();
}
}
and the listener like this
#Configuration
#ComponentScan(basePackages = { "com.sample.processor" })
#IntegrationComponentScan(basePackages = { "com.sample.processor" })
public class ProcessorConfig {
public static final String ON_POST_JOB = "onPostJob";
public static final String JOB_TOPIC = "jobTopic";
#Bean
public Queue jobTopic() {
return new ActiveMQQueue(JOB_TOPIC);
}
#Bean
public JmsMessageDrivenEndpoint inboundJmsAdapter(ConnectionFactory connectionFactory) {
return new JmsMessageEndpointBuilder()
.setConnectionFactory(connectionFactory)
.setDestination(JOB_TOPIC)
.setInputChannel(onPostJob())
.build();
}
#Bean(name = ON_POST_JOB)
public MessageChannel onPostJob() {
return new PublishSubscribeChannel();
}
}
I have a sample project that uses jms and Spring Integration as form of communication between two applications running on separate vm/process/:
https://github.com/vineey/sample-jobqueue

UsernameTokenValidator Can not #Autowired Dao

I have a Spring-ws and i am using Apahce-wss4j for spring-ws authentication. I want to use my Dao class in my custom TokenValidator class. But there was an exception can not #Autowired my Dao class. Here is my code
applicationContext.xml
<bean id="myWssConfig" class="tr.com.xxx.services.MyWssConfig"/>
<bean id="kepDBDAO" class="tr.com.xxx.dao.KepDBDAOImpl"/>
<bean id="ssha" class="tr.com.xxx.utils.SSHA"/>
<bean id="memberStatusService" class="tr.com.xxx.services.MemberStatusServiceImpl"/>
<bean id="myUsernameTokenValidator" class="tr.com.xxx.services.MyUsernameTokenValidator">
<property name="kepDBDAO" ref="kepDBDAO"/>
</bean>
<sws:interceptors>
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="validationActions" value="UsernameToken"/>
<property name="validationCallbackHandler" ref="callbackHandler"/>
<property name="wssConfig">
<ref bean="myWssConfig"/>
</property>
</bean>
</sws:interceptors>
Here is MyWssConfig.java
#Component("myWssConfig")
public class MyWssConfig extends WSSConfig {
public MyWssConfig() {
setValidator(WSSecurityEngine.USERNAME_TOKEN, MyUsernameTokenValidator.class);
setRequiredPasswordType(WSConstants.PASSWORD_TEXT);
}
}
And here is MyUsernameTokenValidator.java
#Component
public class MyUsernameTokenValidator extends UsernameTokenValidator {
private static final Logger LOGGER = LoggerFactory
.getLogger(MyUsernameTokenValidator.class);
#Autowired
private KepDBDAO kepDBDAO;
#Transactional
protected void verifyPlaintextPassword(UsernameToken usernameToken, RequestData data) throws WSSecurityException {
if (usernameToken != null && usernameToken.getPassword() != null) {
byte[] saltValue = null;
kepDBDAO.getWsUsers("basvuru");
String hashPassword = null;
try {
hashPassword = SSHA.calculateSSHA256(saltValue, usernameToken.getPassword());
} catch (NoSuchAlgorithmException e) {
LOGGER.error(e.toString(), e);
} catch (IOException e) {
LOGGER.error(e.toString(), e);
}
usernameToken.setPassword(hashPassword);
super.verifyDigestPassword(usernameToken, data);
}
}
public KepDBDAO getKepDBDAO() {
return kepDBDAO;
}
public void setKepDBDAO(KepDBDAO kepDBDAO) {
this.kepDBDAO = kepDBDAO;
}
}
Couldn't #Autowired my KepDBDAO when I call webservice in SOAPUI.
Help me please.. THank you all guys.
Try this:
1. In applicationContext:
<context:component-scan base-package="tr.com.xxx.dao"/>
<context:component-scan base-package="package for MyUsernameTokenValidator"/>
remove these beans:
kepDBDAO, myUsernameTokenValidator
2. Remove setter and getter for KepDBDAO in MyUsernameTokenValidator
3. Make sure KepDBDAOImpl is marked as #Service
I solved my problem.
#Component("myWssConfig")
public class MyWssConfig extends WSSConfig {
#Autowired
private MyUsernameTokenValidator myUsernameTokenValidator;
//
#PostConstruct
public void myInit() {
setValidator(WSSecurityEngine.USERNAME_TOKEN, myUsernameTokenValidator);
setRequiredPasswordType(WSConstants.PASSWORD_TEXT);
}
}

Spring Social + Spring Security HTTPS/HTTP

How can I make the remember me cookie and session accessible through http when requesting a facebook login from either http or https with spring social. Currently if a user logs in through https the cookie is not readable through http pages (no user logged in). I am using use-secure-cookie="false" but that doesn't help.
<s:remember-me key="mykey" services-ref="rememberMeServices" use-secure-cookie="false"/>
<bean id="rememberMeServices" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
<property name="userDetailsService" ref="userService" />
<property name="tokenRepository" ref="persistentTokenRepository" />
<property name="key" value="mykey" />
<property name="cookieName" value="rmb" />
<property name="useSecureCookie" value="false" />
<property name="tokenValiditySeconds" value="946708560" />
<property name="alwaysRemember" value="true"></property>
</bean>
My Social Config:
#Configuration
public class SocialConfig {
#Inject
private Environment environment;
#Inject
private DataSource dataSource;
#Inject
private TextEncryptor textEncryptor;
#Value("${app.url}")
private String applicationUrl;
#Value("${facebook.clientId}")
private String facebookClientId;
#Value("${facebook.clientSecret}")
private String facebookClientSecret;
#Bean
public ConnectionFactoryLocator connectionFactoryLocator() {
ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry();
registry.addConnectionFactory(new FacebookConnectionFactory(
facebookClientId,
facebookClientSecret));
return registry;
}
#Bean
#Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
public ConnectionRepository connectionRepository() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in");
}
return usersConnectionRepository().createConnectionRepository(authentication.getName());
}
#Bean
public UsersConnectionRepository usersConnectionRepository() {
JdbcUsersConnectionRepository repository = new JdbcUsersConnectionRepository(
dataSource, connectionFactoryLocator(), textEncryptor);
repository.setConnectionSignUp(connectionSignUp());
return repository;
}
#Bean
public TextEncryptor textEncryptor() {
return Encryptors.noOpText();
}
#Bean
public ConnectController connectController() {
ConnectController controller = new ConnectController(
connectionFactoryLocator(), connectionRepository());
controller.setApplicationUrl(applicationUrl);
return controller;
}
#Bean
public ProviderSignInController providerSignInController(RequestCache requestCache) {
ProviderSignInController controller = new ProviderSignInController(connectionFactoryLocator(),
usersConnectionRepository(), signInAdapter());
controller.setSignUpUrl("/register");
controller.setSignInUrl("/socialSignIn");
controller.setPostSignInUrl("socialSignIn");
controller.addSignInInterceptor(new RedirectAfterConnectInterceptor());
return controller;
}
#Bean
public SignInAdapter signInAdapter() {
return new SignInAdapterImpl();
}
#Bean
public ConnectionSignUp connectionSignUp() {
return new ConnectionSignUpImpl();
}
}

Spring #Cacheable Not Working

I have a dao method annotate with #Cacheable but its cache not working at all. I put log message inside the method.
<cache:annotation-driven mode="proxy" proxy-target-class="true" cache-manager="cacheManager" />
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="WEB-INF/ehcache/ehcache.xml"></property>
<property name="shared" value="true"></property>
</bean>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehcache"></property>
</bean>
#Controller
#RequestMapping(value = "/analytics")
public class AnalyticsController {
#Autowired
private ReportDao reportDao;
/**
*
*/
public AnalyticsController() {
}
#RequestMapping(value = "/lcr-report", method = RequestMethod.GET)
public String viewCostReport(ModelMap map) {
List<Country> countryList = reportDao.getAllCountry();
map.put("countryList", countryList);
return "lcrReport";
}
}
#Repository
#Transactional(propagation=Propagation.REQUIRED, isolation=Isolation.DEFAULT,
rollbackFor={DataAccessException.class, SQLException.class, Exception.class})
public class ReportDao {
#Autowired
private JdbcTemplate dao;
/**
*
*/
public ReportDao() {
}
#Cacheable(value = {"reportDao"}/*, key= "T(Country).hash(#List<Country>)"*/)
#Transactional(propagation=Propagation.REQUIRED, isolation=Isolation.DEFAULT, readOnly=true,
rollbackFor={DataAccessException.class, SQLException.class, Exception.class})
public List<Country> getAllCountry() {
List<Country> countryList = null;
BeanPropertyRowMapper<Country> mapper = new BeanPropertyRowMapper<Country>(Country.class);
PreparedStatementCreator psc = new GenericPreparedStatementCreator("select c.country_code as countryCode, c.name as countryName from country c");
System.out.println("Not from cache");
countryList = dao.query(psc, mapper);
return countryList;
}
}
You should create key by using parameters to method getAllCountry. In your case it is empty, so you can do like this:
#Transactional(readOnly = true)
#Cacheable(value = CACHE_NAME, key = "'countries'")
and check if it works using Map cache:
#Configuration
#EnableCaching(proxyTargetClass = true)
public class CacheProducer {
#Bean
public CacheManager cacheManager() {
SimpleCacheManager result = new SimpleCacheManager();
result.setCaches(Arrays.asList(new ConcurrentMapCache(DictionaryServiceImpl.CACHE_NAME)));
return result;
}
}
If it works - it is time to check your echache config.

Resources