How to implement Observer Pattern?

Hello guys,
I have some problems with implementing the observer pattern. So i m making an sound application and i need to put a meter changing with the volume.
I have already the meter designed and the volume is calculated.
So i have a class called Application (is the main class) and this class have the graphic designer from the application, makes the audio capture and calculate the volume.
And i have the MeterMic class and in this class i have the graphic Meter where i send this graphic meter to the application via JPanel.
In MeterMic i have the variable "value" and this variable will make the changes in the bars of the meter and i want to equal the value to the volume from the application. I try referencing by the Application object but doesnt pass the value from the volume.
So i would like to implement the Observer pattern.
I need to observ the variable volume and than the volume have changes i want to send that change to variable value in MeterMic.
My problem is: who is the observer and observ? And what i need to do to implement the pattern.
My best,
David

Kayaman wrote:
DavidHenriques wrote:
So i just need to implement the observers interfaces and than implement the method update and notify in the classes.You should probably forget the Observer/Observable classes, they're Java 1.0 stuffDo you think they are usless just because they are old?
so you don't have to or need to use them, even though the names sound appealing.I still like them because the Observable saves me from repetitively implementing (hopefully thread save) method for notifying the observers...
It's basically the same thing, you just see a lot more talk about Events/Listeners than Observers/Observables these days.The good thing on Events/Listeners is that they are type save which is an importand feature.
But I like to build them on top of Observer/Observable on the event source side.
bye
TPD

