WindowLeaked Error Android Dialog Builder during .show() method call - builder

this is my first question on Stack Overflow and is has to do with the builder pattern for an Android dialog. I recently started reading through the book Hello Android 3rd Edition to learn how to build a basic Android application. I have basic Java experience (two intro programming courses and one data structures/algorithms class all with homework in Java), but am not familiar with builder patterns or Android in general yet.
I am getting a WindowLeaked error when executing the .show() command for the alert dialog builder in the openNewGameDialog() method shown below. I broke up the method into individual calls on the builder to identify which one was the source of the error:
// Creates a selection for game difficulty
private void openNewGameDialog() {
AlertDialog.Builder builderDifficulty = new AlertDialog.Builder(this);
builderDifficulty.setTitle(R.string.new_game_title);
builderDifficulty.setItems(R.array.difficulty,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
startGame(i);
}
});
builderDifficulty.show(); // Throws an error
}
I researched the problem I am having elsewhere on this site, but for the most part it appears that people are getting problems where they have not correctly dismissed the dialog. I don't think that the same problem is occurring for me, but I am not familiar with dialogs or builders like this, so I could be mistaken. The code is taken directly from an example in the book, so I was expecting it to work properly.
I am emulating a Nexus 5 with Android 4.4.2 to test the program. Here is the error text from LogCat:
06-18 15:37:05.260: E/WindowManager(1089): android.view.WindowLeaked: Activity book.example.sudoku.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b1dfa088 V.E..... R....... 0,0-1026,684} that was originally added here
06-18 15:37:05.260: E/WindowManager(1089): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:348)
06-18 15:37:05.260: E/WindowManager(1089): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
06-18 15:37:05.260: E/WindowManager(1089): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
06-18 15:37:05.260: E/WindowManager(1089): at android.app.Dialog.show(Dialog.java:286)
06-18 15:37:05.260: E/WindowManager(1089): at android.app.AlertDialog$Builder.show(AlertDialog.java:951)
06-18 15:37:05.260: E/WindowManager(1089): at book.example.sudoku.MainActivity.openNewGameDialog(MainActivity.java:72)
06-18 15:37:05.260: E/WindowManager(1089): at book.example.sudoku.MainActivity.onClick(MainActivity.java:54)
06-18 15:37:05.260: E/WindowManager(1089): at android.view.View.performClick(View.java:4438)
06-18 15:37:05.260: E/WindowManager(1089): at android.view.View$PerformClick.run(View.java:18422)
06-18 15:37:05.260: E/WindowManager(1089): at android.os.Handler.handleCallback(Handler.java:733)
06-18 15:37:05.260: E/WindowManager(1089): at android.os.Handler.dispatchMessage(Handler.java:95)
06-18 15:37:05.260: E/WindowManager(1089): at android.os.Looper.loop(Looper.java:136)
06-18 15:37:05.260: E/WindowManager(1089): at android.app.ActivityThread.main(ActivityThread.java:5017)
06-18 15:37:05.260: E/WindowManager(1089): at java.lang.reflect.Method.invokeNative(Native Method)
06-18 15:37:05.260: E/WindowManager(1089): at java.lang.reflect.Method.invoke(Method.java:515)
06-18 15:37:05.260: E/WindowManager(1089): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
06-18 15:37:05.260: E/WindowManager(1089): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
06-18 15:37:05.260: E/WindowManager(1089): at dalvik.system.NativeStart.main(Native Method)
Any help would be appreciated!

I don't see dialogInterface.dismiss(); being called anywhere in your code. You'll probably want to add it right above startGame(i);.

Something to do with your startGame(i) method.
The code is running fine without any problem. Attached the complete code with screenshots
MainActivity.java
package com.example.userinput;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send = (Button) findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openNewGameDialog();
Log.d("MainActivity", "Inside On Click Button");
}
});
}
// Creates a selection for game difficulty
private void openNewGameDialog() {
AlertDialog.Builder builderDifficulty = new AlertDialog.Builder(this);
builderDifficulty.setTitle(R.string.new_game_title);
builderDifficulty.setItems(R.array.difficult,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//startGame(i);
Log.d("MainActivity", "Item on click");
showToast(i);
}
});
builderDifficulty.show(); // Throws an error
}
public void showToast(int i) {
Log.d("MainActivity", "Inside Toast");
Toast.makeText(getBaseContext(), "Open Dialog " + i,
Toast.LENGTH_LONG).show();
Log.d("MainActivity", "OpenDialog " + i);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}" >
<Button
android:id="#+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="40dp"
android:layout_marginTop="30dp"
android:text="OpenNewGameDialog" />
</RelativeLayout>
difficult.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="difficult">
<item>item1</item>
<item>item2</item>
<item>item3</item>
</string-array>
</resources>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">UserInput</string>
<string name="hello_world">TextView tvTi</string>
<string name="new_game_title">New Game Title</string>
</resources>

Related

