Apache Commons IO Tailer example - java

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);
}
}
}

Related

File Tailing not working using TailerListenerAdapter of Apache Commons io

I want to tail file contents using Java.I tried using Tailer and TailerListenerAdapter of Apache commons io. I have included storm-core-1.1.1.jar in the classpath for the required dependencies.Program compiles and runs; But the 'handle' method of TailerListenerAdapter is not called at all and the execution gets stuck inside the main method.Following is the code:
import org.apache.storm.shade.org.apache.commons.io.input.TailerListenerAdapter;
import org.apache.storm.shade.org.apache.commons.io.input.Tailer;
import org.apache.storm.shade.org.apache.commons.io.input.TailerListener;
import java.io.File;
public class LogTailTest {
/**
* TailerListener implementation.
*/
static public class ShowLinesListener extends TailerListenerAdapter {
#Override
public void handle(String line) {
System.out.println(line);
System.out.println("inside handle");
}
}
public static void main(String args[]) {
TailerListener listener = new ShowLinesListener();
File file = new File("C:/LogFiles/Radius-log");
System.out.println("inside main");
Tailer tailer = Tailer.create(file, listener);
tailer.run();
}
}
If the execution stays in the main method, then it at least means that it did not crash.
You can get further insight what is happening by implementing other methods of TailerListener interface in your show ShowLinesListener. There are methods to handle file being not present, file rotationg, generic exceptions etc.
You shouldn't call "tailer.run()" directly. Instead do:
TailerListener listener = new ShowLinesListener();
File file = new File("C:/LogFiles/Radius-log");
System.out.println("inside main");
Tailer tailer = Tailer.create(file, listener);
Thread thread = new Thread(tailer);
thread.setDaemon(true); // optional
thread.start();

netbeans: Class path in Class.forName

I wrote a chat java application that use sockets. I have three Netbeans project, 1. Client side, 2. Server side and 3.Tester.
projects Hierarchy
In the Tester I want to start a Thread for Server class.
public class Tester {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
//for (int i = 0; i<args.length; i++) {
final Class clazz = Class.forName("ServerSide");
new Thread(new Runnable() {
#Override
public void run() {
try{
Method main = clazz.getMethod("main", String[].class);
main.invoke(null, new Object[]{});
} catch(Exception e) {
// improper exception handling - just to keep it simple
}
}
}).start();
// }
}
}
but I always obtain ClassNotFoundException. Is the path wrong?
Thanks a lot. Sorry for the stupid question!
You must include also the package into the required classname parameter:
Class.forName("serverside.ServerSide");

How to clear the console for a clock system

Im currently writing a program that runs a class that implements runnable.
I have it so the time in a format of HH:MM:SS is printed to the screen every second.
Heres the code:
public class LaunchCounter
{
public static void main(String[] args)
{
//Runs the CounterThread
new CounterThread().start();
}
}
And here is the counter class
public class CounterThread implements Runnable
{
//Declare new thread
private Thread thread;
public void start()
{
thread = new Thread(this, "");
thread.start();
}
#Override
public void run()
{
//Formatter used to display just time not date
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
//never ending forloop to display time
for(int i = 1; i > 0; i++)
{
try
{
//Runtime.getRuntime().exec( "cmd /c cls" );
//Sleep for 1 second after each loop
Thread.sleep(1000);
//new calender is created
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
}
catch(Exception e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
This works perfectly fine.
What i am trying to achieve is that the line that is printed is cleared after waiting a second, and the the new time is printed and so on.
So 12:00:01 becocomes 12:00:02 with out taking a new line.
I've tried System.out.print("\b\b\b\b\b\b\b") and Runtime.getRuntime().exec( "cmd /c cls" ); But this is just printing squares to the console.
How would i achieve this?
The problem is the terminal you're using. (My guess is that you are using the terminal in your IDE.) If your output terminal doesn't do full terminal emulation, it will either ignore the \b characters or display them as unprintable characters.
I tested the following code in IntelliJ IDEA 16 and verified that \b is ignored by the built in IDEA terminal. I then tested it in the MacOS terminal and it worked the way you want it to.
package test;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class CounterThread implements Runnable {
//Declare new thread
private Thread thread;
public void start() {
thread = new Thread(this, "");
thread.start();
}
#Override
public void run() {
//Formatter used to display just time not date
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
//never ending forloop to display time
for (int i = 1; i > 0; i++) {
try {
//Runtime.getRuntime().exec( "cmd /c cls" );
//Sleep for 1 second after each loop
Thread.sleep(1000);
//new calender is created
Calendar cal = Calendar.getInstance();
System.out.print("\b\b\b\b\b\b\b\b");
System.out.print(dateFormat.format(cal.getTime()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args) throws Exception {
//Runs the CounterThread
new CounterThread().start();
final Object monitor = new Object();
synchronized (monitor) {
monitor.wait();
}
}
}
You're on the right track using Runtime.getRuntime().exec("cls");. See this post here by Holger for maybe why you're not able to clear the console.
To solve this problem, we have to invoke the command line interpreter
(cmd) and tell it to execute a command (/c cls) which allows invoking
builtin commands. Further we have to directly connect its output
channel to the Java process’ output channel, which works starting with
Java 7, using inheritIO():
import java.io.IOException;
public class CLS {
public static void main(String... arg) throws IOException, InterruptedException {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
}
}
Now when the Java process is connected to a console, i.e. has been
started from a command line without output redirection, it will clear
the console.

Run java program with thread

Good evening, I got this two programs here
httpServer.java
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicInteger;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class httpServer extends Thread {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/test", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
AtomicInteger atomicInteger = new AtomicInteger(0);
int theValue = atomicInteger.get();
#Override
public void handle(final HttpExchange t) throws IOException {
final String response;
final String requestMethod = t.getRequestMethod();
if ("GET".equals(requestMethod)) {
response = String.format("Besuche: %d%n", atomicInteger.addAndGet(1));
}
else if ("POST".equals(requestMethod)) {
atomicInteger.set(0);
response = "Reset to 0";
}
else {
throw new IOException("Unsupported method");
}
t.sendResponseHeaders(200, response.length());
final OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
Test.java
public class Test {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
Now i want that the Test.java to start working when i start the httpServer.java.
I want to achieve this with threads. I found this here online which expalins how i make a thread but i dont know how to get the Test.java to work there.
Note: I know i could write both in one programm but i want to know how to work with threads for another project im working on.
To start a thread you need to implement the run-Method. Everything inside the run-Method will be executed in a new Thread.
You did not implement a run method so the call of server.start(); does acutally nothing. With a run-Method it would look like this:
public class httpServer extends Thread
{
//Everything inside this method is executed in a new Thread
#Override
public void run()
{
super.run();
System.out.println("THIS IS EXECUTED IN A THREAD");
this.serverStuff();
}
private void serverStuff()
{
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/test", new MyHandler());
server.setExecutor(null); // creates a default executor
}
}
public class Test
{
public static void main(String[] args)
{
System.out.println("THIS IN NOT EXECUTED IN THREAD");
//This call creates a new Thread. It calls the run()-Method
new httpServer().start();
}
}
This might be useful ! But i think #Kayaman already provided an answer !

Camel Helloworld program

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);
}
}

Categories

Resources