Script is getting hanged and not giving any output - java

I have return one script which on execution modifies a line in one file.
Flow for working script is from run method after printing checkpoint 111 it is going to executeCmd method after printing checkpoint aaaa, execution again goes to run method prints checkpoint 222 and comeback to executeCmd method and exit the execution after printing bbb.
But in my case after checkpoint aaa it is printing checkpoint bbb and this loop is never ending so execution is not going back to run method and hence script is stuck and hangs the session.
public String executeCmd(String classOpts, String cmdLine, String[] opts)
{
while (myCmd.isAlive() == true)
{
try
{
log.debug("checkpoint aaaa");
Thread.sleep(100);
log.debug("checkpoint bbbb");
}
}
exitVal = myCmd.getCmdExitValue();
log.debug("The script exit code: = " + exitVal);
}
public void run()
{
Runtime rt = Runtime.getRuntime();
try
{
String sCommand = cmdUtils.sScriptLauncher + " " + this.cmdline;
proc = rt.exec(cmdUtils.sScriptLauncher + " " + this.cmdline;
proc = rt.exec(cmdUtils.ParseCommandLine(sCommand));
try
{
log.debug("Checkpoint 111");
cmdExitVal = proc.waitFor();`enter code here`
log.debug("Checkpoint 222");
}
//remaining code

I use following class RunProcessCMD that uses ProcessBuilder, stdout and stderr:
class RunProcessCMD {
static BufferedReader stdout, stderr;
private Boolean isWaitFor = true;// wait for reply from CMD
private static RunProcessCMD startRunProcessCMD = null;
private String[] input = null;
private static boolean isRealTime = false;
private static StringBuilder buff = null;
public static RunProcessCMD getInstance(){
if(startRunProcessCMD == null){
startRunProcessCMD = new RunProcessCMD();
}
return startRunProcessCMD;
}
private RunProcessCMD(){}// destroy public constructor
public void start(String[] command) throws IOException {
buff = new StringBuilder();
System.out.println(Arrays.asList( command ) );
ProcessBuilder launcher = new ProcessBuilder();
launcher.redirectErrorStream(true);
launcher.command(command);
launcher.start(); // And launch a new process
buff.append("Done").append("\n");System.out.println("Done.");
}
public void start () throws IOException, InterruptedException{
buff = new StringBuilder();
if(input == null){
buff.append("Command == null");
return;
}
//String[] input = new String[] {"tasklist"};
Runtime r = Runtime.getRuntime();
//System.out.println("Execute ...");
//Process p = r.exec("cmd /c", input, null);
System.out.println(Arrays.asList( input ) );
Process p = r.exec(input);
//System.out.println("Finish to execute, start read output");
InputStream is = p.getInputStream();
stdout = new BufferedReader(new InputStreamReader(is));
is = p.getErrorStream();
stderr = new BufferedReader(new InputStreamReader(is));
//outputLines = new Vector();
if( isWaitFor == true ){
StdoutThread cltOut = RunProcessCMD.getInstance().new StdoutThread();
Thread tOut = new Thread(cltOut);
tOut.start();
StderrThread cltErr = RunProcessCMD.getInstance().new StderrThread();
Thread tErr = new Thread(cltErr);
tErr.start();
p.waitFor();
}
buff.append("Done").append("\n");System.out.println("Done.");
if( isWaitFor == false ){
buff.append("WaitFor defined to be false, respectivally no output from CMD").append("\n");
System.out.println("WaitFor defined to be false, respectively no output from CMD");
}
}
private class StdoutThread implements Runnable {
#Override
public void run() {
try {
int l;
String line;
for(l = 0; (line = stdout.readLine()) != null; ) {
if (line.length() > 0)
l++;
//outputLines.addElement(line);
buff.append(line).append("\n");
if(!line.trim().equals("")){
System.out.println(line);
}
}
stdout.close();
}
catch(IOException ie) {
buff.append("IO exception on stdout: " + ie).append("\n");
}
}
}
private class StderrThread implements Runnable {
public StderrThread() {}
#Override
public void run() {
try {
int l;
String line;
for(l = 0; (line = stderr.readLine()) != null; ) {
if (line.length() > 0) l++;
buff.append(line).append("\n");
System.out.print(line);
}
stderr.close();
}
catch(IOException ie) {
buff.append("IO exception on stdout: " + ie).append("\n");//System.out.println("IO exception on stdout: " + ie);
}
}
}
public static void ClearBuff (){
buff.setLength(0);
isRealTime = false;
}
public void setInput(String[] input) {
// reset flag
isWaitFor = true;
if(input[input.length-1].contains("waitFor") && input[input.length-1].split("=").length == 2 ){
String bull = input[input.length-1].split("=")[1];
isWaitFor = new Boolean( bull );
System.out.println("isWaitFor = " + isWaitFor);
// remove last value from String array
String[] input_new = new String[input.length -1];
for(int k=0; k < input_new.length; k++){
input_new[k] = input[k];
}
input = input_new;
}
// add proper value for input
String[] str = new String[input.length + 2];
str[0] = "cmd.exe";
str[1] = "/c";
for(int i=2; i<str.length; i++){
str[i] = input[i-2];
}
this.input = str;
}
public static StringBuilder getBuff() {
if( buff == null ){
return new StringBuilder( "" );
}
return buff;
}
public void setRealTime(boolean b) {
isRealTime = b;
}
}
Usage:
private void runSomeCommandOverCmd(){
String runP = "adb devices";
String[] strArr = new String[2];
strArr[0] = runP;
strArr[1] = "waitFor=true";
RunProcessCMD.getInstance().setInput( strArr );
try {
RunProcessCMD.getInstance().start();
String str = ( RunProcessCMD.getBuff() ).toString();
System.out.println(str);
RunProcessCMD.ClearBuff();
} catch (Exception e) {
try {
throw new Exception( "Failed to Start process CMD" );
} catch (Exception e1) {
e1.printStackTrace();
}
}
}

Related

String[] cannot be converted to State[]

Just wondering what I have done wrong here I'm getting an error in the method setLine() which is:
error: incompatible types: String[] cannot be converted to State[]
Im not too sure on what to do to fix it since I need the line to be split and stored in that state array so I can determine whether if it is a state or location when reading from a csv file.
public static void readFile(String inFilename)
{
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
int stateCount = 0, locationCount = 0;
String line;
try
{
fileStrm = new FileInputStream(inFilename);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
line = bufRdr.readLine();
while (line != null)
{
if (line.startsWith("STATE"))
{
stateCount++;
}
else if (line.startsWith("LOCATION"))
{
locationCount++;
}
line = bufRdr.readLine();
}
fileStrm.close();
State[] state = new State[stateCount];
Location[] location = new Location[locationCount];
}
catch (IOException e)
{
if (fileStrm != null)
{
try { fileStrm.close(); } catch (IOException ex2) { }
}
System.out.println("Error in file processing: " + e.getMessage());
}
}
public static void processLine(String csvRow)
{
String thisToken = null;
StringTokenizer strTok;
strTok = new StringTokenizer(csvRow, ":");
while (strTok.hasMoreTokens())
{
thisToken = strTok.nextToken();
System.out.print(thisToken + " ");
}
System.out.println("");
}
public static void setLine(State[] state, Location[] location, int stateCount, int locationCount, String line)
{
int i;
state = new State[stateCount];
state = line.split("="); <--- ERROR
for( i = 0; i < stateCount; i++)
{
}
}
public static void writeOneRow(String inFilename)
{
FileOutputStream fileStrm = null;
PrintWriter pw;
try
{
fileStrm = new FileOutputStream(inFilename);
pw = new PrintWriter(fileStrm);
pw.println();
pw.close();
}
catch (IOException e)
{
if (fileStrm != null)
{
try
{
fileStrm.close();
}
catch (IOException ex2)
{}
}
System.out.println("Error in writing to file: " + e.getMessage());
}
}
This error occurs, as it just says 'String[] cannot be converted to State[]'. That is like you wanted to store an Integer into a String, it's the same, because the types don't have a relation to each other (parent -> child).
So if you want to solve your problem you need a method which converts the String[] into a State[]. Something like this:
private State[] toStateArray(String[] strings){
final State[] states = new State[strings.length];
for(int i = strings.length-1; i >= 0; i--){
states[i] = new State(strings[i]); // here you have to decide how to convert String to State
}
return states;
}

Pass input to bash script using java input stream and collect bash script output to java output stream using thread

I am trying to pass input to bash script using java input stream and collect bash script output to java output stream using two different thread.
my bash script is:
#!/bin/sh
echo "added at start"
while read LINE; do
echo $LINE
done
and my Java code is:
public class NewRedirector implements Runnable {
private static final int BULK_BUFFER_SIZE = 500000;
private static final int READ_BUFFER_SIZE = 250000;
private static final int OFFSET = 0;
private final OutputStream targetStream;
private final InputStream sourceStream;
private final boolean useChannel;
public NewRedirector(InputStream sourceStream , OutputStream targetStream, boolean useChannel) {
this.sourceStream = sourceStream;
this.targetStream = targetStream;
this.useChannel = useChannel;
}
#Override
public void run() {
byte[] readbyte = new byte[READ_BUFFER_SIZE];
int dataSize = 0;
try {
if(targetStream instanceof FileOutputStream && useChannel) {
FileChannel targetFC = ((FileOutputStream) targetStream).getChannel();
try {
if(sourceStream instanceof FileInputStream && useChannel) {
FileChannel sourceFC = ((FileInputStream) sourceStream).getChannel();
ByteBuffer bb = ByteBuffer.allocateDirect(BULK_BUFFER_SIZE);
bb.clear();
dataSize = 0;
while ((dataSize = sourceFC.read(bb)) > 0) {
bb.flip();
while (bb.hasRemaining()) {
targetFC.write(bb);
}
bb.clear();
}
} else {
ByteBuffer bb = ByteBuffer.allocateDirect(BULK_BUFFER_SIZE);
dataSize = 0;
while ((dataSize = sourceStream.read(readbyte)) > 0) {
if(BULK_BUFFER_SIZE > bb.position() + dataSize) {
bb.put(readbyte, OFFSET, dataSize);
continue;
} else {
bb.flip();
targetFC.write(bb);
bb.clear();
}
bb.put(readbyte, OFFSET, dataSize);
}
if(bb.position() > 0) {
bb.flip();
targetFC.write(bb);
bb.clear();
}
}
} catch(IOException e) {
System.out.println("Got Exception: " + e);
} finally {
if(targetFC != null && targetFC.isOpen()) {
targetFC.close();
targetFC = null;
}
}
} else {
BufferedOutputStream btarget = new BufferedOutputStream(targetStream);
try {
if (sourceStream instanceof FileInputStream && useChannel) {
FileChannel sourceFC = ((FileInputStream) sourceStream).getChannel();
ByteBuffer bb = ByteBuffer.allocateDirect(BULK_BUFFER_SIZE);
bb.clear();
dataSize = 0;
while ((dataSize = sourceFC.read(bb)) > 0) {
bb.position(OFFSET);
bb.limit(dataSize);
while (bb.hasRemaining()) {
dataSize = Math.min(bb.remaining(), READ_BUFFER_SIZE);
bb.get(readbyte, OFFSET, dataSize);
btarget.write(readbyte, OFFSET, dataSize);
}
btarget.flush();
bb.clear();
}
} else {
dataSize = 0;
while ((dataSize = sourceStream.read(readbyte)) > 0) {
btarget.write(readbyte, OFFSET, dataSize);
}
btarget.flush();
}
} catch(IOException e) {
System.out.println("Got Exception: " + e);
} finally {
if(btarget != null) {
btarget.close();
btarget = null;
}
}
}
} catch (IOException e) {
System.out.println("Got Exception: " + e);
}
}
}
and
public class NewProcessExecutor {
public static void main(String ... args) throws IOException, InterruptedException {
NewProcessExecutor pe = new NewProcessExecutor();
pe.startProcessinputfromstreamoutputtostreamintwothread();
}
private void startProcessinputfromstreamoutputtostreamintwothread()
throws IOException, InterruptedException {
String lscriptLocation = "/scratch/demo/RunScript/append.sh";
File inFile = new File("/scratch/demo/Source/inFile");
File outFile = new File("/scratch/demo/Source/outFile");
ProcessBuilder processBuilder = new ProcessBuilder(lscriptLocation);
/*processBuilder.redirectInput(Redirect.PIPE);
processBuilder.redirectOutput(Redirect.PIPE);*/
Process process = processBuilder.start();
if(Redirect.PIPE.file() == null && Redirect.PIPE.type() == Redirect.Type.PIPE) {
System.out.println("IO connected over PIPE");
}
//startStreamRedirector(new FileInputStream(inFile), process.getOutputStream());
startStreamRedirector(process.getInputStream(), new FileOutputStream(outFile));
int exitvalue = process.waitFor();
System.out.println("Exit value: " + exitvalue);
if (exitvalue != 0) {
System.out.println("Script execution failed with error: "
+ readErrorStream(process.getErrorStream()));
return;
} else {
System.out.println("Script executed successfully, please see output file: " + outFile.getAbsolutePath());
}
}
private String readErrorStream(InputStream errorStream) {
StringBuilder sb = new StringBuilder();
try (BufferedReader buffR = new BufferedReader(new InputStreamReader(
errorStream))) {
String line = null;
while ((line = buffR.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
System.out.println("Got Exception: " + e);
}
return sb.toString();
}
private void startStreamRedirector(InputStream inputStream, OutputStream outputStream) {
new Thread(new NewRedirector(inputStream, outputStream, true)).start();
}
}
Now the problem is this code sometime runs perfectly but some times it creates zero size file.
Can someone point out what could be the issue?
As per my information default redirect is PIPE so hope I don't need set redirect input and output to PIPE.
processBuilder.redirectInput(Redirect.PIPE)

how to remove 503 exceptions in java

I have a list of names in the form of a CSV and I am up for google searching those names using java. But the problem that i am facing is that when i initially run the code i am able to search the query but in the middle of the code the code starts to throw 503 exceptions and when i again run the code it starts throwing 503 exceptions from the very beginning.Here is the code that i am using.
public class ExtractInformation
{
static String firstname,middlename,lastname;
public static final int PAGE_NUMBERS = 10;
public static void readCSV()
{
boolean first = true;
try
{
String splitBy = ",";
BufferedReader br = new BufferedReader(new FileReader("E:\\KOLDump\\names.csv"));
String line = null;
String site = null;
while((line=br.readLine())!=null)
{
if(first)
{
first = false;
continue;
}
String[] b = line.split(splitBy);
firstname = b[0];
middlename = b[1];
lastname = b[2];
String name = null;
if(middlename == null || middlename.length() == 0)
{
name = firstname+" "+lastname+" OR "+lastname+" "+firstname.charAt(0);
}
else
{
name = firstname+" "+lastname+" OR "+lastname+" "+firstname.charAt(0)+" OR "+firstname+" "+middlename.charAt(0)+". "+lastname;
}
BufferedReader brs = new BufferedReader(new FileReader("E:\\KOLDump\\site.csv"));
while((site = brs.readLine()) != null)
{
if(first)
{
first = false;
continue;
}
String [] s = site.split(splitBy);
String siteName = s[0];
siteName = (siteName.replace("www.", ""));
siteName = (siteName.replace("http://", ""));
getDataFromGoogle(name.trim(), siteName.trim());
}
brs.close();
}
//br.close();
}
catch(Exception e)
{
System.out.println("unable to read file...some problem in the csv");
}
}
public static void main(String[] args)
{
readCSV();
}
private static void getDataFromGoogle(String query,String siteName)
{
Set<String> result = new HashSet<String>();
String request = "http://www.google.co.in/search?q="+query+" "+siteName;
try
{
Document doc = Jsoup.connect(request).userAgent("Chrome").timeout(10000).get();
Element query_results = doc.getElementById("ires");
Elements gees = query_results.getElementsByClass("g");
for(Element gee : gees)
{
Element h3 = gee.getElementsByTag("h3").get(0);
String annotation = h3.getElementsByTag("a").get(0).attr("href");
if(annotation.split("q=",2)[1].contains(siteName))
{
System.out.println(annotation.split("q=",2)[1]);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
any suggestions on how to remove this exceptions from the code would really be helpful.
If you wait a little do the 503's go away? If so, then you're probably being rate-limited by Google. https://support.google.com/gsa/answer/2686272?hl=en
You may need to put some kind of delay between requests.

Java : Unable to get the List size during Thread Processing

I am processing a File in java where i am counting the number of occurrences of a particular Filed in every line of that file Where i am starting a Thread for every Line
as shown below
input = new BufferedReader(new FileReader(new File(finaName)));
String line = null;
while ((line = input.readLine()) != null) {
FileThread t = new FileThread(line);
t.start();
}
FileThread st = new FileThread();
System.out.println("Size"+st.list.size());
FileThread.java
public class FileThread extends Thread
List<String> list = new ArrayList<String>();
public FileThread(){}
public FileThread(String line){}
private String line = null;
public void run() {
String[] tokens = line.split("\\|", LIST.length);
String Symbol = null;
try {
Symbol = tokens[4];
list.add(symbol);
} catch (Throwable t1) {
t1.printStackTrace();
}
}
The problem is that i am always getting the Size as 0 .
please see the sample output
BIM!A
BIM!B
BIM!C
BIM!D
Size0
I have made some changes in your code, that may help you
public class FileThread extends Thread {
private List<String> list = new ArrayList<String>();
private boolean inThread = false;
.......
public int getListSize() {
if(!inThread)
return list != null ? list.size() : 0 ;
else
return 0;
}
public FileThread(String line) {
}
public void run() {
inThread = true;
// You logic of the thread
inThread = false;
}
public static void main(String args[]) throws IOException {
..............
..............
..............
System.out.println("Size" + st.getListSize());
}
}

How can I read the registry values using java? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
read/write to Windows Registry using Java
I want to read the registry value of the path HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Uninstall\{2FC099BD-AC9B-33EB-809C-D332E1B27C40}.
Can you please help me with the code?
This shows how to read the registry, but could be extended to write operations: How to read the Windows Registry
import java.io.*;
public class RegQuery {
private static final String REGQUERY_UTIL = "reg query ";
private static final String REGSTR_TOKEN = "REG_SZ";
private static final String REGDWORD_TOKEN = "REG_DWORD";
private static final String PERSONAL_FOLDER_CMD = REGQUERY_UTIL +
"\"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\"
+ "Explorer\\Shell Folders\" /v Personal";
private static final String CPU_SPEED_CMD = REGQUERY_UTIL +
"\"HKLM\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\""
+ " /v ~MHz";
private static final String CPU_NAME_CMD = REGQUERY_UTIL +
"\"HKLM\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\""
+ " /v ProcessorNameString";
public static String getCurrentUserPersonalFolderPath() {
try {
Process process = Runtime.getRuntime().exec(PERSONAL_FOLDER_CMD);
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
String result = reader.getResult();
int p = result.indexOf(REGSTR_TOKEN);
if (p == -1)
return null;
return result.substring(p + REGSTR_TOKEN.length()).trim();
}
catch (Exception e) {
return null;
}
}
public static String getCPUSpeed() {
try {
Process process = Runtime.getRuntime().exec(CPU_SPEED_CMD);
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
String result = reader.getResult();
int p = result.indexOf(REGDWORD_TOKEN);
if (p == -1)
return null;
// CPU speed in Mhz (minus 1) in HEX notation, convert it to DEC
String temp = result.substring(p + REGDWORD_TOKEN.length()).trim();
return Integer.toString
((Integer.parseInt(temp.substring("0x".length()), 16) + 1));
}
catch (Exception e) {
return null;
}
}
public static String getCPUName() {
try {
Process process = Runtime.getRuntime().exec(CPU_NAME_CMD);
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
String result = reader.getResult();
int p = result.indexOf(REGSTR_TOKEN);
if (p == -1)
return null;
return result.substring(p + REGSTR_TOKEN.length()).trim();
}
catch (Exception e) {
return null;
}
}
static class StreamReader extends Thread {
private InputStream is;
private StringWriter sw;
StreamReader(InputStream is) {
this.is = is;
sw = new StringWriter();
}
public void run() {
try {
int c;
while ((c = is.read()) != -1)
sw.write(c);
}
catch (IOException e) { ; }
}
String getResult() {
return sw.toString();
}
}
public static void main(String s[]) {
System.out.println("Personal directory : "
+ getCurrentUserPersonalFolderPath());
System.out.println("CPU Name : " + getCPUName());
System.out.println("CPU Speed : " + getCPUSpeed() + " Mhz");
}
}
There's a tutorial that shows you without using Runtime.exec() function and uses specifically java.util.prefs.WindowsPreferences.

Categories

Resources