issue with parsing log file continuously - java

I am trying to read a log file continuously where the logs are being written ,both the processes are happening simultaneously.I am using rolling file appender for generating logs but the problem is ,when the file is about to change sometimes the data written when the file is nearing end is not read.Here is my code that generates log file continuously.
import java.util.Timer;
import java.util.TimerTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class Slf4jSample {
static Logger logger = LoggerFactory.getLogger(Slf4jSample.class);
public static void main(final String[] args) {
int delay = 0; // delay for 5 sec.
int period = 1000; // repeat every sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
int i = 0;
public void run() {
// Task here ...
for (i = 0; i < 50; i++) {
logger.error("testing" + i);
System.out.println(i);
}
}
}, delay, period);
}
}
and here is my code that is reading it continuously.
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.mobility.config.ParseConfig;
import com.mobility.mail.SendMail;
import com.mobility.vo.ConfigurationVO;
import com.mobility.vo.LogVO;
import javax.mail.*;
TimerTask fileWatcherTask = new LogWatcher(fileName) {
long addFileLen = fileName.length();
FileChannel channel, oldChannel;
FileLock lock, oldLock;
#Override
protected void onChange(File file) {
RandomAccessFile access = null;
RandomAccessFile oldAccess = null;
int level = 0;
try {
access = new RandomAccessFile(file, "rw");
oldAccess = new RandomAccessFile(prevFileName, "rw");
channel = access.getChannel();
lock = channel.lock();
oldChannel = oldAccess.getChannel();
oldLock = oldChannel.lock();
// System.out.println("addFileLen>>" + addFileLen);
if (file.length() <= addFileLen) {
System.out.println("in if>>");
// reading old file
if (prevFileName.exists()) {
parsingLog(oldAccess, addFileLen,level);
addFileLen = file.length();
}
// reading old file ends
// Seek to 0th position when the file changes.
parsingLog(access, 0,level);
} else {
// access.seek(addFileLen);
parsingLog(access, addFileLen,level);
System.out.println("else>>>");
addFileLen = file.length();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
lock.release();
oldLock.release();
} catch (IOException e1) {
e1.printStackTrace();
} // Close the file
try {
channel.close();
oldChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Timer timer = new Timer();
// repeat the check every second
long scheduleTimer = Long.parseLong(properties
.getProperty("scheduler.timer"));
timer.schedule(fileWatcherTask, new Date(), scheduleTimer);
}
}
public void parsingLog(RandomAccessFile access, long fileLength, int level) {
List<String> logList = new ArrayList<String>();
int flag = 0;
String line = null;
try {
access.seek(fileLength);
while ((line = access.readLine()) != null) {
System.out.println("after reading line >"+line);
}
}catch(Exception e){
}
}
PS:it doesn't read the contents when it is nearing end.

I would open the file until it has been fully read and only close it when you have finished reading it. This may require your logger to create a new file each time, but you are unlikely to miss anything this way.

Related

How do I make a java program act as an audio output device?

I am trying to make a program that acts as an audio device so that I can modify the volumes of all of the programs that go through it, then send the audio to a another real playback device. I have done some research on the java class' and found the AudioSystem class which looks promising, but I don't know how to get all of the individual program audio lines.
The program I am making is pretty much a simplified replica of the windows volume mixer which I plan to do more with, but this is just what I am starting with.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Control;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;
public class SystemTests {
public static Mixer headPhones;
public static final int inputInfo = 10;
public static Mixer.Info[] mi;
public static Line.Info[] ti;
public static SourceDataLine line;
public static AudioFormat format;
public static final int recordTime = 10000;
static AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;
static File wavFile = new File("c://temp//testFile1.wav");
public static void main(String[] args) {
final SystemTests recorder = new SystemTests();
//create a thread for stopping the process
Thread stop = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(recordTime);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
// Scanner in = new Scanner(System.in);
// System.out.println("Press Enter to stop Recording.");
// in.nextLine();
// recorder.finish();
System.exit(0);
}
});
stop.start();
recorder.start();
}
public void start(){
mi = AudioSystem.getMixerInfo();
System.out.println(mi[inputInfo]);
//show all mixer info
// for(int i = 0; i < mi.length; i++) {
// System.out.println(mi[i] + " _ " + i);
// }
//get mixer and line info
headPhones = AudioSystem.getMixer(mi[inputInfo]);
ti = headPhones.getSourceLineInfo();
//show all line info
// for(int i = 0; i < ti.length; i++) {
// System.out.println(ti[i] + " _ " + i);
// }
//get the line
// try {
// line = (SourceDataLine) headPhones.getLine(ti[0]);
// } catch (LineUnavailableException e) {
// e.printStackTrace();
// }
Control[] controls = AudioSystem.getMixer(mi[inputInfo]).getControls();
for(int i = 0; i < controls.length; i++) {
System.out.println(controls[i]);
}
}
public void finish() {
line.stop();
line.close();
System.out.println("Finished");
}
}

