Pragmatically quartz in grails - grails

I have a problem. I wanna create a Job but not when application is started.
I wanna invoke method from pingServcie but is null.
This is my code:
Job class
class MyJob implements Job {
def pingService
#Override
void execute(JobExecutionContext context) throws JobExecutionException {
pingService.checkPing()
}
}
I read somewhere that I need bean with my Service class, because Spring Autowire doesn't work in this case, so I create it (I never work with bean so I don't if this is correct).
I create resources.xml instead of resources.groovy
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name="pingService" class="inzynierka.PingService" />
</beans>
But this doesn't work.
Finally, I did something like this.
class MyJob implements Job {
def PingService pingService
#Override
void execute(JobExecutionContext context) throws JobExecutionException {
JobDataMap dataMap = context.getJobDetail().getJobDataMap();
pingService = dataMap.getWrappedMap().get("pingService")
pingService.checkPing()
}
}
I passing params in different class like this
job.getJobDataMap().put("pingService", pingService)
and it works.

Related

Spring data elasticsearch CRUD configuration

I am facing problem while configuring the spring data elasticsearch, I followed the procedure mentioned here Spring bean configuration for Crud Repositories. But I am getting error:
Exception in thread "main"
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'customerService': Injection of resource
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'customerRepo': Cannot resolve reference to
bean 'elasticsearchTemplate' while setting bean property
'elasticsearchOperations'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'elasticsearchTemplate' defined in class path
resource [spring-repository.xml]: Instantiation of bean failed; nested
exception is org.springframework.beans.BeanInstantiationException:
Could not instantiate bean class
[org.springframework.data.elasticsearch.core.ElasticsearchTemplate]:
Constructor threw exception; nested exception is
java.lang.NoSuchMethodError:
com.fasterxml.jackson.core.JsonFactory.requiresPropertyOrdering()Z
Here is the code:
CustomerService.java
#Service
public class CustomerService {
#Resource
CustomerRepo custRepo;
public void save(Customer cust) {
custRepo.save(cust);
}
}
Customer.java
#Document(
indexName = "Customer", type = "cust"
)
public class Customer {
#Id
private String id;
private String name;
public Customer(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
CustomerRepo.java
public interface CustomerRepo extends ElasticsearchRepository<Customer, String> {
}
MainClass.java
public class MainClass {
public static void main(String args[]) {
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"spring-customer.xml"});
CustomerService cust = (CustomerService)context.getBean("CustomerService");
Customer customer = new Customer("test_name");
cust.save(customer);
}
}
spring-customer.xml
<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.xsd">
<context:component-scan base-package="com.elasticsearch" />
<import resource="spring-repository.xml"/>
</beans>
spring-repository.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
xsi:schemaLocation="http://www.springframework.org/schema/data/elasticsearch
http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<elasticsearch:transport-client id="client" cluster-nodes="xx.xx.xx.xx:9200" />
<bean name="elasticsearchTemplate"
class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
<constructor-arg name="client" ref="client" />
</bean>
<elasticsearch:repositories
base-package="com.elasticsearch.repositories" />
I don't know why it is not working. Please help me out.
It worked finally, after modifying these files:
1) spring-customer.xml
<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.xsd">
<context:component-scan base-package="com.elasticsearch.repositories" />
<import resource="spring-repository.xml"/>
<bean id="customerService" class="com.elasticsearch.CustomerService" scope="prototype" >
<property name="custRepo" ref="custRepo"></property>
</bean>
</beans>
2) Changing port no. from 9200 to 9300 in spring-repository.xml. As 9200 is for http, where as 9300 is for node to node communication.
3) Adding getter and setter for custRepo in CustomerService.java file.

embedded a ldap server with spring-security using java (instead of xml)