XMLStreamException: ParseError at [row,col] when opening new stage (new window) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to switch from a window to another one.
This is my code:
public class SelectTypeController implements Initializable {
#FXML
private Button buttonVai;
#FXML
private ComboBox<String> comboBox;
#FXML
private AnchorPane rootPane;
#Override
public void initialize(URL location, ResourceBundle resources) {
ObservableList<String> observableListOfAccomodations = FXCollections.observableArrayList("1", "2", "3");
comboBox.setItems(observableListOfAccomodations);
buttonVai.setDisable(true);
}
#FXML
public void comboChanged() {
buttonVai.setDisable(false);
}
#FXML
public void showCrudPage() {
switch (comboBox.getValue()) {
case "3":
showCrudPageRestaurantScene();
break;
}
}
// this is giving problem
public void showCrudPageRestaurantScene() {
try {
Parent parent = FXMLLoader.load(SelectTypeController.class.getResource("/crud_restaurant.fxml"));
Stage stage = new Stage();
Scene scene = new Scene(parent);
stage.setScene(scene);
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
which manages the following fxml view
select_type.fxml
<AnchorPane
fx:id="rootPane"
xmlns:fx="http://javafx.com/fxml/1" fx:controller="controllers.SelectTypeController" maxHeight="-Infinity"
maxWidth="-Infinity"
minHeight="-Infinity" minWidth="-Infinity" prefHeight="800.0" prefWidth="1280.0"
xmlns="http://javafx.com/javafx/11.0.1">
<ImageView fitHeight="800.0" fitWidth="1280.0" pickOnBounds="true">
<Image url="images/3156482.jpg"/>
</ImageView>
<Pane layoutX="440.0" layoutY="307.0" opacity="0.8" prefHeight="200.0" prefWidth="400.0"
style="-fx-background-color: #06BCAD; -fx-background-radius: 20;"/>
<Pane layoutX="336.0" layoutY="206.0" prefHeight="336.0" prefWidth="608.0">
<Label layoutX="200.0" layoutY="29.0" text="Seleziona una tipologia">
<font>
<Font size="20.0"/>
</font>
</Label>
<Button fx:id="buttonVai" layoutX="260.0" layoutY="250.0" mnemonicParsing="false"
onMouseClicked="#showCrudPage"
style="-fx-background-color: #0078D7;" text="Vai" textFill="white"/>
</Pane>
<ComboBox fx:id="comboBox" layoutX="512.0" layoutY="371.0" prefHeight="30.0" prefWidth="292.0"
promptText="Seleziona una tipologia"
onAction="#comboChanged"/>
</AnchorPane>
I want that clicking on Vai button, I get redirected to:
public class CrudRestaurant {
#FXML
private Label labelDescription;
}
which manages
crud_restaurant.fxml
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="1080.0"
fx:controller="controllers.CrudRestaurant"
prefWidth="1920.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1">
<Label layoutX="828.0" layoutY="415.0" text="Placeholder"/>
</AnchorPane>
Unfortunately I am getting an exception:
javax.xml.stream.XMLStreamException: ParseError at [row,col]:[3,6]
and in particular:
javafx.fxml.LoadException:
/home/john/Desktop/myProject/build/resources/main/crud_restaurant.fxml
at javafx.fxml/javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2625)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2568)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2466)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3237)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3194)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3163)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3136)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3113)
at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:3106)
at controllers.SelectTypeController.showCrudPageRestaurantScene(SelectTypeController.java:60)
at controllers.SelectTypeController.showCrudPage(SelectTypeController.java:47)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at com.sun.javafx.reflect.Trampoline.invoke(MethodUtil.java:76)
at jdk.internal.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at javafx.base/com.sun.javafx.reflect.MethodUtil.invoke(MethodUtil.java:273)
at javafx.fxml/com.sun.javafx.fxml.MethodHelper.invoke(MethodHelper.java:83)
at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1784)
at javafx.fxml/javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1670)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
at javafx.graphics/javafx.scene.Scene$ClickGenerator.postProcess(Scene.java:3564)
at javafx.graphics/javafx.scene.Scene$ClickGenerator.access$8200(Scene.java:3492)
at javafx.graphics/javafx.scene.Scene$MouseHandler.process(Scene.java:3860)
at javafx.graphics/javafx.scene.Scene$MouseHandler.access$1200(Scene.java:3579)
at javafx.graphics/javafx.scene.Scene.processMouseEvent(Scene.java:1849)
at javafx.graphics/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2588)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:397)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:434)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:390)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:433)
at javafx.graphics/com.sun.glass.ui.View.handleMouseEvent(View.java:556)
at javafx.graphics/com.sun.glass.ui.View.notifyMouse(View.java:942)
at javafx.graphics/com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.gtk.GtkApplication.lambda$runLoop$11(GtkApplication.java:277)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[3,6]
Message: The processing instruction target matching "[xX][mM][lL]" is not allowed.
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:652)
at java.xml/javax.xml.stream.util.StreamReaderDelegate.next(StreamReaderDelegate.java:84)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2538)
... 51 more
How can I fix?javaf
SOLVED
I duplicated <?xml version="1.0" encoding="UTF-8"?> in crud_restaurant.fxml file. My fault.
Just remove one redundant declaration.

spring boot and camel throws direct.DirectConsumerNotAvailableException

