HttpConnection.getResponseCode - MIDP bug?

Hi!
Try the following:
-make some example trying to connect to a valid Url...
-verify your connection...
-now make sure that is working properly.
-turn off your Ethernet cable or ISP connection
-Try to run the same example now.
The IOException is raised.... Iwonder Why??? The returned response code should be 503 HTTP_UNAVAILABLE .... Is this a MIDP bug or am I missing something?
public boolean verifyConnection(HttpConnection conn) throws IOException
          boolean res=false;
          if (conn==null)
               sConError="Null Connection";
               res=false;
          else
//System.out.println("1a" + conn.getURL() + conn.getResponseMessage());
               int rc;
               rc=conn.getResponseCode(); //Here's the problem when I'am not connected to the internet and try to make a Connection to an outside Site....
               sConError="";
               switch( rc )
                    case HttpConnection.HTTP_OK:
                         res=true;
                         break;
                    case HttpConnection.HTTP_TEMP_REDIRECT:
                         res=true;
                         break;
                    case HttpConnection.HTTP_ENTITY_TOO_LARGE:
                         res=false;
                         break;
                    default:
                         sConError=conn.getResponseMessage();
                         res=false;
                         break;
System.out.println("3a");          
          return res;
Marco

I could be wrong on this....
The response code comes from the web server. If you disconnect your internet connection your MIDlet is no longer able to establish a connection to the web-server therefore it gets an IOException.

