Camel Helloworld program - java

package com.camel;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class FirstRoute {
public static void main(String args []) throws Exception{
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
#Override
public void configure() throws Exception {
from("file:C:\\workspace\\input?noop=true").process(new strong textProcessor() {
#Override
public void process(Exchange arg0) throws Exception {
System.out.println("hello camel!");
}
}).to("file:C:\\workspace\\output").end();
}
});
context.start();
Thread.sleep(1000);
context.stop();
}
}
This is my first camel program. looks like every thing is correct. but the file transfer is not happening.
I added
camel conext 2.12.1 jar
camel core 2.12.1 jar
camel ftp 2.12.1 jar
slf4j api 1.7.6 jar

increase the sleep time to get the result correctly.
That 1000 ms is not enough to copy the files from input directory to output directory.
That sleep time specifies a time limit to copy files from input to output. if you increase sleep time context will copy more files from input to output directory

Usually when Camel is used as a standalone application, you should use Main provided by Camel. I have posted the code from their site :
public class MainExample {
private Main main;
public static void main(String[] args) throws Exception {
MainExample example = new MainExample();
example.boot();
}
public void boot() throws Exception {
// create a Main instance
main = new Main();
// enable hangup support so you can press ctrl + c to terminate the JVM
main.enableHangupSupport();
// bind MyBean into the registery
main.bind("foo", new MyBean());
// add routes
main.addRouteBuilder(new MyRouteBuilder());
// run until you terminate the JVM
System.out.println("Starting Camel. Use ctrl + c to terminate the JVM.\n");
main.run();
}
private static class MyRouteBuilder extends RouteBuilder {
#Override
public void configure() throws Exception {
from("timer:foo?delay=2000")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
System.out.println("Invoked timer at " + new Date());
}
})
.beanRef("foo");
}
}
public static class MyBean {
public void callMe() {
System.out.println("MyBean.calleMe method has been called");
}
}
}
Refer http://camel.apache.org/running-camel-standalone-and-have-it-keep-running.html for more details.

context.start();
Thread.sleep(10000);
context.stop();
Change this piece of code to give time for camel to move the file.

Your code return some exception?
The problem can be the timeout 1000 is equals 1 second, is a very short time for copy a file, you can try, up the value of timeout or remove.
Follow an example without timeout:
This Class create a RouteBuilder
public class CamelRoute extends RouteBuilder {
#Override
public void configure() throws Exception {
from("file:/opt/files-camel?noop=true")
.routeId("file-in")
.choice()
.when(header(Exchange.FILE_NAME).endsWith(".xml"))
.to("file:/opt/files-camel/xml?noop=true")
.when(header(Exchange.FILE_NAME).endsWith(".txt"))
.to("file:/opt/files-camel/txt?noop=true")
.end()
.end();
}
}
This Class run a RouteBuilder
public class Launcher {
public static void main(String... args) throws Exception {
Main main = new Main();
main.addRouteBuilder(new CamelRoute());
main.run(args);
}
}

Related

Open Task manager and handle its multiple tabs using Java code

I want to open Task Manager and click on its tabs like 'Process','Performance','App history', etc. by using core java only.
Tried to begin with
public class Desktop1 {
public static void main(String[] args) throws IOException {
Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"Taskmgr.exe");
}
}
Exception in thread "main" java.io.IOException: Cannot run program "C:\WINDOWS\system32\Taskmgr.exe": CreateProcess error=740, The requested operation requires elevation
There are multiple ways of achieving this. The simplest way is mentioned by #mkane in his comment. Programatically, this could be achieved in the following way:
Add following dependency to your application:
<dependency>
<groupId>com.vnetpublishing.java</groupId>
<artifactId>super-user-application</artifactId>
<version>0.0.5</version>
</dependency>
Now you can make your class extend SuperUserApplication class and override its run() as:
public int run(String[] strings) {
try {
Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"Taskmgr.exe");
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
Now call static run(...) of class SU passing in the instance of the class extending SuperUserApplication. Here is a complete example for your reference:
public class Main extends SuperUserApplication {
public static void main(String[] args) {
SU.run(new Main(), args);
}
// #Override
public int run(String[] strings) {
try {
Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"Taskmgr.exe");
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
}

My Apache Camel Processor is Not Working

I am trying to use an Apache Camel interface called a Processor and am running into some difficulties. I was expected the messages to 1) be sent to the ActiveMQ queues in the JBoss Fuse application server, 2) be processed by the Camel Processor, and then 3) be sent to a different Queue specified in the source-code. What happens now is that the SOP statements in main print and some error messages on Logging but nothing is sent to the queues from the program.
Here is my code:
/* create a Camel processor */
package foo;
import org.apache.camel.Processor;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
public class MyOwnProcessor implements Processor {
//main
public static void main(String[] args) {
System.out.println("Starting main method in MyOwnProcessor.java");
RouteBuilder builder = new RouteBuilder() {
public void configure() {
from("QueueA").processRef("MyOwnProcessor").to("QueueB");
}
};
System.out.println("main is done.");
} //end main
public void process(Exchange exchange) {
System.out.println("Hello the process was executed.");
String s = exchange.getIn().getBody(String.class);
exchange.getIn().setBody("The body of the message is: " + s);
} //end process method
} //end class
Here is the current output:
Starting main method in MyOwnProcessor.java
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
main is done.
Try this,
public static void main(String args[]) throws Exception {
// create CamelContext
CamelContext context = new DefaultCamelContext();
// connect to embedded ActiveMQ JMS broker
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
"tcp://localhost:61616");
context.addComponent("jms",
JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));
// add our route to the CamelContext
context.addRoutes(new RouteBuilder() {
#Override
public void configure() {
from("jms:queue:QueueA")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
String s = exchange.getIn().getBody(String.class);
System.out.println("The body of the message is: " + s);
}
}).to("jms:queue:QueueB");
}
});
// start the route and let it do its work
context.start();
Thread.sleep(10000);
// stop the CamelContext
context.stop();
}
Creating a route isn't going to cause it to run -- you still need a running CamelContext, and it needs to be passed a message in order to get things started. Try getting this to work first, just using an anonymous inner class for your Processor:
public static void main(String[] args) throws Exception {
CamelContext context = new DefaultCamelContext();
RouteBuilder builder = new RouteBuilder() {
public void configure() {
from("direct:source").process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
System.out.println("Success!");
}
});
}
};
context.addRoutes(builder);
ProducerTemplate template = context.createProducerTemplate();
context.start();
template.sendBody("direct:source", "test");
}
Once that works, add a separate class that implements Processor and use that instead of the anonymous inner class.

