Autowired annotation is ignored in camel process statement - apache-camel

I need to implement db connection and query in process step.
So, I defined datasource in bean property.
And I tried to use jdbctemplate.
But result is returned with java.lang.NullPointException.
Do camel ignore autowired annotation in process statement?
If there is another solution, let me know it please.
Thank you.
CamelContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:camel="http://camel.apache.org/schema/spring"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
...
http://camel.apache.org/schema/spring/camel-spring.xsd">
<bean class="com.ktds.openmzn.common.bean.ProcFormat" id="procFormat"/>
<bean class="com.ktds.openmzn.common.bean.ProcessDistributor" id="splitChannel"/>
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
<property name="driverClassName" value="${spring.datasource.driver-class-name}"/>
<property name="url" value="${spring.datasource.url}"/>
<property name="username" value="${spring.datasource.username}"/>
<property name="password" value="${spring.datasource.password}"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<bean class="com.ktds.openmzn.common.bean.FilePathProcessor" id="filePathProcessor"/>
...
<camelContext id="camelContext-f611cb6c-d516-4346-9adc-5512d327a88d"
trace="true" xmlns="http://camel.apache.org/schema/spring">
<camel:route id="fixed_processor">
<camel:from id="_from1" uri="timer:fromPollTimer?period=20000"/>
<camel:process id="_sourceDirectory" ref="filePathProcessor"/>
...
FilePathProcessor.java
public class FilePathProcessor implements Processor {
...
#Override
public void process(Exchange exchange) throws Exception {
List<Map<String, Object>> rows = SetFilePath.getInstance().getPathList("aaaa");
SetFilePath.java
#ManagedResource
public class SetFilePath {
private static SetFilePath instance = null;
private String sourceDirectory;
private String targetDirectory;
#Autowired
private JdbcTemplate jdbcTemplate;
public static SetFilePath getInstance() {
if(instance == null) {
instance = new SetFilePath();
}
return instance;
}
Result
Message History
---------------------------------------------------------------------------------------------------------------------------------------
RouteId ProcessorId Processor
Elapsed (ms)
[fixed_processor ] [fixed_processor ] [timer://fromPollTimer?period=20000 ] [ 0]
[fixed_processor ] [_sourceDirectory ] [ref:filePathProcessor ] [ 0]
Stacktrace
---------------------------------------------------------------------------------------------------------------------------------------
java.lang.NullPointerException: null
at com.ktds.openmzn.common.bean.FilePathProcessor.process(FilePathProcessor.java:20) ~[classes/:na]
at org.apache.camel.processor.DelegateSyncProcessor.process(DelegateSyncProcessor.java:63) ~[camel-core-2.23.1.jar:2.23.1]

Well of course its null, because you are creating the instance yourself via the new constructor:
instance = new SetFilePath();
The #Autowired is from spring framework, and you would essentially need to use spring to create this bean for you.
There are different ways of doing this such as creating a <bean> in the XML file and then configure that on your processor via a setter <property>.
You can also let spring/camel create the bean instance instead of the new constructor, but this requires a bit of Camel API to do so
public static SetFilePath getInstance(CamelContext camel)
if (instance == null) {
instance = camel.getInjector().newInstance(SetFilePath.class);
}
Which will then via the injector create the bean instance via spring framework that does its auto-wiring.

Related

JPA NamedQuery not found

I'm trying to get a list of persons using JPA. Every time I run the code, I get "java.lang.IllegalArgumentException: NamedQuery of name: Persoon.getAllePersonen not found."
I tried changing the table name, replaced Persoon.getAllePersonen by getAllePersonen,.... I just can't seem to figure out what's causing the error
Persoon
#Entity
#Table(name = "Persoon")
#NamedQueries({
#NamedQuery(name = "Persoon.getAllePersonen",
query = "SELECT p FROM Persoon p"),
#NamedQuery(name = "Persoon.findByName",
query = "SELECT p FROM Persoon p WHERE p.achternaam = :persoonNaam OR p.voornaam = :persoonNaam")
})
public class Persoon implements Serializable {
PersoonDao
public List<Persoon> getAlleLeden(){
TypedQuery<Persoon> queryP = em.createNamedQuery("Persoon.getAllePersonen", Persoon.class);
try{ return queryP.getResultList();
} catch (NoResultException e){
throw new EntityNotFoundException("Cannot find leden");
}
}
EDIT:
Generic Superclass DAO
public class GenericDaoJpa<T>{
private static final EntityManagerFactory emf = Persistence.createEntityManagerFactory("TaijitanPU");
protected static final EntityManager em = emf.createEntityManager();
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="TaijitanPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>domein.Persoon</class>
<class>domein.Graad</class>
<class>domein.Locatie</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:sqlserver://localhost\sqlexpress:1433;databaseName=Taijitan;integratedSecurity=true;"/>
<property name="javax.persistence.jdbc.user" value=""/>
<property name="javax.persistence.jdbc.driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
You have to do an abstract class Generic class and override the entityManager of the parent class for each child. Check below. I used EJB Stateless for the childs.
-> PARENT DAO
public abstract class AbstractDAO<T> {
...
protected abstract EntityManager getEntityManager();
-> CHILD DAO
#PersistenceContext(unitName = "yourPersistenceUnitName")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}

How to send a file to the ActiveMQ Queue?

I have a simple Apache Camel route in JBoss FUSE:
<?xml version="1.0"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd">
<bean id="startPolicy" class="org.apache.camel.routepolicy.quartz.CronScheduledRoutePolicy">
<property name="routeStartTime" value="*/3 * * * * ?"/>
</bean>
<bean id="activemq" class="org.apache.activemq.camel.component.ActiveMQComponent">
<property name="brokerURL" value="tcp://localhost:61616" />
<property name="userName" value="admin" />
<property name="password" value="admin" />
</bean>
<camelContext id="blueprintContext" trace="false" xmlns="http://camel.apache.org/schema/blueprint">
<route id="testRoute" routePolicyRef="startPolicy" autoStartup="false">
<from uri="activemq:source-queue?username=admin&password=admin"></from>
<log message="${body}" loggingLevel="INFO"></log>
<to uri="activemq:sink-queue?username=admin&password=admin"></to>
</route>
</camelContext>
</blueprint>
I can connect to the ActiveMQ broker and send a message to the queue, by using this standalone client:
public class MessageSender {
public static void main(String[] args) throws Exception {
ActiveMQConnectionFactory factory =
new ActiveMQConnectionFactory("tcp://localhost:61616");
factory.setUserName("admin");
factory.setPassword("admin");
Connection connection = factory.createConnection();
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue("source-queue");
MessageProducer producer = session.createProducer(queue);
Message message = session.createTextMessage("some message to queue...");
producer.send(message);
} finally {
connection.close();
}
}
}
From the logs I see, that messages is consumed from the queue and message bodies are displays in the log:
How to send a file to the ActiveMQ Queue? For example, I have a simple form with <input type="file"> encoded in multipart/form-data. By using this form I need to send a payload of POST request to the ActiveMQ Queue.
How can I do that?
I would be very grateful for the information.
Thanks to all.
#Mary Zheng provided an excellent example, how it may be done:
ActiveMQ File Transfer Example
Method of class QueueMessageProducer, that sends the file message to ActiveMQ Broker:
private void sendFileAsBytesMessage(File file) throws JMSException, IOException {
BytesMessage bytesMessage = session.createBytesMessage();
bytesMessage.setStringProperty("fileName", file.getName());
bytesMessage.writeBytes(fileManager.readfileAsBytes(file));
msgProducer.send(bytesMessage);
}
, where:
ConnectionFactory connFactory =
new ActiveMQConnectionFactory(username, password, activeMqBrokerUri);
Connection connection = connFactory.createConnection();
ActiveMQSession session =
(ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
FileAsByteArrayManager class that performs a low-level operations with files:
public class FileAsByteArrayManager {
public byte[] readfileAsBytes(File file) throws IOException {
try (RandomAccessFile accessFile = new RandomAccessFile(file, "r")) {
byte[] bytes = new byte[(int) accessFile.length()];
accessFile.readFully(bytes);
return bytes;
}
}
public void writeFile(byte[] bytes, String fileName) throws IOException {
File file = new File(fileName);
try (RandomAccessFile accessFile = new RandomAccessFile(file, "rw")) {
accessFile.write(bytes);
}
}
}

JPA not generating tables from entities

Here is some entity:
#Entity
public class Forest {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
public Forest() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
I want to insert some element in table forest:
public class Main {
private static EntityManagerFactory emf =
Persistence.createEntityManagerFactory("server");
public static void main(String[] args) {
EntityManager em = emf.createEntityManager();
EntityTransaction trx = em.getTransaction();
Forest forest = new Forest();
trx.begin();
em.persist(forest);
trx.commit();
}
}
Thrown exception:
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: Table 'server.forest' doesn't exist
Caused by: org.hibernate.exception.SQLGrammarException: Table 'server.forest' doesn't exist
My persistence.xml file with settings:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="server">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/server"/>
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
</persistence-unit>
</persistence>
When I removed #GeneratedValue(strategy = GenerationType.AUTO) and set id for forest:
forest.setID(1), there was no exception and table has been generated. So, auto-generating of id is not working and I don't know why.
According configuration there is org.hibernate.dialect.HSQLDialect used with MySQL database. Using MySQL dialect instead of one of HSQL likely helps. Likely InnoDB is used - if so, then MySQL5InnoDBDialect is way to go.

JPA + Google SQL + GWT + Eclipse

I'm trying to run a simple project.
I'm struggling with some issues.
I created a simple table in a database instance.
Then, following google tutorial, I set up my project in Eclipse.
I raise this error on running from localhost:
[EL Severe]: 2012-11-23 14:23:16.915--ServerSession(1241461653)--Exception [EclipseLink-0] (Eclipse Persistence Services - 2.4.1.v20121003-ad44345): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions:
---------------------------------------------------------
Exception [EclipseLink-60] (Eclipse Persistence Services - 2.4.1.v20121003-ad44345): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: The method [set] or [get] is not defined in the object [com.shared.Main].
Internal Exception: java.lang.NoSuchMethodException: com.shared.Main.get(java.lang.String)
Mapping: org.eclipse.persistence.mappings.DirectToFieldMapping[id-->main.ID]
Descriptor: RelationalDescriptor(com.shared.Main --> [DatabaseTable(main)])
Exception [EclipseLink-60] (Eclipse Persistence Services - 2.4.1.v20121003-ad44345): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: The method [set] or [get] is not defined in the object [com.shared.Main].
Internal Exception: java.lang.NoSuchMethodException: com.shared.Main.get(java.lang.String)
Mapping: org.eclipse.persistence.mappings.DirectToFieldMapping[name-->main.NAME]
Descriptor: RelationalDescriptor(com.shared.Main --> [DatabaseTable(main)])
It seems that eclipse link can't find getter and setter for my object...
Any clue?
My persistence.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
<persistence-unit name="transactions-optional" transaction-type="RESOURCE_LOCAL">
<provider></provider>
<mapping-file>META-INF/eclipselink-orm.xml</mapping-file>
<properties>
<property name="datanucleus.NontransactionalRead" value="true"/>
<property name="datanucleus.NontransactionalWrite" value="true"/>
<property name="datanucleus.ConnectionURL" value="appengine"/>
<property name="javax.persistence.jdbc.driver" value="com.google.appengine.api.rdbms.AppEngineDriver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:google:rdbms://myinstance/test_jpa"/>
<property name="javax.persistence.jdbc.user" value="myuser"/>
<property name="javax.persistence.jdbc.password" value="mypassword"/>
</properties>
</persistence-unit>
</persistence>
My eclipse-orm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings version="2.4" xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.eclipse.org/eclipselink/xsds/persistence/orm http://www.eclipse.org/eclipselink/xsds/eclipselink_orm_2_4.xsd">
<entity class="com.shared.Main" access="VIRTUAL">
<attributes>
<id name="id" attribute-type="int">
<generated-value strategy="AUTO"/>
</id>
<basic name="name" attribute-type="String">
</basic>
</attributes>
</entity>
</entity-mappings>
My Object:
package com.shared;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the main database table.
*
*/
#Entity
#Table(name="main")
public class Main implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(unique=true, nullable=false)
private int id;
#Column(length=50)
private String name;
public Main() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
Your shared folder exists (also) on client. The client can not know anything about databases. SQL etc. Remove all database relations from shared to server.
The problem was solved removing the link to the orm file in persistance.xml:
<mapping-file>META-INF/eclipselink-orm.xml</mapping-file>
and adding direct mapping to classes
<class>org.my.package.MyClass</class>

mandatory request param in cxf

I developed a web service with CXF and It work fine.
I have a service with two input parameters and both of them should be mandatory.
but when I call my service just the first parameter is mandatory.
please let me know what should I do?
my SEI
#WebService(
endpointInterface = "com.myCompany.product.webService",
targetNamespace = "http://product.myCompany.com",
portName = "product",
serviceName = "ProductService")
#DataBinding(org.apache.cxf.aegis.databinding.AegisDatabinding.class)
public interface ProductService {
#WebMethod(operationName = "authentication")
#WebResult(name = "authenticationResponseParam")
public AuthenticationResponseParam authentication(#WebParam(name = "user", header = true) String user,
#WebParam(name = "authenticationRequestParam") AuthenticationRequestParam authenticationRequestParam);
}
and my AuthenticationResponseParam class
#XmlAccessorType(XmlAccessType.FIELD
)
#XmlType(name = "authenticationRequestParam", propOrder = {
"account", "password"
})
public class AuthenticationRequestParam implements Serializable {
#XmlElement(name = "account", required = true)
private BigDecimal account;
#XmlElement(name = "password", required = true)
private String password;
public BigDecimal getAccount() {
return account;
}
public void setAccount(BigDecimal account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "AuthenticationRequestParam{" +
"account=" + account +
", password='" + password + '\'' +
'}';
}
}
and my CXF servlet 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:jaxws="http://cxf.apache.org/jaxws"
xmlns:cxf="http://cxf.apache.org/core"
xmlns:soap="http://cxf.apache.org/bindings/soap"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
http://cxf.apache.org/bindings/soap
http://cxf.apache.org/schemas/configuration/soap.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml"/>
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
<import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
<cxf:bus>
<cxf:features>
<cxf:logging/>
</cxf:features>
</cxf:bus>
<!--Data binding-->
<bean id="aegisBean" class="org.apache.cxf.aegis.databinding.AegisDatabinding" scope="prototype"/>
<bean id="jaxws-and-aegis-service-factory"
class="org.apache.cxf.jaxws.support.JaxWsServiceFactoryBean"
scope="prototype">
<property name="dataBinding" ref="aegisBean"/>
</bean>
<jaxws:endpoint id="telBank" implementor="#myService" address="/telBank">
<jaxws:binding>
<soap:soapBinding mtomEnabled="false" version="1.2"/>
</jaxws:binding>
</jaxws:endpoint>
<bean id="myService" class="com.myCompany.product.webService.impl.ProductServiceImpl"/>
</beans>
thank you
Hey guys
I added a new service in my web service
public BigDecimal sample(#WebParam(name = "sam1") BigDecimal a1,#WebParam(name = "sam2") BigDecimal a2);
and none of both parameters are mandatory
what should I do?please help me
I found what my problem.
I use org.apache.cxf.aegis.databinding.AegisDatabinding az data binder and it just recognize primitive type az mandatory.when I commend that my input param become mandatory.
what kind of data binder should I use?
If you want to use AegisDatabinding class as data binder,set this property it bean definition.
<bean id="aegisBean" class="org.apache.cxf.aegis.databinding.AegisDatabinding" scope="prototype">
<property name="configuration">
<bean class="org.apache.cxf.aegis.type.TypeCreationOptions">
<property name="defaultMinOccurs" value="1"/>
<property name="defaultNillable" value="false"/>
</bean>
</property>
</bean>

Resources