Can't set ImageView photo from datainputstream JavaFx socket application

I am trying to output an image to an ImageView in javafx, i am recieving the image via socket connection and saving it to my hard-drive then i create an Image object with the path of the newly created image, the problem is that the image view is not updated.
public void save(String path, DataInputStream dis) throws IOException {
FileOutputStream fos = new FileOutputStream("src/img"+(frame_number)+".jpg");
//Image imBuff = ImageIO.read(socket.getInputStream());
int filesize = dis.readInt(); // Send file size in separate msg
byte[] buffer = new byte[filesize];
int read = 0;
int totalRead = 0;
int remaining = filesize;
while ((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) >= 1) {
totalRead += read;
remaining -= read;
//System.out.println("read " + totalRead + " bytes.");
fos.write(buffer, 0, read);
System.err.println("img"+(frame_number)+".jpg");
fos.flush();
}
fos.flush();
fos.close();
System.out.println("frame num:"+frame_number);
Image i = new Image("Camera_Frame.jpg");
try{
//i=new Image("img"+frame_number+".jpg");
File f = new File("img"+frame_number+".jpg");
i = new Image(f.toURI().toString());
iv.setImage(i);
}catch(Exception e){
System.out.println("didn't find");
}
System.out.println("stream size:"+image_Stream.size());
ps.println("ok");
frame_number++;
}
Things i have tried:
1- i tried to used the path i saved the photo in to create an Image then used the setImage() function on my ImageView (iv), i got Invalid Url even though i loaded an image image from the same directory before.
2- we tried using (file:///) to get an absolute path but it didn't work, also invalid url
3- i tried loading the image as a file first then using the toURI() function to get the proper path to it then create an image accordingly, i don't get an error but it also doesn't update the UI
P.S
this function is called in a sub Thread that updates an ImageView in the main javafx thread, i tried it with images not loaded through the socket connection and it worked, but when i try to display the images i receive the face this problem.
EDIT: I managed to load the image properly, now i can't update the ImageView using iv.setImage()
EDIT:
CameraOBJ class
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import javax.imageio.ImageIO;
import javafx.animation.AnimationTimer;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.stage.FileChooser;
import javafx.util.Duration;
public class CameraOBJ implements Runnable{
String name;
int delay;
Socket socket;
String ip;
int port;
PrintStream ps;
Scanner sc;
static int frame_number;
StackPane sp;
Label delay_lbl;
ImageView iv;
public CameraOBJ (String name, String ip, int port){
this.ip = ip;
this.port = port;
this.name = name;
sp = new StackPane();
}
public void run() {
setStackPane();
connect();
while(true){
update();
}
// Timeline timeline = new Timeline();
// Duration duration = Duration.seconds(1/Settings.FPS);
// KeyFrame f1 = new KeyFrame(duration,e->{
// update();
// });
// timeline.getKeyFrames().add(f1);
// timeline.setCycleCount(Timeline.INDEFINITE);
// timeline.play();
}
private void update() {
// Platform.runLater(new Runnable() {
// public void run() {
DataInputStream dis;
try {
dis = new DataInputStream(socket.getInputStream());
if(dis!=null){
save("images",dis);
//setStackPane();
}
} catch (IOException e1) {
System.out.println(e1.getMessage());
}
// }
// });
}
public void setStackPane(){
Platform.runLater(new Runnable() {
public void run() {
sp.setMinSize(500, 384);
sp.setMaxSize(500, 384);
sp.setStyle("-fx-background-color: #FFFFFF;");
Image image = new Image("Camera_Frame.jpg");
iv = new ImageView(image);
iv.setFitWidth(470);
iv.setPreserveRatio(true);
Label name_lbl = new Label(name);
delay_lbl = new Label(delay+"");
sp.setAlignment(iv,Pos.CENTER);
sp.setAlignment(name_lbl,Pos.TOP_LEFT);
sp.setAlignment(delay_lbl,Pos.BOTTOM_RIGHT);
sp.getChildren().addAll(iv,name_lbl,delay_lbl);
}
});
}
public void connect(){
try{
socket = new Socket(ip, port);
System.out.println(socket.isConnected());
ps = new PrintStream(socket.getOutputStream());
sc = new Scanner(socket.getInputStream());
}
catch (Exception c){
c.getMessage();
}
}
public void save(String path, DataInputStream dis) throws IOException {
Platform.runLater(new Runnable() {
public void run() {
FileOutputStream fos;
try {
fos = new FileOutputStream("src/img"+(frame_number)+".jpg");
int filesize;
try {
filesize = dis.readInt();
byte[] buffer = new byte[filesize];
int read = 0;
int totalRead = 0;
int remaining = filesize;
while ((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) >= 1) {
totalRead += read;
remaining -= read;
//System.out.println("read " + totalRead + " bytes.");
fos.write(buffer, 0, read);
System.err.println("img"+(frame_number)+".jpg");
fos.flush();
}
fos.flush();
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
System.out.println("frame num:"+frame_number);
Image i = new Image("Camera_Frame.jpg");
try{
//i=new Image("file:img"+frame_number+".jpg");
File f = new File("C:\\Users\\ahmed\\workspace\\College\\RTS_Client\\src\\img"+frame_number+".jpg");
i = new Image(f.toURI().toString());
iv.setImage(i);
delay_lbl.setText("frame_number: "+frame_number);
}catch(Exception e){
System.out.println("didn't find");
}
frame_number++;
}
});
}
}
Main class:
import java.io.File;
import java.io.PrintStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import com.sun.prism.paint.Color;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Background;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class main extends Application{
static Stage window;
static String default_ip = "192.168.43.200";
static int default_port = 1234;
public static void main(String[] args) {
launch(args);
}
public void start(Stage stage) {
window = stage;
window.setResizable(false);
window.setTitle("Control Room");
StackPane sp = new StackPane();
sp.setMinSize(500, 500);
Scene sc = new Scene(sp);
window.setScene(sc);
window.show();
CameraOBJ camera = new CameraOBJ("Camera 1", default_ip, default_port);
Thread t = new Thread(camera);
camera.run();
sc = new Scene(camera.sp);
window.setScene(sc);
}
}
Server class:
import java.io.IOException;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Camera implements Runnable {
long timeStamp;
int delayShift;
int FPS;
boolean idle;
//Control Rooms object here
int portNumber;
Socket csocket;
Camera() {
}
Camera(Socket csocket) {
this.csocket = csocket;
}
void startConnection() throws Exception {
ServerSocket ssock = new ServerSocket(1234);
System.out.println("Listening");
while (true) {
Socket sock = ssock.accept();
System.out.println("Connected");
new Thread(new Camera(sock)).start();
}
}
public void run() {//Start Stream
try {
PrintStream pstream = new PrintStream(csocket.getOutputStream());
Scanner inpstream = new Scanner(csocket.getInputStream());
// Receiving an integer that is sent from the client side.
int ID = inpstream.nextInt();
// Generating a reply based on the ID sent from the client.
String response = "";
if (ID == 1100) {
response = "Your name is Mahmoud. \n" + "You are 22 years old.";
} else {
response = "No data found matching the ID you entered.";
}
// Sending the reply through the OutputStream to the client.
pstream.println(response);
pstream.close();
terminateConnection();
} catch (InputMismatchException e) {
System.out.println(e.toString() + "\nNo data is received.");
} catch (IOException e) {
System.out.println(e.toString());
} catch (Exception c) {
System.out.println(c.toString());
}
}
void terminateConnection() throws IOException {
csocket.close();
}
public static void main(String[] args) throws Exception {
Camera cam = new Camera();
cam.startConnection();
}
}

JavaFX label set to Variable problems

Im trying to build an Installer/Updater for a project im working on.
My only problem im facing is that my variable of my progess bar doesn't want to be displayed in a label :C.
I already looked up and found an answer from Sebastian who said
myLabel.textProperty().bind(valueProperty); should work but ... well you guess the outcome.
Eclipse says I have to change the type of my int to: ObservableValue<? extends String> and when I changed it it says I have to change it back to int. I dont know what I have to do now ://
EDIT: Full code of my controller class
package application;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
public class Controller {
#FXML
ProgressBar pb;
Label progText;
public void install(){
new Thread(new Runnable() {
#Override public void run() {
download();
}}).start();
};
public void load(){
new Thread(new Runnable() {
#Override public void run() {
download();
Unzip.extract();
System.out.println("Finished");
}}).start();
};
public void download(){
try {
System.out.println("Start");
URL url = new URL("https://www.dropbox.com/s/27d4us64oqifuph/modpack.zip?dl=1");
HttpURLConnection httpConnection = (HttpURLConnection) (url.openConnection());
long completeFileSize = httpConnection.getContentLength();
java.io.BufferedInputStream in = new java.io.BufferedInputStream(httpConnection.getInputStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream(
"modpack.zip");
java.io.BufferedOutputStream bout = new BufferedOutputStream(
fos, 1024);
byte[] data = new byte[1024];
long downloadedFileSize = 0;
int x = 0;
while ((x = in.read(data, 0, 1024)) >= 0) {
downloadedFileSize += x;
//calculate progress
int cp = (int) ((((double)downloadedFileSize) / ((double)completeFileSize)) * 10000);
DoubleProperty progress = new SimpleDoubleProperty(0);
// update progress bar
pb.setProgress(cp*0.0001);
progress.setValue(cp*0.0001);
progText.textProperty().bind(progress.asString());
bout.write(data, 0, x);
}
bout.close();
in.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
};
}
Create a DoubleProperty that is bound to the label and is updated when you update the progressbar.
DoubleProperty progress = new SimpleDoubleProperty(0);
progText.textProperty().bind(progress.asString());
...
// update progress bar
pb.setProgress(cp*0.0001);
progress.setValue(cp*0.0001)

Creating threads to download a file and make a counter java

Im trying to make a program that downloads a file. While downloading the file there needs to have a basic counter which counts from start to end. These two functions need to be in their own threads. I have created a method/thread to download the file. I'm having trouble figuring out how to make a basic counter. Nothing fancy but it needs to count up and only display the current number. Any help would be appreciated.
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static myutilites.methods.*;
public class Downloader
{
public static void main(String[] args) throws IOException
{
String filename = "Nexus5MahdiRom.zip";
URL link = new URL(
"http://files.mahdi-rom.com/OnePlus%20One/"
+ "OnePlus%20One%20Builds/mahdi-2.7-bacon-20140903.zip");
Thread t1 = new Thread(new Runnable()
{
#Override
public void run()
{
try
{
downloadFile(filename,link);
} catch (IOException e)
{
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable()
{
#Override
public void run()
{
try {
counter(link, t1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t1.start();
println("Downloading File...");
}
public void getScreenSize()
{
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
println("width = " + d.width + " height = " + d.height);
}
public static void downloadFile(String fileName, URL link) throws IOException
{
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte [] buf = new byte[1024];
int n = 0;
int count = 0;
while (-1 !=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
println(count);
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(response);
fos.close();
println("Download Finished");
}
public static void locate(int row, int col)
{
System.out.print("\033["+row+";"+col+"H");
}
public static int counter(URL link, Thread t1) throws IOException
{
int count = 0;
link.openConnection();
while(t1.isAlive())
{
count++;
return count;
}
return count;
}
}
Use getAndIncrement or incrementAndGet on AtomicInteger, which is a thread-safe counter (with the counter initialized to 0, if two threads simultaneously call incrementAndGet then you're guaranteed that the counter will return 1 to one thread and 2 to the other thread, and will have a final state of 2)

send a ping to multiple ip addresses at the same time

i did a code wish send a ping to multiple ip adresses and get the value of time from each ping request and then print write the result in a from of a matrix in a text file....anyway my problem is that after i finished my code i figure out that i should send the ping to these adresses at the same time or in my code i did send it consecutively to the adresses.i really i hope if someone helps me with it...
code:
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class Pinggg extends JFrame{
private boolean stop = false; // start or stop the ping
public Pinggg(){
Container cp = this.getContentPane();
cp.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
JButton btnStart=new JButton("demarrer le test");
cp.add(btnStart);
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
stop = false;
try {
final Formatter x = new Formatter("C:/Users/VAIO/workspace/tcc/gastoon/kkk.txt");
PrintWriter writer;
writer = new PrintWriter("C:Users/VAIO/workspace/tcc/gastoon/kkk.txt");
for (int m = 0; m < 10; m++) {
if (stop) break;
// check if STOP button has been pushed,
// which changes the stop flag to true
DocumentBuilderFactory BuilderFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder db=BuilderFactory.newDocumentBuilder();
Document doc=db.parse("C:/Users/VAIO/workspace/tcc/gastoon/adresStore.xml");
doc.normalize();
NodeList rootNodes=doc.getElementsByTagName("connection");
Node rootNode=rootNodes.item(0);
Element rootElement=(Element) rootNode;
NodeList l=rootElement.getElementsByTagName("users");
Node users=l.item(0);
Element element=(Element) users;
NodeList nl=element.getElementsByTagName("user");
List<String> allIps = new ArrayList<String>();
for(int i=0;i<nl.getLength();i++){
Node user=nl.item(i);
Element ele=(Element) user;
String adrss=ele.getElementsByTagName("ipAdress").item(0).getTextContent();//+" -n 1";
//System.out.println(adrss);
allIps.add(i, adrss);
//writer.print(allIps.get(i)+" ");
// System.out.println(adrss);
//System.out.println(i);
// writer.format("%s ",i);
//writer.println( adrss);
}
// for(String n : allIps)
//{
// writer.print(allIps+" ");
//}
writer.println("\n");
for(int j=0;j<allIps.size();j++)
{
//writer.print(allIps.get(i)+" ");
String pingCmd = "ping " +allIps.get(j) +" -n 1";
String pingResult = "";
String str="";
try {
Runtime r = Runtime.getRuntime();
Process p = r.exec(pingCmd);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
// writer.println(inputLine);
//System.out.println(inputLine);
pingResult += inputLine;
}
String[] lines = pingResult.split("\n");
List<String> bb = new ArrayList<String>();
for (int k=0;k<lines.length;k++) {
String line=lines[k];
if ((line.contains("temps=") && (line.contains(allIps.get(j))))){
// Find the index of "time="
int index = line.indexOf("temps=");
String time = line.substring(index + "temps=".length(),line.indexOf("ms"));
//bb.add(time);
// writer.print(allIps.get(j)+" ");
writer.print(time);
//System.out.println(allIps.get(j)+" ");
System.out.println(time);
}
else {
writer.print("NON"+" ");
}
}
int[]tab=new int[allIps.size()];
for(int d=0;d<tab.length;d++ ){
}
}
catch (IOException ie) {
System.out.println(ie);
}
}}
writer.flush();
}//}
catch (SAXException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (ParserConfigurationException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
);
JButton btnStop = new JButton("Analyser le test ");
cp.add(btnStop);
btnStop.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
stop = false; // set the stop flag
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cp.setBackground(Color.black);
setTitle("PING");
setSize(300, 120);
setVisible(true);
}
}
It depends on what you mean by "i should send the ping to these adresses [sic] at the same time".
1) Create a threadppol and send your requests through that. This will batch up your ping requests (to the size of the threadpool). However this is technically not "at the same time".
2) Ping the broadcast address. Whether or not this works (or rather works how you think it works) depends on your network setup. It won't work on the Internet, but it may work on a corporate LAN. So it depends on the nature of the IP addresses you are trying to ping.

Categories