InputStream in = urlconnection.getInputStream();

Dear All,
I am trying to zip a file in the client side and sending it to the server side machine......there, i am trying to unzip it and writting it over there...for this, i am using a seperate program in the client side and in the server side.................................
In the client program, after opening all the necessary streams and all formalities, i am using the code...
"InputStream in = urlconnection.getInputStream();
while (in.read()!=-1);"
only if i use the above code, the zipped file is transfered to my server machine...but in this case, the link with the server is not getting disconnected...i mean the command prompt remains alive, without stopping...what i inferred is, my control is got into the above said "InputStream in = urlconnection.getInputStream();"...indefinitely...
so i tried of removing the above said statement.....in this case, the zipped file is NOT getting written in my server machine....
what to do???
any suggestions please...waiting for the reply very anxiously, refreshing this site for every 2 minutes....
sakthivel s.
snippet code for ur reference...
Client side
try
ZipOutputStream zipoutputstream = new ZipOutputStream(urlconnection.getOutputStream());
ZipEntry zipentry = new ZipEntry(filename);
zipentry.setMethod(ZipEntry.DEFLATED);
zipoutputstream.putNextEntry(zipentry);
byte bytearray[] = new byte[1024];
File file = new File(filenamedir);
FileInputStream fileinputstream = new FileInputStream(file);
BufferedInputStream bufferedinputstream = new BufferedInputStream(fileinputstream);
int length = 0;
while((length=bufferedinputstream.read(bytearray)) != -1)
zipoutputstream.write(bytearray,0,length);
fileinputstream.close();
bufferedinputstream.close();
zipoutputstream.flush();
zipoutputstream.finish();
zipoutputstream.closeEntry();
zipoutputstream.close();
InputStream in = urlconnection.getInputStream();
while (in.read()!=-1); // the said while loop....................
System.runFinalization();
urlconnection.getInputStream().close();
urlconnection.disconnect();
the way of connecting witht the server : (just a snippet of the code)
URL serverURL = new URL("http://192.168.10.55:8001/servlet/uploadservlet");
HttpURLConnection.setFollowRedirects(true);
urlconnection= (HttpURLConnection)serverURL.openConnection();
urlconnection.setDoOutput(true);
urlconnection.setRequestMethod("POST");
urlconnection.setDoOutput(true);
urlconnection.setDoInput(true);
urlconnection.setUseCaches(false);
urlconnection.setAllowUserInteraction(true);
urlconnection.setRequestProperty("Cookie",cookie);
urlconnection.connect();
Server Side:
javax.servlet.ServletInputStream servletinputstream = httpservletrequest.getInputStream();
ZipInputStream zipinputstream = new ZipInputStream(servletinputstream);
ZipEntry zipentry = null;
String directory="c:\\test"; // the unzipped file should be written to this directory...
try
File file = new File(directory);
if(!file.exists())
file.mkdirs();
catch(Exception exp)
{System.out.println("I am from Server: " + exp);}
try
zipentry = zipinputstream.getNextEntry();
if(zipentry != null)
int slash = zipentry.getName().lastIndexOf(File.separator) + 1;
String filename = zipentry.getName().substring(slash);
File file1 = new File(directory + File.separator + filename);
FileOutputStream fostream = new FileOutputStream(file1);
BufferedOutputStream bufferedoutputstream = new BufferedOutputStream(fostream);
byte abyte0[] = new byte[1024];
for(int index = 0; (index = zipinputstream.read(abyte0)) > 0;)
bufferedoutputstream.write(abyte0, 0, index);
servletinputstream.close();
bufferedoutputstream.flush();
bufferedoutputstream.close();
zipinputstream.closeEntry();
zipinputstream.close();
fostream.flush();
fostream.close();
catch(IOException ioexception)
{System.out.println("IOException occured in the Server: " + ioexception);ioexception.printStackTrace();}
P.S: I am not getting any error in the server side or cleint side...the only problem is, the command prompt(where i am running my cleint program) is getting standing indefinitely...i have to use control-c to come to the command prompt again...this is because of the while looop said in the client machine....if i remove it...the file is not gettting transfered...what to do????

snoopybad77 wrote:
I can't, I'm using java.net.URL and java.net.URLConnection....Actually you are using HttpURLConnection.
java.net.URLConnection is an abstract class. The concrete implementation returned by openConnection for an HTTP based URL is HttpURLConnection. So you might want to try the previous suggestion and otherwise examining the methods of HttpURLConnection to see how they might be helpful to you.

