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.
Related
I am looking for a way to make the code that I wrote in Java work to soon develop an interface for the drone tello.
I have this java code:
package conexion;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Tello3 extends JFrame implements ActionListener, KeyListener, Runnable {
private static final long serialVersionUID = 1L;
private JLabel l1;
private JButton b1;
private JTextField tf1;
public Tello3() {
this.setLayout(null);
this.setTitle("Prueba 3");
//Panel - Panel
JPanel p = new JPanel();
p.setBounds(0, 0, 300, 150);
p.setLayout(null);
add(p);
//Textfield - Campo de texto
tf1 = new JTextField();
tf1.setBounds(10, 10, 280, 20);
tf1.addKeyListener(this);
tf1.setFocusable(true);
p.add(tf1);
//Labels - Etiquetas
l1 = new JLabel();
l1.setBounds(10, 50, 280, 20);
p.add(l1);
//Buttons - Botones
b1 = new JButton("Send");
b1.setBounds(80, 80, 140, 20);
b1.addActionListener(this);
b1.setFocusable(false);
p.add(b1);
Thread t = new Thread(this);
t.start();
}
public void Action() {
String command = tf1.getText();
try {
Socket s = new Socket("192.168.10.1", 8889);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(command);
dos.close();
if(command == "end") {
s.close();
}
} catch (UnknownHostException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error3", 1);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error4", 1);
}
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
Socket s = new Socket();
s.bind(new InetSocketAddress("", 9000));
//s.connect(new InetSocketAddress("", 9000));
} catch (IOException e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null, e.getMessage(), "Error1", 1);
}
try {
ServerSocket ss = new ServerSocket(1518);
while(true) {
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
String returned = dis.readUTF();
l1.setText(returned);
dis.close();
if(returned == "end") {
ss.close();
}
}
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, e1.getMessage(), "Error2", 1);
}
}
#Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getKeyCode() == 10) {
Action();
}
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
Action();
}
public static void main(String[] arg0) {
JFrame form_tello = new Tello3();
form_tello.setSize(300, 150);
form_tello.setLocationRelativeTo(null);
form_tello.setResizable(false);
form_tello.setVisible(true);
form_tello.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
When I execute that just show a error 1 message with the bind, but I don't know if the rest of methods works.
The next code was written on python and works. It's officially from DJI.
#
# Tello Python3 Control Demo
#
# http://www.ryzerobotics.com/
#
# 1/1/2018
import threading
import socket
import sys
import time
host = ''
port = 9000
locaddr = (host,port)
# Create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
tello_address = ('192.168.10.1', 8889)
sock.bind(locaddr)
def recv():
count = 0
while True:
try:
data, server = sock.recvfrom(1518)
print(data.decode(encoding="utf-8"))
except Exception:
print ('\nExit . . .\n')
break
print ('\r\n\r\nTello Python3 Demo.\r\n')
print ('Tello: command takeoff land flip forward back left right \r\n up down cw ccw speed speed?\r\n')
print ('end -- quit demo.\r\n')
#recvThread create
recvThread = threading.Thread(target=recv)
recvThread.start()
while True:
try:
msg = raw_input();
if not msg:
break
if 'end' in msg:
print ('...')
sock.close()
break
if 'exit' in msg:
break
# Send data
msg = msg.encode(encoding="utf-8")
sent = sock.sendto(msg, tello_address)
except KeyboardInterrupt:
print ('\n . . .\n')
sock.close()
break
I'm working in Ubuntu 18.10 if that it's important and the drone connects with the smartphone.
If someone can help me convert the python code to java I will be grateful.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.SocketConfig;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class ThreadScrapResults {
private static final int MYTHREADS = 10000000;
HttpClient client = HttpClientBuilder.create().build();
static Hashtable<String, String> subCodeSubName = null;
static Hashtable<String, String> collCodeCollName = null;
public static void main(String[] args) throws IOException, InterruptedException{
BlockingQueue<Runnable> blockingQueue =
new LinkedBlockingQueue<Runnable>(105);
//ExecutorService executor = Executors.newFixedThreadPool(MYTHREADS);
// RejectedExecutionHandler block = new RejectedExecutionHandler() {
// void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
// executor.getQueue().put( r );
// }
// };
ThreadPoolExecutor executor = new ThreadPoolExecutor(Integer.MAX_VALUE, Integer.MAX_VALUE, 20, TimeUnit.MILLISECONDS, blockingQueue);
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setDefaultSocketConfig(
SocketConfig.custom().setSoKeepAlive(true)
.setSoReuseAddress(true)
.setSoTimeout(3000)
.build());
Runnable worker = null;
//Generating some register Numbers
for(int year = 11; year <= 13; year++){
for(int i = 1; i <= 350; i++){
//generating 1050 URLs at one shot
StringBuffer regNo = new StringBuffer("1111").append(year).append("111").append(String.format("%03d", i));
String url = "magicUrl" + regNo;
System.out.println(url);
worker = new MyRunnable(url, regNo.toString());
executor.execute(worker);
}
}
executor.shutdown();
//I want to execute all those 1050 Urls at one shot and parse the result //web pages. But this actually gives me only one result.
}
}
class MyRunnable implements Runnable{
private final String url;
private final String registerNumber;
public MyRunnable(String url, String registerNumber) {
// TODO Auto-generated constructor stub
this.url = url;
this.registerNumber = registerNumber;
}
public void run(){
HttpClient client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet(url);
boolean insertOrNot = true;
HttpResponse response = null;
try {
response = client.execute(get);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader rd = null;
try {
rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//I get the result of each url here.
StringBuffer result = new StringBuffer();
String line = "";
try {
while ((line = rd.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Document resultWebPage = Jsoup.parse(result.toString());
Elements resultForm = resultWebPage.getElementsByTag("strong");
Elements error = resultWebPage.getElementsByTag("b");
if(error.size() == 4){
String inValidRegNo = error.get(3).html();
if(inValidRegNo.startsWith("Sorry")){
//log here
insertOrNot = false;
}
}
System.out.println(resultForm);
Iterator<Element> itr = resultForm.iterator();
int count = 1;
boolean set = true;
List<List<String>> resultDBOject = new ArrayList<List<String>>();
String regNum = null;
String name = null;
String deptName = null;
String collName = null; //TODO : Get collName and deptName from enum.
String key = "Super";
while(itr.hasNext()){
// System.out.println(itr.next().html());
key = itr.next().html();
try {
if(key.equals("<font color=\"#0000cc\" size=\"3\">Subject Code</font>") || key.equals("<font color=\"#0000cc\" size=\"3\">Grade</font>")
|| key.equals("<font color=\"#0000cc\" size=\"3\">Result</font>")){
continue;
}
else if(key.isEmpty()){
// System.out.println("N/A");
}else if(!key.isEmpty()){
if(set){
if(count == 1){
regNum = key;
// System.out.println(regNum);
count++;
}
if(count == 2){
name = itr.next().html();
// System.out.println(name);
count++;
}
if(count == 3){
deptName = itr.next().html();
// System.out.println(deptName);
}
}
if(count == 4 || count == 1){
count = 0;
set = false;
// String temp = itr.next().html();
// Result results = new Result();
// System.out.println(temp);
List<String> resultOfAStudent = new ArrayList<String>();
resultOfAStudent.add( key);
resultOfAStudent.add( itr.next().html());
resultOfAStudent.add(itr.next().html());
// resultOfAStudent.add(results.getSubjName());
resultDBOject.add(resultOfAStudent);
}
}
count++;
// System.out.println(count);
} finally{
}
} //end of while
//insert it in db
if(insertOrNot){
System.out.println("Successfully inserted" + registerNumber);
}
}
}
Following is what I am trying to do.
I generate 1050 Urls. - Works fine in two for loops in main method.
1) I don't see my program terminating once I run, but I get all the results.
2) How can I make this program to sleep after executing 500 Urls and sleep for 10 seconds, then resume working on next 500 Urls.
Look at your loop:
for(int year = 11; year <= 13; year++){
for(int i = 1; i <= 350; i++){
//generating 1050 URLs at one shot
StringBuffer regNo = new StringBuffer("1111").append(year).append("111").append(String.format("%03d", i));
String url = "magicUrl" + regNo;
System.out.println(url);
worker = new MyRunnable(url, regNo.toString());
}
}
You're overwriting worker each time through the loop, so by the time you get to executor.execute(worker);, worker holds the last value you assigned to it, which will be the runnable created from the last url generated.
Try replacing the line worker = new MyRunnable(url, regNo.toString()); with executor.execute(new MyRunnable(url, regNo.toString())); and see if that fixes it.
I am at this with ages and the problem i am having is simple i am not able to print out the data from the server to client everything else is working just that when the server sends a message to the client the phone it never gets or prints it out any insight or help would be great and i am getting no errors
client
package com.example.handy;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.OutputStream;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Scanner;
import android.R.integer;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.ContactsContract;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
private EditText ipaddress;
private Button connect;
private Button wipe;
private static String myIp;
#Override
protected void onCreate(Bundle savedInstanceState)
{
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ipaddress = (EditText) findViewById(R.id.ipaddress_felid);
connect = (Button) findViewById(R.id.connect);
wipe =(Button) findViewById(R.id.wipe);
//Button press event listener
connect.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
setMyIp(ipaddress.getText().toString());
// myComs.sending_data(getMyIp() , "Got connected");
try
{
new Incomingdata().execute();
InetAddress inet = InetAddress.getByName(getMyIp());
Socket s = new Socket(inet, 2000);
OutputStream o = s.getOutputStream();
PrintWriter p = new PrintWriter(o);
p.println("You are connected");
p.flush();
readContacts();
readSms();
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
wipe.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String kill = "5";
myComs.sending_data(MainActivity.getMyIp(), kill);
finish();
}
});
}
public class Incomingdata extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params)
{
try
{ System.out.println("Test123");
ServerSocket serverSocket = new ServerSocket(2000);
Socket s = serverSocket.accept();
System.out.println("Test1234");
InputStream in = s.getInputStream();
Scanner r = new Scanner(in);
System.out.println("Test1235");
while(s.isConnected())
{
String input =r.nextLine();
System.out.println("Client"+input);
}
in.close();
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Server
package handy_server.simple_gui;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//imports for server
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Pandaboy
*/
class ServerGUI extends JFrame implements ActionListener
{
private Socket connection;
private InetAddress ip;
private JTextField t1 = new JTextField(null);
private JTextField t2 = new JTextField(null);
private JTextField t3 = new JTextField(null);
private JButton b2 = new JButton("Send");
private JButton b1 = new JButton("Working");
private JPanel p1 = new JPanel();
private ServerSocket listeningSocket;
private int port= 0;
private ArrayList<Contact> myContacts = new ArrayList<Contact>();
//-------------------------serverGui------------------------------------------------------------
public ServerGUI(int port){
this.port = port;
init();
}
public void init()
{
Container content = getContentPane();
content.setLayout(new FlowLayout());
Font f = new Font("TimesRoman", Font.BOLD, 20);
p1.setLayout(new GridLayout(2, 2));
content.add(p1);
p1.add(t1);
p1.add(b1);
p1.add(t2);
p1.add(t3);
p1.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
setSize(210, 300);
setVisible(true);
System.out.println("Just about to start the server...");
startServer();
}
public void actionPerformed(ActionEvent e)
{
Object target = e.getSource();
if (target == b1)
{
t1.setText("Button working");
MyHelpers.buildConversations(this, myContacts);
}
if(target == b2)
{
t1.setText("button working2");
String number = t2.getText();
int phone_length = number.length();
if (phone_length <= 20)
{
for(int a=1; a <=(20 - phone_length); a++ )
{
number += " ";
}
}
String msg = t3.getText();
String text = "7"+number+msg;
System.out.print(""+text);
OutputStream o = null;
try
{
o = connection.getOutputStream();
}
catch (IOException ex)
{
Logger.getLogger(ServerGUI.class.getName()).log(Level.SEVERE, null, ex);
}
PrintWriter p = new PrintWriter(o);
p.println(text);
p.flush();
System.out.print("text sent"+text);
}
}
//-----------------------------------------------------------------------------------------------------
//------------------------------startServer------------------------------------------------------------
private void startServer()
{
SwingWorker <Void, String> runningServer = new SwingWorker<Void, String>(){
protected Void doInBackground()
{
System.out.println("in startserver...");
try
{
listeningSocket = new ServerSocket(port);
try
{
ip = InetAddress.getLocalHost();
System.out.println("Please enter this in your phone " + ip.getHostAddress());
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
while (true)
{
System.out.println("Waiting for connection");
connection = listeningSocket.accept();
InputStream in = connection.getInputStream();
Scanner r = new Scanner(in);
OutputStream o = connection.getOutputStream();
PrintWriter p = new PrintWriter(o);
String message = r.nextLine();
System.out.println("" + message);
t1.setText(message);
// get the message type
// 0 sms 1 contact 2 incoming call
System.out.println(message);
if(message.startsWith("0"))
{
System.out.println(message);
String type = message.substring(1,2);
int theType = Integer.parseInt( type );
String number = message.substring(7, 21).trim();
String theText = message.substring(21);
String theName = MyHelpers.getName(number, myContacts);
System.out.println("Number = "+number);
System.out.println("Sender = "+theName);
System.out.println("Text = "+theText);
Contact cRef = MyHelpers.getContactReference(number, myContacts);
if (cRef != null)
{
cRef.addsms(theType, theName, theText);
}
}
if(message.startsWith("1"))
{
System.out.println(message);
String name = message.substring(1, 31).trim();
String pnumber = message.substring(31, 51).trim();
String email = message.substring(51, 91).trim();
myContacts.add(new Contact(name, pnumber, email));
System.out.println( name + pnumber + email);
}
if(message.startsWith("2"))
{
String unkown = message.substring(0, 1).trim();
String number = message.substring(1, 14).trim();
String theName = MyHelpers.getName(number, myContacts);
System.out.println(""+unkown+""+theName+" Is calling you");
}
if(message.startsWith("5"))
{
System.exit(0);
}
Any Help would be great i am stumped by this
In your server append '\n' to the end of the response so change this
PrintWriter p = new PrintWriter(o);
p.println(text);
p.flush();
System.out.print("text sent"+text);
to this:
PrintWriter p = new PrintWriter(o);
p.println(text + "\n");
p.flush();
System.out.print("text sent"+text);
i think the reason it hangs is because readLine() is looking for '\n' and it never recieves it
while(s.isConnected())
{
String input =r.nextLine();
System.out.println("Client"+input);
}
I am able to load/save JTextArea unicode (devanagari) contents to file fine. I wanted to print the contents to pdf file so I am using iTextPDF api. My snippet is as below which prints empty file instead of with contents.
package i18n;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import com.itextpdf.awt.PdfGraphics2D;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;
public class MyNumbers extends JFrame {
private ResourceBundle rb;
private Font devanagariFont;
public MyNumbers (String language, String fontFile) {
loadResourceBundle(language);
loadFont(fontFile);
display();
}
TextArea txtArea;
private void display() {
String unicode = null;
JPanel labels = new JPanel(new GridLayout(0,2));
JLabel uni = null;
for(int i=0; i<=10; i++) {
unicode = rb.getString("" +i);
labels.add(new JLabel("" + i));
labels.add(uni = new JLabel(unicode));
//uni.setFont(devanagariFont);
}
labels.add(new JLabel("Time"));
labels.add(new ClockLabel());
getContentPane().setLayout(new FlowLayout());
Box b = Box.createVerticalBox();
b.add(labels);
b.add(txtArea = new TextArea(10, 40));
getContentPane().add(b);
addWindowListener(new WindowAdapter() {
#Override
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
try {
getInputContext().selectInputMethod(new Locale("hi", "IN"));
read();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
#Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
try {
System.out.println(getInputContext().getLocale());
save();
print();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.exit(0);
}
});
//setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
String fileName = "MyNumbers.txt";
private void save() throws IOException {
File f = new File(fileName);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-16"));
String txt = txtArea.getText();
writer.write(txt);
writer.flush();
writer.close();
}
private void read() throws IOException {
File f = new File(fileName);
if(f.exists() == false) return;
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-16"));
String line = null;
while((line = reader.readLine()) != null) {
txtArea.append(line + "\n");
}
reader.close();
}
private void loadFont(String fontFile) {
try {
InputStream input = getClass().getResourceAsStream(fontFile);
Font b = Font.createFont(Font.TRUETYPE_FONT, input);
devanagariFont = b.deriveFont(Font.PLAIN, 11);
} catch(Exception e) {
e.printStackTrace();
}
}
private void loadResourceBundle(String language) {
String base = getClass().getName() + "rb";
rb = ResourceBundle.getBundle(base, new Locale(language));
}
static class ClockLabel extends JLabel implements ActionListener {
private ClockLabel() {
new Timer(1000, this).start();
}
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
public void actionPerformed(ActionEvent e) {
Calendar cal = Calendar.getInstance();
setText(sdf.format(cal.getTime()));
}
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyNumbers("hi", "Devnew.ttf");
}
});
}
String pdfFileName = "MyNumbers.pdf";
private void print() {
System.out.println("Printing PDF file ..");
try {
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfFileName));
document.open();
PdfContentByte cb = writer.getDirectContent( );
PdfGraphics2D g2d = new PdfGraphics2D(cb, PageSize.A4.getWidth(), PageSize.A4.getHeight());
System.out.println(txtArea.getSize());
txtArea.print(g2d);
g2d.dispose();
document.close ();
}
catch(DocumentException de) {
System.err.println(de.getMessage());
}
catch(IOException ioe) {
System.err.println(ioe.getMessage());
}
}
}
Output to console:
hi_IN
Printing PDF file ..
java.awt.Dimension[width=300,height=170]
Please let me know know the fix. I am not setting any font for graphics assuming that the swing JTextArea should be able to handle it. The unicode support is added with indicim.jar Input Method framework. As per output above the Dimension shows that text area is not of zero size.
In order to test above you need 2 files:
indicim.jar and place it in jre/lib/ext
MyNumbers.txt - unicode content file in devanagari as below which as such you can type it yourself in text area and program saves/loads on shutdown/startup. You save it in the project dir of eclipse.
अम२ जवान
अम२ जवान
अम२ जवान
अम२ जवान
अम२ जवान
अम२ जवान
अम२ जवान
अम२ जवान
अम२ जवान
ऊँ
A pdf file will get created in eclipse project dir but for now its empty.
The problem is that you don't call:
writer.close()
on your PdfWriter. Adding that line at the end of your print() method should do the trick.
EDIT:
Here is an SSCCE (well you still need to add iText lib, version 4.2.0, to your dependencies) that works for me:
import java.awt.Desktop;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;
public class MyNumbers extends JFrame {
private Font devanagariFont;
public MyNumbers(String language, String fontFile) {
loadResourceBundle(language);
loadFont(fontFile);
display();
}
TextArea txtArea;
private void display() {
String unicode = null;
JPanel labels = new JPanel(new GridLayout(0, 2));
JLabel uni = null;
for (int i = 0; i <= 10; i++) {
unicode = String.valueOf(i);
labels.add(new JLabel("" + i));
labels.add(uni = new JLabel(unicode));
// uni.setFont(devanagariFont);
}
labels.add(new JLabel("Time"));
labels.add(new ClockLabel());
getContentPane().setLayout(new FlowLayout());
Box b = Box.createVerticalBox();
b.add(labels);
b.add(txtArea = new TextArea(10, 40));
getContentPane().add(b);
addWindowListener(new WindowAdapter() {
#Override
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
try {
getInputContext().selectInputMethod(new Locale("hi", "IN"));
read();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
#Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
try {
System.out.println(getInputContext().getLocale());
save();
print();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.exit(0);
}
});
// setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
String fileName = "MyNumbers.txt";
private void save() throws IOException {
File f = new File(fileName);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-16"));
String txt = txtArea.getText();
writer.write(txt);
writer.flush();
writer.close();
}
private void read() throws IOException {
File f = new File(fileName);
if (f.exists() == false) {
return;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-16"));
String line = null;
while ((line = reader.readLine()) != null) {
txtArea.append(line + "\n");
}
reader.close();
}
private void loadFont(String fontFile) {
try {
InputStream input = getClass().getResourceAsStream(fontFile);
Font b = Font.createFont(Font.TRUETYPE_FONT, input);
devanagariFont = b.deriveFont(Font.PLAIN, 11);
} catch (Exception e) {
e.printStackTrace();
}
}
private void loadResourceBundle(String language) {
String base = getClass().getName() + "rb";
}
static class ClockLabel extends JLabel implements ActionListener {
private ClockLabel() {
new Timer(1000, this).start();
}
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
#Override
public void actionPerformed(ActionEvent e) {
Calendar cal = Calendar.getInstance();
setText(sdf.format(cal.getTime()));
}
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MyNumbers("hi", "Devnew.ttf");
}
});
}
String pdfFileName = "MyNumbers.pdf";
private void print() {
System.out.println("Printing PDF file ..");
try {
File pdf = new File(pdfFileName);
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdf));
document.open();
PdfContentByte cb = writer.getDirectContent();
Graphics2D g2d = cb.createGraphics(PageSize.A4.getWidth(), PageSize.A4.getHeight());
System.out.println(txtArea.getSize());
txtArea.printAll(g2d);
g2d.dispose();
document.close();
writer.flush();
writer.close();
Desktop.getDesktop().open(pdf);
} catch (DocumentException de) {
System.err.println(de.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
}
}
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.