I'm trying to get simple example of springboot and camel working but come undone. Not sure what i'm doing wrong. in the gradle build i've included so far
dependencies {
compile 'org.apache.camel:camel-spring-boot-starter:2.18.4'
compile 'org.apache.camel:camel-groovy:2.18.4'
compile 'org.apache.camel:camel-stream:2.18.4'
compile 'org.codehaus.groovy:groovy-all:2.4.11'
testCompile group: 'junit', name: 'junit', version: '4.11'
testCompile group: 'junit', name: 'junit', version: '4.12'
}
i've create a DirectRoute component like this
#Component
class DirectRoute extends RouteBuilder{
#Override
void configure () throws Exception {
from ("direct:in") //tried stream:in also
.to ("stream:out")
}
}
I then have a driver bean that try's to invoke the route
#Component
public class HelloImpl implements Hello {
#Produce(uri = "direct:in")
private ProducerTemplate template;
#Override
public String say(String value) throws ExecutionException, InterruptedException {
assert template
println "def endpoint is : " + template.getDefaultEndpoint()
return template.sendBody (template.getDefaultEndpoint(), value)
}
}
lastly in the springboot application class i added a command line runner like this, that gets my bean from the spring context, and invokes the say method. I'm using groovy so i just passed a closure to the command line runner.
#Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
//return closure to run on startup - just list the beans enabled
{args ->
println("Let's inspect the beans provided by Spring Boot:")
String[] beanNames = ctx.getBeanDefinitionNames()
Arrays.sort(beanNames)
for (String beanName : beanNames) {
println(beanName)
}
println("call the direct:start route via the service")
Hello service = ctx.getBean("helloService")
def result = service.say("William")
println "service returned : $result "
}
}
when i run my application i get all the bean names printed out (that's ok), however when i invoke the direct:in via producer template i get this error (org.apache.camel.component.direct.DirectConsumerNotAvailableException) see below.
I was expecting the route to be triggered the name sent to see that arrive in the output stream - but this is what i get.
Caused by: org.apache.camel.CamelExecutionException: Exception occurred during execution on the exchange: Exchange[ID-MONSTER-PC2-58911-1496920205300-0-2]
at org.apache.camel.util.ObjectHelper.wrapCamelExecutionException(ObjectHelper.java:1795) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.util.ExchangeHelper.extractResultBody(ExchangeHelper.java:677) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.impl.DefaultProducerTemplate.extractResultBody(DefaultProducerTemplate.java:515) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.impl.DefaultProducerTemplate.extractResultBody(DefaultProducerTemplate.java:511) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.impl.DefaultProducerTemplate.sendBody(DefaultProducerTemplate.java:163) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.ProducerTemplate$sendBody$0.call(Unknown Source) ~[na:na]
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) [groovy-all-2.4.11.jar:2.4.11]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) [groovy-all-2.4.11.jar:2.4.11]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133) [groovy-all-2.4.11.jar:2.4.11]
at services.HelloImpl.say(HelloImpl.groovy:29) ~[main/:na]
at services.Hello$say.call(Unknown Source) ~[na:na]
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) [groovy-all-2.4.11.jar:2.4.11]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) [groovy-all-2.4.11.jar:2.4.11]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125) [groovy-all-2.4.11.jar:2.4.11]
at application.Application$_commandLineRunner_closure1.doCall(Application.groovy:47) ~[main/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93) ~[groovy-all-2.4.11.jar:2.4.11]
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325) ~[groovy-all-2.4.11.jar:2.4.11]
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:294) ~[groovy-all-2.4.11.jar:2.4.11]
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022) ~[groovy-all-2.4.11.jar:2.4.11]
at groovy.lang.Closure.call(Closure.java:414) ~[groovy-all-2.4.11.jar:2.4.11]
at org.codehaus.groovy.runtime.ConvertedClosure.invokeCustom(ConvertedClosure.java:54) ~[groovy-all-2.4.11.jar:2.4.11]
at org.codehaus.groovy.runtime.ConversionHandler.invoke(ConversionHandler.java:124) ~[groovy-all-2.4.11.jar:2.4.11]
at com.sun.proxy.$Proxy44.run(Unknown Source) ~[na:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:776) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
... 10 common frames omitted
Caused by: org.apache.camel.component.direct.DirectConsumerNotAvailableException: No consumers available on endpoint: direct://in. Exchange[ID-MONSTER-PC2-58911-1496920205300-0-2]
at org.apache.camel.component.direct.DirectProducer.process(DirectProducer.java:55) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:197) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:97) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.impl.ProducerCache$1.doInProducer(ProducerCache.java:529) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.impl.ProducerCache$1.doInProducer(ProducerCache.java:497) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.impl.ProducerCache.doInProducer(ProducerCache.java:365) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.impl.ProducerCache.sendExchange(ProducerCache.java:497) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.impl.ProducerCache.send(ProducerCache.java:225) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.impl.DefaultProducerTemplate.send(DefaultProducerTemplate.java:144) ~[camel-core-2.18.4.jar:2.18.4]
at org.apache.camel.impl.DefaultProducerTemplate.sendBody(DefaultProducerTemplate.java:161) ~[camel-core-2.18.4.jar:2.18.4]
What have i done wrong - and why does the producer template invocation on 'direct:in' (also tried stream in with same problem) not work? I thought that .to("stream:out") would be a consumer.
any pointers or advice gratefully received at this point
I have an update on my problems:
I had a subpackage with the application class annotated with #SpringBootApplication. So yes, unadorned it only scans subpackages.
you can add scanBasePackages= or scanBaseClasses= parameter, however when I tried doing a scan for single class, it seemed to scan the whole directory any way and grabbed the others as well.
I refactored the app to have a single root package with subpackages and elected to set the 'scanBasePakages to the new root package. but left the Application class in its own subpackage (personal preference only - documentation suggests leaving the Application in the root package)
you can now add other classes annotated with #Configuration to generate beans or use the basic #Component.
if you create Camel routes annotated with #Component they will be auto configured in the camelContext for you.
it appears by default that Spring isnt not starting the camelContext for you. When I checked the status of the context it shows as starting and not started. so in my commandLineRunner I had to start get the spring injected camelContext and had to start it myself, and exited it when I finished. I was slightly suprised as I thought SpringBootStarter would auto start the camelContext, but it appears not.
once you have Spring component scanning etc working and you start the camelContext, then problems with the org.apache.camel.component.direct.DirectConsumerNotAvailableException exception went away and things started to work - at least the baby examples I'm trying.
So revised structure now looks like this:
The revised ApplicationClass now looks like this with some simple println output to see the state of the context, and beans in the spring ctx. The helleoService bean is still the proxy I use to setup the producer template to call the DirectRoute.
package com.softwood.application
import groovy.util.logging.Slf4j
import org.apache.camel.CamelContext
import org.springframework.beans.factory.annotation.Autowired
import com.softwood.services.Hello
/**
* Created by willw on 07/06/2017.
*/
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean
#Slf4j //inject logger
#SpringBootApplication (scanBasePackages = ["com.softwood"]) //forces scan at parent
// same as #Configuration #EnableAutoConfiguration #ComponentScan with 'defaults' e.g. sub packages
public class Application {
#Autowired
ApplicationContext ctx
#Autowired
CamelContext camelContext
public static void main(String[] args) {
SpringApplication.run(Application.class, args)
}
#Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
//return closure to run on startup - just list the beans enabled
{args ->
println("Let's inspect the beans provided by Spring Boot:")
String[] beanNames = ctx.getBeanDefinitionNames()
Arrays.sort(beanNames)
for (String beanName : beanNames) {
println(beanName)
}
/* when component scan is working - bean routes are added
automatically to camel context via springBoot, however you do have to start
the camel context, yourself
*/
println "camelCtx has following components : " + camelContext.componentNames
println "camelCtx state is : " + camelContext.status
println "starting camel context"
camelContext.start()
println "camelCtx state now is : " + camelContext.status
//log.debug "wills logging call "
println("call the direct:start route via the service")
Hello service = ctx.getBean("helloService")
def result = service.say("William")
println "service returned : $result "
println "sleep 5 seconds "
sleep (5000)
println "stop camel context"
camelContext.stop()
println "camelCtx state now is : " + camelContext.status
}
}
}
That proxy is just registered as a simple bean like this in the spring context
package com.softwood.services
/**
* Created by willw on 07/06/2017.
*/
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate
import org.springframework.stereotype.Component;
import java.util.concurrent.ExecutionException
#Component
public class HelloImpl implements Hello {
#Produce(uri = "direct:in") /* ?block=true */
private ProducerTemplate template
#Override
public String say(String value) throws ExecutionException, InterruptedException {
assert template
println "def endpoint is : " + template.getDefaultEndpoint()
//Future future = template.asyncSendBody(template.getDefaultEndpoint(), value)
//return future.get()
return template.sendBody (template.getDefaultEndpoint(), value)
}
}
The TimedRoute just sorts itself out with no template required to invoke in
package com.softwood.camelRoutes
/**
* Created by willw on 07/06/2017.
*/
import org.apache.camel.builder.RouteBuilder
import org.springframework.stereotype.Component
#Component
class TimedRoute extends RouteBuilder {
#Override
void configure () throws Exception {
from ("timer:foo")
.to ("log:com.softwood.application.Application?level=WARN")
}
}
My simple no-op file route isn't working (yet) and not sure why. I suspect I've not got the file config right somehow; some playing is required.
package com.softwood.camelRoutes
import org.apache.camel.builder.RouteBuilder
import org.springframework.stereotype.Component
/**
* Created by willw on 08/06/2017.
*/
#Component
class FileNoOpRoute extends RouteBuilder{
#Override
void configure () throws Exception {
from ("file:../com.softwood.file-inbox?recursive=true&noop=true&idempotent=true")
.to ("file:../com.softwood.file-outbox")
}
}
However the basics are not working and least camel is doing something whereas before I just had the exception and nothing.
I have found another question on Spring config highlighting some of the above also.

