HttpServer not dispatching (or receiving?) Ajax requests - Help needed

Hello,
I have run into a strange problem. Strange because the combination of com.sun.net.httpserver.HttpServer with Internet Explorer works whereas the combination of com.sun.net.HttpServer with Firefox and Opera doesn't work!
To illustrate I have written a small Java program that implements a HttpHandler that I want to serve Ajax requests that are fired from Javascript. I use the prototype.js Javascript library to send the Ajax requests.
The webpage fires a Ajax request every second. The HttpHandler responds with a <script> block that calls the paint() function on the webpage.
This works fine on Internet Explorer 6, but Firefox and Opera don't get an answer on the Ajax requests that the Javascript sends. Even more, the request doesn't event make it to the MyHandler.handle() method. How can I test whether the request even makes it to the HttpServer object, and if it reaches the HttpServer object, then why isn't it dispatched to my HttpHandler?
I hope I made myself clear and that someone can point out to me what I am doing wrong or what the code that I wrote is lacking to make it work with Firefox and Opera.
Thanks a whole lot in advance!
Here is the code:
File TestHttpServerWithPrototypeJS.html (run it on IIS or Apache or whatever)
<html>
     <head>
          <title>Test HttpServer with prototype.js</title>
          <script type="text/javascript" src="http://localhost/prototype.js"></script>
          <script>
               function uncache(url)
                    return url + '?time=' + (new Date()).getTime();
               function initialize()
                    try
                         // Make a HTTP request every second to /myapp and update the mydiv1 element.
                         // What is written into the mydiv1 is a <script> section that calls the paint function.
                         // The paint function then updates the mydiv2 element with a counter value that
                         // is incremented by the server code after each http (ajax) request.
                         var myAjax = new Ajax.PeriodicalUpdater(
                                        'mydiv1',
                                        uncache('http://localhost:8000/myapp'),
                                             method: 'post',
                                             asynchronous: true,
                                             frequency: 1,
                                             evalScripts: true
                    catch(e)
                         alert('Exception: ' + e);
               function paint(data)
                    $(mydiv2).innerHTML = data;
               window.onload = initialize;
          </script>
     </head>
     <body>
          <div id='mydiv1'></div>
          <div id='mydiv2'></div>
     </body>
</html>
File TestHttpServer.java:
import java.io.IOException;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpServer;
public class TestHttpServer
public static void main(String[] args)
     HttpServer server = null;
          try
               server = HttpServer.create(new InetSocketAddress(8000), 100);
          catch (IOException e)
               // TODO Auto-generated catch block
               e.printStackTrace();
     server.createContext("/myapp", new MyHandler());
     server.setExecutor(null); // creates a default executor
     server.start();
File MyHandler.java:
import java.io.IOException;
import java.io.OutputStream;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
class MyHandler implements HttpHandler
     int counter = 0;
     public void handle(HttpExchange t) throws IOException
          try
               String response = "<script type=\"text/javascript\">paint('server side counter = "+ counter + "')</script>";
               counter++;
               t.sendResponseHeaders(200, response.length());
               OutputStream os = t.getResponseBody();
               os.write(response.getBytes());
               os.close();
          catch (Exception e)
               int a_variable_on_which_a_breakpoint_can_be_set = 0;
}

Hi there,
I had run into the same problem, it wouldn't work with Opera, worked but not very well with IE7 and Safari, and on Firefox seemed to work fine. I was able to solve this problem by making sure there was always a result code greater than zero when writing the respose headers. I am now running my application on all major browsers and have no problems at all. The application makes heavy use of ajax as well.
Summing up:
- before writing the response, make sure to write the headers and make sure the result code is greater than zero. I use a response length of 0 when writing the headers as I ran into a bit of trouble when using responses of specific length.
- write the response then make sure to close the connection.

