Apache Camel box component file dowload, how do I use the output parameter? - apache-camel

I have been trying to download a file from Box using the Apache Camel Box component. I cannot seem to unserstand how to use the required parameter output with the uri box://files/downloadFile.
I am able to upload files fine (code not listed), so I am confident that this is a problem configure this particular endpoint and not with, for example, my org.apache.camel.component.box.BoxConfiguration.
How do I use camel-box and box://files/downloadFile to download a file? Specifically what I am expected to pass as the output parameter of the endpoint uri?
I've been referring to this documentation:
https://github.com/apache/camel/blob/master/components/camel-box/camel-box-component/src/main/docs/box-component.adoc
Here's what I am working with:
camel-core 2.19.3,camel-box 2.19.3,camel-spring-javaconfig 2.19.3
Here's the route, BoxRoute.java that I cant figure out:
package [REDACTED];
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
#Component
public class BoxRoute extends RouteBuilder{
private static final Logger LOG = LoggerFactory.getLogger(BoxRoute.class);
#Override
public void configure() throws Exception {
from("box://files/downloadFile?fileId=[REDACTED]&output=#outputStream") //I expect this to refer to the outputStream #Bean
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
for(String key: exchange.getProperties().keySet()){
LOG.debug("ex prop {} = {}", key, exchange.getProperty(key));
}
for(String key: exchange.getIn().getHeaders().keySet()){
LOG.debug("he prop {} = {}", key, exchange.getIn().getHeader(key));
}
}
})
.to("file:c:/_/dat/camel/out");
}
}
So I think I'm giving this uri what it needs. Namely, a reference to my outputStream been which is an OutputStream, defined in the next listing.
My application's main method is in BoxApplication.java:
package [REDACTED];
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import org.apache.camel.spring.javaconfig.CamelConfiguration;
import org.apache.camel.spring.javaconfig.Main;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
#Configuration
#ComponentScan
#ImportResource("classpath:/META-INF/spring/box-context.xml")
public class BoxApplication extends CamelConfiguration{
public static void main(String[] args) throws Exception {
Main main = new Main();
main.setConfigClass(BoxApplication.class);
main.setDuration(10);
main.run();
}
#Bean()
public OutputStream outputStream(){
System.out.println("I AM GETTING REGISTERED"); // I see this in stdout, so this bean is available to Camel (right?)
return new ByteArrayOutputStream();
}
}
The contents of box-context.xml are (I can use camel box to upload, so I doubt my problems is here):
?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.xsd">
<bean id="box" class="org.apache.camel.component.box.BoxComponent">
<property name="configuration">
<bean class="org.apache.camel.component.box.BoxConfiguration">
<property name="userName" value="[REDACTED]" />
<property name="userPassword" value="[REDACTED]" />
<property name="clientId" value="[REDACTED]" />
<property name="clientSecret" value="[REDACTED]" />
<property name="authenticationType" value="STANDARD_AUTHENTICATION" />
</bean>
</property>
</bean>
Alas, I get this error, and I am stumped. Any help would be appreciated.
2017-10-07 18:05:00.128 [main] INFO o.s.c.a.AnnotationConfigApplicationContext(583) - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#bd8db5a: startup date [Sat Oct 07 18:05:00 EDT 2017]; root of context hierarchy
2017-10-07 18:05:00.216 [main] INFO o.s.b.f.xml.XmlBeanDefinitionReader(317) - Loading XML bean definitions from class path resource [META-INF/spring/box-context.xml]
2017-10-07 18:05:00.500 [main] INFO o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker(325) - Bean 'boxApplication' of type [com.hqcllc.box.BoxApplication$$EnhancerBySpringCGLIB$$4e7e4dfa] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
I AM GETTING REGISTERED
Exception in thread "main" org.apache.camel.spring.javaconfig.CamelSpringJavaconfigInitializationException: org.apache.camel.RuntimeCamelException: Error invoking downloadFile with {output=, listener=Consumer[box://files/downloadFile?fileId=[REDACTED]&output=%23outputStream], fileId=[REDACTED]}: object is not an instance of declaring class
at org.apache.camel.spring.javaconfig.RoutesCollector.onApplicationEvent(RoutesCollector.java:88)
at org.apache.camel.spring.javaconfig.RoutesCollector.onApplicationEvent(RoutesCollector.java:33)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:393)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:347)
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:883)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)
at org.apache.camel.spring.javaconfig.Main.createDefaultApplicationContext(Main.java:148)
at org.apache.camel.spring.Main.doStart(Main.java:154)
at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:61)
at org.apache.camel.main.MainSupport.run(MainSupport.java:168)
at com.hqcllc.box.BoxApplication.main(BoxApplication.java:22)
Caused by: org.apache.camel.RuntimeCamelException: Error invoking downloadFile with {output=, listener=Consumer[box://files/downloadFile?fileId=[REDACTED]&output=%23outputStream], fileId=[REDACTED]}: object is not an instance of declaring class
at org.apache.camel.util.component.ApiMethodHelper.invokeMethod(ApiMethodHelper.java:514)
at org.apache.camel.component.box.BoxConsumer.doStart(BoxConsumer.java:98)
at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:61)
at org.apache.camel.impl.DefaultCamelContext.startService(DefaultCamelContext.java:3514)
at org.apache.camel.impl.DefaultCamelContext.doStartOrResumeRouteConsumers(DefaultCamelContext.java:3831)
at org.apache.camel.impl.DefaultCamelContext.doStartRouteConsumers(DefaultCamelContext.java:3767)
at org.apache.camel.impl.DefaultCamelContext.safelyStartRouteServices(DefaultCamelContext.java:3687)
at org.apache.camel.impl.DefaultCamelContext.doStartOrResumeRoutes(DefaultCamelContext.java:3451)
at org.apache.camel.impl.DefaultCamelContext.doStartCamel(DefaultCamelContext.java:3305)
at org.apache.camel.impl.DefaultCamelContext.access$000(DefaultCamelContext.java:202)
at org.apache.camel.impl.DefaultCamelContext$2.call(DefaultCamelContext.java:3089)
at org.apache.camel.impl.DefaultCamelContext$2.call(DefaultCamelContext.java:3085)
at org.apache.camel.impl.DefaultCamelContext.doWithDefinedClassLoader(DefaultCamelContext.java:3108)
at org.apache.camel.impl.DefaultCamelContext.doStart(DefaultCamelContext.java:3085)
at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:61)
at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:3022)
at org.apache.camel.spring.javaconfig.RoutesCollector.onApplicationEvent(RoutesCollector.java:84)
... 12 more
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.camel.util.component.ApiMethodHelper.invokeMethod(ApiMethodHelper.java:506)
... 28 more
This is my first Camel project fyi.

