Example usage for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler

List of usage examples for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler

Introduction

In this page you can find the example usage for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler.

Prototype

BasicResponseHandler

Source Link

Usage

From source file:dataServer.StorageRESTClientManager.java

public String getMachineProperties(String machineId) {
    // Default HTTP client and common properties for requests
    requestUrl = null;/*ww w  . j av a 2 s . c  o m*/
    params = null;
    queryString = null;

    // Default HTTP response and common properties for responses
    HttpResponse response = null;
    ResponseHandler<String> handler = null;
    int status = 0;
    String body = null;

    // Query for machine properties
    requestUrl = new StringBuilder("http://" + storageLocation + ":" + storagePortRegistryC
            + storageRegistryContext + "/query/machine/properties");

    params = new LinkedList<NameValuePair>();
    params.add(new BasicNameValuePair("machineId", machineId));

    queryString = URLEncodedUtils.format(params, "utf-8");
    requestUrl.append("?");
    requestUrl.append(queryString);

    try {
        HttpGet query = new HttpGet(requestUrl.toString());
        query.setHeader("Content-type", "application/json");
        response = client.execute(query);

        // Check status code
        status = response.getStatusLine().getStatusCode();
        if (status != 200) {
            throw new RuntimeException("Failed! HTTP error code: " + status);
        }

        // Get body
        handler = new BasicResponseHandler();
        body = handler.handleResponse(response);

        //System.out.println("MACHINE PROPRIETIES: " + body);
        return body;
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
        return null;
    }
}

From source file:com.nexmo.verify.sdk.NexmoVerifyClient.java

public SearchResult[] search(String... requestIds) throws IOException, SAXException {
    if (requestIds == null || requestIds.length == 0)
        throw new IllegalArgumentException("request ID parameter is mandatory.");

    if (requestIds.length > MAX_SEARCH_REQUESTS)
        throw new IllegalArgumentException("too many request IDs. Max is " + MAX_SEARCH_REQUESTS);

    log.debug("HTTP-Number-Verify-Search Client .. for [ " + Arrays.toString(requestIds) + " ] ");

    List<NameValuePair> params = new ArrayList<>();

    params.add(new BasicNameValuePair("api_key", this.apiKey));
    params.add(new BasicNameValuePair("api_secret", this.apiSecret));

    if (requestIds.length == 1) {
        params.add(new BasicNameValuePair("request_id", requestIds[0]));
    } else {//from w w  w. jav  a2  s .com
        for (String requestId : requestIds)
            params.add(new BasicNameValuePair("request_ids", requestId));
    }

    String verifySearchBaseUrl = this.baseUrl + PATH_VERIFY_SEARCH;

    // Now that we have generated a query string, we can instanciate a HttpClient,
    // construct a POST method and execute to submit the request
    String response = null;
    for (int pass = 1; pass <= 2; pass++) {
        HttpPost httpPost = new HttpPost(verifySearchBaseUrl);
        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        HttpUriRequest method = httpPost;
        String url = verifySearchBaseUrl + "?" + URLEncodedUtils.format(params, "utf-8");

        try {
            if (this.httpClient == null)
                this.httpClient = HttpClientUtils.getInstance(this.connectionTimeout, this.soTimeout)
                        .getNewHttpClient();
            HttpResponse httpResponse = this.httpClient.execute(method);
            int status = httpResponse.getStatusLine().getStatusCode();
            if (status != 200)
                throw new Exception(
                        "got a non-200 response [ " + status + " ] from Nexmo-HTTP for url [ " + url + " ] ");
            response = new BasicResponseHandler().handleResponse(httpResponse);
            log.info(".. SUBMITTED NEXMO-HTTP URL [ " + url + " ] -- response [ " + response + " ] ");
            break;
        } catch (Exception e) {
            method.abort();
            log.info("communication failure: " + e);
            String exceptionMsg = e.getMessage();
            if (exceptionMsg.indexOf("Read timed out") >= 0) {
                log.info(
                        "we're still connected, but the target did not respond in a timely manner ..  drop ...");
            } else {
                if (pass == 1) {
                    log.info("... re-establish http client ...");
                    this.httpClient = null;
                    continue;
                }
            }

            // return a COMMS failure ...
            return new SearchResult[] { new SearchResult(BaseResult.STATUS_COMMS_FAILURE, null, null, null,
                    null, 0, null, null, null, null, null, null, null,
                    "Failed to communicate with NEXMO-HTTP url [ " + url + " ] ..." + e, true) };
        }
    }

    Document doc;
    synchronized (this.documentBuilder) {
        doc = this.documentBuilder.parse(new InputSource(new StringReader(response)));
    }

    Element root = doc.getDocumentElement();
    if ("verify_response".equals(root.getNodeName())) {
        // error response
        VerifyResult result = parseVerifyResult(root);
        return new SearchResult[] {
                new SearchResult(result.getStatus(), result.getRequestId(), null, null, null, 0, null, null,
                        null, null, null, null, null, result.getErrorText(), result.isTemporaryError()) };
    } else if (("verify_request").equals(root.getNodeName())) {
        return new SearchResult[] { parseSearchResult(root) };
    } else if ("verification_requests".equals(root.getNodeName())) {
        List<SearchResult> results = new ArrayList<>();

        NodeList fields = root.getChildNodes();
        for (int i = 0; i < fields.getLength(); i++) {
            Node node = fields.item(i);
            if (node.getNodeType() != Node.ELEMENT_NODE)
                continue;

            if ("verify_request".equals(node.getNodeName()))
                results.add(parseSearchResult((Element) node));
        }

        return results.toArray(new SearchResult[results.size()]);
    } else {
        throw new IOException("No valid response found [ " + response + "] ");
    }
}

