I want to execute a class method that is present in another file. I am doing the following:
import java.io.IOException;
public class run_java_program {
public static void main(String[] args) {
try {
Process process = Runtime.getRuntime().exec("java -cp C:\\Users\\96171\\eclipse-workspace\\IR_Project\\src test");
} catch (IOException e) {
e.printStackTrace();
}
}
}
But its not working. However on the cmd it is:
I tried replacing C:\\Users\\96171\\eclipse-workspace\\IR_Project\\src with C:/Users/96171/eclipse-workspace/IR_Project/src but still nothing is printed out to the console.
Here is the other program:
//import py4j.GatewayServer;
public class test {
public static void addNumbers(int a, int b) {
System.out.print(a + b);
}
// public static void addNumbers(int a, int b) {
// System.out.print(a + b);
// }
public static void main(String[] args) {
// GatewayServer gatewayServer = new GatewayServer(new test());
// gatewayServer.start();
// System.out.println("Gateway Server Started");
test t = new test();
t.addNumbers(5, 6);
}
}
The outputstream of the executed program test would become the inputstream for your current program run_java_program. Change your code to this and try:
import java.io.IOException;
public class run_java_program {
public static void main(String[] args) {
try {
Process process = Runtime.getRuntime().exec("java -cp C:\\Users\\96171\\eclipse-workspace\\IR_Project\\src test");
java.util.Scanner s = new java.util.Scanner(process.getInputStream());
System.out.println(s.nextLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
I used Scanner as I know it returns only one line. Based on your need you can also use apache common utils.
Related
I want to send a String to a Telnet Connection using TelnetConnection from Apache
import java.io.IOException;
import org.apache.commons.net.telnet.TelnetClient;
public class TestClass {
public static void main(String[] args) throws IOException, InterruptedException {
String telnetServer = "123.456.789.123";
int telnetPort = 32106;
TelnetClient telnet = new TelnetClient();
try {
telnet.connect(telnetServer, telnetPort);
String start = "start";
telnet.getOutputStream().write(start.getBytes());
telnet.getOutputStream().flush();
System.out.println(telnet.getInputStream());
} catch (Exception e) {
System.out.println(e);
}finally {
telnet.disconnect();
}
}
}
However, I don't get a result. How do I use Input and Output Stream in this case?
The command ("start") should start the recording of METUS INGEST 5.6.
Thanks to Some programmer dude(https://stackoverflow.com/users/440558/some-programmer-dude). This totally did the job.
Here is the complete code:
import java.io.IOException;
import org.apache.commons.net.telnet.TelnetClient;
public class TestClass {
public static void main(String[] args) throws IOException, InterruptedException {
String telnetServer = "123.456.789.123";
int telnetPort = 32106;
TelnetClient telnet = new TelnetClient();
try {
telnet.connect(telnetServer, telnetPort);
String start = "start\r\n";
telnet.getOutputStream().write(start.getBytes());
telnet.getOutputStream().flush();
System.out.println(telnet.getInputStream());
} catch (Exception e) {
System.out.println(e);
}finally {
telnet.disconnect();
}
}
}
You can stop the recording of all sources with:
String stop = "stop\r\n";
telnet.getOutputStream().write(stop.getBytes());
telnet.getOutputStream().flush();
I use sandboxed Nashorn like this:
ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine(
new String[]{"--no-java", "--no-syntax-extensions", "--optimistic-types=true", "--language=es6"},
null);
But I want to use a single particular class in my javascript. How to do that?
For example, I have a class:
class MyClass
{
public void m1()
{
System.out.println("This is m1");
}
public void m2()
{
System.out.println("This is m2");
}
}
And I want to use it in the script like
let a=new MyClass();
a.m1();
a.m2();
How to do that?
Thank you
you can use Bindings to provide java objects to the ScriptEngine:
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
public class MyClass {
public static void main(String[] args) {
ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine(
new String[]{"--no-java", "--no-syntax-extensions", "--optimistic-types=true", "--language=es6"},
null);
Bindings bindings = engine.createBindings();
bindings.put("myclass", new MyClass());
engine.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
String code = "myclass.m1();";
try {
engine.eval(code, bindings);
} catch (ScriptException e) {
e.printStackTrace();
}
}
public void m1() {
System.out.println("This is m1");
}
public void m2(String str) {
System.out.println("This is m2 " + str);
}
public void m3(Class claz) {
System.out.println(claz);
}
}
or if MyClass really needs to be instantiated in the JS code you could do (works with Java >=9):
Bindings bindings = engine.createBindings();
bindings.put("myclass", StaticClass.forClass(MyClass.class));
var code = "var a = new myclass(); a.m1();";
try {
engine.eval(code, bindings);
} catch (ScriptException e) {
e.printStackTrace();
}
I am trying to print stack walker in exception block but it is displaying only current class
public class Test1 {
public void test() throws Exception{
Test2 test2 = new Test2();
test2.test();
}
}
public class Test2 {
public void test() throws Exception{
System.out.println(1/0);
}
}
public class TestStackWalker {
public static void main(String[] args) {
Test1 test1 = new Test1();
try {
test1.test();
} catch (Exception e) {
StackWalker stack = StackWalker.getInstance();
stack.forEach(System.out::println);
}
}
}
From StackWalker docs :
The walk method opens a sequential stream of StackFrames for the current thread and then applies the given function to walk the StackFrame stream.
Since you are calling it from your main method - there is only one StackFrame allocated and is being printed :
TestStackWalker.main(TestStackWalker.java:10)
If you want have access to each stack element of you exception's stack trace - use Throwable::getStackTrace which returns array of StackTraceElement :
class TestStackWalker {
public static void main(String[] args) {
Test1 test1 = new Test1();
try {
test1.test();
} catch (Exception e) {
Arrays.stream(e.getStackTrace()).forEach(System.out::println);
}
}
}
which will print :
Test2.test(Test2.java:3)
Test1.test(Test1.java:4)
TestStackWalker.main(TestStackWalker.java:7)
If you want only to print it Throwable::printStackTrace should be enough.
Is there a way to save the whole console output to a file when multithreading? I'm working with 5 threads. I had this idea that i can put a printstream in the run-method.
example:
public void run() {
try{
PrintStream out = new PrintStream(file);
stopExecute stop = new stopExecute();
Thread t = new Thread(stop);
Scanner in = new Scanner(System.in);
t.start();
while (!in.hasNextLine())
{
classThatUsingMultipleThrads();
System.out.println("Finished");
anotherClassThatUsingThreads();
System.out.println("Finished");
}
System.out.prinln("User stopped the execution");
stop.keepRunning = false;
System.setOut(out);
}
catch(IOException e){System.out.println(e);}
Problem here is that it's only saving the output "User stoped the execution" and everything in the whileloop are not saved. Or the outputstream from other classes.
I've tried to put the
System.setOut(out);
in the while-loop, but didn't help.
Edit: Spell correction
try {
System.setOut(new PrintStream(new File("output-file.txt")));
}
catch (Exception e) {
e.printStackTrace();
}
thanks to: System.out to a file in java
You should probably look into using a logging library such as Log4J. However you could also use something like a TeeOutputStream. This type of output stream writes to 2 other streams when called. A few libraries have great implementations but you can also write one yourself. I whipped this one up real quick.
You could set the output stream for your entire program in your main method to use this TeePrintStream, then all calls to System.out.* will write data to the usual System.out and your FileOutputStream.
Theres also an implementation of the TeePrintStream here http://www.java2s.com/Code/Java/File-Input-Output/TeePrintStreamteesallPrintStreamoperationsintoafileratherliketheUNIXtee1command.htm
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
public class SO34042494 {
public static void main(String[] args) throws FileNotFoundException {
System.setOut(new TeePrintStream(System.out, new FileOutputStream(new File("x:\\output.txt"))));
System.out.println("Check check");
System.out.println("1");
System.out.println(2);
System.out.println(3L);
}
public static class TeePrintStream extends PrintStream {
private final OutputStream tee;
public TeePrintStream(PrintStream original, OutputStream tee) {
super(original);
this.tee = tee;
}
#Override
public void write(byte[] b) throws IOException {
super.write(b);
tee.write(b);
}
#Override
public void write(byte[] buf, int off, int len) {
super.write(buf, off, len);
try {
tee.write(buf, off, len);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
#Override
public void write(int b) {
super.write(b);
try {
tee.write(b);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
#Override
public synchronized void close() {
try {
tee.close();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
super.close();
}
}
}
}
The TeePrintStream I have here is something I just threw together, please if your going to use this in a production project polish it up and test it thoroughly
Okej i think i solved it. In my main i just did like this:
public static void main(String[] args) {
Prinstream out = new Prinststream(file);
/*
Do some things like start threads, call objects etc..
.
.
.
.
*/
System.setOut(out);
I think that when all threads are started and doing their things(i do assign a object to each thread) the printstream will catch every console-output that occurs in other classes.
This didn't work before i edited my stopExecute class.
public class stopExecute implements Runnable {
Scanner scan = new Scanner(System.in);
private Object[] obj;
public stopExecute(Object[] obj)
{
this.obj = obj;
}
public void run() {
while(true){
stop();
}
}
public void stop() {
if(scan.hasNextLine()){
System.out.println("Stopped");
System.exit(0);
}
}
}
Thank you for your help guys. I will look into your suggestions and try them. In this solution i'm unable to use Log4J. But i will definitely check it out.
I'm trying to stop a java thread from a different class, but unable to figure out. I have looked into the below links, googled a lot from past 2 days but unable to nail down. May be a simple thing which i need to change but i'm out of options and hence posting it here.
Referred Links
java external threads (outside the class file it's used)
http://tutorials.jenkov.com/java-concurrency/creating-and-starting-threads.html
http://www.java2novice.com/java_thread_examples/
While typing the question, I referred the below links as well..
Stop a thread from outside
Below is my code sample. I'm able to start the WorkerThread from the MainThread and get into the loop. But unable to stop the thread started using the StopThread class.
I've also used the volatile option suggested in the below link.
http://tutorials.jenkov.com/java-concurrency/volatile.html
I feel I'm making a simple mistake, but not able to identify it.
//class WorkerThread
package main;
public class WorkerThread implements Runnable
{
public WorkerThread() {
isRunning = true;
}
public WorkerThread(boolean False) {
isRunning = False;
}
private volatile boolean isRunning;
public synchronized void stopThread() {
isRunning = false;
}
public synchronized boolean IsThreadRunning() {
return isRunning;
}
#Override
public void run()
{
int i = 1;
while(isRunning)
{
System.out.println("Loop " + i);
i++;
try { Thread.sleep(2000); }
catch (InterruptedException e) { e.printStackTrace(); }
}
}
}
//class MainThread
package main;
public class MainThread
{
public static Thread t;
public static void main(String[] args)
{
t = new Thread(new WorkerThread());
t.start();
}
}
//class StopThread
package main;
public class StopThread
{
public static void main(String[] args)
{
//What should i write here to stop the thread started by MainThread
MainThread.t.interrupt();
}
}
public class MainThread
{
public static Thread t;
public static void main(String[] args)
{
t = new Thread(new WorkerThread());
t.start();
}
}
public class StopThread
{
public static void main(String[] args)
{
MainThread.t.interrupt();
}
}
It is not safe to call Thread.stop() it is listed as deprecated in JavaDocs
Also this may be just for the sake of this question, but why does your program have two main methods?
You have an opportunity to make use of what you defined volatile variable and gracefully come out of thread like below:
public class MainThread
{
public static WorkerThread workerThread;
public static void main(String[] args)
{
workerThread = new WorkerThread();
Thread t = new Thread(workerThread);
t.start();
}
}
public class StopThread
{
public static void main(String[] args)
{
Main.workerThread.stopThread();
}
}
Note: This solution works but not a perfect solution.
You can write and read value of isRunning variable from a properties file. This way you can have interaction between two different java processes. ThreadWorker just creates file upon initiation & and just makes attempt to read the file after that. StopThread modifies the properties file when triggered which should be picked up by ThreadWorker.
Check below example:
public class ThreadWorker implements Runnable
{
public volatile static boolean isRunning = false;
public ThreadWorker() {
Properties p = new Properties();
p.setProperty("isRunning", "1");
FileOutputStream out;
try {
//Writes all properties in appProperties file
out = new FileOutputStream("appProperties");
p.store(out, "---Thread Status----");
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run()
{
int i = 1;
String status = "1";
while("1".equals(status))
{
status = getStatus();
System.out.println("Loop " + i);
i++;
try { Thread.sleep(2000); }
catch (InterruptedException e) { e.printStackTrace(); }
}
}
public String getStatus() {
FileInputStream in;
Properties p = new Properties();
try {
in = new FileInputStream("appProperties");
p.load(in);
return p.getProperty("isRunning");
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//class StopThread
public class StopThread
{
public static void main(String[] args)
{
Properties p = new Properties();
p.setProperty("isRunning", "0");
FileOutputStream out;
try {
out = new FileOutputStream("appProperties");
p.store(out, "---Thread Status----");
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//class StopThread
public class StopThread
{
public static void main(String[] args)
{
Properties p = new Properties();
p.setProperty("isRunning", "0");
FileOutputStream out;
try {
out = new FileOutputStream("appProperties");
p.store(out, "---Thread Status----");
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Make thread t a public member of class MainThread, and then just call MainThread.t.interrupt() from StopThread