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.
Related
I had to take a break from working on my react native app for a couple of months and when i came back to work on it again i couldn't boot anything up and i am getting a load of React Native Navigation errors...
I dont really know where to start with this, i have made some changes to the java files but nothing seems to get me out of this hole...
the error is below... if anyone knows how to deal with this i would be really greatful
error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081
C:\git\BattleBuddy\android\app\src\main\java\com\battlebuddy\MainActivity.java:3: error: package com.reactnativenavigation does not exist
import com.reactnativenavigation.NavigationActivity;
^
C:\git\BattleBuddy\android\app\src\main\java\com\battlebuddy\MainActivity.java:5: error: cannot find symbol
public class MainActivity extends NavigationActivity {
^
symbol: class NavigationActivity
C:\git\BattleBuddy\android\app\src\main\java\com\battlebuddy\MainApplication.java:21: error: package com.reactnativenavigation does not exist
import com.reactnativenavigation.NavigationApplication;
^
C:\git\BattleBuddy\android\app\src\main\java\com\battlebuddy\MainApplication.java:22: error: package com.reactnativenavigation.react does not exist
import com.reactnativenavigation.react.NavigationReactNativeHost;
^
C:\git\BattleBuddy\android\app\src\main\java\com\battlebuddy\MainApplication.java:27: error: cannot find symbol
public class MainApplication extends NavigationApplication {
^
symbol: class NavigationApplication
C:\git\BattleBuddy\android\app\src\main\java\com\battlebuddy\MainApplication.java:29: error: cannot find symbol
new NavigationReactNativeHost(this) {
^
symbol: class NavigationReactNativeHost
location: class MainApplication
C:\git\BattleBuddy\android\app\src\main\java\com\battlebuddy\MainApplication.java:47: error: method does not override or implement a method from a supertype
#Override
^
C:\git\BattleBuddy\android\app\src\main\java\com\battlebuddy\MainApplication.java:51: error: method does not override or implement a method from a supertype
#Override
^
C:\git\BattleBuddy\android\app\src\main\java\com\battlebuddy\MainApplication.java:53: error: cannot find symbol
super.onCreate();
^
symbol: variable super
location: class MainApplication
C:\git\BattleBuddy\android\app\src\main\java\com\battlebuddy\MainApplication.java:54: error: cannot find symbol
initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
^
symbol: method initializeFlipper(MainApplication,ReactInstanceManager)
location: class MainApplication
FAILURE: Build failed with an exception.
What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
Compilation failed; see the compiler error output for details.
This is from the build.gradle
buildscript {
ext {
buildToolsVersion = "28.0.3"
minSdkVersion = 19
compileSdkVersion = 28
targetSdkVersion = 27
supportLibVersion = "28.0.0"
RNNKotlinVersion = "1.3.61" // Or any version above 1.3.x
RNNKotlinStdlib = "kotlin-stdlib-jdk8"
}
repositories {
google()
mavenLocal()
mavenCentral()
jcenter()
maven { url "$rootDir/../node_modules/react-native/android" }
maven { url 'https://maven.google.com' }
// ADD THIS
maven { url "https://www.jitpack.io" }
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.61"
classpath 'com.android.tools.build:gradle:3.6.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
this if from the app build.gradle
dependencies {
implementation project(':#react-native-community_async-storage')
implementation project(':react-native-linear-gradient')
implementation project(':react-native-image-crop-picker')
implementation project(':react-native-vector-icons')
implementation "androidx.appcompat:appcompat:1.0.0"
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
implementation "com.facebook.react:react-native:+" // From node_modules
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.android.support:design:27.1.0'
}
This is the mainapp
public class MainApplication extends NavigationApplication {
private final ReactNativeHost mReactNativeHost =
new NavigationReactNativeHost(this) {
#Override
public boolean isDebug() {
return BuildConfig.DEBUG;
}
#Override
protected List<ReactPackage> getPackages() {
#SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
return packages;
}
#Override
protected String getJSMainModuleName() {
return "index";
}
};
#Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
#Override
public void onCreate() {
super.onCreate();
initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
}
main activigty just looks like this
package com.battlebuddy;
import com.reactnativenavigation.NavigationActivity;
public class MainActivity extends NavigationActivity {
}
If there is anything you can think of that would help a lot
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.
My goal is to call succesfully a WebService in activity process.
I'm working with Servicemix 5.0.0. I started with example apache-servicemix-5.0.0/examples/activiti/activiti-camel , which I run succesfully via features:install.
Then I modified file OrderProcess.bpmn.xml and the main process in it looks like below now:
<process id="OrderProcess" isExecutable="true">
<startEvent id="start"/>
<sequenceFlow id="flow1" sourceRef="start" targetRef="Call_WS"/>
<serviceTask id="Call_WS" name="Call WS" activiti:class="org.apache.servicemix.examples.activiti.WsDelegate" >
<extensionElements>
<activiti:field name="wsdl" expression="http://localhost:8282/dodawanie?wsdl" />
<activiti:field name="operation" expression="sayHi" />
<activiti:field name="parameters" expression="${arg0}" />
<activiti:field name="returnValue" expression="sayHiResponse" />
</extensionElements>
</serviceTask>
<sequenceFlow id="flow2" sourceRef="Call_WS" targetRef="end"/>
<endEvent id="end"/>
</process>
I use the class WsDelegate I found as a sample to help calling WebService from activiti process, and it looks like below:
package org.apache.servicemix.examples.activiti;
import java.util.ArrayList;
import java.util.StringTokenizer;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.Expression;
import org.activiti.engine.delegate.JavaDelegate;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import javax.xml.namespace.*;
public class WsDelegate implements JavaDelegate {
private Expression wsdl;
private Expression operation;
private Expression parameters;
private Expression returnValue;
public void execute(DelegateExecution execution) throws Exception {
String wsdlString = (String)wsdl.getValue(execution);
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
Client client = dcf.createClient(wsdlString);
ArrayList paramStrings = new ArrayList();
if (parameters!=null) {
StringTokenizer st = new StringTokenizer( (String)parameters.getValue(execution), ",");
while (st.hasMoreTokens()) {
paramStrings.add(st.nextToken().trim());
}
}
Object response = client.invoke((String)operation.getValue(execution), paramStrings.toArray(new Object[0]));
if (returnValue!=null) {
String returnVariableName = (String) returnValue.getValue(execution);
execution.setVariable(returnVariableName, response);
}
}
}
I modified example class ActivitiRouteBuilder and this is the code after modification:
package org.apache.servicemix.examples.activiti;
import static org.activiti.camel.ActivitiProducer.PROCESS_KEY_PROPERTY;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.Exchange;
import org.apache.camel.Handler;
import org.apache.camel.Message;
import org.apache.camel.builder.RouteBuilder;
/**
* Camel routes that interact with the business process defined in the
* OSGI-INF/activiti/OrderProcess.bpmn20.xml file
*/
public class ActivitiRouteBuilder extends RouteBuilder {
private final Helper helper = new Helper();
#Override
public void configure() throws Exception {
/*
* This route will start a new OrderProcess instance. Using the PROCESS_KEY_PROPERTY, we are assigning a
* business key to our process to allow for easier correlation in later processing steps. We are also
* sending a Map containing additional variables to add to the process instance.
*/
from("jetty:http://0.0.0.0:8484/test")
.setBody(bean(helper))
.setProperty(PROCESS_KEY_PROPERTY, simple("file:name"))
.to("activiti:OrderProcess")
.log("Process to handle incoming order file has been started (process instance id ${body})");
/*
* This route will notify a running OrderProcess of an order delivery event. Here too, we are setting the
* PROCESS_KEY_PROPERTY to correlate the delivery message with right order process instance.
*/
from("file:var/activiti-camel/delivery")
.log("Notifying process about delivery for order ${file:name}")
.setProperty(PROCESS_KEY_PROPERTY, simple("file:name"))
.to("activiti:OrderProcess:receiveDelivery");
/*
* The BPMN process can also trigger Camel routes as part of the process. In these routes, the variables that
* you added to the process are available as Exchange properties. The next two routes will be triggered while
* processing the order and the order delivery.
*/
from("activiti:OrderProcess:processOrder")
.log("Processing order ${property.orderid} created on ${property:timestamp}")
.log(" original message: ${property.message}");
from("activiti:OrderProcess:processDelivery")
.log("Processing delivery for order ${property.orderid} created on ${property:timestamp}")
.log(" original message: ${property.message}");
}
/*
* A few helper methods used for routing
*/
public static final class Helper {
/*
* This method will extract information from the Exchange (using Camel annotations) and put them in a
* Map that will be used for setting up the process' variables.
*/
#Handler
public Map getProcessVariables(Exchange exchange) {
Message in = exchange.getIn();
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("message", "pusto");
variables.put("orderid", in.getHeader("id"));
variables.put("timestamp", "teraz");
return variables;
}
}
}
And when I try to start the process through calling http://localhost:8484/test
i get this stack trace:
org.apache.camel.CamelExecutionException: Exception occurred during execution on the exchange: Exchange[Message: {timestamp=teraz, message=pusto, orderid=null}]
at org.apache.camel.util.ObjectHelper.wrapCamelExecutionException(ObjectHelper.java:1379)
at org.apache.camel.impl.DefaultExchange.setException(DefaultExchange.java:283)
at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:64)
at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:110)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:72)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:398)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:118)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:80)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.component.jetty.CamelContinuationServlet.service(CamelContinuationServlet.java:151)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:806)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:652)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1320)
at org.eclipse.jetty.servlets.MultiPartFilter.doFilter(MultiPartFilter.java:119)
at org.apache.camel.component.jetty.CamelFilterWrapper.doFilter(CamelFilterWrapper.java:44)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1291)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:443)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1044)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:372)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:978)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
at org.eclipse.jetty.server.Server.handle(Server.java:363)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:486)
at org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:926)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:988)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:640)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:235)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:628)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:52)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.NoClassDefFoundError: Ljavax/xml/namespace/QName;
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Class.java:2308)
at java.lang.Class.getDeclaredFields(Class.java:1760)
at com.sun.xml.bind.v2.model.nav.ReflectionNavigator.getDeclaredFields(ReflectionNavigator.java:274)
at com.sun.xml.bind.v2.model.nav.ReflectionNavigator.getDeclaredFields(ReflectionNavigator.java:57)
at com.sun.xml.bind.v2.model.impl.ClassInfoImpl.findFieldProperties(ClassInfoImpl.java:377)
at com.sun.xml.bind.v2.model.impl.ClassInfoImpl.getProperties(ClassInfoImpl.java:308)
at com.sun.xml.bind.v2.model.impl.RuntimeClassInfoImpl.getProperties(RuntimeClassInfoImpl.java:176)
at com.sun.xml.bind.v2.model.impl.ModelBuilder.getClassInfo(ModelBuilder.java:243)
at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:100)
at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:81)
at com.sun.xml.bind.v2.model.impl.ModelBuilder.getClassInfo(ModelBuilder.java:209)
at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:95)
at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:81)
at com.sun.xml.bind.v2.model.impl.ModelBuilder.getTypeInfo(ModelBuilder.java:315)
at com.sun.xml.bind.v2.model.impl.ModelBuilder.getTypeInfo(ModelBuilder.java:330)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:466)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.(JAXBContextImpl.java:302)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1140)
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:154)
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:121)
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:202)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:143)
at javax.xml.bind.ContextFinder.find(ContextFinder.java:310)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:446)
at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:393)
at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:240)
at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:233)
at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:188)
at org.apache.servicemix.examples.activiti.WsDelegate.execute(WsDelegate.java:22)
at org.activiti.engine.impl.delegate.JavaDelegateInvocation.invoke(JavaDelegateInvocation.java:34)
at org.activiti.engine.impl.delegate.DelegateInvocation.proceed(DelegateInvocation.java:37)
at org.activiti.engine.impl.delegate.DefaultDelegateInterceptor.handleInvocation(DefaultDelegateInterceptor.java:25)
at org.activiti.engine.impl.bpmn.behavior.ServiceTaskJavaDelegateActivityBehavior.execute(ServiceTaskJavaDelegateActivityBehavior.java:49)
at org.activiti.engine.impl.bpmn.behavior.ServiceTaskJavaDelegateActivityBehavior.execute(ServiceTaskJavaDelegateActivityBehavior.java:40)
at org.activiti.engine.impl.bpmn.helper.ClassDelegate.execute(ClassDelegate.java:115)
at org.activiti.engine.impl.pvm.runtime.AtomicOperationActivityExecute.execute(AtomicOperationActivityExecute.java:44)
at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:80)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:546)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:541)
at org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerStart.eventNotificationsCompleted(AtomicOperationTransitionNotifyListenerStart.java:52)
at org.activiti.engine.impl.pvm.runtime.AbstractEventAtomicOperation.execute(AbstractEventAtomicOperation.java:56)
at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:80)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:546)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:541)
at org.activiti.engine.impl.pvm.runtime.AbstractEventAtomicOperation.execute(AbstractEventAtomicOperation.java:49)
at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:80)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:546)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:541)
at org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionCreateScope.execute(AtomicOperationTransitionCreateScope.java:49)
at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:80)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:546)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:541)
at org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerTake.execute(AtomicOperationTransitionNotifyListenerTake.java:65)
at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:80)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:546)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:541)
at org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionDestroyScope.execute(AtomicOperationTransitionDestroyScope.java:115)
at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:80)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:546)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:541)
at org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionNotifyListenerEnd.eventNotificationsCompleted(AtomicOperationTransitionNotifyListenerEnd.java:36)
at org.activiti.engine.impl.pvm.runtime.AbstractEventAtomicOperation.execute(AbstractEventAtomicOperation.java:56)
at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:80)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:546)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:541)
at org.activiti.engine.impl.pvm.runtime.AbstractEventAtomicOperation.execute(AbstractEventAtomicOperation.java:49)
at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:80)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:546)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:541)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.take(ExecutionEntity.java:381)
at org.activiti.engine.impl.bpmn.behavior.BpmnActivityBehavior.performOutgoingBehavior(BpmnActivityBehavior.java:102)
at org.activiti.engine.impl.bpmn.behavior.BpmnActivityBehavior.performDefaultOutgoingBehavior(BpmnActivityBehavior.java:51)
at org.activiti.engine.impl.bpmn.behavior.FlowNodeActivityBehavior.leave(FlowNodeActivityBehavior.java:44)
at org.activiti.engine.impl.bpmn.behavior.FlowNodeActivityBehavior.execute(FlowNodeActivityBehavior.java:36)
at org.activiti.engine.impl.pvm.runtime.AtomicOperationActivityExecute.execute(AtomicOperationActivityExecute.java:44)
at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:80)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:546)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:541)
at org.activiti.engine.impl.pvm.runtime.AtomicOperationProcessStartInitial.eventNotificationsCompleted(AtomicOperationProcessStartInitial.java:46)
at org.activiti.engine.impl.pvm.runtime.AbstractEventAtomicOperation.execute(AbstractEventAtomicOperation.java:56)
at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:80)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:546)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:541)
at org.activiti.engine.impl.pvm.runtime.AtomicOperationProcessStart.eventNotificationsCompleted(AtomicOperationProcessStart.java:45)
at org.activiti.engine.impl.pvm.runtime.AbstractEventAtomicOperation.execute(AbstractEventAtomicOperation.java:56)
at org.activiti.engine.impl.interceptor.CommandContext.performOperation(CommandContext.java:80)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperationSync(ExecutionEntity.java:546)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:541)
at org.activiti.engine.impl.persistence.entity.ExecutionEntity.start(ExecutionEntity.java:335)
at org.activiti.engine.impl.cmd.StartProcessInstanceCmd.execute(StartProcessInstanceCmd.java:72)
at org.activiti.engine.impl.cmd.StartProcessInstanceCmd.execute(StartProcessInstanceCmd.java:31)
at org.activiti.engine.impl.interceptor.CommandExecutorImpl.execute(CommandExecutorImpl.java:24)
at org.activiti.engine.impl.interceptor.CommandContextInterceptor.execute(CommandContextInterceptor.java:42)
at org.activiti.engine.impl.interceptor.JtaTransactionInterceptor.execute(JtaTransactionInterceptor.java:59)
at org.activiti.engine.impl.interceptor.LogInterceptor.execute(LogInterceptor.java:33)
at org.activiti.engine.impl.RuntimeServiceImpl.startProcessInstanceByKey(RuntimeServiceImpl.java:55)
at Proxyf138e743_9da0_45a4_be4e_6b2c8e65cd48.startProcessInstanceByKey(Unknown Source)
at org.activiti.camel.ActivitiProducer.startProcess(ActivitiProducer.java:93)
at org.activiti.camel.ActivitiProducer.process(ActivitiProducer.java:48)
at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)
... 32 more
Caused by: java.lang.ClassNotFoundException: javax.xml.namespace.QName
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
... 137 more
What should I do to make it run?
It looks like your application bundle have some trouble to load the class javax.xml.namespace.QName. can you double check you bundle import packages?
Today the illumination API was released and I tried to make a simple app of showing of a blink of the illumination bar upon click of a button. I just copy-pasted the code in the sony developers website, but it gives error that, there is no acitivity to handle this intent START_LED.
Here's the main_activity:
package com.example.myillumin;
import com.sonyericsson.illumination.IlluminationIntent;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1= (Button) findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
Intent intent=new Intent(IlluminationIntent.ACTION_START_LED);
intent.putExtra(IlluminationIntent.EXTRA_LED_COLOR,0xFFFF0000);
intent.putExtra(IlluminationIntent.EXTRA_PACKAGE_NAME, "com.example.myillumin");
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
And here's the manifest file I tried to modify seeing other posts of stackoverflow.
<uses-permission android:name="com.sonyericsson.illumination.permission.ILLUMINATION"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.myillumin.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.sonyericsson.illumination.IlluminationIntent"
android:label="#string/activity_name"
android:exported="false">
<intent-filter>
<action android:name="com.sonyericsson.illumination.intent.action.START_LED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
Please help me out :(
The illumination bar API uses a 'service' to change the colors of the bar, so you have to start a Service not an Activity.
So, in your code,
Intent intent=new Intent(IlluminationIntent.ACTION_START_LED);
intent.putExtra(IlluminationIntent.EXTRA_LED_COLOR,0xFFFF0000);
intent.putExtra(IlluminationIntent.EXTRA_PACKAGE_NAME, "com.example.myillumin");
startActivity(intent);
instead of starting an activity with the intent, try starting a service with the created Intent. From:
startActivity(intent);
change to
startService(intent);
You can also check whether the device supports the API by calling:
Intent checkIntent = new Intent(IlluminationIntent.ACTION_STOP_LED);
if (null == getPackageManager().resolveService(checkIntent,
PackageManager.GET_RESOLVED_FILTER)) {
// Not supported
}
In order to start the illumination service you must provide the intent with certain mandatory fields, you already have IlluminationIntent.EXTRA_PACKAGE_NAME and IlluminationIntent.ACTION_START_LED so now u need to add IlluminationIntent.EXTRA_LED_ID, therefore, inside the onClick method Add the line:
intent.putExtra(IlluminationIntent.EXTRA_LED_ID, IlluminationIntent.VALUE_BUTTON_2);
Since it is a service, you need to change:
startActivity(intent);
And replace it with:
startService(intent);
I'm trying to generate graphs using JFreeChart. I added record in web.xml, installed jfreechart library. Compiled servlet. Below code of servlet has shown:
import java.io.IOException;
import java.io.OutputStream;
import java.io.File;
import javax.servlet.*;
import javax.servlet.http.*;
import java.awt.Color;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
public class diagram extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doTestPieChart(request,response);
}
protected void doTestPieChart(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
OutputStream out = response.getOutputStream();
try
{
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("Graphic Novels", 192);
dataset.setValue("History", 125);
dataset.setValue("Military Fiction", 236);
dataset.setValue("Mystery", 547);
dataset.setValue("Performing Arts", 210);
dataset.setValue("Science, Non-Fiction", 70);
dataset.setValue("Science Fiction", 989);
JFreeChart chart = ChartFactory.createPieChart(
"Books by Type",
dataset,
true,
false,
false
);
chart.setBackgroundPaint(Color.white);
response.setContentType("image/png");
ChartUtilities.writeChartAsPNG(out, chart, 400, 300);
/*
ServletContext sc = getServletContext();
String filename = sc.getRealPath("pie.png");
File file = new File(filename);
ChartUtilities.saveChartAsPNG(file,chart,400,300);
*/
}
catch (Exception e)
{
System.out.println(e.toString());
}
finally
{
out.close();
}
}
}
When i launch the servlet, mistake has shown :
HTTP Status 500 -
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Error instantiating servlet class diagram
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
java.lang.Thread.run(Thread.java:619)
root cause
java.lang.NoClassDefFoundError: org/jfree/data/general/PieDataset
java.lang.Class.getDeclaredConstructors0(Native Method)
java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
java.lang.Class.getConstructor0(Class.java:2699)
java.lang.Class.newInstance0(Class.java:326)
java.lang.Class.newInstance(Class.java:308)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
java.lang.Thread.run(Thread.java:619)
root cause
java.lang.ClassNotFoundException: org.jfree.data.general.PieDataset
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1484)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1329)
java.lang.ClassLoader.loadClassInternal(ClassLoader.java:316)
java.lang.Class.getDeclaredConstructors0(Native Method)
java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
java.lang.Class.getConstructor0(Class.java:2699)
java.lang.Class.newInstance0(Class.java:326)
java.lang.Class.newInstance(Class.java:308)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
java.lang.Thread.run(Thread.java:619)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.24 logs.
Help me to solve a problem. and where is problem?
Make sure you have JFreeChart jar inside your
WEB-INF/lib
directory or your WAR deployment file.