bash script does not work when called on jee - linux

i have a script bash which requires parameters.
when i call it directly from putty, it works, hen i do from my jee program it does not work and does not show me any errors.
This is my java code:
String[] cmdArray = {"sudo", "ssh", "-tt", "root#89.40.112.248", "/root/dve", "-l", "89.40.112.120,89.40.112.248", "you.mp4", "-s",".teeeest.avi" };
List<ObjectNode> listFileNode = new ArrayList<ObjectNode>();
try{
Runtime rt = Runtime.getRuntime();
ProcessBuilder pb = new ProcessBuilder(cmdArray);
Process proc = pb.start(); // Start the process.
System.out.println("Script executing");
rc= proc.waitFor(); // Wait for the process to finish.
System.out.printf("Script executed successfully in ", rc);
InputStream stderr = proc.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("<ERROR___EXEC>");
while ( (line = br.readLine()) != null){
System.out.println(line);
node.put("line",line );
listFileNode.add(node);
}
System.out.println("</ERROR___EXEC>");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
InputStream processInputStream =proc.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(processInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
System.out.println("<RESULTAT___EXEC>");
while ( (line = bufferedReader.readLine()) != null){
System.out.println(line);
node.put("lineR",line );
listFileNode.add(node);
}
System.out.println("</RESULTAT___EXEC>");
}catch (Throwable t)
{
t.printStackTrace();
}
please help me i am stuck on this from a week and i don't find solution

You can't use sudo command in the java code. If you need to run root privileged application you need to switch to root before running your java code.
If you want to do it from your java code, you need to call setuid. But I don't know you can call setuid from a java code. For that purpose you may need a C/C++ wrapper for switching to root. Refer:http://unix.stackexchange.com question for writing wrapper.

Related

.NET 4.7.2 => c-sharp => UI async/await

I'm trying to load a content of a text file into text box asynchronously.
Therefore my goal is to not block the UI-Thread.
To check that, the code gives feedback with Console.Writeline("..."+Thread.CurrentThread.ManagedThreadId)
My first intention shows the code below, which will give me Thread 1 in both Console.WriteLines().
That means UI-Thread is blocked, right?
private async void cmdProgrammLaden_Click(object sender, EventArgs e)
{
Console.WriteLine("Button-Thread-ID: " + Thread.CurrentThread.ManagedThreadId);
this.txtSendData.Text = await DncProgrammLadenAsync();
}
async Task<string> DncProgrammLadenAsync()
{
string path = String.Empty;
string content = String.Empty;
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = #"c:\Test\";
openFileDialog.Filter = "Textfile (*.txt)|*.txt";
openFileDialog.FilterIndex = 0;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
path = openFileDialog.FileName;
var filestream = openFileDialog.OpenFile();
using (StreamReader reader = new StreamReader(filestream))
{
content = await reader.ReadToEndAsync();
Console.WriteLine("Task-Thread-ID: " + Thread.CurrentThread.ManagedThreadId);
//Thread.Sleep(3000);
}
}
return content;
}
}
Then I tried to rework this code like *(short version)*
Task.Run(() =>
{
string content = String.Empty;
using (StreamReader reader = new StreamReader(#"c:\Test\File C.txt"))
{
content = reader.ReadToEnd();
Console.WriteLine("Task-Thread-ID: " + Thread.CurrentThread.ManagedThreadId);
}
});
Then I get different Thread IDs.
But this seems not right to me.
What do I not understand correctly?
That means UI-Thread is blocked, right?
No. By default, await captures the current context and resumes executing the async method in that context when that await completes. The UI thread is not blocked during the await, but the code resumes executing on the UI thread after the await.
However, file streams are tricky. They are only asynchronous if opened with an asynchronous flag, and I have no idea if OpenFile passes that flag. Asynchronous APIs called on a synchronous file handle just run the operation on a thread pool thread (I think).

Transition between child thread to Application thread in JavaFX

I am new to JavaFX. I am trying to implement multithreading in my project.
Here I want to do download work in a background thread. But in the code, some components like Filechooser and label are not accessed by the background thread, so I used Platform.runLater for it. But then I am stuck in between. Please guide me.
FileChooser fc = new FileChooser();
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("Compressed(zipped) Folder (*.zip)", "*.zip");//Compressed(zipped) Folder (*.gz)", "*.gz"
fc.getExtensionFilters().add(extFilter);
String downloadsLocation = System.getProperty("user.home") + "/Downloads/";
/// get a File file with name as you save in file chooser
Platform.runLater(()->{
System.out.println("Inside runlator"+Thread.currentThread());
file = fc.showSaveDialog(downloadMultiTraceFileButton.getScene().getWindow());
System.out.println("Path of file->" + file.getAbsolutePath());
file.mkdirs();
});
System.out.println("after runlator"+Thread.currentThread());
Thread.sleep(1000);
System.out.println("after sleep"+Thread.currentThread());
File theDir = null;
try{
theDir = new File(destFile.getAbsolutePath());
}catch(Exception e){
System.out.println(e);
}
/// Iterating through the slected item of trace files one by one for create a file and then fill it
for (String str : traceFileListView.getSelectionModel().getSelectedItems()) {
System.out.println("inside of the for loop "+Thread.currentThread());
File myFile = new File(theDir.getAbsolutePath() + "\\" + str);
/// make new file if myFile doesnt exist
if (!myFile.exists()) {
myFile.createNewFile();
}
Here backgroung thread is going through it. But this thread is not going to this part of code.
File theDir = null;
try{
theDir = new File(destFile.getAbsolutePath());
}catch(Exception e){
System.out.println(e);
}
Please give me solution. I tried every possibility like inserting Thread.currentthread.sleep(1000) and some other things too.

Start test body after jar file loading (from JAVA) is finished

I want to write UNIT test with SOAP webservices. Webservices work in other jar file, which I try to load Runtime.getRuntime().exec(// java - jar ...). Loading jar file takes 2 min. When loading is in new Thread the test ends before loading jar file will be finished. If loading is in main thread, test is not finished. I try to listen HTTP response with while cycle, but when cycle is working, the jar file is not loading.
#Before
public void setUp() throws Exception {
// Get path of jar file
thread = new Thread() {
public void run() {
try {
Process process = Runtime.getRuntime().exec(path-to-java.exe -jar webservices.jar);
process.waitFor();
process.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
int responseCode;
do {
responseCode = getResponseCodeHTTP("http://localhost:8080/services");
} while (responseCode < 200 || responseCode >= 400);
System.out.println("Web services have loaded");
}
public int getResponseCodeHTTP(String urlToRead) throws IOException {
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
int result;
try {
conn.connect();
result = conn.getResponseCode();
} catch (ConnectException e){
return 500;
}
return result;
}
OK. I want to write test, which will start the webservices from jar file (loading process takes 1.5 min) and then execute test. To start web services I use Runtime.getRuntime().exec and to understand that them started I use HTTP response code. When the code [200-400) , it means the ws started OK.
I tried to debug code inside new Thread and added code with InputStreamReader and while cycle.
String line;
InputStream stdout = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
while ((line = reader.readLine()) != null)
System.out.println("[Stdout] " + line);
And test successfully executed. The when I removed the while cycle with readline, the problem had repeated.
I have not understand yet why it worked.

BufferedReader is sometimes empty

I have Loader class where I load txt file into BufferedReader from resources and return this field. I use this method but it acts really strange(for me). When I don't put
String str = bufferReader.readLine(); after
bufferReader = new BufferedReader(fileReader);
(in Loader class) than bufferReader in another class is empty, and readLine() returns null. When I write that piece of code in Loader class, I can read each line from txt, except the 1. one which is read in Loader class. Also, I can't read last line if I dont put enter at the end.
public BufferedReader loadFromFileToBufferReader(String fileName) {
ClassLoader classLoader = getClass().getClassLoader();
System.out.print(getClass().getClassLoader().getResource("resources/" + fileName));
File file = new File(classLoader.getResource("resources/" + fileName).getFile());
BufferedReader bufferReader = null;
try (FileReader fileReader = new FileReader(file)) {
bufferReader = new BufferedReader(fileReader);
String str = bufferReader.readLine();
} catch (IOException e) {
System.err.println("Something went terribly wrong with file reading");
}
return bufferReader;
}
and usage:
public Database() {
productsInDatabse = new ArrayList<>();
codesList = new ArrayList<>();
loader = new LoadFromFile();
BufferedReader output = loader.loadFromFileToBufferReader("database.txt");
Product product;
String line;
String[] array;
try {
line = output.readLine();
while (line != null) {
You should paste your code here because it's hard to deduce all the possible causes of this without seeing the code on 100% but I am guessing you have it the same file open at the same time from multiple sources without closing it before from one? Could be literally millions of little things, just telling you how the same error happened to me.

Execute a external program within a groovy script and capture the output

I need to write a groovy script, that is executing a external program and print the output of that program to the console.
Here is the regarding code snippet:
def pmdCommand = "${scriptDir}/run.sh pmd -d ${filesToAnalyse}"
def sout = new StringBuffer()
def serr = new StringBuffer()
def process = pmdCommand.execute()
process.consumeProcessOutput(sout, serr)
process.waitFor()
if (process.exitValue() !=0 ) {
System.err << serr.toString()
System.exit(-1)
}
else {
System.out << sout.toString()
System.exit(0)
}
I did something similar in Java, but I can't translate it to groovy.
StringBuffer output = new StringBuffer();
String s = null;
try {
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
while ((s = stdError.readLine()) != null) {
System.err.println(s);
}
System.exit(0);
}
catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
Update: I seems the waitFor() never returns and blocks the execution
Solution provided by Emmanuel Rosa:
def pmdCommand = "/usr/src/app/lib/pmd/bin/run.sh pmd -d ${filesToAnalyse} -f codeclimate -R ${ruleset} -l apex -v 35"
def sout = new StringBuffer()
def serr = new StringBuffer()
def process = pmdCommand.execute()
process.consumeProcessOutput(sout, serr)
process.waitForProcessOutput()
System.out << sout.toString()
System.exit(0)
The documentation states that consumeProcessOutput()...
Gets the output and error streams from a process and reads them to
keep the process from blocking due to a full output buffer. The
processed stream data is appended to the supplied OutputStream. For
this, two Threads are started, so this method will return immediately.
So far so good. Here's the important part...
The threads will not be join()ed, even if waitFor() is called.
And the solution...
To wait
for the output to be fully consumed call waitForProcessOutput().
So what you can do is replace process.waitFor() with process.waitForProcessOutput().

Resources