Related

java.lang.IllegalArgumentException due to named query not found

I can adding to data to database but I am not getting data from database . Okey I am writing my problem,my entity class Product and I store the database operations on ProductRepository.java
Then at my database that;its name jsfjpadb.
productId productName salesPrice
1 Kerem 1235
2 Book 23
I am trying to get the data in the database and I want will show on the ProductOzetSayfasi.xhtml but doesnt come.
public class ProductRepository {
public List<Product> list() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("kerem");
EntityManager manager = factory.createEntityManager();
// String string = "SELECT product FROM Product as product";
// Query query = manager.createNamedQuery(string);
TypedQuery<Product> productQuery = manager.createQuery("SELECT p FROM Product p",Product.class);
List<Product> productList =productQuery.getResultList();
manager.close();
return productList;
}
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2" 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_2.xsd">
<persistence-unit name="kerem" transaction-type="RESOURCE_LOCAL">
<class>com.kerem.inventory.entity.Tablo</class>
<class>com.kerem.inventory.entity.Product</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jsfjpadb"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="kerem2112"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
</properties>
</persistence-unit>
</persistence>
package com.kerem.inventory.faces;
import java.util.*;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import com.kerem.inventory.entity.Product;
import com.kerem.inventory.repository.ProductRepository;
#ManagedBean
public class ProductOzetSayfasiBean {
private List<Product> productList;
public ProductOzetSayfasiBean() {
ProductRepository repository = new ProductRepository();
productList = repository.list();
}
public List<Product> getProductList() {
return productList;
}
}
package com.kerem.inventory.entity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.*;
#Entity
#Table(name = "product")
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int productId;
private String productName;
private double salesPrice;
public Product() {
}
public int getProductId() {
return this.productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return this.productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public double getSalesPrice() {
return this.salesPrice;
}
public void setSalesPrice(double salesPrice) {
this.salesPrice = salesPrice;
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Product</title>
</h:head>
<h:body>
<h1>Product</h1>
<h:form>
<h:dataTable value="#{productOzetSayfasiBean.productList}" var="product">
<h:column>
<h:outputText value="#{product.productId}"/>
</h:column>
</h:dataTable>
</h:form>
</h:body>
</html>
STACK TRACE
INFO: Creating instance of com.kerem.inventory.faces.ProductOzetSayfasiBean
[EL Info]: 2020-05-01 04:44:00.226--ServerSession(985404382)--EclipseLink, version: Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd
Fri May 01 04:44:00 PDT 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Fri May 01 04:44:01 PDT 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
[EL Info]: connection: 2020-05-01 04:44:02.365--ServerSession(985404382)--file:/D:/EclipseProjeleri/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/kerem/WEB-INF/classes/_kerem login successful
May 01, 2020 4:44:02 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [/kerem] threw exception [NamedQuery of name: select product from Product as product not found.] with root cause
java.lang.IllegalArgumentException: NamedQuery of name: select product from Product as product not found.
at org.eclipse.persistence.internal.jpa.QueryImpl.getDatabaseQueryInternal(QueryImpl.java:351)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createNamedQuery(EntityManagerImpl.java:1124)
at com.kerem.inventory.repository.ProductRepository.list(ProductRepository.java:19)
at com.kerem.inventory.faces.ProductOzetSayfasiBean.<init>(ProductOzetSayfasiBean.java:19)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:166)
at java.base/jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:404)
at java.base/java.lang.Class.newInstance(Class.java:591)
at org.apache.myfaces.config.annotation.Tomcat7AnnotationLifecycleProvider.newInstance(Tomcat7AnnotationLifecycleProvider.java:56)
at org.apache.myfaces.config.ManagedBeanBuilder.buildManagedBean(ManagedBeanBuilder.java:156)
at org.apache.myfaces.el.unified.resolver.ManagedBeanResolver.createManagedBean(ManagedBeanResolver.java:333)
at org.apache.myfaces.el.unified.resolver.ManagedBeanResolver.getValue(ManagedBeanResolver.java:296)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:63)
at org.apache.myfaces.el.unified.resolver.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:169)
at org.apache.myfaces.el.VariableResolverImpl.resolveVariable(VariableResolverImpl.java:65)
at org.apache.myfaces.el.convert.VariableResolverToELResolver.getValue(VariableResolverToELResolver.java:123)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:63)
at org.apache.myfaces.el.unified.resolver.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:169)
at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:94)
at org.apache.el.parser.AstValue.getValue(AstValue.java:137)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
at org.apache.myfaces.view.facelets.el.ContextAwareTagValueExpression.getValue(ContextAwareTagValueExpression.java:96)
at javax.faces.component._DeltaStateHelper.eval(_DeltaStateHelper.java:246)
at javax.faces.component.UIData.getValue(UIData.java:2028)
at javax.faces.component.UIData.createDataModel(UIData.java:1976)
at javax.faces.component.UIData.getDataModel(UIData.java:1953)
at javax.faces.component.UIData.getRowCount(UIData.java:478)
at org.apache.myfaces.shared.renderkit.html.HtmlTableRendererBase.encodeInnerHtml(HtmlTableRendererBase.java:328)
at org.apache.myfaces.shared.renderkit.html.HtmlTableRendererBase.encodeChildren(HtmlTableRendererBase.java:198)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:549)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:749)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:758)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:758)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:758)
at org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage.renderView(FaceletViewDeclarationLanguage.java:1900)
at org.apache.myfaces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:285)
at org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:115)
at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:241)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:199)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:830)
define named query via annotation or in xml mapping file. createNamedQuery requires name of query but not the actual query. If you dont want to go that way, use createQuery instead. createQuery takes actual query.
Refer Creating Queries using JPQL

