Set datasource for custom itemWriter (spring batch) - datasource

I want to read from a database and write to another database using a custom itemWriter.
How can I set datasource for custom itemWriter?

Please have a look at this sample project Spring Batch Example
Here is sample code for your custom ItemWriter.
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.stereotype.Component;
import com.x.y.z.MyBean;
#Component("myJdbcWriter")
public class MyCustomJdbcWriter extends JdbcBatchItemWriter<MyBean> {
MyCustomJdbcWriter() {
}
#Override
#Resource
public void setDataSource(DataSource dataSource) {
super.setDataSource(dataSource);
}
// define other methods also that you want to override in the same manner
}
Either use auto-detect feature of Spring or you can define a bean in your spring xml configuration file as shown below and use this bean in you respective job.
<bean id="myJdbcWriter" class="com.x.y.z.MyCustomJdbcWriter"
scope="step">
<property name="dataSource" ref="dataSource" />
</bean>

Related

ActiveMQ Authorization - How To Read Authorization Entries from Database

I am in a process of deploying ActiveMQ with custom Authentication and Authorization. I have a query regarding custom authorization map.
Question
I want to have the authorization entries read from database rather than activemq.xml. We don't want to write our authorization entries in activemq.xml file. I don't want to change the wildcard queue name hierarchies as provided in default authorization plugin.
What code components do I need to re-write ?
I have figured out the answer to my above question. I only need to interface my custom class so that I am able to load authorization entries from a source other than activemq.xml. And I can also re-load my authorization every 1 minute so that If a new role or authorization entry is made, it gets reloaded in to the system without restarting.
Solution Configurations
Create a class that interface AuthorizationMap.
In my case I extended my class from DefaultAuthorizationMap.java. I
want similar functionality and want to change only the input of authorization entries. My code reads roles from a database. Refer to section "Code-CustomAuthorizationMap" below.
Configure CustomAuthorizationMap class as bean in activemq.xml
<plugins>
<jaasAuthenticationPlugin configuration="activemq"/>
<authorizationPlugin>
<map>
<bean xmlns="" class="com.test.CustomAuthorizationMap"
</map>
</authorizationPlugin
</plugins>
Add lib to classpath
a. Create the jar file. Place it in "%ActiveMQ-Home%/lib" folder. E.g. custom-authorization.jar
b. Modify "%ActiveMQ-Home%/bin/activemq.bat".
**Replace**
set ACTIVEMQ_CLASSPATH=%ACTIVEMQ_CONF%;%ACTIVEMQ_BASE%/conf;%ACTIVEMQ_HOME%/conf;%ACTIVEMQ_CLASSPATH%;
**With**
set ACTIVEMQ_CLASSPATH=%ACTIVEMQ_CONF%;%ACTIVEMQ_BASE%/conf;%ACTIVEMQ_HOME%/conf;%ACTIVEMQ_CLASSPATH%;%ACTIVEMQ_HOME%/lib/custom-authorization.jar;
Code-CustomAuthorizationMap
package com.test.authorization.map;
import java.util.ArrayList;
import java.util.List;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTempQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.filter.DefaultDestinationMapEntry;
import org.apache.activemq.filter.DestinationMapEntry;
import org.apache.activemq.security.AuthorizationEntry;
import org.apache.activemq.security.DefaultAuthorizationMap;
public class SecGwAuthorizationMap extends DefaultAuthorizationMap {
public SecGwAuthorizationMap() throws Exception {
super();
List<DestinationMapEntry> authorizationEntries =
loadAuthorizationEntriesFromPropFiles();
// For information. After loading I populate
//authorization entries like below
// AuthorizationEntry entry = new AuthorizationEntry();
// entry.setTopic(">");
// entry.setAdmin("admins");
// entry.setRead("admins");
// entry.setWrite("admins");
// authorizationEntries.add(entry);
// entry = new AuthorizationEntry();
// entry.setQueue(">");
// entry.setAdmin("admins");
// entry.setRead("admins");
// entry.setWrite("admins");
// authorizationEntries.add(entry);
// entry= new AuthorizationEntry();
// entry.setTopic("ActiveMQ.Advisory.>");
// entry.setAdmin("gcabrokerusers,admins,users");
// entry.setRead("gcabrokerusers");
// entry.setWrite("gcabrokerusers");
// authorizationEntries.add(entry);
// entry = new AuthorizationEntry();
// entry.setQueue("gcaa.test.jms.>");
// entry.setAdmin("gcabrokerusers");
// entry.setRead("gcabrokerusers");
// entry.setWrite("gcabrokerusers");
// authorizationEntries.add(entry);
setAuthorizationEntries(authorizationEntries);
}
public SecGwAuthorizationMap(List<DestinationMapEntry>
authorizationEntries) {
super(authorizationEntries);
// TODO Auto-generated constructor stub
}
}
Note:- Below is a sample roles.properties files to tell how we are creating authorization roles.
roles.properties file
//commentedLine Destination Read-ACLs Write-ACLs AdminAcls Type
ActiveMQ.Advisory.>::admins,appUsr::admins,appusr::admins,appUsr::TOPIC
test.accounts.queue::appClientId::appClientId::admins::QUEUE
>::admins::admins::admins::QUEUE
>::admins::admins::admins::TOPIC

