Win a copy of Head First Android this week in the Android forum!

Sanjit Singh

Greenhorn
+ Follow
since Nov 12, 2001
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by Sanjit Singh

Hi Everyone,
Below you will find a method that takes a Document object as a parameter and returns a byte array.
**************************************************************
private byte[] xmlToBytes(Document document) {
try {
TransformerFactory tfactory = TransformerFactory.newInstance();
Source source = new DOMSource(document);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
Result result = new StreamResult(bout);
Transformer transformer = tfactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "no");
transformer.transform(source, result);
return bout.toByteArray();
}catch(Exception e) {
return null;
}
}
**************************************************************
You might have noticed that I set OutputKeys.INDENT to "no" during transformation, but this doesn�t seem to have an effect. I would like to get a byte array containing xml, but without any carriage returns or whitespaces (simply the whole xml without any gaps in between).
Can somebody please help me out? Is there a way to convert a dom to a byte array without carriage returns/whitespaces/blankspaces?
Thanks in advance and looking forward to some replies!
18 years ago
Hi Everyone,
I have written a simple client and a server program that attmepts to transfer a zip file (though it can e used to transfer any file). It works perfectly and the transferred zip file is saved successfully on the client machine, but the problem arises when I try to open the saved file again using the "ZipFile" class. The server and client code is as follows:
SERVER
************************************************************************
public class OldFtpServer {

private final int port = 50001;
private ServerSocket mServerSocket = null;

public OldFtpServer() {
try {
mServerSocket = new ServerSocket(port);
} catch(IOException e) {
e.printStackTrace();
return;
}

System.out.println("FTP Server Ready");

File file = new File("C:\\error.zip");

while(true) {
BufferedReader in = null;
Socket clientSocket = null;
BufferedOutputStream out = null;
FileInputStream fin = null;

try {
clientSocket = mServerSocket.accept();
} catch(Exception e) {
e.printStackTrace();
return;
}
System.out.println("-->" + clientSocket.getInetAddress().getHostAddress() + " connected");

try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new BufferedOutputStream(clientSocket.getOutputStream());

String temp = null;
String request = in.readLine();
while(!(temp = in.readLine()).equals("end"))
request = request + temp;

fin = new FileInputStream(file);

byte[] bytes = new byte[1024];

while(fin.read(bytes) != -1) {
out.write(bytes);
out.flush();
}
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
fin.close();
in.close();
out.close();
clientSocket.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}

}
public static void main(String[] args) {
OldFtpServer mFtpServer = new OldFtpServer();
}
}
**********************************************************************
CLIENT
*********************************************************************
public class OldFtpClient {
private final int port = 50001;
private final String address = "localhost";
public OldFtpClient() {
Socket mSocket = null;
try {
mSocket = new Socket(address, port);
} catch (Exception e) {
e.printStackTrace();
return;
}
PrintWriter out = null;
FileOutputStream fout = null;
BufferedInputStream in = null;
File file = new File("C:\\errorresult.zip");
try {
out = new PrintWriter(new OutputStreamWriter(mSocket.getOutputStream()));
in = new BufferedInputStream(mSocket.getInputStream());
out.println("blabla");
out.println("end");
out.flush();
fout = new FileOutputStream(file);
byte[] bytes = new byte[1024];
while(in.read(bytes) != -1) {
fout.write(bytes);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
fout.close();
out.close();
in.close();
mSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//CHECK TO SEE IF ZIP FILE CAN BE OPENED!!!
//This is where the exception occurrs..Why???
try {
ZipFile zipFile = new ZipFile(file);
zipFile.close();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
OldFtpClient mFtpClient = new OldFtpClient();
}
}
***********************************************************************
As you can see in the client program, the small check in the end fails and an exception is thrown. I have even tried using ZipInputStream and ZipOutputStream, but all my efforts were in vain.Can somebody please help me?
Thanks and looking forward to some replies!
Hi Everyone,
I have a series of large XML files that I would like to transfer "one by one" from my server to the client (in bytes) over sockets.
I would like to use a byte array and also a buffer. As of now, I have the folloing;
SERVER
OutputStream out = socket.getOutputStream();
out.write(bytes);
out.flush();
out.close();
CLIENT
InputStream in = socket.getInputStream();
byte[] bytes = new byte[999999999];
//a huge byte array because each file is very hugeint i = in.read(bytes);
String request = new String(bytes, "UTF-8");
in.close();
After the transfer of one XML file, I get an "OutOfMemeoryException". Could someone give me an optimal solution so that I can transfer large amounts of bytes from the server to the client efficiently. Thanks!
Hi All,
I am not too familiar with thread programming and thus, any help with my problem would be highly appreciated.
I have a program that wants to contact a server, but sometimes it hangs in the middle. Thus, I have tried to use threads to implement timeout.
I start two threads, one of them goes to sleep for a particular period of time and the other one starts the process of contacting the server. If the contact is successfull, but the sleeping thread is still alive, then no timeout occurs. But on the other hand, if the sleeping thread wakes up and the contact thread is still executing, then I would like to "terminate" that thread and simply show Timeout message.
I have imeplemented something, but it doesn�t work properly. Sample code is as follows:
******************************************
public synchronized void performOperation(String request, int sequence) {
Thread timerThread = new TimerThread();
Thread contactXMLClient = new ContactXMLClient(request, sequence);

contactXMLClient.start();
timerThread.start();
while(contactXMLClient.isAlive() && timerThread.isAlive()) {
//simply wait.dont do anything
}
if(contactXMLClient.isAlive()) {
contactXMLClient.interrupt();//interrupt is only a possibility
System.out.println("TIMEOUT");
}
else {
timerThread.interrupt();
System.out.println("Worked");}
}
***********************************************
//private classes
private class TimerThread extends Thread {
public TimerThread(){}

public void run() {
try {
this.sleep(20000);
} catch(Exception e) {}
}
}

private class ContactXMLClient extends Thread {
private String xml;
private int sequence;

public ContactXMLClient(String xml, int sequence) {
this.xml = xml;
this.sequence = sequence;
}

public void run() {
String line;
String receivedXML = "";
try {
URL repURL = new URL(url);
HttpURLConnection con = (HttpURLConnection) repURL.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setUseCaches(false);
byte[] bytes = xml.getBytes();
con.setRequestProperty("Content-length", String.valueOf(bytes.length));

OutputStream out = con.getOutputStream();
out.write(bytes);
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

while((line = in.readLine()) != null)
receivedXML = receivedXML + "\n" + line;

in.close();
con.disconnect();
} catch(Exception e) {}
}}
*********************************************
the interrupt method was only a suggestion. I hope you understand what I want to achieve. The above does not work properly and any help would be highly appreciated. Thanks!
Hi Everyone,
I have a JAVA client that sometimes hangs up waiting for a response from the server.
The basic code where it hangs is as follows:
********
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
********
where con is an object of the HttpURLConnection class.
I would like to avoid this somehow. I would like the thread to only wait for 10 seconds on this particular line (only on this line) and if a response still doesn�t come, then exception occurs.
I can imagine that I have to use the Timer class. Any help in this regard (sample code, ideas) would be highly appreciated.
Thanks!
19 years ago
Hi,
I am displaying an XML file in a JTree. I would like the user to be able to click on the nodes and change its name. It would be nice if after removing the focus from the changed node, the changes are automatically saved in the xml file.
I have no idea how to implement this and any insights from an experienced person would be very helpful.
Regards,
Sanjit
19 years ago
Hi,<p>
I would like to display well formed XML in a swing GUI. The main point that I would like to achieve is the "indentation", so that the user can easily read the xml file.
Does anyone have any ideas about which component is best to use in this scenario? Any code would also be very helpful!
As of now, I have a JTextArea, but the xml is not indented. Thus, looking forward to a way to indent xml so that it is user readable.
Thanks!
P.S: any other way except JTree?
19 years ago
Hi Peter,
Thanks a lot for your reply. I realize what you just said, but the strange thing is that if I put a out.close() method after out.flush(), then the message is received successfully on the server with the body, but the client and the server crashes (i.e. exceptions). I can imagine that out.close() releases some resources, including the connection. If you are interested, kindly try it out. I am confused. How can I simply send a series of bytes to the server and when the server receives all of it, then it sends a series of bytes back to the client. How can I read and write them? Any example would be great!
Thanks!
SS
Hi,
Thanks a lot for your reply.
1. As mentioned by you, I tried \r\n in my response string and then somehow I don�t receive anything on the client side. I only receive a response on the client side with "\n\r".. . I dont know why.
2. I put a line terminator (\n, \r, \r\n) in the client code and it still doesn�t work.
Any other ideas. Thanks!
SS
Hi,
I am trying to write my own java client and a java http server. My main aim is to send an XML document in the body of http and in return get a sequence ID from my own http server. The code for both client and server is as follows:
***********SERVER**********************
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(12001);
System.out.println("HTTP Server (only POST implemented) is ready and is listening on Port Number 12001 \n");
while(true) {
Socket clientSocket = serverSocket.accept();
System.out.println(clientSocket.getInetAddress().toString() + " " + clientSocket.getPort());
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
OutputStream out = clientSocket.getOutputStream();
String temp;
while((temp=in.readLine()) != null)
System.out.println(temp);
String response = "HTTP/1.1 200 OK\n\r";
response = response + "Date: Fri, 04 May 2001 20:08:11 GMT\n\r";
response = response + "Server: Sanjits Server\n\r";
response = response + "Connection: close\n\r";
response = response + "1";
byte[] bytes = response.getBytes();
out.write(bytes);
out.flush();
in.close();
out.close();
}
} catch(Exception e) {
System.out.println("ERROR: " + e.getMessage());
System.exit(1);
}}}
********************************************************* **********CLIENT***************************************
public class Client {
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:12001");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setUseCaches(false);
String test = "<name>Hello</name>";
byte[] bytes = test.getBytes();
con.setRequestProperty("Content-length", String.valueOf(bytes.length));
con.setRequestProperty("Content-type", "text/html");
OutputStream out = con.getOutputStream();
out.write(bytes);
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String temp;
while((temp = in.readLine()) != null)
System.out.println(temp);
out.close();
in.close();
con.disconnect();
} catch(Exception e) {
e.printStackTrace();
System.exit(1);}}}
*********************************************************** The output on the server side is as follows
HTTP Server (only POST implemented) is ready and is HTTP Server (only POST implemented) is ready and is listening on Port Number 12001
127.0.0.1/127.0.0.1 1592
POST / HTTP/1.1
Content-length: 18
Content-type: text/html
User-Agent: Java1.3.1_04
Host: localhost:12001
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
************************
As you can see above, the http server simply "hangs" after reading the http header. It never reaches the http body and doesnt even process the response to the client. Does anyone have any ideas how to solve this? I am stuck and any help would be appreciated. Please feel free to try the code above. Thanks in advance!
Hi Everyone,
I am trying to achieve something and I am not sure if it is the right way of doing it.
My client program is as follows:
***********CLIENT*********************************
URL url = new URL("http://localhost:12000");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setUseCaches(false);
String test = "Normally here would be contents of an XML file";
byte[] bytes = test.getBytes("UTF8");
OutputStream out = con.getOutputStream();
out.write(bytes);
out.flush();
out.close();
con.disconnect();
**********************************************
Due to some reasons, the client code cannot be changed. I need to send the contents as a byte array over http using the POST method. Now, I am interested in creating my own Server which takes this post request and stores the contents in a string. Could someone kindly help me with this. I have written the following so far:
*************SERVER*******************************
ServerSocket serverSocket = new ServerSocket(12000);
System.out.println("HTTP Server (only POST implemented) is ready and is listening on Port Number 12000 \n");
Socket clientSocket = serverSocket.accept();
BufferedInputStream in = new BufferedInputStream(clientSocket.getInputStream());
//kindly help here.code for manipulating the bytes. storing stuff in byte array and storing the contents received in a string
in.close();
clientSocket.close();
serverSocket.close();
*************************************************
Please note that I have tried the BufferedReader and readLine() method, but I do not receive anything and it doesnt seem to work. Any code would be very helpful. I am nterested in extracting the xml file that is in the body of the http post request and storing this in a string on the server.
Thanks in advance!
Sanjit
Hi,
I have a Document object that contains the contents of an XML document. Is it possible to get the whole XML document as a "string" from this document object?
I would be interested in storing the whole XML document as a string. Thanks in advance!
Hi All,
I have a very basic I/O question concerning PrintWriter. I am basically new to JAVA, so any help would be appreciated.
I have a method:
public void onResponseSent(PrintWriter writer){
}
How can I call this method?. My main aim is to transfer the contents of an XML file from one class to this class using the above method. In this method then I want to manipluate the contents of the XML document. How can I achieve this?
I can only use the above method, so any helpful code would be appreciated.
As you can see, its a stupid q, but hopefully somebody can help me out. Thanks!
19 years ago
Hi everyone,
This is fairly a basic question and I am somehow confused how to implement it due to my lack of experience with Java I/O.
I have an XML document that I am gerneating on the fly and writing it out to a file with PrintWriter out statements on a FileOutputStream.
I want to achieve the following:
I want another class (exists within the same JVM) to get hold of this XML document without reading it out of the file. In other words, I want everything to remain in memory, so that no file system is involved.
Is it possible to write the contents of the XML document out on the stream into the memory and have my other java program simply read it in through an input stream (without any sockets).
I am not sure whether this is possible, so any help would be appreciated. Even some sample code would be nice. THANKS!
19 years ago