JavaCV record video in Android

I want to record video quiet and without preview in Android. So I choice MediaRecorder but I could record only without preview but what make me crazy is that when MediaRecorder start or stop it will with a sound dee.... I try many methods about that . But I think it perhaps sth related to the OS of the mobile. So I try JavaCV because I also want to have a Live function in my app.
But JavaCV spent me to too much time to solve some strange problems because it's my first time to do sth about C++ src and video.
Just compile group: 'org.bytedeco', name: 'javacv-platform', version: '1.3' as the README.md ,I even can't build my apk.
Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK org/bytedeco/javacpp/macosx-x86_64/libusb-1.0.dylib
File1: /Users/wyx/.gradle/caches/modules-2/files-2.1/org.bytedeco.javacpp-presets/libfreenect/0.5.3-1.3/736d65a3ef042258429d8e7742128c411806b432/libfreenect-0.5.3-1.3-macosx-x86_64.jar
File2: /Users/wyx/.gradle/caches/modules-2/files-2.1/org.bytedeco.javacpp-presets/libdc1394/2.2.4-1.3/f1498dacc46162ab68faeb8d66cf02b96fe41c61/libdc1394-2.2.4-1.3-macosx-x86_64.jar
And then I modified it according this issuse
use this to repalce. It can build the apk. But the can't run.
android {
..............
packagingOptions {
exclude 'META-INF/services/javax.annotation.processing.Processor'
pickFirst 'META-INF/maven/org.bytedeco.javacpp-presets/opencv/pom.properties'
pickFirst 'META-INF/maven/org.bytedeco.javacpp-presets/opencv/pom.xml'
pickFirst 'META-INF/maven/org.bytedeco.javacpp-presets/ffmpeg/pom.properties'
pickFirst 'META-INF/maven/org.bytedeco.javacpp-presets/ffmpeg/pom.xml'
}
}
dependencies {
compile group: 'org.bytedeco', name: 'javacv', version: '1.3'
compile group: 'org.bytedeco.javacpp-presets', name: 'ffmpeg', version: '3.2.1-1.3', classifier: 'android-x86'
compile group: 'org.bytedeco.javacpp-presets', name: 'ffmpeg', version: '3.2.1-1.3', classifier: 'android-arm'
compile group: 'org.bytedeco.javacpp-presets', name: 'opencv', version: '3.1.0-1.3', classifier: 'android-x86'
compile group: 'org.bytedeco.javacpp-presets', name: 'opencv', version: '3.1.0-1.3', classifier: 'android-arm'
}
My demo code VideoService which will invoke in MainActivity
package com.fs.fs.api;
import com.fs.fs.App;
import com.fs.fs.utils.DateUtils;
import com.fs.fs.utils.FileUtils;
import org.bytedeco.javacpp.avcodec;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.FrameRecorder;
import java.util.Date;
/**
* Created by wyx on 2017/1/11.
*/
public class VideoService {
private FFmpegFrameRecorder mFrameRecorder;
private String path;
private VideoService() {
}
private static class SingletonHolder {
private static final VideoService INSTANCE = new VideoService();
}
public static VideoService getInstance() {
return SingletonHolder.INSTANCE;
}
public void startRecordVideo() {
String fileName = String.format("%s.%s", DateUtils.date2String(new Date(), "yyyyMMdd_HHmmss"), "mp4");
path = FileUtils.getExternalFullPath(App.getInstance(), fileName);
mFrameRecorder = new FFmpegFrameRecorder(path, 640, 480, 1);
mFrameRecorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
mFrameRecorder.setVideoOption("tune", "zerolatency");
mFrameRecorder.setVideoOption("preset", "ultrafast");
mFrameRecorder.setVideoOption("crf", "28");
mFrameRecorder.setVideoBitrate(300 * 1000);
mFrameRecorder.setFormat("mp4");
mFrameRecorder.setFrameRate(30);
mFrameRecorder.setAudioOption("crf", "0");
mFrameRecorder.setSampleRate(48 * 1000);
mFrameRecorder.setAudioBitrate(960 * 1000);
mFrameRecorder.setAudioCodec(avcodec.AV_CODEC_ID_AAC);
try {
mFrameRecorder.start();
} catch (FrameRecorder.Exception e) {
e.printStackTrace();
}
}
public void stop() {
if (mFrameRecorder != null) {
try {
mFrameRecorder.stop();
mFrameRecorder.release();
} catch (FrameRecorder.Exception e) {
e.printStackTrace();
}
mFrameRecorder = null;
}
}
}
MainActivity
package com.fs.fs.activity;
import android.app.Activity;
import android.os.Bundle;
import com.fs.fs.R;
import com.fs.fs.api.VideoService;
import static java.lang.Thread.sleep;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VideoService.getInstance().startRecordVideo();
try {
sleep(10 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
VideoService.getInstance().stop();
}
}
Error which make me want to cry.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.fs.fs, PID: 30259
java.lang.NoClassDefFoundError: java.lang.ClassNotFoundException: org.bytedeco.javacpp.avutil
at org.bytedeco.javacpp.Loader.load(Loader.java:590)
at org.bytedeco.javacpp.Loader.load(Loader.java:530)
at org.bytedeco.javacpp.avcodec$AVPacket.<clinit>(avcodec.java:1694)
at org.bytedeco.javacv.FFmpegFrameRecorder.<init>(FFmpegFrameRecorder.java:149)
at com.fs.fs.api.VideoService.startRecordVideo(VideoService.java:34)
at com.fs.fs.activity.MainActivity.onCreate(MainActivity.java:75)
at android.app.Activity.performCreate(Activity.java:5304)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1090)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2331)
at android.app.ActivityThread.access$1000(ActivityThread.java:143)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5291)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: org.bytedeco.javacpp.avutil
at java.lang.Class.classForName(Native Method)
at java.lang.Class.forName(Class.java:251)
at org.bytedeco.javacpp.Loader.load(Loader.java:585)
at org.bytedeco.javacpp.Loader.load(Loader.java:530) 
at org.bytedeco.javacpp.avcodec$AVPacket.<clinit>(avcodec.java:1694) 
at org.bytedeco.javacv.FFmpegFrameRecorder.<init>(FFmpegFrameRecorder.java:149) 
at com.fs.fs.api.VideoService.startRecordVideo(VideoService.java:34) 
at com.fs.fs.activity.MainActivity.onCreate(MainActivity.java:75) 
at android.app.Activity.performCreate(Activity.java:5304) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1090) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2245) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2331) 
at android.app.ActivityThread.access$1000(ActivityThread.java:143) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5291) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.NoClassDefFoundError: org/bytedeco/javacpp/avutil
at java.lang.Class.classForName(Native Method) 
at java.lang.Class.forName(Class.java:251) 
at org.bytedeco.javacpp.Loader.load(Loader.java:585) 
at org.bytedeco.javacpp.Loader.load(Loader.java:530) 
at org.bytedeco.javacpp.avcodec$AVPacket.<clinit>(avcodec.java:1694) 
at org.bytedeco.javacv.FFmpegFrameRecorder.<init>(FFmpegFrameRecorder.java:149) 
at com.fs.fs.api.VideoService.startRecordVideo(VideoService.java:34) 
at com.fs.fs.activity.MainActivity.onCreate(MainActivity.java:75) 
at android.app.Activity.performCreate(Activity.java:5304) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1090) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2245) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2331) 
at android.app.ActivityThread.access$1000(ActivityThread.java:143) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5291) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.ClassNotFoundException: Didn't find class "org.bytedeco.javacpp.avutil" on path: DexPathList[[zip file "/data/app/com.fs.fs-2.apk"],nativeLibraryDirectories=[/data/app-lib/com.fs.fs-2, /vendor/lib, /system/lib, /data/datalib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
at java.lang.Class.classForName(Native Method) 
at java.lang.Class.forName(Class.java:251) 
at org.bytedeco.javacpp.Loader.load(Loader.java:585) 
at org.bytedeco.javacpp.Loader.load(Loader.java:530) 
at org.bytedeco.javacpp.avcodec$AVPacket.<clinit>(avcodec.java:1694) 
at org.bytedeco.javacv.FFmpegFrameRecorder.<init>(FFmpegFrameRecorder.java:149) 
at com.fs.fs.api.VideoService.startRecordVideo(VideoService.java:34) 
at com.fs.fs.activity.MainActivity.onCreate(MainActivity.java:75) 
at android.app.Activity.performCreate(Activity.java:5304) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1090) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2245) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2331) 
at android.app.ActivityThread.access$1000(ActivityThread.java:143) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5291) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665) 
at dalvik.system.NativeStart.main(Native Method) 
So I want to know a comfortable method to achieve my goal : recode video quiet and without preview. And Live real time ?
I found ffmpeg4android is a prefect library to run ffmpeg command. I just use it to compress videos from MediaRecorder But I don't how to do use it to achieve my goal.