GWTP Dispatch -- Replacement for DefaultDispatchAsync (RpcDispatchAsync)

We had been using GWT-Dispatch to support the RPC calls using command patterns. We now need to move to GWTP since Dispatch has been absorbed into that project. Would seem to be all well and good. The problem is that we are unable to get a DispatchAsync object anymore. In Dispatch, it was extremely simple to get the default implementation:
private final DispatchAsync dispatchAsync = GWT.create(DefaultDispatchAsync.class);
This no longer works. DefaultDispatchAsync is deprecated, and when we use the suggested replacement for it (RpcDispatchAsync) it looks like this:
private final DispatchAsync dispatchAsync = GWT.create(RpcDispatchAsync.class);
we get the following error:
Rebind result 'com.gwtplatform.dispatch.rpc.client.RpcDispatchAsync' has no default (zero argument) constructors.
Does anyone have an idea about how to do this? I know if we rewrite all the pages to use the GWTP MVP pattern that it's available in the Presenter but moving things over to use full GWTP is a long process and if we can't get the RPC calls up and working quickly that will be a problem for the project.
Thanks in advance -- hopefully it's something easy.
DispatchAsync is no longer generated via deferred binding. Thus you can’t use GWT.create to instantiate it.
GWTP Dispatch is making heavy use of GIN/Guice. So I would recommend that you use this dependency injection framework to get GWTP Dispatch work.
Here is an example, which provides easy access to the DispatchAsync (without the need of rewriting all pages to use the GWTP MVP Pattern):
[Note: This example uses gwtp dispatch 1.0.3]
Client:
MyClientModule.java - configure injection-rules for DispatchAsync
import com.google.gwt.inject.client.AbstractGinModule;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.gwtplatform.dispatch.client.DefaultExceptionHandler;
import com.gwtplatform.dispatch.client.DefaultSecurityCookieAccessor;
import com.gwtplatform.dispatch.client.ExceptionHandler;
import com.gwtplatform.dispatch.client.RpcDispatchAsync;
import com.gwtplatform.dispatch.client.actionhandler.ClientActionHandlerRegistry;
import com.gwtplatform.dispatch.client.actionhandler.DefaultClientActionHandlerRegistry;
import com.gwtplatform.dispatch.shared.DispatchAsync;
import com.gwtplatform.dispatch.shared.SecurityCookie;
import com.gwtplatform.dispatch.shared.SecurityCookieAccessor;
public class MyClientModule extends AbstractGinModule {
private static final String COOKIE_NAME = "JSESSIONID";
#Override
protected void configure() {
bindConstant().annotatedWith(SecurityCookie.class).to(COOKIE_NAME);
bind(ExceptionHandler.class).to(DefaultExceptionHandler.class);
bind(SecurityCookieAccessor.class).to(DefaultSecurityCookieAccessor.class);
bind(ClientActionHandlerRegistry.class).to(DefaultClientActionHandlerRegistry.class);
bind(DispatchAsync.class).toProvider(DispatchAsyncProvider.class).in(Singleton.class);
}
public static class DispatchAsyncProvider implements Provider<DispatchAsync> {
private final DispatchAsync fDispatchAsync;
#Inject
public DispatchAsyncProvider(ExceptionHandler eh, SecurityCookieAccessor sca, ClientActionHandlerRegistry cahr) {
this.fDispatchAsync = new RpcDispatchAsync(eh, sca, cahr);
}
#Override
public DispatchAsync get() {
return fDispatchAsync;
}
}
}
MyClientInjector.java - injector provides access to DispatchAsync
import com.google.gwt.inject.client.GinModules;
import com.google.gwt.inject.client.Ginjector;
import com.gwtplatform.dispatch.shared.DispatchAsync;
#GinModules(MyClientModule.class)
public interface MyClientInjector extends Ginjector {
DispatchAsync getDispatchAsync();
}
Server:
MyGuiceServletContextListener.java - create injector for the servlet, which receives the commands and the servermodule, in which the bindings between (clientside) command and (serverside) handler are defined.
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;
public class MyGuiceServletContextListener extends GuiceServletContextListener {
#Override
protected Injector getInjector() {
return Guice.createInjector(new ServerModule(), new DispatchServletModule());
}
}
DispatchServletModule.java - configures the servlet, which receives the commands
import com.google.inject.servlet.ServletModule;
import com.gwtplatform.dispatch.server.guice.DispatchServiceImpl;
import com.gwtplatform.dispatch.server.guice.HttpSessionSecurityCookieFilter;
import com.gwtplatform.dispatch.shared.Action;
import com.gwtplatform.dispatch.shared.SecurityCookie;
public class DispatchServletModule extends ServletModule {
#Override
public void configureServlets() {
bindConstant().annotatedWith(SecurityCookie.class).to("JSESSIONID");
filter("*").through(HttpSessionSecurityCookieFilter.class);
serve("/" + Action.DEFAULT_SERVICE_NAME + "*").with(DispatchServiceImpl.class);
}
}
ServerModule.java - bindings between (clientside) command and (serverside) handler
import com.gwtplatform.dispatch.server.guice.HandlerModule;
public class ServerModule extends HandlerModule {
#Override
protected void configureHandlers() {
bindHandler(YourCommand.class, YourHandler.class);
}
}
web.xml - tell the web-server to use MyGuiceServletContextListener
<filter>
<filter-name>guiceFilter</filter-name>
<filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>guiceFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--
This Guice listener hijacks all further filters and servlets. Extra
filters and servlets have to be configured in your
ServletModule#configureServlets() by calling
serve(String).with(Class<? extends HttpServlet>) and
filter(String).through(Class<? extends Filter)
-->
<listener>
<listener-class>de.gwtpdispatch.server.MyGuiceServletContextListener</listener-class>
</listener>
Usage
Now you can create the injector with deferred binding and get access to the DispatchAsync-instance:
MyClientInjector injector = GWT.create(MyClientInjector.class);
injector.getDispatchAsync().execute(...YourCommand...)
(AND: Don't forget to include the jars of GIN and Guice in your project and add the gin-module to the project's gwt.xml)
I hope this explanation is detailed enough. Happy coding :)

