Run java program with thread - java

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 !

Related

Why is my java program spinning after I hit server.stop(0)?

I wrote a basic java server class. When it handles the "shutdown" request, it calls server.stop(0) and the spins in place. Why is this happening?
I copied most of the code from this StackOverflow post.
The only significant modification to this code is that I added the server.stop(0).
Other facts: I am running this using java 8 and I am running this through IntelliJ.
package good.question.ask.questions.stackoverflow;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
public class ServerTester2
{
private HttpServer server = null;
public static void main(String[] args) throws Exception {
ServerTester2 serverTester2 = new ServerTester2();
serverTester2.start();
}
void start()
{
try {
server = HttpServer.create(new InetSocketAddress(8000), 0);
} catch (IOException e) {
e.printStackTrace();
}
server.createContext("/shutdown", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
class MyHandler implements HttpHandler
{
#Override
public void handle(HttpExchange t) throws IOException
{
String response = "This is the response";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
t.close();
System.out.println("Stopping Server...");
stop();
System.out.println("Server Stopped!");
}
}
void stop()
{
server.stop(0);
}
}
Currently, the server returns a response message to the client (I tested that using postman), and then prints "Stopping Server" to the console. After that, the server object seems to be shut down, because when I send it more requests it doesn't respond to them, however, the thread running the server continues to spin.
Minimally, I expected the server to reach this line of code
System.out.println("Server Stopped!");
but it never does.
More to the point, I expected the server thread to terminate but instead, it just spins.
Why is this happening? (Do I have a deadlock in the code somewhere?)
Is there a better way to handle server shutdown (using the httpserver library)?

Android: How to make a thread which waits for server messages and updates the UI?

i have made a java server and java client programms that communicate with TCP sockets sending String messages. Those java programs work perfectly. The client logic is that it has a UI and a thread, which is waiting all the time for new messages and updates the UI accordingly what message it recieved (e.x. add buttons,set buttons visible, change texts).
Now, im totally new to android and i want to make an equal client for android but i faced those problems:
1) I can't update the UI from a background thread just passing parameters(like java).
2) I want that one thread to update 2 or 3 Activies(i need 2-3 because the lack of screen space)
I have read about AsyncTask but they say it is recommended for sort tasks, then i read about threads with handlers but they say is difficult to work with and i got confused. So my question is what method should i use on android to achieve that "message listener/UI updater" thread.
UPDATE: Ok, i used threads and handlers and my main activity got updated, but now how i can update the second Activitie from that thread too??
well, you can start a thread for some specific time and after that check if there is any message from server, if not, restart the thread or else do your work. hope this is helpful.
you can implement it like this
package com.example.a41264.myapplication;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Created by 41264 on 04/23/17.
*/
public class Client implements Runnable{
final CopyOnWriteArrayList<MsgListener> listeners = new CopyOnWriteArrayList<>();
#Override
public void run() {
Socket socket = new Socket();
try {
int yourPort = 0;
SocketAddress address = new InetSocketAddress("your ip",yourPort);
socket.connect(address);
int your_buffer_size = 1024;
byte[] buffers = new byte[your_buffer_size];
InputStream is = socket.getInputStream();
int resultLength;
String msg;
while(true){
resultLength = is.read(buffers);
msg = new String(buffers,0,resultLength);
if(listeners.size() != 0){
for(MsgListener msgListener: listeners){
msgListener.onMsgRecived(msg);
}
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void addListener(MsgListener listener){
listeners.add(listener);
}
public void removeListener(MsgListener listener){
listeners.remove(listener);
}
public interface MsgListener{
void onMsgRecived(String msg);
}
}
and do your work at activity like this
package com.example.a41264.myapplication;
import android.app.Activity;
import android.util.Log;
/**
* Created by 41264 on 04/23/17.
*/
public class YourActivity extends Activity{
private Client client; //you need to get your clent;
private Client.MsgListener msgListener = new Client.MsgListener() {
#Override
public void onMsgRecived(final String msg) {
runOnUiThread(new Runnable() {
#Override
public void run() {
//do your own work in main thread
Log.i("tag",msg);
}
});
}
};
#Override
protected void onRestart() {
super.onRestart();
client.addListener(msgListener);
}
#Override
protected void onStop() {
super.onStop();
client.removeListener(msgListener);
}
}

Second thread is not reached

I am trying to start 2 threads, one for tcp and one for udp
package com.main;
import com.utility.HibernateUtil;
public class ServerStarter {
public static void main(String[] args) {
System.out.print("Reach 1");
Thread tcp = new Thread(new TcpServerStarter());
tcp.start();
System.out.print("Reach 2");
Thread udp = new Thread(new UdpServerStarter());
System.out.print("Reach 3");
HibernateUtil.buildSessionFactory();
System.out.print("Reach 4");
}
public static class TcpServerStarter extends Thread{
public TcpServerStarter(){
new TcpServer(8500).run();
}
}
public static class UdpServerStarter extends Thread{
public UdpServerStarter(){
new UdpServer(1000).run();
}
}
}
Only "reach 1" is printed. I read that this may occur if i have single core, however i have 2 cores.
When you call new TcpServer(8500).run(); in TcpServerStarter's constructor
It starts running the tcpServer in the MAIN thread.
I'm guessing that it just serves forever and this is why it doesn't reach any of the following code.
Also what Zbynek said : you didn't start the udp thread.
You only create udp thread but not really start it. Add this:
udp.start();
Secondly you start the loop directly from the constructor instead of run method. Change to:
public static class TcpServerStarter implements Runnable {
public void run(){
new TcpServer(8500).run();
}
}
And similarly for the UdpServerStarter.
Put the code into method called run() instead of calling it from the constructor (calling the run() will block the execution)
public static class TcpServerStarter extends Thread {
#Override
public void run() {
new TcpServer(8500).run();
}
}
public static class UdpServerStarter extends Thread {
#Override
public void run() {
new UdpServer(1000).run();
}
}
}
If the UdpServer and TcpServer already extends Thread or implements Runnable, you can start them directly by the start() method w/o creating the wrapper classes.
Without changing too much your code, this one works. I am not sure what is your specific implementation fo TcpServer or UdpServer looks like. So implemented some dummy ones for now. I see that all the print outs print as expected.
package network;
class TcpServer implements Runnable{
TcpServer(int port){
}
#Override
public void run() {
for (int i=0; i < 10; i++){
System.out.println("Thread printing:" + i + "tid:" + Thread.currentThread().getId());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class UdpServer implements Runnable{
UdpServer(int port){
}
#Override
public void run() {
for (int i=0; i < 10; i++){
System.out.println("Thread printing:" + i + "tid:" + Thread.currentThread().getId());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ServerStarter {
public static void main(String[] args) {
System.out.print("Reach 1");
Thread tcp = new Thread(new TcpServerStarter());
tcp.start();
System.out.print("Reach 2");
Thread udp = new Thread(new UdpServerStarter());
System.out.print("Reach 3");
//HibernateUtil.buildSessionFactory();
System.out.print("Reach 4");
}
public static class TcpServerStarter extends Thread{
public TcpServerStarter(){
new TcpServer(8500).run();
}
}
public static class UdpServerStarter extends Thread{
public UdpServerStarter(){
new UdpServer(1000).run();
}
}
}
A thread object must be started so that the execution of the corresponding Thread can be initiated.
I see in your code below code
System.out.print("Reach 1");
Thread tcp = new Thread(new `TcpServerStarter`());
Till now you have not yet called the tcp.start(). Till now you have created a new object of Thread.java which is OK but the main problem I feel is with the constructor of TcpServerStarter.java the code written it it prevents the flow of execution of your main method ahead.
See TcpServerStarter.java class is a Thread itself as it extends Thread.java. should override run method in your TcpServerStarter.java You Should move the code from the constructor to the run() method. Instead of creating the objects of `Thread.java modify the code as below.
Thread tcp = new `TcpServerStarter`();
Then you need to call start on the Thread object you have created.
tcp.start()
Similarly you need to modify the code including the usage of UdpServerStarter.

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

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

Categories

Resources