URLConnections and Input Streams
I am trying to get a jar file I have up on a web server.
First I make a connection to the server requesting the file..that works fine.
Second i want to use an input stream to bring in the file so i can read its contents.
The problem lies in using the InputStream to read a URL connection.
I have tried using the JarInputStream but that wont work.
Do I need to take my URLConnection and convert it to an object or data type that I am not aware of?
URL url = new URL("http://www.domain.com/myfile.jar");
URLConnection conn = url.openConnection();
JarFile in = new JarFile(new BufferedReader(new InputStreamReader(conn)));
Any ideas fellas?
At this point that is all I want to do. Just download the file.
Thats where I am having trouble.
Once I get it downloaded it should be fine.
Should I maybe write the input of the file coming off the server to input of a new file?
Similar Messages
-
When using URLConnection read input stream error
hi,
In my applet I build a URLConnection, it connect a jsp file. In my jsp file I refer to a javaBean. I send two objects of request and response in jsp to javaBean. In javabean return output stream to URLConnect. At that time a error happened.WHY???(Applet-JSP-JAVABean)
Thanks.
My main code:
APPLET:(TestApplet)
URL url = new URL("http://210.0.8.120/jsp/test.jsp";
URLConnection con;
con = url .openConnection();
con = servlet.openConnection();
con.setDoInput( true );
con.setDoOutput( true );
con.setUseCaches( false );
con.setRequestProperty( "Content-Type","text/plain" );
con.setAllowUserInteraction(false);
ObjectOutputStream out;
out = new ObjectOutputStream(con.getOutputStream());
Serializable[] data ={"test"};
out.writeObject( data );
out.flush();
out.close();
//until here are all rigth
ObjectInputStream in = new ObjectInputStream( con.getInputStream() );//happened error
JSP:
TestBean testBean = new TestBean ();
testBean .execute(request, response);
JAVABEAN:
public void execute( HttpServletRequest request,
HttpServletResponse response )
ObjectInputStream in = new ObjectInputStream( request.getInputStream() );
String direct = (String) in.readObject();
System.out.prinltn("direct");
ObjectOutputStream out = new ObjectOutputStream( response.getOutputStream() );
SerializableSerializable[] data ={"answer"};
out.writeObject( data );
out.flush();
out.close();
Error detail:
java.io.StreamCorruptedException: invalid stream header
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:729)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:251)
at TestApplet.postObjects(TestApplet.java:172)you have to pay attention to the sequence of opening the streams.
The following example is: client sends a string to server, and servlet sends a response string back.
client side:
URL url = new URL( "http://152.8.113.149:8080/conn/servlet/test" );
URLConnection conn = url.openConnection();
System.out.println( "conn: " + conn );
conn.setDoOutput( true );
conn.setDoInput( true );
conn.setUseCaches( false );
conn.setDefaultUseCaches (false);
// send out a string
OutputStream out = conn.getOutputStream();
ObjectOutputStream oOut = new ObjectOutputStream( out );
oOut.writeObject( strSrc );
// receive a string
InputStream in = conn.getInputStream();
ObjectInputStream oIn = new ObjectInputStream( in );
String strDes = (String)oIn.readObject();server side
// open output stream
OutputStream out = res.getOutputStream();
ObjectOutputStream oOut = new ObjectOutputStream( out );
// open input stream and read from client
InputStream in = req.getInputStream();
ObjectInputStream oIn = new ObjectInputStream( in );
String s = (String)oIn.readObject();
System.out.println( s );
// write to client
oOut.writeObject( s + " back" ); I have the complete example at http://152.8.113.149/samples/app_servlet.html
don't forget to give me the duke dollars. -
Regular expressions and input streams
Hello,
I am trying to find a way to read characters from a stream and find matches in them with regular expressions. The problem is that the stream may contain a big amount of characters, so I can't read all of them, keep them in a big string, and then perform the searches. Is there a way to perform searches while I read the characters? I scanned the documentation of Pattern and Matcher and found nothing that can help.
Any ideas?
Thanks.Looking at the method
public Matcher Pattern.matcher(CharSequence input);
one could be excused for assuming that one could turn an InputStream into a CharSequence object since a 'stream' implies sequencial access and CharSequence sounds like it provides sequential access.
This would just require the implementation of 4 method of which two (toString() and subSequence()) could probably be ignored BUT the method you wouild have to implement are charAt() and length() which imply random access rather than sequencial access!
Using the built in regex your problem looks difficult. If you are just looking for 'equality' matches (simple searching) then you could use Knuth-Morris-Pratt algorithm or the Boyer-Moore algorithm. -
Questions about reading/writing with output and input streams
I'm getting a bit confused on this subject. I have written an array of doubles to a file, and now I need to know how to read them back in to another array. I have also wrapped each double into its own object, but I need to know how to write those to a file, and read the doubles contained in them back into an array.
Here is what I have so far; the method that writes the array of doubles to a file.
public void writePrimDoubles() {
DataOutputStream outStream;
System.out.println("Now writing the values to file...");
try {
outStream = new DataOutputStream(new FileOutputStream("file.dat"));
catch (IOException ex) {
System.out.println("Error opening file");
return;
try {
for(int i = 0; i<arraySize; i++)
outStream.writeBytes(numberArray[i] + "\n");
outStream.close();
catch(IOException e) {
System.out.println("Error writing to file");
}* writes all doubles in the given array to the file 'file.dat'
public void writePrimDoubles(double[] array) throws IOException {
DataOutputStream out = new DataOutputStream(new FileOutputStream("file.dat"));
for(int i=0; i<array.length; i++) {
out.writeDouble(array);
out.close();
* reads in all stored doubles from the given file ('file.dat').
* cause of each double has been written to a 8byte part of the file
* you could get the number of doubles stored in the file by dividing
* its filesize by 8.
* Alternatively you might first store all read doubles as Double in
* a list (e.g. java.util.ArrayList). After reading all doubles you could then
* create a new double[] with the lists size (double[] array = new double[list.size()];)
* -> this alternative is commented out in the following code.
public double[] readPrimDoubles() throws IOException {
File file = new File("file.dat");
DataInputStream in = new DataInputStream(new FileInputStream(file));
double[] array = new double[file.length()/8];
for(int i=0; i<array.length; i++) {
array[i] = in.readDouble();
in.close();
return array;
ArrayList list = new ArrayList();
try {
while(true) {
list.add(new Double(in.readDouble()));
catch(EOFException e) {} // catchs the exception thrown when end of file is reached
in.close();
double[] array = new double[list.size()];
for(int i=0; i<list.size(); i++) {
array[i] = ((Double)list.get(i)).doubleValue();
return array;
For further information on the classes you have to use you might have a look to the concerning API documentation (http://java.sun.com/j2se/1.4.2/docs/api/). In this docs you could find all methods, constructors and fields accessable for a class.
have fun... -
Problem reading input stream of urlconnection within portal
Hi,
This may be a generic server issue rather than portal but since it's my portal app that's displaying the problem I'll post it here.
Part of my Portal attempts to POST to a remote server to retrieve some search results.
In environments A & B (both standalone instances) this works fine.
In environment C this works on the managed instances in the cluster but not the admin instance.
In environment D (again standalone) it fails, but if I add a managed instance it works from the managed instance.
The problem I'm seeing is that I get a stuck thread and the thread dump shows it is blocked attempting to read the resulting input from a urlconnection. (Using a buffered input stream).
I've copied the code to a standalone class that runs fine from the same server(s). I've pasted this code below, the contents of the test() method were copied directly from my webapp (urls changed here for clarity).
Does anyone know of any securitymanager issues that may cause this?
Or anything else for that matter?
Code sample:
package src.samples;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class POSTTest {
public static boolean test()
URL url = null;
try {
url = new URL
("http://hostx:80/myapp/search.html");
catch (MalformedURLException e)
e.printStackTrace();
return false;
URLConnection urlConn;
DataOutputStream printout;
BufferedReader input;
urlConn = null;
try {
urlConn = url.openConnection();
catch (IOException e)
e.printStackTrace();
return false;
// Let the run-time system (RTS) know that we want input.
urlConn.setDoInput (true);
// Let the RTS know that we want to do output.
urlConn.setDoOutput (true);
// No caching, we want the real thing.
urlConn.setUseCaches (false);
// Specify the content type.
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// Send POST output (this is a POST because we write then read as per the JDK Javadoc)
printout = null;
String body = "";
try {
System.out.println("url=" + url.toString());
printout = new DataOutputStream (urlConn.getOutputStream ());
String content = "param1=A¶m2=B¶m3=C¶m4=D¶m5=E";
System.out.println("urlParams= " + content);
printout.writeBytes (content);
System.out.println("written parameters");
printout.flush ();
System.out.println("flushed parameters");
printout.close ();
System.out.println("closed parameter stream");
// <b>Get response data - this is where it blocks indefinitely</b>
input = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
System.out.println("got input");
String str;
while (null != ((str = input.readLine()))) {
body = body + str + "\n";
System.out.println("read input:");
System.out.println(body);
input.close ();
System.out.println("closed input stream");
catch (IOException e) {
System.out.println("IOException caught: read failed");
e.printStackTrace();
return false;
return true;
* @param args
public static void main(String[] args) {
System.out.println("Test result= " + test());In your recuperar() method, read the FTP input stream into a byte array. (You can do that by copying it to a ByteArrayOutputStream and then getting the byte array from that object.) Then, return a ByteArrayInputStream based on those bytes. After you call completePendingCommand(), of course.
That's one way.
PC² -
I have maybe simple question, but I can`t really understand how to figure out this problem.
I have 2 applications(one on mobile phone J2ME, one on computer J2SE). They commuinicate with Input and Output Streams. Everything is ok, but all communication is in sequence, for example,
from mobile phone:
out.writeUTF("GETIMAGE")
getImage();
form computer:
reply = in.readUTF();
if(reply.equals("GETIMAGE")) sendimage()
But I need to include one simple thing in my applications - when phone rings there is function in MIDlet - pauseApp() and i need to send some signal to Computer when it happens. But how can i catch this signal in J2SE, because mayble phone rings when computer is sending byte array? and then suddnely it receives command "RINGING"....?
Please explain how to correcly solve such problem?
Thanks,
ErvinsEh?
TCP/IP is not a multiplexed protocol. And why would you need threads or polling to decipher a record-oriented input stream?
Just send your images in packets with a type byte (1=command, 2=image, &c) and a packet length word. At the receiver:
int type = dataInputStream.read();
int length = dataInputStream.readInt();
byte[] buffer = new byte[length];
int count, read = 0;
while ((count = dataInputStream.read(buffer,count,buffer.length)) > 0)
read += count;
// At this point we either have:
// type == -1 || count = -1 => EOF
// or count > 0, type >= 0, and buffer contains the entire packet.
switch (type)
case -1:
// EOF, not shown
break;
case COMMAND: // assuming a manifest constant somewhere
// process incoming command
break;
case IMAGE:
// process or continue to process incoming image
break;
}No threads, no polling, and nuthin' up my sleeve.
Modulo bugs. -
Separate thread for input stream and output stream.
Hi Techies,
In a socket connection, can we run the input stream and output stream in separate threads. actually in my case, the input stream will be getting the input regularly and output stream will send data very rare. so if i impelment them in one class then unless there is data to send output stream will be blocked. i was thinking to impelment both the streams in separate threads. is it a good way? so how to implement it. your guidance will be of great help.
thanks in advance.JavaBreather wrote:
Hi Techies,
In a socket connection, can we run the input stream and output stream in separate threads.I would say this is the most common way of handling sockets and threads. esp pre-NIO.
Iis it a good way? so how to implement it. your guidance will be of great help.Once you have a socket, create two threads, one which does the reading and one which does the writing.
You could use BlockingQueues to abstract access to these threads. i.e. the reading thread reads something from the socket and adds it to the BlockingQueue. The writing thread take()s something froma second BlockingQueue and writes it to the Socket. This way you add things to write or get thing to process by looking at the BlockingQueues. -
MultiThreading with Input and Output Streams
Hi,
I have a problem and I think it's because I'm not coding correctly. Please help me if you can understand what I'm doing wrong.
I have a server that spawns a separate thread to go off and collect data from a serial port. It also waits to accept connections from any client and if a connection is made it will send that data to the clients connected.
There is data constantly coming in through the serial port. It is output through a DataOutputStream so when the thread is created in the server, I pipe it into a DataInputStream. I do does because I want the server to then read in the data from the inputstream and then send it out to all my clients.
So far, the way I have it set up seems to do this. But my problem occurs when I try to close a client connection. Instead of removing the socket connection it gives me an error that it can't send data to the client, but it shouldn't be sending data to the client because I just closed it. I realize this is probably because I'm still constantly receiving data from my inputstream and the connection was closed so it can't send that data to the client. I know I need to either close the stream or close my socket but I don't know where this needs to be done. I'm stuck on the correct way to fix this.
My second problem is the initial connection made to receive data from the inputstream. This is probably because I'm not very familiar with how input/output streams work. But instead of just sending the client the current data being received in real time, it'll send all the data that's buffered in the inputstream. I don't want all the data that's been collecting to go to that first client. I only want the recent data that is coming through while the client is connected. Does this make sense? Because after I make a second client connection I don't have this problem because the InputStream is no longer buffered up. Should I be using something else besides the DataInputStream?
I feel like I'm going about this the wrong way. Please advise. I'm shy about showing the code but I've included the bulk of it here in hopes that someone will see what I'm doing wrong. The only part that's left out is the thread that reads from the serial port. I don't seem to have any problems with that thread.
Thanks,
kim
===
import java.io.*;
import java.net.*;
import javax.comm.*;
import java.util.*;
// DataServer waits for a client connection
class DataServer
static final int PORT = 7;
// The ServerSocket to use for accepting new connections
private ServerSocket ss;
// A mapping from sockets to DataOutputStreams. This will
// help us avoid from having to create a DataOutputStream each time
// we want to write to a stream.
private Hashtable outputStreams = new Hashtable();
// The inputstream that will receive serial port data through a
// piped inputstream
public DataInputStream datalogger;
// Constructor and while-accept loop all in one.
public DataServer() throws IOException
try {
// Creating pipe to convert the outputstream from the
// RS232 Thread to an inputstream for the server to read
PipedOutputStream pout = new PipedOutputStream();
PipedInputStream pin = new PipedInputStream(pout);
// The inputstream that will receive data from the RS232Thread
datalogger = new DataInputStream(pin);
// Spawn the thread that will read data through from
// the TINI serial port
new RS232Thread( pout ).start();
// Begin listening for connections and send data
listen();
} catch (IOException ioe) {
System.out.println("Error >> DataServer::DataServer()");
System.out.println(ioe.getMessage());
ioe.printStackTrace();
} finally {
try {
System.out.println( "Closing >> DataServer::DataServer()" );
datalogger.close();
} catch (IOException i ) {
System.out.println( "Error2 >> DataServer::DataServer()" );
System.out.println(i); }
private void listen() throws IOException
// Create the ServerSocket
ss = new ServerSocket( PORT );
// Inform that the server is ready to go
System.out.println( "Listening on " + ss );
// Keep accepting connections forever
while (true) {
// Grab the next incoming connection
Socket s = ss.accept();
// Inform that connection is made
System.out.println( "Connection from " + s );
// Create a DataOutputStream for writing data to the
// other side
DataOutputStream dout = new DataOutputStream( s.getOutputStream() );
// Save this stream so we don't need to make it again
outputStreams.put( s, dout );
// Create a new thread for this connection, and then foret
// about it
new ServerThread( this, s );
// Get an enumeration of all the OutputStreams, one for each client
// connected to the server
Enumeration getOutputStreams() {
return outputStreams.elements();
// Send a message to all clients (utility routine)
void sendToAll( byte[] b ) {
// synchronize on this because another thread might be
// calling removeConnection() and this would screw things up
// while it walks through the list
synchronized( outputStreams ) {
// For each client...
for (Enumeration e = getOutputStreams(); e.hasMoreElements();) {
// ... get the output stream ...
DataOutputStream dout = (DataOutputStream)e.nextElement();
// ... and send the message
try {
dout.write( b );
} catch(IOException ie) {
System.out.println( "Error >> ServerThread::sendToAll()" );
System.out.println( ie );
// remove a socket, and it's corresponding output stream, from the
// list. This is usually called by a connection thread that has
// discovered that the connection to the client is dead.
void removeConnection( Socket s ) {
// Synchronize so it doesn't mess up sendToAll() while it walks
// down the list of all output streams
synchronized( outputStreams ) {
// Inform about removal
System.out.println( "Removing connection to " + s );
// Remove if from our hastable/list
outputStreams.remove( s );
// Make sure it's closed
try {
s.close();
} catch( IOException ie ) {
System.out.println( "Error closing " + s );
ie.printStackTrace();
// main - Opens a server socket and spins off a new thread each time
// a new client connection is accepted on this socket.
public static void main(String[] args) throws Exception
System.out.println("Starting DataServer version 1.0 ...");
try
new DataServer();
catch (IOException ioe)
System.out.println( "Error >> DataServer::main()" );
System.out.println(ioe.getMessage());
ioe.printStackTrace();
class ServerThread extends Thread
//The Server that spawned this thread
private DataServer server;
// The Socket connected to the client
private Socket socket;
//Constructor
public ServerThread( DataServer server, Socket socket )
// save the parameters
this.server = server;
this.socket = socket;
// Start up the thread
start();
// This runs in a separate thread when start() is called in the
// constructor
public void run() {
try {
// The inputstream receiving data from the global inputstream
// that is piped to the RS232 Thread
// ???? is this where i'm messing up ???
DataInputStream in = new DataInputStream( server.datalogger );
int num = 0;
byte[] d = new byte[1];
// read from the inputstream over and over, forever ...
while( ( num = in.read(d) ) > 0 ) {
// ... and have the server send it to all clients
server.sendToAll( d );
} catch (IOException ioe) {
System.out.println( "Error >> ServerThread::run()" );
System.out.println(ioe.getMessage());
ioe.printStackTrace();
} finally {
// The connection is closed for one reason or another,
// so have the server dealing with it
System.out.println( "Closing" );
server.removeConnection( socket );A couple of things to note...
First, you are looping infinitely in your server's constructor. Since the constructor is never completing, your server object is never completely constructed - this may cause indeterminate behaviour when you pass a reference to the server to another thread.
Second, I would recommend fixing your issues by modifying your design somewhat. The design I would recommend (read: The design I would use) is:
A server object, with a public listen method. The constructor spawns a thread to constantly read from the serial port and forward the data read back to the server, via a multicast (sendToAll) method.
The listen method sets up a server socket to accept connections, and in a loop opens client sockets and stores them in a set.
The multicast method iterates through the list of open client sockets, and for each in turn confirms that it is still open. If open, send the data down the socket's output stream; if closed, remove the socket from the set.
Note that this design includes only two threads - the main thread listens for and accepts new socket connections, while the extra thread collects data from the serial port, multicasts it to all of the open sockets, and removes all of the closed sockets. If you require to perform any other communication with the sockets, it may be necessary to create a thread for those sockets, to facilitate reading from their input streams, but in the given design, this is not necessary.
I hope this helps,
-Troy -
Create HelpSet using input stream and not URL
Hi All,
I looked over the docs and apis and I was not able to find any way to create a HelpSet from an input stream.
Basically all I have is are input streams to the help files and not URLs, is there a way to initialize the help set with that?
thanksNever compare Strings using Object equality or inequality ("==" resp. "!=").
Use [url http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#equals(java.lang.Object)]String#equals (or [url http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#indexOf(java.lang.String)]String#indexOf or [url http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#matches(java.lang.String)]String#matches).
Please use code tags when posting code. This means wrapping your text between [code[/b]][[/b]code] tags. See the [url http://forum.java.sun.com/help.jspa?sec=formatting]Formatting tips. -
Read binary and ascii values from input stream
Hi All
I want to read a stream that consist both binary values and ascii values. Length of the stream cannot anticipate. Can you help me?
ThanksSameera wrote:
Hi All
I want to read a stream that consist both binary values and ascii values. Length of the stream cannot anticipate. Can you help me?
ThanksHave a look at this:
Character and Byte Streams
http://java.sun.com/docs/books/tutorial/i18n/text/stream.html -
SocketException during reads - JVM_recv in socket input stream read
I am getting a SocketException when a Java applet talks to our
WebLogic 7.0 server. The catch is that it only occurs at one site
(that has very high T1 utilization, although latency is only ~60 ms)
Our setup is such that the calls hit an Alteon load balancer, which
then sends the request out to one of 4 IIS clustered servers, where it
then is sent to one of 2 WL clustered servers. I figured latency
would be the cause, but on IIS and on WL, the timeouts are set to
several hundred seconds, so I am not quite seeing where the connection
is being reset. To be honest, I really don't know if it is WL that is
killing the connection, as nothing abnormal shows up in the WL log. I
have seen similar problems in this group, though, although the stack
traces never follow the same path mine does. I do have the following
call stack from the Java plug-in console, though. Any ideas would be
greatly appreciated.
java.net.SocketException: Connection reset by peer: JVM_recv in socket
input stream read
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read1(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown
Source)
at sun.plugin.net.protocol.http.HttpURLConnection.getInputStream(Unknown
Source)
at sun.net.www.protocol.http.HttpURLConnection.getHeaderFields(Unknown
Source)
at sun.plugin.net.protocol.http.HttpURLConnection.checkCookieHeader(Unknown
Source)
at sun.plugin.net.protocol.http.HttpURLConnection.getInputStream(Unknown
Source)
at org.xxxx.abstracts.Controller.sendRequest(Controller.java:39)
at org.xxxx.data.DataMediator.getDataNode(DataMediator.java:46)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Also, here is my code, although I can't see anything on the client
side that seems off:
public Object sendRequest( Object request, URL receiver ) throws
Exception{
Object response = null;
URLConnection con = null;
ObjectOutputStream out = null;
ObjectInputStream in = null;
try {
con = receiver.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setDefaultUseCaches(false);
con.setAllowUserInteraction(false);
out = new ObjectOutputStream(con.getOutputStream());
out.writeObject(request);
out.flush();
out.close();
in = new ObjectInputStream(con.getInputStream());
response = in.readObject();
in.close();
} catch (ClassCastException e) {
if( out != null ){
out.close();
if( in != null ){
in.close();
} catch (Exception e) {
if( out != null ){
out.close();
if( in != null ){
in.close();
throw e;
return response;There is a known bug on earlier 1.3.1 releases with sockets on Windows 2k
and XP. I don't remember all the details.
Peace,
Cameron Purdy
Tangosol, Inc.
http://www.tangosol.com/coherence.jsp
Tangosol Coherence: Clustered Replicated Cache for Weblogic
"Keith Patrick" <[email protected]> wrote in message
news:[email protected]...
I'm getting the exception on the client, which is an XP machine, while
the server is Win2K. I can't recall which, but either the applet or
the server runs 1.3x while the other runs 1.4. I discounted that
factor, though, as the problem only occurs on one site, which on all
others it works fine.
"Cameron Purdy" <[email protected]> wrote in message
news:<[email protected]>...
Exception is in the applet or on the server?
Would one of those by any chance be running on W2K with JDK 131_01 orolder?
>>
Peace,
Cameron Purdy
Tangosol, Inc.
http://www.tangosol.com/coherence.jsp
Tangosol Coherence: Clustered Replicated Cache for Weblogic
"Keith Patrick" <[email protected]> wrote in message
news:[email protected]...
I am getting a SocketException when a Java applet talks to our
WebLogic 7.0 server. The catch is that it only occurs at one site
(that has very high T1 utilization, although latency is only ~60 ms)
Our setup is such that the calls hit an Alteon load balancer, which
then sends the request out to one of 4 IIS clustered servers, where it
then is sent to one of 2 WL clustered servers. I figured latency
would be the cause, but on IIS and on WL, the timeouts are set to
several hundred seconds, so I am not quite seeing where the connection
is being reset. To be honest, I really don't know if it is WL that is
killing the connection, as nothing abnormal shows up in the WL log. I
have seen similar problems in this group, though, although the stack
traces never follow the same path mine does. I do have the following
call stack from the Java plug-in console, though. Any ideas would be
greatly appreciated.
java.net.SocketException: Connection reset by peer: JVM_recv in socket
input stream read
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read1(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown
Source)
at
sun.plugin.net.protocol.http.HttpURLConnection.getInputStream(Unknown
Source)
at sun.net.www.protocol.http.HttpURLConnection.getHeaderFields(Unknown
Source)
atsun.plugin.net.protocol.http.HttpURLConnection.checkCookieHeader(Unknown
Source)
atsun.plugin.net.protocol.http.HttpURLConnection.getInputStream(Unknown
Source)
at org.xxxx.abstracts.Controller.sendRequest(Controller.java:39)
at org.xxxx.data.DataMediator.getDataNode(DataMediator.java:46)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Also, here is my code, although I can't see anything on the client
side that seems off:
public Object sendRequest( Object request, URL receiver ) throws
Exception{
Object response = null;
URLConnection con = null;
ObjectOutputStream out = null;
ObjectInputStream in = null;
try {
con = receiver.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setDefaultUseCaches(false);
con.setAllowUserInteraction(false);
out = new ObjectOutputStream(con.getOutputStream());
out.writeObject(request);
out.flush();
out.close();
in = new ObjectInputStream(con.getInputStream());
response = in.readObject();
in.close();
} catch (ClassCastException e) {
if( out != null ){
out.close();
if( in != null ){
in.close();
} catch (Exception e) {
if( out != null ){
out.close();
if( in != null ){
in.close();
throw e;
return response; -
ImageIO - javax.imageio.IIOException: Can't get input stream from URL
Hi,
I'm developing a program which accesses a given URL of an image and saves it to a file. However when I try this I get the following error:
javax.imageio.IIOException: Can't get input stream from URL!
at javax.imageio.ImageIO.read(Unknown Source)
at ImageSave.main(ImageSave.java:12)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
... 2 moreThe internet connection I am using uses a proxy server and I think this is where the problem lies. I'm using Eclipse version 3.3 and I've tried changing the network settings to use the proxy's hostname and port but this still isn't working. I've also tried using System.setProperty("http.proxyHost", "hostname") and System.setProperty("http.proxyPort", "port") but that hasn't worked for me either. Below is my class in full.
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.net.*;
public class ImageSave
public static void main(String args[])
try {
URL url = new URL("http://www.example.com/image.jpg");
BufferedImage image = ImageIO.read(url);
ImageIO.write(image, "JPG", new File("image.jpg"));
catch (Exception e) {
e.printStackTrace();
}The error occurs with the line: BufferedImage image = ImageIO.read(url);
I have tried looking for a way to change how this specific method accesses the internet (e.g: a Proxy parameter with URLConnection) but there doesn't seem to be any.
Any help or suggestions would be greatly appreciated.
-RobertAh, that worked fine. I had thought of using that earlier but I was under the impression that the input stream would be HTML rather than an actual image. Not sure why.. Anyway, thanks very much for your help!
Here is the new code with your suggested revisions and a URLConnection to get the input stream:
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.net.*;
public class ImageSave
public static void main(String args[])
try {
// This is where you'd define the proxy's host name and port.
SocketAddress address = new InetSocketAddress(hostName, port);
// Create an HTTP Proxy using the above SocketAddress.
Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
URL url = new URL("www.example.com/image.jpg");
// Open a connection to the URL using the proxy information.
URLConnection conn = url.openConnection(proxy);
InputStream inStream = conn.getInputStream();
// BufferedImage image = ImageIO.read(url);
// Use the InputStream flavor of ImageIO.read() instead.
BufferedImage image = ImageIO.read(inStream);
ImageIO.write(image, "JPG", new File("image.jpg"));
catch (Exception e) {
e.printStackTrace();
}Edited by: Ragnarob on Apr 21, 2009 2:49 AM -
This is probably a little thing that I have forgotten but I can't for the life of me get. Ok I should probably say I am running XP, with Java 1.5 and Firefox
I have an applet that works fine on Eclipse but when I try to run it by it self it seems to die at the point where I have my input streams.
Basicly I have included the test code that removes all the input processing and tree building. This test script below just opens a input stream, creates a tree with two nodes and displays the tree. If you remove any the 3 TRYS it will not work.
I have tried various methods to read in the URL I have but it seems to die every time. I have included the code below. If anyone has any suggestions I would greatly appreciate it.
Thanks
Luis
import java.applet.AppletContext;
import java.awt.Color;
import java.awt.Font;
import java.io.DataInputStream;
import java.io.InputStream;
import java.net.*;
import java.io.*;
import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.net.URLConnection;
public class TestApplet extends JApplet{
// Variables used by the applet
protected JTree jt;
protected URL url;
public void init() {
setBackground(Color.lightGray);
setFont(new Font("Verdana", Font.BOLD, 12));
try{
url = new URL("http://www.yahoo.com");
//IF I REMOVE ANY OF THE FOLLOWING COMMENTS IT DOES NOT WORK
//TRY 1. IF REMOVED IT WILL NOT WORK
/* URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(yahoo.openStream());
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
//TRY 2. IF REMOVED IT WILL NOT WORK
/* URLConnection connection = url.openConnection();
InputStream in = connection.getInputStream();
DataInputStream stream = new DataInputStream(in);
//TRY 3. IF REMOVED IT WILL NOT WORK
//BufferedReader stream = new BufferedReader(new InputStreamReader(url.openStream()));
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(url);
rootNode.add(new DefaultMutableTreeNode("Child 1"));
JTree jt = new JTree(rootNode);
// Tree Setup
jt.setExpandsSelectedPaths(true);
jt.setVisible(true);
jt.putClientProperty("JTree.lineStyle", "Angled");
getContentPane().removeAll();
getContentPane().add(jt);
//stream.close();
//iStream.close();
} catch (Exception e) {
e.printStackTrace();
public void start() {
}// end TreeApplet ClassYou are right on the money about the applet viewer working and the security errors I am getting. Look below this is from the console.
java.security.AccessControlException: access denied (java.net.SocketPermission www.reservhotel.com:80 connect,resolve)
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at RHMenu.start(RHMenu.java:80)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I understand that the applet cannot connect to a server other than the one it is connected to but shouldn't I be able to connect to "www.yahoo.com"? I tried putting the URL and open stream in the start thread but it does not seem to work. When I run it in a web browser, the Java Sun comes up and it says it is inited and started but nothing comes up. Any ideas?
Thanks,
Luis -
Reading an image from input stream
Hello all,
I'm familiar with setting up an input stream but I have never actually done it. I'm making a connection to a URL (a JPG image). I would like to read the JPG from the URL using an input stream. With the URL class I was able to open a stream, however, I'm not exactly sure how to read from it.
I'm aware of the read() method and read(byte[]) methods of inputstream. But how do I actually implement it?
If I use read(), then bytes come in individually... do I need to combine them at one point? If I read the bytes into an array, how do I determine what size to set the array and how do I convert the byte array into an Image or ImageIcon?
Please advise.
R. AlcazarHi,
See http://java.sun.com/products/jdk/1.2/docs/guide/2d/api-jpeg/
and especially JPEGCodec.createJPEGDecoder(java.io.InputStream).
Anyway, you might not want to do it with InputStream. Instead you could try something like this:
URLConnection con = // get it somehow
Image i = (Image) con.getContent(new Class[] {Image.class});
However, If you still want to use the InputStream, here you go with some pseudo code:
InputStream in = // get the input stream with JPEG data...
JPEGImageDecoder dec = JPEGCodec.createJPEGDecoder(in);
Image i = dec.decodeAsBufferedImage();
You can get the InputStream from the URLConnection with getInputStream(). However, I don't remember if the InputStream contained also the HTTP (or what ever protocol the URL specifies) headers. If it contains the headers, then you must rip them of before giving the InputStream to the JPEGCodec...
If this is the case, try calling the URLConnection.getHeaderFields() method before getInputStream. This might not work though. -
Error obtaining input stream!!!
Hi java guys,
i am trying to connect from an applet thru sockets. its working fine on the intranet, but on the internet its not. i am using ObjectInputStream to wrap the input stream but its blocking for some time and then giving a EOF Exception. i am trying to pass java objects from the applet. i am using port 7129. Even while using URLConnection its giving me the same problem!
kindly help!!!!
philhi everybody,
thanx to all. pls take a look at the servlet end of the sample code. this is inside the innerclass of the servlet which is responsible for the IO part:-
Socket client = s.accept();
client.setSoTimeout(5000); //timeout after 5 seconds
ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
out.flush();
ObjectInputStream in = new ObjectInputStream(client.getInputStream());
in.close();
if (in==null){
//null notification
ChatRoom dt = (ChatRoom) in.readObject();
if (dt==null)
//null notification
distributeMsgs(dt);
RoomList newRoomList=null;
if (lastUpdate != null){
newRoomList = getNewRoomList();
out.writeObject(newRoomList);
out.close();
client.close();
client = null;
help needed!
and thanx everybody
luv
phil
Maybe you are looking for
-
When I installed itunes into my old computer (loaded with Windows Vista) it deleated my CD burner and would only allow me to burn via itunes - I had to go in to Best Buy to have them fis the problem but was told not to download new updates for itunes
-
Hi all, When I want to edit the audio of a subclip created in FCP, the entire clip opens in Soundtrack, not just the portion of it that I've made into a subclip. Even if I mark the In and Out in FCP, it opens without showing this segment, so I can't
-
ITS 6.20 patch level 18 - dual host - Linux/Apache
Has anyone had to deal with the error message? "Error in EnviInitialize, rc=1100" This is diplayed when starting Apache. I suspect it's from the Wgate component that Apache is trying to start. I setup a dual-host ITS, and it worked fine: I could acc
-
Can I use gmail instead of yahoo in combination with Adobe Reader
Adobe Reader has the ability to attach a pdf to an email. It is defaulting to Yahoo mail. I have changed the default email in firefox to gmail, but that does not seem to impact anything. I have also tried to change the email client within Adobe Reade
-
Keyboard Shortcuts not working on iPad Air / iOS 8.1
No idea why.