How to add the transaction timeout for Apache Camel route with IBM MQ?

We have an issue in the application that the jms message commit on the ibm mq takes hours to complete which inturn causing the log space filling up in ibm mq and also JVM hung issues on the application side. To resolve this, I tried implementing the transaction timeout on the route, jms component etc. But nothing looks to be working.
There are 3 routes in the application
To Read message (Start route)
Deliver/Send message
Error Route (sending to error queue)
The Route definitions are below,
Input/Consumer Route
public class InputRoute extends SpringRouteBuilder {
#Override
public void configure() throws Exception {
from("wmqInConsumer:{{mq.inputQueue}}?concurrentConsumers={{num.consumers}}&maxConcurrentConsumers={{max.num.consumers}}&defaultTaskExecutorType=ThreadPool&preserveMessageQos=true").routeId("input-route").setHeader("Message_Key").method("headerEnricher", "setKey").inOnly("direct:deliver-normal-route-1");
}
}
Deliver Route
public class DeliverRoute extends SpringRouteBuilder {
#Override
public void configure() throws Exception {
from("direct:deliver-normal-route-1").transacted("PROPAGATION_REQUIRES_NEW").inOnly("direct:deliver-route-2");
from("direct:deliver-route-2").process("myServicesProcessor").split()
.method("messageSplitterBean", "splitMessage").shareUnitOfWork().stopOnException()
.toD("wmqDeliverJms:${headers.Deliver}?preserveMessageQos=true");
}
}
Error Route
public class ErrorRoute extends SpringRouteBuilder {
#Override
public void configure() throws Exception {
from("direct:errorChannelRoute").transacted("PROPAGATION_REQUIRES_NEW").inOnly("direct:errorChannelRoute-1");
from("direct:errorChannelRoute-1").process("errorServicesProcessor").split()
.method("messageSplitterBean", "splitErrorMessage").shareUnitOfWork().stopOnException()
.toD("wmqDeliverJms:${headers.Deliver}?preserveMessageQos=true");
}
}
Here the transaction timeouts I tried based on the Camel documentation. But It's not working and I don't see transaction timeout happening in the trace logs too. Also, not sure what will happen to the message if the timeout occurs. Will it go to error queues or full rollback for a retry??
On Input Route, transactionTimeout=10
from("wmqInConsumer:{{mq.inputQueue}}?concurrentConsumers={{num.consumers}}&maxConcurrentConsumers={{max.num.consumers}}&defaultTaskExecutorType=ThreadPool&preserveMessageQos=true&transactionTimeout=10").routeId("input-route").setHeader("Message_Key").method("headerEnricher", "setKey").inOnly("direct:deliver-normal-route-1");
On Input Route JMS Component,
<bean id="wmqInConsumer" class="org.apache.camel.component.jms.JmsComponent">
<property name="connectionFactory" ref="myConnectionFactory" />
<property name="transacted" value="true" />
<property name="transactionTimeout" value="30"></property> -->
</bean>
On Deliver Route JMS Component,
<bean id="wmqDeliverJms" class="org.apache.camel.component.jms.JmsComponent">
<property name="connectionFactory" ref="myConnectionFactory" />
<property name="destinationResolver" ref="myJmsDestinationResolver" />
<property name="transacted" value="true" />
<property name="transactionTimeout" value="30"></property>
</bean>