Similar Messages

  • URLConnection.getInputStream() craches thread

    Hi
    I'm trying to parallelize a downloading process i'm developing, and my download started to behave a bit sporadic. The thread dies right after the System.out.println("1") in the following code snippet, s is an url.
    for(String s:urls) {
      try {
        URL url = new URL(s);
        URLConnection uc = url.openConnection();
        System.out.println("1 " + s);
        InputStream is = uc.getInputStream();
        System.out.println("2");
        BufferedReader br = new BufferedReader(new InputStreamReader(is));the output from strace (list of system commands) on my system shows the following relevant part:
    [pid  4438] write(1, "1 http://alatest1-cnet.com.com/4"..., 513 http://alatest1-cnet.com.com/4941-3000_9-0-1.html) = 51
    [pid  4438] write(1, "\n", 1
    ) = 1
    [pid  4438] gettimeofday({1174556453, 323179}, NULL) = 0
    [pid  4438] send(17, "GET /4941-3000_9-0-1.html HTTP/1"..., 177, 0) = 177
    [pid  4438] recv(17, <unfinished ...>
    [pid  4438] <... recv resumed> 0xb52e6cb0, 8192, 0) = ? ERESTARTSYS (To be restarted)
    this is the last output from this pid, it seems like it just lies down and dies efter it got the ERESTARTSYS.
    I have tried this on java 1.6.0 and 1.5.0_07 with linux kernel 2.6.17.7.
    Am I calling the connecting function wrong, or is there some other error maybe?

    sorry to be a little unclear.
    I don't get any exceptions, and i also added a catch(Exception e) { System.out.println(e); } to make sure.
    The Thread doesn't hang, it just dies silently.

  • URLConnection getInputStream()

    Hi guys.
    I am writing an applet that is getting information from a .php file. I am opening a connection to the .php and posting to it, then I am opening an input stream from the connection and reading from it.
    From the input stream, I can easily open a stream reader and read the data from it, but when I try to pass the input stream to another function, the program stalls indefinitely.
    Here is an example:
                   //works fine
                                    URLConnection conCon = conURL.openConnection();
                        conCon.setDoOutput(true);
                        conCon.setUseCaches(false);
                        OutputStreamWriter conOut = new OutputStreamWriter(conCon.getOutputStream());
                        conOut.write(conPost);
                        conOut.flush();
                        conOut.close();
                        InputStream conIS = conCon.getInputStream();
                        BufferedReader buff = new BufferedReader(new InputStreamReader(conIS));
                        System.out.println(buff.readLine());
                    //but if instead I do
                        InputStream conIS = conCon.getInputStream();
                        conSeq = FastaParser.getSequence(conIS);
    //elsewhere
         public static String getSequence(InputStream is) throws IOException{
              String seq = "";
              InputStreamReader ir = new InputStreamReader(is);
              BufferedReader br = new BufferedReader(ir);
              String line = br.readLine();
                    return line;
    //it times outThis is just an example. I am doing other things with the input stream. Is there any way to stop it from stalling here?
    Edited by: shiroganeookami on Oct 19, 2007 9:21 AM

    shiroganeookami wrote:
    well, here's the actual code:
    ...I don't see anything in that which would behave badly, other than possibly not checking your initially read string for null or checking string lengths before trying to use charAt(0) on it. I do see that you're conditionally building a "seq" string and then tossing it, returning only the last line (or null) you read, so that doesn't look right. But it doesn't look like it could possibly be the problem leading to this topic.
    Looks like you better do some (more) debugging, by running in a debugger if possible, or at a minimum logging clues along the way, such as putting a
    System.out.println("Here's the line I just read from the stream:" + line + ":");
    in the do-while loop to see if it's getting in there and what you're reading from the stream.
    And log other clues as well, such as at the end of the method to let yourself know whether the method returned or not, and before and after each br.readLine to let yourself know whether the readLine is hanging.

  • InputStream in = uConnect.getInputStream();//Error

    Hi,
    It would be kind if anybody could tell me why i am getting :java.io.FileNotFoundException:
    on line
    InputStream in = uConnect.getInputStream();
    I am created a URL object and passing that URL object in a URLConnection object.
    String page_to_connect = "http://cd2iis02/inbi/admin/updatestatus.cfm?domain="+s_name+"&requestid="+sreq_id+"&status="+status+"&msg="+ smessage;
    URL serverUrl = new URL(page_to_connect);
    URLConnection uConnect = serverUrl.openConnection();
    uConnect.setDoOutput(true);
    uConnect.setUseCaches(false);
    PrintStream out = new PrintStream
    (uConnect.getOutputStream());
    out.close();
    //Filenotfound exception is thrown at the below line**
    InputStream in = uConnect.getInputStream();
    StringBuffer response = new StringBuffer();
    int chr;
    while((chr=in.read())!=-1) { // this is line number 94
    response.append((char)chr);
         in.close();
         String sResponse = response.toString();
    Can anyone tell me why is this exception coming ,Its not finding the file . Is there any way to rectify this error.
    Any replies will be appreciated
    Thanks
    Regards,
    John

    i don't know if this will help but this is how i did it:
    create a URL object out of the base url (i.e. not including the parameters).
    get a connection
    get the OutputStream
    send the parameters through the connection
    flush and close the OutputStream
    then open the InputSteam.
    do whatever....

  • Bad Record MAC. exception while using urlConnection.getInputStream()

    All,
    In my SAP J2EE instance, from filter I am trying to do get data from an url (protocol is https).
    For this I am using urlInstance.openConnection() after that urlConnection.getInputStream() and then reading from this input stream.
    When I use http protocol, everything works fine. But with https, during urlConnection.getInputStream(), I get an exception saying "Bad Record MAC".
    I tried to execute the same code in a standalone java program. It went fine with both http and https.
    I get this error only when I run in SAP J2EE instance and only with https.
    From the exception trace, I can see that while running in J2ee engine, the URLConnection instance is org.w3c.www.protocol.http.HttpURLConnection.
    When I run a standalone program from command prompt, the instance is com.ibm.net.ssl.www.protocol.https.r. This runs without any issues.
    I understand that these instances are different due to different URLStreamHandlerFactory instances.
    But I didnt set the factory instance in either of the programs.
    1. Is the exception I get is simply bcoz of instance org.w3c.www.protocol.http.HttpURLConnection?
    2. In that case how can I change the factory instance in j2ee engine?
    Please help.
    Thanks.
    Edited by: Who-Am-I on Nov 28, 2009 7:54 AM

    May be my question is too complex to understand. Let me put it simple.
    After upgrading to NW 7.01 SP5, an existing communication between SAP J2EE engine and a 3rd party software is not working.
    After a lot of debuggin I came to know that its happening at the filter we implemented to route the requests through the 3rd party authentication system.
    At the filter exception is coming from org.w3c.www.protocol.http.HttpURLConnection.getInputStream.
    This instance of HTTPURLConnection given by protocol handler factory(implementation of URLStreamHandlerFactory) which SAP is considering by default. I want to replace this protocol handler with another handler as I see no problems running the same program outside SAP J2EE instance.
    Can we change this protocol handler factory? Where can we change it?

  • Re: Cannot get new URLconnection.getInputStream() in JAVA

    new URLConnection.getInputStream() does not seem to work.
    Background: I am trying to POST the data to an ASP page and reading the response back but it does not seem to work...if I comment this line out it works but does not do what it is intended for.
    Basically I am trying to upload files to the server and am connecting to the URL and writing to its stream....but cannot read the response back..Please help as I have tried everything I could and have read the forums but no LUCK yet

    Yeah yeah that is what I meant ...please excuse me for that ... jst getting slightly pissed off with this problem....see the code below...
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    this is where the error is coming from and the server throws error no 500.
    I have tried posting to the same URL using a Form and it works without any issues....please help

  • URLConnection.getInputStream()  not reading the full HTML

    I need code to read a html file after posting a request. The code is as follows:
    URLConnection connection = url.openConnection();
    connection.setDoInput( true );
    connection.connect();
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    if(in.equals(null)){
    throw new IOException();
    while((inputLine = in.readLine()) != null){
    System.out.println("line is: " + inputLine);
    Sometimes it works fine. Sometimes it can not read full content.(may be the low network). but i view the source in my browser, I can find it just fine.
    Any ideas? Has anyone encountered this kind of problem?

    my code is same for reading input from a servlet, but it sometimes get and inputstream, sometimes, don't, it always can not read the second one. mine code is inside applet and chat with other applet thourgh a servlet. The server side does write message out.
    Any insight how to debug this, I am totally out!!

  • URLConnection.getInputStream and synchronization.

    I can't quite understand why url.getInputStream must by globaly synchronized, if it isn't I will start to receive "connection refused" exceptions
    import java.net.*;
    import java.io.*;
    public class TestURL {
        private final Object lock = new Object();
        public void test() {
            for(int i=0;i<1000;i++) {
                new Thread(new Runnable() {
                    public void run() {
                        try {
                            while(true) {
                               URLConnection url = null;
                               url = new URL("http://localhost:5222").openConnection();
                               InputStream s;
                               synchronized(TestURL.this.lock) {
                                   s = url.getInputStream();
                               while(s.read() != -1) {};                            
                               s.close();
                               System.out.println(Thread.currentThread().hashCode());
                        }catch(Exception e) {
                            e.printStackTrace();
                }).start();
                System.out.println(i);
            while(true);
    }

    moonlighting wrote:
    Hmmm, I don't quite understand your answer could you be more specific ?Without the synchronization you create and start 1000 threads with each one accessing the same URL. Can the server cope with 1000 requests at pretty much the same time?
    With the synchronization, each thread has to acquire a lock on the object referenced by 'TestURL.this.lock' so only one can run at a time. All the other 999 will be suspended until they can acquire the lock.

  • Getting images using URLConnection.getInputStream

    Hi,
    I'm trying to get an image with the following code but the image is garbled. Does anyone know what I'm missing?
    try
    PrintWriter out =response.getWriter();
    String userUrl= "http://freshmeat.net/img/url_changelog.gif"
    int buffer=4096;
    byte[] stream = new byte[buffer];
    int input=0;
    URL url = new URL(userUrl);
    URLConnection conn = url.openConnection();
    String contentType=conn.getHeaderField("Content-Type").toUpperCase();
    if(!contentType.equals("TEXT/HTML"))
    response.setContentType(contentType.toLowerCase());
    BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
    while((input = in.read(stream, 0, buffer)) >=0 )
    out.write(new String(stream).toCharArray());
    in.close();
    in=null;
    out.flush();
    out.close();
    Thanks,
    Ralph

    It's not what you are missing, it's what you have extra. You are converting the stream of bytes to a String. That is what garbles your image. Don't do that. Instead, doOutputStream out = response.getOutputStream();and copy the bytes to it, using basically the same code you are using now.

  • Applet URLConnection.getInputStream() blocks

    There seems to be a bug in Java (#4333920, #4976917) that causes the getInputStream() method to
    block and never return. I've tried many things to solve this. I'm using Java 1.4 to connect to servlet
    running on Tomcat. Does anyone know a solution to this problem?

    Nevermind. I found the problem, which was at the client side I wasn't closing the url connection before opening a new one. After I added the line
    HttpURLConnection con = ...;
    con.disconnect();
    The getInputStream() never blocked.

  • IMAGEIO IS WORKING BUT BYTEARRAY IS NOT WORKING:

    Hi all
    I am getting images from gmail contacts and trying to store it in DB
    using my http code:InputStream is=urlconnection.getInputStream();
    i could able to store the inputstream in file using:
    BufferedImage filebuffer=ImageIO.read(is);
    FileOutputStream fos=new FileOutputStream("picturerecent.jpg");
    ImageIO.write(filebuffer, "jpg", fos);
    but i was trying to store it in DB using the following code but it is not working.i am having a question that
    how it writing to a file without any problem.why not to database:
    try {
           String url = "jdbc:mysql://localhost:3306/";
             String db = "test";
             String driver = "com.mysql.jdbc.Driver";
                    Class.forName(driver);
                    con = DriverManager.getConnection(url+db,"root","");
                    try{
    PreparedStatement psmnt;
         psmnt = con.prepareStatement("insert into gmailphoto(id,Photo) "+ "values(?,?)");
         psmnt.setInt(1, 9);
         psmnt.setObject(2, is, java.sql.Types.BLOB);
         int s = psmnt.executeUpdate();
           Statement st = con.createStatement();
        try{
            ResultSet rs=st.executeQuery("select photo from gmailphoto where id=9");
            if(rs.next())
              {     //byte[] bytearray = new byte[4096];
                  int size=0;
                File sImage;
    //FIRST TRY
                FileWriter wr=new FileWriter(new File("c:\\imageOutput.jpg"));
                IOUtils.copy(rs.getBlob("photo").getBinaryStream(),wr);
                //SECOND TRY
                BufferedImage bf=ImageIO.read(new ByteArrayInputStream(rs.getBytes("photo")));
                FileOutputStream fout=new FileOutputStream(new File("C:\\imageOut"));
                if(bf!=null)ImageIO.write(bf, "jpg", fout);
                if(wr!=null)
                wr.flush();
                wr.close();
              rs.close();
           }}catch(SQLException e){
                System.out.println(e);
           }Thanks a lot for help

    but i was trying to store it in DB using the following codeThere is no code here that writes to a database. There are two lots of code that write to a file.

  • CTD bug in simple video streaming applet.

    I'm trying to write a simple applet to use JMF to allow an end-user to view a video stream that's being served up by VLC. It doesn't have to look immensely pretty (in fact, streamlined is what I want most). I swiped some code from the jicyshout project (http://jicyshout.sourceforge.net) which handles streaming MP3s, and borrowed a framework for an applet from one of Sun's example applets for the JMF.
    Here's my code so far:
    ** begin file SimpleVideoDataSource.java **
    import java.lang.String;
    import java.net.*;
    import java.io.*;
    import java.util.Properties;
    import javax.media.*;
    import javax.media.protocol.*;
    /* The SeekableStream and DataSource tweaks are based on the code from
    * jicyshout (jicyshout.sourcefourge.net), which was written by Chris Adamson.
    * The code was simplified (no need for mp3 metadata here), cleaned up, then
    * extended for our puposes.
    * This is a DataSource using a SeekableStream suitable for
    * streaming video using the default parser supplied by JMF.
    public class SimpleVideoDataSource extends PullDataSource {
    protected MediaLocator myML;
    protected SeekableInputStream[] seekStreams;
    protected URLConnection urlConnection;
    // Constructor (trivial).
    public SimpleVideoDataSource (MediaLocator ml) throws MalformedURLException {
    super ();
    myML = ml;
    URL url = ml.getURL();
    public void connect () throws IOException {
    try {
    URL url = myML.getURL();
    urlConnection = url.openConnection();
    // Make the stream seekable, so that the JMF parser can try to parse it (instead
    // of throwing up).
    InputStream videoStream = urlConnection.getInputStream();
    seekStreams = new SeekableInputStream[1];
    seekStreams[0] = new SeekableInputStream(videoStream);
    } catch (MalformedURLException murle) {
    throw new IOException ("Malformed URL: " + murle.getMessage());
    } catch (ArrayIndexOutOfBoundsException aioobe) {
    fatalError("Array Index OOB: " + aioobe);
    // Closes up InputStream.
    public void disconnect () {
    try {
    seekStreams[0].close();
    } catch (IOException ioe) {
    System.out.println ("Can't close stream. Ew?");
    ioe.printStackTrace();
    // Returns just what it says.
    public String getContentType () {
    return "video.mpeg";
    // Does nothing, since this is a stream pulled from PullSourceStream.
    public void start () {
    // Ditto.
    public void stop () {
    // Returns a one-member array with the SeekableInputStream.
    public PullSourceStream[] getStreams () {
    try {
    // **** This seems to be the problem. ****
    if (seekStreams != null) {
    return seekStreams;
    } else {
    fatalError("sourceStreams was null! Bad kitty!");
    return seekStreams;
    } catch (Exception e) {
    fatalError("Error in getStreams(): " + e);
    return seekStreams;
    // Duration abstract stuff. Since this is a theoretically endless stream...
    public Time getDuration () {
    return DataSource.DURATION_UNBOUNDED;
    // Controls abstract stuff. No controls supported here!
    public Object getControl (String controlName) {
    return null;
    public Object[] getControls () {
    return null;
    void fatalError (String deathKnell) {
    System.err.println(":[ Fatal Error ]: - " + deathKnell);
    throw new Error(deathKnell);
    ** end file SimpleVideoDataSource.java **
    ** begin file SeekableInputStream.java **
    import java.lang.String;
    import java.net.*;
    import java.io.*;
    import java.util.Properties;
    import javax.media.*;
    import javax.media.protocol.*;
    /* The SeekableStream and DataSource tweaks are based on the code from
    * jicyshout (jicyshout.sourcefourge.net), which was written by Chris Adamson.
    * The code was simplified (no need for mp3 metadata here), cleaned up, then
    * extended for our puposes.
    /* This is an implementation of a SeekableStream which extends a
    * BufferedInputStream to basically fake JMF into thinking that
    * the stream is seekable, when in fact it's not. Basically, this
    * will keep JMF from puking over something it expects but can't
    * actually get.
    public class SeekableInputStream extends BufferedInputStream implements PullSourceStream, Seekable {
    protected int tellPoint;
    public final static int MAX_MARK = 131072; // Give JMF 128k of data to "play" with.
    protected ContentDescriptor unknownCD;
    // Constructor. Effectively trivial.
    public SeekableInputStream (InputStream in) {
    super (in, MAX_MARK);
    tellPoint = 0;
    mark (MAX_MARK);
    unknownCD = new ContentDescriptor ("unknown");
    // Specified size constructor.
    public SeekableInputStream (InputStream in, int size) {
    super (in, Math.max(size, MAX_MARK));
    tellPoint = 0;
    mark(Math.max(size, MAX_MARK));
    unknownCD = new ContentDescriptor ("unknown");
    // Reads a byte and increments tellPoint.
    public int read () throws IOException {
    int readByte = super.read();
    tellPoint++;
    return readByte;
    // Reads bytes (specified by PullSourceStream).
    public int read (byte[] buf, int off, int len) throws IOException {
    int bytesRead = super.read (buf, off, len);
    tellPoint += bytesRead;
    return bytesRead;
    public int read (byte[] buf) throws IOException {
    int bytesRead = super.read (buf);
    tellPoint += bytesRead;
    return bytesRead;
    // Returns true if in.available() <= 0 (that is, if there are no bytes to
    // read without blocking or end-of-stream).
    public boolean willReadBlock () {
    try {
    return (in.available() <= 0);
    } catch (IOException ioe) {
    // Stick a fork in it...
    return true;
    // Resets the tellPoint to 0 (meaningless after you've read one buffer length).
    public void reset () throws IOException {
    super.reset();
    tellPoint = 0;
    // Skips bytes as expected.
    public long skip (long n) throws IOException {
    long skipped = super.skip(n);
    tellPoint += skipped;
    return skipped;
    // Trivial.
    public void mark (int readLimit) {
    super.mark (readLimit);
    // Returns the "unknown" ContentDescriptor.
    public ContentDescriptor getContentDescriptor () {
    return unknownCD;
    // Lengths? We don't need no stinkin' lengths!
    public long getContentLength () {
    return SourceStream.LENGTH_UNKNOWN;
    // Theoretically, this is always false.
    public boolean endOfStream () {
    return false;
    // We don't provide any controls, either.
    public Object getControl (String controlName) {
    return null;
    public Object[] getControls () {
    return null;
    // Not really... but...
    public boolean isRandomAccess () {
    return true;
    // This only works for the first bits of the stream, while JMF is attempting
    // to figure out what the stream is. If it tries to seek after that, bad
    // things are going to happen (invalid-mark exception).
    public long seek (long where) {
    try {
    reset();
    mark(MAX_MARK);
    skip(where);
    } catch (IOException ioe) {
    ioe.printStackTrace();
    return tell();
    // Tells where in the stream we are, adjusted for seeks, resets, skips, etc.
    public long tell () {
    return tellPoint;
    void fatalError (String deathKnell) {
    System.err.println(":[ Fatal Error ]: - " + deathKnell);
    throw new Error(deathKnell);
    ** end file SeekableInputStream.java **
    ** begin file StreamingViewerApplet.java **
    * This Java Applet will take a streaming video passed to it via the applet
    * command in the embedded object and attempt to play it. No fuss, no muss.
    * Based on the SimplePlayerApplet from Sun, and uses a modified version of
    * jicyshout's (jicyshout.sourceforge.net) tweaks to get JMF to play streams.
    * Use it like this:
    * <!-- Sample HTML
    * <APPLET CODE="StreamingViewerApplet.class" WIDTH="320" HEIGHT="240">
    * <PARAM NAME="code" VALUE="StreamingViewerApplet.class">
    * <PARAM NAME="type" VALUE="application/x-java-applet;version=1.1">
    * <PARAM NAME="streamwidth" VALUE="width (defaults to 320, but will resize as per video size)">
    * <PARAM NAME="streamheight" VALUE="height (defaults to 240, but will resize as per video size)">
    * <PARAM NAME="stream" VALUE="insert://your.stream.address.and:port/here/">
    * </APPLET>
    * -->
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.String;
    import java.lang.ArrayIndexOutOfBoundsException;
    import java.net.URL;
    import java.net.MalformedURLException;
    import java.net.*;
    import java.io.*;
    import java.io.IOException;
    import java.util.Properties;
    import javax.media.*;
    import javax.media.protocol.*;
    public class StreamingViewerApplet extends Applet implements ControllerListener {
    Player player = null;
    Component visualComponent = null;
    SimpleVideoDataSource dataSource;
    URL url;
    MediaLocator ml;
    Panel panel = null;
    int width = 0;
    static int DEFAULT_VIDEO_WIDTH = 320;
    int height = 0;
    static int DEFAULT_VIDEO_HEIGHT = 240;
    String readParameter = null;
    // Initialize applet, read parameters, create media player.
    public void init () {
    try {
    setLayout(null);
    setBackground(Color.white);
    panel = new Panel();
    panel.setLayout(null);
    add(panel);
    // Attempt to read width from applet parameters. If not given, use default.
    if ((readParameter = getParameter("streamwidth")) == null) {
    width = DEFAULT_VIDEO_WIDTH;
    } else {
    width = Integer.parseInt(readParameter);
    // Ditto for height.
    if ((readParameter = getParameter("streamheight")) == null) {
    height = DEFAULT_VIDEO_HEIGHT;
    } else {
    height = Integer.parseInt(readParameter);
    panel.setBounds(0, 0, width, height);
    // Unfortunately, this we can't default.
    if ((readParameter = getParameter("stream")) == null) {
    fatalError("You must provide a stream parameter!");
    try {
    url = new URL(readParameter);
    ml = new MediaLocator(url);
    dataSource = new SimpleVideoDataSource(ml);
    } catch (MalformedURLException murle) {
    fatalError("Malformed URL Exception: " + murle);
    try {
    dataSource.connect();
    player = Manager.createPlayer(dataSource);
    } catch (IOException ioe) {
    fatalError("IO Exception: " + ioe);
    } catch (NoPlayerException npe) {
    fatalError("No Player Exception: " + npe);
    if (player != null) {
    player.addControllerListener(this);
    } else {
    fatalError("Failed to init() player!");
    } catch (Exception e) {
    fatalError("Error opening player. Details: " + e);
    // Start stream playback. This function is called the
    // first time that the applet runs, and every time the user
    // re-enters the page.
    public void start () {
    try {
    if (player != null) {
    player.realize();
    while (player.getState() != Controller.Realized) {
    Thread.sleep(100);
    // Crashes... here?
    player.start();
    } catch (Exception e) {
    fatalError("Exception thrown: " + e);
    public void stop () {
    if (player != null) {
    player.stop();
    player.deallocate();
    } else {
    fatalError("stop() called on a null player!");
    public void destroy () {
    // player.close();
    // This controllerUpdate function is defined to implement a ControllerListener
    // interface. It will be called whenever there is a media event.
    public synchronized void controllerUpdate(ControllerEvent event) {
    // If the player is dead, just leave.
    if (player == null)
    return;
    // When the player is Realized, get the visual component and add it to the Applet.
    if (event instanceof RealizeCompleteEvent) {
    if (visualComponent == null) {
    if ((visualComponent = player.getVisualComponent()) != null) {
    panel.add(visualComponent);
    Dimension videoSize = visualComponent.getPreferredSize();
    width = videoSize.width;
    height = videoSize.height;
    visualComponent.setBounds(0, 0, width, height);
    } else if (event instanceof CachingControlEvent) {
    // With streaming, this doesn't really matter much, does it?
    // Without, a progress bar of some sort would be appropriate.
    } else if (event instanceof EndOfMediaEvent) {
    // We should never see this... but...
    player.stop();
    fatalError("EndOfMediaEvent reached for streaming media. ewe ewe tea eff?");
    } else if (event instanceof ControllerErrorEvent) {
    player = null;
    fatalError(((ControllerErrorEvent)event).getMessage());
    } else if (event instanceof ControllerClosedEvent) {
    panel.removeAll();
    void fatalError (String deathKnell) {
    System.err.println(":[ Fatal Error ]: - " + deathKnell);
    throw new Error(deathKnell);
    ** end file StreamingViewerApplet.java **
    Now, I'm still new to the JMF, so this might be obvious to some of you... but it's exploding on me, and crashing to desktop (both in IE and Firefox) with some very fun errors:
    # An unexpected error has been detected by HotSpot Virtual Machine:
    # EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x21217921, pid=3200, tid=3160
    # Java VM: Java HotSpot(TM) Client VM (1.5.0_06-b05 mixed mode, sharing)
    # Problematic frame:
    # C 0x21217921
    --------------- T H R E A D ---------------
    Current thread (0x058f7280): JavaThread "JMF thread: com.sun.media.amovie.AMController@506411[ com.sun.media.amovie.AMController@506411 ] ( realizeThread)" [_thread_in_native, id=3160]
    siginfo: ExceptionCode=0xc0000005, writing address 0x034e6360
    (plenty more here, I can post the rest if necessary)
    The problem seems to be coming from the "return seekStreams" statement in the first file; when I have execution aborted before that (with a fatalError call), it doesn't crash.
    Any tips/hints/suggestions?

    You should write your own Applet, where you can easily get the visual component (getVisualComponent())and show it directly in your Applet (you call it "embedded"). As far as I know, all examples (AVReceive* etc.) use the component which opens a new window.
    Best regards from Germany,
    r.v.

  • Sending a file from Applet to servlet HELP me Please

    Sorry, i have the problem this is my code Applet & Servlet but it seems working asynchronously if you have some ideas please reply me i send bytes on outputstream but the inputstream of servlet receive nothing bytes but write my system.out.print on screen server:
    Applet:
    URL servletURL = new URL(codebase, "/InviaFile/servlet/Ricevi");
    HttpURLConnection urlConnection = (HttpURLConnection) servletURL.openConnection();
    urlConnection.setRequestMethod("POST");
    urlConnection.setUseCaches(false);
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);
    urlConnection.setAllowUserInteraction(false);
    urlConnection.setRequestProperty("Content-Type", "application/octet-stream");
    urlConnection.setRequestProperty("Content-length", String.valueOf(100));
    urlConnection.connect();
    if(urlConnection.HTTP_BAD_REQUEST == HttpURLConnection.HTTP_BAD_REQUEST){
    /*System.out.println("Cattiva Richiesta: "+urlConnection.getContentEncoding());
    System.out.println("Tipo di metodo: "+urlConnection.getRequestMethod());
    System.out.println("Tipo di Risposta: "+urlConnection.getResponseCode());
    System.out.println("Tipo di messaggio: "+urlConnection.getResponseMessage());
    System.out.println("Tipo di contenuto: "+urlConnection.getContentType());
    System.out.println("Tipo di lunghezza contenuto: "+urlConnection.getContentLength());
    System.out.println("Tipo di doinput: "+urlConnection.getDoInput());
    System.out.println("Tipo di doouput: "+urlConnection.getDoOutput());
    System.out.println("Tipo di URL: "+urlConnection.getURL());
    System.out.println("Tipo di propriet� richiesta: "+urlConnection.getRequestProperty("Content-Type"));
    System.out.println("Entra if");
    DataOutputStream dout = new DataOutputStream(urlConnection.getOutputStream());
    InputStream is = urlConnection.getInputStream();
    if(ritornaFile("C:/Ms.tif", dout))System.out.println("Finita lettura");
    dout.close();
    urlConnection.disconnect();
    System.out.println("Fine Applet");
    }catch(Exception e) { System.err.println(e.getMessage());e.printStackTrace();}
    public boolean ritornaFile(String file, OutputStream ots)throws Exception{
    FileInputStream f = null;
    try{
    f = new FileInputStream(file);
    byte[] buf = new byte[4 * 1024];
    int byteLetti;
    while((byteLetti = f.read()) != -1){ots.writeByte(buf, 0, byteLetti);ots.flush();
    while((byteLetti = f.read()) != -1){ots.write(byteLetti);ots.flush();
    System.out.println("byteLetti= "+byteLetti);
    return true;
    }catch(Exception ex){
    System.err.println(ex.getMessage());
    return false;
    }finally{
    if(f != null)f.close();
    Servlet:
    HttpSession ses = request.getSession(true);
    System.out.println("Passa servlet "+request.getMethod());
    System.out.println("Passa servlet "+ses.getId());
    ServletInputStream servletinputstream = request.getInputStream();
    DataInputStream dis = new DataInputStream(request.getInputStream());
    int c = dis.available();
    System.out.println("c="+c);
    //ServletOutputStream servletoutputstream
    //response.getOutputStream();
    response.setContentType("application/octet-stream");
    System.out.println("URI= "+request.getRequestURI());
    System.out.println("pathTranslated: "+request.getPathTranslated());
    System.out.println("RemoteUser: "+request.getRemoteUser());
    System.out.println("UserInRole: "+String.valueOf(request.isUserInRole("")));
    System.out.println("pathInfo: "+request.getPathInfo());
    System.out.println("Protocollo: "+request.getProtocol());
    System.out.println("RemoteAddr:"+request.getRemoteAddr());
    System.out.println("RemoteHost:"+request.getRemoteHost());
    System.out.println("SessionID:"+request.getRequestedSessionId());
    System.out.println("Schema:"+request.getScheme());
    System.out.println("SeesionValido:"+String.valueOf(request.isRequestedSessionIdValid()));
    System.out.println("FromURL:"+String.valueOf(request.isRequestedSessionIdFromURL()));
    int i = request.getContentLength();
    System.out.println("i: "+i);
    ritornaFile(servletinputstream, "C:"+File.separator+"Pluto.tif");
    System.out.println("GetMimeType= "+getServletContext().getMimeType("Ms.tif"));
    InputStream is = request.getInputStream();
    int in = is.available();
    System.out.println("Legge dallo stream in="+in);
    DataInputStream diss = new DataInputStream(servletinputstream);
    int ins = diss.read();
    System.out.println("Legge dallo stream ins="+ins);
    int disins = diss.available();
    System.out.println("Legge dallo stream disins="+disins);
    is.close();
    System.out.println("Fine Servlet");
    catch(Exception exception) {
    System.out.println("IOException occured in the Server: " + exception.getMessage());exception.printStackTrace();
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    processRequest(request, response);
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    processRequest(request, response);
    /** Returns a short description of the servlet.
    public String getServletInfo() {
    return "Short description";
    public void ritornaFile(InputStream its, String fileDest )throws Exception{
    FileOutputStream f = null;
    try{
    f = new FileOutputStream(fileDest);
    byte[] buf = new byte[2 * 1024];
    int byteLetti;
    while((byteLetti = its.read()) != -1){
    f.write(buf, 0, byteLetti);
    f.flush();
    System.out.println("Byteletti="+byteLetti);
    }catch(Exception ex){
    System.err.println(ex.getMessage());
    }finally{
    if(f != null)f.close();

    Hi all,
    Can anyone help me.I am trying to send an audio file from a applet to servlet with HTTP method(no raw sockets), also the servlet shld be able to save the file on the server.Any suggestions welcome.USing audiostream class from javax.sound.sampled.
    The part of applet code which calls servlet is :
    URL url = new URL("http://" + host + "/" + context + "/servlet/UserUpdateWorkLogAudio?userid=" + userId.replace(' ', '+') + "&FileName=" + filename.replace(' ', '+'));
    URLConnection myConnection = url.openConnection();
    myConnection.setUseCaches(false);
    myConnection.setDoOutput(true);
    urlConnection.setRequestProperty("Content-Type", "application/octet-stream");
    myConnection.connect();
    out = new BufferedOutputStream(myConnection.getOutputStream());
    AudioSystem.write(audioInputStream, fileType,out); // IS THIS RIGHT APPROACH?
    ************************end of applet code**********************
    ************************servlet code******************************
    try
    {BufferedInputStream in = new BufferedInputStream(request.getInputStream());
    ????????What code shld i write here to get the audio file stream
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filename));
    *********************************************end***********************
    Thanks
    Joe.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Parse method hangs

    I am trying to to parse a file using DocumentBuilder. The parse() method hangs for no reason. There are no errors or exceptions thrown. I even used a StringReader but in vain. Pl see code below:
    The file is read correctly and i could even print the XML string out.
    System.out.println("Parsing XML file from performParsing():" +s);
              Document doc = null;
              DocumentBuilderFactory factory = null;
              DocumentBuilder builder = null;
              try{
                   factory = DocumentBuilderFactory.newInstance();
                   System.out.println("Parsing XML factory:" +factory);
                   builder = factory.newDocumentBuilder();
                   System.out.println("Parsing XML builder:" +builder);
                   URL url = new URL(s);
                   URLConnection urlConnection = url.openConnection();
                   InputStream in = urlConnection.getInputStream();
                   String XMLStr = getStringReaderFromFile(in); //private method that gives a string
                   StringReader stReader = new StringReader(XMLStr);
                   InputSource ins = new InputSource(stReader);
         doc = builder.parse(ins);--->IT HANGS HERE

    Not an expert on this but presumably you have the properties set up correctly.
    From javadoc ...
    DocumentBuilderFactory uses the system property javax.xml.parsers.XmlDocumentParserFactory to find the class to load. So you can change the parser by calling:
    System.setProperty("javax.xml.parsers.XmlDocumentParserFactory",
    "com.foo.myFactory");

  • Getting .php files(output)with java

    i'm trying to get he contenty of a php file,
    but i don't receive anything with .html files it works great kan someone help me, please
    import java.io.*;
    import java.net.*;
    import java.util.Date;
    class URLConnecties
        public static void main(String args[]) throws Exception
            int teken;
            URL url = new URL("http://www.gamer.mineurwar.nl/net/javachallenge.php?command=DaTe");
            URLConnection urlconnection = url.openConnection();
            System.out.println("Type inhoud: " +
                urlconnection.getContentType());
            System.out.println("Datum document: " +
                new Date(urlconnection.getDate()));
            System.out.println("Laatst gewijzigd: " +
                new Date(urlconnection.getLastModified()));
            System.out.println("Document vervalt: " +
                urlconnection.getExpiration());
            int lengteinhoud = urlconnection.getContentLength();
            System.out.println("Lengte inhoud: " + lengteinhoud);
            if (lengteinhoud > 0) {
                InputStream in = urlconnection.getInputStream();
                while ((teken = in.read()) != -1) {
                    System.out.print((char) teken);
                in.close();
    }

    but i don't receive anything with .html files it works great kan someone help me, pleaseWhat's that mean? Either you need to call:
    URLConnection urlconnection = url.openConnection();
    urlconnection.connect();
    Or you mean you aren't getting things like the images in the file... Well, of course, cuz there are no images in an HTML file. Only links to images, which a browser would parse out of the HTML and make another connection to the server to get. So you'd have to do the same thing. URLConnection is not a browser, it doesn't parse HTML.

Maybe you are looking for

  • Error while building code in Weblogic Integration 9.2 MP3

    Hi, I upgarded my code from Weblogic 8.1 sp4 to 9.2 MP3 directly. Weblogic 9.2 MP3 automatically converts all the .jpd, .jcx files to .java extensions. While building the code in Workshop,I got the following error: Interfaces such as com.x.y.z cannot

  • Tired of apps freezing and banging on the screen like a gorilla trying to get a response

    When will there be an update that actually improves the ios so that you can actually hit a link in safari without zooming in and so that the email quits freezing and has to be swiped away and restarted to work or when that won't even work and the dev

  • MobileMe emails all show as unread

    Heya Guys, Since upgrading to MobileMe emails don't seem to be functioning for me as IMAP should. When I read an email on my Mac they still are flagged as a new message on the iPhone - same thing when done the opposite way around. It all worked fine

  • Which adapter?

    Hi I need to buy an adapter for my new Acer monitor which has a VGA cable supplied. So I would need a DVI-D male to VGA female adapter, right? Thanks. David

  • PHOTO GADGETS

    Wondering why when you choose 8x10 Photo to print on an 8.5x11 paper its not 8x10. Also wondering why it does not have an 8x10 borderless setting. Using 7410 all in one HP printer and Windows 7 Any one have this same problem?