I have a class with this code
public boolean busybox() throws IOException
{
try
{
Process p =Runtime.getRuntime().exec("busybox");
InputStream a = p.getInputStream();
InputStreamReader read = new InputStreamReader(a);
BufferedReader in = new BufferedReader(read);
StringBuilder buffer = new StringBuilder();
String line = null;
try {
while ((line = in.readLine()) != null) {
buffer.append(line);
}
} finally {
read.close();
in.close();
}
String result = buffer.toString().substring(0, 15);
System.out.println(result);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
In another class I have this code
try {
if(root.busybox()) {
Busybox.setText(Html.fromHtml((getString(R.string.busybox))));
}
else {
Busybox.setText(Html.fromHtml((getString(R.string.no))));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
If I want to write in this TextView the outpout generated by System.out.println(result);
How can i do? Thanks in advance! I made several attempts, but I have several errors and the code is wrong.
change return type of public boolean busybox() to string like public String busybox() and return result.
then use
try {
String myResult=root.busybox();
if(myResult!=null&&myResult.length>0) {
Busybox.setText(Html.fromHtml((myResult)));
}
else {
Busybox.setText(Html.fromHtml((getString(R.string.no))));
}
}
Related
I am facing some difficulties with testing constructor of my class using JUnit 4.13. What I am trying to do is to test that constructor is throwing FileNotFoundExeption when I pass wrong file name.
This is my constructor (parameter 'file' is name of file where I store languages):
public LanguageManager(String file) {
this.languages = new ArrayList<Language>();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
String line;
while((line = in.readLine()) != null) {
line = line.trim();
if (line.equals("") || line.startsWith("#"))
continue;
Language j = new Language(line);
this.languages.add(j);
}
in.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
This is my function for testing this constructor:
#Test(expected=FileNotFoundException.class)
public void testLanguageManager() {
LanguageManager ajm = new LanguageManager("non_existing_file.txt");
}
I suspect that there is problem with try catch block in constructor but can't figure out what I am doing wrong. Any help is appreciated.
here is code
private static class NgrokRunner implements Runnable {
private InputStream inputStream;
private boolean doStop = false;
public NgrokRunner(InputStream inputStream) {
this.inputStream = inputStream;
}
#Override
public void run() {
// TODO Auto-generated method stub
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
try {
while((line = reader.readLine()) != null) {
System.out.println(line);
if (keepRunning()) {
continue;
} else {
System.out.println("break ----");
break;
}
}
} catch (Exception e) {
//TODO: handle exception
System.out.println("Ngrok exception");
}
}
public synchronized void doStop() {
this.doStop = true;
}
private synchronized boolean keepRunning() {
return this.doStop == false;
}
}
and i started above thread like this
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("ngrok", "http","8080", "--log=stdout");
try {
Process process = processBuilder.start();
NgrokRunner runner = new NgrokRunner(process.getInputStream());
Thread ngrokThread = new Thread(runner);
ngrokThread.start();
for (int i = 0; i < 4; i++) {
System.out.println(i);
Thread.sleep(10L * 100L);
}
//System.out.println("It works");
runner.doStop();
} catch (Exception e) {
//TODO: handle exception System.out.println(e);
}
But in while loop my child thread which is reading input from ngrok , blocking and even after calling doStop() it never reached at if condition where i am checking bool flag to exit from thread.
Well can anyone suggest me logic to achieve my ideal situation.
what i want is "Run ngrok server through binary file of ngrok in a thread and close the thread/ngrok whenever i want ( like when user wants through a pause/end button )"
ok so i solved it and here is final solution
run() code :
#Override
public void run() {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
try {
while(!Thread.interrupted()) {
if (!reader.ready()) {
try {
Thread.sleep(1000);
continue;
} catch (InterruptedException e) {
//TODO: handle exception
System.out.println("We got interrupted");
return;
}
}
line = reader.readLine();
System.out.println(line);
}
} catch (IOException e) {
//TODO: handle exception
System.out.println("Ngrok exception" + e);
}
}
Now from main thread
try {
process = processBuilder.start();
NgrokRunner runner = new NgrokRunner(process.getInputStream());
ngrokThread = new Thread(runner);
ngrokThread.start();
for (int i = 0; i < 8; i++) {
System.out.println(i);
Thread.sleep(1000);
}
ngrokThread.interrupt();
} catch (Exception e) {
//TODO: handle exception
System.out.println(e);
}
I have a Java program that reads from a cvs file that looks like this:
2000;Mall1;8
2002;Mall3;23
2003;Mall4;31
...
I want the program to read from the cvs file into an array and sort the array based on the third column/field.
However, whenever I print the elements of array[2] I get an ArrayIndexOutOfBoundException. I can't see why is this happening since the array's[2] size should be already fixed.
Here is the code:
import java.util.*;
import java.io.*;
public class Prog3
{
public static void main(String[] args)
{
String csvFile = "test.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] array = line.split(cvsSplitBy);
System.out.println(array[2]);
Arrays.sort(array[2]);
System.out.println("Sorted\n" + Arrays.toString(array[2]));
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ArrayIndexOutOfBoundsException e)
{
e.printStackTrace();
}
finally {
if (br != null)
{
try
{
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
Any help is appreciated :)
My requirement is to connect to some server through telnet using a java program and run few commands and read the responses. Based on these responses I need to perform some operation
I strated with https://stackoverflow.com/a/1213188/1025328
I'm using commons-net and my program is something like this:
public class TelnetSample {
private TelnetClient telnet;
private InputStream in;
private PrintStream out;
public TelnetSample(String server, int port) {
try {
// Connect to the specified server
telnet = new TelnetClient();
telnet.connect(server, port);
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
public String readResponse() {
System.out.println("TelnetSample.readResponse()");
StringBuilder out = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(out.toString());
System.out.println("==========================================================");
return out.toString();
}
public String read2() {
System.out.println("TelnetSample.read()");
StringBuffer sb = new StringBuffer();
try {
int available = in.available();
for (int index = 0; index < available; index++) {
char ch = (char) in.read();
System.out.print(ch);
sb.append(ch);
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
public String sendCommand(String command) {
try {
InputStream is = new ByteArrayInputStream(command.getBytes());
int ch;
while ((ch = is.read()) != -1) {
out.write(ch);
out.flush();
}
System.out.println(command);
String output = read2();
if (output.trim().isEmpty()) {
System.out.println("output empty");
} else {
System.out.println(output);
}
System.out.println("==========================================================");
return output;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void disconnect() {
try {
telnet.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
TelnetSample telnet = new TelnetSample("aspmx2.xxxxxx.com", 25);
telnet.readResponse();
telnet.sendCommand("Helo hi");
telnet.sendCommand("mail from:xyz#testmail.com");
telnet.sendCommand("rcpt to:pk#testmail.com");
telnet.sendCommand("quit");
telnet.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here apart form the telnet connection response, for every other sendCommand I'm getting an empty response. Can some one point me what could be the issue.
My output is something like this
TelnetSample.readResponse()
220 mx.xxxxxx.com ESMTP o86si4086625pfi.217 - gsmtp
==========================================================
Helo hi
TelnetSample.read()
output empty
==========================================================
mail from:xyz#testmail.com
TelnetSample.read()
output empty
==========================================================
rcpt to:pk#testmail.com
TelnetSample.read()
output empty
==========================================================
quit
TelnetSample.read()
output empty
==========================================================
This code has several issue:
the first issue is in readResponse method. When you use
readLine() you can easy block your code and will wait forever. Please have a look at discussion How to determine the exact state of a BufferedReader?
the second you don't send any CR/LF chars. Server got your requests like a single line. Ex:
mail from:xyz#testmail.comrcpt to:pk#testmail.comquit
To fix first issue you can choose several ways:
use multi-threading model
use NIO API. I would recommend Netty for that. Especially for your case as i can see you didn't use Telnet protocol at all, you connected to SMTP server.
Quick fix but the worst, wait first line from server and go on:
public String readResponse() {
System.out.println("TelnetSmtpSample.readResponse()");
StringBuilder out = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
out.append(reader.readLine());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(out.toString());
System.out.println("=====================");
return out.toString();
}
To fix second one:
telnet.sendCommand("Helo hi\r\n");
telnet.sendCommand("mail from:xyz#testmail.com\r\n");
telnet.sendCommand("rcpt to:pk#testmail.com\r\n");
telnet.sendCommand("quit\r\n");
It's possible read2 is getting a null value back from the input stream before data is actually returned. Try something like this:
private String read2() {
StringBuffer sb = new StringBuffer();
try {
do {
if (in.available() > 0) {
char ch = (char) in.read();
sb.append(ch);
} else {
Thread.sleep(1000);
}
} while (in.available()>0);
String output = new String(sb);
return output;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
I am trying to write a method in java, where I take some information from a file and see if the file has the information the user looks for. However, for the code that I present, eclipse signs that I have an resource leak in line "return true;" and that the "br = new BufferedReader(fr);" is never close, despite the fact that I am using the close() method at the end of the program. Apparently I am missing something. Could someone help me figure out what is happening? Great thanks in advance!
import java.io.*;
class Help{
String helpfile;
Help(String fname){
helpfile = fname;
}
boolean helpon(String what){
FileReader fr;
BufferedReader br;
int ch;
String topic, info;
try{
fr = new FileReader(helpfile);
br = new BufferedReader(fr);
}
catch(FileNotFoundException e){
System.out.println(e);
return false;
}
try{
do{
ch = br.read();
if(ch=='#'){
topic = br.readLine();
if(what.compareTo(topic) == 0){
do{
info = br.readLine();
if(info!=null)
System.out.println(info);
}while((info!= null) && (info.compareTo("")!= 0));
return true;
}
}
}while(ch!=-1);
}
catch(IOException e){
System.out.println(e);
return false;
}
try{
br.close();
}
catch(IOException e){
System.out.println(e);
}
return false;
}
}
The issue is that you're returning before the program gets the chance to close the resource. There are 2 ways to fix this issue:
Put the returns after you close the resource (by possibly putting the return result in a boolean).
Modify your code to put the close in a finally block so any return done will still execute that code.
Number 2 is generally a more accepted practice because then if you add more things in the future you are still guaranteed to close the resource (unless a catastrophic event occurs).
boolean helpon(String what){
FileReader fr;
BufferedReader br;
int ch;
String topic, info;
try{
fr = new FileReader(helpfile);
br = new BufferedReader(fr);
do{
ch = br.read();
if(ch=='#'){
topic = br.readLine();
if(what.compareTo(topic) == 0){
do{
info = br.readLine();
if(info!=null)
System.out.println(info);
}while((info!= null) && (info.compareTo("")!= 0));
return true;
}
}
}while(ch!=-1);
} catch(IOException e){
System.out.println(e);
return false;
} catch(FileNotFoundException e){
System.out.println(e);
return false;
} finally {
try {
if (br != null) {
br.close();
}
} catch(IOException e){
System.out.println(e);
return false;
}
}
}
You have return statements all over the method, but only have a br.close() at the end. It's possible in the flow of code that the method will be returned leaving the br still open.
You may be interested in using try with resources
try (
FileReader fr = new FileReader(helpfile);
BufferedReader br = new BufferedReader(fr)
)
{
//your code
}
catch (IOException e)
{
//error
}
With this, the close methods will automatically be called for you on the resources.
You should put the call to close() in a finally block. In the current state, your code will never reach the final try/catch because you are returning true or false.
try {
fr = new FileReader(helpfile);
br = new BufferedReader(fr);
do {
ch = br.read();
if(ch=='#'){
topic = br.readLine();
if(what.compareTo(topic) == 0){
do{
info = br.readLine();
if(info!=null)
System.out.println(info);
}while((info!= null) && (info.compareTo("")!= 0));
return true;
}
}
}while(ch!=-1);
} catch (IOException e) {
System.out.println(e);
return false;
} catch (FileNotFoundException e) {
System.out.println(e);
return false;
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException e) {
System.out.println(e);
}
}
If you're using Java 7, use the try-with-resources functionality:
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html