From source file:com.BeatYourRecord.SubmitActivity.java

public void iregistered() {
    EditText e2 = (EditText) findViewById(R.id.editText9);
    String str = e2.getText().toString();
    //log.v("Value1",str);
    EditText e3 = (EditText) findViewById(R.id.editText8);
    String str1 = e3.getText().toString();
    //log.v("Value1",str1);
    EditText e4 = (EditText) findViewById(R.id.editText0);
    String str2 = e4.getText().toString();
    EditText e5 = (EditText) findViewById(R.id.editText14);
    String str3 = e5.getText().toString();
    //log.v("Value1",str2);

    DefaultHttpClient client = new DefaultHttpClient();
    //log.v("here12","here");
    HttpPost post = new HttpPost(
            "http://ec2-54-212-221-3.us-west-2.compute.amazonaws.com/api/v3/registrations/");
    JSONObject holder = new JSONObject();
    JSONObject userObj = new JSONObject();
    JSONObject userObj1 = new JSONObject();
    JSONObject userObj2 = new JSONObject();
    JSONObject userObj4 = new JSONObject();

    String response = null;/*from  www. ja  v  a  2 s . c  o m*/
    JSONObject json = new JSONObject();

    try {
        try {
            // setup the returned values in case
            // something goes wrong
            json.put("success", false);
            json.put("info", "Something went wrong. Retry!");
            // add the user email and password to
            // the params
            String k = "";
            String k1 = "";
            String k2 = "";
            SharedPreferences pref6 = getApplicationContext().getSharedPreferences("TourPref", 0); // 0 - for private mode
            Editor editor6 = pref6.edit();
            editor6.putString("Username", str3);
            editor6.commit();
            userObj.put("email", str);
            k = userObj.toString();
            k = k.substring(0, k.length() - 1);
            k += ",";
            userObj4.put("username", str3);
            k1 = userObj4.toString();
            k1 = k1.substring(1, k1.length() - 1);
            k1 += ",";
            k += k1;
            userObj1.put("password", str1);
            k1 = userObj1.toString();
            k1 = k1.substring(1, k1.length() - 1);
            k1 += ",";
            k += k1;
            userObj2.put("password_confirmation", str2);
            k1 = userObj2.toString();
            k1 = k1.substring(1, k1.length());
            k += k1;
            //log.v("holder",k);
            StringEntity se = new StringEntity(k);
            post.setEntity(se);

            // setup the request headers
            post.setHeader("Content-Type", "application/json");
            post.setHeader("Accept", "application/json");
            //  post.setHeader("Content-Type", "application/json");

            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            response = client.execute(post, responseHandler);
            json = new JSONObject(response);
            String test = json.getJSONObject("data").getString("auth_token");
            SharedPreferences pref = getApplicationContext().getSharedPreferences("Tester15", 0); // 0 - for private mode
            Editor editor = pref.edit();
            editor.putString("BYR_session", test); // Storing string
            auth = test;
            editor.commit();
            Log.v("test1authinsub", test);

        } catch (HttpResponseException e) {
            e.printStackTrace();
            Log.e("ClientProtocol", "" + e);
            json.put("info", "Email and/or password are invalid. Retry!");
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("IO", "" + e);
        }
    } catch (JSONException e) {
        e.printStackTrace();
        Log.e("JSON", "" + e);
    }
}

