Javafx get Ping Result - java

I have written a class to ping an IP address that i provide, but it won't return anything.
I tried adding a few markers to see where it goes wrong, but not even that worked...
I have a gui interface and I use a Label to write my data out (the same format worked before with a string), here is the code. There were certain lines that i did or did not want, hence the "relevant" integer, you may ignore it. This should run on ubuntu 13.10.
public static ArrayList<String> PingIpAddr(String string) throws IOException{
String s = new String();
int relevant =0;
ArrayList<String> List = new ArrayList<String>();
List.add("it happens \n");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(new ProcessBuilder(string).start().getInputStream()));
while ((s = stdInput.readLine()) != null){
List.add("does this happen? \n");
relevant++;
if( (relevant == 2) || (relevant == 3) || (relevant == 4) || (relevant == 5) || (relevant == 6) || (relevant == 9) ){List.add(s + "\n");
List.add("or this? \n");}} //end of while
List.add("This must happen! \n");
return List;} //end of Ping
and if this would work, here is where it would be implemented:
String test;
test = PingIp.testPingIpAddr("ping -c 5 4.2.2.2").toString();
TeltonikaPing.setWrapText(true);
TeltonikaPing.setText(test);
Strangely it doesn't give back a sigle line. Maybe I'm just missing something very basic?:/

the main issue is caused by the fact ping has a delay in most cases, try making use of stdInput.ready().
I would probably pass this to ProcessBuilder: new ProcessBuilder("myCommand", "myArg1", "myArg2"); split out the command ping from its parameters.
as in - http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html
I hope this helps (:
Edit -- (this works below)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Pinger
{
public static List<String> PingIpAddr(String ip) throws IOException
{
ProcessBuilder pb = new ProcessBuilder("ping", ip);
//ProcessBuilder pb = new ProcessBuilder("ping", "-c 5", ip);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(pb.start().getInputStream()));
while (!stdInput.ready())
{
// custom timeout handling
}
String line;
ArrayList<String> output = new ArrayList<>();
while ((line = stdInput.readLine()) != null)
{
output.add(line);
}
return output;
}
public static void main(String[] args) throws IOException
{
List<String> lines = Pinger.PingIpAddr("127.0.0.1");
for (String line : lines)
{
System.out.println(line);
}
}
}

I found a nother solution, that lets me enter how long i want the Ping to be.
How to run PING command and get ping host summary?
if anyone else needs to incorporate it into a GUI :)

Related

StreamTokenizer infinite input problem from console

I am beginner in Java, so during my learning another topic as StreamTokenizer, I faced some kind of intresting problem. And I didn't found any close solutions or hints in the Internet.
So, basically, almost every educational source give us an example like this:
import java.io.*;
public class pr_23 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StreamTokenizer st = new StreamTokenizer(br);
while (st.nextToken() != st.TT_EOF)
if (st.ttype == st.TT_NUMBER)
System.out.print(st.nval + " "); // not infinite cycle
br.close();
}
}
And it works well. But if I include in the cycle some other operators with st.nval, like double b = st.nval and exclude this System.out.print() code, compiler cant determine the end of the Stream in this case anymore, so it starts infinite reading. I wanted StreamTokenizer gave numbers to my ArrayList, but magically it cant see the end of Stream in this case with similar cycle. What's intresting it does work correctly if I use FileInputStream instead of InputStreamReader. But I need to get input from the console, not from a file. Also, using FIS in Tokenizer is deprecated. So here's similar code, but it doesnt work properly:
import java.io.*;
import java.util.ArrayList;
public class pr_23 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StreamTokenizer st = new StreamTokenizer(br);
ArrayList<Integer> a = new ArrayList<>();
while (st.nextToken() != st.TT_EOF) {
a.add((int)st.nval); // infinite cycle
}
System.out.print(a);
br.close();
}
}
P.S. input is meant to be only int numbers for simplicity
Please understand that your loop is repeating until the input reaches to the EOF. And, your latter code does not output anything before your loop would exit. So, if you want to see your output with the latter code, you must close your standard input stream first. To close standard input, you should send EOF code from keyboard. On Linux and macos, you can close standard input with Ctrl-D, and on Windows, it is Ctrl-Z.
The source of your problem is using System.in.
Try reading from a file:
import java.io.*;
import java.util.ArrayList;
public class pr_23 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("myfile.txt"));
StreamTokenizer st = new StreamTokenizer(br);
ArrayList<Integer> a = new ArrayList<>();
while (st.nextToken() != st.TT_EOF) {
a.add((int)st.nval); // infinite cycle
}
System.out.print(a);
br.close();
}
}
The problem is that you won't get an EOF in a System.in if you run it interactively. Though you would get it if you run it like this:
java pr_23 < myfile.txt
By the way a better way to write this without the dangling close() would be:
import java.io.*;
import java.util.ArrayList;
public class pr_23 {
public static void main(String[] args) throws IOException {
// using try this way will close br automagically
try (BufferedReader br = new BufferedReader(new FileReader("myfile.txt"))) {
StreamTokenizer st = new StreamTokenizer(br);
ArrayList<Integer> a = new ArrayList<>();
while (st.nextToken() != st.TT_EOF) {
a.add((int)st.nval); // infinite cycle
}
System.out.print(a);
}
}
}

