List of usage examples for org.apache.http.client.methods HttpPost getEntity
public HttpEntity getEntity()
From source file:tap.Tap.java
/** * Dumps the ballots to the server TODO more refined explanation */// w w w . j a v a 2 s.co m public void uploadToServer() { System.out.println("Uploading Ballots to the server!"); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://localhost:9000/3FF968A3B47CT34C"); String encoded; try { System.out.println("Encoding the Supervisors' records... "); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); /* Write the record to the stream */ objectOutputStream.writeObject(supervisorRecord); objectOutputStream.close(); /* Encode the record as a string */ encoded = new String(Base64.encodeBase64(byteArrayOutputStream.toByteArray())); try { PrintWriter out = new PrintWriter("testdata.txt"); out.print(encoded); out.close(); } catch (Exception e) { e.printStackTrace(); } List<BasicNameValuePair> bnvp = new ArrayList(); bnvp.add(new BasicNameValuePair("record", encoded)); bnvp.add(new BasicNameValuePair("precinctID", Integer.toString((new Random()).nextInt()))); /* Set entities for each of the url encoded forms of the NVP */ post.setEntity(new UrlEncodedFormEntity(bnvp)); System.out.println("Executing post..." + post.getEntity()); /* Execute the post */ client.execute(post); } catch (IOException e) { e.printStackTrace(); } System.out.println("Upload complete!"); /* Shutdown the connection when done */ client.getConnectionManager().shutdown(); }
From source file:org.dasein.cloud.nimbula.NimbulaMethod.java
public @Nonnegative int post(@Nonnull Map<String, Object> state) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("ENTER - " + NimbulaMethod.class.getName() + ".post(" + state + ")"); }/*from ww w. j a v a2s . c o m*/ try { authenticate(); if (wire.isDebugEnabled()) { wire.debug(""); wire.debug(">>> [POST (" + (new Date()) + ")] -> " + url + "/ >--------------------------------------------------------------------------------------"); } try { ProviderContext ctx = cloud.getContext(); if (ctx == null) { throw new CloudException("No context was set for this request"); } HttpClient client = getClient(ctx, url.startsWith("https")); HttpPost post = new HttpPost(url + "/"); post.setHeader("Cookie", authCookie); post.addHeader("Accept", "application/nimbula-v2+json"); try { //noinspection deprecation post.setEntity(new StringEntity((new JSONObject(state)).toString(), "application/nimbula-v2+json", "UTF-8")); } catch (UnsupportedEncodingException e) { throw new InternalException(e); } if (wire.isDebugEnabled()) { wire.debug(post.getRequestLine().toString()); for (Header header : post.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); try { wire.debug(EntityUtils.toString(post.getEntity())); } catch (IOException ignore) { } wire.debug(""); } HttpResponse response; try { response = client.execute(post); if (wire.isDebugEnabled()) { wire.debug(response.getStatusLine().toString()); for (Header header : response.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } } catch (IOException e) { logger.error("I/O error from server communications: " + e.getMessage()); e.printStackTrace(); throw new InternalException(e); } int code = response.getStatusLine().getStatusCode(); logger.debug("HTTP STATUS: " + code); if (code != HttpServletResponse.SC_NO_CONTENT) { HttpEntity entity = response.getEntity(); if (entity != null) { try { this.response = EntityUtils.toString(entity); } catch (IOException e) { throw new CloudException(e); } if (wire.isDebugEnabled()) { wire.debug(this.response); wire.debug(""); } } checkResponse(response, code, this.response); } else { checkResponse(response, code); } return code; } finally { if (wire.isDebugEnabled()) { wire.debug("<<< [POST (" + (new Date()) + ")] -> " + url + "/ <--------------------------------------------------------------------------------------"); wire.debug(""); } } } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + NimbulaMethod.class.getName() + ".post()"); } } }
From source file:org.dasein.cloud.joyent.JoyentMethod.java
public @Nullable String doPostHeaders(@Nonnull String endpoint, @Nonnull String resource, @Nullable Map<String, String> customHeaders) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("ENTER - " + JoyentMethod.class.getName() + ".doPostHeaders(" + endpoint + "," + resource + "," + customHeaders + ")"); }//from www. jav a 2 s . c o m if (wire.isDebugEnabled()) { wire.debug(""); wire.debug(">>> [POST (" + (new Date()) + ")] -> " + endpoint + "/my/" + resource + " >--------------------------------------------------------------------------------------"); } try { HttpClient client = clientFactory.getClient(endpoint); HttpPost post = new HttpPost(endpoint + "/my/" + resource); httpAuth.addPreemptiveAuth(post); post.addHeader("Accept", "application/json"); post.addHeader("X-Api-Version", VERSION); if (customHeaders != null) { for (Map.Entry<String, String> entry : customHeaders.entrySet()) { String val = (entry.getValue() == null ? "" : entry.getValue()); post.addHeader(entry.getKey(), val); } } if (wire.isDebugEnabled()) { wire.debug(post.getRequestLine().toString()); for (Header header : post.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); try { wire.debug(EntityUtils.toString(post.getEntity())); } catch (IOException ignore) { } wire.debug(""); } HttpResponse response; try { response = client.execute(post); if (wire.isDebugEnabled()) { wire.debug(response.getStatusLine().toString()); for (Header header : response.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } } catch (IOException e) { logger.error("I/O error from server communications: " + e.getMessage()); throw new InternalException(e); } int code = response.getStatusLine().getStatusCode(); logger.debug("HTTP STATUS: " + code); if (code != HttpStatus.SC_ACCEPTED && code != HttpStatus.SC_NO_CONTENT && code != HttpStatus.SC_CREATED) { logger.error("Expected ACCEPTED for POST request, got " + code); String json = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { json = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(json); wire.debug(""); } } } catch (IOException e) { logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } JoyentException.ExceptionItems items = JoyentException.parseException(code, json); if (items == null) { items = new JoyentException.ExceptionItems(); items.code = 404; items.type = CloudErrorType.COMMUNICATION; items.message = "itemNotFound"; items.details = "No such object: " + resource; } logger.error("[" + code + " : " + items.message + "] " + items.details); throw new JoyentException(items); } else { if (code == HttpStatus.SC_ACCEPTED || code == HttpStatus.SC_CREATED) { String json = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { json = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(json); wire.debug(""); } } } catch (IOException e) { logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } if (json != null && !json.trim().equals("")) { return json; } } return null; } } finally { if (logger.isTraceEnabled()) { logger.trace("EXIT - " + JoyentMethod.class.getName() + ".doPostHeaders()"); } if (wire.isDebugEnabled()) { wire.debug("<<< [POST (" + (new Date()) + ")] -> " + endpoint + "/my/" + resource + " <--------------------------------------------------------------------------------------"); wire.debug(""); } } }
From source file:org.dasein.cloud.aws.compute.EC2Method.java
public Document invoke(boolean debug) throws EC2Exception, CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("ENTER - " + EC2Method.class.getName() + ".invoke(" + debug + ")"); }//from ww w . java 2 s . co m if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("--------------------------------------------------------------------------------------"); } try { if (logger.isDebugEnabled()) { logger.debug("Talking to server at " + url); } HttpPost post = new HttpPost(url); HttpClient client = getClient(); HttpResponse response; attempts++; post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); List<NameValuePair> params = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : parameters.entrySet()) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } try { post.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new InternalException(e); } if (wire.isDebugEnabled()) { wire.debug(post.getRequestLine().toString()); for (Header header : post.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); try { wire.debug(EntityUtils.toString(post.getEntity())); } catch (IOException ignore) { } wire.debug(""); } try { APITrace.trace(provider, parameters.get(AWSCloud.P_ACTION)); response = client.execute(post); if (wire.isDebugEnabled()) { wire.debug(response.getStatusLine().toString()); } } catch (IOException e) { logger.error("I/O error from server communications: " + e.getMessage()); e.printStackTrace(); throw new InternalException(e); } int status = response.getStatusLine().getStatusCode(); if (status == HttpServletResponse.SC_OK) { try { HttpEntity entity = response.getEntity(); if (entity == null) { throw new EC2Exception(status, null, "NoResponse", "No response body was specified"); } InputStream input = entity.getContent(); try { return parseResponse(input); } finally { input.close(); } } catch (IOException e) { logger.error("Error parsing response from AWS: " + e.getMessage()); e.printStackTrace(); throw new CloudException(CloudErrorType.COMMUNICATION, status, null, e.getMessage()); } } else if (status == HttpServletResponse.SC_FORBIDDEN) { String msg = "API Access Denied (403)"; try { HttpEntity entity = response.getEntity(); if (entity == null) { throw new EC2Exception(status, null, "NoResponse", "No response body was specified"); } InputStream input = entity.getContent(); try { BufferedReader in = new BufferedReader(new InputStreamReader(input)); StringBuilder sb = new StringBuilder(); String line; while ((line = in.readLine()) != null) { sb.append(line); sb.append("\n"); } //System.out.println(sb); try { Document doc = parseResponse(sb.toString()); if (doc != null) { NodeList blocks = doc.getElementsByTagName("Error"); String code = null, message = null, requestId = null; if (blocks.getLength() > 0) { Node error = blocks.item(0); NodeList attrs; attrs = error.getChildNodes(); for (int i = 0; i < attrs.getLength(); i++) { Node attr = attrs.item(i); if (attr.getNodeName().equals("Code")) { code = attr.getFirstChild().getNodeValue().trim(); } else if (attr.getNodeName().equals("Message")) { message = attr.getFirstChild().getNodeValue().trim(); } } } blocks = doc.getElementsByTagName("RequestID"); if (blocks.getLength() > 0) { Node id = blocks.item(0); requestId = id.getFirstChild().getNodeValue().trim(); } if (message == null && code == null) { throw new CloudException(CloudErrorType.COMMUNICATION, status, null, "Unable to identify error condition: " + status + "/" + requestId + "/" + code); } else if (message == null) { message = code; } throw new EC2Exception(status, requestId, code, message); } } catch (RuntimeException ignore) { // ignore me } catch (Error ignore) { // ignore me } msg = msg + ": " + sb.toString().trim().replaceAll("\n", " / "); } finally { input.close(); } } catch (IOException ignore) { // ignore me } catch (RuntimeException ignore) { // ignore me } catch (Error ignore) { // ignore me } throw new CloudException(msg); } else { if (logger.isDebugEnabled()) { logger.debug("Received " + status + " from " + parameters.get(AWSCloud.P_ACTION)); } if (status == HttpServletResponse.SC_SERVICE_UNAVAILABLE || status == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) { if (attempts >= 5) { String msg; if (status == HttpServletResponse.SC_SERVICE_UNAVAILABLE) { msg = "Cloud service is currently unavailable."; } else { msg = "The cloud service encountered a server error while processing your request."; try { HttpEntity entity = response.getEntity(); if (entity == null) { throw new EC2Exception(status, null, "NoResponse", "No response body was specified"); } msg = msg + "Response from server was:\n" + EntityUtils.toString(entity); } catch (IOException ignore) { // ignore me } catch (RuntimeException ignore) { // ignore me } catch (Error ignore) { // ignore me } } logger.error(msg); throw new CloudException(msg); } else { try { Thread.sleep(5000L); } catch (InterruptedException e) { /* ignore */ } return invoke(); } } try { HttpEntity entity = response.getEntity(); if (entity == null) { throw new EC2Exception(status, null, "NoResponse", "No response body was specified"); } InputStream input = entity.getContent(); Document doc; try { doc = parseResponse(input); } finally { input.close(); } if (doc != null) { NodeList blocks = doc.getElementsByTagName("Error"); String code = null, message = null, requestId = null; if (blocks.getLength() > 0) { Node error = blocks.item(0); NodeList attrs; attrs = error.getChildNodes(); for (int i = 0; i < attrs.getLength(); i++) { Node attr = attrs.item(i); if (attr.getNodeName().equals("Code")) { code = attr.getFirstChild().getNodeValue().trim(); } else if (attr.getNodeName().equals("Message")) { message = attr.getFirstChild().getNodeValue().trim(); } } } blocks = doc.getElementsByTagName("RequestID"); if (blocks.getLength() > 0) { Node id = blocks.item(0); requestId = id.getFirstChild().getNodeValue().trim(); } if (message == null) { throw new CloudException(CloudErrorType.COMMUNICATION, status, null, "Unable to identify error condition: " + status + "/" + requestId + "/" + code); } throw new EC2Exception(status, requestId, code, message); } throw new CloudException("Unable to parse error."); } catch (IOException e) { logger.error(e); e.printStackTrace(); throw new CloudException(e); } } } finally { if (logger.isTraceEnabled()) { logger.trace("EXIT - " + EC2Method.class.getName() + ".invoke()"); } if (wire.isDebugEnabled()) { wire.debug( "--------------------------------------------------------------------------------------"); wire.debug(""); } } }
From source file:org.dasein.cloud.nimbula.NimbulaMethod.java
private void authenticate() throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("ENTER - " + NimbulaMethod.class.getName() + ".authenticate()"); }/* w ww. j a v a 2s . c o m*/ try { if (authCookie != null) { return; } String uri = cloud.getURL("authenticate") + "/"; if (wire.isDebugEnabled()) { wire.debug(""); wire.debug(">>> [POST (" + (new Date()) + ")] -> " + uri + " >--------------------------------------------------------------------------------------"); } try { ProviderContext ctx = cloud.getContext(); if (ctx == null) { throw new CloudException("Unable to authenticate without a context"); } HttpClient client = getClient(ctx, uri.startsWith("https")); HttpPost post = new HttpPost(uri); HashMap<String, Object> request = new HashMap<String, Object>(); try { request.put("user", "/" + ctx.getAccountNumber() + "/" + new String(ctx.getAccessPublic(), "utf-8")); request.put("password", new String(ctx.getAccessPrivate(), "utf-8")); } catch (UnsupportedEncodingException e) { throw new InternalException(e); } post.addHeader("Accept", "application/nimbula-v2+json"); try { //noinspection deprecation post.setEntity(new StringEntity((new JSONObject(request)).toString(), "application/nimbula-v2+json", "UTF-8")); } catch (UnsupportedEncodingException e) { throw new InternalException(e); } if (wire.isDebugEnabled()) { wire.debug(post.getRequestLine().toString()); for (Header header : post.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); try { wire.debug(EntityUtils.toString(post.getEntity())); } catch (IOException ignore) { } wire.debug(""); } HttpResponse response; try { response = client.execute(post); if (wire.isDebugEnabled()) { wire.debug(response.getStatusLine().toString()); for (Header header : response.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } } catch (IOException e) { logger.error("I/O error from server communications: " + e.getMessage()); e.printStackTrace(); throw new InternalException(e); } int code = response.getStatusLine().getStatusCode(); logger.debug("HTTP STATUS: " + code); if (code != HttpServletResponse.SC_NO_CONTENT) { HttpEntity entity = response.getEntity(); String data = ""; if (entity != null) { try { data = EntityUtils.toString(entity); } catch (IOException e) { throw new CloudException(e); } } if (wire.isDebugEnabled()) { wire.debug(data); wire.debug(""); } } checkResponse(response, code); } finally { if (wire.isDebugEnabled()) { wire.debug("<<< [POST (" + (new Date()) + ")] -> " + uri + " <--------------------------------------------------------------------------------------"); wire.debug(""); } } } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + NimbulaMethod.class.getName() + ".authenticate()"); } } }
From source file:org.dasein.cloud.joyent.JoyentMethod.java
public @Nullable String doPostString(@Nonnull String endpoint, @Nonnull String resource, @Nullable String payload) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("ENTER - " + JoyentMethod.class.getName() + ".doPostString(" + endpoint + "," + resource + ",PAYLOAD)"); }/*www . j a v a 2 s. c om*/ if (wire.isDebugEnabled()) { wire.debug(""); wire.debug(">>> [POST (" + (new Date()) + ")] -> " + endpoint + "/my/" + resource + " >--------------------------------------------------------------------------------------"); } try { HttpClient client = clientFactory.getClient(endpoint); HttpPost post = new HttpPost(endpoint + "/my/" + resource); httpAuth.addPreemptiveAuth(post); if (payload != null && payload.startsWith("action")) { post.addHeader("Content-Type", "application/x-www-form-urlencoded"); } else { post.addHeader("Content-Type", "application/json"); } post.addHeader("Accept", "application/json"); post.addHeader("X-Api-Version", VERSION); if (payload != null && payload.startsWith("action")) { post.setEntity(new StringEntity(payload, APPLICATION_FORM_URLENCODED_UTF8)); } else { post.setEntity(new StringEntity(payload == null ? "" : payload, APPLICATION_JSON_UTF8)); } if (wire.isDebugEnabled()) { wire.debug(post.getRequestLine().toString()); for (Header header : post.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); try { wire.debug(EntityUtils.toString(post.getEntity())); } catch (IOException ignore) { } wire.debug(""); } HttpResponse response; try { response = client.execute(post); if (wire.isDebugEnabled()) { wire.debug(response.getStatusLine().toString()); for (Header header : response.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } } catch (IOException e) { logger.error("I/O error from server communications: " + e.getMessage()); throw new InternalException(e); } int code = response.getStatusLine().getStatusCode(); logger.debug("HTTP STATUS: " + code); if (code != HttpStatus.SC_ACCEPTED && code != HttpStatus.SC_NO_CONTENT && code != HttpStatus.SC_CREATED) { logger.error("Expected ACCEPTED for POST request, got " + code); String json = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { json = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(json); wire.debug(""); } } } catch (IOException e) { logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } JoyentException.ExceptionItems items = JoyentException.parseException(code, json); if (items == null) { items = new JoyentException.ExceptionItems(); items.code = 404; items.type = CloudErrorType.COMMUNICATION; items.message = "itemNotFound"; items.details = "No such object: " + resource; } logger.error("[" + code + " : " + items.message + "] " + items.details); throw new JoyentException(items); } else { if (code == HttpStatus.SC_ACCEPTED || code == HttpStatus.SC_CREATED) { String json = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { json = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(json); wire.debug(""); } } } catch (IOException e) { logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } if (json != null && !json.trim().equals("")) { return json; } } return null; } } finally { if (logger.isTraceEnabled()) { logger.trace("EXIT - " + JoyentMethod.class.getName() + ".doPostString()"); } if (wire.isDebugEnabled()) { wire.debug("<<< [POST (" + (new Date()) + ")] -> " + endpoint + "/my/" + resource + " <--------------------------------------------------------------------------------------"); wire.debug(""); } } }
From source file:org.cm.podd.report.service.DataSubmitService.java
private boolean submitReport(Report report) throws URISyntaxException, IOException, JSONException { HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpClient client = new DefaultHttpClient(params); boolean success = false; try {//from w w w.java 2 s .co m String serverUrl = settings.getString("serverUrl", BuildConfig.SERVER_URL); URI http = new URI(serverUrl + "/reports/"); Log.i(TAG, "submit report url=" + http.toURL()); HttpPost post = new HttpPost(http); post.setHeader("Content-type", "application/json"); post.setHeader("Authorization", "Token " + sharedPrefUtil.getAccessToken()); SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd"); JSONObject data = new JSONObject(); data.put("reportId", report.getId()); data.put("guid", report.getGuid()); data.put("reportTypeId", report.getType()); if (report.getFollowFlag() == Report.TRUE) { data.put("date", sdfDateTime.format(report.getFollowDate())); data.put("followFlag", Report.TRUE); data.put("parentGuid", report.getParentGuid()); } else { data.put("date", sdfDateTime.format(report.getDate())); } Date startDate = report.getStartDate(); if (startDate == null) { startDate = new Date(); } data.put("incidentDate", sdfDate.format(startDate)); if (report.getRegionId() != 0) { data.put("administrationAreaId", report.getRegionId()); } if (report.getLatitude() != 0.00 && report.getLongitude() != 0.00) { JSONObject loc = new JSONObject(); loc.put("latitude", report.getLatitude()); loc.put("longitude", report.getLongitude()); data.put("reportLocation", loc); } data.put("remark", report.getRemark()); data.put("negative", report.getNegative() == 1); JSONObject formObj = report.getNegative() == 1 ? report.getSubmitJSONFormData() : new JSONObject(); formObj.put("programVersion", BuildConfig.VERSION_CODE); formObj.put("reportTypeVersion", report.getReportTypeVersion()); data.put("formData", formObj); if (report.isTestReport()) { data.put("testFlag", true); } else { data.put("testFlag", false); } post.setEntity(new StringEntity(data.toString(), HTTP.UTF_8)); Log.d(TAG, "request with " + EntityUtils.toString(post.getEntity())); HttpResponse response; response = client.execute(post); HttpEntity entity = response.getEntity(); // Detect server complaints int statusCode = response.getStatusLine().getStatusCode(); Log.d(TAG, "status code=" + statusCode); if (statusCode == HttpURLConnection.HTTP_INTERNAL_ERROR) { Log.e(TAG, "error " + EntityUtils.toString(response.getEntity())); } success = statusCode == 201; entity.consumeContent(); } finally { client.getConnectionManager().shutdown(); } return success; }
From source file:org.dasein.cloud.vcloud.vCloudMethod.java
public @Nonnull String post(@Nonnull String action, @Nonnull String endpoint, @Nullable String contentType, @Nullable String payload) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("ENTER: " + vCloudMethod.class.getName() + ".post(" + endpoint + ")"); }//from w w w . ja va 2s.c om try { HttpClient client = null; if (wire.isDebugEnabled()) { wire.debug(""); wire.debug(">>> [POST (" + (new Date()) + ")] -> " + endpoint + " >--------------------------------------------------------------------------------------"); } try { Org org = authenticate(false); client = getClient(false); HttpPost post = new HttpPost(endpoint); post.addHeader("Accept", "application/*+xml;version=" + org.version.version + ",application/*+xml;version=" + org.version.version); addAuth(post, org.token); if (contentType != null) { post.addHeader("Content-Type", contentType); } if (wire.isDebugEnabled()) { wire.debug(post.getRequestLine().toString()); for (Header header : post.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } if (payload != null) { try { //noinspection deprecation post.setEntity( new StringEntity(payload == null ? "" : payload, "application/json", "UTF-8")); } catch (UnsupportedEncodingException e) { throw new InternalException(e); } try { wire.debug(EntityUtils.toString(post.getEntity())); } catch (IOException ignore) { } wire.debug(""); } HttpResponse response; try { APITrace.trace(provider, "POST " + action); response = client.execute(post); if (wire.isDebugEnabled()) { wire.debug(response.getStatusLine().toString()); for (Header header : response.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } } catch (IOException e) { logger.error("I/O error from server communications: " + e.getMessage()); throw new InternalException(e); } int code = response.getStatusLine().getStatusCode(); logger.debug("HTTP STATUS: " + code); if (code == HttpServletResponse.SC_NOT_FOUND) { throw new CloudException("No action match for " + endpoint); } else if (code == HttpServletResponse.SC_UNAUTHORIZED) { authenticate(true); return post(action, endpoint, contentType, payload); } else if (code == HttpServletResponse.SC_NO_CONTENT) { return ""; } else if (code == HttpServletResponse.SC_OK || code == HttpServletResponse.SC_CREATED || code == HttpServletResponse.SC_ACCEPTED) { String xml = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { xml = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(xml); wire.debug(""); } } } catch (IOException e) { logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } return xml; } else { logger.error("Expected OK or CREATED or NO_CONTENT or ACCEPTED for POST request, got " + code); String xml = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { xml = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(xml); wire.debug(""); } } } catch (IOException e) { logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } vCloudException.Data data = null; if (xml != null && !xml.equals("")) { Document doc = parseXML(xml); String docElementTagName = doc.getDocumentElement().getTagName(); String nsString = ""; if (docElementTagName.contains(":")) nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1); NodeList errors = doc.getElementsByTagName(nsString + "Error"); if (errors.getLength() > 0) { data = vCloudException.parseException(code, errors.item(0)); } } if (data == null) { throw new vCloudException(CloudErrorType.GENERAL, code, response.getStatusLine().getReasonPhrase(), "No further information"); } logger.error("[" + code + " : " + data.title + "] " + data.description); throw new vCloudException(data); } } finally { if (client != null) { client.getConnectionManager().shutdown(); } if (wire.isDebugEnabled()) { wire.debug("<<< [POST (" + (new Date()) + ")] -> " + endpoint + " <--------------------------------------------------------------------------------------"); wire.debug(""); } } } finally { if (logger.isTraceEnabled()) { logger.trace("EXIT: " + vCloudMethod.class.getName() + ".post()"); } } }
From source file:com.infinities.skyport.openstack.nova.os.SkyportNovaMethod.java
@Override protected @Nullable String postString(@Nonnull String authToken, @Nonnull String endpoint, @Nonnull String resource, @Nonnull String payload) throws CloudException, InternalException { Logger std = NovaOpenStack.getLogger(NovaOpenStack.class, "std"); Logger wire = NovaOpenStack.getLogger(NovaOpenStack.class, "wire"); if (std.isTraceEnabled()) { std.trace("enter - " + AbstractMethod.class.getName() + ".postString(" + authToken + "," + endpoint + "," + resource + "," + payload + ")"); }/*from w ww . j ava 2 s . com*/ if (wire.isDebugEnabled()) { wire.debug("---------------------------------------------------------------------------------" + endpoint + resource); wire.debug(""); } HttpClient client = null; try { client = getClient(); HttpPost post = new HttpPost(endpoint + resource); post.addHeader("Content-Type", "application/json"); post.addHeader("X-Auth-Token", authToken); if (wire.isDebugEnabled()) { wire.debug(post.getRequestLine().toString()); for (Header header : post.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } if (payload != null) { try { // noinspection deprecation post.setEntity(new StringEntity(payload == null ? "" : payload, "application/json", "UTF-8")); } catch (UnsupportedEncodingException e) { throw new InternalException(e); } try { wire.debug(EntityUtils.toString(post.getEntity())); } catch (IOException ignore) { } wire.debug(""); } HttpResponse response; try { std.debug("POST " + toAPIResource(resource)); response = client.execute(post); if (wire.isDebugEnabled()) { wire.debug(response.getStatusLine().toString()); for (Header header : response.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } } catch (IOException e) { std.error("I/O error from server communications: " + e.getMessage()); e.printStackTrace(); throw new InternalException("Communication error while reading from cloud endpoint", e); } int code = response.getStatusLine().getStatusCode(); std.debug("HTTP STATUS: " + code); if (code == HttpStatus.SC_REQUEST_TOO_LONG || code == HttpStatus.SC_REQUEST_URI_TOO_LONG) { String data = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { data = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(data); wire.debug(""); } } } catch (IOException e) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); e.printStackTrace(); throw new CloudException(e); } try { if (data != null) { JSONObject ob = new JSONObject(data); if (ob.has("overLimit")) { ob = ob.getJSONObject("overLimit"); int min = ob.optInt("retryAfter", 0); if (min < 1) { throw new CloudException(CloudErrorType.CAPACITY, 413, "Over Limit", ob.has("message") ? ob.getString("message") : "Over Limit"); } try { Thread.sleep(CalendarWrapper.MINUTE * min); } catch (InterruptedException ignore) { } return postString(authToken, endpoint, resource, payload); } } } catch (JSONException e) { throw new CloudException(e); } } if (code != HttpStatus.SC_OK && code != HttpStatus.SC_ACCEPTED && code != HttpStatus.SC_NO_CONTENT && code != HttpStatus.SC_CREATED) { std.error("postString(): Expected OK, ACCEPTED, or NO CONTENT for POST request, got " + code); String data = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { data = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(data); wire.debug(""); } } } catch (IOException e) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); e.printStackTrace(); throw new CloudException(e); } NovaException.ExceptionItems items = NovaException.parseException(code, data); if (items == null) { items = new NovaException.ExceptionItems(); items.code = 404; items.type = CloudErrorType.COMMUNICATION; items.message = "itemNotFound"; items.details = "No such object: " + resource; } std.error("postString(): [" + code + " : " + items.message + "] " + items.details); throw new NovaException(items); } else { if (code != HttpStatus.SC_NO_CONTENT) { String data = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { data = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(data); wire.debug(""); } } } catch (IOException e) { std.error("Failed to read response due to a cloud I/O error: " + e.getMessage()); e.printStackTrace(); throw new CloudException(e); } if (data != null && !data.trim().equals("")) { return data; } else if (code == HttpStatus.SC_ACCEPTED) { Header[] headers = response.getAllHeaders(); for (Header h : headers) { if (h.getName().equalsIgnoreCase("Location")) { return "{\"location\" : \"" + h.getValue().trim() + "\"}"; } } } } return null; } } finally { if (client != null) { client.getConnectionManager().shutdown(); } if (std.isTraceEnabled()) { std.trace("exit - " + AbstractMethod.class.getName() + ".postString()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("---------------------------------------------------------------------------------" + endpoint + resource); } } }