Promoting header values from a file to job execution context - java

I have a file where the first line contains the field names as headers as below:
Id;ToyName;ToyType;ToyColor
1;abc;abc;red
2;pqr;pqr;blue
3;xyz;xyz;orange
My reader is as below:
<beans:bean id="MyFileItemReader" class="org.springframework.batch.item.file.FlatFileItemReader" scope="step">
<beans:property name="linesToSkip" value="1"/>
<beans:property name="skippedLinesCallback" ref="headerSkipCallback" />
<beans:property name="resource" ref="MyInputFileResource" />
<beans:property name="lineMapper">
<beans:bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<beans:property name="lineTokenizer">
<beans:bean class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
<beans:property name="delimiter" value=";"/>
<beans:property name="names" value="#{jobExecutionContext['columnsFromFileHeader']}" />
</beans:bean>
</beans:property>
<beans:property name="fieldSetMapper">
<beans:bean class="mypackage.MyFieldSetMapper">
</beans:bean>
</beans:property>
</beans:bean>
</beans:property>
</beans:bean>
Thus I have a header line call back implemented to read the skipped header line.
<beans:bean id="headerSkipCallback" class="mypackage.HeaderLineHandler" scope="step">
</beans:bean>
and the class as:
public class HeaderLineHandler implements LineCallbackHandler {
public void handleLine(final String headerLine) {
System.out.println(headerLine);
}}
This works correctly and the header line from the file gets printed.
Now I want to use these field names from file header in the names property of DefaultLineTokenizer
So to put the header line inside the context, I implemented a context injector class as below:
public class StepExecutionListenerCtxInjector {
private ExecutionContext stepExecutionCtx;
private ExecutionContext jobExecutionCtx;
#BeforeStep
public void beforeStep(final StepExecution stepExecution) {
this.stepExecutionCtx = stepExecution.getExecutionContext();
this.jobExecutionCtx = stepExecution.getJobExecution().getExecutionContext();
}
public ExecutionContext getStepExecutionCtx() {
return this.stepExecutionCtx;
}
public ExecutionContext getJobExecutionCtx() {
return this.jobExecutionCtx;
}
}
And changed my header line handler to:
<beans:bean id="headerSkipCallback" class="mypackage.HeaderLineHandler" scope="step">
<beans:property name="stepExecutionListener" ref="stepExecutionListener" />
</beans:bean>
and the class as:
public class HeaderLineHandler implements LineCallbackHandler {
private StepExecutionListenerCtxInjector stepExecutionListener;
public void handleLine(final String headerLine) {
this.stepExecutionListener.getJobExecutionCtx().put("columnsFromFileHeader", headerLine.replaceAll(";", ","));
}
// getter setters
}
Here I am saving the header line as columnsFromFile key inside the job execution context.
However, when I am trying to access it in DefaultLineTokenizer as:
<beans:property name="names" value="#{jobExecutionContext['columnsFromFileHeader']}" />
I am getting null pointer exception:
org.springframework.batch.item.file.FlatFileParseException: Parsing error at line: 2 in resource=[file [C:\myFile.dat]], input=[1;abc;abc;red]
at org.springframework.batch.item.file.FlatFileItemReader.doRead(FlatFileItemReader.java:182)
Caused by:
java.lang.NullPointerException
at org.springframework.batch.item.file.transform.AbstractLineTokenizer.tokenize(AbstractLineTokenizer.java:113)
How can I use the header line from the file in the property to DefaultLineTokenizer?

Make DelimitedLineTokenizer a non-anonymous bean and inject it into your HeaderLineHandler; in HeaderLineHandler.handleLine() set DelimitedLineTokenizer.names using handleLine() input param.
I can't test it but should works.

Related

Spring batch - How to write data multiple rows after processing single record?

