List of usage examples for javax.servlet.http HttpServletResponse SC_CREATED
int SC_CREATED
To view the source code for javax.servlet.http HttpServletResponse SC_CREATED.
Click Source Link
From source file:org.osaf.cosmo.cmp.CmpServlet.java
private void processUserCreate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {//from w w w . j a v a 2 s. c om Document xmldoc = readXmlRequest(req); String urlUsername = usernameFromPathInfo(req.getPathInfo()); UserResource resource = new UserResource(getUrlBase(req), xmldoc, entityFactory); User user = resource.getUser(); if (user.getUsername() != null && !user.getUsername().equals(urlUsername)) { log.warn("bad request for user create: " + "username does not match request URI"); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Username does not match request URI"); return; } user = userService.createUser(user, createUserCreateListeners(req)); resp.setStatus(HttpServletResponse.SC_CREATED); resp.setHeader("ETag", resource.getEntityTag()); } catch (SAXException e) { log.warn("error parsing request body: " + e.getMessage()); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Error parsing request body: " + e.getMessage()); return; } catch (CmpException e) { log.warn("bad request for user create: " + e.getMessage()); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } catch (ModelValidationException e) { handleModelValidationError(resp, e); } catch (InvalidStateException ise) { handleInvalidStateException(resp, ise); } }
From source file:org.dasein.cloud.azure.AzureMethod.java
public void tempRedirectInvoke(@Nonnull String tempEndpoint, @Nonnull String method, @Nonnull String account, @Nonnull String resource, @Nonnull String body) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("enter - " + AzureMethod.class.getName() + ".post(" + account + "," + resource + ")"); }//w w w .j a va2 s. c o m if (wire.isDebugEnabled()) { wire.debug("POST --------------------------------------------------------> " + endpoint + account + resource); wire.debug(""); } try { HttpClient client = getClient(); String url = tempEndpoint + account + resource; HttpRequestBase httpMethod = getMethod(method, url); //If it is networking configuration services if (httpMethod instanceof HttpPut) { if (url.endsWith("/services/networking/media")) { httpMethod.addHeader("Content-Type", "text/plain"); } else { httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8"); } } else { httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8"); } //dmayne version is older for anything to do with images and for disk deletion if (url.indexOf("/services/images") > -1 || (httpMethod instanceof HttpDelete && url.indexOf("/services/disks") > -1)) { httpMethod.addHeader("x-ms-version", "2012-08-01"); } else { httpMethod.addHeader("x-ms-version", "2012-03-01"); } if (wire.isDebugEnabled()) { wire.debug(httpMethod.getRequestLine().toString()); for (Header header : httpMethod.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (body != null) { wire.debug(body); wire.debug(""); } } if (httpMethod instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBase) httpMethod; if (body != null) { try { entityEnclosingMethod.setEntity(new StringEntity(body, "application/xml", "utf-8")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } HttpResponse response; StatusLine status; try { response = client.execute(httpMethod); status = response.getStatusLine(); } catch (IOException e) { logger.error("post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); if (logger.isTraceEnabled()) { e.printStackTrace(); } throw new CloudException(e); } if (logger.isDebugEnabled()) { logger.debug("post(): 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_OK && status.getStatusCode() != HttpServletResponse.SC_CREATED && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) { logger.error("post(): Expected OK for GET request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); 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) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), "Unknown", "Unknown"); } logger.error("post(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details); throw new AzureException(items); } } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + AzureMethod.class.getName() + ".post()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("POST --------------------------------------------------------> " + endpoint + account + resource); } } }
From source file:com.esri.gpt.control.rest.ManageDocumentServlet.java
private void createAndUpload(HttpServletRequest request, HttpServletResponse response, RequestContext context, Publisher publisher) throws IOException, IllegalStateException, ServletException, SchemaException, CatalogIndexException, ImsServiceException, SQLException, NotAuthorizedException, IdentityException { //XML/*from w w w .j a v a2 s . c om*/ InputStream xmlStream = request.getPart("xml").getInputStream(); String xml = IOUtils.toString(xmlStream, "UTF-8"); xml = Val.chkStr(Val.removeBOM(xml)); //read file OutputStream out = null; InputStream filecontent = request.getPart("file").getInputStream(); //ID InputStream idStream = request.getPart("id").getInputStream(); String id = IOUtils.toString(idStream, "UTF-8"); /**Collection<Part> x = request.getParts(); Part[] array = x.toArray (new Part[x.size ()]); for(int f=0; f<array.length;f++){ System.out.println(array[f].getName() + " " + array[f].getSize()); }*/ //verify - throw servlet exception ValidationRequest vRequest = new ValidationRequest(context, "id", xml); // in case of schema problems verify method would throw exception try { vRequest.verify(); } catch (ValidationException e) { System.out.println("valid error: " + e); throw new ServletException("409: Document failed to validate."); } //Save Zip file String webDataPath = Constant.UPLOAD_FOLDER, folder = id; new File(webDataPath + File.separator + folder).mkdir(); try { //initiate output stream out = new FileOutputStream(new File( webDataPath + File.separator + folder + File.separator + Constant.XML_OUTPUT_ZIP_NAME)); int read = 0; final byte[] bytes = new byte[1024]; while ((read = filecontent.read(bytes)) != -1) { out.write(bytes, 0, read); } } finally { //close all open streams if necessary if (out != null) { out.close(); } if (filecontent != null) { filecontent.close(); } } //save xml in mcp saveXml2Package(xml, id); //save xml in db if (xml.length() > 0) { //PublicationRequest pubRequest = new PublicationRequest(context,publisher,xml); //PublicationRecord pubRecord = pubRequest.getPublicationRecord(); //pubRecord.setPublicationMethod("editor"); //pubRequest.publish(); MovingCodePackage mvp = new MovingCodePackage(new File( webDataPath + File.separator + folder + File.separator + Constant.XML_OUTPUT_ZIP_NAME)); McpPublish mcpP = new McpPublish(mvp, webDataPath + File.separator + folder + File.separator + Constant.XML_OUTPUT_ZIP_NAME, id, context); if (mcpP.publish(false)) System.out.println("publishing successfully"); } response.setStatus(HttpServletResponse.SC_CREATED); }
From source file:org.dasein.cloud.azure.AzureStorageMethod.java
public void invoke(@Nonnull String strMethod, @Nonnull String resource, @Nonnull Map<String, String> queries, @Nullable String body, @Nullable Map<String, String> headerMap, boolean authorization) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("enter - " + AzureStorageMethod.class.getName() + "." + strMethod + "(" + getStorageAccount() + "," + resource + ")"); }/*from w w w .j a va2 s .co m*/ String endpoint = getStorageEnpoint(); if (wire.isDebugEnabled()) { wire.debug(strMethod + "--------------------------------------------------------> " + endpoint + getStorageAccount() + resource); wire.debug(""); } try { HttpClient client = getClient(); if (headerMap == null) { headerMap = new HashMap<String, String>(); } HttpRequestBase method = getMethod(strMethod, buildUrl(resource, queries), queries, headerMap, authorization); if (wire.isDebugEnabled()) { wire.debug(method.getRequestLine().toString()); for (Header header : method.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (body != null) { wire.debug(body); wire.debug(""); } } // If it is post or put if (method instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBase) method; if (body != null) { entityEnclosingMethod.setEntity(new StringEntity(body, "application/xml", "utf-8")); } } HttpResponse response; StatusLine status; try { response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { logger.error("post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); if (logger.isTraceEnabled()) { e.printStackTrace(); } throw new CloudException(e); } if (logger.isDebugEnabled()) { logger.debug("post(): 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_CREATED && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED && status.getStatusCode() != HttpServletResponse.SC_OK) && status.getStatusCode() != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION) { logger.error( strMethod + "(): Expected OK for " + strMethod + "request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); String result; if (entity == null) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } try { result = EntityUtils.toString(entity); } catch (IOException e) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } if (wire.isDebugEnabled()) { wire.debug(result); } wire.debug(""); AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), result); if (items != null) { logger.error(strMethod + "(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details); throw new AzureException(items); } else { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), "UnknownError", result); } } } catch (UnsupportedEncodingException e) { throw new CloudException(e); } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + AzureMethod.class.getName() + ".getStream()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("--------------------------------------------------------> "); } } }
From source file:org.opencastproject.adminui.endpoint.AbstractEventEndpoint.java
@POST @Path("{eventId}/comment") @Produces(MediaType.APPLICATION_JSON)/* w w w .j a v a 2 s.c o m*/ @RestQuery(name = "createeventcomment", description = "Creates a comment related to the event given by the identifier", returnDescription = "The comment related to the event as JSON", pathParameters = { @RestParameter(name = "eventId", description = "The event id", isRequired = true, type = RestParameter.Type.STRING) }, restParameters = { @RestParameter(name = "text", isRequired = true, description = "The comment text", type = TEXT), @RestParameter(name = "resolved", isRequired = false, description = "The comment resolved status", type = RestParameter.Type.BOOLEAN), @RestParameter(name = "reason", isRequired = false, description = "The comment reason", type = STRING) }, reponses = { @RestResponse(description = "The comment has been created.", responseCode = HttpServletResponse.SC_CREATED), @RestResponse(description = "If no text ist set.", responseCode = HttpServletResponse.SC_BAD_REQUEST), @RestResponse(description = "No event with this identifier was found.", responseCode = HttpServletResponse.SC_NOT_FOUND) }) public Response createEventComment(@PathParam("eventId") String eventId, @FormParam("text") String text, @FormParam("reason") String reason, @FormParam("resolved") Boolean resolved) throws Exception { Opt<Event> optEvent = getEvent(eventId); if (optEvent.isNone()) return notFound("Cannot find an event with id '%s'.", eventId); if (StringUtils.isBlank(text)) return Response.status(Status.BAD_REQUEST).build(); User author = getSecurityService().getUser(); try { Comment createdComment = Comment.create(Option.<Long>none(), text, author, reason, BooleanUtils.toBoolean(reason)); createdComment = getEventCommentService().updateComment(eventId, createdComment); List<Comment> comments = getEventCommentService().getComments(eventId); updateCommentCatalog(optEvent.get(), comments); return Response.created(getCommentUrl(eventId, createdComment.getId().get())) .entity(createdComment.toJson().toJson()).build(); } catch (Exception e) { logger.error("Unable to create a comment on the event {}: {}", eventId, ExceptionUtils.getStackTrace(e)); throw new WebApplicationException(e); } }
From source file:org.dasein.cloud.rackspace.AbstractMethod.java
protected @Nullable String putHeaders(@Nonnull String authToken, @Nonnull String endpoint, @Nonnull String resource, @Nonnull Map<String, String> customHeaders) throws CloudException, InternalException { Logger std = RackspaceCloud.getLogger(RackspaceCloud.class, "std"); Logger wire = RackspaceCloud.getLogger(RackspaceCloud.class, "wire"); if (std.isTraceEnabled()) { std.trace("enter - " + AbstractMethod.class.getName() + ".putHeaders(" + authToken + "," + endpoint + "," + resource + "," + customHeaders + ")"); }// www . ja va 2s .c om if (wire.isDebugEnabled()) { wire.debug("---------------------------------------------------------------------------------" + endpoint + resource); wire.debug(""); } try { HttpClient client = getClient(); HttpPut put = new HttpPut(endpoint + resource); put.addHeader("Content-Type", "application/json"); put.addHeader("X-Auth-Token", authToken); if (customHeaders != null) { for (Map.Entry<String, String> entry : customHeaders.entrySet()) { String val = (entry.getValue() == null ? "" : entry.getValue()); put.addHeader(entry.getKey(), val); } } if (wire.isDebugEnabled()) { wire.debug(put.getRequestLine().toString()); for (Header header : put.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } HttpResponse response; try { response = client.execute(put); 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(e); } int code = response.getStatusLine().getStatusCode(); std.debug("HTTP STATUS: " + code); if (code != HttpServletResponse.SC_CREATED && code != HttpServletResponse.SC_ACCEPTED && code != HttpServletResponse.SC_NO_CONTENT) { std.error("putString(): Expected CREATED, ACCEPTED, or NO CONTENT for put request, got " + code); HttpEntity entity = response.getEntity(); String json = null; if (entity != null) { try { json = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(json); wire.debug(""); } } catch (IOException e) { throw new CloudException(e); } } RackspaceException.ExceptionItems items = (json == null ? null : RackspaceException.parseException(code, json)); if (items == null) { items = new RackspaceException.ExceptionItems(); items.code = 404; items.type = CloudErrorType.COMMUNICATION; items.message = "itemNotFound"; items.details = "No such object: " + resource; } std.error("putString(): [" + code + " : " + items.message + "] " + items.details); throw new RackspaceException(items); } else { if (code == HttpServletResponse.SC_ACCEPTED || code == HttpServletResponse.SC_CREATED) { HttpEntity entity = response.getEntity(); String json = null; if (entity != null) { try { json = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(json); wire.debug(""); } } catch (IOException e) { throw new CloudException(e); } } if (json != null && !json.trim().equals("")) { return json; } } return null; } } finally { if (std.isTraceEnabled()) { std.trace("exit - " + AbstractMethod.class.getName() + ".putString()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("---------------------------------------------------------------------------------" + endpoint + resource); } } }
From source file:org.dasein.cloud.azure.AzureStorageMethod.java
public void putWithFile(@Nonnull String strMethod, @Nonnull String resource, Map<String, String> queries, File file, Map<String, String> headerMap, boolean authorization) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("enter - " + AzureStorageMethod.class.getName() + "." + strMethod + "(" + getStorageAccount() + "," + resource + ")"); }//w ww . j ava2 s .c om String endpoint = getStorageEnpoint(); if (wire.isDebugEnabled()) { wire.debug(strMethod + "--------------------------------------------------------> " + endpoint + getStorageAccount() + resource); wire.debug(""); } long begin = System.currentTimeMillis(); try { HttpClient client = getClient(); String contentLength = null; if (file != null) { contentLength = String.valueOf(file.length()); } else { contentLength = "0"; } HttpRequestBase method = getMethod(strMethod, buildUrl(resource, queries), queries, headerMap, authorization); if (wire.isDebugEnabled()) { wire.debug(method.getRequestLine().toString()); for (Header header : method.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (file != null) { wire.debug(file); wire.debug(""); } } // If it is post or put if (method instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBase) method; if (file != null) { entityEnclosingMethod.setEntity(new FileEntity(file, ContentType.APPLICATION_OCTET_STREAM)); } } HttpResponse response; StatusLine status; try { response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { logger.error("post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); if (logger.isTraceEnabled()) { e.printStackTrace(); } long end = System.currentTimeMillis(); logger.debug("Totoal time -> " + (end - begin)); throw new CloudException(e); } if (logger.isDebugEnabled()) { logger.debug("post(): 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_CREATED && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED && status.getStatusCode() != HttpServletResponse.SC_OK) && status.getStatusCode() != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION) { logger.error( strMethod + "(): Expected OK for " + strMethod + "request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); String result; if (entity == null) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } try { result = EntityUtils.toString(entity); } catch (IOException e) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } if (wire.isDebugEnabled()) { wire.debug(result); } wire.debug(""); AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), result); logger.error(strMethod + "(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details); throw new AzureException(items); } } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + AzureMethod.class.getName() + ".getStream()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("--------------------------------------------------------> "); } } }
From source file:org.clothocad.phagebook.controllers.OrdersController.java
@RequestMapping(value = "/resubmitOrder", method = RequestMethod.POST) public void resubmitOrder(@RequestParam Map<String, String> params, HttpServletResponse response) throws IOException, ServletException { ClothoConnection conn = new ClothoConnection(Args.clothoLocation); Clotho clothoObject = new Clotho(conn); String username = this.backendPhagebookUser; String password = this.backendPhagebookPassword; Map loginMap = new HashMap(); loginMap.put("username", username); loginMap.put("credentials", password); clothoObject.login(loginMap);/*from www. j a v a2 s . c o m*/ Order orderOld = ClothoAdapter.getOrder(params.get("orderId"), clothoObject); String orderName = orderOld.getName(); String createdBy = orderOld.getCreatedById(); String labId = orderOld.getAffiliatedLabId(); // Removed // Double taxRate = orderOld.getTaxRate(); String associatedProjectId = orderOld.getRelatedProjectId(); // Double budget = orderOld.getBudget(); // Integer orderLimit = orderOld.getMaxOrderSize(); Date date = new Date(); boolean isValid = false; //All parameters needed to create a new order as per the wire frame. if (!orderName.equals("") && !createdBy.equals("") && !labId.equals("") && !associatedProjectId.equals("")) { isValid = true; } if (isValid) { /* DIRECT ASSUMPTION THAT USER: phagebook exists and their PASSWORD: backend */ Order order = new Order(); order.setName(orderName); order.setCreatedById(createdBy); order.setDateCreated(date); // Removed // order.setBudget(budget); // order.setMaxOrderSize(orderLimit); // Added order.setTaxRate(0.00); order.setAffiliatedLabId(labId); order.setRelatedProjectId(associatedProjectId); order.setStatus(OrderStatus.INPROGRESS); ClothoAdapter.createOrder(order, clothoObject); // CREATED THE ORDER // BUT I NOW NEED TO LINK IT TO THE USER Person creator = ClothoAdapter.getPerson(order.getCreatedById(), clothoObject); List<String> createdOrders = creator.getCreatedOrders(); createdOrders.add(order.getId()); System.out.println("I am still on this part"); clothoObject.logout(); ClothoAdapter.setPerson(creator, clothoObject); // LINK CREATED response.setStatus(HttpServletResponse.SC_CREATED); PrintWriter writer = response.getWriter(); response.setContentType("application/JSON"); JSONObject responseJSON = new JSONObject(); responseJSON.put("message", "order created"); responseJSON.put("orderId", order.getId()); writer.println(responseJSON); writer.flush(); writer.close(); conn.closeConnection(); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); PrintWriter writer = response.getWriter(); response.setContentType("application/JSON"); JSONObject responseJSON = new JSONObject(); responseJSON.put("message", "Missing Required Parameters."); writer.println(responseJSON.toString()); writer.flush(); writer.close(); } PrintWriter writer = response.getWriter(); writer.println("temp"); writer.flush(); writer.close(); }
From source file:org.dasein.cloud.azure.AzureStorageMethod.java
public void putWithBytes(@Nonnull String strMethod, @Nonnull String resource, Map<String, String> queries, byte[] body, Map<String, String> headerMap, boolean authorization) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("enter - " + AzureStorageMethod.class.getName() + "." + strMethod + "(" + getStorageAccount() + "," + resource + ")"); }/*from ww w. j a va2 s . c o m*/ String endpoint = getStorageEnpoint(); if (wire.isDebugEnabled()) { wire.debug(strMethod + "--------------------------------------------------------> " + endpoint + getStorageAccount() + resource); wire.debug(""); } try { HttpClient client = getClient(); String contentLength = null; if (body != null) { contentLength = String.valueOf(body.length); } else { contentLength = "0"; } HttpRequestBase method = getMethod(strMethod, buildUrl(resource, queries), queries, headerMap, authorization); if (wire.isDebugEnabled()) { wire.debug(method.getRequestLine().toString()); for (Header header : method.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (body != null) { wire.debug(body); wire.debug(""); } } // If it is post or put if (method instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBase) method; if (body != null) { entityEnclosingMethod.setEntity(new ByteArrayEntity(body)); } } HttpResponse response; StatusLine status; try { response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { logger.error("post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); if (logger.isTraceEnabled()) { e.printStackTrace(); } throw new CloudException(e); } if (logger.isDebugEnabled()) { logger.debug("post(): 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_CREATED && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED && status.getStatusCode() != HttpServletResponse.SC_OK) && status.getStatusCode() != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION) { logger.error( strMethod + "(): Expected OK for " + strMethod + "request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); String result; if (entity == null) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } try { result = EntityUtils.toString(entity); } catch (IOException e) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } if (wire.isDebugEnabled()) { wire.debug(result); } wire.debug(""); AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), result); logger.error(strMethod + "(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details); throw new AzureException(items); } } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + AzureMethod.class.getName() + ".getStream()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("--------------------------------------------------------> "); } } }
From source file:org.dasein.cloud.rackspace.AbstractMethod.java
protected @Nullable String putString(@Nonnull String authToken, @Nonnull String endpoint, @Nonnull String resource, @Nullable String payload) throws CloudException, InternalException { Logger std = RackspaceCloud.getLogger(RackspaceCloud.class, "std"); Logger wire = RackspaceCloud.getLogger(RackspaceCloud.class, "wire"); if (std.isTraceEnabled()) { std.trace("enter - " + AbstractMethod.class.getName() + ".putString(" + authToken + "," + endpoint + "," + resource + "," + payload + ")"); }/* www .ja va 2s . c o m*/ if (wire.isDebugEnabled()) { wire.debug("---------------------------------------------------------------------------------" + endpoint + resource); wire.debug(""); } try { HttpClient client = getClient(); HttpPut put = new HttpPut(endpoint + resource); put.addHeader("Content-Type", "application/json"); put.addHeader("X-Auth-Token", authToken); if (payload != null) { put.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON)); } if (wire.isDebugEnabled()) { wire.debug(put.getRequestLine().toString()); for (Header header : put.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (payload != null) { wire.debug(payload); wire.debug(""); } } HttpResponse response; try { response = client.execute(put); 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(e); } int code = response.getStatusLine().getStatusCode(); std.debug("HTTP STATUS: " + code); if (code != HttpServletResponse.SC_CREATED && code != HttpServletResponse.SC_ACCEPTED && code != HttpServletResponse.SC_NO_CONTENT) { std.error("putString(): Expected CREATED, ACCEPTED, or NO CONTENT for put request, got " + code); HttpEntity entity = response.getEntity(); String json = null; if (entity != null) { try { json = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(json); wire.debug(""); } } catch (IOException e) { throw new CloudException(e); } } RackspaceException.ExceptionItems items = (json == null ? null : RackspaceException.parseException(code, json)); if (items == null) { items = new RackspaceException.ExceptionItems(); items.code = 404; items.type = CloudErrorType.COMMUNICATION; items.message = "itemNotFound"; items.details = "No such object: " + resource; } std.error("putString(): [" + code + " : " + items.message + "] " + items.details); throw new RackspaceException(items); } else { if (code == HttpServletResponse.SC_ACCEPTED || code == HttpServletResponse.SC_CREATED) { HttpEntity entity = response.getEntity(); String json = null; if (entity != null) { try { json = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(json); wire.debug(""); } } catch (IOException e) { throw new CloudException(e); } } if (json != null && !json.trim().equals("")) { return json; } } return null; } } finally { if (std.isTraceEnabled()) { std.trace("exit - " + AbstractMethod.class.getName() + ".putString()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("---------------------------------------------------------------------------------" + endpoint + resource); } } }