error in build to process builder in java - perl

I have devloped myself tagger and I want to host on the web. my server is based on jsp. But This tagger is based on svmtool and it has been written in Perl script. That's why, I have created one ".java" file. In this file I've created Processor builder and via the Runtime.getRuntime().exec through this process I am calling this file. It is working but it doesn't show my output. Plz help to solve this issue. For the better under standing below I am giving my java code and also given last line of output/stop the process:
import java.io.*;
public class ExeCommand { String outS = "", errS="";
try {
// run the Unix "type your terminal command" command
System.out.println ("Running tagger!");
String command = "perl /home/svmtool_v1.3.2/bin/SVMTagger.pl -V 4 -S LRL /home/svmtool_v1.3.2/models/ih/IN < /home/tomcat4.1.40/webapps/pos/textfile/tests.txt > /home/tomcat4.1.40/webapps/pos/textfile/output.txt"; Process p = Runtime.getRuntime().exec(command);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("It will take time so keep the patience:\n" + command);
System.out.println ("First error line: " + stdError.readLine());
// read any errors from the attempted command
System.out.println("Please check your command (if any):\n");
while ((errS = stdError.readLine()) != null) {
System.out.println("Error:\t" + errS);
}
stdError.close();
System.out.println ("First output line: " + stdInput.readLine());
while ((outS = stdInput.readLine()) != null) {
System.out.println("Output:\t" + outS);
}
stdInput.close();
System.out.println("Finished!");
}
catch (Exception e) {
System.out.println("found exception: " + e);
e.printStackTrace();
//System.exit(-1);
}
System.out.println("Finished all!");
}
}
After this nothing doing/ last output shows in terminal:
TAGGING < DIRECTION = left-to-right then right-to-left >

First, your perl script redirects its standard output to a file (
/home/tomcat4.1.40/webapps/pos/textfile/output.txt). So there is no way, you can capture standard output in Java.
Instead, you can use tee command which can write the output to both your output file and the standard output. Now, this can be captured in Java.
Second, use ProcessBuilder instead of Runtime. Process Builder is more flexible and gives you options to capture the standard output / input / error.
ProcessBuilder p = new ProcessBuilder();
p.inheritIO(); // Sets the source and destination for subprocess standard I/O to be the same as those of the current Java process.
p.command("perl", "somescript.pl");
p.start();

