Run python script in Java : Why do I get null output? - java

I'm trying to run a python script in Java. python script converts speech to text. But, after executing it in java, I get null output.
The python script does not have any error and works fine as I run it in the terminal.
I tried "Thread.sleep()" in order to wait for process but It did not help.
"SampleHandler" is my java class name.
Java:
try {
java.net.URL location = SampleHandler.class.getProtectionDomain().getCodeSource().getLocation();
Process p = Runtime.getRuntime().exec(location.getFile() + "resources/speech_to_text.py");
Thread.sleep(8000);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ret = "";
ret = in.readLine();
System.out.println(ret);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Python :
import os
import io
from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="key.json"
client = speech.SpeechClient()
file_name = os.path.join('audio.wav')
with io.open(file_name, 'rb') as audio_file:
content = audio_file.read()
audio = types.RecognitionAudio(content=content)
config = types.RecognitionConfig(
encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=44100,
audio_channel_count=2,
language_code='en-US')
response = client.recognize(config, audio)
for result in response.results:
print(format(result.alternatives[0].transcript))

Related

JMeter does not execute Java code correctly if it's ran as .jar file from command line

I'm designing JMeter scenario which implies executing a certain .jar file via OS Process Sampler element. My Java code has while loop which basically checks a certain mailbox for a letter with a certain subject. Loop waits until finds one (emails are always delivered with roughly 3 minutes delay), parses it and writes some data to .txt file.
If I run this .jar directly from cmd then the code works as expected. But if I run it via JMeter OS Process Sampler then it never creates a file for me. I do see that email is delivered to inbox, so expect it to be parsed and .txt created.
At first I suspected that JMeter finishes Java scenario without waiting for while loop to execute. Then I put OS Process Sampler in a separate Thread and added a huge delay for this thread in order to wait and make 100% sure that email is delivered and Java only need to parse it but it does not help.
View Results Tree never shows any errors.
Here is my OS Process Sampler: https://www.screencast.com/t/LomYGShJHAkS
This is what I execute via cmd and it works as expected: java -jar mailosaurJavaRun.jar email533.druzey1a#mailosaur.in
And here is my code (it does not looks good but it works):
public class Run {
public static void main(String[] args) {
MailosaurHelper ms = new MailosaurHelper();
String arg1 = ms.getFirstLinkInEmail(args[0]);
BufferedWriter output = null;
try {
File file = new File("url.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(arg1);
} catch ( IOException e ) {
e.printStackTrace();
} finally {
if ( output != null ) {
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class MailosaurHelper {
protected final String API_KEY = "b3e4d2b193b5eb2";
protected final String MAILBOX_ID = "d1uzey1a";
public MailboxApi getEmailBox() {
return new MailboxApi(MAILBOX_ID, API_KEY);
}
public String getFirstLinkInEmail(String email) {
MailosaurHelper ms = new MailosaurHelper();
String link = "";
if (link.equals("") || link.isEmpty()) {
try {
Thread.sleep(3000);
link = ms.getAllEmailsByReceipent(email)[0].html.links[0]
.toString();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return link;
}
public Email[] getAllEmailsByReceipent(String recepient) {
try {
int ifArrayIsEmpty = getEmailBox().getEmailsByRecipient(recepient).length;
while (ifArrayIsEmpty == 0) {
try {
Thread.sleep(3000);
ifArrayIsEmpty = getEmailBox().getEmailsByRecipient(
recepient).length;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (MailosaurException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Email[] listOfEmails = null;
try {
listOfEmails = getEmailBox().getEmailsByRecipient(recepient);
} catch (MailosaurException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listOfEmails;
}
The bottom line is that I need to parse Mailosaur email, retrieve URL from it and use it further. Any other suggestion on how to do that using Jmeter/Java/Mailosaur are appreciated.
You don't need cmd in here, but if you're adamant to stick with it - use /C key when you call it.
Then, are your sure you're looking for your file in the right place?
According to documentation:
By default the classes in the java.io package always resolve relative
pathnames against the current user directory. This directory is named
by the system property user.dir, and is typically the directory in
which the Java virtual machine was invoked.
Check it thoroughly, BTW - you should see it in your sampler result.

Trying to retrieve python version from java

I'm trying to retrieve the version of python form java using ProcessBuilder.
The command i'm using is:
{process = new ProcessBuilder("C:\\Python27\\python.exe", "-V")}
This command does not return anything.
I'm almost sure this is the correct syntax to retrieve the python version,
{process = new ProcessBuilder("C:\\Python27\\python.exe", "-h")}
returns the python help as expected, but python -V does not return the python version.
package com.x.x.precheck.python;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Process process = null;
try {
process = new ProcessBuilder("C:\\Python27\\python.exe", "-V")
.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:", Arrays.toString(args));
try {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
It's because, strangely enough, the python2.7 version is displayed in stderr. in python version 3.4 this behaviour will change see http://bugs.python.org/issue18338
so instead of
InputStream is = process.getInputStream();
you should call
InputStream stderr = process.getErrorStream ();
I tested your code with other programs.It all works fine.for example i gave octave instead of the python and It printed out.Its weird.

Executing imagemagick commands with java gives no output

I am writing a java aplication that edits images using imagemagick commands;
However, the comands do not work and I am getting no output from them;
Actually, the comand identify is not recognized and I get CreateProcess error=2;
This seems odd, because the imagemagick instalation folder is included in my Path variable.
Here's my code:
public class Test {
public static void main(String argv[]) {
Runtime ru = Runtime.getRuntime();
Process p = null;
try {
//I've added this as a bouns, this should not be neccessary(methinks)
String[] s = {"C:\\Program Files\\ImageMagick-6.8.6-Q16"};
String[] cmd = {"convert", "acc-logo.jpg","-flip", "edited.jpg"};
p = ru.exec(cmd,s);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader ina = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = null;
try {
while ((line = ina.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You have a space in the path to the executable, and the Runtime.exec() call is having problems with it. Use ProcessBuilder instead; it handles spaces in arguments much more easily.

Windows cmd-output (Java)

I've found this topic, but the code doesn't work for me... Return Windows cmd text from Java?
After pressing a button I want to execute a batch-file, for testing purposes it's just the ipconfig-command.
The cmd-output should be written into a JTextFiled, but all I get is no text...
Here the code for writing it into the JTextField:
btnLock.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String g = "";
try {
Runtime.getRuntime().exec(new String[] {"ipconfig", g});
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Process p = null;
try {
p = Runtime.getRuntime().exec(new String[] {"ipconfig", g});
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream s = p.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(s));
String temp;
try {
while ((temp = in.readLine()) != null)
{
System.out.println(temp);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnLock.setBounds(10, 68, 89, 23);
contentPane.add(btnLock);
So what do I do wrong?
It's my first project with cmd-input, so please don't get mad cause of silly mistakes I made. ;)
Thx
Try the exec command that just takes a String parameter. The following test code worked on my system (though I was only printing to console, not to textfield):
BufferedReader in = null;
try{
Process p = Runtime.getRuntime().exec("ipconfig");
InputStream s = p.getInputStream();
in = new BufferedReader(new InputStreamReader(s));
String temp;
while ((temp = in.readLine()) != null) {
System.out.println(temp);
}
} catch (Exception e){
e.printStackTrace();
} finally {
if (in != null) in.close();
}
Also your code in the original post is also using a System.out.println. As far as I'm aware, you can't print to a JTextField using System.out.println.... You'd have to use the setText method.
If I run
ipconfig ""
I get
** Error: unrecognized or incomplete command line.**
You can only run from Java, commands which work on the command line.
BTW: If you are looking for errors, you need to read the error stream.
I would Runtime.getRuntime().exec(new String[] {"ipconfig > temp.txt"}); and then just read it as a text file using a BufferedReader.
I hope this helps.

Run a .dmg file through java code

How can I mount a .dmg file through java code under OS X?
This will work (but only on OS X):
try {
String[] command = {"/usr/bin/hdiutil", "attach", "/Users/path/to/your.dmg"};
String sendback = "";
Process proc = Runtime.getRuntime().exec(command);
InputStream istr = proc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(istr));
String str;
while ((str = br.readLine()) != null) {
sendback = sendback + str;
}
int resultCode = proc.waitFor();
br.close();
if (resultCode != 0) {
throw new Exception("failed to open system profiler");
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DMGs are not executables, are apple diskimages
reference is here
thus you can't "run" it.
You can use a Process, of course. But it won't work anywhere except on a Mac.
Saying that is like asking how to run an ISO file through Java. You simply can't; it's a disk image.

Categories