Similar Messages

  • User anonymous does not have permission to perform lookup : help needed

    Hi All,
    I'm facing a strange problem.
    I'm using weblogic 8.1
    Some ejbs are deployed in the application and security settings are done properly.
    But sometimes, i get an exception saying that
    'javax.naming.NoPermissionException: User <anonymous> does not have permission on weblogic to perform lookup operation. [Root exception is javax.naming.NoPermissionException: User <anonymous> does not have permission on weblogic to perform lookup operation.]
    at weblogic.rjvm.BasicOutboundRequest.sendReceive(BasicOutboundRequest.java:108)' .
    This ejb is invoked from a web application, and the exception happens only once in the server lifecycle (but not on the first try).
    This happens in a JTA transaction and eventually the transaction gets timed out. Once timed out for the first time, further requests are executing fine and it is connecting with the configured security credentials.
    Initially i thought ejb caching was causing the problem. But even after removing the cache, it is throwing the exception.
    Only sometimes, it is trying to connect as <anonymous> user.
    I'm so fed up with this..
    Can anybody help me out..?

    Which 8.1 SP are you on? If you open a support case, a support engineer may be able to identify a fix that has been included in a newer Service Pack.

  • WRT54G Not Supported By LELA...help needed

    Alright, roughly 2 days ago I hooked up this router (WRT54G) to the computer, and then later that day hooked up a laptop by wireless signal.  These first couple of days were fine, but last night while on my laptop searching the web, I began to lose a signal every few minutes for roughly 30-45 seconds.  After becoming annoyed, I went to check out my network by using LELA.  However, instead of the screen I expected (showing your network diagram), I was told that I was using a new router.
    Obviously, I hadn't changed the router so I was confused and decided to update, which was the option it gave me and because cancelling out wasn't possible.  However, it didn't work.  After going through the setup, which was essentially just like the original setup for the router, I got to the last step and it said the LELA didn't support the router, as though I was using one from another computer or something.
    My dad said he had installed an Internet Explorer update and it had prompt him to change settings, and he had, but nothing that he thought would affect it.  Also, I did a system restore to a point just shortly after it was originally installed, and at a time I knew it had been working, but alas that didn't work either.
    I've searched on google and all over these forums for some help, but I've found nothing that gives me good answers.  I saw somewhere to roll back my firmware, but I don't know how, as it won't let me connect to the internet through the router, and if I unplug the router and bypass the router for my internet then I can access the web, but obviously not the router.  I'm stumped, and wondering if maybe all I need to do is a power cycle or roll back my firmware.  Please, answers would be helpful.  Thank you
    EDIT:  Also, I'm not sure where to find what version I have or what firmware I have.  I just know my model number, and that I can get to my settings by typing in the IP of the router in IE address bar.  I had enough knowledge to get it going, but its been very frustrating in fixing the problems.
    Message Edited by stangman on 12-31-2007 07:52 AM
    Message Edited by stangman on 12-31-2007 08:06 AM

    Oh, and a couple more things.  Why did a system restore not work, shouldn't this technical reset the system back to a time when it was working?  Or, does firmware not change?  I suppose, I'm kind of a newb to the whole router thing, and to be really honest, we just barely changed to high speed internet the day before I bought the router.  The high speed modem was professionally installed.  I know for a fact I had it hooked up right, I mean it didnt seem too confusing and plus it was working great for a short time.  Thanks.
    EDIT:  You know, now that I've done so much searching for answers, I've found that lots of people are having this problem, but yet, I'm having a hard time finding answers.  So you would think Linksys might fix this problem in a firmware update, and yet the only valid solution I have found is to go back to the previous firmware.  Yet, I don't know how to do that, besides I'm at school right now, so yeah thank you for the help in advance.
    Message Edited by stangman on 12-31-2007 10:29 AM

  • HT4623 i have iphone 3 but with not update to the lastest ios help needed

    got iphone 3 but not updated so i cant also get imessage help me anyone

    There are some texting apps which are compatible with the iPhone 3G. I don't use texting myself, but one compatible app that people have recommended is Text Free:
    https://itunes.apple.com/us/app/text-free-real-phone-number/id470580739?mt=8

  • My Newly bought Blackberry Classic left side speaker is not working.... Help needed...!!!!!

    Dear All,
    Please kindly help me on this, I am from Pakistan and I got my Blackberry Classic delieved to me from USA my cousin bought it from online blackberry store and brought it by hand. Just now i have noticed that my blackberry classic left side speaker is not working only ringing sound music sound and loudspeaker sounds are coming from the right side of the speaker.
    Has anyone faced this problem with his new classic and what should i do?
    Please help or guide me
    Solved!
    Go to Solution.

    Knowing this that classic comes up with only one speaker did broke my heart  But to be honest the sound is excellent even at high volume the sound does not distort. its a genuien stereo speaker

  • RECEIVER FILE FCC - Help needed.

    Hi,
    Iam working on a idoc-to-file interface.My receiver structure is as follows:
    <HEADER_1st_LINE>
          <field1>
         <field2>
       <field n>
    </ HEADER_1st_LINE>
    <HEADER_2nd_LINE>
          <field1>
         <field2>
       <field n>
    </ HEADER_2nd_LINE>
    <PO_LINE>
      <POLINE_1st_LINE>
          <field1>
         <field2>
       <field n>
    < /POLINE_1st_LINE>
    <POLine_2ndLine>
       <field1>
         <field2>
       <field n>
    </ POLINE_2nd_LINE>
    </PO_LINE>
    My FILE RECEIVER channel is as follows:
    RECORDSET STRUCTURE : HEADER_1stLINE,HEADER_2ndLINE,POLINE,POLINE_1stLINE,POLINE_2ndLINE
    Kindly pls help me in content conversion parameters.My target structure should be as follows:
    HEADER_1st_LINE
    HEADER_2nd_LINE
    POLINE_1st_LINE
    POLINE_2nd_LINE
    POLINE_1st_LINE
    POLINE_2nd_LINE
    POLINE_1st_LINE
    POLINE_2nd_LINE
    Thanks in advance,
    Cheers,
    Ram.

    Hi Kenneth,
    Thanks for your reply.
    PO_LINE has two child nodes...POLINE_1st_LINE & POLINE_2nd_LINE respectively.
    In the target flat file i must generate the structure which has the following nodes in sequence :
    HEADER_1st_LINE
    HEADER_2nd_LINE
    POLINE_1st_LINE
    POLINE_2nd_LINE
    POLINE_1st_LINE
    POLINE_2nd_LINE
    POLINE_1st_LINE
    POLINE_2nd_LINE
    How to write Content Conversion Parameters so as to achieve my task of generating the desired file structure ?
    Cheers,
    Ram.

  • Moving Clips - and how not to lose the audio? Help needed!

    Hi,
    I have used Premiere Pro 6.0 quite extensively over the years and have recently moved to Premiere Pro CS5.
    With Premiere Pro 6.0 I could move/drag clips on the time-line and their linked audio would move with them.  If I moved the video clip to another video track, say, above an existing clip, the audio would also move to a free audio track and not automically write over any existing audio.  This would allow me to easily reorder clips on the timeline by simply moving them around and using other video tracks as temporary storage locations... and not lose or write over any other existing audio.
    However in Premiere Pro CS5 if I do the same thing, the video will move to the other video track I move it to, but the audio will stay in the say audio track and will write-over any existing audio when the mouse button is released.  The only way around this I can find in the manual is to: (1) drag the video to the other video track, and (2) press and hold the <SHIFT> key, whilst, (3) draging the linked audio to another audio track to avoid existing audio from being over-written.
    My question:  Is there a configuation I can set in CS5 to allow moving/draging of clips to work like in Premiere Pro 6.0?  I have already messed up multiple times in CS5 by inadvertently over-writing existing audio.
    Your expert advice and recommendations would be greatly appreciated.
    THANKS IN ADVANCE.

    Harm,
    Your reply is not helpful.  Just so you know, I have read through the manual extensively and could not find an answer for my question.  AND that's why I brought my question here.
    Perhaps I missed something in the manual.  Would you mind re-reading my question and helping me if it is so easy?!
    This has been frustrating for me for the last three months and I thought I would come to this forum for some expert advice.  So far I have been told that CS5 is designed to be like this (does not answer my question), and now you tell me to look up the manual (again does not answer my question).
    I'm amazed by responses that miss the question entirely and give helpful suggestions like that!

  • Menu Button not working at all..Please help needed urgently for deadline.

    I have used all the suggestions I can find in the forum. Nothing is working.
    I am trying to draw button rectangle on a still background for a menu. Draging the pointer doesn't do anything. I have tried to import a tutorial with menu and buttons within it. When loading the project assets the import stops at "Loading menu" and does not proceed.
    I am using suitcase fusion for a font manager.I have reinstalled the DSP a few times without any success.
    I have spent three nights trying to solvge the problem and I am running out of time for the project delivery help is need urgently

    Your key is the "suitcase fusion for a font manager" line.
    There is a bug where you won't be able to create a button if you have a bad font, or a duplicate font, installed.
    First try shutting off all of the fonts you have open with Suitcase, and see if that helps. If so, open one suitcase at a time until you figure out which font is the culprit.
    If shutting off all but the basic System fonts does not help, you might have to reinstall your system, or somehow update your core System fonts. I don't know how to do that, but there was a recent article at http://www.tidbits.com/ that discussed fonts and their maintenance. But ultimately it's a font problem.

  • Download helper no longer works - icon is there but it does not recognise flv video on any site - not a PC guru so easy help needed !!!!

    I have only just started to use Firefox as I got very tired of IE. I watch a lot of flash/flv videos on many different sites and sometimes like to download some of these (which I could do on IE but couldn't here). I downloaded the add on "download helper" which was great and worked really well and easily but all of a sudden it now no longer works (the icon is still there but it won't recognise any type of video form any site at all - and I have no idea at all how to repair/fix it.
    I am not a PC expert or guru so any kind of easy step by step help will be greatly appreciated (I don't want to have to go back to the horrible IE please!!!!!)

    Does it work in the latest Release version - Firefox 31?
    ''Firefox 32 is currently a Beta version; not all add-ons are compatible with pre-release Beta versions of Firefox.''

  • Not a valid Photoshop document (urgent help needed))

    I am using Photoshop CS5. Suddenly I am not able to open any of my .psd documents. I get a box that tells me "This is not a valid Phoroshop document." I don't know what has happened.
    Is my application corrupt? Should I reinstall it?
    Is the problem with the preferences file? Should I delete it? If so, how do I do that?
    I am a web designer and now I cannot access my files and work on them. This is a really desperate situation!! I appreciate any insights someone can give me!
    Thank you.

    Thank you for your response. I did find the keyboard shortcut and that was so easy. Why can't Adobe tell that? By the way, I am ready to give up on my Mac. I have 10 library folders and every day a new one pops up - I have no idea where all this stuff comes from to cause my computer to be so unorganized and the folks at my user group don't seem to understand why I am so frustrated. I am ready to buy a new PC. And none of these library folders have a preference file for Photoshop.
    Well, that is all I have for this discussion and thank you for letting me vent (as if you even wanted me to!).

  • Server will not boot after update !! Help needed fast !!

    I have a new (Aug 2005) XServe G5, running 4.3.
    Active Directory integrated, stores home folders (AFP), manages preferences and 5 print queues for 55 Mac OS X.4.3 clients and 200 users.
    It downloaded the 4.4 update, unchecked the OS 4.4 update (I think was my first mistake), restarted. Now, at boot up, about the moment the apple would appear (maybe it appears for a split second) all I get is the ugly not sign.
    -- Am able to boot to external firewire drive
    -- Drive shows as boot option
    -- Disk repair reported no problems to fix
    -- Can not find any log entries after last shut down. No service ever starts for any entries to be made.
    -- Applied the 4.4 update successfully while booted from external fw drive, no effect. Startup disk reports system to be OS X Server 4.4 and lists as a boot option.
    -- Drive behaves same when transferred to my G5 tower: big not sign.
    What other steps can I do to troubleshoot this boot problem? If I don't get this server up this weekend, I'll get roasted by an angry mob.
    Any suggestions are welcomed and greatly appreciated.

    Eeh...
    Always clone the existing system prior to updating it. Do so when the server is not in use, shut off services where possible (you want it to be as quiescent as possible).
    Mike Bombich (at Apple) describes how you can do this via the command-line, which I prefer for this purpose (you can stagger the process):
    http://www.bombich.com/mactips/image.html
    Now then:
    Have you booted from the install CD and used Disk Utility to run Repair Permissions ? That should be your first step.
    It may change nothing, but can you boot into Safe mode ? Hold down the Shift key at powerup and keep holding it until you see: "Safe boot"
    If you CAN get it booted in that state, then run the 10.4.4 COMBO updater
    you need to run the combo updater at this point. After doing so, use Disk Utility to run repair permissions on the boot drive itself, and then reboot.
    Otherwise, start it in Target Disk Mode as you did before, connect it to a unit running 10.4.4, and run the /combo/ 10.4.4 Server updator (NOT client, of course) onto the server's mounted hard drive.
    I'm not sure you can do this while running 10.4.x client. You may need to do a quick install of 10.4 server (say onto a Firewire drive), boot your spare Mac from it, and -then- mount the server via Firewire target mode, and apply the 10.4.4 server combo updater.
    Good luck !

  • XML Gurus -My first request -Help needed urgently

    Hi XML gurus,
    I have a requirement to convert the following XML into two oracle tables.This is the first time I am looking at an XML script this closely....Could any of the gurus study the pattern of the xml and convert this into oracle tables with the constraints and post the script.After some thorough look I am able to conclude that the data has to be pushed into two tables.Appreciate your help!!
    XML file is as below
    - <Batch BatchCreated="633479274856698434" TransType="EISendCATProfile">
    - <SiebelMessage>
    - <CATProfiles>
    - <CATProfile Id="1-6XCMTV3">
    <CATCode>SE0</CATCode>
    <LegacyHandled>N</LegacyHandled>
    <DOLStart>05/31/2008</DOLStart>
    <DOLEnd>06/02/2008</DOLEnd>
    <Status>New</Status>
    <TransStatus>Pending</TransStatus>
    <Description>CAT SE0 MN Auto Wind and Hail Prop Wind, Hail and Other Weather 5/31 - 6/2</Description>
    <GMTCreated>06/01/2008 14:23:26</GMTCreated>
    <GMTUpdated>06/01/2008 14:31:21</GMTUpdated>
    - <Details>
    - <Detail Id="1-6XCMTV5">
    <State>MN</State>
    <PolicyType>Auto</PolicyType>
    <ClaimType>Comprehensive</ClaimType>
    <CauseOfLoss>Hail</CauseOfLoss>
    <Status>New</Status>
    <GMTCreated>06/01/2008 14:23:47</GMTCreated>
    <GMTUpdated>06/01/2008 14:24:11</GMTUpdated>
    </Detail>
    - <Detail Id="1-6XCMTV9">
    <State>MN</State>
    <PolicyType>Auto</PolicyType>
    <ClaimType>Comprehensive</ClaimType>
    <CauseOfLoss>Wind</CauseOfLoss>
    <Status>New</Status>
    <GMTCreated>06/01/2008 14:24:11</GMTCreated>
    <GMTUpdated>06/01/2008 14:24:28</GMTUpdated>
    </Detail>
    - <Detail Id="1-6XCMTVC">
    <State>MN</State>
    <PolicyType>Commercial Auto</PolicyType>
    <ClaimType>Comprehensive</ClaimType>
    <CauseOfLoss>Hail</CauseOfLoss>
    <Status>New</Status>
    <GMTCreated>06/01/2008 14:24:29</GMTCreated>
    <GMTUpdated>06/01/2008 14:24:45</GMTUpdated>
    </Detail>
    - <Detail Id="1-6XCMTVF">
    <State>MN</State>
    <PolicyType>Commercial Auto</PolicyType>
    <ClaimType>Comprehensive</ClaimType>
    <CauseOfLoss>Wind</CauseOfLoss>
    <Status>New</Status>
    <GMTCreated>06/01/2008 14:24:47</GMTCreated>
    <GMTUpdated>06/01/2008 14:25:10</GMTUpdated>
    </Detail>
    - <Detail Id="1-6XCMTVI">
    <State>MN</State>
    <PolicyType>Commercial Property</PolicyType>
    <ClaimType>Commercial Property</ClaimType>
    <CauseOfLoss>Windstorm & Hail</CauseOfLoss>
    <Status>New</Status>
    <GMTCreated>06/01/2008 14:25:13</GMTCreated>
    <GMTUpdated>06/01/2008 14:25:55</GMTUpdated>
    </Detail>
    - <Detail Id="1-6XCMTVL">
    <State>MN</State>
    <PolicyType>Homeowners</PolicyType>
    <ClaimType>Property</ClaimType>
    <CauseOfLoss>Hail</CauseOfLoss>
    <Status>New</Status>
    <GMTCreated>06/01/2008 14:25:57</GMTCreated>
    <GMTUpdated>06/01/2008 14:26:14</GMTUpdated>
    </Detail>
    - <Detail Id="1-6XCMTVO">
    <State>MN</State>
    <PolicyType>Homeowners</PolicyType>
    <ClaimType>Property</ClaimType>
    <CauseOfLoss>Wind</CauseOfLoss>
    <Status>New</Status>
    <GMTCreated>06/01/2008 14:26:16</GMTCreated>
    <GMTUpdated>06/01/2008 14:27:06</GMTUpdated>
    </Detail>
    - <Detail Id="1-6XCMTVU">
    <State>MN</State>
    <PolicyType>Homeowners</PolicyType>
    <ClaimType>Property</ClaimType>
    <CauseOfLoss>Other Weather Related</CauseOfLoss>
    <Status>New</Status>
    <GMTCreated>06/01/2008 14:29:35</GMTCreated>
    <GMTUpdated>06/01/2008 14:29:52</GMTUpdated>
    </Detail>
    </Details>
    </CATProfile>
    </CATProfiles>
    </SiebelMessage>
    </Batch>
    Thanks Much!
    Sridhar

    I tried what you told AnanSmriti.
    But still Server cannot find the page .
    I have saved JSP pages in DefaultWebApp and Java class files in WEB-INF /classes under DefaultWebApp dir.
    Also I have given the same URl in web.xml as in my first page.
    Please tell me where am I going wrong.
    Thanx in advance for any help.

  • Scene selection will not play to the end! help needed

    Hi
    I am using Encore CS5 and my DVD is a DUAL LAYER
    I have created a DVD of a dance show. I have a PLAY ALL button that plays the full show but on the timeline I have created CHAPTER POINTS for each dance.
    On a SUB MENU I have created a dance selection menu, the buttons on this menu point to CHAPTER PLAYLISTS that I have created, so for example I have 18 dances and I have created 18 CHAPTER PLAYLISTS with each one having every dance in it. I have applied end actions to every playlist to go back to the previous menu. When I preview the DVD in Encore the dance selection works fine, it plays that dance and goes back to the previous menu.
         The problem I have is when I have created the image and watch it with VLC player or I burn it to a DVD some of the dance selections only play about 10 secs and not the full dance and then it will apply the end action and go back to the previous menu. This is extremely frustrating!!!!!!!!
    Has any one experienced anything similar or have any idea why this is happening.
    Thanks!

    CHAPTER PLAYLISTS that I have created, so for example I have 18 dances and I have created 18 CHAPTER PLAYLISTS with each one having every dance in it. I have applied end actions to every playlist to go back to the previous menu.
    From the rest of what you said, I assume you mean that each chapter playlist includes ONLY ONE dance in it. If you mean what you said in this sentence, you want only one dance in each chapter playlist.
    Make sure that you have no end actions on any chapters. While you are looking at that, make sure that you have no overrides anywhere in the project. It doesn't matter whether you are sure you did not add any. There is the inadvertant click, and I have had Encore add chapter end actions when working with its timeline.
    If all is as it should be, burn a test disk, and confirm you see the problem from a DVD player. I find VLC a great test option, but it does not handle slideshows, so I'd test beyond it.

  • My webroot tool bar will not install firefox. How to Help needed. I did the reinstall from the start button in windows. Thanks

    The toolbar for my webroot account will not install on firefox for some reason. It remembers my accounts and passwords along with the sign in pages of my accounts.

    It works again, thanks. It was only a small thing but so annoying. Do you know why this happened so I can maybe avoid it in future?

  • JAVA SOUND APPLICATION not applet.....help needed.....cheers

    hey there people heres the deal I need to complete this before 5 today but im completely stumped...we have to make a sound file player with a swing interface I have it playing(kind of!) but where now...I would be forever in your debt as my masters degree hangs in the balance! de de duhhhh! cheers
    iT WORKS ALRIGHT JUST NEED STOP PAUSE BUTTON FUNCTION..........
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.event.*;
    import java.io.File;
    import java.io.IOException;
    import javax.sound.sampled.*;
    import javax.sound.sampled.AudioFormat;
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.Clip;
    import javax.sound.sampled.DataLine;
    import javax.sound.sampled.LineEvent;
    import javax.sound.sampled.LineListener;
    import javax.sound.sampled.LineUnavailableException;
    public class AudioPlayer extends JFrame implements ActionListener, ChangeListener{
    boolean playing;
    boolean looping;
    String filename = File.separator+"tmp";
    File selFile;
    Clip clip;
    JFileChooser fc = new JFileChooser();
    JButton btnOpen = new JButton("Open");
    JButton btnPlay = new JButton("Play");
    JButton btnStop = new JButton("Stop");
    JButton btnPause = new JButton("Pause");
    JButton btnLoop = new JButton("Loop");
    JSlider volume = new JSlider(SwingConstants.HORIZONTAL,0,100,0);
    JSlider panning = new JSlider(SwingConstants.HORIZONTAL,0,100,0);
    public AudioPlayer(){
    Container contentPane = getContentPane();
    contentPane.setLayout(new FlowLayout());
    contentPane.add(btnOpen);btnPlay.addActionListener(this);
    contentPane.add(btnPlay);btnPlay.addActionListener(this);
    contentPane.add(btnStop);btnStop.addActionListener(this);
    contentPane.add(btnPause);btnPause.addActionListener(this);
    contentPane.add(btnLoop);btnLoop.addActionListener(this);
    // Show open dialog; this method does not return until the dialog is closed
    fc.showOpenDialog(this);
    selFile = fc.getSelectedFile();
    volume.addChangeListener(this);
    panning.addChangeListener(this);
    volume.putClientProperty("JSlider.isFilled", Boolean.TRUE);
    volume.setPaintTicks(true);volume.setPaintLabels(true);
    volume.setMajorTickSpacing(20);volume.setMinorTickSpacing(10);
    contentPane.add(volume);
    panning.putClientProperty("JSlider.isFilled", Boolean.TRUE);
    panning.setPaintTicks(true);panning.setPaintLabels(true);
    panning.setMajorTickSpacing(20);panning.setMinorTickSpacing(10);
    contentPane.add(panning);
    addWindowListener(
    new WindowAdapter () {
    public void windowClosing(WindowEvent e){
    setVisible(false);
    public void actionPerformed(ActionEvent e){
    int returnVal = JFileChooser.APPROVE_OPTION;
    //Handle open file action.
    if (e.getSource() == btnOpen)
    System.out.println("FA1");
    returnVal = fc.showOpenDialog(AudioPlayer.this);
    if (returnVal == JFileChooser.APPROVE_OPTION)
    { selFile = fc.getSelectedFile();
    //This is where a real application would open the file.
    else
    if(e.getSource() == btnPlay)
    playAudio();
    public void stateChanged(ChangeEvent e)
    public static void main(String[] args)
    AudioPlayer audioPlayer = new AudioPlayer();
    audioPlayer.setSize(400,400);
    audioPlayer.show();
    public void playAudio ()
    playing = true;
    AudioInputStream audiosource = null;
    try
    audiosource = AudioSystem.getAudioInputStream(selFile);
    System.out.println("here");
    //System.out.println(audiosource.getFormat());
    DataLine.Info dataLineInfo = new DataLine.Info(Clip.class,audiosource.getFormat());
    clip = (Clip)AudioSystem.getLine(dataLineInfo);
    clip.open(audiosource);
    catch (UnsupportedAudioFileException e)
    catch (LineUnavailableException e)
    catch (IOException e)
    //catch (Exception e) {}
    if (looping)
    clip.loop(clip.LOOP_CONTINUOUSLY);
    else
    clip.loop(0);
    playing = false;
    }

    You have not added the actionListener to all the button D'oh
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.event.*;
    import javax.sound.sampled.*;
    * Description of the Class
    *@author rsmazara
    *@created 28 February 2003
    public class AudioPlayer extends JFrame implements ActionListener, ChangeListener {
    File selFile;
    JFileChooser fc = new JFileChooser();
    JButton btnOpen = new JButton( "Open" );
    JButton btnPlay = new JButton( "Play >" );
    JButton btnStop = new JButton( "Stop" );
    JButton btnPause = new JButton( "Pause ||" );
    JCheckBox btnLoop = new JCheckBox( "Loop" );
    JSlider volume = new JSlider( SwingConstants.HORIZONTAL, 0, 100, 0 );
    JSlider panning = new JSlider( SwingConstants.HORIZONTAL, 0, 100, 0 );
    JLabel label = new JLabel( " " );
    public AudioPlayer() {
    Container contentPane = getContentPane();
    contentPane.setLayout( new FlowLayout() );
    btnOpen.addActionListener( this );
    contentPane.add( btnOpen );
    btnPlay.addActionListener( this );
    contentPane.add( btnPlay );
    btnPlay.addActionListener( this );
    contentPane.add( btnStop );
    btnStop.addActionListener( this );
    contentPane.add( btnPause );
    btnPause.addActionListener( this );
    contentPane.add( btnLoop );
    btnLoop.addActionListener( this );
    btnPlay.setEnabled( false );
    btnStop.setEnabled( false );
    btnPause.setEnabled( false );
    // Show open dialog; this method does not return until the dialog is closed
    // fc.showOpenDialog( this );
    // selFile = fc.getSelectedFile();
    volume.addChangeListener( this );
    panning.addChangeListener( this );
    volume.putClientProperty( "JSlider.isFilled", Boolean.TRUE );
    volume.setPaintTicks( true );
    volume.setPaintLabels( true );
    volume.setMajorTickSpacing( 20 );
    volume.setMinorTickSpacing( 10 );
    contentPane.add( volume );
    panning.putClientProperty( "JSlider.isFilled", Boolean.TRUE );
    panning.setPaintTicks( true );
    panning.setPaintLabels( true );
    panning.setMajorTickSpacing( 20 );
    panning.setMinorTickSpacing( 10 );
    contentPane.add( panning );
    contentPane.add( label );
    addWindowListener(
    new WindowAdapter() {
    public void windowClosing( WindowEvent e ) {
    setVisible( false );
    System.exit( -100 );
    public void actionPerformed( ActionEvent e ) {
    int returnVal = JFileChooser.APPROVE_OPTION;
    //Handle open file action.
    System.out.println( e.getActionCommand() );
    ///open
    if ( e.getSource() == btnOpen ) {
    System.out.println( "FA1" );
    returnVal = fc.showOpenDialog( AudioPlayer.this );
    if ( returnVal == JFileChooser.APPROVE_OPTION ) {
    selFile = fc.getSelectedFile();
    player = new Player( selFile );
    label.setText( "File loaded : " + selFile.getAbsolutePath() );
    btnPlay.setEnabled( true );
    btnStop.setEnabled( false );
    btnPause.setEnabled( false );
    //This is where a real application would open the file.
    } else {
    //play
    if ( e.getSource() == btnPlay ) {
    player.go( btnLoop.isSelected() );
    btnPlay.setEnabled( false );
    btnStop.setEnabled( true );
    btnPause.setEnabled( true );
    // playAudio();
    // pause
    if ( e.getSource() == btnPause ) {
    player.pause();
    btnPlay.setEnabled( true );
    btnStop.setEnabled( true );
    btnPause.setEnabled( false );
    if ( e.getSource() == btnStop ) {
    player.finish();
    btnPlay.setEnabled( true );
    btnStop.setEnabled( false );
    btnPause.setEnabled( false );
    public void stateChanged( ChangeEvent e ) {
    private Player player = null;
    public static void main( String[] args ) {
    AudioPlayer audioPlayer = new AudioPlayer();
    audioPlayer.setSize( 400, 400 );
    audioPlayer.show();
    * Description of the Class
    *@author rsmazara
    *@created 28 February 2003
    class Player {
    Clip clip;
    private java.io.File selectedFile = null;
    private boolean looping = false;
    public Player( File file ) {
    selectedFile = file;
    AudioInputStream audiosource = null;
    try {
    audiosource = AudioSystem.getAudioInputStream( selectedFile );
    System.out.println( "here" );
    //System.out.println(audiosource.getFormat());
    DataLine.Info dataLineInfo = new DataLine.Info( Clip.class, audiosource.getFormat() );
    clip = ( Clip ) AudioSystem.getLine( dataLineInfo );
    clip.open( audiosource );
    } catch ( UnsupportedAudioFileException e1 ) {
    e1.printStackTrace();
    } catch ( LineUnavailableException e2 ) {
    e2.printStackTrace();
    } catch ( IOException e3 ) {
    e3.printStackTrace();
    private boolean work = false;
    public void go( boolean loop ) {
    looping = loop;
    playAudio();
    public void finish() {
    clip.stop();
    public boolean isWorking() {
    return clip.isRunning();
    long pausePosition = ( long ) 0;
    public void pause() {
    pausePosition = clip.getMicrosecondPosition();
    clip.stop();
    public void restart() {
    clip.setMicrosecondPosition( pausePosition );
    playAudio();
    public void loop( boolean loop ) {
    looping = loop;
    private void playAudio() {
    if ( looping ) {
    clip.loop( clip.LOOP_CONTINUOUSLY );
    } else {
    clip.loop( 0 );

Maybe you are looking for

  • Setting the request of follow-on documents

    Hello everybody, my issue is the following: I'm using the SAP Supplier Self-Services. When I display the Purchase Order selected from a list, in the field "Requested Follow-On Documents" appears also the voice "Invoice". My target is to remove this v

  • Reading Files from client directory folder using servlets or struts.

    HI All, Could you please help me out int the below query. I want read all files from paricular directory folder from the client machine in web application. I am able to do it from my local machine. but when I am try to do it from some other machine I

  • Quicktime not playing video

    I am on a Mac Pro running Snow Leopard. I have a number of videos downloaded from various cameras and an iTouch with .mov extensions. I downloaded Quicktime 10, and Quicktime 7 yesterday. When I open any of the videos in either Quicktime and click Pl

  • Japanese Crop Marks illustrator CS6

    The setting to 'use japanese cropmarks' has been removed from the general settings in illustrator CS6. Any suggestions as to how I can get these back? I want them on my artwork not added at print. I have an Action to add them to my cutter profiles in

  • My iMac G5 with OSX 10.5.8 says Firefox 4 is not supported by the archetecture. Solution?

    Downloaded Firefox 4, replacing older edition, which worked well. Icon of new version came up with circle with slash on it, and when I attempted to open the new Firefox, the Mac said it was not supported by the architecture. What's the problem and so