As I wrote here:
Sorry for the harsh words, but your code is a disaster. No compiler do something with it.
I have made no further tweaks to your code, I have the code modified so that it works at least:
package stackoverflow;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ExeCommand {
/**
*
* run the Unix "type your terminal command" command
*
* #param args
*/
public static void main(String[] args) {
System.out.println("Running tagger!");
String command = "perl /home/svmtool_v1.3.2/bin/SVMTagger.pl -V 4 -S LRL /home/svmtool_v1.3.2/models/ih/IN < /home/tomcat4.1.40/webapps/pos/textfile/tests.txt > /home/tomcat4.1.40/webapps/pos/textfile/output.txt";
// String command = "ls -og";
Process p = null;
try {
p = Runtime.getRuntime().exec(command);
} catch (IOException e) {
e.printStackTrace();
}
// read the output from the command
System.out.println("It will take time so keep the patience:\n" + command);
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
try {
System.out.println(": " + stdError.readLine());
} catch (IOException e) {
e.printStackTrace();
}
// read any errors from the attempted command
System.out.println("Please check your command (if any):\n");
try {
String errS = "";
while ((errS = stdError.readLine()) != null) {
System.out.println("Error:\t" + errS);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
stdError.close();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
try {
System.out.println("First output line: " + stdInput.readLine());
} catch (IOException e) {
e.printStackTrace();
}
try {
String outS = "";
while ((outS = stdInput.readLine()) != null) {
System.out.println("Output:\t" + outS);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
stdInput.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Finished!");
}
}
Replace the lines 19 and 20
String command = "perl /home/svmtool_v1.3.2/bin/SVMTagger.pl -V 4 -S LRL /home/svmtool_v1.3.2/models/ih/IN < /home/tomcat4.1.40/webapps/pos/textfile/tests.txt > /home/tomcat4.1.40/webapps/pos/textfile/output.txt";
// String command = "ls -og";
with
// String command = "perl /home/svmtool_v1.3.2/bin/SVMTagger.pl -V 4 -S LRL /home/svmtool_v1.3.2/models/ih/IN < /home/tomcat4.1.40/webapps/pos/textfile/tests.txt > /home/tomcat4.1.40/webapps/pos/textfile/output.txt";
String command = "ls -og";
Then you get this output:
Running tagger!
It will take time so keep the patience:
ls -og
: null
Please check your command (if any):
First output line: insgesamt 12
Output: drwxrwxr-x 3 4096 Mai 23 20:51 bin
Output: drwxrwxr-x 3 4096 Apr 26 15:49 src
Output: -rw-rw-r-- 1 28 Apr 26 15:51 test
Finished!

Related

Execute linux command on Centos using dotnet core

I'm running a .NET Core Console Application on CentOS box. The below code is executing for normal command like uptime, but not executing for lz4 -dc --no-sparse vnp.tar.lz4 | tar xf - Logs.pdf:
try
{
var connectionInfo = new ConnectionInfo("server", "username", new PasswordAuthenticationMethod("username", "pwd"));
using (var client = new SshClient(connectionInfo))
{
client.Connect();
Console.WriteLine("Hello World!");
var command = client.CreateCommand("lz4 -dc --no-sparse vnp.tar | tar xf - Logs.pdf");
var result = command.Execute();
Console.WriteLine("yup ! UNIX Commands Executed from C#.net Application");
Console.WriteLine("Response came form UNIX Shell" + result);
client.Disconnect();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Expected output is Logs.pdf file needs to be extracted and saved in the current location. Can someone correct me where im
If application is running on Linux machine then you can try this also:
string command = "write your command here";
string result = "";
using (System.Diagnostics.Process proc = new System.Diagnostics.Process())
{
proc.StartInfo.FileName = "/bin/bash";
proc.StartInfo.Arguments = "-c \" " + command + " \"";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.Start();
result += proc.StandardOutput.ReadToEnd();
result += proc.StandardError.ReadToEnd();
proc.WaitForExit();
}
return result;

Why does this text decoded in 2 different ways not match in GWT?

I've been trying to track down why my Russian translations are not appearing correctly in the GWT version of my game. I've narrowed it down to something going wrong with the decoding of the file. This code works correctly outside of the GWT environment.
I create the UTF-8 byte array from a string for this test. The method below outputs two instances of the text to the log. The first uses new String(bytes) and gives the correct output, the second uses the BufferedReader and produces incorrect output. The diff of the two files can be seen here.
The classes I'm using for localisation are using the ByteBuffer approach and are therefore outputting incorrect text for the Russian translation and I'm struggling to understand why.
public void test(){
String text = "# suppress inspection \"UnusedProperty\" for whole file\n" +
"\n" +
"# Notes\n" +
"# I used the phrase \"Power Flower\" in English as it rhymes. They can be called something else in other languages.\n" +
"# They're \"fleurs magiques\" (Magic Flowers) in French.\n" +
"\n" +
"# Tutorials\n" +
"#-----------\n" +
"Tutorial_1_1=Составляй слова, проводя пальцем по буквам.Сейчас попробуй создать слово 'СОТЫ'\n" +
"Tutorial_1_2=Ты можешь складывать слова справа налево. Попробуй составить слово 'ЖАЛО' справа налево\n" +
"Tutorial_1_3=Слова могут распологаться сверху вниз, снизу вверх, справа налево, слева направо, а также по диагонали.\n" +
"Tutorial_1_4=Создавая слова, ты можешь изменять направление.Составь слово 'ВОСК'\n" +
"Tutorial_1_5=Ты даже можешь пересекать свое собственное слово. Тем не менее, используй каждую букву только один раз. А сейчас, сложи слово 'УЛЕЙ'\n" +
"Tutorial_1_6=Чем длиннее окажется твоё слово, тем больше у тебя шансов получить много очков и возможность заработать Чудо-Цветок. Составь слово 'ПЧЕЛА'\n" +
"Tutorial_1_7=Получи Чудо-Цветы за каждое слово из пяти или более букв. Они могут быть использованы в качестве любой из букв.\n" +
"Tutorial_1_8=Составь слово 'СТЕБЕЛЬ'\n" +
"Tutorial_1_9=Из разных по длине и форме слов получаются разные Чудо-Цветы.\n" +
"Tutorial_1_10=Теперь ты справишься сам. Составь еще четыре слова, чтобы уровень был пройден";
// This defaults to the default charset, which in my instance, and most probably yours is UTF-8
byte[] bytes = new byte[0];
try {
bytes = text.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String test = new String(bytes);
// This is correct
Gdx.app.log("File1", test);
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
InputStreamReader reader = null;
try {
reader = new InputStreamReader(is, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
BufferedReader br = new BufferedReader(reader);
StringBuilder fileContents = new StringBuilder();
String line;
try {
while ((line = br.readLine()) != null) {
fileContents.append(line + "\r\n");
}
} catch (IOException e) {
e.printStackTrace();
}
// This is incorrect
Gdx.app.log("File2", fileContents.toString());
}
It would appear the ByteArrayInputStream and the BufferedReader partial strings are being decoded by the UTF-8 decoder which is corrupting the result. This would appear to be a GWT issue.

Any way to access a NFS from Bluemix runtime?

I need to push an application to Bluemix that requires access to a remote file system via NFS.
I haven't found any NFS service. Existing Object Store services use Swift API and the application requires native file system access, not other kind of APIs.
I tried to execute "mkdir" and "mount" commands from app initialization but it seems there are restrictions for such executions from the user that runs the runtime. I got return codes that mean errors.
So I run out of ideas. Do you have any suggestion or idea to explore?
I think Dockers could be an option (haven't explored yet if I can mount the nfs file system) but currently it is in Beta, so no production ready.
Thanks!
NFS is not supported, however Cloud Foundry now supports FUSE, which is a pretty close alternative to NFS.
To take advantage of FUSE you need to use the cflinuxfs2 stack.
cflinuxfs2 is a new stack that supports FUSE, see below. Cloud Foundry recently added FUSE support, see here for more info.
name description
lucid64 Ubuntu 10.04
cflinuxfs2 Ubuntu 14.04.2 trusty
When you push your app you need to use the -s option, example below.
cf push myappname -s cflinuxfs2.
Update:
The poster posted a solution to his another question on how to do this. I have pasted it below...
Ok, finally I found the reason of the issue with the help of team colleagues. Problem was with permissions of the private ssh key. It has to be 600 and by default it was 644 after the cf push.
So here it is the final code (quick and dirty) that worked, just in case it can be useful to others...
1.- Include into the app the private key and the known_hosts files.
2.- Push the app adding "-s cflinuxfs2" parameter.
3.- Execute at runtime startup some code like this:
String s = null;
Process p = null;
BufferedReader br = null;
try
{
p = Runtime.getRuntime().exec("mkdir -p /home/vcap/misc");
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((s = br.readLine()) != null)
System.out.println("line: " + s);
p.waitFor();
System.out.println ("#### Executing command mkdir with exit: " + p.exitValue());
p.destroy();
br.close();
p = Runtime.getRuntime().exec("chmod 600 /home/vcap/app/wlp/usr/servers/defaultServer/apps/myapp.ear/cloud.key");
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((s = br.readLine()) != null)
System.out.println("line: " + s);
p.waitFor();
System.out.println ("#### Executing command chmod with exit: " + p.exitValue());
p.destroy();
br.close();
p = Runtime.getRuntime().exec("chmod 600 /home/vcap/app/wlp/usr/servers/defaultServer/apps/myapp.ear/known_hosts");
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((s = br.readLine()) != null)
System.out.println("line: " + s);
p.waitFor();
System.out.println ("#### Executing command chmod with exit: " + p.exitValue());
p.destroy();
br.close();
p = Runtime.getRuntime().exec("sshfs ibmcloud#129.41.133.34:/home/ibmcloud /home/vcap/misc -o IdentityFile=/home/vcap/app/wlp/usr/servers/defaultServer/apps/myapp.ear/cloud.key -o StrictHostKeyChecking=yes -o UserKnownHostsFile=/home/vcap/app/wlp/usr/servers/defaultServer/apps/myapp.ear/known_hosts -o idmap=user -o compression=no -o sshfs_debug");
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((s = br.readLine()) != null)
System.out.println("line: " + s);
p.waitFor();
System.out.println ("#### Executing command sshfs with exit: " + p.exitValue());
p.destroy();
br.close();
p = Runtime.getRuntime().exec("ls -l /home/vcap/misc");
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((s = br.readLine()) != null)
System.out.println("line: " + s);
p.waitFor();
System.out.println ("#### Executing command ls with exit: " + p.exitValue());
p.destroy();
br.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
finally
{
try
{
if(br != null)
br.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
This snippet should create a folder, mount a remote file system into that folder and list the content of the remote file system.

FileMaker 10 Pro Insert data by Asp.Net

I am trying to insert the data in FM but get the parse error serached number of fourms with no luck.
ERROR [HY000] [DataDirect][ODBC SequeLink driver][ODBC Socket][DataDirect][ODBC FileMaker driver][FileMaker]Parse Error in SQL
enter code here
StringBuilder sbAddBarcode = new StringBuilder();
sbAddBarcode.Append("insert into BarCode (PONumber,Description,Model,[Serial Number])");
sbAddBarcode.Append("values");
sbAddBarcode.Append(" ("+ barcode.PONumber + ",");
sbAddBarcode.Append(" '" + barcode.Description +"',");
sbAddBarcode.Append(" '" + barcode.ModelNumber +"')");
//sbAddBarcode.Append(" '" + barcode.SerialNumber +"')");
fmCommand = new OdbcCommand(sbAddBarcode.ToString(), fmcon);
fmCommand.CommandType = CommandType.Text;
fmCommand.Connection = fmcon;
try
{
fmcon.Open();
fmCommand.ExecuteNonQuery();
}
catch (OdbcException oe)
{
throw new Exception(oe.Message);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
fmcon.Close();
}
Echo your sbAddBarcode value. The SQL you're building does look to be invalid.

Binary File Download using socket connection in Java ME

I am trying to download a pdf file on my mobile (using Java ME) using SocketConnection Api. The idea is to send the server a HTTP GET request, and it replies back with the data for pdf file. However, the problem I am facing is that the server initially replies back with string data (the HTTP Headers), and then the binary data. I just want to store the binary data (the pdf file).
I have written this code so far, and it works perfectly fine as far as the server replies back with string data. However, when it replies back with binary data, this code still tries to store everything as string, correctly storing the initially returned HTTP Headers (not required) and then garbled bits corresponding to the binary data of my PDF file.
public void FileDownload() {
try {
sc = (SocketConnection) Connector.open("socket://" + hostname + ":" + port);
OutputStream os = sc.openOutputStream();
os.write(("GET " + link_to_file_to_be_downloaded + " HTTP/1.0\r\n").getBytes("UTF-8"));
os.write(("HOST: " + hostname + "\r\n").getBytes("UTF-8"));
os.write(("\r\n").getBytes("UTF-8"));
os.flush();
os.close();
String url = "file:///E:/Data/" + "binary_data.pdf";
FileConnection fconn = (FileConnection) Connector.open(url, Connector.READ_WRITE);
if (!fconn.exists()) {
fconn.create();
}
OutputStream ops = fconn.openOutputStream();
byte data = 0;
in = sc.openInputStream();
data = (byte) in.read();
while (data != -1) {
ops.write(data);
data = (byte) in.read();
}
ops.flush();
ops.close();
fconn.close();
} catch (IOException ex) {
parent_class.main_form.append("Exception occured while "
+ "downloading file: " + ex.toString() + "\n");
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
parent_class.main_form.append("Exception occured while "
+ "downloading file: " + ex.toString() + "\n");
}
}
}
}
This is what gets stored in the file "binary_data.pdf" using this code -
HTTP/1.1 200 OK
Date: Sun, 25 Mar 2012 07:03:10 GMT
Server: Apache/2.2.14 (Ubuntu)
Last-Modified: Tue, 20 Mar 2012 22:00:45 GMT
ETag: "420050-12bad-4bbb3ce85fd21"
Accept-Ranges: bytes
Content-Length: 76717
Content-Type: application/pdf
Via: 1.0 www.XXX.XXX.org
Connection: close
%PDF-1.4
%????
3 0 obj <<
/Length 4077
/Filter /FlateDecode
>>
stream
x??ZYs?6~????9U.?#??Udg?M*qYJ???T-4?fq? #Z????<FT?}
lt7??n???_???4?s???????"
3????<???^?V?z??M?z??m?^????V???o??S'm6?????.??/Sx??Y?av?MB?*b^?f??/?IO??B??q??/?(??aT?a?##??,?%???Z8? ?]??-?\?]??????nw?2?;?????Z?;?[}??????&J=ml??-??V?|??:??"?(?Gf??D??~?QW?U?Z???cP?b???QX
(This operation might be simpler using the high level HttpConnection api, but I wish to understand how everything works at the most basic level, and hence I am using the SocketConnection api instead.)
In short, what I wish my app to do is simply interpret the data replied by the server correctly, either as string or binary, and then accordingly store the binary file (possibly discarding the string HTTP headers).
I found the solution. Below is the working code.
I am first storing the header response as a string. Headers are terminated by \r\n\r\n, (so, read in bytes upto these characters). Later am storing the (possibly) binary data in a file separately.
public String FileDownloadNonPersistently() {
String server_reply = new String();
try {
sc = (SocketConnection) Connector.open("socket://" + hostname + ":" + port);
os = sc.openOutputStream();
os.write(("GET " + link_to_file_to_be_downloaded +
" HTTP/1.0\r\n").getBytes("UTF-8"));
os.write(("HOST: " + hostname + "\r\n").getBytes("UTF-8"));
os.write(("\r\n").getBytes("UTF-8"));
os.flush();
os.close();
in = sc.openInputStream();
// 1. Read the response header from server separately beforehand.
byte data;
String temp_char = "";
while (!"\r\n\r\n".equals(temp_char)) {
data = (byte) in.read();
server_reply += String.valueOf((char) data);
if (((char) data) == '\r' || ((char) data) == '\n') {
temp_char += String.valueOf((char) data);
} else {
temp_char = "";
}
}
// 2. Recieving the actual data, be it text or binary
current = 0;
mybytearray = new byte[filesize];
bytesRead = in.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead = in.read(mybytearray, current,
(mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
// Store recieved data to file, if set true from options
if (tcp_save_downloaded_file == true) {
// decide an appropriate file name acc. to download link
String url = "file:///E:/Data/" + "tcp_downloaded_file.pdf";
FileConnection fconn = (FileConnection)
Connector.open(url, Connector.READ_WRITE);
if (!fconn.exists()) { // XXX. what if file already present? overwrite or append mode?
fconn.create();
}
OutputStream ops = fconn.openOutputStream();
ops.write(mybytearray, 0 , current);
ops.flush();
ops.close();
}
} catch (Exception ex) {
parent_class.main_form.append("Exception occured while "
+ "downloading file: " + ex.toString() + "\n\n");
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
parent_class.main_form.append("Exception occured while "
+ "closing inputstream "
+ "after downloading file: " + ex.toString() + "\n\n");
}
}
// XXX. see if you need to close the OutputStreams and
// SocketConnection as well.
return server_reply;
}
}
The first 10 lines are the HTTP message headers. For more information on them please go to https://www.rfc-editor.org/rfc/rfc2616#page-31.
The blank line identifies where the body starts.
You can start saving the pdf content from line 12 onwards, but you should do it using a different read method.
Instead of
data = (byte) in.read();
while (data != -1) {
ops.write(data);
data = (byte) in.read();
}
please try
byte buff[] = new byte[1024];
int len = in.read(buff);
while (len > 0) {
ops.write(buff, 0, len);
len = in.read(buff);
}