Find string and print next lines until empty line

I have a file in the following format
USER1
foo
foo
USER2
foo
bar
foo
USER3
bar
bar
I want to find a USER - e.g. USER2 and print the next lines up until the empty line
In Unix I could do something like
cat $FILE | sed -n '/USER2/,/^$/p'
Which would give the output
foo
bar
foo
How can I do similar in Java? I'm OK to read the file, run a for line in loop and find the "USER2" but not sure how I would get the next lines until the empty line?
On StackOverflow it is expected etiquette to post the code you have tried to write, so that answerers can focus on helping you with your specific mistakes, rather than asking for a from-scratch solution. Nevertheless, here you go:
import java.io.BufferedReader;
import java.io.FileReader;
public class SO {
public static void main(String[] args) throws Exception {
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
boolean blank = false;
boolean found = false;
String line;
while ((line = br.readLine()) != null) {
if (line.strip().equals("")) {
blank = true;
found = false;
continue;
} else {
blank = false;
}
if (line.equals("USER1")) {
found = true;
continue;
}
if (!blank && found) {
System.out.println(line);
}
}
}
}
}

Cannot capture command line output in Java

I have a python script that searches the given search term on youtube and prints out the result on the console. When I run this script on cmd.exe it takes 2 seconds for it to print out the result but it does. However, I cannot capture the command line output on my Java code. It returns an empty ArrayList. I am one hundred percent sure that I execute the same command in my code as cmd.exe. What should I do to get the output of this script in my Java code? Thank you in advance.
Java Code:
package musicplayer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Wrapper {
public static ArrayList<String> search(String searchTerm) throws IOException {
String projectDirectory = System.getProperty("user.dir");
ArrayList<String> result = new ArrayList<>();
String[] commands = {"python", "'" + projectDirectory + "\\src\\python\\search.py'", "--q","\'"+ searchTerm +"\'"};
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String line = "";
while ((line = stdInput.readLine()) != null)
result.add(line);
return result;
}
public static void main(String[] args) {
try {
System.out.println(search("foo"));
} catch (IOException exc) {
exc.printStackTrace();
}
}
}
Python Script:
#!/usr/bin/python
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from oauth2client.tools import argparser
# valid developer key
DEVELOPER_KEY = "AIzaSyDvIqgHz4EQBm3qPRdonottrythisoneQ0W0Wooh5gYPQ8"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
def youtube_search(options):
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
developerKey=DEVELOPER_KEY)
search_response = youtube.search().list(
q=options.q,
part="id,snippet",
maxResults=options.max_results
).execute()
videos = []
channels = []
playlists = []
for search_result in search_response.get("items", []):
if search_result["id"]["kind"] == "youtube#video":
videos.append("%s (%s)" % (search_result["snippet"]["title"],
search_result["id"]["videoId"]))
elif search_result["id"]["kind"] == "youtube#channel":
channels.append("%s (%s)" % (search_result["snippet"]["title"],
search_result["id"]["channelId"]))
elif search_result["id"]["kind"] == "youtube#playlist":
playlists.append("%s (%s)" % (search_result["snippet"]["title"],
search_result["id"]["playlistId"]))
print("Videos:\n", "\n".join(videos), "\n")
print("Channels:\n", "\n".join(channels), "\n")
print("Playlists:\n", "\n".join(playlists), "\n")
if __name__ == "__main__":
searchString = ''
argparser.add_argument("--q", help=searchString, default=searchString)
argparser.add_argument("--max-results", help="Max results", default=25)
args = argparser.parse_args()
try:
youtube_search(args)
except HttpError as e:
print ("An HTTP error %d occurred:\n%s" % (e.resp.status, e.content))

Reading a list of strings from command line in Java