Writing java based JMS Client for WildFly10

I writing java based JMS Client for WildFly10 and I had problem
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
props.put(Context.PROVIDER_URL, WILDFLY_REMOTING_URL); // NOTICE: "http- remoting" and port "8080"
props.put(Context.SECURITY_PRINCIPAL, JMS_USERNAME);
props.put(Context.SECURITY_CREDENTIALS, JMS_PASSWORD);
//props.put("jboss.naming.client.ejb.context", true);
context = new InitialContext(props);
i run your client code and i got this error:
Got initial Context: javax.naming.InitialContext#5442a311
Exception in thread “main” org.jboss.naming.remote.protocol.NamingIOException: Failed to lookup [Root exception is java.io.IOException: java.lang.ClassNotFoundException: org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory]
at org.jboss.naming.remote.client.ClientUtil.namingException(ClientUtil.java:49)
at org.jboss.naming.remote.protocol.v1.Protocol$1.execute(Protocol.java:104)
at org.jboss.naming.remote.protocol.v1.RemoteNamingStoreV1.lookup(RemoteNamingStoreV1.java:95)
at org.jboss.naming.remote.client.HaRemoteNamingStore$1.operation(HaRemoteNamingStore.java:276)
at org.jboss.naming.remote.client.HaRemoteNamingStore.namingOperation(HaRemoteNamingStore.java:137)
at org.jboss.naming.remote.client.HaRemoteNamingStore.lookup(HaRemoteNamingStore.java:272)
at org.jboss.naming.remote.client.RemoteContext.lookup(RemoteContext.java:87)
at org.jboss.naming.remote.client.RemoteContext.lookup(RemoteContext.java:129)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at com.almasprocess.model.bl.WildFlyJmsQueueSender.init(WildFlyJmsQueueSender.java:49)
at com.almasprocess.model.bl.WildFlyJmsQueueSender.main(WildFlyJmsQueueSender.java:43)
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:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.io.IOException: java.lang.ClassNotFoundException: org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory
at org.jboss.naming.remote.protocol.v1.Protocol$1$3.read(Protocol.java:159)
at org.jboss.naming.remote.protocol.v1.Protocol$1$3.read(Protocol.java:149)
at org.jboss.naming.remote.protocol.v1.BaseProtocolCommand.readResult(BaseProtocolCommand.java:59)
at org.jboss.naming.remote.protocol.v1.Protocol$1.handleClientMessage(Protocol.java:149)
at org.jboss.naming.remote.protocol.v1.RemoteNamingStoreV1$MessageReceiver$1.run(RemoteNamingStoreV1.java:232)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:340)
at org.jboss.marshalling.AbstractClassResolver.loadClass(AbstractClassResolver.java:131)
at org.jboss.marshalling.AbstractClassResolver.resolveClass(AbstractClassResolver.java:112)
at org.jboss.marshalling.river.RiverUnmarshaller.doReadClassDescriptor(RiverUnmarshaller.java:1002)
at org.jboss.marshalling.river.RiverUnmarshaller.doReadNewObject(RiverUnmarshaller.java:1256)
at org.jboss.marshalling.river.RiverUnmarshaller.doReadObject(RiverUnmarshaller.java:276)
at org.jboss.marshalling.river.RiverUnmarshaller.doReadObject(RiverUnmarshaller.java:209)
at org.jboss.marshalling.AbstractObjectInput.readObject(AbstractObjectInput.java:41)
at org.jboss.naming.remote.protocol.v1.Protocol$1$3.read(Protocol.java:156)
… 7 more
Process finished with exit code 1
And I changed code like this and add activemq lib in my project:
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY,"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
props.put(Context.PROVIDER_URL, WILDFLY_REMOTING_URL); // NOTICE: "http-remoting" and port "8080"
props.put(Context.SECURITY_PRINCIPAL, JMS_USERNAME);
props.put(Context.SECURITY_CREDENTIALS, JMS_PASSWORD);
and i got this error :
Got initial Context: javax.naming.InitialContext#6842775d
Exception in thread "main" javax.naming.NameNotFoundException: jms/RemoteConnectionFactory
at org.apache.activemq.jndi.ReadOnlyContext.lookup(ReadOnlyContext.java:225)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at com.almasprocess.model.bl.WildFlyJmsQueueSender.init(WildFlyJmsQueueSender.java:49)
at com.almasprocess.model.bl.WildFlyJmsQueueSender.main(WildFlyJmsQueueSender.java:43)
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:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
and standalone-full.xml config file like this :
<subsystem xmlns="urn:jboss:domain:messaging-activemq:1.0">
<server name="default">
<security-setting name="#">
<role name="guest" send="true" consume="true" create-non-durable-queue="true" delete-non-durable-queue="true"/>
</security-setting>
<address-setting name="#" dead-letter-address="jms.queue.DLQ" expiry-address="jms.queue.ExpiryQueue" max-size-bytes="10485760" page-size-bytes="2097152" message-counter-history-day-limit="10"/>
<http-connector name="http-connector" socket-binding="http" endpoint="http-acceptor"/>
<http-connector name="http-connector-throughput" socket-binding="http" endpoint="http-acceptor-throughput">
<param name="batch-delay" value="50"/>
</http-connector>
<in-vm-connector name="in-vm" server-id="0"/>
<http-acceptor name="http-acceptor" http-listener="default"/>
<http-acceptor name="http-acceptor-throughput" http-listener="default">
<param name="batch-delay" value="50"/>
<param name="direct-deliver" value="false"/>
</http-acceptor>
<in-vm-acceptor name="in-vm" server-id="0"/>
<jms-queue name="ExpiryQueue" entries="java:/jms/queue/ExpiryQueue"/>
<jms-queue name="DLQ" entries="java:/jms/queue/DLQ"/>
<jms-queue name="clickQueue" entries="java:/jms/queue/clickQueue java:/jboss/exported/jms/queue/clickQueue"/>
<jms-queue name="emailQueue" entries="java:/jms/queue/EmailQueue java:/jboss/exported/jms/queue/EmailQueue"/>
<jms-queue name="emailSendQueue" entries="java:/jboss/exported/jms/queue/EmailSendQueue"/>
<connection-factory name="InVmConnectionFactory" entries="java:/ConnectionFactory" connectors="in-vm"/>
<connection-factory name="RemoteConnectionFactory" entries="java:jboss/exported/jms/RemoteConnectionFactory" connectors="http-connector"/>
<pooled-connection-factory name="activemq-ra" entries="java:/JmsXA java:jboss/DefaultJMSConnectionFactory" connectors="in-vm" transaction="xa"/>
</server>
</subsystem>
can you help me about error???
thanks.
Working example:
public class JMSClient {
private static final String INITIAL_CONTEXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory";
private static final String PROVIDER_URL = "http-remoting://127.0.0.1:8080";
private static final String CONNECTION_FACTORY = "jms/RemoteConnectionFactory";
private static final String DESTINATION = "topic/irisWebBroadcaster";
private static final String USERNAME = "jmsuser";
private static final String PASSWORD = "qqq";
public static void main(String[] args) {
Context namingContext = null;
JMSContext context = null;
try {
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, PROVIDER_URL);
env.put(Context.SECURITY_PRINCIPAL, USERNAME);
env.put(Context.SECURITY_CREDENTIALS, PASSWORD);
namingContext = new InitialContext(env);
ConnectionFactory connectionFactory = (ConnectionFactory) namingContext.lookup(CONNECTION_FACTORY);
Destination destination = (Destination) namingContext.lookup(DESTINATION);
context = connectionFactory.createContext(USERNAME, PASSWORD);
JMSProducer producer = context.createProducer();
producer.send(destination, "TEST");
} catch (Exception e) {
// print error messge
} finally {
if (namingContext != null) {
try {
namingContext.close();
} catch (NamingException e) {
// print error messge
}
}
if (context != null) {
context.close();
}
}
}
}
Corresponding classpath (maybe excessive):
[WILDFLY10_DIR]/modules/system/layers/base/javax/annotation/api/main/jboss-annotations-api_1.2_spec-1.0.0.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/javax/servlet/api/main/jboss-servlet-api_3.1_spec-1.0.0.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/javax/ejb/api/main/jboss-ejb-api_3.2_spec-1.0.0.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/javax/enterprise/api/main/cdi-api-1.2.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/log4j/logmanager/main/log4j-jboss-logmanager-1.1.2.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/javax/inject/api/main/javax.inject-1.jar
[WILDFLY10_DIR]/modules/system/layers/base/javax/ws/rs/api/main/jboss-jaxrs-api_2.0_spec-1.0.0.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/javax/jms/api/main/jboss-jms-api_2.0_spec-1.0.0.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/codehaus/jackson/jackson-core-asl/main/jackson-core-asl-1.9.13.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/codehaus/jackson/jackson-mapper-asl/main/jackson-mapper-asl-1.9.13.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/logging/main/jboss-logging-3.3.0.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/logmanager/main/jboss-logmanager-2.0.3.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/remote-naming/main/jboss-remote-naming-2.0.4.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/xnio/main/xnio-api-3.3.4.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/xnio/nio/main/xnio-nio-3.3.4.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/remoting/main/jboss-remoting-4.0.18.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/marshalling/main/jboss-marshalling-1.4.10.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/marshalling/river/main/jboss-marshalling-river-1.4.10.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/apache/activemq/artemis/main/artemis-jms-client-1.1.0.wildfly-011.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/apache/activemq/artemis/main/artemis-core-client-1.1.0.wildfly-011.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/apache/activemq/artemis/main/artemis-commons-1.1.0.wildfly-011.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/apache/activemq/artemis/main/artemis-selector-1.1.0.wildfly-011.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/apache/commons/beanutils/main/commons-beanutils-1.9.2.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/apache/commons/collections/main/commons-collections-3.2.2.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/slf4j/jcl-over-slf4j/main/jcl-over-slf4j-1.7.7.jbossorg-1.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/slf4j/main/slf4j-api-1.7.7.jbossorg-1.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/slf4j/impl/main/slf4j-jboss-logmanager-1.0.3.GA.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/ejb-client/main/jboss-ejb-client-2.1.4.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/io/netty/main/netty-all-4.0.32.Final.jar
You can add something like this if you have problems with logging:
InternalLoggerFactory.setDefaultFactory(new Log4JLoggerFactory());
PropertyConfigurator.configure("conf/log4j.properties");
I see that Answer given by Rudik is not yet accepted , hence posting my take on this problem.
Test case
#Test
public void sendMessagesToWildfly10() throws IOException, NamingException {
String Message = "Hello, World!";
String connectionFactoryJNDIName = "jms/RemoteConnectionFactory";
String queueName = "jms/queue/TestQueue";
Context namingContext = null;
JMSContext context = null;
try {
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY,"org.jboss.naming.remote.client.InitialContextFactory");
env.put(Context.PROVIDER_URL, "http-remoting://localhost:8470");
// Below May Not be needed if you have turned off the security for Messaging
env.put(Context.SECURITY_PRINCIPAL, "guest");
env.put(Context.SECURITY_CREDENTIALS, "guest");
namingContext = new InitialContext(env);
ConnectionFactory connectionFactory = (ConnectionFactory) namingContext.lookup(connectionFactoryJNDIName);
Destination destination = (Destination) namingContext.lookup(queueName);
context = connectionFactory.createContext("userName", "password");
JMSProducer producer = context.createProducer();
for (int i = 0; i < 10; i++) {
producer.send(destination, Message+" - "+i);
}
JMSConsumer consumer = context.createConsumer(destination);
for (int i = 0; i < 10; i++) {
String text = consumer.receiveBody(String.class, 5000);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (namingContext != null) {
namingContext.close();
}
if (context != null) {
context.close();
}
}
}
You will require below mentioned Jars/dependencies added to your classpath. Most of them you can find in Wildfly/modules
If a JMS client is running within a WildFly application then the org.apache.activemq.artemis module must be added as a dependency on your deployment to avoid the java.lang.ClassNotFoundException: org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory, e.g. as answered here.
Otherwise ( standalone java application) - the jboss-client.jar needs to be included into class-path.
Note: take the jboss-client.jar based on your target WildFly version because it differs between WildFLy 8 and 10.