I have bean class as below -
public class Account {
private String strAccNumber = "";
private List<Account> accountList = new ArrayList<Account>();
// getter setter
....
...
#Override
public String toString() {
// code for PassThroughLineAggregator
String data="";
for (int j=0; j<accountList.size(); j++) {
Account bean = accountList.get(j);
data = data + bean.getStrAccNumber();
if (j<(accountList.size()-1)) {
data = data + "\n";
}
}
return data;
}
}
to write data I want to set accountList in my config file.
I'm using below code to set bean property.
<bean id="flatFileReader" class="org.springframework.batch.item.file.FlatFileItemReader"
scope="step">
<property name="resource" value="classpath:springBatch.csv" />
<property name="strict" value="false"></property>
<property name="linesToSkip" value="1" />
<property name="lineMapper">
<bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<property name="lineTokenizer">
<bean
class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
<property name="names" value="ACC#" />
</bean>
</property>
<property name="fieldSetMapper">
<bean
class="com.abc.reader.AccountDetailsFieldSetMapper" />
</property>
</bean>
</property>
</bean>
<bean id="flatFileProcessor"
class="com.abc.processor.AccountItemProcessor"
scope="step"></bean>
<bean id="flatFileWriter"
class="com.abc.FlatFileItemWriterListener"
scope="step">
<property name="resource" value="classpath:springBatch1.csv" />
<property name="lineAggregator">
<bean class="org.springframework.batch.item.file.transform.DelimitedLineAggregator">
<property name="fieldExtractor">
<bean class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
<property name="names" value="strAccNumber" />
</bean>
</property>
</bean>
</property>
</bean>
AccountItemProcessor -
public class AccountItemProcessor implements ItemProcessor<Account, List<Account>>{
#Override
public List<Account> process(Account accObj) throws Exception {
// logic..
}
After processing single record in the process step I want to write multiple items(list of item) , how can I write multiple item at a time using arraylist. In my case I want to write data from accountlist.
You'll want to implement your own LineAggregator. That is what provides the String to be written to the file. In your case, you'll write one that returns a String that is really multiple lines.
You can read more about the LineAggregator interface in the documentation here: http://docs.spring.io/spring-batch/apidocs/org/springframework/batch/item/file/transform/LineAggregator.html

Spring security authentication fails

I am using Spring security version 3.1.4.RELEASE. When I try to login to the application I am getting an error. I have cross checked the credentials in DB. Even though the credentials are correct the system is not lettng me to login. Following the details of error and my configuration settings.
Getting following error while trying to login to the system:
web.security.auth.CustomUsernamePasswordAuthenticationFilter username is support
web.security.auth.CustomUsernamePasswordAuthenticationFilter password is [PROTECTED]
web.security.auth.CustomUsernamePasswordAuthenticationFilter authRequest is org.springframework.security.authentication.UsernamePasswordAuthenticationToken#4a159a52: Principal: support; Credentials: [PROTECTED]; Authenticated: false; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#0: RemoteIpAddress: 204.238.52.177; SessionId: 9B49838B0DF4224E169EAF425C0AABE9; Not granted any authorities
web.security.auth.CustomUsernamePasswordAuthenticationFilter Authentication manager was com.sun.proxy.$Proxy476
System.out loadUserByUsername support enter
org.springframework.security.authentication.event.LoggerListener Authentication event AuthenticationFailureServiceExceptionEvent: support; details: org.springframework.security.web.authentication.WebAuthenticationDetails#0: RemoteIpAddress: 204.238.52.177; SessionId: 9B49838B0DF4224E169EAF425C0AABE9; exception: null
Here I am getting the exception as null!
Config:
<authentication-manager alias="authenticationManager">
<authentication-provider ref="daoAuthenticationProvider" />
</authentication-manager>
<beans:bean id="plaintextPasswordEncoder" class="org.springframework.security.authentication.encoding.PlaintextPasswordEncoder" />
<beans:bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<beans:property name="userDetailsService" ref="daoUserDetailsService" />
<beans:property name="passwordEncoder" ref="plaintextPasswordEncoder" />
</beans:bean>
<beans:bean id="daoUserDetailsService" class="web.security.auth.DAOUserDetailsService">
<beans:property name="dataSource" ref="dataSource" />
</beans:bean>
<beans:bean id="dataSource" class="web.security.auth.DAODataSource" />
<beans:bean id="filterChainProxy" class="org.springframework.security.web.FilterChainProxy">
<filter-chain-map request-matcher="ant">
<filter-chain pattern="/**" filters="channelProcessingFilter, SecurityContextPersistenceFilter, logoutFilter, authenticationFilter, anonymousAuthFilter, exceptionTranslationFilter, filterSecurityInterceptor" />
</filter-chain-map>
</beans:bean>
<beans:bean id="channelProcessingFilter" class="org.springframework.security.web.access.channel.ChannelProcessingFilter">
<beans:property name="channelDecisionManager" ref="channelDecisionManager"/>
<beans:property name="securityMetadataSource">
<filter-security-metadata-source request-matcher="ant">
<intercept-url pattern="/**" access="REQUIRES_SECURE_CHANNEL"/>
</filter-security-metadata-source>
</beans:property>
</beans:bean>
<beans:bean id="channelDecisionManager" class="org.springframework.security.web.access.channel.ChannelDecisionManagerImpl">
<beans:property name="channelProcessors">
<beans:list>
<beans:ref bean="secureChannelProcessor"/>
<beans:ref bean="insecureChannelProcessor"/>
</beans:list>
</beans:property>
</beans:bean>
<beans:bean id="secureChannelProcessor" class="org.springframework.security.web.access.channel.SecureChannelProcessor" />
<beans:bean id="insecureChannelProcessor" class="org.springframework.security.web.access.channel.InsecureChannelProcessor" />
<beans:bean id="SecurityContextPersistenceFilter" class="org.springframework.security.web.context.SecurityContextPersistenceFilter" />
<beans:bean id="authenticationFilter" class="web.security.auth.CustomUsernamePasswordAuthenticationFilter">
<beans:property name="authenticationManager" ref="authenticationManager"/>
<beans:property name="filterProcessesUrl" value="/j_spring_security_check"/>
<beans:property name="usernameParameter" value="username"/>
<beans:property name="passwordParameter" value="password"/>
</beans:bean>
<beans:bean id="anonymousAuthFilter" class="org.springframework.security.web.authentication.AnonymousAuthenticationFilter">
<beans:property name="key" value="foobar"/>
<beans:property name="userAttribute" value="anonymousUser,ROLE_ANONYMOUS"/>
</beans:bean>
<beans:bean id="anonymousAuthenticationProvider" class="org.springframework.security.authentication.AnonymousAuthenticationProvider">
<beans:property name="key" value="foobar"/>
</beans:bean>
<beans:bean id="filterSecurityInterceptor" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
<beans:property name="authenticationManager" ref="authenticationManager"/>
<beans:property name="accessDecisionManager" ref="accessDecisionManager"/>
<beans:property name="securityMetadataSource">
<filter-security-metadata-source>
<intercept-url pattern="/LoginPage" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<intercept-url pattern="/LoginExpiredPage" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<intercept-url pattern="/wicket/bookmarkable/web.sec.pages.LoginExpiredPage" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<intercept-url pattern="/css/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<intercept-url pattern="/images/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<intercept-url pattern="/*.png" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<intercept-url pattern="/*.ico" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<intercept-url pattern="/wicket/resource/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<intercept-url pattern="/**" access="IS_AUTHENTICATED_FULLY, IS_AUTHENTICATED_REMEMBERED"/>
</filter-security-metadata-source>
</beans:property>
</beans:bean>
<beans:bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
<beans:property name="decisionVoters">
<beans:list>
<beans:bean class="org.springframework.security.access.vote.RoleVoter">
<beans:property name="rolePrefix" value="ROLE_"/>
</beans:bean>
<beans:bean class="org.springframework.security.access.vote.AuthenticatedVoter"/>
</beans:list>
</beans:property>
</beans:bean>
<beans:bean id="logoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
<beans:constructor-arg value="/" />
<beans:constructor-arg>
<beans:list>
<beans:bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/>
</beans:list>
</beans:constructor-arg>
<beans:property name="filterProcessesUrl" value="/logout"/>
</beans:bean>
<beans:bean id="forceCookieUseFilter" class="web.security.ForceCookieUseFilter">
<beans:constructor-arg>
<beans:list>
<beans:bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/>
</beans:list>
</beans:constructor-arg>
</beans:bean>
<beans:bean id="exceptionTranslationFilter" class="org.springframework.security.web.access.ExceptionTranslationFilter">
<beans:property name="authenticationEntryPoint" ref="authenticationEntryPoint"/>
<beans:property name="accessDeniedHandler" ref="accessDeniedHandler"/>
</beans:bean>
<beans:bean id="authenticationEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<beans:property name="loginFormUrl" value="/LoginPage"/>
</beans:bean>
<beans:bean id="accessDeniedHandler" class="org.springframework.security.web.access.AccessDeniedHandlerImpl">
<beans:property name="errorPage" value="/accessDenied.htm"/>
</beans:bean>
<beans:bean id="loggerListener" class="org.springframework.security.authentication.event.LoggerListener"/>
AuthenticationFilter class as follows:
public class CustomUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "j_username";
public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "j_password";
public static final String SPRING_SECURITY_LAST_USERNAME_KEY = "SPRING_SECURITY_LAST_USERNAME";
private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY;
private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;
private boolean postOnly = true;
public CustomUsernamePasswordAuthenticationFilter() {
super("/j_spring_security_check");
}
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
String username = obtainUsername(request);
String password = obtainPassword(request);
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
if(this.getAuthenticationManager()==null){
logger.info("Authentication manager is null.");
} else {
logger.info("Authentication manager was "+this.getAuthenticationManager().getClass().getName());
}
return this.getAuthenticationManager().authenticate(authRequest);
}
protected String obtainPassword(HttpServletRequest request) {
return request.getParameter(passwordParameter);
}
protected String obtainUsername(HttpServletRequest request) {
return request.getParameter(usernameParameter);
}
protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {
authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
}
public void setUsernameParameter(String usernameParameter) {
this.usernameParameter = usernameParameter;
}
public void setPasswordParameter(String passwordParameter) {
this.passwordParameter = passwordParameter;
}
public void setPostOnly(boolean postOnly) {
this.postOnly = postOnly;
}
public final String getUsernameParameter() {
return usernameParameter;
}
public final String getPasswordParameter() {
return passwordParameter;
}
}
UserDetails class as follows:
public class DAOUserDetailsService implements UserDetailsService {
private DataSource dataSource;
public void setDataSource(DAODataSource dataSource) {
this.dataSource = dataSource;
}
public DAOUserDetailsService () { }
public DAOUserDetailsService (DAODataSource dataSource) {
this.dataSource = dataSource;
}
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
DataSource ds = dataSource;
PreparedStatement userStatement = null;
try {
Connection con = ds.getConnection();
String userQuery = "SELECT USER_ID, USER_PASSWORD, USER_ENABLED FROM USER WHERE USER_ID = ?";
userStatement = con.prepareStatement(userQuery);
userStatement.setString(0, username);
ResultSet userResults = userStatement.executeQuery();
if (userResults.next()) {
final SimpleGrantedAuthority supervisorAuthority = new SimpleGrantedAuthority(
"supervisor");
final SimpleGrantedAuthority userAuthority = new SimpleGrantedAuthority(
"user");
Collection<GrantedAuthority> authorityList = new ArrayList<GrantedAuthority>();
authorityList.add(supervisorAuthority);
authorityList.add(userAuthority);
return new User(userResults.getString(0), userResults.getString(1), authorityList);
}
throw new UsernameNotFoundException(username);
} catch (SQLException e) {
throw new UsernameNotFoundException(e.toString());
}
finally {
if (userStatement != null) {
try {
userStatement.close();
} catch (SQLException e) {
throw new UsernameNotFoundException(e.toString());
}
}
}
}
}
Kindly provide some idea on the issue.
Thanks in advance.
You can create your implementation of LoggerListener for investigate more the causes.
public class LoggerListener implements ApplicationListener<AbstractAuthorizationEvent> {
private static final Log logger = LogFactory.getLog(LoggerListener.class);
public void onApplicationEvent(AbstractAuthorizationEvent event) {
//investigation code
}
}
I had a very similar problem and the cause was one ClassCastException in other part of code, one controller.
In your class DAOUserDetailsService:
...
return new User(userResults.getString(0), userResults.getString(1), new ArrayList<GrantedAuthority>());
...
you return UserDeatils with empty authorities. So your user is loged in but he has no roles (not authorised).
You have to add ROLE_ prefix to role while creating your GrantedAuthority. So you code should look like:
// For xxx
final SimpleGrantedAuthority supervisorAuthority = new SimpleGrantedAuthority(
"ROLE_xxx");
Alternative: You can clear default prefix in RoleVoter but IMO this is not a good choice because ROLE_ prefix actually helps RoleVoter to understand what remaning string is.
<bean id="roleVoter" class="org.springframework.security.vote.RoleVoter">
<property name="rolePrefix" value=""></property>
</bean>

ExchangeTimedOutException: The OUT message was not received

I have a problem the InOnly exchange pattern what I use with aciveMq.
I wrote a module what run in ServiceMix. It works correctly except that it send every message to dead letter queue (ActiveMQ.DLQ). If I check the message then dlqDeliveryFailureCause contains this message: java.lang.Throwable: Message Expired.
I checked the JMSExpiration = 0.
The route:
from("direct:" + reqOutQueue).id("reqInEnritch")
.log("Start dispatch")
.setExchangePattern(ExchangePattern.InOnly)
.recipientList().method(EsbDynamicRouter.class, "systemRoute").parallelProcessing();
The function, what gives back the endpoint list:
#RecipientList
public String[] systemRoute(#Body Object body) throws Exception
{
String[] result = null;
List<DispConfView> targetList;
int cikl = 0;
SystemQueueHelper systemInfo;
MessageHeaderHelper msgHeadHelp = new MessageHeaderHelper(body);
// The object contains the affected elements
targetList = dispHelp.getDispConfByMsgType(msgHeadHelp.getMsgType());
result = new String[targetList.size()];
for (DispConfView element : targetList)
{
// It builds the target andpoints
systemInfo = new SystemQueueHelper(element.getSystemCode(), null, msgHeadHelp.getDirection());
result[cikl] = systemInfo.getQueuName();
cikl++;
}
return result;
}
The list contains these values:
activemq:queue:ERP.req.in?exchangePattern=InOnly
activemq:queue:WF.req.in?exchangePattern=InOnly
As you see, I try to set the correct pattern, but every messages go to dead letter queue.
Please help, what I have to set up!
Thank you!
The solution:
It is settable in context file:
<!-- JMS configuration -->
<bean id="pooledJmsConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory" init-method="start" destroy-method="stop">
<property name="maxConnections" value="1" />
<property name="connectionFactory" ref="jmsConnectionFactory" />
</bean>
<bean id="jmsConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="failover:(tcp://localhost:61616)" />
<property name="redeliveryPolicy">
<bean class="org.apache.activemq.RedeliveryPolicy">
<property name="maximumRedeliveries" value="5"/>
</bean>
</property>
</bean>
<bean id="jmsConfig" class="org.apache.camel.component.jms.JmsConfiguration">
<property name="connectionFactory" ref="pooledJmsConnectionFactory"/>
<property name="cacheLevelName" value="CACHE_CONSUMER" />
<property name="disableReplyTo" value="true" />
</bean>
The "jmsConfig bean ""diasbleReplayTo" property solve the problem.

Spring JDBCTemplate + Transaction Manager memory leak

i have really strange problem. My Spring web-application seems to have a memory-leak.
i'm using Spring 3.2
my Tomcat config:
JAVA_OPTS="-Dfile.encoding=UTF-8 -server -Xms512m -Xmx1024m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=128m
-XX:MaxPermSize=256m -XX:+DisableExplicitGC -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/dumps"
my dataSource declaration:
<!-- declare transactionManager -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<beans:bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<beans:property name="dataSource" ref="dataSource"></beans:property>
</beans:bean>
<beans:bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://localhost/test" />
<beans:property name="username" value="User" />
<beans:property name="password" value="password" />
<beans:property name="initialSize" value="5" />
<beans:property name="maxActive" value="55" />
<beans:property name="maxIdle" value="20" />
<beans:property name="minIdle" value="10" />
<beans:property name="maxWait" value="10000" />
<beans:property name="minEvictableIdleTimeMillis" value="55000" />
<beans:property name="timeBetweenEvictionRunsMillis" value="34000" />
<beans:property name="validationQuery" value="SELECT 1" />
<beans:property name="testOnBorrow" value="true" />
<beans:property name="removeAbandoned" value="true"/>
<beans:property name="removeAbandonedTimeout" value="60"/>
<beans:property name="logAbandoned" value="true"/>
</beans:bean>
<beans:bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<beans:property name="dataSource" ref="dataSource"></beans:property>
</beans:bean>
i'm injecting the jdbcTemplate into dao. I'm using Transaction-Annotations as well.
this is what i got from Memory Analizer (MAT):
The class "com.mysql.jdbc.NonRegisteringDriver", loaded by "org.apache.catalina.loader.StandardClassLoader # 0x515c1390", occupies 758.845.296 (72,57%) bytes. The memory is accumulated in one instance of "java.util.concurrent.ConcurrentHashMap$Segment[]" loaded by "system class loader".
in the detail-view i saw this:
com.mysql.jdbc.NonRegisteringDriver$ConnectionPhantomReference
First 10 of 14.360 objects. Number of Objects: 14.360. Used Heap Size: 459.520. Retained Heap Size: 732.819.568
i found this: bug report, but i'm using 5.1.29, so i think i shouldn't have this problem. But maybe the problem is somewhere in apache dbcp. Can someone help me? Is my configuration ok? Is there a problem in JDBCTemplate + TransactionManager?
here is 1 of my services. I use Transactions in the services, is it ok?
#Service
public class ModerationServiceImpl implements ModerationService {
#Autowired
private EventService eventService;
#Autowired
private ContentManagementService cmService;
#Autowired
private IconDao iconDao;
#Transactional(rollbackFor = Exception.class)
#Override
public void activateUserIcon(long userIconId, long userId, String comment)
throws IconNotFoundException, NoPermissionException, IOException,
IconNotAssignedToUserException, WrongIconStateException {
if(!iconDao.isAssignedToUser(userIconId))
throw new IconNotAssignedToUserException("icon: " + userIconId + " is not assigned to a user and can't be activated!");
cmService.activateUserIcon(userIconId);
eventService.writeUserIconEvent(userIconId, userId, new Date().getTime(), Enum_ServerEvent.verified, Enum_UserIconState.approved, comment);
}
and here is 1 of my DAO's:
#Repository
public class IconDaoImpl extends DB_Contract implements IconDao{
#Autowired
private JdbcTemplate jdbcTemplate;
#Override
public IconData getUserIconById(long iconId) throws IconNotFoundException {
String sql = SELECT + UserIcon.CN_ServerID + NEXT +
UserIcon.CN_State + NEXT +
UserIcon.CN_Ref +
FROM + UserIcon.TABLE_NAME + WHERE + UserIcon.CN_ServerID + " = ?";
try{
return jdbcTemplate.queryForObject(sql, new UserIconRowMapper(), iconId);
}catch (EmptyResultDataAccessException e){
throw new IconNotFoundException("couldn't find icon for id: " + iconId);
}
}

NullPointerException returned by Query object in DAO using Spring 3 MVC

I'm new in spring, I have 3 projects in my eclipse. One JPA.jar, client.jar and a Web.war.
I am going to deploy these on Tomcat 6 so all the dependencies are mainly on the Web.war.
My problem is that I can persist data in the oracle data base but I cannot get(select) the data from the Query object in the DAO :(.
here is my servlet-context
</beans:bean>
<!-- Oracle Driver -->
<beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<beans:property name="url" value="jdbc:oracle:thin:#//sapodev.sapo.co.za:1523/P3P"/>
<beans:property name="username" value="pensions"/>
<beans:property name="password" value="pensions"/>
</beans:bean>
<!-- JPA EntityManagerFactory -->
<beans:bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<beans:property name="persistenceUnitName" value="frameworkPU"/>
<beans:property name="dataSource" ref="dataSource"/>
<beans:property name="jpaVendorAdapter">
<beans:bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<beans:property name="showSql" value="true"/>
<!-- <property name="generateDdl" value="false"/> -->
<beans:property name="databasePlatform" value="org.hibernate.dialect.Oracle10gDialect"/>
</beans:bean>
</beans:property>
</beans:bean>
<beans:bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<beans:property name="entityManagerFactory" ref="entityManagerFactory" />
<beans:property name="dataSource" ref="dataSource"/>
</beans:bean>
<beans:bean id="persistenceAnnotation" class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<beans:bean id="contactService" class="za.co.sapo.service.ContactServiceImpl"/>
<context:component-scan base-package="za.co.sapo.controller" />
<context:annotation-config />
<context:component-scan base-package="za.co.sapo.dao"/>
</beans:beans>
Here is the DAO class
public List<DevUserTab> findUsers() {
List<DevUserTab> list = null;
log.info("DD");
try{
TypedQuery<DevUserTab> query = this.entityManagerFactory.createNamedQuery("SELECT d from DevUserTab d", DevUserTab.class);
list= query.getResultList();
} catch(Exception e){
log.info(" EE");
e.printStackTrace();
}
return list;
}
Here is the service class
#Autowired
public ContactDAO contactDAO;
public List findUsers() {
// TODO Auto-generated method stub
ContactDAO contact = new ContactDAO();
List users = contact.findUsers();
return users;
}
My controller
#RequestMapping(value = "/table")
public ModelAndView getContacts(Locale locale, Model model) {
logger.info("Getting the Contacts for us "+ locale.toString());
ModelAndView mv = new ModelAndView("/table");
try{
List<Contact> objects = ServiceLayerContext.getContext().findContacts();
mv.addObject("objects", objects );
} catch(Exception e){
e.printStackTrace();
}
return mv;
}
The createNamedQuery expects you to be referencing a query you configured in your persistence.xml
When specifying the JPQL directly as you are doing, you need to use the createQuery method instead.

Categories