Native interface for auto run on Boot in cn1

I am not quite sure how to implement the native android code in cn1 through native interface, although I've done few successfully. Below is the native android code and a try I've done in cn1 native interface. I have a couple of questions:
1) How can I call a class in nativeImpl class? eg: I've created YourActivityRunOnStartup class inside native/android folder in the project. How to call it in nativeImpl class? The receiver in manifest has this class not found exception.
2) There is intent in onReceive method of BroadcastReceiver where I've MainActivity.class, so that each time the device boots, it runs MainActivity class in native android. How can I call specific form or class of cn1 in it through native interface?
Native android code:
**MainActivity**
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e("bootDeviceValue", " aaaaa");
}
}
**YourActivityRunOnStartup class**
public class YourActivityRunOnStartup extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Log.e("bootDeviceValue", " bbbbb");
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
What I've tried in cn1:
Try 1: YourActivityRunOnStartup class inside Native/android folder
public class YourActivityRunOnStartup extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Log.e("bootDeviceValue", " bbbbb");
Intent i = new Intent(context, null);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
Build hint:
1)android.xapplication: <receiver android:enabled="true" android:exported="true" android:name=".YourActivityRunOnStartup"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver>
2)android.xpermissions: <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
How to call YourActivityRunOnStartup class in NativeImpl class and what to do in cn1 code?
NativeImpl class
public class NativeImpl {
public boolean isSupported() {
return true;
}
//what to do here? . . . . . . . . . . . . . . . . . .
}
Nokia.class
public void start() {
if (current != null) {
current.show();
return;
}
na = (Native) NativeLookup.create(Native.class);
if (na != null && na.isSupported()) {
**// what to do here??? . . . . . . . . . . . . . . . . . .**
}
new Home(theme).show();
}
Error on debug:
09-04 14:28:00.805 26852-26852/com.zzzz.nokiaApp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.zzzz.nokiaApp, PID: 26852
java.lang.RuntimeException: Unable to instantiate receiver com.zzzz.nokiaApp.YourActivityRunOnStartup: java.lang.ClassNotFoundException: Didn't find class "com.zzzz.nokiaApp.YourActivityRunOnStartup" on path: DexPathList[[zip file "/data/app/com.zzzz.nokiaApp-1/base.apk"],nativeLibraryDirectories=[/data/app/com.zzzz.nokiaApp-1/lib/arm, /vendor/lib, /system/lib]]
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3682)
at android.app.ActivityThread.access$2000(ActivityThread.java:230)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1904)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7409)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.zzzz.nokiaApp.YourActivityRunOnStartup" on path: DexPathList[[zip file "/data/app/com.zzzz.nokiaApp-1/base.apk"],nativeLibraryDirectories=[/data/app/com.zzzz.nokiaApp-1/lib/arm, /vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3677)
at android.app.ActivityThread.access$2000(ActivityThread.java:230) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1904) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:7409) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
Suppressed: java.lang.ClassNotFoundException: com.zzzz.nokiaApp.YourActivityRunOnStartup
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 10 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available
New Error Log:
09-07 11:54:05.462 8116-8116/com.thecapitaleyenepal.nokiaApp D/AndroidRuntime: Shutting down VM
09-07 11:54:05.462 8116-8116/com.thecapitaleyenepal.nokiaApp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.thecapitaleyenepal.nokiaApp, PID: 8116
java.lang.RuntimeException: Unable to start receiver com.thecapitaleyenepal.nokiaApp.YourActivityRunOnStartup: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.thecapitaleyenepal.nokiaApp/com.thecapitaleyenepal.nokiaApp.Nokia}; have you declared this activity in your AndroidManifest.xml?
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3708)
at android.app.ActivityThread.access$2000(ActivityThread.java:230)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1904)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7409)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.thecapitaleyenepal.nokiaApp/com.thecapitaleyenepal.nokiaApp.Nokia}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1855)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1546)
at android.app.ContextImpl.startActivity(ContextImpl.java:752)
at android.app.ContextImpl.startActivity(ContextImpl.java:734)
at android.content.ContextWrapper.startActivity(ContextWrapper.java:345)
at android.content.ContextWrapper.startActivity(ContextWrapper.java:345)
at com.thecapitaleyenepal.nokiaApp.YourActivityRunOnStartup.onReceive(YourActivityRunOnStartup.java:25)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3701)
at android.app.ActivityThread.access$2000(ActivityThread.java:230) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1904) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:7409) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
09-07 11:54:45.302 8116-8116/com.thecapitaleyenepal.nokiaApp I/Process: Sending signal. PID: 8116 SIG: 9
AndroidManifest:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:enabled="true"
android:exported="true"
android:name=".YourActivityRunOnStartup">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
Notice that within the build hints you included strings that you need to update such as YourActivityRunOnStartup etc. make sure they point to the right package/class names.