I am trying to read a list of strings from command line in Java and then print the strings.
Here is the code: -
public class Example {
public static void main(String args[] ) throws Exception {
List<String> list = new ArrayList<String>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while((line = br.readLine()) != null) {
list.add(line);
}
System.out.println(list);
}
}
But it enters into an infinite loop and never prints the list.
Can anyone please help me point the mistake in my code?
Checking the terminating condition inside the while loop will solve your issue.
public class Example {
public static void main(String args[] ) throws Exception {
List<String> list = new ArrayList<String>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
while(true) {
line = br.readLine();
if (line == null || line.isEmpty()) {
break;
}
list.add(line);
}
System.out.println(list);
}
}
There's nothing wrong with your code. It doesn't terminate simply because it haven't got the correct "signal" yet.
Try Ctrl+D after you are done with the input. It should work for most cases.
Or Ctrl+Z for windows command line.
If you are using Java 8. There's a shorter version
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.stream.Collectors;
public class ReadLinesFromStdin {
public static void main(String [] args) throws IOException {
List<String> lines = new BufferedReader(new InputStreamReader(System.in))
.lines().collect(Collectors.toList());
System.out.println(lines);
}
}

How to store words from a file into a string, and print them out in reverse?

So I need to do exactly what it says in the title, take a text file called "words.txt", have the program read it, take all the words in it, and store them into an array. After that, the program needs to pick one out randomly, and print it in reverse. I'm having a lot of trouble getting it to work, as it always crashes at the end. Here's what I got so far:
import java.io.*;
import java.util.Random;
public class wordReader{
public static void main (String args[]) throws Exception{
BufferedReader br = new BufferedReader(new FileReader("words.txt"));
String strLine;
String[] filearray;
filearray = new String[10];
while ((strLine = br.hasNextLine())) {
for (int j = 0; j < filearray.length; j++){
filearray[j] = br.readLine();
System.out.println(filearray);
}
}
}
}
Alright, this i what I have at the moment:
import java.io.*;
import java.util.Random;
public class wordReader{
public static void main (String args[]) throws Exception{
BufferedReader br = new BufferedReader(new FileReader("words.txt"));
String strLine;
String[] filearray;
filearray = new String[10];
int j = 0;
int i = 0;
Random r = new Random();
while(((strLine = br.readLine()) !=null) && j < filearray.length){
filearray[j++] = strLine;
int idx = r.nextInt(filearray.length);
}
}
}
You can do this easily using the new Files API and StringBuilder to reverse your String. It will cut down your lines of code significantly.
public static void main(String[] args) throws Exception {
Path path = Paths.get("words.txt");
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
String[] words = content.split(",|\.|\s+");
int randomIndex = new Random().nextInt(words.length);
String word = words[randomIndex];
String reversed = StringBuilder(word).reverse().toString();
System.out.println(reversed);
}
Try using the StringTokenizer to read the line.
http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
Lot's of ways to accomplish this. Here's a recursive method that prints as the calls are popping off the return stack. This was adapted from Reversing Lines With Recursion Java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintWriter;
public class ReverseLines {
public static BufferedReader input;
public static PrintWriter output;
public static void main(String[] args) throws Exception {
input = new BufferedReader(new FileReader("/tmp/words.txt"));
output = new PrintWriter(System.out);
reverse(input, output);
input.close();
output.flush();
output.close();
}
public static void reverse(BufferedReader input, PrintWriter output)
throws Exception {
String line = input.readLine();
if (line != null) {
reverse(input, output);
output.println(line);
}
}
}
You don't seem to have gotten to the point of doing the random index selection or the line reversal yet, so I won't address that stuff here. There are endless duplicates all over StackOverflow to tell you how to reverse a String.
At the moment, you're getting compile errors because (among other things) you're trying to use a method (BufferedReader#hasNextLine()) that doesn't exist. It looks like you were mixing up a couple of other approaches that you might have found, e.g.:
int j = 0;
while ((strLine = br.readLine()) != null) { // Set strLine to the next line
filearray[j++] = strLine; // Add strLine to the array
// I don't recommend printing the whole array on every pass through the loop...
}
You'll notice that I also took out your inner for loop, because it was just setting every element of your list to the most recent line on every iteration. I'm assuming you wanted to populate the list with all of your lines. Realistically, you should also check whether j is in an acceptable range as well:
while (((strLine = br.readLine()) != null) && j < filearray.length) {...}
Note that realistically, you'd almost certainly be better off using a List to store your lines, so you could just add all the lines to the List and not worry about the length:
List<String> contents = new ArrayList<String>();
while ((strLine = br.readLine()) != null) {
contents.add(strLine); // Add strLine to the List
}
But, this does smell like homework, so maybe you're required to use a String[] for whatever reason.
Finally, there's a discrepancy between what you've written in your question and what your program looks like it's intended to do. You claim that you need a list of each word, but it looks more like you're trying to create a list of each line. If you need words instead of lines, you'll need to split up each line and add each token to the list.

Categories