I need to embeed a LDAP server with spring for testing purposes. The following code works:
src/main/webapp/WEB-INF/web.xml
[...]
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
[...]
com.example.config.servlet.TestLDAPServerConfiguration
</param-value>
</context-param>
[...]
src/main/java/com/example/config/servlet/TestLDAPServerConfiguration.java
package com.example.config.servlet;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
#Configuration
#ImportResource({"/WEB-INF/test-ldap-server.xml"})
public class TestLDAPServerConfiguration {
}
src/main/webapp/WEB-INF/test-ldap-server.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:s="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<s:ldap-server ldif="classpath:users.ldif" root="dc=nestle,dc=com" port="33389"/>
</beans>
I do need to use AnnotationConfigWebApplicationContext instead of XmlWebApplicationContext. However, here I am using a class TestLDAPServerConfiguration which just imports a test-ldap-server.xml, and this test-ldap-server.xml just declares the ldap-server.
I'd like to remove the test-ldap-server.xml file. How can I do the equivalent of s:ldap-server with java code inside the TestLDAPServerConfiguration class? And where is this documented?
Try something like this;
protected static ApacheDSContainer server;
#BeforeClass
public static void startServer() throws Exception {
server = new ApacheDSContainer( "dc=yourdomain,dc=com", "classpath:test-server.ldif" );
server.setPort( 53389 );
server.afterPropertiesSet();
server.start();
}
#AfterClass
public static void stopServer() throws Exception {
if( server != null ) {
server.stop();
}
}
You can get guides from the spring-security-ldap source code.

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/

struts2 ognl servlet context

I have some constants like APPVERSION, APPNAME and APPREV that I want to display on every page on my Struts 2 app.
With these requirements I thought that it would be great to put that info intro servletContext and to load this when the app is deployed.
I have created a listener that implements ServletContextListener:
public class ApplicationInitListenerImpl extends GenericVsService implements ApplicationInitListener,ServletContextListener {
#Override
public void contextDestroyed(ServletContextEvent sce) {
}
#Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
sc.setAttribute("appVer",xxx.utils.VConstants.APPVER);
sc.setAttribute("appName",xxx.utils.VConstants.APPNAME);
sc.setAttribute("appRev",xxx.utils.VConstants.APPREV);
}
}
and then I have added in my web.xml the listener:
<listener>
<listener-class>xxx.listeners.ApplicationInitListenerImpl</listener-class>
</listener>
In my Tiles template I have added:
<s:property value="#application.appName"/> - <s:property value="#application.appVer"/>
But I get nothing here.
If I retrieve the servletContext from a Struts 2 Action I can read the correct values, so the values are set ok.
What am I doing wrong?
You can use
<s:property value="#attr.appName"/> - <s:property value="#attr.appVer"/>
Or
${appName} - ${appVer}

Using #Interceptor in #ManagedBean

Interception with CDI works perfectly in #Named , but doesn't in #ManagedBean:
Logable.java
#InterceptorBinding
#Retention(RUNTIME)
#Target({TYPE, METHOD})
public #interface Logable {
}
LoggingInterceptor.java
#Logable
#Interceptor
public class LoggingInterceptor {
#AroundInvoke
public Object log(InvocationContext ctx) throws Exception {
//log smth. with ctx.
}
}
WorkingBean.java
#Named
#Logable
public class WorkingBean implements Serializable {
//works : methods will be logged
}
beans.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
<interceptors>
<class>LoggingInterceptor</class>
</interceptors>
</beans>
ViewScopedBean.java
#Logable
#ManagedBean
public class ViewScopedBean implements Serializable {
//doesn't work
}
I'm aware, that this kind of Interceptor is meant to work with WebBeans (and EJB),
but i'm searching for solution for both worlds (described + JSF) with same Interceptor concept
I need #ViewScoped #ManagedBean, thats why i cant get rid of #ManagedBean in favour of pure WebBeans
System:
Mojarra 2.1.7
Primefaces 3.2
As far as I understand, there isn't one. JSF doesn't have anything supporting interception.
JSF does not support the CDI interception like you have posted per se. A CDI interceptor will work for lifecycle methods like #PostConstruct
#Inherited
#InterceptorBinding
#Retention(RUNTIME)
#Target({TYPE})
public #interface TypeLogger {
#Nonbinding
public LoggingLevel logLevel() default LoggingLevel.INFO;
}
Here is how it would be used since it only binds to the #Target({TYPE})
#ManagedBean
#ViewScoped
#TypeLogger
public class Index implements Serializable {
private static final long serialVersionUID = 3336392241545517919L;
#PostConstruct
private void init() {
setup();
}
}

Resources