JavaFX Application keeps running even if i have an error in my main class static initializer

Keeps running:
package app;
import javafx.application.Application;
import javafx.stage.Stage;
public class Test extends Application {
static {
throwAnException();
}
#Override
public void start(Stage primaryStage) throws Exception {
}
public static void main(String[] args) {
launch(args);
}
private static void throwAnException() {
throw new RuntimeException();
}
}
Stops:
package app;
import javafx.application.Application;
import javafx.stage.Stage;
public class Test extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
}
public static void main(String[] args) {
throwAnException();
launch(args);
}
private static void throwAnException() {
throw new RuntimeException();
}
}
Why?
In the first case the program keeps running, even with the exception.
In the second case the program stops before calling the javafx thread.
The static initializer should run before the main method, right?
My english is vary bad so i didn't write much.
I hope you understand my question.
This is kind of a cheap answer
It keeps running because there are 4(3) other Threads running ..
when you exit/close/shutdown your application through stop() you kill it the right way, also i think, the main Thread is triggered after the stop() method so if you have an exception there, it pretty much happens after the show, if you throw the exception in the init() method the app shutdowns for real - the init() method starts two additional threads..
replace this and see
static {
new Thread(new Runnable() {
#Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("There are "+ Thread.activeCount()+" still running");
}
}
}).start();
throwAnException();
}

Apache Commons IO Tailer example

I am working on a monitoring program that reads the /var/log/auth.log file. I am using Apache Commons IO Tailer class to read the file in real time. To get started, I wanted to test the real-time reading part on a simple file, and manually enter some code in the console line. Here is my code:
public class Main {
public static void main(String[] args) {
TailerListener listener = new MyListener();
Tailer tailer = Tailer.create(new File("log.txt"), listener, 500);
while(true) {
}
}
}
public class MyListener extends TailerListenerAdapter {
#Override
public void handle(String line) {
System.out.println(line);
}
}
And from the terminal : sudo echo "Hello" >> log.txt
The problem is when I try to write manually something in the file, it does not print it in the console. I tried to find a concrete example of usage of Tailer class, but no luck. What am I doing wrong here?
Based on my testing, Tailer will only print a line when you've added a newline to the file. So try sudo echo "Hello\n" >> log.txt
Also note that if you call create, you start a thread but have no handle on it. Hence why you had to have a while/true loop.
You could try this instead:
public static void main(String[] args) {
TailerListener listener = new MyListener();
Tailer tailer = new Tailer(new File("log.txt"), listener, 500);
tailer.run();
}
Your code should work. For me, this does works as expected.
package de.lhorn.stackoverflowplayground;
import java.io.File;
import org.apache.commons.io.input.Tailer;
import org.apache.commons.io.input.TailerListenerAdapter;
public class App {
private static final int SLEEP = 500;
public static void main(String[] args) throws Exception {
App app = new App();
app.run();
}
private void run() throws InterruptedException {
MyListener listener = new MyListener();
Tailer tailer = Tailer.create(new File("/tmp/log.txt"), listener, SLEEP);
while (true) {
Thread.sleep(SLEEP);
}
}
public class MyListener extends TailerListenerAdapter {
#Override
public void handle(String line) {
System.out.println(line);
}
}
}

RMI multithread skeleton

My application use rmi for serve client request to manipulate data on a database (using JDBC). I would like that skeleton run a thread for each client's operation request. I need just to to something like
public MySkeleton implement MyInterface {
public string method1() {
myThread.start();
}
or something else?
You don't need to do anything special whatsoever, the RMI framework takes care of spinning off new threads automatically for you. Try it with the simplest server possible, you will see that every time a new client connects it is always able to connect to the server straightaway:
public interface Server extends java.rmi.Remote {
void doIt () throws java.rmi.RemoteException;
}
public class ServerImpl extends java.rmi.server.UnicastRemoteObject implements Server {
public ServerImpl() throws java.rmi.RemoteException {
super();
}
public void doIt () {
System.out.println ("Starting in " + Thread.currentThread().getName());
try { Thread.sleep(10000); } catch(InterruptedException t) {}
System.out.println ("Stopping in " + Thread.currentThread().getName());
}
public static void main (String[] argv) throws Exception {
java.rmi.registry.LocateRegistry.createRegistry(1099);
java.rmi.Naming.rebind ("//localhost/Server", new ServerImpl ());
}
}
public class Client {
public static void main(String[] argv) throws Exception {
((Server) java.rmi.Naming.lookup("Server")).doIt();
}
}
I would like that skeleton run a thread for each client's operation request.
RMI already does that.
I need just to to something like
No you don't. Just write the method normally. RMI will multithread it for you.

Categories

Resources