camel http component 500

i was creating cxf/camel webservice and i've created for test code like this:
#GET
#Path("/user")
#ProduceMime({ "application/json" })
public String user(#FormParam("token") String token) throws Exception {
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
public void configure(){
from("direct:start").to("http://google.com");
}
});
context.start();
return token;
}
}
Then i've compiled it and copied do FUSE ESB deploy folder. My webservice was installed, but when i opened URL with my webservice i got 500 response:
org.apache.cxf.interceptor.Fault: Failed to create route route17 at: >>> To[http://google.com] <<< in route: Route[[From[direct:start]] -> [To[http://google.com]]] because of Failed to resolve endpoint: http://google.com due to: No component found with scheme: http
Caused by:
java.lang.RuntimeException: org.apache.cxf.interceptor.Fault: Failed to create route route17 at: >>> To[http://google.com] <<< in route: Route[[From[direct:start]] -> [To[http://google.com]]] because of Failed to resolve endpoint: http://google.com due to: No component found with scheme: http
at org.apache.cxf.interceptor.AbstractFaultChainInitiatorObserver.onMessage(AbstractFaultChainInitiatorObserver.java:108)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:323)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:206)
at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:209)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:152)
at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:114)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:184)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doGet(AbstractHTTPServlet.java:112)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:575)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:163)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:538)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:478)
at org.ops4j.pax.web.service.jetty.internal.HttpServiceServletHandler.doHandle(HttpServiceServletHandler.java:70)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:480)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:225)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:937)
at org.ops4j.pax.web.service.jetty.internal.HttpServiceContext.doHandle(HttpServiceContext.java:116)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:406)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:183)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:871)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
at org.ops4j.pax.web.service.jetty.internal.JettyServerHandlerCollection.handle(JettyServerHandlerCollection.java:72)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:110)
at org.eclipse.jetty.server.Server.handle(Server.java:346)
at org.eclipse.jetty.server.HttpConnection.handleRequest(HttpConnection.java:438)
at org.eclipse.jetty.server.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:905)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:561)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:214)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:43)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:538)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:43)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:529)
at java.lang.Thread.run(Thread.java:680)
additionally i have imported:
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.component.http.*;
import org.apache.camel.component.http.helper.*;
on ESB i have turned on camel-http
what is wrong?
--------------
So i this what i wrote is wrong, is this code below should works right?
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:osgi="http://www.springframework.org/schema/osgi"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:camel="http://camel.apache.org/schema/spring"
xmlns:cxf="http://camel.apache.org/schema/cxf"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
http://www.springframework.org/schema/osgi http://www.springframework.org/schema/osgi/spring-osgi.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
http://camel.apache.org/schema/cxf http://camel.apache.org/schema/cxf/camel-cxf.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/osgi/cxf-extension-osgi.xml" />
<bean id="cxfSSO" class="com.esb.cxf.SSO" />
<jaxrs:server id="sso" address="/ssocamel2">
<jaxrs:serviceBeans>
<ref bean="cxfSSO" />
</jaxrs:serviceBeans>
</jaxrs:server>
<camelContext xmlns="http://camel.apache.org/schema/spring">
<endpoint id="endpointURL" uri="http://localhost:8080/SSO/?token=test"/>
<route>
<from uri="direct:start"/>
<to uri="callRealWebService"/>
</route>
</camelContext>
</beans>
You need to install the camel-http feature. From the Fuse ESB console you can type:
features:install camel-http
And then after that you can install/start your bundle.
And as Ben says, what you are doing inside the rest service is totally wrong. You should setup Camel route once. If you want to call a http endpoint from Java code using Camel, then you do not need a route, but you can use a ProducerTemplate. See the Camel docs for more details.
couple of things, "No component found with scheme: http" means that you are missing the camel-http dependency in your bundle
next, you should setup your Camel context/routes once...not in a method call like this.

