i am importing data from file ,its get the data suceessfully .my flow to call the ruleimplservice from the main class ,where i get the value from file.bt when i call jdbclogdatarepository to save the data ,it shows the following error.the data isreached successfully in impl bt not in jdbc class.
ERRORS
java.lang.NullPointerException
at com.heavymeddlellc.heavymeddle.metrics.service.RuleServiceImpl.insertlogcontent(RuleServiceImpl.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:133)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:121)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at $Proxy6.insertlogcontent(Unknown Source)
at com.heavymeddlellc.heavymeddle.utils.readingdata.main(readingdata.java:97)
Java code is as below:
package com.heavymeddlellc.heavymeddle.utils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.test.context.ContextConfiguration;
import com.heavymeddlellc.heavymeddle.metrics.domain.LogData;
import com.heavymeddlellc.heavymeddle.metrics.repository.jdbc.JdbcLogDataRepository;
import com.heavymeddlellc.heavymeddle.metrics.service.RuleService;
import com.heavymeddlellc.heavymeddle.metrics.service.RuleServiceImpl;
#ContextConfiguration(locations = "/hm-metrics-context.xml")
public class readingdata
{
public static void main(String args[])
{
//RuleService ruleService=new RuleService();
List<LogData> dataList = new ArrayList<LogData>();
Resource r= new ClassPathResource("/hm-metrics-context.xml");
BeanFactory factory=new XmlBeanFactory((org.springframework.core.io.Resource) r);
// LogData logData=(LogData) factory.getBean("ruleService");
RuleService ruleService=(RuleService) factory.getBean("ruleService");
// JdbcLogDataRepository dataRepository= (JdbcLogDataRepository) factory.getBean("ruleService");
LogData logData=new LogData();
// public List<LogData> inserttable(LogData logData2)
//{
try
{
BufferedReader reader=new BufferedReader(new FileReader("E://tracker.log"));
String lines;
String[] contentid;
while((lines=reader.readLine())!=null)
{
String[] datas=lines.split(Pattern.quote("|"));
logData.setUserId(datas[0]);
logData.setRequestDate(datas[1]);
System.out.println(datas[1]);
logData.setSessionId(datas[2]);
System.out.println(datas[2]);
// System.out.println(datas[2]);
contentid=datas[2].split("html/meta/content/");
// System.out.println(contentid[0]);
// System.out.println(datas[2]);
logData.setContentId(contentid[0]);
System.out.println(contentid[0]);
logData.setUserAgent(datas[6]);
System.out.println(datas[6]);
logData.setUserType(datas[4]);
logData.setReferer(datas[5]);
logData.setRedirectUrl(datas[7]);
String sessionId=logData.getSessionId();
System.out.println(logData.getSessionId());
String contentId=logData.getContentId();
System.out.println(contentId);
String userAgent=logData.getUserAgent();
System.out.println(userAgent);
String requestDate=logData.getRequestDate();
String userId=logData.getUserId();
String userType=logData.getUserType();
String referer=logData.getReferer();
String redirectUrl=logData.getRedirectUrl();
//Saystem.out.println(datas[4]);
// dataList.add(logData);
// System.out.print(logData.getSessionId());
//ruleService.insertlogcontent(logData.setSessionId(datas[2]),logData.setContentId(contentid[0]), logData.setRequestDate(datas[1]), logData.setUserId(datas[0]),logData.setUserType(datas[4]),logData.setReferer(datas[5]),logData.setRedirectUrl(datas[7]));
ruleService.insertlogcontent(sessionId, contentId, userAgent, requestDate, userId, userType, referer, redirectUrl);
}
}
catch(Exception e)
{
e.printStackTrace();
}
// return dataList;
// }
}}
/**
*
*/
ruleServiceimpls
package com.heavymeddlellc.heavymeddle.metrics.service;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.*;
import org.springframework.transaction.annotation.Transactional;
import com.heavymeddlellc.heavymeddle.metrics.domain.LogData;
import com.heavymeddlellc.heavymeddle.metrics.repository.LogDataRepository;
#Repository
public class RuleServiceImpl implements RuleService {
private static final Logger log = Logger.getLogger(RuleServiceImpl.class);
#Autowired
private LogDataRepository logDataRepository;
#Override
public void insertlogcontent(String sessionId, String contentId, String userAgent,
String requestDate, String userId,
String userType, String referer,
String redirectUrl) {
//logDataRepository.insertlogcontent(sessionId, contentId,userAgent, requestDate, userId, userType, referer, redirectUrl);
System.out.println(sessionId);
System.out.println(requestDate);
System.out.println(userType);
logDataRepository.insertlogcontent(sessionId, contentId, userAgent,
requestDate, userId, userType, referer, redirectUrl);
}
}
/**
*
*/
package com.heavymeddlellc.heavymeddle.metrics.repository.jdbc;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.heavymeddlellc.heavymeddle.metrics.MetricsException;
import com.heavymeddlellc.heavymeddle.metrics.domain.LogData;
import com.heavymeddlellc.heavymeddle.metrics.repository.LogDataRepository;
import com.heavymeddlellc.heavymeddle.utils.readingdata;
#Transactional
#Repository("logDataRepository")
public class JdbcLogDataRepository implements LogDataRepository {
#Autowired
private JdbcTemplate jdbcTemplate;
#Autowired
private final static String LOG_REDIRECT_VIEW_TABLENAME = "hm_log_redirect_view";
private final static String LOG_REDIRECT_URL_LOOKUP_TABLENAME = "hm_log_redirect_url_lookup";
public final static String LOG_ALL_CONTENTS_VIEW_TABLENAME = "hm_log_all_contents_view";
private final static String LOG_ALL_SN_CONTENTS_VIEW = "hm_log_sn_contents_view";
#Override
public void insertlogcontent(String sessionId, String contentId, String userAgent,
String requestDate, String userId,
String userType, String referer,
String redirectUrl) {
int values=0;
System.out.println(userType);
StringBuffer sqlQuery = new StringBuffer(
"insert into "+JdbcLogDataRepository.LOG_ALL_CONTENTS_VIEW_TABLENAME
+"(uri,content_id,content_owner_id,request_date,user_id,user_type,referer,redirect_url) values (?,?,?,?,?,?,?,?)");
values=jdbcTemplate.update(sqlQuery.toString(),sessionId,contentId,userAgent,requestDate,userId,userType,referer,redirectUrl);
}
}
Spring xml
<!-- Activates scanning of #Autowired -->
<context:annotation-config />
<context:component-scan base-package="com.heavymeddlellc.heavymeddle.metrics" />
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>
<!-- enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- (this dependency is defined somewhere else) -->
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="metricsProcessor" class="com.heavymeddlellc.heavymeddle.metrics.processor.MetricsProcessorImpl">
<constructor-arg ref="taskExecutor" />
<property name="ruleService" ref="ruleService"/>
</bean>
<bean id="ruleService" scope="prototype" class="com.heavymeddlellc.heavymeddle.metrics.service.RuleServiceImpl">
<!-- This instructs the container to proxy the current bean-->
<aop:scoped-proxy proxy-target-class="false"/>
</bean>
<!-- <bean id="logDataRepository" scope="prototype" class="com.heavymeddlellc.heavymeddle.metrics.repository.JdbcLogDataRepository">
This instructs the container to proxy the current bean
<aop:scoped-proxy proxy-target-class="false"/>
<property name="ruleService" ref="ruleService"></property>
</bean>
-->
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="50" />
<property name="maxPoolSize" value="100" />
<property name="queueCapacity" value="150" />
</bean>
</beans>
Replace the following two lines:
Resource r = new ClassPathResource("/hm-metrics-context.xml");
BeanFactory factory = new XmlBeanFactory((org.springframework.core.io.Resource) r);
with this:
ApplicationContext factory = new ClassPathXmlApplicationContext("/hm-metrics-context.xml");
Read this section of the reference documentation about the differences between a BeanFactory and an ApplicationContext.
Your auto-wiring doesn't work because <context:annotation-config/> is processed as a BeanPostProcessor and the BeanFactory is missing this feature of using BeanPostProcessor extension points, as per the link from the docs above.
Related
I am using Hibernate4 in my application for multitenancy implementation while building application war i got following error in my catalina of tomcat.
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field:
protected org.hibernate.SessionFactory com.boxco.blip.dao.BaseDao.sessionFactory;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext-persistence.xml]:
Invocation of init method failed; nested exception is java.lang.NullPointerException
Here is my application -persistance.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="...">
<context:annotation-config />
<tx:annotation-driven />
<context:component-scan base-package="com.boxco.blip">
</context:component-scan>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>jdbc/blip</value>
</property>
<property name="resourceRef">
<value>true</value>
</property>
</bean>
<!-- Hibernate Session Factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>com.boxco.blip.model.Address</value>
</list>
</property>
<property name="hibernateProperties">
<map>
<entry key="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<entry key="hibernate.hbm2ddl.auto" value="validate" />
<entry key="hibernate.show_sql" value="true" />
<entry key="hibernate.connection.autocommit" value="false" />
<entry key="hibernate.jdbc.batch_size" value="0" />
<entry key="hibernate.connection.release_mode" value="after_transaction" />
<entry key="hibernate.multiTenancy" value="SCHEMA" />
<entry key="hibernate.tenant_identifier_resolver" value-ref="multiTenantIdentifierResolver1" />
<entry key="hibernate.multi_tenant_connection_provider" value-ref="multiTenantConnectionProvider1" />
</map>
</property>
</bean>
<bean id="multiTenantConnectionProvider1" class="com.boxco.blip.web.util.SchemaMultiTenantConnectionProviderBlip">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="multiTenantIdentifierResolver1" class="com.boxco.blip.web.util.SchemaCurrentTenantIdentifierResolverBlip" />
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
<property name="dataSource" ref="dataSource"/>
</bean>
MY AddressDao.java File
package com.boxco.blip.dao;
import com.boxco.blip.model.Address;
public interface AddressDao {
public Address getAddressByAddressId(int addressId);
}
My AddressDaoImpl.java file
package com.boxco.blip.dao;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.boxco.blip.model.Address;
#Component
#Repository(value = "addressDao")
public class AddressDaoImpl extends BaseDao implements AddressDao {
private static final Logger logger = Logger.getLogger(AddressDaoImpl.class);
#Override
public Address getAddressByAddressId(int addressId) {
logger.info("Entering getAddressByAddressId()........");
Address address = null;
Criteria criteria = getSession().createCriteria(Address.class);
criteria.add(Restrictions.eq("addressId", addressId));
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
address = (Address)criteria.uniqueResult();
logger.info("Exiting getAddressByAddressId()..........");
return address;
}
}
My Base Dao file where i init sessionFactory object:
package com.boxco.blip.dao;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.mysql.jdbc.Connection;
public abstract class BaseDao
{
#Autowired
#Qualifier("sessionFactory")
protected SessionFactory sessionFactory;
protected void init(SessionFactory factory) {
try {
setSessionFactory(factory);
} catch (Exception e) {
e.printStackTrace();
}
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getSession() throws HibernateException {
// return sessionFactory.getCurrentSession();
return sessionFactory.withOptions().tenantIdentifier("BLIP1314ERP")
.openSession();
}
//some more methods
}
My Dispatcher-servlet.xml file where is added
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="...">
<mvc:annotation-driven/>
<context:component-scan base-package="com.boxco">
<!-- <context:exclude-filter type="regex" expression="com.boxco.blip.dao.*" /> -->
</context:component-scan>
<bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basenames" value="views"/>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<value>messages,error_codes</value>
</property>
</bean>
<bean id="validatorFactory"
class="org.springmodules.validation.commons.DefaultValidatorFactory">
<property name="validationConfigLocations">
<list>
<value>/WEB-INF/validator-rules.xml</value>
<value>/WEB-INF/validator.xml</value>
<value>/WEB-INF/validatorFas.xml</value>
<value>/WEB-INF/validatorFas-rules.xml</value>
</list>
</property>
</bean>
<bean id="validator" class="org.springmodules.validation.commons.DefaultBeanValidator">
<property name="validatorFactory" ref="validatorFactory"/>
</bean>
Error is in my SessionFactory initialization but why it is not getting init is my problem..?
(I am handling this error first time)..
Any suggestion appreciated.
It shouldn't be your solution, in any case the #component annotation over #repository is useless. Either you insert #repository (better for exception translation) or #component.
I resolved it by replacing my JAR files from 4.3.4 to 4.1.7 (downgraded my jar) hibernate version ,I dont know why its not working with latest versions of Hibernate
Here's the error I'm receiving.
Caused by: java.lang.IllegalStateException: Cannot convert value of type [code.ProductFieldSetMapper] to required type [org.springframework.batch.item.file.mapping.FieldSetMapper] for property 'FieldSetMapper': no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:264)
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:450)
... 23 more
Here's my context file (FileReaderConfig.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:batch="http://www.springframework.org/schema/batch"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch.xsd">
<bean id="reader" class="org.springframework.batch.item.file.FlatFileItemReader">
<property name="resource" value="file:./output.txt" />
<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="PRODUCT_ID,NAME,DESCRIPTION,PRICE" />
</bean>
</property>
<property name="fieldSetMapper">
<bean class="code.ProductFieldSetMapper" />
</property>
</bean>
</property>
</bean>
<job id="importProducts" xmlns="http://www.springframework.org/schema/batch">
<step id="readWriteProducts">
<tasklet>
<chunk reader="reader" writer="writer" commit-interval="100" />
</tasklet>
</step>
</job>
Here's the interface (FieldSetMapper.java)
package code;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.validation.BindException;
public interface FieldSetMapper<T> {
T mapFieldSet(FieldSet fieldSet) throws BindException;
}
Here's ProductFieldSetMapper.java
package code;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.validation.BindException;
public class ProductFieldSetMapper implements FieldSetMapper<Product> {
public Product mapFieldSet(FieldSet fieldSet) throws BindException {
// TODO Auto-generated method stub
Product product = new Product();
product.setId(fieldSet.readString("PRODUCT_ID"));
product.setName(fieldSet.readString("NAME"));
product.setDescription(fieldSet.readString("DESCRIPTION"));
product.setPrice(fieldSet.readBigDecimal("PRICE"));
return product;
}
}
And here's the class that I'm running (Runner.java)
package code;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.validation.BindException;
public class Runner {
public static void main(String[] args) throws BeansException, BindException {
// TODO Auto-generated method stub
Product product;
ApplicationContext context =
new ClassPathXmlApplicationContext("FileReaderConfig.xml");
ProductFieldSetMapper obj = (ProductFieldSetMapper) context.getBean("FieldSetMapper");
product = (Product) obj.mapFieldSet((FieldSet)context.getBean("lineTokenizer"));
System.out.println(product.getDescription() + ""+product.getId()+""+product.getName());
}
}
I don't see where (or why for that matter)my code is attempting to convert a ProductFieldSetMapper into a FieldSetMapper (which is just an interface, I understand that won't work).
BTW, Product.java is a POJO with variables and their respective setters and getters.
The error was the result of me using my own interface rather than the one provided by Spring. I deleted my interface class and had ProductFieldSetMapper implement org.springframework.batch.item.file.mapping.FieldSetMapper after importing it. That solved the issue.
ProductFieldSetMapper obj =
(ProductFieldSetMapper) context.getBean("FieldSetMapper");
Should be
ProductFieldSetMapper obj =
(ProductFieldSetMapper) context.getBean("fieldSetMapper");
See your bean declaration.
<property name="fieldSetMapper">
<bean class="code.ProductFieldSetMapper" />
</property>
Here is code with some correction:
Runner.java (use DelimitedLineTokenizer class to tokenize a comma separated string into FieldSet that is further used to map it with an object (Product) via ProductFieldSetMapper class)
ApplicationContext context = new ClassPathXmlApplicationContext(
"FileReaderConfig.xml");
ProductFieldSetMapper obj = (ProductFieldSetMapper) context.getBean("fieldSetMapper");
DelimitedLineTokenizer tokenizer = (DelimitedLineTokenizer) context
.getBean("lineTokenizer");
FieldSet fieldSet = tokenizer.tokenize("1,Pepsi,Cold drinks,30");
Product product = (Product) obj.mapFieldSet(fieldSet);
System.out.println(product.getDescription() + "-" + product.getId() + "-"
+ product.getName());
Config xml file: (No need to declare any beans or jobs other than two defined below because you are not using it anywhere in you Main class)
<bean id="lineTokenizer"
class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
<property name="names" value="PRODUCT_ID,NAME,DESCRIPTION,PRICE" />
</bean>
<bean id="fieldSetMapper" class="com.spring.batch.domain.ProductFieldSetMapper" />
ProductFieldSetMapper.java: (There is no need to define your custom FieldSetMapper)
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.validation.BindException;
public class ProductFieldSetMapper implements org.springframework.batch.item.file.mapping.FieldSetMapper<Product> {
public Product mapFieldSet(FieldSet fieldSet) throws BindException {
Product product = new Product();
product.setId(fieldSet.readString("PRODUCT_ID"));
product.setName(fieldSet.readString("NAME"));
product.setDescription(fieldSet.readString("DESCRIPTION"));
product.setPrice(fieldSet.readBigDecimal("PRICE"));
return product;
}
}
For a detailed sample please read it HERE with extra functionality using spring batch jobs.
I am using Spring AOP for logging in my application. Here is the applicationContext.xml file
<mvc:annotation-driven />
<context:component-scan base-package="com.template" />
<context:annotation-config />
<jpa:repositories base-package="com.template.repository"/>
<tx:annotation-driven />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/template?autoReconnect=true"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"/>
<property name="persistenceUnitName" value="template"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
and my aopLogging.xml is
<bean id="aopLogging" class="com.template.log.AopLoggingAspect" />
<aop:aspectj-autoproxy proxy-target-class="false"/>
and my Aspect class is
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
#Aspect
#Component
public class AopLoggingAspect {
private static final Logger logger = Logger.getLogger(AopLoggingAspect.class);
#Around(value="#annotation(com.template.log.Loggable)")
public Object logAround(final ProceedingJoinPoint joinPoint) throws Throwable{
Object retVal = null;
try {
StringBuffer startMessageStringBuffer = new StringBuffer();
startMessageStringBuffer.append("Start method execution :: ");
startMessageStringBuffer.append(joinPoint.getSignature().getName());
startMessageStringBuffer.append("(");
Object[] args = joinPoint.getArgs();
for (int i = 0; i < args.length; i++) {
startMessageStringBuffer.append(args[i]).append(",");
}
if (args.length > 0) {
startMessageStringBuffer.deleteCharAt(startMessageStringBuffer.length() - 1);
}
startMessageStringBuffer.append(")");
logger.info(startMessageStringBuffer.toString());
StopWatch stopWatch = new StopWatch();
stopWatch.start();
retVal = joinPoint.proceed();
stopWatch.stop();
StringBuffer endMessageStringBuffer = new StringBuffer();
endMessageStringBuffer.append("Finish method ");
endMessageStringBuffer.append(joinPoint.getSignature().getName());
endMessageStringBuffer.append("(..); execution time: ");
endMessageStringBuffer.append(stopWatch.getTotalTimeMillis());
endMessageStringBuffer.append(" ms;");
logger.info(endMessageStringBuffer.toString());
} catch(Exception ex) {
StringBuffer errorMessageStringBuffer = new StringBuffer();
logger.error(errorMessageStringBuffer.toString(), ex);
throw ex;
}
return retVal;
}
}
and my Custom annotation is
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.METHOD, ElementType.TYPE})
public #interface Loggable {
}
and my Service class is
public class UserService {
#Transactional(readOnly=true)
#Loggable
public User getUserByUserId(Long userId){
return userRepository.findOne(userId);
}
}
The problem is that the logs are not getting printed. Please help me. Thanks in advance. Please do let me know if any other info is needed.
It seems to me you have forgot to import in your applicationContext.xml file the aopLogging.xml file. Try to add this to your applicationContext.xml file:
<!-- Import your AspectJ config -->
<import resource="classpath:aopLogging.xml" />
Create a Annotation
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.RUNTIME)
public #interface LogExecutionTime { }
Then an Aspect
#Aspect
#Component
public class LoggingAspect {
Then a method in the Aspect
#Around("#annotation(LogExecutionTime)")
public Object
logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
Object proceed = joinPoint.proceed();
long executionTime = System.currentTimeMillis() - start;
LOGGER.info(joinPoint.getSignature() + " executed in " + executionTime + "ms");
return proceed; }
Then use the Annotation Anywhere
#PostMapping(value="/signup")
#LogExecutionTime
public #ResponseBody
ResponseObject register(User user){
}
Try this..
#Around(value="#annotation(Loggable)")
public Object logAround(final ProceedingJoinPoint joinPoint) throws Throwable{
All. Attached herewith all the files. If I give the same name for both bean property name and reference, it returns the object. But it returns null, in case both are different. Please help. Thank you so much.
The AuthenticateAction.java file has got the detailed comments inside it.....
below are my files list:
WIRAdminBaseAction.java ---> my base action
AuthenticateAction.java ---> my java file that calls the bean here
applicationContext_MNC.xml
The below way of calling works...... This is not encouraged, as we
should not use applicationContext always
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletRequest().getSession().getServletConte xt());
ICacheDelegate cacheAction = (ICacheDelegate)applicationContext.getBean("BMOCacheDelegate");
The below way of calling does NOT work .... returns null value....
Please help... I assume that, since I have extended the
WIRAdminBaseAction, i should be able to call the getCacheDelegate
directly and it should return my cacheDelegate object ... Again,
Please note.....if I change my applicationContext_MNC.xml as below,
the below way of calling works fine. But, i don't want to change my
applicationContext_MNC.xml as below, due to some necessity.
<bean id="BMOWIRAdminBaseAction" class="com.symcor.wiradmin.web.action.WIRAdminBase Action">
<property name="cacheDelegate">
<ref bean="cacheDelegate" />
</property>
</bean>
<bean id="cacheDelegate" class="com.symcor.wiradmin.delegate.CacheDelegate" >
<property name="statusDBDAO"><ref bean="BMOStatusDBDAO" /></property>
</bean>
Is it that the name and bean should have the same value.... ??? No
Need to be.....Am i right ? Please advise.
getCacheDelegate().getActorAction(1); // this way of calling doesn't work and returns null value. please help.
MY CODE Follows below.
AuthenticateAction.java
package com.symcor.wiradmin.web.action;
import java.net.UnknownHostException;
import java.sql.SQLException;
import org.bouncycastle.crypto.CryptoException;
import org.springframework.context.ApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.web.context.support.WebApplica tionContextUtils;
import com.symcor.wiradmin.delegate.ICacheDelegate;
public class AuthenticateAction extends WIRAdminBaseAction {
private static final long serialVersionUID = 1L;
public String authenticate() throws UnknownHostException, CryptoException,
DataAccessException, SQLException{
/** This way of calling works...... This is not encouraged, as we should not use applicationContext always **/
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContex t(getServletRequest().getSession().getServletConte xt());
ICacheDelegate cacheAction = (ICacheDelegate) applicationContext.getBean("BMOCacheDelegate");
/** The below way of calling does NOT work .... returns null value.... Please help...
* I assume that, since I have extended the WIRAdminBaseAction, i should be able to call the getCacheDelegate directly
* and it should return my cacheDelegate object ...
* Again, Please note.....if I change my applicationContext_MNC.xml as below, the below way of calling works fine...
* but, i don't want to change my applicationContext_MNC.xml as below, due to some necessity.
<bean id="BMOWIRAdminBaseAction" class="com.symcor.wiradmin.web.action.WIRAdminBase Action">
<property name="cacheDelegate">
<ref bean="cacheDelegate" />
</property>
</bean>
<bean id="cacheDelegate" class="com.symcor.wiradmin.delegate.CacheDelegate" >
<property name="statusDBDAO"><ref bean="BMOStatusDBDAO" /></property>
</bean>
... is it that the name and bean should have the same value.... ??? No Need to be.....Am i right ? Please advise.
*
* **/
getCacheDelegate().getActorAction(1); // this way of calling doesn't work and returns null value. please help.
return "success";
}
}
WIRAdminBaseAction.java
package com.symcor.wiradmin.web.action;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ParameterAware;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.config.entities.Parameteri zable;
import com.symcor.wiradmin.delegate.ICacheDelegate;
public class WIRAdminBaseAction extends ActionSupport implements Preparable, ParameterAware, Parameterizable, SessionAware,RequestAware {
private HttpServletRequest request;
private static final long serialVersionUID = 1L;
private HttpServletResponse response;
private ICacheDelegate cacheDelegate;
private Map session;
private Map<String, String> params;
private Map parameters;
public void prepare() throws Exception {
}
public String execute() throws Exception {
return SUCCESS;
}
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletRequest getServletRequest() {
return this.request;
}
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
public HttpServletResponse getServletResponse() {
return this.response;
}
public ICacheDelegate getCacheDelegate() {
return cacheDelegate;
}
public void setCacheDelegate(ICacheDelegate cacheDelegate) {
this.cacheDelegate = cacheDelegate;
}
public void addParam(final String key, final String value) {
this.params.put(key, value);
}
public Map getParams() {
return params;
}
public void setParams(final Map<String, String> params) {
this.params = params;
}
public Map getSession() {
return this.session;
}
public void setSession(final Map session) {
this.session = session;
}
public void setParameters(final Map param) {
this.parameters = param;
}
}
applicationContext_MNC.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- database configuration from property file -->
<bean id="BMOAdminDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close" lazy-init="default" autowire="default" dependency-check="default">
<property name="driverClass" value="${jdbc.driver}" ></property>
<property name="jdbcUrl" value="${admin.jdbc.url}" ></property>
<property name="user" value="${admin.jdbc.user}" ></property>
<property name="password" value="${admin.jdbc.password}" ></property>
<property name="initialPoolSize" value="3" ></property>
<property name="minPoolSize" value="3" ></property>
<property name="maxPoolSize" value="25" ></property>
<property name="acquireIncrement" value="1" ></property>
<property name="acquireRetryDelay" value="1000" ></property>
<property name="debugUnreturnedConnectionStackTraces" value="true" ></property>
<property name="maxIdleTime" value="300" ></property>
<property name="unreturnedConnectionTimeout" value="300000" ></property>
<property name="preferredTestQuery" value="SELECT COUNT(*) FROM LOCALE_CODE" ></property>
<property name="checkoutTimeout" value="300000" ></property>
<property name="idleConnectionTestPeriod" value="600000" ></property>
</bean>
<bean id="BMOWIRAdminBaseAction" class="com.symcor.wiradmin.web.action.WIRAdminBase Action">
<property name="cacheDelegate">
<ref bean="BMOCacheDelegate" />
</property>
</bean>
<bean id="BMOCacheDelegate" class="com.symcor.wiradmin.delegate.CacheDelegate" >
<property name="statusDBDAO"><ref bean="BMOStatusDBDAO" /></property>
</bean>
<bean id="BMOStatusDBDAO" class="com.symcor.wiradmin.dao.StatusDBDAO">
<property name="dataSource">
<ref bean="BMOAdminDataSource" />
</property>
</bean>
<!-- this bean is set to map the constants which needs to be configured as per
the environment to the java constants file -->
<bean id="envConstantsConfigbean" class="com.symcor.wiradmin.util.constants.Environm entConstantsSetter">
<property name="loginUrl" value="${login.url}"/>
<property name="logoutIR" value="${logout.from.image.retrieval}"/>
<property name="adminModuleUrl" value="${admin.url}"/>
<property name="adminUrlSym" value="${admin.url.sym}"/>
<property name="envProperty" value="${env.property}"/>
</bean>
</beans>
I am trying to create a spring rest service. My servlet.xml is like following:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<!-- Database Configuration -->
<import resource="classpath:DataSource.xml"/>
<import resource="classpath:Hibernate.xml"/>
<!-- Beans Declaration -->
<import resource="classpath:Employee.xml"/>
<context:component-scan base-package="com.nilenium.service.controller" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonConverter"/>
<ref bean="marshallingHttpMessageConverter"/>
</list>
</property>
</bean>
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="autodetectAnnotations" value="true"/>
<property name="annotatedClasses">
<list>
<value>com.nilenium.employee.model.Employee</value>
<value>com.nilenium.employee.model.EmployeeRecord</value>
</list>
</property>
</bean>
<bean id="marshallingHttpMessageConverter"
class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="xstreamMarshaller"/>
<property name="unmarshaller" ref="xstreamMarshaller"/>
</bean>
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="ignoreAcceptHeader" value="true" />
<property name="defaultContentType" value="application/json" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
<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"/>
<property name="aliases">
<props>
<prop key="employee">com.nilenium.employee.model.Employee</prop>
<prop key="employee">com.nilenium.employee.model.EmployeeRecord</prop>
</props>
</property>
</bean>
</constructor-arg>
</bean>
</list>
</property>
</bean>
</beans>
And my model class is like this:
package com.nilenium.employee.model;
import java.io.Serializable;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonRootName;
import com.thoughtworks.xstream.annotations.XStreamAlias;
#XStreamAlias("employee")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private int employeeId;
private String employeeName;
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public Employee(int employeeId, String employeeName)
{
this.employeeId = employeeId;
this.employeeName = employeeName;
}
public Employee() {
}
}
My service controller class is like this:
package com.nilenium.service.controller;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.nilenium.employee.bo.EmployeeBo;
import com.nilenium.employee.model.Employee;
import com.nilenium.employee.model.EmployeeRecord;
#Controller
#RequestMapping("/Service")
public class NileniumServiceController {
#Autowired
private EmployeeBo employeeBo;
#ExceptionHandler
public String exceptionHandler(Exception e){
return "serviceError";
}
#RequestMapping(value = "employeeId/{employeeId}", method = RequestMethod.GET, headers = "Accept=application/xml, application/json")
public Employee getEmployeeName(#PathVariable int employeeId,
HttpServletResponse resp,
ModelMap model) {
// System.out.println("Emp Name : " + employeeName);
Employee empReturned = new Employee();
empReturned.setEmployeeId(employeeId);
empReturned.setEmployeeName("Demo Name");
return empReturned;
}
#RequestMapping(value = "/employees", method = RequestMethod.GET, headers = "Accept=application/xml, application/json")
public EmployeeRecord getAllEmployeeDetails(HttpServletResponse resp,
ModelMap model) {
List<Employee> empListReturned = employeeBo.getAllEmployee();
EmployeeRecord eRecords = new EmployeeRecord();
eRecords.setEmployeeList(empListReturned);
return eRecords;
}
#RequestMapping(value = "/storeemployee",method = RequestMethod.POST, headers = {"Accept=text/xml, application/json"})
public Employee storeEmpRecord(#RequestBody Employee employee,HttpServletResponse resp,
ModelMap model)
{
System.out.println("Emp Id received : "+employee.getEmployeeId());
System.out.println("Emp Name received : "+employee.getEmployeeName());
// Employee empReturned = employeeBo.findByEmployeeId(1);
return employee;
}
}
When I am trying to post an xml to the storeEmpRecord method xstream marshaller is not able to convert the xml request to respective object (Employee object).
My test client is like this:
package com.nilenium.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.aop.framework.adapter.DefaultAdvisorAdapterRegistry;
import com.nilenium.employee.model.Employee;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class RestPostTest {
public static void main(String[] args) {
Employee emp = new Employee();
emp.setEmployeeId(1);
emp.setEmployeeName("Nilalohita");
XStream xStream = new XStream(new DomDriver());
xStream.alias("employee", Employee.class);
System.out.println(xStream.toXML(emp));
String xmlBody = xStream.toXML(emp);
HttpClient client = new DefaultHttpClient();
String jsonDemo = "{\"employeeId\":2,\"employeeName\":\"He-Man\"}";
try {
HttpPost post = new HttpPost("http://localhost:8080/SampleMaven/Service/storeemployee");
// post.addHeader("Accept", "application/json");
// post.addHeader("Content-Type", "application/json");
post.addHeader("Accept", "application/xml");
post.addHeader("Content-Type", "application/xml");
StringEntity entity = new StringEntity(xmlBody, "UTF-8");
// entity.setContentType("application/json");
entity.setContentType("application/xml");
post.setEntity(entity);
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Please let me know if i am doing something wrong. The same thing is working for jaxb using #XMLroot for Employee class instead of #XStreamAlias("employee").
I am getting the following error. the full stack trace is like this
Caused by:</h3><pre>javax.servlet.ServletException: Unable to locate object to be marshalled in model: {}
at org.springframework.web.servlet.view.xml.MarshallingView.renderMergedOutputModel(MarshallingView.java:100)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1047)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:726)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:206)
at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:324)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:648)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:205)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)
The problem is in the controller method :
#RequestMapping(value = "/storeemployee",method = RequestMethod.POST, headers = {"Accept=text/xml, application/json"})
public Employee storeEmpRecord(#RequestBody Employee employee,HttpServletResponse resp,
ModelMap model)
{
System.out.println("Emp Id received : "+employee.getEmployeeId());
System.out.println("Emp Name received : "+employee.getEmployeeName());
// Employee empReturned = employeeBo.findByEmployeeId(1);
return employee;
}
Spring MVC does not (cannot) add objects to model automatically. You need to add the employee object to the ModelMap. The model map is then passed to the marshaling view, which looks for any objects that it can marshal, and marshals them to response.
Unable to locate object to be marshalled in model: {} Means the Marshalling View received a ModelMap with no objects that have the XStream annotations.
Hope this helps.