From source file:ca.sqlpower.wabit.enterprise.client.WabitClientSession.java

/**
 * Sends an HTTP request to a Wabit Enterprise Server to create a new remote
 * Wabit Workspace on that server./*  w  w  w.ja  v a2 s  .  c  o m*/
 * 
 * @param serviceInfo
 *            A {@link SPServerInfo} containing the connection
 *            information for that server
 * @return The {@link WorkspaceLocation} of the newly created remote
 *         WabitWorkspace
 * @throws URISyntaxException
 * @throws ClientProtocolException
 * @throws IOException
 * @throws JSONException
 */
public static WorkspaceLocation createNewServerSession(SPServerInfo serviceInfo)
        throws URISyntaxException, ClientProtocolException, IOException, JSONException {
    HttpClient httpClient = createHttpClient(serviceInfo);
    try {
        HttpUriRequest request = new HttpPost(getServerURI(serviceInfo, "workspaces"));
        String responseBody = httpClient.execute(request, new BasicResponseHandler());
        JSONObject response = new JSONObject(responseBody);
        logger.debug("New Workspace:" + responseBody);
        return new WorkspaceLocation(response.getString("name"), response.getString("UUID"), serviceInfo);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:dataServer.StorageRESTClientManager.java

public String getSensorProprerties(String sensorId, String context) {
    // Default HTTP client and common properties for requests
    requestUrl = null;// ww  w. j a v a  2  s  .  c o m
    params = null;
    queryString = null;

    // Default HTTP response and common properties for responses
    HttpResponse response = null;
    ResponseHandler<String> handler = null;
    int status = 0;
    String body = null;

    // Query for sensor properties
    requestUrl = new StringBuilder("http://" + storageLocation + ":" + storagePortRegistryC
            + storageRegistryContext + "/query/sensor/properties?dataset=" + context + "&sensorId=" + sensorId);

    try {
        HttpGet query = new HttpGet(requestUrl.toString());
        query.setHeader("Content-type", "application/json");
        response = client.execute(query);

        // Check status code
        status = response.getStatusLine().getStatusCode();
        if (status != 200) {
            throw new RuntimeException("Failed! HTTP error code: " + status);
        }

        // Get body
        handler = new BasicResponseHandler();
        body = handler.handleResponse(response);

        //System.out.println("SENSOR PROPRIETIES: " + body);
        return body;
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
        return null;
    }
}

From source file:com.ibuildapp.romanblack.FanWallPlugin.data.Statics.java

public static IncrementSharingStatus incrementSharing(String postId) {
    String loginUrl = com.appbuilder.sdk.android.Statics.BASE_DOMEN + "/modules/fanwall/sharing_increment";
    Log.e(TAG, "incrementSharing url = " + loginUrl);

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 15000);
    HttpConnectionParams.setSoTimeout(params, 15000);
    HttpClient httpClient = new DefaultHttpClient(params);
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

    try {//from   www .  j ava2 s.  c  om
        HttpPost httpPost = new HttpPost(loginUrl);

        // order details
        nameValuePairs.add(new BasicNameValuePair("app_id", com.appbuilder.sdk.android.Statics.appId));
        nameValuePairs.add(new BasicNameValuePair("module_id", Statics.MODULE_ID));
        nameValuePairs.add(new BasicNameValuePair("post_id", postId));
        nameValuePairs.add(new BasicNameValuePair("token", com.appbuilder.sdk.android.Statics.appToken));

        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        String resp = httpClient.execute(httpPost, new BasicResponseHandler());

        if (TextUtils.isEmpty(resp)) {
            return null;
        }

        Log.e(TAG, "incrementSharing response = " + resp);

        JSONObject mainObject = new JSONObject(resp);

        IncrementSharingStatus result = new IncrementSharingStatus();
        result.status_code = mainObject.getInt("status_code");
        result.error = mainObject.getString("error");

        return result;

    } catch (Exception e) {
        return null;
    }
}

From source file:org.nema.medical.mint.dcm2mint.ProcessImportDir.java

private JobInfo send(final File metadataFile, final BinaryData binaryData, final Collection<File> studyFiles,
        final StudyQueryInfo studyQueryInfo) throws IOException, SAXException {
    final HttpPost httpPost = new HttpPost(studyQueryInfo == null ? createURI : updateURI);
    final MultipartEntity entity = new MultipartEntity();

    if (studyQueryInfo != null) {
        entity.addPart(HttpMessagePart.STUDY_UUID.toString(), new StringBody(studyQueryInfo.studyUUID));
    }/*from w  ww  .  ja  v a 2 s .  c o m*/

    final StudyMetadata study = useXMLNotGPB ? StudyIO.parseFromXML(metadataFile)
            : StudyIO.parseFromGPB(metadataFile);
    if (studyQueryInfo != null) {
        //Specify current study version
        entity.addPart(HttpMessagePart.OLD_VERSION.toString(), new StringBody(studyQueryInfo.studyVersion));
    }

    //Pretty significant in-memory operations, so scoping to get references released ASAP
    {
        final byte[] metaInBuffer;
        {
            final ByteArrayOutputStream metaOut = new ByteArrayOutputStream(10000);
            if (useXMLNotGPB) {
                StudyIO.writeToXML(study, metaOut);
            } else {
                StudyIO.writeToGPB(study, metaOut);
            }
            metaInBuffer = metaOut.toByteArray();
        }
        final ByteArrayInputStream metaIn = new ByteArrayInputStream(metaInBuffer);
        //We must distinguish MIME types for GPB vs. XML so that the server can handle them properly
        entity.addPart(metadataFile.getName(), new InputStreamBody(metaIn,
                useXMLNotGPB ? "text/xml" : "application/octet-stream", metadataFile.getName()));
    }

    //We support only one type
    assert binaryData instanceof BinaryDcmData;
    {
        int i = 0;
        for (final InputStream binaryStream : iter(((BinaryDcmData) binaryData).streamIterator())) {
            final String fileName = "binary" + i++;
            entity.addPart(fileName, new InputStreamBody(binaryStream, fileName));
        }
    }

    //Debugging only
    //        int i = 0;
    //        for (final InputStream binaryStream: Iter.iter(((BinaryDcmData) binaryData).streamIterator())) {
    //            final OutputStream testout = new BufferedOutputStream(new FileOutputStream("E:/testdata/" + i), 10000);
    //            for(;;) {
    //                final int val = binaryStream.read();
    //                if (val == -1) {
    //                    break;
    //                }
    //                testout.write(val);
    //            }
    //            testout.close();
    //            ++i;
    //        }

    httpPost.setEntity(entity);

    final String response = httpClient.execute(httpPost, new BasicResponseHandler());
    final long uploadEndTime = System.currentTimeMillis();

    LOG.debug("Server response:" + response);

    final String jobID;
    final String studyID;
    final Document responseDoc = documentBuilder.parse(new ByteArrayInputStream(response.getBytes()));
    try {
        jobID = xPath.evaluate("/jobStatus/@jobID", responseDoc).trim();
        studyID = xPath.evaluate("/jobStatus/@studyUUID", responseDoc).trim();
    } catch (final XPathExpressionException e) {
        //This shouldn't happen
        throw new RuntimeException(e);
    }
    final JobInfo jobInfo = new JobInfo(jobID, studyID, studyFiles, uploadEndTime);
    jobIDInfo.put(jobID, jobInfo);
    return jobInfo;
}

From source file:com.nexmo.messaging.sdk.NexmoSmsClient.java

/**
 * submit a message submission request object.
 * This will use the supplied object to construct a request and post it to the Nexmo REST interface.<br>
 * This method will respond with an array of SmsSubmissionResult objects. Depending on the nature and length of the submitted message, Nexmo may automatically
 * split the message into multiple sms messages in order to deliver to the handset. For example, a long text sms of greater than 160 chars will need to be split
 * into multiple 'concatenated' sms messages. The Nexmo service will handle this automatically for you.<br>
 * The array of SmsSubmissionResult objects will contain a SmsSubmissionResult object for every actual sms that was required to submit the message.
 * each message can potentially have a different status result, and each message will have a different message id.
 * Delivery notifications will be generated for each sms message within this set and will be posted to your application containing the appropriate message id.
 *
 * @param message The message request object that describes the type of message and the contents to be submitted.
 * @param validityPeriod The validity period (Time-To-Live) for this message. Specifies the time before this mesage will be expired if not yet delivered
 * @param networkCode (Optional) use this parameter to force this message to be associated with and delivered on this network. Use this in cases where you want to over-ride
 *                               the automatic network detection provided by Nexmo. This value will be used in order to determine the pricing and routing for this message.<br>
 *                               (Note) This feature must be enabled and available on your account or else this value will be ignored.
 * @param performReachabilityCheck Flag to indicate wether a reachability check should be performed on this message before delivery is attempted. If the destination is
 *                                 not reachable, the message will be rejected and a reachability status will be returned in the response field smsSubmissionReachabilityStatus<br>
 *                                 (Note) This feature must be enabled and available on your account or else the message request will be rejected. There may be additional cost
 *                                 associated with the use of this feature.
 *
 * @return SmsSubmissionResult[] an array of results, 1 object for each sms message that was required to submit this message in its entirety
 *
 * @throws Exception There has been a general failure either within the Client class, or whilst attempting to communicate with the Nexmo service (eg, Network failure)
 *//*  ww  w .  j a v a  2 s.c  om*/
public SmsSubmissionResult[] submitMessage(final Message message, final ValidityPeriod validityPeriod,
        final String networkCode, final boolean performReachabilityCheck) throws Exception {

    log.debug("HTTP-Message-Submission Client .. from [ " + message.getFrom() + " ] to [ " + message.getTo()
            + " ] msg [ " + message.getMessageBody() + " ] ");

    // From the Message object supplied, construct an appropriate request to be submitted to the Nexmo REST Service.

    // Determine what 'product' type we are submitting, and select the appropriate endpoint path
    String submitPath = SUBMISSION_PATH_SMS;

    // Determine the type parameter based on the type of Message object.
    boolean binary = message.getType() == Message.MESSAGE_TYPE_BINARY;
    boolean unicode = message.isUnicode();
    boolean wapPush = message.getType() == Message.MESSAGE_TYPE_WAPPUSH;

    String mode = "text";

    if (binary)
        mode = "binary";

    if (unicode)
        mode = "unicode";

    if (wapPush)
        mode = "wappush";

    // Construct a query string as a list of NameValuePairs

    List<NameValuePair> params = new ArrayList<>();

    boolean doPost = false;

    params.add(new BasicNameValuePair("api_key", this.apiKey));
    if (!this.signRequests)
        params.add(new BasicNameValuePair("api_secret", this.apiSecret));
    params.add(new BasicNameValuePair("from", message.getFrom()));
    params.add(new BasicNameValuePair("to", message.getTo()));
    params.add(new BasicNameValuePair("type", mode));
    if (wapPush) {
        params.add(new BasicNameValuePair("url", message.getWapPushUrl()));
        params.add(new BasicNameValuePair("title", message.getWapPushTitle()));
        if (message.getWapPushValidity() > 0)
            params.add(new BasicNameValuePair("validity", "" + message.getWapPushValidity()));
    } else if (binary) {
        // Binary Message
        if (message.getBinaryMessageUdh() != null)
            params.add(new BasicNameValuePair("udh", HexUtil.bytesToHex(message.getBinaryMessageUdh())));
        params.add(new BasicNameValuePair("body", HexUtil.bytesToHex(message.getBinaryMessageBody())));
    } else {
        // Text Message
        params.add(new BasicNameValuePair("text", message.getMessageBody()));
        if (message.getMessageBody() != null && message.getMessageBody().length() > 255)
            doPost = true;
    }

    if (message.getClientReference() != null)
        params.add(new BasicNameValuePair("client-ref", message.getClientReference()));

    params.add(new BasicNameValuePair("status-report-req", "" + message.getStatusReportRequired()));

    if (message.getMessageClass() != null)
        params.add(new BasicNameValuePair("message-class", "" + message.getMessageClass().getMessageClass()));

    if (message.getProtocolId() != null)
        params.add(new BasicNameValuePair("protocol-id", "" + message.getProtocolId()));

    if (validityPeriod != null) {
        if (validityPeriod.getTimeToLive() != null)
            params.add(new BasicNameValuePair("ttl", "" + validityPeriod.getTimeToLive().intValue()));
        if (validityPeriod.getValidityPeriodHours() != null)
            params.add(new BasicNameValuePair("ttl-hours",
                    "" + validityPeriod.getValidityPeriodHours().intValue()));
        if (validityPeriod.getValidityPeriodMinutes() != null)
            params.add(new BasicNameValuePair("ttl-minutes",
                    "" + validityPeriod.getValidityPeriodMinutes().intValue()));
        if (validityPeriod.getValidityPeriodSeconds() != null)
            params.add(new BasicNameValuePair("ttl-seconds",
                    "" + validityPeriod.getValidityPeriodSeconds().intValue()));
    }

    if (networkCode != null)
        params.add(new BasicNameValuePair("network-code", networkCode));

    if (performReachabilityCheck)
        params.add(new BasicNameValuePair("test-reachable", "true"));

    if (this.signRequests)
        RequestSigning.constructSignatureForRequestParameters(params, this.signatureSecretKey);

    String baseUrl = this.baseUrlHttps + submitPath;

    // Now that we have generated a query string, we can instanciate a HttpClient,
    // construct a POST or GET method and execute to submit the request
    String response = null;
    for (int pass = 1; pass <= 2; pass++) {
        HttpUriRequest method = null;
        doPost = true;
        String url = null;
        if (doPost) {
            HttpPost httpPost = new HttpPost(baseUrl);
            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            method = httpPost;
            url = baseUrl + "?" + URLEncodedUtils.format(params, "utf-8");
        } else {
            String query = URLEncodedUtils.format(params, "utf-8");
            method = new HttpGet(baseUrl + "?" + query);
            url = method.getRequestLine().getUri();
        }

        try {
            if (this.httpClient == null)
                this.httpClient = HttpClientUtils.getInstance(this.connectionTimeout, this.soTimeout)
                        .getNewHttpClient();
            HttpResponse httpResponse = this.httpClient.execute(method);
            int status = httpResponse.getStatusLine().getStatusCode();
            if (status != 200)
                throw new Exception(
                        "got a non-200 response [ " + status + " ] from Nexmo-HTTP for url [ " + url + " ] ");
            response = new BasicResponseHandler().handleResponse(httpResponse);
            log.info(".. SUBMITTED NEXMO-HTTP URL [ " + url + " ] -- response [ " + response + " ] ");
            break;
        } catch (Exception e) {
            method.abort();
            log.info("communication failure: " + e);
            String exceptionMsg = e.getMessage();
            if (exceptionMsg.indexOf("Read timed out") >= 0) {
                log.info(
                        "we're still connected, but the target did not respond in a timely manner ..  drop ...");
            } else {
                if (pass == 1) {
                    log.info("... re-establish http client ...");
                    this.httpClient = null;
                    continue;
                }
            }

            // return a COMMS failure ...
            SmsSubmissionResult[] results = new SmsSubmissionResult[1];
            results[0] = new SmsSubmissionResult(SmsSubmissionResult.STATUS_COMMS_FAILURE, null, null,
                    "Failed to communicate with NEXMO-HTTP url [ " + url + " ] ..." + e,
                    message.getClientReference(), null, null, true, null, null);
            return results;
        }
    }

    // parse the response doc ...

    /*
    We receive a response from the api that looks like this, parse the document
    and turn it into an array of SmsSubmissionResult, one object per <message> node
            
        <mt-submission-response>
            <messages count='x'>
                <message>
                    <to>xxx</to>
                    <messageId>xxx</messageId>
                    <status>xx</status>
                    <errorText>ff</errorText>
                    <clientRef>xxx</clientRef>
                    <remainingBalance>##.##</remainingBalance>
                    <messagePrice>##.##</messagePrice>
                    <reachability status='x' description='xxx' />
                    <network>23410</network>
                </message>
            </messages>
        </mt-submission-response>
    */

    List<SmsSubmissionResult> results = new ArrayList<>();

    Document doc = null;
    synchronized (this.documentBuilder) {
        try {
            doc = this.documentBuilder.parse(new InputSource(new StringReader(response)));
        } catch (Exception e) {
            throw new Exception("Failed to build a DOM doc for the xml document [ " + response + " ] ", e);
        }
    }

    NodeList replies = doc.getElementsByTagName("mt-submission-response");
    for (int i = 0; i < replies.getLength(); i++) {
        Node reply = replies.item(i);
        NodeList messageLists = reply.getChildNodes();
        for (int i2 = 0; i2 < messageLists.getLength(); i2++) {
            Node messagesNode = messageLists.item(i2);
            if (messagesNode.getNodeType() != Node.ELEMENT_NODE)
                continue;
            if (messagesNode.getNodeName().equals("messages")) {
                NodeList messages = messagesNode.getChildNodes();
                for (int i3 = 0; i3 < messages.getLength(); i3++) {
                    Node messageNode = messages.item(i3);
                    if (messageNode.getNodeType() != Node.ELEMENT_NODE)
                        continue;

                    int status = -1;
                    String messageId = null;
                    String destination = null;
                    String errorText = null;
                    String clientReference = null;
                    BigDecimal remainingBalance = null;
                    BigDecimal messagePrice = null;
                    SmsSubmissionReachabilityStatus smsSubmissionReachabilityStatus = null;
                    String network = null;

                    NodeList nodes = messageNode.getChildNodes();
                    for (int i4 = 0; i4 < nodes.getLength(); i4++) {
                        Node node = nodes.item(i4);
                        if (node.getNodeType() != Node.ELEMENT_NODE)
                            continue;
                        if (node.getNodeName().equals("messageId")) {
                            messageId = node.getFirstChild() == null ? null
                                    : node.getFirstChild().getNodeValue();
                        } else if (node.getNodeName().equals("to")) {
                            destination = node.getFirstChild() == null ? null
                                    : node.getFirstChild().getNodeValue();
                        } else if (node.getNodeName().equals("status")) {
                            String str = node.getFirstChild() == null ? null
                                    : node.getFirstChild().getNodeValue();
                            try {
                                status = Integer.parseInt(str);
                            } catch (NumberFormatException e) {
                                log.error("xml parser .. invalid value in <status> node [ " + str + " ] ");
                                status = SmsSubmissionResult.STATUS_INTERNAL_ERROR;
                            }
                        } else if (node.getNodeName().equals("errorText")) {
                            errorText = node.getFirstChild() == null ? null
                                    : node.getFirstChild().getNodeValue();
                        } else if (node.getNodeName().equals("clientRef")) {
                            clientReference = node.getFirstChild() == null ? null
                                    : node.getFirstChild().getNodeValue();
                        } else if (node.getNodeName().equals("remainingBalance")) {
                            String str = node.getFirstChild() == null ? null
                                    : node.getFirstChild().getNodeValue();
                            try {
                                if (str != null)
                                    remainingBalance = new BigDecimal(str);
                            } catch (NumberFormatException e) {
                                log.error("xml parser .. invalid value in <remainingBalance> node [ " + str
                                        + " ] ");
                            }
                        } else if (node.getNodeName().equals("messagePrice")) {
                            String str = node.getFirstChild() == null ? null
                                    : node.getFirstChild().getNodeValue();
                            try {
                                if (str != null)
                                    messagePrice = new BigDecimal(str);
                            } catch (NumberFormatException e) {
                                log.error(
                                        "xml parser .. invalid value in <messagePrice> node [ " + str + " ] ");
                            }
                        } else if (node.getNodeName().equals("reachability")) {
                            NamedNodeMap attributes = node.getAttributes();
                            Node attr = attributes.getNamedItem("status");
                            String str = attr == null
                                    ? "" + SmsSubmissionReachabilityStatus.REACHABILITY_STATUS_UNKNOWN
                                    : attr.getNodeValue();
                            int reachabilityStatus = SmsSubmissionReachabilityStatus.REACHABILITY_STATUS_UNKNOWN;
                            try {
                                reachabilityStatus = Integer.parseInt(str);
                            } catch (NumberFormatException e) {
                                log.error(
                                        "xml parser .. invalid value in 'status' attribute in <reachability> node [ "
                                                + str + " ] ");
                                reachabilityStatus = SmsSubmissionReachabilityStatus.REACHABILITY_STATUS_UNKNOWN;
                            }

                            attr = attributes.getNamedItem("description");
                            String description = attr == null ? "-UNKNOWN-" : attr.getNodeValue();

                            smsSubmissionReachabilityStatus = new SmsSubmissionReachabilityStatus(
                                    reachabilityStatus, description);
                        } else if (node.getNodeName().equals("network")) {
                            network = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
                        } else
                            log.error(
                                    "xml parser .. unknown node found in status-return, expected [ messageId, to, status, errorText, clientRef, messagePrice, remainingBalance, reachability, network ] -- found [ "
                                            + node.getNodeName() + " ] ");
                    }

                    if (status == -1)
                        throw new Exception("Xml Parser - did not find a <status> node");

                    // Is this a temporary error ?
                    boolean temporaryError = (status == SmsSubmissionResult.STATUS_THROTTLED
                            || status == SmsSubmissionResult.STATUS_INTERNAL_ERROR
                            || status == SmsSubmissionResult.STATUS_TOO_MANY_BINDS);

                    results.add(new SmsSubmissionResult(status, destination, messageId, errorText,
                            clientReference, remainingBalance, messagePrice, temporaryError,
                            smsSubmissionReachabilityStatus, network));
                }
            }
        }
    }

    return results.toArray(new SmsSubmissionResult[results.size()]);
}

From source file:org.hfoss.posit.android.web.Communicator.java

/**
 * A wrapper(does some cleanup too) for sending HTTP GET requests to the URI
 * //from ww w .jav  a2  s  . co  m
 * @param Uri
 * @return the request from the remote server
 */
public String doHTTPGET(String Uri) {
    if (Uri == null)
        throw new NullPointerException("The URL has to be passed");
    String responseString = null;
    HttpGet httpGet = new HttpGet();

    try {
        httpGet.setURI(new URI(Uri));
    } catch (URISyntaxException e) {
        Log.e(TAG, "doHTTPGet " + e.getMessage());
        e.printStackTrace();
        return "[Error] " + e.getMessage();
    }
    if (Utils.debug) {
        Log.i(TAG, "doHTTPGet Uri = " + Uri);
    }
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    mStart = System.currentTimeMillis();

    try {
        responseString = mHttpClient.execute(httpGet, responseHandler);
    } catch (ClientProtocolException e) {
        Log.e(TAG, "ClientProtocolException" + e.getMessage());
        e.printStackTrace();
        return "[Error] " + e.getMessage();
    } catch (SocketTimeoutException e) {
        Log.e(TAG, "[Error: SocketTimeoutException]" + e.getMessage());
        e.printStackTrace();
        return "[Error] " + e.getMessage();
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
        e.printStackTrace();
        return "[Error] " + e.getMessage();
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
        e.printStackTrace();
        return "[Error] " + e.getMessage();
    }

    long time = System.currentTimeMillis() - mStart;
    mTotalTime += time;
    Log.i(TAG, "TIME = " + time + " millisecs");

    if (Utils.debug)
        Log.i(TAG, "doHTTPGet Response: " + responseString);
    return responseString;
}