Persisting new Entity to existing Database JPA

I've created a database connection and some entities, now I'm trying to test the functionality of my database. I have a User entity class, which has a unique username along with some other information. Right now I'm trying to simply create a new User and Profile and map them together, then persist them. When I test the code, it successfully runs through, but the DB is not updated. Here's what I have:
package servlets;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;
import entities.Profile;
import entities.User;
#WebServlet("/NewUser")
public class NewUser extends HttpServlet {
#Resource
UserTransaction utx;
#PersistenceUnit
EntityManagerFactory emf;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String email = request.getParameter("email");
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String phone = request.getParameter("phone");
String address1 = request.getParameter("address1");
String address2 = request.getParameter("address2");
try {
utx.begin();
EntityManager em = emf.createEntityManager();
//create User & Profile
User u = new User();
u.setUsername(username);
Profile p = new Profile();
p.setUser(username);
//add email to profile's list
List<String> emails = new ArrayList<String>();
emails.add(email);
p.setEmails(emails);
//assign the profile to the user
u.setProfile(p);
//persist user to the database
em.persist(u);
utx.commit();
em.close();
emf.close();
} catch (Exception e) {
e.printStackTrace();
}
response.sendRedirect("index.jsp");
}
}
Am I doing something wrong or is the problem somewhere else in the application?
EDIT: I found the following error: Exception Description: Unable to acquire a connection from driver [null], user [null] and URL [null]. Verify that you have set the expected driver class and URL. Check your login, persistence.xml or sessions.xml resource. The jdbc.driver property should be set to a class that is compatible with your database platform
I'm not sure what to make of the error, however...I've checked my db connection and everything seems to be in order. :/
My persistence.xml file:
<?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="myPersistenceUnit" >
<jta-data-source>jdbc/mydatasource</jta-data-source>
<class>entities.User</class>
<class>entities.Profile</class>
<class>entities.Message</class>
<class>entities.Image</class>
<properties>
<property name="eclipselink.ddl-generation" value="create-tables"/>
<property name="eclipselink.ddl-generation.output-mode" value="both"/>
</properties>
</persistence-unit>
</persistence>
I have never use container managed transactions but your persistence.xml at least have.
<persistence-unit name="myPersistenceUnit" transaction-type="JTA">

Resources