Similar Messages

  • How to implement command pattern into BC4J framework?

    How to implement command pattern into BC4J framework, Is BC4J just only suport AIDU(insert,update,delete,query) function? Could it support execute function like salary caculation in HR system or posting in GL(general ledger) system? May I create a java object named salaryCalc which use view objects to get the salary by employee and then write it to database?
    Thanks.

    BC4J makes it easy to support the command pattern, right out of the box.
    You can write a custom method on your application module class, then visit the application module wizard and see the "Client Methods" tab to select which custom methods should be exposed for invocation as task-specific commands by clients.
    BC4J is not only for Insert,Update,Delete style applications. It is a complete application framework that automates most of the typical things you need to do while building J2EE applications. You can have a read of my Simplifying J2EE and EJB Development Using BC4J whitepaper to read up on an overview of all the basic J2EE design patterns that the framework implements for you.
    Let us know if you have more specific questions on how to put the framework into practice.

  • How to implement Strategy pattern in ABAP Objects?

    Hello,
    I have a problem where I need to implement different algorithms, depending on the type of input. Example: I have to calculate a Present Value, sometimes with payments in advance, sometimes payment in arrear.
    From documentation and to enhance my ABAP Objects skills, I would like to implement the strategy pattern. It sounds the right solution for the problem.
    Hence I need some help in implementing this pattern in OO. I have some basic OO skills, but still learning.
    Has somebody already implemented this pattern in ABAP OO and can give me some input. Or is there any documentation how to implement it?
    Thanks and regards,
    Tapio

    Keshav has already outlined required logic, so let me fulfill his answer with a snippet
    An Interface
    INTERFACE lif_payment.
      METHODS pay CHANGING c_val TYPE p.
    ENDINTERFACE.
    Payment implementations
    CLASS lcl_payment_1 DEFINITION.
      PUBLIC SECTION.
      INTERFACES lif_payment.
      ALIASES pay for lif_payment~pay.
    ENDCLASS.                 
    CLASS lcl_payment_2 DEFINITION.
      PUBLIC SECTION.
      INTERFACES lif_payment.
      ALIASES pay for lif_payment~pay.
    ENDCLASS.                   
    CLASS lcl_payment_1 IMPLEMENTATION.
      METHOD pay.
        "do something with c_val i.e.
        c_val = c_val - 10.
      ENDMETHOD.                   
    ENDCLASS.                  
    CLASS lcl_payment_2 IMPLEMENTATION.
      METHOD pay.
        "do something else with c_val i.e.
        c_val = c_val + 10.
      ENDMETHOD.  
    Main class which uses strategy pattern
    CLASS lcl_main DEFINITION.
      PUBLIC SECTION.
        "during main object creation you pass which payment you want to use for this object
        METHODS constructor IMPORTING ir_payment TYPE REF TO lif_payment.
        "later on you can change this dynamicaly
        METHODS set_payment IMPORTING ir_payment TYPE REF TO lif_payment.
        METHODS show_payment_val.
        METHODS pay.
      PRIVATE SECTION.
        DATA payment_value TYPE p.
        "reference to your interface whcih you will be working with
        "polimorphically
        DATA mr_payment TYPE REF TO lif_payment.
    ENDCLASS.                  
    CLASS lcl_main IMPLEMENTATION.
      METHOD constructor.
        IF ir_payment IS BOUND.
          me->mr_payment = ir_payment.
        ENDIF.
      ENDMETHOD.                  
      METHOD set_payment.
        IF ir_payment IS BOUND.
          me->mr_payment = ir_payment.
        ENDIF.
      ENDMETHOD.                  
      METHOD show_payment_val.
        WRITE /: 'Payment value is now ', me->payment_value.
      ENDMETHOD.                  
      "hide fact that you are using composition to access pay method
      METHOD pay.
        mr_payment->pay( CHANGING c_val = payment_value ).
      ENDMETHOD.                   ENDCLASS.                  
    Client application
    PARAMETERS pa_pay TYPE c. "1 - first payment, 2 - second
    DATA gr_main TYPE REF TO lcl_main.
    DATA gr_payment TYPE REF TO lif_payment.
    START-OF-SELECTION.
      "client application (which uses stategy pattern)
      CASE pa_pay.
        WHEN 1.
          "create first type of payment
          CREATE OBJECT gr_payment TYPE lcl_payment_1.
        WHEN 2.
          "create second type of payment
          CREATE OBJECT gr_payment TYPE lcl_payment_2.
      ENDCASE.
      "pass payment type to main object
      CREATE OBJECT gr_main
        EXPORTING
          ir_payment = gr_payment.
      gr_main->show_payment_val( ).
      "now client doesn't know which object it is working with
      gr_main->pay( ).
      gr_main->show_payment_val( ).
      "you can also use set_payment method to set payment type dynamically
      "client would see no change
      if pa_pay = 1.
        "now create different payment to set it dynamically
        CREATE OBJECT gr_payment TYPE lcl_payment_2.
        gr_main->set_payment( gr_payment ).
        gr_main->pay( ).
        gr_main->show_payment_val( ).
      endif.
    Regads
    Marcin

  • How to implement DAO pattern in CMP

    How do I use the DAO pattern when going for container managed persistence, because all the database access is defined by the CMP.
    How to go about it ?

    Hi,
    The DAO pattern http://java.sun.com/blueprints/patterns/DAO.html
    is used with Bean Managed Persitence(BMP). For CMP you should not write the SQL in the EJB code, but instead let the container generate the SQL and handle all the data access.
    Another pattern that might help when modelling your EJBs is the Composite Entity pattern at
    http://java.sun.com/blueprints/patterns/CompositeEntity.html
    Also, the new J2EE BluePrints book has some tips and strategies in the EJB tier chapter at
    http://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/index.html
    hope that helps,
    Sean

  • How to implement pattern matching in RFC input paramenter?

    Dear Friend.......
    I have a requirment for implement a pattern match for name field of vendor in one of RFC.........
    For ex..........
    Name field:-  A* -> give all list of name  starting with a.
    how can we implement this?
    Any way............Suggest me
    Regards
    Ricky

    Hi,
    I am not using any ABAP program for calling this RFC,I am using Webdynpro for this one.
    so how it possible to implemnet same things at there.
    Regards
    ricky

  • How to add observable behaviour in existing code?

    Hi everyone, I'm new to design patterns. I have an existing numerical analysis package that I use to find roots using multiple strategy (bisection, secant, newton, etc). I want to show the process of root finding for every iterations taken by the algorithm (for example, iteration 0: left = 0, mid = 0.5, right = 1; iteration 2: left = 0, mid = 0.25, right = 0.5; ... etc. Its not exactly like that, I want to show it graphically, but you see what I mean). Looks like I need Observer to add event handling to notify the change of state in each initial guess as well as signaling the event when a root is/isn't found. But the solver classes doesn't seem to be implementing Observable, they just give out the answer, or not. How do I add Observer pattern without modifying the original code? I thought about using Decorator and having the real solver do the root finding but it just doesn't make sense to me. Thanx in advance.

    endasil wrote:
    georgemc wrote:
    endasil wrote:
    georgemc wrote:
    That won't get you intermediate results, though.If the method being observed needs to be firing multiple events per invocation, no, it won't.
    @OP, you were on the right track with the decorator pattern (indeed, that could be just as appropriate). What made you think it was wrong?I think that's the OP's tripping point:
    I want to show the process of root finding for every iterations taken by the algorithm
    ...But the solver classes doesn't seem to be implementing Observable, they just give out the answer, or not.
    Aha. Bytecode weaving (or plain old decompiling and nicking the source) then.Nope, I didn't. You're just too damned fast!For my own good! I hit "post" and immediately go "I forgot to say X" :-/
    @OP: if you want to see some examples of using bytecode weaving to introduce observableness to existing code, have a look at the sources for a test coverage tool like Cobertura. That's basically what they do. If you've never done it before, it'll take you a fair bit of head-scratching and sideways thinking to get your head round it all, but stick with it. Be prepared to learn a bit about opcodes as well. Or maybe just plundering the sources for this library is the way to go, not that I'm advocating that ;)

  • How to implement MVC model?

    Hi, I have a question on how to implement MVC model, that is, how will the GUI be informed that the data from the Model has been changed?
    Suppose that I have two simple classes, Model and GUI. Model creates 10 integers each time, and then GUI draws some bars whose height is the integers. then after each time the integers has been created, how could GUI know?
    Thanks!!!!

    There is an Observer pattern specific to Google?I so implement the Google Observer pattern. ;o)Isn't that the (G)oogling Observer pattern? ;)

  • Observer pattern with TCP

    Hello java friends!
    I have implemented an auction application over a TCP communication. The client's using a basis Socket and the server is multi threaded with a ServerSocket returning a Socket which is processed in a separate thread. The connection between server and client is closed automatic after each request, so another request from the client would need to be connected over a new connection. It's implemented like this for the sake of performance.
    But however, I now want to implement the Observer pattern(which I'm also comfortable with). This would let the client be notified by the server if someone else overbids him in a auction. And I wonder how this could be completed?
    I had a thought and it went like this. If the client would also have a ServerSocket then the server would be able to connect to it when ever he would like to notifying the client. What I like by this implementation is that the notification is done without any delay! This is obviously one way to implement it, but I wonder if someone else in here had a better idea,or if someone knew the standard implementation for a situation like this.
    Thanks in regards!

    superdeportivo wrote:
    The sever creates a new thread for every request that the client makes. If performance is important you may want to use a thread pool.
    For example the client makes a bid on an auction item. [deleted]This is simplest way to do what you require. I am generally in favour of keeping things simple.
    if the Client would like to make another bid then the client would need to go through all the steps again from 1 to 4. Why the fourth step is implemented is because otherwise the client would held a thread live at the server as long as he is connected (using the application) and eventually the server would run out of threads!How many clients do you have at once? You should be able to support 1,000 on a typical PC and 10,000 on a decent server. You can keep the connection/thread for a period of time and drop the connection if the client disconnects or doesn't do anything for a period of time (from a few seconds to a few hours)
    Another approach is to use non-blocking IO (see the samples which come with the JDK) In this way a small number of threads can manage a large number of connections.
    So lets say if we're using a thread pool with maximum 20 threads, then only 20 clients would be able to connect to the server at the same time (use the application). If the maximum is 2,000 then you can have up to 2,000 clients.
    I hope I made my self clear if not please tell me which part wasn't.I think you have made a few assumptions about what performs best or what is possible could have a rethink.
    And about the delay, of course the connection delay is what's acceptable for my program.The simplest approach using your current model is for the client to poll the server.
    Edited by: Peter__Lawrey on 30-Jan-2009 22:56

  • Observer Pattern applied in Abap

    Observer Pattern
    Observer pattern is a well known pattern especially with Java, here i continue my work in patterns.
    This is my humble understanding of a way how we can apply observer pattern
    The main components of this pattern is:
    Observer pattern:
    Subject
    Observer
    Context
    Why do we need?
    Cant i do without this pattern, well of course you can do although you will be having a tightly coupled application
    The main reason is we don't want to couple the objects
    The main goal is the " Least knowledge in objects across each other"
    The trick here is the use of the Events in ABAP where an event gets raised and then that will be handled by a listener!!
    Subject:
    Its the main object the core data that we will be working with
    You could have multiple implementations of the subject
    One approach: is to have an interface where we can extract the event.
    Here is a code sample: Subject is data based on the sales order item data when there is a change it will fire the event below
    interface lif_subject.
       EVENTS: SUBJECT_IS_CHANGED.
    ENDINTERFACE.
    Here is the subject:
    class lcl_subject definition .
    public section.
    INTERFACES lif_subject.
       methods CONSTRUCTOR
         importing
           !IV_MATNR type MATNR
           !IV_SPRAS type SPRAS
        methods GET_MATNR
         returning
           value(RV_MATNR) type MATNR .
       methods GET_SPRAS
         returning
           value(RV_SPRAS) type SPRAS .
        methods SET_MATNR
         importing
           !IV_MATNR type MATNR .
       methods SET_SPRAS
         importing
           !IV_SPRAS type SPRAS .
    protected section.
    private section.
       data MV_MATNR type MATNR .
       data MV_SPRAS type SPRAS .
    ENDCLASS.
    CLASS lcl_subject IMPLEMENTATION.
    METHOD constructor.
       mv_matnr = iv_matnr.
       mv_spras = iv_spras.
    ENDMETHOD.
    METHOD get_matnr.
       rv_matnr = mv_matnr.
    ENDMETHOD.
    METHOD get_spras.
       rv_spras = mv_spras.
    ENDMETHOD.
    METHOD set_matnr.
       mv_matnr = iv_matnr.
       RAISE EVENT lif_subject~SUBJECT_IS_CHANGED.
    ENDMETHOD.
    METHOD set_spras.
       mv_spras = iv_spras.
       RAISE EVENT lif_subject~SUBJECT_IS_CHANGED.
    ENDMETHOD.
    ENDCLASS.
    Observer:
    Observer is the one thats interested in the change of the subject
    That could be any observer
    Here is the code sample
    ****Observer
    INTERFACE lif_observer.
    METHODS: update.
    ENDINTERFACE.
    class lcl_observer1 DEFINITION.
    PUBLIC SECTION.
    INTERFACES lif_observer.
    ENDCLASS.
    class lcl_observer1 IMPLEMENTATION.
    method lif_observer~update.
    WRITE:/ ' Observer 1 is updated '.
    ENDMETHOD.
    ENDCLASS.
    class lcl_observer2 DEFINITION.
    PUBLIC SECTION.
    INTERFACES lif_observer.
    ENDCLASS.
    class lcl_observer2 IMPLEMENTATION.
    method lif_observer~update.
    WRITE:/ ' Observer 2 is updated '.
    ENDMETHOD.
    ENDCLASS.
    Context:  Its the manager of the all communication like a channel
    It separates the observer from the observable.
    class   lcl_channel  definition.
    PUBLIC SECTION.
    methods: add_observer IMPORTING io_observer type REF TO lif_observer.
    methods: remove_observer IMPORTING io_observer type REF TO lif_observer.
    methods: constructor.
    methods: notify_observers FOR EVENT lif_subject~SUBJECT_IS_CHANGED of lcl_subject IMPORTING sender.
    PRIVATE SECTION.
    DATA: lo_list type REF TO CL_OBJECT_MAP.
    class-DATA: lv_key type i.
    ENDCLASS.
    Notice that the event listener for the subject is the channel itself
    and notify_observers method is responsible for that.
    ****Manager!!
    class   lcl_channel  definition.
    PUBLIC SECTION.
    methods: add_observer IMPORTING io_observer type REF TO lif_observer.
    methods: remove_observer IMPORTING io_observer type REF TO lif_observer.
    methods: constructor.
    methods: notify_observers FOR EVENT lif_subject~SUBJECT_IS_CHANGED of lcl_subject IMPORTING sender.
    PRIVATE SECTION.
    DATA: lo_list type REF TO CL_OBJECT_MAP.
    class-DATA: lv_key type i.
    ENDCLASS.
    class lcl_channel IMPLEMENTATION.
    method constructor.
       create OBJECT lo_list.
       lv_key  = 1.
    ENDMETHOD.
    method add_observer.
    lo_list->PUT(
       EXPORTING
         KEY      = lv_key
         VALUE    = io_observer
    lv_key = lv_key + 1.
    ENDMETHOD.
    method remove_observer.
    ENDMETHOD.
    METHOD notify_observers.
    DATA: lo_map_iterator TYPE REF TO CL_OBJECT_COLLECTION_ITERATOR.
    DATA: lo_observer type REF TO lif_observer.
    break developer.
    lo_map_iterator ?= lo_list->GET_VALUES_ITERATOR( ).
    while lo_map_iterator->HAS_NEXT( ) = abap_true.
    lo_observer ?= lo_map_iterator->GET_NEXT( ).
    lo_observer->UPDATE( ).
    ENDWHILE.
    ENDMETHOD.
    Notice the use of the Collections as well cl_object_collections object in SAP Standard
    I hope you find this useful
    The sample code is attached as a text file
    ENDCLASS.

    Are you asking to check string in data in the course of running the program, or are you asking how to check patterns in the source of the program itself?
    The other replies have covered checking patterns in data.
    If you want to check for patterns in the ABAP source itself, you can check for patterns in ABAP source using SCII Code inspector.
    Enter SCII and select the object or set of objects to check.
    Under the list of checks for Temporary Definition there is area called
    Search Functs.
    Under Search Functs., if you expand it, there are options to search for
    Search of ABAP Tokens
    Search ABAP Statement Patterns
    Click on the arrow to the left of these and you can specify details about the patterns that you want to search for.
    Good luck
    Brian

  • Observer pattern in J2EE

    I have a question about the Observer patterne.
    I have tried to implement it im my application but without result. First my idea was to save all the client Object references in A linked List in a bean on the server. Then each time a certain event ocurs on my server I will call a method fire() which iterate through my linked list and finds all my client references. Then I will make a "call back" to all the clients which are in my linked list. But my teacher tells my that is not the way to do. He belives that there is a much easier way to make sure that all the clients get updates. But he does't know how to do it. So my question is how do I implements Observer Design patterns in the J2ee enviroment ??

    It seems to that one of the solotions to this problem is to use RMI. Apperently it is not possible to make a regular callback to a client in the J2EE enviroment. That,s not good, because you have to make a call back if you want to implement the observer deign patterne. I think it is sad, because one of the most important design pattern is The observer pattern.

  • Observer Pattern Help

    hi,
    I am trying to understand how and when you would use an observer pattern. I understand that it allows one class to observe another, i.e if a variable was to change in 1 class all observing classes would be notified of the change. I do not understand how u would implement this, I have seen some examples but they are kinda confusing does anybody have a simple way of showing how this pattern is implemented?
    thx
    sbains

    Dish would be the observable in this case. Waiter and Chef are the /
    contain observers. The observer's update method will get called whenever
    the observable calls notifyObservers.
    public class Dish extends Observable {
        public void setStock(int stock) {
            .. business logic ..
            this.setChanged();
            this.notifyObservers(new Integer(stock));
    public class Waiter implements Observer {
        public void update(Observable o, Object arg) {
            Long stock = (Long) arg;
            .. business logic ..
    }Note that Listeners are also implementations of the Observer pattern, if
    that helps any.

  • Observer pattern in BC4J?

    Just wondering if anyone has implemented a publisher/subscriber (or observer) pattern with BC4J? For instance, has anyone implemented an application module supporting multiple clients that allows clients to call a method to send a message to all the clients that listen to the sender? Would the performance be much worse if I implement the piece in BC4J rather than implementing it in, say, VisiBroker CORBA or straight UDP datagram sockets?

    Actually I have a similar question as well... I wonder if anyone has tried to implement something like a simple chat server that listens to all incoming messages and route those messages to the listening clients. I am not sure how to implement this.

  • CS4 / Win: How can I observe a table (insert and delete)

    Hi
    How can i observe the insertion oder deletion of a table in my Indesign document?
    I have implemented a doc change observer. But I don't know if it is possible to observe the tables in this observer or how I can do that.
    Any help? Thanks.
    Hans

    after i have done some changes now it inserts into the table but returning the data twice, not sure why.
    <!--  <cfdump var="#reports#">   -->
    <cfloop query=reports>
    <cfquery name="second" datasource="Intranet">
    insert into intranet.dbo.CSE_Monthly_Reports (starburst_winner)
    values ('#emp_namefirst#')
    </cfquery>
    </cfloop>
    this is a test im doing to make sure it works

  • Implementing DAO Pattern in ABAP

    This discussion implement DAO pattern asked the question of how to develop a DAO pattern in ABAP but i'd like to go a little deeper.
    The only answer given suggested the following design pattern:
    I don't have an coded example here, but isn't it sufficient for this pattern  to build an interface with some get- and set-methods? This interface can be implemented by several classes with different data retrieval logic. Then a static factory-method could do the job to decide during runtime which actual class is instantiated, returning the interface.
    Can anyone give an abstract description of this implementation relative to an SAP module (How would one approach this implementation in MM, PM, FICO, HR)
    Can anyone see any issues in this design?
    Can anyone provide an alternate design?
    Are we missing any steps?
    Together we can build a solid abap DAO everyone can use.

    I started to read about DAO pattern some days ago and found this great blog post:
    ABAP Unit Tests without database dependency - DAO concept
    I am starting to implement unit test in my developments and DAO pattern seems to be a clever choice.
    Regards,
    Felipe

  • How to Implement HTTP Request Status Code Processing

    I actually have two questions. First, I wondering how to add multiple status code processing to an http request. Secondly, I was wondering how to go about using alternate http requests to different servers in case the primary server is down. What kind of parameter would the program use to determine that the server is unavailable and switch to another server??
    Currently, the program I've written calls an rdf server (http://www.rdfabout.com/sparql) using a sparql query,
    the server returns an xml string, the program parses it, and calculates numbers
    from the string. The program works, but the problem is that the server is down occasionally.
    When the server is down, we need to add calls to another server to
    increase reliability. So, the next task is to call this server:
    http://www.melissadata.com/lookups/ZipDemo2000.asp
    I need to do exactly the same things I did with the rdf server. The
    difference will be constructing a request and a bit different parsing of
    the response.
    current SPARQL query is defined as follows:
    PREFIX dc:  <http://purl.org/dc/elements/1.1/>
    PREFIX census: <http://www.rdfabout.com/rdf/schema/census/>
    PREFIX census1: <tag:govshare.info,2005:rdf/census/details/100pct/>
    DESCRIBE ?table WHERE {
    <http://www.rdfabout.com/rdf/usgov/geo/census/zcta/90292> census:details
    ?details .
    ?details census1:totalPopulation ?table .
    ?table dc:title "SEX BY AGE (P012001)" .
    }current HTTP Request is defined as follows:
    import java.net.*;
    import java.net.URL;
    import java.net.URLConnection;
    import java.io.*;
    import java.io.DataOutputStream;
    import java.io.BufferedReader;
    import java.io.StringReader;
    import java.io.InputStreamReader;
    import java.io.PrintStream;
    import java.util.Scanner;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import java.util.Arrays; 
    public class MyConnection
         static Scanner sc = new Scanner(System.in);//allows user to input zipcode
        public static void main(String[] args) throws Exception
             int zip;//zipcode is declared as integer format
            //User defines zip through input
            //proceed to put SPARQL query into string, which is then used to call the server
            String requestPart1 =
            "query=PREFIX+dc%3A++%3Chttp%3A%2F%2Fpurl.org%2Fdc%2Felements%2F1.1%2F%3E+%0D%0APREFIX+census%3A+%3Chttp%3A%2F%2Fwww.rdfabout.com%2Frdf%2Fschema%2Fcensus%2F%3E+%0D%0APREFIX+census1%3A+%3Ctag%3Agovshare.info%2C2005%3Ardf%2Fcensus%2Fdetails%2F100pct%2F%3E+%0D%0A%0D%0ADESCRIBE+%3Ftable+WHERE+%7B+%0D%0A+%3Chttp%3A%2F%2Fwww.rdfabout.com%2Frdf%2Fusgov%2Fgeo%2Fcensus%2Fzcta%2F";
            String requestPart2 = "" + zip; // zipcode is transformed from int to string format and plugged into SPARQL query here
            String requestPart3 =
            "%3E+census%3Adetails+%3Fdetails+.+%0D%0A+%3Fdetails+census1%3AtotalPopulation+%3Ftable+.+%0D%0A+%3Ftable+dc%3Atitle+%22SEX+BY+AGE+%28P012001%29%22+.+%0D%0A%7D%0D%0A&outputMimeType=text%2Fxml";
            String response = "";
            URL url = new URL("http://www.rdfabout.com/sparql");//designates server to connect to
            URLConnection conn = url.openConnection();//opens connection to server
            // Set connection parameters.
            conn.setDoInput (true);
            conn.setDoOutput (true);
            conn.setUseCaches (false);
            // Make server believe we are form data…
            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            DataOutputStream out = new DataOutputStream (conn.getOutputStream ());
            // Write out the bytes of the content string to the stream.
            out.writeBytes(requestPart1 + requestPart2 + requestPart3);
            out.flush ();
            out.close ();
            // Read response from the input stream.
            BufferedReader in = new BufferedReader (new InputStreamReader(conn.getInputStream ()));
            String temp;
            while ((temp = in.readLine()) != null)
                 response += temp + "\n";
            temp = null;
            in.close ();
            //parsing stuff is taken care of after here
    }What remains now is to:
    1) add status code processing: notify if the server is not available, ect.
    2) add ability to connect to additional server if primary server is down.
    I'm thinking an if/else statement, which I've tried a few different ways,
    but I don't quite know how to implement that...Also trying to add the
    status code processing/error handling, but I'm not sure how to do that
    for multiple/different errors, such as 404, 503, 504, ect.. try/catch statements?
    So yeah, just been scratching my head on this trying to figure out how to work it..
    If you can help me out on this, I've been going nuts trying to figure this out...

    I think your issue comes form the fact that you are not casting URLConnection to HttpURLConnection.
    Doing the cast would allow you to use getResponseCode() - among other methods - and test for a response different than 200.
    Read: [http://mindprod.com/jgloss/urlconnection.html|http://mindprod.com/jgloss/urlconnection.html]

Maybe you are looking for

  • How to email PDF form as an attachment?

    Hi All, I have developed online interactive form app(dynamic). When user clicks the submit button after entered the data, I want to email the PDF form as an attachment to some users. Could anyone please explain the steps or give me some sample code?

  • TV out function

    Hi I've got the MX440-t8x video card on the MSI K7N2 Delta motherboard. My monitor is fine but Im trying to connect to a tv in another room using an s video to scart lead. I get nothing on the av channel of the tv, do i need to enable anthing to use

  • UTF8 and Traditional chinese display problem

    I have having problems displaying chinese because I am trying to pull data from 2 difference sources into a 3rd source. Question 1 I am using Oracle 8.17 on Sun Solaris - (in China). The NLS_LANG on that machine (Machine name is CNCIM) is American. T

  • Regaring code ,its urgent

    hi, i had amde dis code for displaying the changes made on material in purticular month,70% report is working fine but problem is dat when i want to see the deatils of changes made to it ,it is not displaying all records,i.e. if dere are 5 changes ma

  • Forms 5 Open API Problem

    How can the displayed text of an existing Graphics Text (Boilerplate) be modified with Open API functions? All(?) properties of all Forms objects can be modified with function calls similar to the calls in the example below. Just this one seems impos