SessionFactory XML configuration works, but not Java configuration. Why?

In a Spring XML configuration, I have the followings:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
....
</bean>
and in a Java class, I have
#Autowired
private SessionFactory sessionFactory;
without a setter. That works.
Now, I change the sessionFactory to a Java configuration as the followings.
#Configuration
#EnableTransactionManagement
#PropertySource({ "classpath:jdbc.properties" })
public class PersistenceConfig {
#Bean
public SessionFactory sessionFactory() {
LocalSessionFactoryBuilder lsfb = new LocalSessionFactoryBuilder(dataSource());
lsfb.addAnnotatedClasses(...);
lsfb.setProperties(hibernateProperties());
return lsfb.buildSessionFactory();
}
// ...
}
And I get an error "could not autowire field". Adding a setter doesn't help. Why the sessionFactory can't get autowired with a Java configuration?
BTW, I can work around this problem by having a Java configuration for the DAO as well.
I see that there is no #ComponentScan annotation on your #Configuration class, so probably the problem is in how you import this configuration. Please ensure that all particular beans live in the same context or at least that PersistenceConfig is parent to the context in which you are autowiring SessionFactory
I have added the #ComponentScan annotation and it doesn't solve the problem. The annotation tells Spring to look for any #Components to configure as beans. This problem seems to me is that during the process of creating a bean with #Component, it can't find a bean configured in my Java configuration file which is started in WebAppInitializer.

