Tomcat 8 JNDI Setup for DataSource (Converting from Tomcat 7) - jndi

I have an older Java application that I'm deploying to newer JBoss servers with Tomcat 8/Java 8 (up from Tomcat 7 and Java 7). I'm having some JNDI issues after deploying to the new servers. I'll get the error:
javax.naming.OperationNotSupportedException: Context is read only
Currently, I have a pooled datasource bean being created and then another bean that configures the JNDI reference.
<bean id="dataSourceBean" class="oracle.ucp.jdbc.PoolDataSourceFactory" factory-method="getPoolDataSource" >
<property name="URL" value="${URL}"/>
<property name="user" value="${user}"/>
<property name="password" value="${password}"/>
<property name="connectionFactoryClassName" value="${connectionFactoryClassName}"/>
<property name="minPoolSize" value="${minPoolSize}"/>
<property name="maxPoolSize" value="${maxPoolSize}"/>
<property name="validateConnectionOnBorrow" value="true"/>
<property name="inactiveConnectionTimeout" value="${inactiveConnectionTimeout}"></property>
<property name="fastConnectionFailoverEnabled" value="true"></property>
<property name="maxStatements" value="${maxStatements}"></property>
<property name="loginTimeout" value="${loginTimeout}"></property>
<property name="timeToLiveConnectionTimeout" value="${timeToLiveConnectionTimeout}"></property>
<property name="initialPoolSize" value="${initialPoolSize}"></property>
</bean>
<bean id="jndiConfiger" class="com.uprr.app.cam.common.util.DataBaseJndiConfig">
<property name="jndiName" value="java:comp/env/jdbc/com.uprr.app.cam.cam1_admin_Pool1TXDS"></property>
<property name="dataSource" ref="dataSourceBean"></property>
</bean>
And then the java class to configure it:
public class DataBaseJndiConfig implements InitializingBean {
private static final Logger log = Logger.getLogger(DataBaseJndiConfig.class);
private static boolean hasRun = false;
private String jndiName;
private DataSource dataSource;
private InitialContext ic;
public String getJndiName() {
return jndiName;
}
public void setJndiName(String jndiName) {
this.jndiName = jndiName;
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public DataBaseJndiConfig(){
try {
log.error("IN JNDI CONFIG");
if(hasRun==false){
ic= new InitialContext();
ic.createSubcontext("java:comp");
ic.createSubcontext("java:comp/env");
ic.createSubcontext("java:comp/env/jdbc");
}
} catch (Exception e) {
log.error("Exception in the constructor of DataBaseJndiConfig :"+e);
}
}
public void afterPropertiesSet() {
try {
log.error("SETTING JNDI PROPERTIES");
if(hasRun==false){
if (dataSource != null && jndiName != null) {
ic.bind(jndiName, dataSource);
hasRun=true;
}
}
} catch (Exception e) {
log.error("Exception in the afterPropertiesSet of DataBaseJndiConfig :"+e);
}
}
}
The error comes when I first try and do a createSubcontext()
I've read some other threads that mention having a context.xml file with a tag but am having trouble deciphering what should do in that tag
Is it basically the "dataSourceBean" that would be converted to a tag? Then I'm guessing I could eliminate the "jndiConfiger" bean and should just be able do the JNDI reference without doing all that binding?

Related

could not autowire no beans of type found, for service in hybris

<!-- Total Customer service dao facade-->
<bean id="totalCustomersDao"
class="de.hybris.training.core.dao.impl.TotalCustomersDaoImpl">
<property name="flexibleSearchService" ref="flexibleSearchService"/>
</bean>
<bean id="totalCustomerService" class=" de.hybris.training.core.impl.TotalCustomerServiceImpl">
<property name="totalCustomersDao" ref="totalCustomersDao"/>
</bean>
<bean id="totalCustomerFacade" class="de.hybris.training.core.facade.impl.TotalCustomerFacadeImpl">
<property name="totalCustomerService" ref="totalCustomerService"/>
</bean>
<bean id="usersFindJob" class=" de.hybris.training.core.job.UsersFindJob"
parent="abstractJobPerformable" >
</bean>
this is xml.
This is facade class
public class TotalCustomerFacadeImpl implements TotalCustomerFacade {
//TODO autowired or resoucre not work
private TotalCustomerService totalCustomerService ;
private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(UsersFindJob.class);
public TotalCustomerService getTotalCustomerService() {
return totalCustomerService;
}
public void setTotalCustomerService(TotalCustomerService totalCustomerService) {
this.totalCustomerService = totalCustomerService;
}
here for
private TotalCustomerService totalCustomerService ;
when i put autorwired, it says
could not autowire no beans of type found
WHen i write resource or resource(name=totalCustomerService)
it gives null pointer.
this is serviceimpl
public class TotalCustomerServiceImpl implements TotalCustomerService {
private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(UsersFindJob.class);
#Autowired
private TotalCustomersDao totalCustomersDao;
public TotalCustomersDao getTotalCustomersDao() {
return totalCustomersDao;
}
public void setTotalCustomersDao(TotalCustomersDao totalCustomersDao) {
this.totalCustomersDao = totalCustomersDao;
} public List<CustomerModel> getAllCustomersNames (String name) { LOG.info("***********************************");
LOG.info("***********************************");
LOG.info("*************************getAllCustomersNames::");
LOG.info("***********************************");
LOG.info("***********************************");
List<CustomerModel> customerModels = totalCustomersDao.findAllCustomersFromDao( name);
return customerModels;
}
those are interfaces
public interface TotalCustomerService {
List<CustomerModel> getAllCustomersNames (String name);
}
public interface TotalCustomerFacade {
List<String> findCustomerContainingName(String firstName);
}
how can i solve this?
the paths are they are all in
de.hybris.training.core
divided like
dao
facade
service
what can i do? I need to go for that service. I tried lots of times. added autowired. removed , let it without any annotations but still same.
Also this did not work
#Autowired
#Qualifier("totalCustomerService")
private TotalCustomerService totalCustomerService ;
remove whitespace! class=" de.hybris.training
Change
<bean id="totalCustomerService" class=" de.hybris.training.core.impl.TotalCustomerServiceImpl">
to
<bean id="totalCustomerService" class="de.hybris.training.core.impl.TotalCustomerServiceImpl">
it is because of whitespace
class=" de.
here

How to integrate JMX into tomcat app or what I doing wrong?

I tried to configure JMX with no luck.. What I did?
Created class:
public class JmxTestBean implements IJmxTestBean {
private String name;
private int age;
private boolean isSuperman;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int add(int x, int y) {
return x + y;
}
public void dontExposeMe() {
throw new RuntimeException();
}
}
And after that I've added to spring config following lines:
<bean id="mbeanServer" class="org.springframework.jmx.support.MBeanServerFactoryBean"/>
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<map>
<entry key="bean:name=testBean1" value-ref="testBean"/>
</map>
</property>
<property name="server" ref="mbeanServer"/>
</bean>
<bean id="testBean" class="com.db.gbs.jmx.simulator.JmxTestBean">
<property name="name" value="TEST"/>
<property name="age" value="100"/>
</bean>
As last step I tried to setup env variable as following:
set CATALONA_OPTS="-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9010"
And started tomcat7:
mvn jetty:run-exploded -Dorg.eclipse.jetty.server.Request.maxFormContentSize=100000000
Using JConsole tried to connect and got following error:
Could not connect to localhost:9010 : Failed to retrieve
RMIServer stub: javax.naming.ServiceUnavailableException
[Root exception is java.rmi.ConnectException: Connection
refused to host: localhost; nested exception is:
java.net.ConnectException: Connection refused: connect]
Could not connect to localhost:9010. Make sure the JVM
is running and that you are using the correct protocol
in the Service URL service:jmx:rmi:///jndi/rmi://localhost:9010/jmxrmi).
What I doing wrong?

Grails autowire inside Spring converter

I have something like this...
class DomainConverter implements GenericConverter {
private Class<Domain> classOfDomain;
private Class<DomainCommand> classOfDomainCommand;
public Set<GenericConverter.ConvertiblePair> getConvertibleTypes() {
Set<GenericConverter.ConvertiblePair> convertiblePairs = new HashSet<GenericConverter.ConvertiblePair>();
convertiblePairs.add(new GenericConverter.ConvertiblePair(classOfDomain, classOfDomainCommand));
convertiblePairs.add(new GenericConverter.ConvertiblePair(classOfDomainCommand, classOfDomain));
return convertiblePairs;
}
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (classOfDomain.equals(sourceType.getType())) {
return this.convert((Domain) source);
} else {
return this.convertBack((DomainCommand) source);
}
}
protected DomainCommand convert(Domain definition){
...
}
protected Domain convertBack(DomainCommand command){
...
}
}
Do I have to wire it within the class or add it to the resources.groovy?
How do I create the DomainCommand so that I still have my autowiring
Looking at the Spring documentation you can see an example of bean declaration:
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean"/>
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="example.MyCustomConverter"/>
</list>
</property>
</bean>
So you need to declare your converter and also the conversionService in your resources.groovy file.

Autowiring a bean from one maven module to another maven module within same multi-module maven project

I have a multi module maven project with follwing child module
Tracker
|--Tracker-core
|--Tracker-dao
| |---src/main/resource/spring-dao-config.xml
|
|--Tracker-services
| |---src/main/resource/spring-service-config.xml
|
|--Tracker-web
In Tracker-dao, I have a spring-context.xml in the resource package. this scans for the dao classes and includes other datasource configuration.
spring-dao-config.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="com.gits.tracker"></context:component-scan>
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:/database.properties" />
</bean>
<import resource="classpath:hibernate-config.xml" />
<!-- Declare a datasource that has pooling capabilities -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- An AnnotationSessionFactoryBean for loading Hibernate mappings from
annotated domain classes. -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.gits.tracker.core.entity.Address</value>
<value>com.gits.tracker.core.entity.Company</value>
<value>com.gits.tracker.core.entity.Customer</value>
<value>com.gits.tracker.core.entity.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!-- <prop key="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory</prop> -->
</props>
</property>
</bean>
</beans>
Junit test for the dao layer alone is working perfectly alright.
In the Tracker-service, I have used this Tracker-core as a dependency.
While running the Junit in Tracker-service, it goes error, saying failed to load Application context, failed to find atleast 1 bean matching the name.
spring-service-config.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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<!-- <import resource="classpath:spring-dao-config.xml"/> -->
<context:component-scan base-package="com.gits.tracker.service.services"></context:component-scan>
</beans>
Junit in Tracker-service
Problem is here:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:spring-service-config.xml" })
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:spring-service-config.xml" })
public class TestUserService extends
AbstractTransactionalJUnit4SpringContextTests {
private static Logger logger;
private static ApplicationContext ctx;
private UserService userService;
#BeforeClass
public static void init() {
logger = Logger.getLogger(User.class);
if (logger.isDebugEnabled()) {
logger.debug("IN DEBUG MODE");
}
}
#Before
public void localInit() {
logger.info("*************EXECUTING LOCALINIT*************");
ctx = new FileSystemXmlApplicationContext(
"src/main/resources/spring-config.xml");
userService = (UserService) ctx.getBean("userServiceImpl");
// userDao.executeQuery("delete from User where id<>3");
logger.info("*************DELETED ALL COMPANY FROM TABLE*************");
logger.info("*************EXITING OUT OF LOCALINIT*************");
}
#AfterClass
public static void stop() {
logger.debug("TEST COMPLETED");
}
private UserServiceImpl loadUserService() {
return (UserServiceImpl) ctx.getBean("userServiceImpl");
}
private UserDTO createTestUserDTO() {
UserDTO dto = new UserDTO("manoj", "manojpass", "true");
return dto;
}
#Test
public void testCreateUser() {
loadUserService();
UserDTO dto = createTestUserDTO();
Long id = userService.createUser(dto);
dto.setId(id);
UserDTO dto_1 = userService.getUserById(id);
org.junit.Assert.assertEquals(dto.toString(), dto_1.toString());
}
#Test
public void findByCriteriaWithAlias() {
loadUserService();
UserDTO dto = createTestUserDTO();
Long id = userService.createUser(dto);
CriteriaWithAlias criteriaWithAlias = new CriteriaWithAlias();
HashMap<String, String> alias = new HashMap<String, String>();
List<Criterion> criterions = new ArrayList<Criterion>();
Criterion criterion0 = Restrictions.eq("username", dto.getUsername());
criterions.add(criterion0);
criteriaWithAlias.setAlias(alias);
criteriaWithAlias.setCriterions(criterions);
List<UserDTO> users = userService
.findByCriteriaWithAlias(criteriaWithAlias);
for (UserDTO user : users) {
org.junit.Assert.assertFalse(user.getPassword().isEmpty());
org.junit.Assert.assertFalse(user.getId().toString().isEmpty());
org.junit.Assert.assertFalse(user.getUsername().isEmpty());
org.junit.Assert.assertFalse(user.getEnabled().isEmpty());
}
}
#Test
public void findByProjection() {
loadUserService();
UserDTO dto = createTestUserDTO();
userService.createUser(dto);
CriteriaWithAlias criteriaWithAlias = new CriteriaWithAlias();
HashMap<String, String> alias = new HashMap<String, String>();
HashMap<String, String> projections = new HashMap<String, String>();
List<Criterion> criterions = new ArrayList<Criterion>();
projections.put("username", "username");
projections.put("enabled", "enabled");
Criterion criterion0 = Restrictions.ne("username", "syed");
Criterion criterion1 = Restrictions.eq("enabled", "true");
criterions.add(criterion0);
criterions.add(criterion1);
criteriaWithAlias.setAlias(alias);
criteriaWithAlias.setCriterions(criterions);
criteriaWithAlias.setProjections(projections);
List<UserDTO> users = userService
.findByCriterionWithProjection(criteriaWithAlias);
for (UserDTO user : users) {
org.junit.Assert.assertNull(user.getPassword());
org.junit.Assert.assertNull(user.getId());
org.junit.Assert.assertFalse(user.getUsername().isEmpty());
org.junit.Assert.assertFalse(user.getEnabled().isEmpty());
}
}
I also tried importing the spring-dao-config of tracker-core in spring-service-config of the tracker-service module. But, that time, it says, spring-dao-config.xml file not found.
Please let me know whats wrong and what I have missed and suggest a solution for this.
I have added the dependency for each module in their own POM.xml and not all together in parent POM.xml
I found solution to my own question. Correct me if I'm wrong.
Its not possible to perform a JUnit test by accessing a config file from another maven module. JUnit is meant for Unit testing only. and not the integration testing.
The dependent maven modules config file will not be available in the classpath for the actual maven module you want to test.
So, what I did was, copied the config file of the dependent maven modules into the classpath of the actual maven module which I need to test. This might not be the correct way of doing it. but, I'm able to perform the JUnit test successfully.
Other way to perform Junit test in such case is to use tools like MOCKITO : https://code.google.com/p/mockito/

is there an equivalent of EndpointInterceptorAdapter for the client?

Is there an equivalent of EndpointInterceptorAdapter for the client?
Because i need to intercept outgoing and incoming messages from the client and do some work with them.
EndpointInterceptorAdapter intercepts only endpoint messages.
I think you can use the SmartEndpointInterceptor
public class SmartEndpointInterceptorImpl implements
SmartEndpointInterceptor
{
public boolean handleRequest(MessageContext messageContext, Object endpoint)
throws Exception
{
SaajSoapMessage soapSaajMsg = (SaajSoapMessage)messageContext.getRequest();
return true;
}
public boolean handleResponse(MessageContext messageContext, Object endpoint)
throws Exception {
return true;
}
//I omitted two more methods
}
Well, i found the answer.
You have to create a class that implements ClientInterceptor.
i.e.
package com.coral.project.interceptor;
public class WebServiceClientInterceptor implements ClientInterceptor {
#Override
public boolean handleRequest(MessageContext messageContext)
throws WebServiceClientException {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean handleResponse(MessageContext messageContext)
throws WebServiceClientException {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean handleFault(MessageContext messageContext)
throws WebServiceClientException {
// TODO Auto-generated method stub
return false;
}
}
and define in spring-ws config file:
<bean id="crmClient" class="com.coral.project.clients.CrmClient">
<property name="defaultUri" value="..."/>
<property name="marshaller" ref="jaxb2Marshaller" />
<property name="unmarshaller" ref="jaxb2Marshaller" />
<property name="interceptors">
<list>
<bean class="com.coral.project.interceptor.WebServiceClientInterceptor" />
</list>
</property>
</bean>
and that's it.

Resources