Problem using MockRoundtrip class

I have following code:
#Test
public void testSaveValid() throws Exception {
MockRoundtrip trip = new MockRoundtrip(mockServletContext,
ContactFormActionBean.class, mockSession);
trip.setParameter("contact.email", "test#test.com");
trip.setParameter("contact.phoneNumber", "654-456-4567");
trip.execute("save");
ContactFormActionBean bean =
trip.getActionBean(ContactFormActionBean.class);
assertEquals(0,
bean.getContext().getValidationErrors().size());
PhoneNumber pn = bean.getContact().getPhoneNumber();
assertEquals("654", pn.getAreaCode());
assertEquals("456", pn.getPrefix());
assertEquals("4567", pn.getSuffix());
assertTrue(
trip.getDestination().startsWith("/ContactList.action"));
}
I encounter this error:
net.sourceforge.stripes.exception.StripesServletException: Unhandled exception in exception handler.
at net.sourceforge.stripes.exception.DefaultExceptionHandler.handle(DefaultExceptionHandler.java:158)
at net.sourceforge.stripes.controller.StripesFilter.doFilter(StripesFilter.java:249)
at net.sourceforge.stripes.mock.MockFilterChain.doFilter(MockFilterChain.java:63)
at net.sourceforge.stripes.mock.MockServletContext.acceptRequest(MockServletContext.java:255)
at net.sourceforge.stripes.mock.MockRoundtrip.execute(MockRoundtrip.java:195)
at net.sourceforge.stripes.mock.MockRoundtrip.execute(MockRoundtrip.java:207)
at stripesbook.test.stripesmock.ContactFormActionBeanTest.testSaveValid(ContactFormActionBeanTest.java:96)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
If I delete
trip.setParameter("contact.email", "test#test.com");
trip.setParameter("contact.phoneNumber", "654-456-4567");
I won't get any errors but will get following message from jUnit:
java.lang.AssertionError: expected:<0> but was:<1>
which seems logical.
This is my ContactFormActionBean class
public class ContactFormActionBean extends ContactBaseActionBean {
private static final String FORM="/WEB-INF/jsp/contact_form.jsp";
#DefaultHandler
public Resolution form() {
return new ForwardResolution(FORM);
}
public Resolution save() {
Contact contact = getContact();
contact.setUser(getUser());
contactDao.save(contact);
contactDao.commit();
getContext().getMessages().add(
getLocalizableMessage("contactSaved", contact)
);
return new RedirectResolution(ContactListActionBean.class);
}
#ValidationMethod(on="save")
public void validateEmailUnique(ValidationErrors errors) {
String email = getContact().getEmail();
Contact other = contactDao.findByEmail(email, getUser());
if (other != null && !other.equals(getContact())) {
errors.add("contact.email", new LocalizableError(
getClass().getName()+".contactEmailAlreadyUsed", other));
}
}
}
Why this error happens?
[ADDED]
This is my Setup() function where I configure mockServletContext before running any test functions:
...
private static MockServletContext mockServletContext;
private static MockHttpSession mockSession;
#BeforeClass
public static void setup() throws Exception {
mockServletContext = new MockServletContext("webmail");
Map<String,String> params = new HashMap<String,String>();
params.put("ActionResolver.Packages", "stripesbook.action");
params.put("Extension.Packages", "stripesbook.ext,"
+ "net.sourceforge.stripes.integration.spring");
mockServletContext.addFilter(StripesFilter.class,
"StripesFilter", params);
mockServletContext.setServlet(DispatcherServlet.class,
"DispatcherServlet", null);
mockSession = new MockHttpSession(mockServletContext);
mockServletContext.addInitParameter("contextConfigLocation",
"/WEB-INF/applicationContext-test.xml");
ContextLoaderListener springContextLoader =
new ContextLoaderListener();
springContextLoader.contextInitialized(
new ServletContextEvent(mockServletContext));
// Load mock user
MockRoundtrip trip = new MockRoundtrip(mockServletContext,
MockDataLoaderActionBean.class, mockSession);
trip.execute();
// Login mock user
trip = new MockRoundtrip(mockServletContext,
LoginActionBean.class, mockSession);
trip.setParameter("username", "freddy");
trip.setParameter("password", "nadia");
trip.execute("login");
}
...
I think there could be some config problems cause when I remove
<classpathentry kind="src" path="src/main/webapp" />
from class path I get different error :
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/applicationContext-test.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext-test.xml]
There seems to be a Stripes configuration problem.
Did you configure the mockServletContext correctly?
U tried with Spring ?
I have done it with :
Object test= springContextListener.getContextLoader().getCurrentWebApplicationContext().getBean("MyActionBean");
annoted your class with : #RunWith(SpringJUnit4ClassRunner.class)
concerning org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/applicationContext-test.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext-test.xml]
add :
#RunWith(SpringJUnit4ClassRunner.class to your test Class
and add Spring-test Jar to your project.
recheck the line : filterParams.put("ActionResolver.Packages", "yourapplicationpackagesPath.action");

Resources