Maintain java object state when calling java process from bash script - java

public class Go {
private static SomeObject fld;
public static void main(String[] args) {
//depending on the args I do call different methods(among
//them one arg will do the job of initialization of fld variable)
}
}
I call the above java function from the bash script.
while true
do
read commands
java -cp some-jar.jar Go <commands>
then
Say command1 does initialization of fld in the Go class and command2 does some processing over the initialized field.
As I am calling different java processes for the different commands the objects fld state is not getting persisted for the next command.
How can I modify the code such that the fld information gets persisted for the next commands without using some database or deserializing and serializing?

You could store result in bash variable:
Go.java:
class Go {
private static String fld;
public static void main(String[] args) {
fld = args[0];
fld += fld.length();
System.out.println(fld);
}
}
run.sh
VALUE=test
while true
do
VALUE=`java Go $VALUE`
echo $VALUE
done
Output:
test4
test45
test456
test4567
test45678
Or store result into file, read it in bash and pass as parameter into Go.java .
Here is file storage example:
File example Go.java:
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
class Go {
private static String fld;
public static void main(String[] args) throws IOException {
fld = args[0];
fld += fld.length();
FileWriter fileWriter = new FileWriter("store.txt");
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print(fld);
printWriter.close();
}
}
File example run.sh:
VALUE=store
while true
do
java Go $VALUE
VALUE=`cat ./store.txt`
echo $VALUE
done
File example Output:
store5
store56
store567
store5678

Related

Checking if a string is a compilable Java class

I have an application that has stored various classes in string form.
For example, I might have this class:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
that is stored as a string in a database.
I would like to know whether this string contains a class that can compile successfully.
How would I go about doing that? Is there a package for this?
Create a text file and write the code to the file using Java:
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}");
myWriter.close();
Now run the file via
String[] args = new String[] {"/bin/bash", "-c", "your_command", "with", "args"};
Process proc = new ProcessBuilder(args).start();
You'll get to know if it compiles from its return value.

How to pass a file name as parameter, create and then read the file

I have a method as follows:
public(String input_filename, String output_filename)
{
//some content
}
how to create an input_filename at run time and read the input_filename .I have to pass input_filename as a parameter
Please be patient as I am new to Java
Here a complete sample:
Save it as Sample.java
compile it with: javac Sample.java
run it with: java Sample "in.txt" "out.txt"
or: java Sample
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Sample {
public static void main(String[] args) throws IOException {
if(args.length == 2)
{
doFileStuff(args[0],args[1]);
}
else {
doFileStuff("in.txt","out.txt");
}
}
public static void doFileStuff(String input_filename, String output_filename) throws IOException {
if(!Files.exists(Paths.get(input_filename)))
{
System.err.println("file not exist: " + input_filename);
return;
}
if(!Files.exists(Paths.get(output_filename)))
{
System.err.println("file still exist, do not overwrite it: " + output_filename);
return;
}
String content = new String(Files.readAllBytes(Paths.get(input_filename)));
content += "\nHas added something";
Files.write(Paths.get(output_filename), content.getBytes(StandardCharsets.UTF_8));
}
}
I'm unsure what you want to do with this method, but I hope this can help you a bit.
If you want inputs during runtime, use the Scanner class. A guide on how to use it here
Also if you want an output in your class you should use "return", and not have it as a parameter.
Do note that you haven't named your class yet, or specified the output type.
How it could look:
public String className(String input){
return input;
}

How to pipe input from a Java program to another using Bourne Shell

I have two simple Java programs and I want to pipe the result of the "Test" to the "Test2".
public class Test{
public static void main(String args[]){
System.out.println("Hello from Test");
}
}
and
public class Test2{
public static void main(String args[]){
System.out.printf("Program Test piped me \"%s\"",args[0]);
}
}
After I compiled both of .java files I tried to run the pipe command from terminal
java Test | java Test2, but I get an ArrayIndexOutOfBoundsException which means that the args array is not initialized?
How can the Test2 application take the outputstream value that Test.main() produced through piping?
One way is to use xargs:
java Test| xargs -I ARGS java Test2 ARGS
Pipes connect one program’s standard output to another program’s standard input, not to the other program’s command-line arguments.
The second class will not get the piped output as arguments to its main method; it will get the piped output as its standard input. So you want to read the information from System.in:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Test2 {
public static void main(String args[])
throws IOException {
BufferedReader stdin =
new BufferedReader(new InputStreamReader(System.in));
stdin.lines().forEachOrdered(
line -> String.format("Program Test piped me \"%s\"", line));
}
}

How to execute if statement using Jython

import org.python.util.PythonInterpreter;
public class JythonTest {
public static void main(String[] args) {
PythonInterpreter interp = new PythonInterpreter();
interp.exec("if 2 > 1:");
interp.exec(" print('in if statement!'");
}
}
I need to be able to execute Python code from a Java program, so decided to try out Jython, but I'm unfamiliar with it. I tried executing the above code, but got the error: "Exception in thread "main" SyntaxError: ("mismatched input '' expecting INDENT", ('', 1, 9, 'if 2 > 1:\n'))". Any ideas what this means or how I can otherwise execute an if statement using the PythonInterpreter?
Conditionals must be entered as a single string and you have an extra parenthesis:
import org.python.util.PythonInterpreter;
public class JythonTest {
public static void main(String[] args) {
PythonInterpreter interp = new PythonInterpreter();
interp.exec("if 2 > 1: print 'in if statement!'");
}
}
Rather than executing a script line by line with strings you can invoke the interpreter to run a file. All you have to do is provide a file path to your python file, in this example place script.py in the src folder.
script.py
if 2 > 1:
print 'in if statement'
JythonTest.java
import org.python.util.PythonInterpreter;
public class JythonTest {
public static void main(String[] args) {
PythonInterpreter interp = new PythonInterpreter();
interp.execfile("src/script.py");
}
}

How to get the current umask value from Java?

I am running java 7 applications on unix machines. Is there a way to get the current umask value in pure java ?
In C I would use a combination of umask system calls, but I don't think I can call that in Java without resorting to JNI. Is there another approach ?
Edit: Here is a C example (from GUN libc docs):
mode_t
read_umask (void)
{
mode_t mask = umask (0);
umask (mask);
return mask;
}
A simple solution, if there is no Class/Method to get the umask, why don't you get it before call java and pass as a property?
Can you clarify? Do you want to read the umask of the application(the current java process)? Or do you want to read the umask value of some files on the file system?
You can use NIO (the used code is from the javadocs) to get some file attributes, or you can execute a shell command, since the process created with Runtime.execute inherits the umask of it's creator process.
So you should be able to solve your problem without the use of JNI.
package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermissions;
public class Test {
private static final String COMMAND = "/bin/bash -c umask -S";
public static String getUmask() {
final Runtime runtime = Runtime.getRuntime();
Process process = null;
try {
process = runtime.exec(COMMAND);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String umask = reader.readLine();
if (process.waitFor() == 0)
return umask;
} catch (final IOException e) {
e.printStackTrace();
} catch (final InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
return "";
}
public static void main(String[] args) throws IOException {
/*
* NIO
*/
PosixFileAttributes attrs = Files.getFileAttributeView(Paths.get("testFile"), PosixFileAttributeView.class)
.readAttributes();
System.out.format("%s %s%n", attrs.owner().getName(), PosixFilePermissions.toString(attrs.permissions()));
/*
* execute shell command to get umask of current process
*/
System.out.println(getUmask());
}
}

Categories

Resources