Similar Messages

  • HttpConnection.getResponseCode() return -1

    Hi guy's
    I am developing a midp application which is communicate with server and display the result on the client using HttpConnection.Basically i am from bangalore,India and using Airtel,Vodafone connections for GPRS. My jar file is properly working in the Sony Ericsson models(k800i,k310i) with airtel and vodafone connections. But the same jar file is failed to communicate with server in Nokia models. HttpConnection.getResponseCode() return -1 in Nokia 6020,6070,6300 devices. Even N6030 is also return same value with vodafone. But same time application working fine in another 6030 model with airtel. Please look at my source code below.
    private static String requestToServer(final String url, final String data)throws IOException {
    HttpConnection httpCon = null;
    InputStream inputStream = null;
    String result = null;
    try {
    while (true) {
    httpCon = (HttpConnection) Connector.open(connectionUrl,Connector.READ_WRITE);
    httpCon.setRequestMethod(HttpConnection.POST);
    final String conf = System.getProperty("microedition.configuration");
    final String prof = System.getProperty("microedition.profiles");
    httpCon.setRequestProperty("User-Agent","Profile/" + prof + " Configuration/" + conf);
    writeDataToConnection(httpCon, data);
    if (!isRedirectResponse(httpCon)) {
    break;
    connectionUrl = httpCon.getHeaderField("Location");
    httpCon.close();
    inputStream = httpCon.openInputStream();
    result = readStreamData(inputStream);
    } catch (final ClassCastException e) {
    throw new IllegalArgumentException("Not an HTTP URL"); }
    catch (final IOException e) { throw e; }
    catch (final Exception e) { throw e; }
    finally {
    if (inputStream != null) { inputStream.close(); }
    if (httpCon != null) { httpCon.close(); }
    return result;
    private static void writeDataToConnection(final HttpConnection c, final String data) throws IOException {
    final OutputStream os = c.openOutputStream();
    try {
    final DataOutputStream dos = new DataOutputStream(os);
    dos.writeUTF(data);
    dos.flush();
    catch(IOException e) { throw e; }
    finally { os.close(); }
    private static boolean requestToServer(final HttpConnection httpCon)throws IOException {
    boolean result = false;
    final int conResponseCode = httpCon.getResponseCode();
    switch (conResponseCode) {
    case HttpConnection.HTTP_OK:
    result = false;
    break;
    case HttpConnection.HTTP_MOVED_TEMP:
    if (DEBUG_REDIRECT) {
    System.out.println("Request is redirected"); }
    result = true;
    break;
    default:
    throw new IOException("HTTP response code: " + conResponseCode);
    return result;
    In the Nokia models, the httpCon.getResponseCode() return -1. Can anybody tell me, whats the problem and what the solution for this please.
    Regards,
    Jobin

    use this ---> return new int[]{1,3};

  • IOException when trying to read HttpConnection input (MIDP 2.0-CLDC 1.0)

    Hello!
    I'm using the Java ME Platform SDK 3.0, on a Windows XP machine.
    The midlet's code runs successfully with the emulator, but when i execute it on my motorola c650 (MIDP 2.0-CLDC 1.0), whenever i call the getInputStream method, it hangs for a while (say, 1 second), and then i get an IOException at that point.
    I already tried:
    - call getResponseCode before; i get an IOException at that point
    - use POST method instead of GET
    - call openOutputStream before openInputStream
    - use getDataInputStream instead of getInputStream
    HttpConnection c = (HttpConnection)Connector.open(url);
    c.setRequestMethod(HttpConnection.GET);
    InputStream is = c.openDataInputStream();
    ...Nothing helps... but the same code works on a motorola v3 black (MIDP 2.0-CLDC 1.1)
    Thanks in advance!

    Oh,
    these are a little bit old handsets, aren't they?
    Anyway I can remember that especially on C650 we've experienced some firmware issues. However if this happens also on V3 I can only recomend to check the access point configuration. These old motorolas must be set up correctly and differently for using internal browser (using a WAP access point) and differently for using from within Java applications (using an internet access point).
    Rada

  • HttpConnection.getResponseCode generates a Connection Refused exeption

    I have the following problem:
    I connect to a webserver, this works fine. Then I write data to the webserver, this also works fine. After writing the data, I determine the http response code to see if everything was successfull. Every so often this generates a "connection refused" exception. This happens even after the connect and the write were successfull. I find this strange, since I was able to connect and write data (this data has arrived at the server because I can log it there without a problem).
    Can anyone explain this behaviour to me, because I am lost here.
    Mark

    Have found that wildcard addresses matches any address of the local system, and that in IPv4, the wildcard address is 0.0.0.0. Can check for this with InetAddress.isAnyLocalAddress().
    This means that I could potentially handle these cases by adding code to "ping" a host such as "tigers.com.au" using
    InetAddress address = InetAddress.getByName(name);
    if (InetAddress.isAnyLocalAddress() {
    .... do something, eg raise exception
    }But this is not fully satisfactory, as I would rather know that a "connection refused" exception is raised, which is actually the case with "tigers.com.au" (as all the browsers seem able to detect). I am not entirely sure what the relationship is between a site that has "connection refused" and it returning an ip address of 0.0.0.0. I don't think they are synonymous.
    Any thoughts?

  • HttpConnection hangs in my T630. Please Help !

    Hi all,
    I`ve noticed this problem in a few threads on this forum, but none of them seem to have a definitive answer. Maybe we can answer it once and for all here :-) Any help would be greatly appreciated.
    I`m trying to load a web page from a midlet in my T630. As I don`t really want to pay for call charges during development, I`m using the "Device Explorer" and the "Connection proxy" to try and connect to the internet using my broadband connection. I'm using the SonyEricsson developer kit (version 1) and I'm using a bluetooth serial connection on COM5 for the connection proxy.
    I've based my code on some sample code from Sun to load some info from a web page. This code was even published to get around the IO blocking problem that I seem to be getting still !
    The problem is when I try and use the HttpConnection.getResponseCode() method. Using the advice of other internet resources, I`ve put this code in its own thread. When I call HttpConnection.getResponseCode(), my T630 then pops ups with a menu, offering me these 3 options:
    Allow Web access
    Ask per access
    Deny Web access
    When this happens, it`s as if the thread running the getResponseCode() method blocks, and the T630 OS takes over. When I select an item from that menu, control does not pass back to the thread running getResponseCode(), but goes to the main midlet thread. Once I`m back in the main midlet thread, I don't know how to wake up the url loading thread. Does anyone have any ideas.
    My debugging statements produce the following before the app hangs:
    url=http://java.sun.com
    conn=com.sun.midp.io.j2me.http.Protocol@e4857a1d
    here
    Connecting to http://java.sun.comHere is the source code:
    package com.pg.midp.http;
    import java.io.IOException;
    import javax.microedition.io.Connector;
    import javax.microedition.io.HttpConnection;
    import javax.microedition.lcdui.Alert;
    import javax.microedition.lcdui.Command;
    import javax.microedition.lcdui.CommandListener;
    import javax.microedition.lcdui.Display;
    import javax.microedition.lcdui.Displayable;
    import javax.microedition.lcdui.Form;
    import javax.microedition.lcdui.StringItem;
    import javax.microedition.lcdui.TextBox;
    import javax.microedition.midlet.MIDlet;
    import javax.microedition.midlet.MIDletStateChangeException;
    // Simple class that connects to a given URL and
    // prints out the response code and any headers
    // that are sent back. Shows how to use background
    // threads to make HTTP connections while keeping the
    // user interface alive.
    public class HttpLogger extends MIDlet
         private Display display;
         private Command exitCommand = new Command([quot][/quot]Exit[quot][/quot], Command.EXIT, 1);
         private Command okCommand = new Command([quot][/quot]OK[quot][/quot], Command.OK, 1);
         private Command cancelCommand = new Command([quot][/quot]Cancel[quot][/quot], Command.CANCEL, 1);
         private URLEntry mainForm;
         // Standard MIDlet stuff....
         public HttpLogger()
         protected void debug(String s)
              System.out.println(s);
         protected void destroyApp(boolean unconditional) throws MIDletStateChangeException
              exitMIDlet();
         protected void pauseApp()
         protected void startApp() throws MIDletStateChangeException
              if (display == null)
                   initMIDlet();
         private void initMIDlet()
              display = Display.getDisplay(this);
              mainForm = new URLEntry();
              display.setCurrent(mainForm);
         public void exitMIDlet()
              notifyDestroyed();
         // Utility routine to display exceptions.
         void displayError(Throwable e, Displayable next)
              Alert a = new Alert([quot][/quot]Exception[quot][/quot]);
              a.setString(e.toString());
              a.setTimeout(Alert.FOREVER);
              display.setCurrent(a, next);
         // Simple entry form for entering the URL to
         // connect to.
         class URLEntry extends TextBox implements CommandListener
              URLEntry()
                   super([quot][/quot]Enter URL:[quot][/quot], [quot][/quot]java.sun.com[quot][/quot], 100, 0);
                   addCommand(exitCommand);
                   addCommand(okCommand);
                   setCommandListener(this);
              public void commandAction(Command c, Displayable d)
                   if (c == exitCommand)
                        exitMIDlet();
                   else if (c == okCommand)
                        try
                             String url = [quot][/quot]http://[quot][/quot] + getString();
                             debug([quot][/quot]url=[quot][/quot] + url);
                             HttpConnection conn = (HttpConnection) Connector.open(url);
                             debug([quot][/quot]conn=[quot][/quot] + conn);
                             Logger logger = new Logger(this, conn);
                             debug([quot][/quot]here[quot][/quot]);
                             display.setCurrent(logger);
                        catch (IOException e)
                             displayError(e, this);
         //      Simple form that contains a single string item.
         //      The string item is updated with status messages.
         //      When constructed, it starts a background thread
         //      that makes the actual HTTP connection. Displays
         //      a Cancel command to abort the current connection.
         class Logger extends Form implements Runnable, CommandListener
              private Displayable next;
              private HttpConnection conn;
              private StringItem text = new StringItem(null, [quot][/quot][quot][/quot]);
              boolean done = false;
              Thread t;
              Logger(Displayable next, HttpConnection conn)
                   super([quot][/quot]HTTP Log[quot][/quot]);
                   this.next = next;
                   this.conn = conn;
                   addCommand(cancelCommand);
                   setCommandListener(this);
                   append(text);
                   t = new Thread(this);
                   t.start();
              // Handle the commands. First thing to do
              // is switch the display, in case closing/
              // the connection takes a while...
              public void commandAction(Command c, Displayable d)
                   display.setCurrent(next);
                   try
                        conn.close();
                   catch (IOException e)
                        displayError(e, next);
              // Do the connection and processing on
              // a separate thread...
              public void run()
                   try
                        update([quot][/quot]Connecting to [quot][/quot] + conn.getURL());
                        try
                             int rc = conn.getResponseCode();
                             update([quot][/quot]Response code: [quot][/quot] + rc);
                             update([quot][/quot]Response message: [quot][/quot] + conn.getResponseMessage());
                             String key;
                             for (int i = 0; (key = conn.getHeaderFieldKey(i)) != null; ++i)
                                  update(key + [quot][/quot]: [quot][/quot] + conn.getHeaderField(i));
                        catch (IOException e)
                             update([quot][/quot]Caught exception: [quot][/quot] + e.toString());
                   catch (Exception e)
                        debug(e.getMessage());
                        e.printStackTrace();
                   finally
                   done = true;
                   removeCommand(cancelCommand);
                   addCommand(okCommand);
              // Update the string item with new information.
              // Only do it if we're actually visible.
              void update(String line)
                   debug(line);
                   if (display.getCurrent() != this)
                        return;
                   String old = text.getText();
                   StringBuffer buf = new StringBuffer();
                   buf.append(old);
                   if (old.length() [gt][/gt] 0)
                        buf.append('\n');
                   buf.append(line);
                   text.setText(buf.toString());
    }Thanks,
    Paul.

    Hi, Paulgrime:
    These days I also have struggled with the problem.
    I just saw a java example from SUN site, which does not use getResponseCode(). It seems a good work around.
    I tried that way and works fine. Only thing is you have to figure out the response status by analysing the inputstream content, which is actually easy.
    So I go this way now.
    Huiyi

  • HttpConnection Charset

    Hello guys!
    I tried a lot of times to send chinese characters using HttpConnection in j2me, but I have failed. :(
    I tried in this way: I wrote a MIDlet using the HttpConnection, but when the data arrived in the servlet, the servlet receives a <null> String or an other character.
    I ask to a friend, and he told me to change the charset using setRequestProperty methos in the HttpConnection.
    I changed all values using the charset values from: http://a4esl.org/c/charset.html
    but I have failed again, sometimes the MIDlet send a null String, sometimes I got a java.io.UnsupportedEncodingException...
    If I sent the characters from the servlet directly to the MIDlet, woks... but I want to get the values from the MIDlet first, and them send the response...
    Can anybody help me with this problem?
    Thanks in advance.

    I do not think its a probelm with not specifying encoding format in input stream . I have done a small test for it . I have commented my code of reading the input stream and have just used httpconenctin.dosconnect .
    I ahve changed my code to following
    for(loop)
    String xml request = "xml request..n"
    URL url = new URL(Config.getProperty("url"));
    URLConnection connection = url.openConnection();
    HttpURLConnection httpConnection = (HttpURLConnection) connection;
    httpConnection.setDoOutput(true);
    httpConnection.setDoInput(true);
    httpConnection.setRequestMethod("POST");
    httpConnection.setRequestProperty("Content-Type",
    "application/soap; charset=\"utf-8\"");
    OutputStream stream = httpConnection.getOutputStream();
    stream.write(request.getBytes());
    stream.close();
    log.debug("Teturned from server::::::::::::::"+ httpConnection.getResponseCode() + "message"
                             + httpConnection.getResponseMessage());
    httpConnection.disconnect();
    }Even with this .. iam getting socket reset exception for multiple requests. The curios part is for sirst request i get the response, but for second request it fails .

  • HTTP POST to PHP server problem

    Hi, im trying post a long string to php from a MIDLET, but i have some problems. When i send the whole String, my php server cant receive the request (i have not any response), but, if the string that i send is 1/5 from the original, the process is successful correctly. have somebody any idea?
    thx

    this is my problem, extracted from another topic on this forum:
    "Hi everyone.
    I have a problem, and hope someone may help me.
    My midlet is uploading sizeable data via http POST.
    I'm using WTK104, since i need MIDP1.0
    The code have been tried on DefaultGrayPhone emulator
    and add-on Nokia's Series 60 Emulator.
    Both emulators chunck data, however in different ways.
    Deafult one simply produces wrong chunk length (possibly a bug),
    Nokia's one always chunks by equal offsets of 2016 bytes.
    I'm not using flushing, just close. All the data is being send
    at once by one output stream write call.
    So I believe (after proper investigation) that MIDP will use chunked Transfer-Encoding method whatever
    on such sizeable a data as mine is (up to 50KB) and there's no way to override this behaviour.
    Here the main problem appears - Apache refuses to accept chunked encoding in request. The corresposnding message is given in error log
    *chunked transfer encoding forbidden*. The returned code is 411 - Content-Length requred. I see no way to override this behaviour of Apache. I was trying to upload my data into Zope web-server, which is my primary goal, but it doesn't handle chunked request either.
    Has anyone faced the same problem? Who has managed to POST sizeable data from midlet? Which web servers did you use for that?
    Any inputs are highly appreciated!
    Anton"
    Another:
    "> So I believe (after proper investigation) that MIDP
    will use chunked Transfer-Encoding method whatever
    on such sizeable a data as mine is (up to 50KB) and
    there's no way to override this behaviour.Is this true? When I try to set the content-length headers and then write a large byte[] to the output stream I got from an HttpConnection, the HttpConnection appears to remove the content-length header altogether and automatically sets the transfer-encoding to chunked.
    Note- I am not calling flush on the outputstream, but I am calling httpconnection.getResponseCode, which I believe calls flush on the outputstream.
    Abraham"
    I have the identical problem.

  • J2ME network error

    hi! i'm doing a small app for mobile devices, with j2me, netbeans5.0+mobility pack.
    the problem is
    String url = "http://www.google.ro/";
    try {
          HttpConnection httpConnection =
                (HttpConnection) Connector.open(url, Connector.READ);
          if (httpConnection.getResponseCode() == HttpConnection.HTTP_OK) {
                // i do something around here
            // doing some more of something
    } catch (Exception e) {
              e.printStackTrace();
    }javax.microedition.io.ConnectionNotFoundException: TCP open
    this is what i get when the program reaches httpConnection.getResponseCode() . i read that it's because a connection could not be established, or somethink like this, maybe because of a firewall or something else.
    well, it so happens i connect to the internet through a proxy. but i tried starting the app with parameters like:
    -Dhttp.proxyHost=192.168.xxx.xxx -Dhttp.proxyPort=8080
    yet it still doesn't work. i get the same error.
    what am i doing wrong? please help.
    thank you

    i tryied the same project with java wireless tookit, because it has proxy settings. however, i still get an error:
    java.io.IOException: Error initializing HTTP tunnel connection:
    HTTP/1.0 403 Forbidden
    Server: squid/2.5.STABLE3
    Mime-Version: 1.0
    Date: Sun, 12 Feb 2006 05:46:12 GMT
    Content-Type: text/html
    Content-Length: 1045
    Expires: Sun, 12 Feb 2006 05:46:12 GMT
    X-Squid-Error: ERR_ACCESS_DENIED 0
    X-Cache: MISS from "myproxy-edited"
    Proxy-Connection: close
    at com.sun.midp.io.j2me.http.Protocol.doTunnelHandshake(+279)
    at com.sun.midp.io.j2me.http.Protocol.connect(+145)
    at com.sun.midp.io.j2me.http.Protocol.streamConnect(+57)
    at com.sun.midp.io.j2me.http.Protocol.startRequest(+12)
    at com.sun.midp.io.j2me.http.Protocol.sendRequest(+38)
    at com.sun.midp.io.j2me.http.Protocol.sendRequest(+6)
    at com.sun.midp.io.j2me.http.Protocol.getResponseCode(+8)
    PLEASE HELP

  • OBIEE integrated to Mapviewer , need advice from expert people in my codes

    <!--[if !mso]>
    <style>
    v\:* {behavior:url(#default#VML);}
    o\:* {behavior:url(#default#VML);}
    w\:* {behavior:url(#default#VML);}
    .shape {behavior:url(#default#VML);}
    </style>
    <![endif]--><!--[if gte mso 9]><xml>
    Normal
    0
    false
    false
    false
    MicrosoftInternetExplorer4
    </xml><![endif]--><!--[if gte mso 9]><xml>
    </xml><![endif]--><!--[if !mso]>
    <object
         classid="clsid:38481807-CA0E-42D2-BF39-B33AF135CC4D" id=ieooui>
    </object>
    <style>
    st1\:*{behavior:url(#ieooui) }
    </style>
    <![endif]-->
    <!--[if gte mso 10]>
    <style>
    /* Style Definitions */
    table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;}
    </style>
    <![endif]-->
    Based on Example : [http://www.oracle.com/technology/products/mapviewer/pdf/mapviewer_obiee.pdf|blocked::http://www.oracle.com/technology/products/mapviewer/pdf/mapviewer_obiee.pdf]
    *1- Using OBIEE , I create report with two fields and it's filter on
    field Region:*
    Region , Population
    <!--[if !mso]>
    <style>
    v\:* {behavior:url(#default#VML);}
    o\:* {behavior:url(#default#VML);}
    w\:* {behavior:url(#default#VML);}
    .shape {behavior:url(#default#VML);}
    </style>
    <![endif]--><!--[if gte mso 9]><xml>
    Normal
    0
    false
    false
    false
    MicrosoftInternetExplorer4
    </xml><![endif]--><!--[if gte mso 9]><xml>
    </xml><![endif]-->
    <!--[if gte mso 10]>
    <style>
    /* Style Definitions */
    table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;}
    </style>
    <![endif]-->
    On OBIEE Answers: Statistic Text , I wrote this codes :
    &lt;!-div id must match arg in js call at bottom of code listing --&gt;
    &lt;div id="EPAmapNode1"&gt;&lt;/div&gt;
    &lt;script&gt;
    function readCookie(name) {
    //this pulls authentication out of header
    //which replaces needing to pass user/pwd
    to authenticate (i.e. like SSO or trusted sign on)
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i &lt; ca.length;i++) {
    var c = ca;
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    return null;
    function obiee_mapint_doTheDeed(nodeId) {
    var container = document.getElementById(nodeId);
    var sid = null;
    var x = container;
    do {
    if (x.nodeName == 'TD' || x.nodeName == 'DIV') {
    sid = x.getAttribute('sid');
    if (sid != null && sid != '')
    break;
    x = x.parentNode;
    while (x != null);
    if (sid != null && sid != '') {
    // create the iframe for content
    var nid = readCookie('nQuireID')
    if (nid) {
    var iframe = document.createElement('iframe');
    iframe.src =
    'http://192.168.100.143:8991/yusufMap-ViewController-context-root/BIMapPage.html?sid='
    + encodeURIComponent(sid) + '&nqid=' + nid;
    // following nsdp is subsequently called
    from Mapviewer page
    // passing sid and nqid to get results to
    serve as nsdp data as xml
    // ps["xml_url"] = "http://"+document.location.host+"/mapviewer/_epa/obiee_nsdp_xml_direct.jsp?nqid="
    +
    // urlParamNQID + "&sid=" +
    urlParamSID;
    iframe.height = 260;
    iframe.width = 600;
    iframe.frameBorder = 0;
    iframe.marginHeight = 1;
    iframe.marginWidth = 1;
    container.appendChild(iframe);
    obiee_mapint_doTheDeed('EPAmapNode1');
    // js fn, EPAmapNode1 is id for this map in
    dashbd
    &lt;/script&gt;
    *2-Source code of
    custom JSP to convert Answers Filtered XML into NSDP XML: obiee_nsdp_xml_direct.jsp*
    &lt;%@ page
    language="java" session="true"
    isThreadSafe="true" contentType="text/html; charset=UTF-8"
    %&gt;
    &lt;%@ page
    import="javax.xml.parsers.*"%&gt;
    &lt;%@ page
    import="java.net.*"%&gt;
    &lt;%@ page
    import="java.io.*"%&gt;
    &lt;%@ page
    import="org.w3c.dom.*"%&gt;
    &lt;%
    Sample jsp code file to demonstrate one way to convert Answers xml to
    MapViewer's NSDP xml
    set the character encoding to UTF-8 prior to accessing
    data in the request
    request.setCharacterEncoding("UTF-8");
    %&gt;
    &lt;%
    // RETRIEVE THE QUERY
    STRING PARAMETERS
    String userName =
    request.getParameter("uid");
    String userPassword =
    request.getParameter("password");
    String thesid =
    request.getParameter("sid");
    String nq_id =
    request.getParameter("nqid");
    if (userName == null) {
    userName =
    "mvdemo";
    if (userPassword == null)
    userPassword =
    "mvdemo";
    Document domDoc = null;
    String fieldName = null;
    String urlString =
    "http://192.168.100.143:9704/analytics/saw.dll?Go&searchid=" +
    thesid + "&format=xml&NQId=" + nq_id;
    if (thesid != null) {
    DocumentBuilderFactory
    dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db =
    dbf.newDocumentBuilder();
    URL url = new URL(urlString);
    URLConnection
    URLconnection = url.openConnection();
    HttpURLConnection
    httpConnection = (HttpURLConnection)URLconnection;
    int responseCode =
    httpConnection.getResponseCode();
    if ( responseCode ==
    HttpURLConnection.HTTP_OK) {
    InputStream in =
    httpConnection.getInputStream();
    System.out.println("thesid=
    " + thesid);
    System.out.println("nq_id="
    + nq_id);
    System.out.println("server
    host=" + request.getRemoteHost());
    System.out.println("server
    addr=" + request.getRemoteAddr());
    domDoc = db.parse(in);
    } else {
    System.out.println(
    "HTTP connection response != HTTP_OK" );
    out.println("&lt;nsdp_xml&gt;");
    out.println("&lt;table&gt;");
    //Iterate
    through metadata object and create the ndsp_xml header
    NodeList rowDef =
    domDoc.getElementsByTagName("element");
    out.println("&lt;tr&gt;");
    out.println("&lt;th&gt;Column
    1&lt;/th&gt;&lt;th&gt;Column 2&lt;/th&gt;");
    out.println("&lt;/tr&gt;");
    //Iterate
    through rows & items and create the ndsp_xml body
    NodeList rows =
    domDoc.getElementsByTagName("R");
    if (rows != null) {
    for (int i = 0; i &lt;
    rows.getLength(); i++) {
    out.println("&lt;tr&gt;");
    Node row = rows.item(i);
    if (row == null ||
    row.getNodeType() == Node.TEXT_NODE) {
    continue;
    NodeList items =
    row.getChildNodes();
    if (items == null) {
    continue;
    for (int y = 0; y &lt; 2;
    y++) {
    Node item =
    items.item(y);
    if (item == null ||
    item.getChildNodes() == null)
    continue;
    if (item.getChildNodes()
    == null
    ||
    item.getChildNodes().item(0) == null
    || item.getNodeType()
    == Node.TEXT_NODE)
    continue;
    out.println("&lt;td&gt;"
    +
    item.getChildNodes().item(0).getNodeValue()
    + "&lt;/td&gt;");
    out.println("&lt;/tr&gt;");
    } else {
    out.println("No
    rows.");
    out.println("&lt;/table&gt;");
    out.println("&lt;/nsdp_xml&gt;");
    %&gt;
    *3- Where the source Code of map I created on HTML : BIMapPage.html*
    &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
    Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
    &lt;html&gt;
    &lt;head&gt;
    &lt;meta
    http-equiv="Content-Type" content="text/html;
    charset=windows-1252"&gt;&lt;/meta&gt;
    &lt;title&gt;BI Map
    Page&lt;/title&gt;
    &lt;script
    language="Javascript" src="oraclemaps.js"&gt;&lt;/script&gt;
    &lt;script
    language="Javascript"&gt;
    var dynStatesFOI;
    function show_map(){
    var map;
    var homeCenter,
    homeZoomLevel;
    var baseURL =
    "http://192.168.100.143:9704/mapviewer";
    map = new
    MVMapView(document.getElementById("map"), baseURL);
    var mapSRID = 82364;
    var mapCenterLon = 538940.5;
    var mapCenterLat = 2690457.4;
    homeZoomLevel = 1;
    homeCenter =
    MVSdoGeometry.createPoint(mapCenterLon, mapCenterLat, mapSRID);
    map.addMapTileLayer(new MVMapTileLayer("tcg_gis.ksa_map"));
    map.setCenter(homeCenter, false);
    map.setZoomLevel(homeZoomLevel);
    map.setHomeMap(homeCenter, homeZoomLevel);
    map.addNavigationPanel("East");
    map.addScaleBar();
    dynStatesFOI = new
    MVThemeBasedFOI('dynStatesFOI','tcg_gis.KSA_POP2');
    dynStatesFOI.setRenderingStyle("C.COUNTIES");
    setupNsdp(dynStatesFOI);
    setupDynamicStyles(dynStatesFOI,250000,
    500000, 750000);
    map.addThemeBasedFOI(dynStatesFOI);
    map.display();
    function setupNsdp(dynStatesFOI)
    var nsdpInfo = new
    MVNSDP("defaultNSDP");
    nsdpInfo.setTheme("KSA_POP2"); //the base theme
    nsdpInfo.setKeyColumn("REGION_NAME");
    //'match' column in the base table of the theme
    nsdpInfo.setRenderStyle("C.COUNTIES"); //default style;
    var ps = new Object();
    {color:#ff0000}
    ps["xml_url"] ="http://192.168.100.143/mapviewer/obiee_nsdp_xml_direct.jsp?nqid=" + urlParamNQID
    + "&sid=" + urlParamSID;{color} *{color:#800000}// &lt;== Error line {color}*
    nsdpInfo.setParameters(ps);
    dynStatesFOI.setNSDP(nsdpInfo);
    //setups the dynamically created advanced
    style to
    //be used by the theme-based FOI.
    function setupDynamicStyles(dynStt,val1, val2, val3)
    var buckets = new
    Array(4);
    buckets[0] = new
    MVNumericRangedBucket(100000, val1, "C.COLOR_BLUE",
    "range1");
    buckets[1] = new
    MVNumericRangedBucket(val1, val2, "C.COLOR_GREEN", "range2");
    buckets[2] = new
    MVNumericRangedBucket(val2, val3, "C.COLOR_RED", "range3");
    buckets[3] = new
    MVNumericRangedBucket(val3, null, "C.COLOR_BROWN",
    "range4");
    var bseries = new
    MVBucketSeries("SCHEME_CUSTOM");
    bseries.setBuckets(buckets);
    var bucketSty = new
    MVBucketStyle("region_colors", bseries);
    dynStt.addStyle(bucketSty);
    dynStt.setRenderingStyle("region_colors");
    &lt;/script&gt;
    &lt;/head&gt;
    &lt;body
    onload="javascript:show_map();"&gt;
    Welcome to our Site
    Kingdom of Saudi Arabia
    Map
    &lt;div
    id="map"
    style="width:550.0px; height:500.0px; overflow:auto;
    border-color:rgb(0,0,0);"/&gt;
    &lt;/body&gt;
    &lt;/html&gt;
    {color:#ff0000}
    The
    highlighted line above from function setupNSDP is code line for: NSDP xml
    source to call jsp that invokes java class to convert Answers filtered XML (OBIEE)
    into NSDP XML.
    Where
    its invoke two parameters : 1- urlParamNQID , 2- urlParamSID
    ps["xml_url"] =
    "http://192.168.100.143/mapviewer/obiee_nsdp_xml_direct.jsp?nqid="
    + urlParamNQID + "&sid=" + urlParamSID;
    The
    error when we run this code is: URLParamNQID is not defined ???
    does any of you can read what i wrote in my source codes and let me know what i missed in my html map code : BIMapPage.html and where or how i can get two parameters values URLParamNQID
    and {color}*{color:#ff0000}urlParamSID{color}*{color:#ff0000}?{color}

    yes i checked this site, but i still couldn't reach the answer of my challenge, in how to specify urlParamNQID and urlParamSID , how or where i can get value of these parameters or what should i pass there !?

  • How to get the Response Code when a URL is launched from Web Dynpro

    Hello Experts,
    I have a Web Dynpro Application in which in one of its views i have an IFrame UI element in which i will show a resource stored somewhere ..
    But before showing it i want to check if the resource actually exists. For this i have to check the HTTP Response code from Web Dynpro Application without setting it in the Iframe..
    I am using the following code to get the Response Code:
    try{
    URL url = new URL("Some Url");
    HttpURLConnection.setFollowRedirects(false);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.connect();
    wdComponentAPI.getMessageManager().reportSuccess("Response code ="+connection.getResponseCode());
    }catch(Exception e){
    wdComponentAPI.getMessageManager().reportSuccess("Exception");
    Now the Problem is whatever response Code occurs 403 (for No Proper Authorization), 404 (for Resource not found) etc..
    i always get Response Code=  500 (which is for Internal Server Error) shown in the messgae i have printed.
    Please let me know the correct way of getting the Response Code from Web Dynpro.
    Also my resource is lying on a SAP Portal 6.4
    Best Regards
    Sundeep
    Edited by: Sundeep Sethi on Feb 18, 2008 9:07 AM
    Edited by: Sundeep Sethi on Feb 18, 2008 10:23 AM

    Hi,
      Check this code from /thread/5242768 [original link is broken] if it works.
    try{
    URL myurl = new URL("http://calendar.google.com");
    URLConnection connection = myurl.openConnection();
    if(connection instanceof HttpURLConnection) {
    HttpURLConnection httpConnection = (HttpURLConnection) connection;
    HttpURLConnection.setFollowRedirects(true);
    httpConnection.setRequestMethod("HEAD");
    httpConnection.connect();
    System.out.println("Response = "+httpConnection.getResponseCode());
    catch(Exception e) {
    // print exception
    Regards,
    Harini S

  • HttpURLConnection , Response Code : 404 for HTTP method HEAD  302 for GET

    After establishing the connection For the URL : http://calendar.google.com/ the response code is different for different HTTP METHODS.
    For the method HEAD the response code is 404
    For the method GET the response code is 302
    Ideally according to W3 standards the header part for both methods should be same.
    www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
    Unfortunately all the websites are not following the same standards.
    The above brings up an important issue.
    (i.e) soley depending on the HEAD method for checking the validity of the link may fail sometimes even if the link is
    valid.
    Please put up your comments and observations on this.
    Sample Code
    public static void main(String[] args) {
    try{
    URL myurl = new URL("http://calendar.google.com");
    URLConnection connection = myurl.openConnection();
    if(connection instanceof HttpURLConnection) {
    HttpURLConnection httpConnection = (HttpURLConnection) connection;
    HttpURLConnection.setFollowRedirects(true);
    httpConnection.setRequestMethod("HEAD");
    httpConnection.connect();
    System.out.println("Response = "+httpConnection.getResponseCode());
    catch(Exception e) {
    System.out.println(e);
    Edited by: rama.krishna on Dec 3, 2007 3:47 AM

    Iam not encountering any problem.It's just a discussion.

  • Basic webpage link checker

    Hello all,
    I am attempting to write a basic link checker to parse an html page and determine if any links are dead. I found a couple tutorials online, and am using one of them to test a webpage. However, i am running into multiple problems. The basic link checker verifies links by using the http HEAD request, it then checks the response code and determines from there if the link is dead.
    However, I have two major problems with this:
    1) How can I verify links when they are not using http, for instance a ftp link on a webpage?
    2) Sometimes when I parse link, i am losing the protocol from the link....
    ie. href="http://www.ibm.com/systems/x/=>href="//www.ibm.com/systems/x/"
                 Reader rd = getReader(rootURI);
                  // Parse the HTML.
                  kit.read(rd, doc, 0);
                  // Iterate through the elements
                  // of the HTML document.
                  ElementIterator it = new ElementIterator(doc);
                  javax.swing.text.Element elem;
                  System.out.println("Starting Validation from: " + rootURI);
                  while ((elem = it.next()) != null) {
                    SimpleAttributeSet s = (SimpleAttributeSet)elem.getAttributes().getAttribute(HTML.Tag.A);
                    if (s != null) {
                      System.out.println("attributeSet: " + s);
                      String link = (String)s.getAttribute(HTML.Attribute.HREF);
                      System.out.println("Validating: " + link);
                      validateHref(link);
                    }else{
                      //System.out.println("Attribute set is empty");
                      //flag this to user
                  }This is the block of code i am using to extract the link from the html source. My console output looks like this:
    [stdout]
    attributeSet: href=//www.ibm.com/systems/x/ class=left-nav-overview
    Validating: //www.ibm.com/systems/x/
    [stdout]
    However, looking at the html source, the link should be http protocol....ie. http://www.ibm.com/systems/x , since i later check to make sure that http protocal urls start with "http:", these links that do not have http: at the beginning are being ignored...
    Can someone please help and explain to me how I can fix this? Also, i am eventually planning to turn this into more of a web spider, and traverse levels of pages checking and validating the links.
    Thank you,
    Nick

    heres the full source. Let me know if theres anything else to make my questions more clear. Thanks!
        import java.io.*;
        import java.net.*;
        import javax.swing.text.*;
        import javax.swing.text.html.*;
    public class enhanceLinkCheck {
           static int failCnt = 0;
          public static void main(String[] args) {
              HttpURLConnection.setFollowRedirects(false);
              EditorKit kit = new HTMLEditorKit();
              Document doc = kit.createDefaultDocument();
              // The Document class does not yet
              // handle charset's properly.
              doc.putProperty("IgnoreCharsetDirective",
                Boolean.TRUE);
               try{
                    //String rootURI = "http://www-304.ibm.com/jct01004c/systems/support/supportsite.wss/docdisplay?lndocid=MIGR-65651&brandind=5000008#osa";
                    String rootURI = "http://www-304.ibm.com/jct01004c/systems/support/supportsite.wss/docdisplay?lndocid=MIGR-65665&brandind=5000008";
                  // Create a reader on the HTML content.
                  Reader rd = getReader(rootURI);
                  // Parse the HTML.
                  kit.read(rd, doc, 0);
                  // Iterate through the elements
                  // of the HTML document.
                  ElementIterator it = new ElementIterator(doc);
                  javax.swing.text.Element elem;
                  System.out.println("Starting Validation from: " + rootURI);
                  while ((elem = it.next()) != null) {
                    SimpleAttributeSet s = (SimpleAttributeSet)elem.getAttributes().getAttribute(HTML.Tag.A);
                    if (s != null) {
                      System.out.println("attributeSet: " + s);
                      String link = (String)s.getAttribute(HTML.Attribute.HREF);
                      System.out.println("Validating: " + link);
                      validateHref(link);
                    }else{
                      //System.out.println("Attribute set is empty");
               }catch (Exception e){
                    e.printStackTrace();
               System.out.println("Failed links: " + failCnt);
               System.exit(1);          
          // Returns a reader on the HTML data. If 'uri' begins
          // with "http:", it's treated as a URL; otherwise,
          // it's assumed to be a local filename.
            static Reader getReader(String uri)
              throws IOException {
              if (uri.startsWith("http:")) {     
                // Retrieve from Internet.
                URLConnection conn = new URL(uri).openConnection();
                return new InputStreamReader(conn.getInputStream());
                }else {
                  // Retrieve from file.
                  return new FileReader(uri);
            private static void validateHref(String urlString){
                 if((urlString != null) && (urlString.startsWith("http://"))){
                      try{
                           URL url = new URL(urlString);
                           URLConnection connection = url.openConnection();
                           if(connection instanceof HttpURLConnection){
                                HttpURLConnection httpConnection = (HttpURLConnection)connection;
                                httpConnection.setRequestMethod("HEAD");
                                httpConnection.connect();
                                int response = httpConnection.getResponseCode();
                                if(response >=400){
                                     System.out.print("[FAILED]");
                                     failCnt++;
                                System.out.println("Response: " + response);
                                String location = httpConnection.getHeaderField("Location");
                                if(location != null){
                                     System.out.println("Location: " + location);
                                System.out.println();                            
                           }else {
                                System.out.println("Connection not HTTP: " + connection);
                      }catch (IOException e){
                           e.printStackTrace();
    }

  • EventSender dosen't work properly

    Hi B1i Experts,
    When I first start the EventSender service (after shutdown), the SB1 system try to send some documents to B1iSN, but after a while, the service dosn't work and i get the following exception:
    03-jun-2010 13:23:31 com.sap.b1i.eventsender.EventSender$EventSenderSession doSend
    GRAVE: [<database>] B1EventSubscriberException:
    com.sap.b1i.eventsender.B1EventSubscriberException:
         at com.sap.b1i.eventsender.B1HttpSubscriber.update(B1HttpSubscriber.java:46)
         at com.sap.b1i.eventsender.B1EventPublisher.notifySubscribers(B1EventPublisher.java:133)
         at com.sap.b1i.eventsender.EventSender$EventSenderSession.doSend(EventSender.java:336)
         at com.sap.b1i.eventsender.EventSender$EventSenderSession.run(EventSender.java:223)
         at com.sap.b1i.eventsender.EventSender.execute(EventSender.java:143)
         at com.sap.b1i.eventsender.EventSenderApplication.runPublisher(EventSenderApplication.java:63)
         at com.sap.b1i.eventsender.EventSenderApplication.main(EventSenderApplication.java:78)
    Caused by: com.sap.b1i.eventsender.http.HttpClientException: HTTP request failed:HTTP/1.1 500 Internal Server Error
         at com.sap.b1i.eventsender.http.HttpConnection.getResponseCode(HttpConnection.java:552)
         at com.sap.b1i.eventsender.http.HttpConnection.requestPost(HttpConnection.java:512)
         at com.sap.b1i.eventsender.http.HttpClient.sendEvents(HttpClient.java:109)
         at com.sap.b1i.eventsender.B1HttpSubscriber.update(B1HttpSubscriber.java:44)
    Can anyone help to solve the problem?
    Thanks in advance.
    Jose

    Hello Yatsee,
    We have seen some B1 documents in B1iSN via: Integration application explorer -> B1 Event monitor under tab "Filtered". It seens that the EventSender is working few seconds after the restart, and then, it goes down. From this moment on, we receive the exception shown above constantly (I guest every 3seconds that is the configuration time) and documents are trapped in table SEVT.
    In order to see the error we run the service directly from the windows command console.
    Im not sure but maybe the problem is due to the JAVA VIRTUAL MACHINE version.
    Could you tell us how to check if this problem is due to some java stuff.
    Regards,
    Jose

  • Mixed/multipart Request with a image file and a amr audio file

    Hi people
    I am struggling with multipart/mixed request as i am new to java and http. I basically have to write a java code to send a request with two attachments, an audio amr file and a image file of a proprietry format. following is my code
    public static void GetVideo()
         HttpURLConnection httpConnection = null;
    InputStream bis = null;
         InputStream bis1 = null;
    OutputStream bos = null;
         File audioFile = new File("voicejunk.amr");     
         File avatarFile = new File("out.frf");
         System.out.println("Entered Get Video");
         String Boundary = new String("asdfgh");
    try
    URL url = new URL("http://10.4.21.51:5006/");
    httpConnection = (HttpURLConnection) url.openConnection();
         httpConnection.setRequestProperty("Cache-control", "no-cache");
    httpConnection.setRequestProperty("Pragma", "no-cache");
    httpConnection.setRequestProperty("Content-Type", "multipart/mixed;boundary= \"asdfgh\"");
         httpConnection.setRequestProperty("video-type", "3GPP");
         httpConnection.setRequestProperty("video-encoder", "H.263");
    httpConnection.setRequestProperty("audio-encoder", "AMR-NB");
         httpConnection.setRequestProperty("video-size", "QCIF");
         httpConnection.setRequestProperty("video-fps", "10.0");
         httpConnection.setRequestProperty("video-anti-aliasing","yes");      
         httpConnection.setRequestProperty("Content-Length", Long.toString(audioFile.length()+avatarFile.length()+(3*Boundary.length())));     
         //byte[] bytes = createMessage();
         //httpConnection.setRequestProperty("Content-Length", String.valueOf(bytes.length));     
    //System.out.println("Size of: "+bytes.length);     
         httpConnection.setRequestProperty("Expect", "100-continue");          
         httpConnection.setRequestProperty("Connection", "Keep-Alive");
         //String AvatarType = new String("FRF");     
    httpConnection.setRequestMethod("POST");
         httpConnection.setDoOutput(true);     
         bos = new BufferedOutputStream(httpConnection.getOutputStream());
         bos.write(Boundary.getBytes());
         Session session = Session.getDefaultInstance(new Properties());          
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         Message msg = new MimeMessage(session);
    MimeBodyPart mbp1 = new MimeBodyPart();
    FileDataSource filedatasource1 = new FileDataSource("seestorme.frf");
    DataHandler dh1 = new DataHandler(filedatasource1);
    mbp1.setDataHandler(dh1);
    mbp1.setHeader("Content-Type", "x-seestorm-avatar/frf");
         MimeMultipart mmp = new MimeMultipart();
    mmp.addBodyPart(mbp1);
    msg.setContent(mmp);
    msg.writeTo(baos);
         bos.write(baos.toByteArray());     
    bos.write(Boundary.getBytes());
         ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
         Message msg2 = new MimeMessage(session);     
         MimeBodyPart mbp2 = new MimeBodyPart();
    FileDataSource filedatasource2 = new FileDataSource("voice.amr");
    DataHandler dh2 = new DataHandler(filedatasource2);
    mbp2.setDataHandler(dh2);
    mbp2.setHeader("Content-Type", "audio/amr-nb");
         MimeMultipart mmp2 = new MimeMultipart();
    mmp2.addBodyPart(mbp2);
         msg2.setContent(mmp2);
    msg2.writeTo(baos2);
         bos.write(baos2.toByteArray());     
    bos.write(Boundary.getBytes());          
    //httpConnection.getOutputStream().write(bytes);
         //httpConnection.getOutputStream().flush();
         System.out.println("Request made");
    int result = httpConnection.getResponseCode();
         String Msg1 = new String(httpConnection.getHeaderField(0));
         String Msg2 = new String(httpConnection.getHeaderField(1));
         String Msg3 = new String(httpConnection.getHeaderField(2));
         String Msg4 = new String(httpConnection.getHeaderField(3));     
         String Msg5 = new String(httpConnection.getHeaderField(4));
         System.out.println(Msg1+" " + Msg2+" " + Msg3+" " + Msg4+" " + Msg5+" ");
    if (HttpURLConnection.HTTP_OK == result) {
              System.out.println("Received HTTP result = " + result);
    saveResponseData2(httpConnection.getInputStream(),"SeeStorm.frf");
    } else {
    System.out.println("Received HTTP result = " + result);
         catch (MessagingException me) {
    me.printStackTrace();
    catch (MalformedURLException mue) {
    mue.printStackTrace();
    } catch (ConnectException ce) {
    ce.printStackTrace();
    } catch (IOException ioe) {
         ioe.printStackTrace();
    } finally {
    if (null != bis) {
    try {
    bis.close();
    } catch (IOException ioe) {
    ioe.printStackTrace();
    if (null != httpConnection) {
    httpConnection.disconnect();
    i frankly have no idea how to create a multipart mixed request with boundaries. I get a bad http request error with the above code. Can please someone help me.
    Thanks
    Adil Saleem

    Your WriteImage servlet needs to read the image file in from wherever it is (hard drive, database, whatever), then write it back out to the browser. To do that, first use the HTTPServletResponse object to send the appropriate headers, then call the getOutputStream() method to get an output stream to write the data to. This data will be sent to the browser which, if you've set the headers correctly, will display it as an image.
    It's been a long time since I did this (we abandoned storing images in databases quite a long time ago), so I can't be more specific than that, but hopefully that'll be enough to get you going. If you run into any problems, reply and I'll see if I can help further.

  • OBIEE and Mapviewer

    I just read on the cook book of the OOW last november regarding using OBIEE with Mapviewer. However, I came to one part and I don't know what should put inside the file obiee_nsdp_xml_direct.jsp. Anybody have any idea how to do it? Or this file can be retrieve somewhere?
    Thanks in advance =)

    Sorry, should have included it in the workshop doc. Will be there this time.
    Jerry Conrad wrote it. Hopefully he won't mind it being posted here.
    Note its sample code and hence all the usual disclaimers apply.
    Enclosing the code in CDATA.
    <![CDATA[
    <%@ page language="java" session="true" isThreadSafe="true" contentType="text/html; charset=UTF-8" %>
    <%@ page import="javax.xml.parsers.*"%>
    <%@ page import="java.net.*"%>
    <%@ page import="java.io.*"%>
    <%@ page import="org.w3c.dom.*"%>
    <%
    // Sample jsp code file to demonstrate one way to convert Answers xml to
    // MapViewer's NSDP xml. Author: Jerry Conrad.
    //set the character encoding to UTF-8 prior to accessing
    //data in the request
    request.setCharacterEncoding("UTF-8");
    %>
    <%
    // RETRIEVE THE QUERY STRING PARAMETERS
    String userName = request.getParameter("uid");
    String userPassword = request.getParameter("password");
    String thesid = request.getParameter("sid");
    String nq_id = request.getParameter("nqid");
    if (userName == null) {
         userName = "Administrator";
    if (userPassword == null) {
         userPassword = "Test";
         Document domDoc = null;
         String fieldName = null;     
         String urlString = "http://" + request.getRemoteHost() + ":9704/analytics/saw.dll?Go&searchid=" + thesid + "&format=xml&NQId=" + nq_id;
         if (thesid != null) {
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();
         URL url = new URL(urlString);
         URLConnection URLconnection = url.openConnection();
         HttpURLConnection httpConnection = (HttpURLConnection)URLconnection;
         int responseCode = httpConnection.getResponseCode();
         if ( responseCode == HttpURLConnection.HTTP_OK) {
    InputStream in = httpConnection.getInputStream();
    System.out.println("thesid= " + thesid);
    System.out.println("nq_id=" + nq_id);
    System.out.println("server host=" + request.getRemoteHost());
    System.out.println("server addr=" + request.getRemoteAddr());
              domDoc = db.parse(in);
    } else {
    System.out.println( "HTTP connection response != HTTP_OK" );
         out.println("<nsdp_xml>");
         out.println("<table>");
         //Iterate through metadata object and create the ndsp_xml header
         NodeList rowDef = domDoc.getElementsByTagName("element");
         out.println("<tr>");
         out.println("<th>Column 1</th><th>Column 2</th>");
         out.println("</tr>");
         //Iterate through rows & items and create the ndsp_xml body
         NodeList rows = domDoc.getElementsByTagName("R");
              if (rows != null) {
                   for (int i = 0; i < rows.getLength(); i++) {
                        out.println("<tr>");
                        Node row = rows.item(i);
                        if (row == null || row.getNodeType() == Node.TEXT_NODE) {
                             continue;
                        NodeList items = row.getChildNodes();
                        if (items == null) {
                             continue;
                        for (int y = 0; y < 2; y++) {
                             Node item = items.item(y);
                             if (item == null || item.getChildNodes() == null)
                                  continue;
                             if (item.getChildNodes() == null
                                       || item.getChildNodes().item(0) == null
                                       || item.getNodeType() == Node.TEXT_NODE)
                                  continue;
                             out.println("<td>" + item.getChildNodes().item(0).getNodeValue() + "</td>");
                        out.println("</tr>");
              } else {
                   out.println("No rows.");
         out.println("</table>");
         out.println("</nsdp_xml>");
    %>
    ]]

Maybe you are looking for

  • Installer not picking up install path resulting in err code 22

    I've been trying to install CS5, however for some reason at the installtion options screen, the location path is blank and unchangeable. As a result the Drive is null and I get a Insufficient disk space to complete this installation message. There is

  • How to create a sequence inside a select statement

    I have the following query select t.id_trato2 as DEAL_ID, -- 1 as SEQ_NO from treats t order by id_trato2, seq_noIt will return for example id_trato2 seq_no 3 1 3 1 4 1 4 1 4 1 I need it to return id_trato2 seq_no 3 1 3 2 4 1 4 2 4 3 ¿how can I do th

  • System copy NW04S ABAP+Java same host

    Hi All I have this dev system ECC 6.0 (SAP_SID and DB_SID: D01) ABAPJava system and enterprise portal 7.0 (SAP_SID and DB_SID: P01) on the same host (hostname: host1). Now I need to do a system copy of the D01 ABAPJava system to build new system D02

  • Duplicate programs in "Open With" menu

    How can I clean up the menu that shows when I right click and choose "Open With". I have duplicate programs (for example VLC shows twice). Any way to fix this?

  • Original serial number is getting invalid message

    I received Adobe Photoshop Elements 7 as a gift which was purchased in Costco. I have the original box, disc and serial number from the inside cover. I recently changed computers but cannot reinstall my copy as I am getting a message that the serial