I am facing a problem in Java jsch. I have opened a Shell channel and I have a list of commands that I want to execute and read from the shell.
But in that commands list, there's one command that needs to be scrolled down in the shell to be shown until its end.
I am strugling to implement this auto-scroller for that command.
In my code What I did:
ChannelShell channelShell = (ChannelShell) session.openChannel("shell");
OutputStream inputstream_for_the_channel = channelShell.getOutputStream();
InputStream outputstream_from_the_channel = channelShell.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(outputstream_from_the_channel));
PrintStream commander = new PrintStream(inputstream_for_the_channel, true);
channelShell.connect();
if (!commands.get(0).equals("show system information | match \"System Name\"")) {
commands.add(0, "show system information | match \"System Name\"");
}
String readString = "";
String line;
int index = 0;
for (String cmd : commands) {
System.out.println(cmd);
commander.println(cmd);
try {
Thread.sleep(commandsSleep);
} catch (Exception ee) {
}
while ((line = reader.readLine()) != null)
{
if (cmd.equals("admin display-config")) {
commander.println("");
}
GuiApp.textAreaLog.append("\n"+ ++index + " : " + line);
System.out.println(index + " : " + line);
readString += (line+"\n");
}
}
if (routerType.equals("nokia")) {
commander.println("logout");
System.out.println("logout");
try {
Thread.sleep(commandsSleep);
} catch (Exception ee) {
}
} else if (routerType.equals("linux")){
commander.println("exit");
}
commander.close();
channelShell.disconnect();
try {
Thread.sleep(commandsSleep);
} catch (Exception ee) {
}
return readString;
In the part:
while ((line = reader.readLine()) != null)
{
if (cmd.equals("admin display-config")) {
commander.println("");
}
GuiApp.textAreaLog.append("\n"+ ++index + " : " + line);
System.out.println(index + " : " + line);
readString += (line+"\n");
}
Is where I tried to implement a While loop to read the reader until its null, and to add to the commander a printl with "" to try to scroll this problematic command further down.
What I managed to do was to insert a timelimiter to the readbuffer.
for (String cmd : commands) {
GuiApp.textAreaLog.append("\n"+"Running Command : " + cmd);
commander.println(cmd);
System.out.println(cmd);
if (cmd.equals("admin display-config")) {
commandDelay = commandsSleep*10;
}else{
commandDelay = commandsSleep;
}
line = reader.readLine();
while (line!=null)
{
System.out.println(++index + " : " + line);
readString += (line+"\n");
try {
line = timeLimiter.callWithTimeout(reader::readLine, commandsSleep, TimeUnit.MILLISECONDS, true);
} catch (Exception e) {
e.printStackTrace();
break;
}
}
try {
Thread.sleep(commandDelay);
} catch (Exception e) {
//e.printStackTrace();
}
GuiApp.textAreaLog.append("\n"+"Comando executado com sucesso");
}
Related
I created custom Twitch bot with using of cavariux library. I called this methods in main class.
bot.setOauth_Key("oauth:key_Value");
bot.connect();
bot.joinChannel(channel.toString());
bot.start();
Approximately one of the 5-6 launches of the bot is accompanied by an exception
java.net.SocketException: Connection reset by peer
. The stack trace indicates that the exception starts on this line.
while ((line = this.reader.readLine( )) != null && !stopped)
in TwitchBot class in method start(). I didn't change code of this library except adding utf encoding in method connect(String ip, int port).
this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
I've tested my bot on different PCs. On some machines I don't have this issue. On some I got this exception more often.
This is code of method start() in TwitchBot class.
public final void start()
{
if (isRunning()) return;
String line = "";
stopped = false;
try {
while ((line = this.reader.readLine( )) != null && !stopped) {
if (line.toLowerCase( ).startsWith("ping")) {
LOGGER.log(Level.INFO,"> PING");
LOGGER.log(Level.INFO,"< PONG " + line.substring(5));
this.writer.write("PONG " + line.substring(5) + "\r\n");
this.writer.flush();
} else if (line.contains("PRIVMSG"))
{
String str[];
str = line.split("!");
final User msg_user = User.getUser(str[0].substring(1, str[0].length()));
str = line.split(" ");
Channel msg_channel;
msg_channel = Channel.getChannel(str[2], this);
String msg_msg = line.substring((str[0].length() + str[1].length() + str[2].length() + 4), line.length());
LOGGER.log(Level.INFO,"> " + msg_channel + " | " + msg_user + " >> " + msg_msg);
if (msg_msg.startsWith(commandTrigger))
onCommand(msg_user, msg_channel, msg_msg.substring(1));
if (msg_user.toString().equals("jtv") && msg_msg.contains("now hosting")) {
String hoster = msg_msg.split(" ")[0];
onHost(User.getUser(hoster), msg_channel);
}
onMessage(msg_user, msg_channel, msg_msg);
} else if (line.contains(" JOIN ")) {
String[] p = line.split(" ");
String[] pd = line.split("!");
if (p[1].equals("JOIN"))
userJoins(User.getUser(pd[0].substring(1)), Channel.getChannel(p[2], this));
} else if (line.contains(" PART ")) {
String[] p = line.split(" ");
String[] pd = line.split("!");
if (p[1].equals("PART"))
userParts(User.getUser(pd[0].substring(1)), Channel.getChannel(p[2], this));
} else if (line.contains(" WHISPER ")) {
String[] parts = line.split(":");
final User wsp_user = User.getUser(parts[1].split("!")[0]);
String message = parts[2];
onWhisper(wsp_user, message);
} else if (line.startsWith(":tmi.twitch.tv ROOMSTATE")) {
} else if (line.startsWith(":tmi.twitch.tv NOTICE"))
{
String[] parts = line.split(" ");
if (line.contains("This room is now in slow mode. You may send messages every"))
{
LOGGER.log(Level.INFO,"> Chat is now in slow mode. You can send messages every " + parts[15] + " sec(s)!");
} else if (line.contains("subscribers-only mode")) {
if (line.contains("This room is no longer"))
LOGGER.log(Level.INFO,"> The room is no longer Subscribers Only!");
else
LOGGER.log(Level.INFO,"> The room has been set to Subscribers Only!");
} else {
LOGGER.log(Level.INFO,line);
}
} else if (line.startsWith(":jtv MODE "))
{
String[] p = line.split(" ");
if (p[3].equals("+o")) {
LOGGER.log(Level.INFO,"> +o " + p[4]);
} else {
LOGGER.log(Level.INFO,"> -o " + p[4]);
}
} else if (line.toLowerCase().contains("disconnected"))
{
LOGGER.log(Level.INFO, line);
this.connect();
} else
{
LOGGER.log(Level.INFO,"> " + line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
This is code of method connect() in TwitchBot class.
public void connect(String ip, int port)
{
if (isRunning()) return;
try{
if (user == null || user == "")
{
LOGGER.log(Level.SEVERE, "Please select a valid Username");
System.exit(1);
return;
}
if (oauth_key == null || oauth_key == "")
{
LOGGER.log(Level.SEVERE,"Please select a valid Oauth_Key");
System.exit(2);
return;
}
#SuppressWarnings("resource")
Socket socket = new Socket(ip, port);
this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream(),StandardCharsets.UTF_8));
this.writer.write("PASS " + oauth_key + "\r\n");
this.writer.write("NICK " + user + "\r\n");
this.writer.write("USER " + this.getVersion() + " \r\n");
this.writer.write("CAP REQ :twitch.tv/commands \r\n");
this.writer.write("CAP REQ :twitch.tv/membership \r\n");
this.writer.flush();
String line = "";
while ((line = this.reader.readLine()) != null)
{
if (line.indexOf("004") >= 0) {
LOGGER.log(Level.INFO,"Connected >> " + user + " ~ irc.twitch.tv");
break;
}else {
LOGGER.log(Level.INFO,line);
}
}
} catch (IOException e)
{
e.printStackTrace();
}
}
Thank you for the help
This error means that the peer (i.e. the Twitch server) closes abruptly your connection. See this answer for more details.
I don't know if you can do something to fix that because it can have various external origins (peer crash...). Maybe you can wait and try to reconnect later (note that you might be blacklisted if you connect too often).
So Im working of reading a file containing appointments that I wrote to earlier in my code. I want to sift through the text file and find appointments on a certain date and add them to an ArrayList but when the BufferedReader goes through it, it skips ever other line... Heres my code
public ArrayList<String> read(int checkDay, int checkMonth, int checkYear) {
ArrayList<String> events = new ArrayList<String>();
BufferedReader in = null;
String read;
try {
in = new BufferedReader(new FileReader("calendar.txt"));
while ((read = in.readLine()) != null) {
read = in.readLine();
String[] split = read.split(",");
System.out.println(read);
if (split[1].equals(Integer.toString(checkDay)) && split[2].equals(Integer.toString(checkMonth)) && split[3].equals(Integer.toString(checkYear))) {
events.add(split[0] + " : " + split[1] + "/" + split[2] + "/" + split[3]);
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
return events;
}
You are reading the line twice..
while ((read = in.readLine()) != null) { // here
read = in.readLine(); // and here
You have error here:
while ((read = in.readLine()) != null)
read = in.readLine();
you should keep the read = in.readLine() in the while. and remove the other line.
pl try this
you r using "read = in.readLine())" two times in while loop that why it is skiping the lomes
public ArrayList<String> read(int checkDay, int checkMonth, int checkYear) {
ArrayList<String> events = new ArrayList<String>();
BufferedReader in = null;
String read;
try {
in = new BufferedReader(new FileReader("calendar.txt"));
while ((read = in.readLine()) != null) {
String[] split = read.split(",");
System.out.println(read);
if (split[0].equals(Integer.toString(checkDay)) && split[1].equals(Integer.toString(checkMonth)) && split[2].equals(Integer.toString(checkYear))) {
events.add(split[0] + " : " + split[1] + "/" + split[2] + "/" + split[3]);
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
return events;
When I try to get information from a Socket (it's at localhost) it never returns what I want (info from my server) with php it works fine..
Java application: run & debug doesn't return anything
Glassfish server: run doesn't return anything, debug return all the info, everytime i debug
PHP Code:
$Socket = fsockopen($this->Host, $this->Port, $errno, $errstr, 5);
if(!$Socket) {
return false;
} else {
stream_set_timeout($Socket, 1);
stream_set_blocking($Socket, false);
fwrite($Socket, chr(6).chr(0).chr(255).chr(255).'info');
while(!feof($Socket)) {
$this->SocketData .= fgets($Socket, 8192);
}
fclose($Socket);
return true;
}
Java Code:
public static String serverInfo(String ip, Integer port) {
try (Socket socket = new Socket(ip, port)) {
//System.out.println("Connected to " + socket.getInetAddress() + " on port " + socket.getPort() + " from port " + socket.getLocalPort() + " of " + socket.getLocalAddress());
OutputStream os = socket.getOutputStream();
String info = ((char) 6 + "" + (char) 0 + "" + (char) 255 + "" + (char) 255 + "info");
System.out.println(info);
os.write(info.getBytes());
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuilder stb = new StringBuilder();
while (br.ready()) {
stb.append(br.readLine());
}
if (!stb.toString().isEmpty()) {
//System.out.println("Info: " + stb.toString());
return stb.toString();
} else {
//System.out.println("No answer from server.");
return null;
}
} catch (UnknownHostException e) {
System.err.println("I can't find " + ip);
} catch (SocketException e) {
System.err.println("Could not connect to " + ip);
} catch (IOException e) {
System.err.println(e);
}
return null;
}
What I was looking for, was to do the same as php does, connect to the socket, get the information and return/save/whatever with that information and I don't know what happens that only 1/100 times that I try, it returns something.
When I run in my web application AND debug, it returns EVERYTIME the info, something is really wrong and I can't figure it out..
PS: It's meant to get OTServer information.
I think this is not the right way to read from the br.
while (br.ready()) {
stb.append(br.readLine());
}
Try changing this to:
String line = null;
while ((line = br.readLine()) != null) {
stb.append(line);
}
Also, call os.close() after this line.
os.write(info.getBytes());
I have a Junit / Silkuli test that runs on windows 7 and is dependent on an external program already running.
How can I check if the external program is running from inside the test?
You can run command "tasklist" from within java and look at the returned list to see if your program is in the list. something like:
String program = "eclipse.exe"; //or any other process
String listOfProcesses = getCommandOutput("tasklist");
if (listOfProcesses == null || listOfProcesses.isEmpty()) {
System.err.println("Unable to automatically determine if " + program + " is running");
} else {
if (listOfProcesses.contains(program)) {
System.out.println(program + " is running!");
} else {
System.out.println(program + " is not running!");
}
}//else: process list can be retrieved
and get the output from a command using a method such as:
public static String getCommandOutput(String command) {
String output = null; //the string to return
Process process = null;
BufferedReader reader = null;
InputStreamReader streamReader = null;
InputStream stream = null;
try {
process = Runtime.getRuntime().exec(command);
//Get stream of the console running the command
stream = process.getInputStream();
streamReader = new InputStreamReader(stream);
reader = new BufferedReader(streamReader);
String currentLine = null; //store current line of output from the cmd
StringBuilder commandOutput = new StringBuilder(); //build up the output from cmd
while ((currentLine = reader.readLine()) != null) {
commandOutput.append(currentLine + "\n");
}
int returnCode = process.waitFor();
if (returnCode == 0) {
output = commandOutput.toString();
}
} catch (IOException e) {
System.err.println("Cannot retrieve output of command");
System.err.println(e);
output = null;
} catch (InterruptedException e) {
System.err.println("Cannot retrieve output of command");
System.err.println(e);
} finally {
//Close all inputs / readers
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
System.err.println("Cannot close stream input! " + e);
}
}
if (streamReader != null) {
try {
streamReader.close();
} catch (IOException e) {
System.err.println("Cannot close stream input reader! " + e);
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.err.println("Cannot close reader! " + e);
}
}
}
//Return the output from the command - may be null if an error occured
return output;
}
I am working on an Editor application where I can compile and run c,cpp and Java file.I am developing this application using java programming language.I am developing it in Eclipse.
I am able to create new files(c,cpp and java) on specific locations and also I am able to save file to different-2 locations.
And for execution I am using following methods.
String compileFileCommand = "javac "+fileName;
Process compile_process = new ProcessBuilder(compileFileCommand).redirectErrorStream(true).start();
compile_process.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(compile_process.getInputStream()));
String line=reader.readLine();
while(line!=null) {
System.out.println(line);
line=reader.readLine();
}
My problem is that I am not able to compile files from their corresponding locations.
Always giving Exception
java.io.IOException: error=2, No such file or directory
Please tell me how can I compile and run all c,c++ & java files.
Please also give me any other suggestion for my application.
Edited ..
I have used these two methods for compiling and running.On Compiling it creates a class file in case of Java.But all the time I am getting null from InputStreams(both getErrorStream() and getInputStream()).
void compileJavaFile(String fileName)
{
String compileFileCommand = "javac " + fileName;
try
{
System.out.println("Executing Java File");
Process compileProcess = Runtime.getRuntime().exec(compileFileCommand);
String line = "";
BufferedReader bri = new BufferedReader(new InputStreamReader(compileProcess.getInputStream()));
BufferedReader bre = new BufferedReader(new InputStreamReader(compileProcess.getErrorStream()));
while ((line = bri.readLine()) != null)
{
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null)
{
System.out.println(line);
}
bre.close();
compileProcess.waitFor();
System.out.println("Done.");
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
void runJavaFile(String fileName)
{
String runFileCommand = "java " + fileName.split(".java")[0];
try
{
System.out.println("runFileCommand : " + runFileCommand);
System.out.println("Running Java File");
Process runProcess = Runtime.getRuntime().exec(runFileCommand);
BufferedReader reader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
String line = reader.readLine();
System.out.println("line = " + line);
while (line != null)
{
System.out.println(line);
line = reader.readLine();
}
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
And for C and C++ I am using.
void compileCFile(String fileName)
{
String compileFileCommand = "gcc " + fileName;
resultString = "";
try
{
System.out.println("Compiling C File");
Process processCompile = Runtime.getRuntime().exec(compileFileCommand);
BufferedReader brCompileError = new BufferedReader(new InputStreamReader(processCompile.getErrorStream()));
String errorCompile = brCompileError.readLine();
if (errorCompile != null)
System.out.println("Error Compiler = " + errorCompile);
resultString += errorCompile +"\n";
BufferedReader brCompileRun = new BufferedReader(new InputStreamReader(processCompile.getErrorStream()));
String outputCompile = brCompileRun.readLine();
if (outputCompile != null)
System.out.println("Output Compiler = " + outputCompile);
resultString += outputCompile +"\n";
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
void runCFile(String fileName)
{
String runFileCommand = "./" + fileName.split(".c")[0];
try
{
System.out.println("Running C File");
Process processRun = Runtime.getRuntime().exec(runFileCommand);
BufferedReader brRun = new BufferedReader(new InputStreamReader(processRun.getErrorStream()));
String errorRun = brRun.readLine();
if (errorRun != null)
System.out.println("Error Run = " + errorRun);
BufferedReader brResult = new BufferedReader(new InputStreamReader(processRun.getInputStream()));
String outputRun = brResult.readLine();
if (outputRun != null)
System.out.println("Output Run = " + outputRun);
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
void compileCPPFile(String fileName)
{
String compileFileCommand = "g++ " + fileName;
try
{
System.out.println("Compiling CPP File");
Process processCompile = Runtime.getRuntime().exec(compileFileCommand);
BufferedReader brCompileError = new BufferedReader(new InputStreamReader(processCompile.getErrorStream()));
String errorCompile = brCompileError.readLine();
if (errorCompile != null)
System.out.println("Error Compiler = " + errorCompile);
resultString += errorCompile +"\n";
BufferedReader brCompileRun = new BufferedReader(new InputStreamReader(processCompile.getErrorStream()));
String outputCompile = brCompileRun.readLine();
if (outputCompile != null)
System.out.println("Output Compiler = " + outputCompile);
resultString += outputCompile +"\n";
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
void runCPPFile(String fileName)
{
String runFileCommand = "./" + fileName.split(".cpp")[0];
try
{
System.out.println("Running CPP File");
Process processRun = Runtime.getRuntime().exec(runFileCommand);
BufferedReader brRun = new BufferedReader(new InputStreamReader(processRun.getErrorStream()));
String errorRun = brRun.readLine();
if (errorRun != null)
System.out.println("Error Run = " + errorRun);
BufferedReader brResult = new BufferedReader(new InputStreamReader(processRun.getInputStream()));
String outputRun = brResult.readLine();
if (outputRun != null)
System.out.println("Output Run = " + outputRun);
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
In case of C and C++ it show error like
g++: /media/disk/eclipse/\/UniversalIDE/CPP/firstCPP: No such file or directory
Please give me solution for my problems ..
Please try following,
Process p = Runtime.getRuntime().exec(command);
command is a string you pass. in command you can pass "javac Test.java" to compile your java file & just like that you can use other commands.
replace the line
String runFileCommand = "./" + fileName.split(".c")[0];
with
String runFileCommand = "./a.out";