List of usage examples for org.apache.http.client.methods HttpUriRequest getRequestLine
RequestLine getRequestLine();
From source file:org.dasein.cloud.ibm.sce.SCEMethod.java
public @Nullable Document getAsXML(@Nonnull URI uri, @Nonnull String resource) throws CloudException, InternalException { Logger std = SCE.getLogger(SCEMethod.class, "std"); Logger wire = SCE.getLogger(SCEMethod.class, "wire"); if (std.isTraceEnabled()) { std.trace("enter - " + SCEMethod.class.getName() + ".get(" + uri + ")"); }/*from w w w. j a va 2 s . c o m*/ if (wire.isDebugEnabled()) { wire.debug("--------------------------------------------------------> " + uri.toASCIIString()); wire.debug(""); } try { HttpClient client = getClient(); HttpUriRequest get = new HttpGet(uri); get.addHeader("Accept", "text/xml"); if (wire.isDebugEnabled()) { wire.debug(get.getRequestLine().toString()); for (Header header : get.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } HttpResponse response; StatusLine status; try { APITrace.trace(provider, resource); response = client.execute(get); status = response.getStatusLine(); } catch (IOException e) { std.error("get(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); if (std.isTraceEnabled()) { e.printStackTrace(); } throw new CloudException(e); } if (std.isDebugEnabled()) { std.debug("get(): HTTP Status " + status); } Header[] headers = response.getAllHeaders(); if (wire.isDebugEnabled()) { wire.debug(status.toString()); for (Header h : headers) { if (h.getValue() != null) { wire.debug(h.getName() + ": " + h.getValue().trim()); } else { wire.debug(h.getName() + ":"); } } wire.debug(""); } if (status.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) { return null; } if (status.getStatusCode() != HttpServletResponse.SC_OK && status.getStatusCode() != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION) { std.error("get(): Expected OK for GET request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); String body; if (entity == null) { throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } try { body = EntityUtils.toString(entity); } catch (IOException e) { throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } if (wire.isDebugEnabled()) { wire.debug(body); } wire.debug(""); throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), body); } else { HttpEntity entity = response.getEntity(); if (entity == null) { return null; } InputStream input; try { input = entity.getContent(); } catch (IOException e) { std.error("get(): Failed to read response error due to a cloud I/O error: " + e.getMessage()); if (std.isTraceEnabled()) { e.printStackTrace(); } throw new CloudException(e); } return parseResponse(input, true); } } finally { if (std.isTraceEnabled()) { std.trace("exit - " + SCEMethod.class.getName() + ".getStream()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("--------------------------------------------------------> " + uri.toASCIIString()); } } }
From source file:org.jclouds.http.apachehc.ApacheHCHttpCommandExecutorService.java
@Override protected HttpResponse invoke(HttpUriRequest nativeRequest) throws IOException { org.apache.http.HttpResponse apacheResponse = executeRequest(nativeRequest); Payload payload = null;/*from ww w. ja v a 2 s. co m*/ if (apacheResponse.getEntity() != null) try { payload = Payloads.newInputStreamPayload(apacheResponse.getEntity().getContent()); if (apacheResponse.getEntity().getContentLength() >= 0) payload.getContentMetadata().setContentLength(apacheResponse.getEntity().getContentLength()); if (apacheResponse.getEntity().getContentType() != null) payload.getContentMetadata() .setContentType(apacheResponse.getEntity().getContentType().getValue()); } catch (IOException e) { logger.warn(e, "couldn't receive payload for request: %s", nativeRequest.getRequestLine()); throw e; } Multimap<String, String> headers = LinkedHashMultimap.create(); for (Header header : apacheResponse.getAllHeaders()) { headers.put(header.getName(), header.getValue()); } if (payload != null) { contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers); } return HttpResponse.builder().statusCode(apacheResponse.getStatusLine().getStatusCode()) .message(apacheResponse.getStatusLine().getReasonPhrase()).payload(payload) .headers(filterOutContentHeaders(headers)).build(); }
From source file:jp.yojio.triplog.Common.DataApi.gdata.AndroidGDataClient.java
private InputStream createAndExecuteMethod(HttpRequestCreator creator, String uriString, String authToken) throws HttpException, IOException { HttpResponse response = null;// w w w . j a v a2 s . c om int status = 500; int redirectsLeft = MAX_REDIRECTS; URI uri; try { uri = new URI(uriString); } catch (URISyntaxException use) { Log.w(TAG, "Unable to parse " + uriString + " as URI.", use); throw new IOException("Unable to parse " + uriString + " as URI: " + use.getMessage()); } // we follow redirects ourselves, since we want to follow redirects even on // POSTs, which // the HTTP library does not do. following redirects ourselves also allows // us to log // the redirects using our own logging. while (redirectsLeft > 0) { HttpUriRequest request = creator.createRequest(uri); request.addHeader("Accept-Encoding", "gzip"); // only add the auth token if not null (to allow for GData feeds that do // not require // authentication.) if (!TextUtils.isEmpty(authToken)) { request.addHeader("Authorization", "GoogleLogin auth=" + authToken); } if (LOCAL_LOGV) { for (Header h : request.getAllHeaders()) { Log.v(TAG, h.getName() + ": " + h.getValue()); } Log.d(TAG, "Executing " + request.getRequestLine().toString()); } response = null; try { response = httpClient.execute(request); } catch (IOException ioe) { Log.w(TAG, "Unable to execute HTTP request." + ioe); throw ioe; } StatusLine statusLine = response.getStatusLine(); if (statusLine == null) { Log.w(TAG, "StatusLine is null."); throw new NullPointerException("StatusLine is null -- should not happen."); } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, response.getStatusLine().toString()); for (Header h : response.getAllHeaders()) { Log.d(TAG, h.getName() + ": " + h.getValue()); } } status = statusLine.getStatusCode(); HttpEntity entity = response.getEntity(); if ((status >= 200) && (status < 300) && entity != null) { return getUngzippedContent(entity); } // TODO: handle 301, 307? // TODO: let the http client handle the redirects, if we can be sure we'll // never get a // redirect on POST. if (status == 302) { // consume the content, so the connection can be closed. entity.consumeContent(); Header location = response.getFirstHeader("Location"); if (location == null) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Redirect requested but no Location " + "specified."); } break; } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Following redirect to " + location.getValue()); } try { uri = new URI(location.getValue()); } catch (URISyntaxException use) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Unable to parse " + location.getValue() + " as URI.", use); throw new IOException("Unable to parse " + location.getValue() + " as URI."); } break; } --redirectsLeft; } else { break; } } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Received " + status + " status code."); } String errorMessage = null; HttpEntity entity = response.getEntity(); try { if (response != null && entity != null) { InputStream in = entity.getContent(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[8192]; int bytesRead = -1; while ((bytesRead = in.read(buf)) != -1) { baos.write(buf, 0, bytesRead); } // TODO: use appropriate encoding, picked up from Content-Type. errorMessage = new String(baos.toByteArray()); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, errorMessage); } } } finally { if (entity != null) { entity.consumeContent(); } } String exceptionMessage = "Received " + status + " status code"; if (errorMessage != null) { exceptionMessage += (": " + errorMessage); } throw new HttpException(exceptionMessage, status, null /* InputStream */); }
From source file:br.com.bioscada.apps.biotracks.io.gdata.AndroidGDataClient.java
private InputStream createAndExecuteMethod(HttpRequestCreator creator, String uriString, String authToken) throws HttpException, IOException { HttpResponse response = null;/* ww w. j a v a2 s . c o m*/ int status = 500; int redirectsLeft = MAX_REDIRECTS; URI uri; try { uri = new URI(uriString); } catch (URISyntaxException use) { Log.w(TAG, "Unable to parse " + uriString + " as URI.", use); throw new IOException("Unable to parse " + uriString + " as URI: " + use.getMessage()); } // we follow redirects ourselves, since we want to follow redirects even on // POSTs, which // the HTTP library does not do. following redirects ourselves also allows // us to log // the redirects using our own logging. while (redirectsLeft > 0) { HttpUriRequest request = creator.createRequest(uri); request.addHeader("User-Agent", "Android-GData"); request.addHeader("Accept-Encoding", "gzip"); // only add the auth token if not null (to allow for GData feeds that do // not require // authentication.) if (!TextUtils.isEmpty(authToken)) { request.addHeader("Authorization", "GoogleLogin auth=" + authToken); } if (DEBUG) { for (Header h : request.getAllHeaders()) { Log.v(TAG, h.getName() + ": " + h.getValue()); } Log.d(TAG, "Executing " + request.getRequestLine().toString()); } response = null; try { response = httpClient.execute(request); } catch (IOException ioe) { Log.w(TAG, "Unable to execute HTTP request." + ioe); throw ioe; } StatusLine statusLine = response.getStatusLine(); if (statusLine == null) { Log.w(TAG, "StatusLine is null."); throw new NullPointerException("StatusLine is null -- should not happen."); } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, response.getStatusLine().toString()); for (Header h : response.getAllHeaders()) { Log.d(TAG, h.getName() + ": " + h.getValue()); } } status = statusLine.getStatusCode(); HttpEntity entity = response.getEntity(); if ((status >= 200) && (status < 300) && entity != null) { return getUngzippedContent(entity); } // TODO: handle 301, 307? // TODO: let the http client handle the redirects, if we can be sure we'll // never get a // redirect on POST. if (status == 302) { // consume the content, so the connection can be closed. entity.consumeContent(); Header location = response.getFirstHeader("Location"); if (location == null) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Redirect requested but no Location " + "specified."); } break; } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Following redirect to " + location.getValue()); } try { uri = new URI(location.getValue()); } catch (URISyntaxException use) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Unable to parse " + location.getValue() + " as URI.", use); throw new IOException("Unable to parse " + location.getValue() + " as URI."); } break; } --redirectsLeft; } else { break; } } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Received " + status + " status code."); } String errorMessage = null; HttpEntity entity = response.getEntity(); try { if (entity != null) { InputStream in = entity.getContent(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[8192]; int bytesRead = -1; while ((bytesRead = in.read(buf)) != -1) { baos.write(buf, 0, bytesRead); } // TODO: use appropriate encoding, picked up from Content-Type. errorMessage = new String(baos.toByteArray()); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, errorMessage); } } } finally { if (entity != null) { entity.consumeContent(); } } String exceptionMessage = "Received " + status + " status code"; if (errorMessage != null) { exceptionMessage += (": " + errorMessage); } throw new HttpException(exceptionMessage, status, null /* InputStream */); }
From source file:org.dataconservancy.dcs.ingest.client.impl.SwordClientManager.java
private DepositInfo execute(HttpUriRequest method) { try {/*from w ww.j a v a2 s . c o m*/ HttpResponse response = client.execute(method); int code = response.getStatusLine().getStatusCode(); if (code >= 200 && code <= 202) { Header[] headers = response.getAllHeaders(); InputStream content = response.getEntity().getContent(); byte[] body; try { body = IOUtils.toByteArray(content); } finally { content.close(); } if (response.containsHeader("Location")) { return new DcsDepositInfo(client, response.getFirstHeader("Location").getValue(), headers, body); } else { return new DcsDepositInfo(client, method.getURI().toASCIIString(), headers, body); } } else { log.warn(IOUtils.toString(response.getEntity().getContent())); throw new RuntimeException(String.format("Unexpected http code for %s: %s %s", method.getRequestLine(), code, response.getStatusLine().getReasonPhrase())); } } catch (IOException e) { throw new RuntimeException(e); } }
From source file:eu.prestoprime.plugin.mserve.MServeTasks.java
@WfService(name = "create_mserve_service", version = "1.0.0") public void createService(Map<String, String> sParams, Map<String, String> dParamsString, Map<String, File> dParamFile) throws TaskExecutionFailedException { // retrieve static parameters String tingServer = sParams.get("ting.server"); String slaTemplate = sParams.get("ting.sla.template");// serviceFactory String resourceManager = sParams.get("ting.resource.manager");// cap // retrieve dynamic parameters String userID = dParamsString.get("userID"); // create new SLA String uri = null;/* w w w.j a v a2s. c o m*/ try { URL url = new URL(tingServer + "/resourcemanager/slas?cap=" + resourceManager); HttpClient client = new DefaultHttpClient(); HttpUriRequest request = new HttpPost(url.toString()); List<NameValuePair> parameters = new ArrayList<>(); parameters.add(new BasicNameValuePair("name", "P4-" + System.currentTimeMillis())); parameters.add(new BasicNameValuePair("serviceFactory", slaTemplate)); UrlEncodedFormEntity requestEntity = new UrlEncodedFormEntity(parameters); ((HttpEntityEnclosingRequestBase) request).setEntity(requestEntity); logger.debug(request.getRequestLine().toString()); logger.debug(request.toString()); HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); if (entity != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); String line; StringBuffer sb = new StringBuffer(); while ((line = reader.readLine()) != null) sb.append(line); JSONObject json = new JSONObject(sb.toString()); logger.debug(json.toString()); uri = json.getString("uri"); } } else { throw new TaskExecutionFailedException("Ting error..."); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } logger.debug("URI: " + uri); if (uri == null) { throw new TaskExecutionFailedException("URI null"); } String mserveURL = null; try { String sla = uri.split("#")[1]; logger.debug(sla); URL url = new URL(tingServer + "/slas/sla?cap=" + sla); HttpClient client = new DefaultHttpClient(); HttpUriRequest request = new HttpGet(url.toString()); HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); if (entity != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); String line; StringBuffer sb = new StringBuffer(); while ((line = reader.readLine()) != null) sb.append(line); JSONObject json = new JSONObject(sb.toString()); logger.debug(json.toString()); mserveURL = json.getString("browse"); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } logger.debug(mserveURL); if (mserveURL == null) { throw new TaskExecutionFailedException("mserveURL null"); } String[] fields = mserveURL.split("/"); String mserveID = fields[fields.length - 1]; logger.debug(mserveID); ConfigurationManager.getUserInstance().addUserService(userID, "mserve", mserveID); }
From source file:org.dasein.cloud.azure.AzureMethod.java
public @Nullable InputStream getAsStream(@Nonnull String account, @Nonnull String resource) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("enter - " + AzureMethod.class.getName() + ".get(" + account + "," + resource + ")"); }// ww w.j av a 2s . co m if (wire.isDebugEnabled()) { wire.debug( "--------------------------------------------------------> " + endpoint + account + resource); wire.debug(""); } try { HttpClient client = getClient(); HttpUriRequest get = new HttpGet(endpoint + account + resource); //get.addHeader("Content-Type", "application/xml"); get.addHeader("x-ms-version", "2012-03-01"); if (wire.isDebugEnabled()) { wire.debug(get.getRequestLine().toString()); for (Header header : get.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } HttpResponse response; StatusLine status; try { response = client.execute(get); status = response.getStatusLine(); } catch (IOException e) { logger.error("get(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); e.printStackTrace(); throw new CloudException(e); } if (logger.isDebugEnabled()) { logger.debug("get(): HTTP Status " + status); } Header[] headers = response.getAllHeaders(); if (wire.isDebugEnabled()) { wire.debug(status.toString()); for (Header h : headers) { if (h.getValue() != null) { wire.debug(h.getName() + ": " + h.getValue().trim()); } else { wire.debug(h.getName() + ":"); } } wire.debug(""); } if (status.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) { return null; } if (status.getStatusCode() != HttpServletResponse.SC_OK && status.getStatusCode() != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION) { logger.error("get(): Expected OK for GET request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); String body; if (entity == null) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } try { body = EntityUtils.toString(entity); } catch (IOException e) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } if (wire.isDebugEnabled()) { wire.debug(body); } wire.debug(""); AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body); if (items == null) { return null; } logger.error("get(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details); throw new AzureException(items); } else { HttpEntity entity = response.getEntity(); if (entity == null) { return null; } InputStream input; try { input = entity.getContent(); } catch (IOException e) { logger.error( "get(): Failed to read response error due to a cloud I/O error: " + e.getMessage()); e.printStackTrace(); throw new CloudException(e); } if (wire.isDebugEnabled()) { wire.debug("---> Binary Data <---"); } wire.debug(""); return input; } } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + AzureMethod.class.getName() + ".getStream()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("--------------------------------------------------------> " + endpoint + account + resource); } } }
From source file:com.heneryh.aquanotes.io.ApexExecutor.java
/** * Execute this {@link HttpUriRequest}, passing a valid response through * {@link XmlHandler#parseAndApply(XmlPullParser, ContentResolver)}. *//*www . j av a 2 s .c om*/ public void executeWhySeparate(HttpUriRequest request, DefaultHandler xmlParser, String user, String pw) throws HandlerException { try { // Create credentials for basic auth UsernamePasswordCredentials c = new UsernamePasswordCredentials(user, pw); BasicCredentialsProvider cP = new BasicCredentialsProvider(); cP.setCredentials(AuthScope.ANY, c); ((DefaultHttpClient) mHttpClient).setCredentialsProvider(cP); /** * Execute the command and check the status */ final HttpResponse resp = mHttpClient.execute(request); final int status = resp.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { throw new HandlerException( "Unexpected server response " + resp.getStatusLine() + " for " + request.getRequestLine()); } final InputStream input = resp.getEntity().getContent(); try { NewXmlHandler.parseAndStore(input, controllerUri, xmlParser); } catch (HandlerException e) { throw new HandlerException("Malformed response for " + request.getRequestLine(), e); } finally { if (input != null) input.close(); } } catch (HandlerException e) { throw e; } catch (IOException e) { throw new HandlerException("Problem reading remote response for " + request.getRequestLine(), e); } }
From source file:com.socialize.provider.BaseSocializeProvider.java
private ListResult<T> doListTypeRequest(HttpUriRequest request, ActionType type, boolean isJSONResponse) throws SocializeException { List<T> results = null; List<ActionError> errors = null; HttpEntity entity = null;//from w w w. j a v a2 s . co m ListResult<T> result = null; if (!clientFactory.isDestroyed()) { try { HttpClient client = clientFactory.getClient(); if (logger != null && logger.isDebugEnabled()) { logger.debug("Request: " + request.getMethod() + " " + request.getRequestLine().getUri()); } HttpResponse response = executeRequest(client, request); if (logger != null && logger.isDebugEnabled()) { logger.debug("RESPONSE CODE: " + response.getStatusLine().getStatusCode()); } entity = response.getEntity(); if (httpUtils.isHttpError(response)) { if (sessionPersister != null && httpUtils.isAuthError(response)) { sessionPersister.delete(context.get()); } String msg = ioUtils.readSafe(entity.getContent()); throw new SocializeApiError(httpUtils, response.getStatusLine().getStatusCode(), msg); } else { result = new ListResult<T>(); if (isJSONResponse) { // Read the json just for logging String json = ioUtils.readSafe(entity.getContent()); if (logger != null && logger.isDebugEnabled()) { logger.debug("RESPONSE: " + json); } if (!StringUtils.isEmpty(json)) { JSONObject object; try { object = jsonParser.parseObject(json); } catch (JSONException je) { throw new SocializeException("Failed to parse response as JSON [" + json + "]", je); } if (object.has(JSON_ATTR_ERRORS) && !object.isNull(JSON_ATTR_ERRORS)) { JSONArray errorList = object.getJSONArray(JSON_ATTR_ERRORS); int length = errorList.length(); errors = new ArrayList<ActionError>(length); for (int i = 0; i < length; i++) { JSONObject jsonObject = errorList.getJSONObject(i); ActionError error = errorFactory.fromJSON(jsonObject); errors.add(error); } result.setErrors(errors); } if (object.has(JSON_ATTR_ITEMS) && !object.isNull(JSON_ATTR_ITEMS)) { JSONArray list = object.getJSONArray(JSON_ATTR_ITEMS); int length = list.length(); results = new ArrayList<T>(length); for (int i = 0; i < length; i++) { results.add(fromJSON(list.getJSONObject(i), type)); } result.setItems(results); } if (object.has(JSON_ATTR_COUNT) && !object.isNull(JSON_ATTR_COUNT)) { result.setTotalCount(object.getInt(JSON_ATTR_COUNT)); } } } } } catch (Throwable e) { throw SocializeException.wrap(e); } finally { closeEntity(entity); } return result; } else { if (logger != null) { logger.warn("Attempt to access HttpClientFactory that was already destroyed"); } return null; } }
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) *//*from ww w . ja va2 s . c o m*/ 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()]); }