How to set a spring.NET AOP advice before method call

I want to intercept a method call before execution using spring.NET. Let's assume the class/method to be intercepted is:
public class Listener
{
public void Handle()
{
// method body
}
}
This is what I've done (assuming all code is in a namespace called Example):
1.Created the advice:
public class MyAopAdvice : IMethodBeforeAdvice
{
public void Before(MethodInfo method, object[] args, object target)
{
// Advice action
}
}
2.Updated my spring xml configs:
<object id="myAopAdvice" type="Example.MyAopAdvice" />
<object id="listener" type="Spring.Aop.Framework.ProxyFactoryObject">
<property name="Target">
<object type="Example.Listener" autowire="autodetect"/>
</property>
<property name="InterceptorNames">
<list>
<value>myAopAdvice</value>
</list>
</property>
</object>
For some reason my Advice code is not getting hit if I put a breakpoint in it. However, if I add some console logging statements within my advice, it seems they are logged, but not at the appropriate time (i.e., before calling Listener.Handle()).
I'm willing to bet my configs are wrong (for once, I may be missing a way to tell the configs to listen for just the Handle method call and not any other method that Listener may have). Any ideas what's wrong?
Declare your Handle method as virtual:
public virtual void Handle() // ...
Your class does not implement any interfaces, which spring.net's default aop mechanism uses to create proxies. When spring.net does not find any interfaces to proxy, it looks for virtual methods to create a proxy for a class.

Apache - CXF jaxrs-server - unable to hit the resource which is defined first in jaxrs-server endpoint

I'm using Apache-CXF for JAX-RS implementation. I have two resources which are defined in two bean. My jaxrs-server in context.xml os as follow
<jaxrs:server id="serverId" address="/">
<jaxrs:serviceBeans>
<bean id="bean1" class="com.Bean1" />
<bean id="bean2" class="com.Bean2" />
</jaxrs:serviceBeans>
</jaxrs:server>
Interface for Bean1 is as follows -
#Path("/")
public interface IBean1 {
#GET
#Path("/beaninfo1")
#Produces({ MediaType.APPLICATION_XML })
public Response checkBean1();
}
Interface for Bean2 is as follows -
#Path("/")
public interface IBean2 {
#GET
#Path("/beaninfo2")
#Produces({ MediaType.APPLICATION_XML })
public Response checkBean1();
}
I'm unable to hit the resource which is defined in last in serviceBans definition. In this case i'm able to hit Bean2 but not Bean1, getting 404 error, where as if i put Bean2 first and then Bean1, i'm able to hit Bean1 only.
Is there anything wrong with my configuration ?
It is possible to have the same #Path annotation at class level. You need to use a resourcecomparator. Please check this question
Yes. Give them different #Path annotations at the class level.