List of usage examples for javax.servlet.http HttpServletResponse SC_NO_CONTENT
int SC_NO_CONTENT
To view the source code for javax.servlet.http HttpServletResponse SC_NO_CONTENT.
Click Source Link
From source file:org.dasein.cloud.nimbula.NimbulaMethod.java
public @Nonnegative int list() throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("ENTER - " + NimbulaMethod.class.getName() + ".list()"); }//from www. j a v a 2 s .com try { ProviderContext ctx = cloud.getContext(); if (ctx == null) { throw new CloudException("No context was set for this request"); } authenticate(); String target; if (url.endsWith("info")) { target = url + "/"; } else { target = url + "/" + ctx.getAccountNumber() + "/"; } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug(">>> [GET (" + (new Date()) + ")] -> " + target + " >--------------------------------------------------------------------------------------"); } try { HttpClient client = getClient(ctx, target.startsWith("https")); HttpGet get = new HttpGet(target); get.addHeader("Accept", "application/nimbula-v2+json"); get.setHeader("Cookie", authCookie); if (wire.isDebugEnabled()) { wire.debug(get.getRequestLine().toString()); for (Header header : get.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } HttpResponse response; try { response = client.execute(get); 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); if (wire.isDebugEnabled()) { wire.debug(this.response); wire.debug(""); } } catch (IOException e) { throw new CloudException(e); } } } checkResponse(response, code); return code; } finally { if (wire.isDebugEnabled()) { wire.debug("<<< [GET (" + (new Date()) + ")] -> " + target + " <--------------------------------------------------------------------------------------"); wire.debug(""); } } } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + NimbulaMethod.class.getName() + ".list()"); } } }
From source file:org.apache.openaz.xacml.rest.XACMLPapServlet.java
/** * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response) *//*from w w w . jav a2 s .c om*/ @Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { XACMLRest.dumpRequest(request); // // since getParameter reads the content string, explicitly get the content before doing that. // Simply getting the inputStream seems to protect it against being consumed by getParameter. // request.getInputStream(); // // See if this is Admin Console registering itself with us // String acURLString = request.getParameter("adminConsoleURL"); if (acURLString != null) { // // remember this Admin Console for future updates // if (!adminConsoleURLStringList.contains(acURLString)) { adminConsoleURLStringList.add(acURLString); } if (logger.isDebugEnabled()) { logger.debug("Admin Console registering with URL: " + acURLString); } response.setStatus(HttpServletResponse.SC_NO_CONTENT); return; } // // Is this some other operation from the Admin Console? // String groupId = request.getParameter("groupId"); if (groupId != null) { // // this is from the Admin Console, so handle separately // doACPut(request, response, groupId); return; } // // We do not expect anything from anywhere else. // This method is here in case we ever need to support other operations. // response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId"); }
From source file:org.opendatakit.aggregate.externalservice.GoogleMapsEngine.java
private String executeGMEStmt(String method, String statement, CallingContext cc) throws ServiceException, IOException, ODKExternalServiceException, GeneralSecurityException { if (statement == null && (POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) { throw new ODKExternalServiceException(NO_BODY_ERROR); } else if (statement != null && !(POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) { throw new ODKExternalServiceException(BODY_SUPPLIED_ERROR); }/*from w ww. j av a 2 s . c o m*/ HttpContent entity = null; if (statement != null) { // the alternative -- using ContentType.create(,) throws an exception??? // entity = new StringEntity(statement, "application/json", UTF_8); // NOTE: by using HtmlConsts versus "application/json" we now include the // UTF-8 in the type // could cause problems so place to look for error entity = new ByteArrayContent(HtmlConsts.RESP_TYPE_JSON, statement.getBytes(HtmlConsts.UTF8_ENCODE)); } HttpRequest request = requestFactory.buildRequest(method, generateGmeUrl(), entity); request.setThrowExceptionOnExecuteError(false); HttpResponse resp = request.execute(); String response = WebUtils.readGoogleResponse(resp); int statusCode = resp.getStatusCode(); switch (statusCode) { case HttpServletResponse.SC_CONFLICT: logger.warn("GME CONFLICT DETECTED" + response + statement); case HttpServletResponse.SC_OK: case HttpServletResponse.SC_NO_CONTENT: return response; case HttpServletResponse.SC_FORBIDDEN: case HttpServletResponse.SC_UNAUTHORIZED: throw new ODKExternalServiceCredentialsException(response + statement); default: throw new ODKExternalServiceException(response + statement); } }
From source file:org.opencastproject.adminui.endpoint.EmailEndpoint.java
@DELETE @Path("template/{templateId}") @Produces(MediaType.APPLICATION_JSON)/*from w w w . jav a 2 s.c o m*/ @RestQuery(name = "deleteemailtemplate", description = "Deletes the email template by the given id", returnDescription = "No content", pathParameters = { @RestParameter(name = "templateId", description = "The template id", isRequired = true, type = RestParameter.Type.INTEGER) }, reponses = { @RestResponse(description = "Email template has been deleted", responseCode = HttpServletResponse.SC_NO_CONTENT), @RestResponse(description = "The template has not been found", responseCode = HttpServletResponse.SC_NOT_FOUND) }) public Response deleteEmailTemplate(@PathParam("templateId") long templateId) throws NotFoundException { try { mailService.deleteMessageTemplate(templateId); return Response.noContent().build(); } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not delete the email template {}: {}", templateId, ExceptionUtils.getStackTrace(e)); throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); } }
From source file:org.dasein.cloud.rackspace.AbstractMethod.java
protected @Nullable Map<String, String> head(@Nonnull String authToken, @Nonnull String endpoint, @Nonnull String resource) 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() + ".head(" + authToken + "," + endpoint + "," + resource + ")"); }/*w w w. j a v a 2s . com*/ if (wire.isDebugEnabled()) { wire.debug("--------------------------------------------------------> " + endpoint + resource); wire.debug(""); } try { HttpClient client = getClient(); HttpHead head = new HttpHead(endpoint + resource); head.addHeader("X-Auth-Token", authToken); if (wire.isDebugEnabled()) { wire.debug(head.getRequestLine().toString()); for (Header header : head.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } HttpResponse response; try { response = client.execute(head); 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_NO_CONTENT && code != HttpServletResponse.SC_OK) { if (code == HttpServletResponse.SC_NOT_FOUND) { return null; } std.error("head(): Expected NO CONTENT or OK for HEAD 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) { return null; } std.error("head(): [" + code + " : " + items.message + "] " + items.details); throw new RackspaceException(items); } HashMap<String, String> map = new HashMap<String, String>(); for (Header h : response.getAllHeaders()) { map.put(h.getName().trim(), h.getValue().trim()); } return map; } finally { if (std.isTraceEnabled()) { std.trace("exit - " + AbstractMethod.class.getName() + ".head()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("--------------------------------------------------------> " + endpoint + resource); } } }
From source file:org.ednovo.gooru.controllers.v2.api.TaskManagementRestV2Controller.java
@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_TASK_MANAGEMENT_DELETE }) @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @RequestMapping(method = RequestMethod.DELETE, value = { "/associate/{id}" }) public void deleteTaskAssoc(@PathVariable(ID) String taskAssocUid, HttpServletRequest request, HttpServletResponse response) {//from ww w .ja v a2s. co m this.getTaskService().deleteTaskAssoc(taskAssocUid); SessionContextSupport.putLogParameter(EVENTNAME, DELETE_TASK_ASSOC); SessionContextSupport.putLogParameter(TASK_ASSOC_UID, taskAssocUid); response.setStatus(HttpServletResponse.SC_NO_CONTENT); }
From source file:com.imaginary.home.controller.CloudService.java
public boolean postResult(@Nonnull String cmdId, boolean stateChanged, @Nullable Throwable exception) throws CommunicationException, ControllerException { HttpClient client = getClient(endpoint, proxyHost, proxyPort); HttpPut method = new HttpPut(endpoint + "/command/" + cmdId); long timestamp = System.currentTimeMillis(); method.addHeader("Content-Type", "application/json"); method.addHeader("x-imaginary-version", VERSION); method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp)); method.addHeader("x-imaginary-api-key", serviceId); if (token == null) { authenticate();//from ww w . j av a 2 s . c om } String stringToSign = "PUT:/command/" + cmdId + ":" + serviceId + ":" + token + ":" + timestamp + ":" + VERSION; try { method.addHeader("x-imaginary-signature", sign(apiKeySecret.getBytes("utf-8"), stringToSign)); } catch (Exception e) { throw new ControllerException(e); } HashMap<String, Object> state = new HashMap<String, Object>(); state.put("action", "complete"); Map<String, Object> result = new HashMap<String, Object>(); result.put("result", stateChanged); if (exception != null) { result.put("errorMessage", exception.getMessage()); } state.put("result", result); try { //noinspection deprecation method.setEntity(new StringEntity((new JSONObject(state)).toString(), "application/json", "UTF-8")); } catch (UnsupportedEncodingException e) { throw new ControllerException(e); } HttpResponse response; StatusLine status; try { response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { e.printStackTrace(); throw new CommunicationException(e); } if (status.getStatusCode() != HttpServletResponse.SC_NO_CONTENT) { parseError(response); // this will throw an exception } Header h = response.getFirstHeader("x-imaginary-has-commands"); String val = (h == null ? "false" : h.getValue()); return (val != null && val.equalsIgnoreCase("true")); }
From source file:com.zimbra.cs.service.UserServletContext.java
public InputStream getRequestInputStream(long limit) throws IOException, ServiceException, UserServletException { String contentType = MimeConstants.CT_APPLICATION_OCTET_STREAM; String filename = null;/*from w w w. j a v a 2 s .c om*/ InputStream is = null; final long DEFAULT_MAX_SIZE = 10 * 1024 * 1024; if (limit == 0) { if (req.getParameter("lbfums") != null) { limit = Provisioning.getInstance().getLocalServer() .getLongAttr(Provisioning.A_zimbraFileUploadMaxSize, DEFAULT_MAX_SIZE); } else { limit = Provisioning.getInstance().getConfig().getLongAttr(Provisioning.A_zimbraMtaMaxMessageSize, DEFAULT_MAX_SIZE); } } boolean doCsrfCheck = false; if (req.getAttribute(CsrfFilter.CSRF_TOKEN_CHECK) != null) { doCsrfCheck = (Boolean) req.getAttribute(CsrfFilter.CSRF_TOKEN_CHECK); } if (ServletFileUpload.isMultipartContent(req)) { ServletFileUpload sfu = new ServletFileUpload(); try { FileItemIterator iter = sfu.getItemIterator(req); while (iter.hasNext()) { FileItemStream fis = iter.next(); if (fis.isFormField()) { is = fis.openStream(); params.put(fis.getFieldName(), new String(ByteUtil.getContent(is, -1), "UTF-8")); if (doCsrfCheck && !this.csrfAuthSucceeded) { String csrfToken = params.get(FileUploadServlet.PARAM_CSRF_TOKEN); if (UserServlet.log.isDebugEnabled()) { String paramValue = req.getParameter(UserServlet.QP_AUTH); UserServlet.log.debug( "CSRF check is: %s, CSRF token is: %s, Authentication recd with request is: %s", doCsrfCheck, csrfToken, paramValue); } if (!CsrfUtil.isValidCsrfToken(csrfToken, authToken)) { setCsrfAuthSucceeded(Boolean.FALSE); UserServlet.log.debug( "CSRF token validation failed for account: %s" + ", Auth token is CSRF enabled: %s" + "CSRF token is: %s", authToken, authToken.isCsrfTokenEnabled(), csrfToken); throw new UserServletException(HttpServletResponse.SC_UNAUTHORIZED, L10nUtil.getMessage(MsgKey.errMustAuthenticate)); } else { setCsrfAuthSucceeded(Boolean.TRUE); } } is.close(); is = null; } else { is = new UploadInputStream(fis.openStream(), limit); break; } } } catch (UserServletException e) { throw new UserServletException(e.getHttpStatusCode(), e.getMessage(), e); } catch (Exception e) { throw new UserServletException(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, e.toString()); } if (is == null) throw new UserServletException(HttpServletResponse.SC_NO_CONTENT, "No file content"); } else { ContentType ctype = new ContentType(req.getContentType()); String contentEncoding = req.getHeader("Content-Encoding"); contentType = ctype.getContentType(); filename = ctype.getParameter("name"); if (filename == null || filename.trim().equals("")) filename = new ContentDisposition(req.getHeader("Content-Disposition")).getParameter("filename"); is = new UploadInputStream(contentEncoding != null && contentEncoding.indexOf("gzip") != -1 ? new GZIPInputStream(req.getInputStream()) : req.getInputStream(), limit); } if (filename == null || filename.trim().equals("")) filename = "unknown"; else params.put(UserServlet.UPLOAD_NAME, filename); params.put(UserServlet.UPLOAD_TYPE, contentType); ZimbraLog.mailbox.info("UserServlet received file %s - %d request bytes", filename, req.getContentLength()); return is; }
From source file:org.eclipse.vtp.framework.engine.http.HttpConnector.java
/** * invokeProcessEngine./*from w ww . j ava2 s. c o m*/ * * @param req * @param res * @param httpSession * @param pathInfo * @param embeddedInvocation TODO * @throws IOException * @throws ServletException */ private void invokeProcessEngine(HttpServletRequest req, HttpServletResponse res, HttpSession httpSession, String pathInfo, Map<Object, Object> variableValues, @SuppressWarnings("rawtypes") Map<String, String[]> parameterValues, boolean embeddedInvocation) throws IOException, ServletException { boolean newSession = false; Integer depth = (Integer) httpSession.getAttribute("connector.depth"); if (depth == null) { depth = new Integer(0); } String prefix = "connector.attributes."; String fullPrefix = prefix + depth.intValue() + "."; if (embeddedInvocation) httpSession.setAttribute(fullPrefix + "fragment", "true"); Deployment deployment = null; String brand = null; String entryName = null; boolean subdialog = false; if (!pathInfo.startsWith(PATH_PREFIX)) { System.out.println("invoking process engine for new session: " + pathInfo); newSession = true; synchronized (this) { for (String path : deploymentsByPath.keySet()) { System.out.println("Comparing to deployment: " + path); if (pathInfo.equals(path) || pathInfo.startsWith(path) && pathInfo.length() > path.length() && pathInfo.charAt(path.length()) == '/') { deployment = deploymentsByPath.get(path); System.out.println("Matching deployment found: " + deployment); brand = req.getParameter("BRAND"); if (req.getParameter("SUBDIALOG") != null) subdialog = Boolean.parseBoolean(req.getParameter("SUBDIALOG")); if (pathInfo.length() > path.length() + 1) { entryName = pathInfo.substring(path.length() + 1); System.out.println("Entry point name: " + entryName); } break; } } } if (deployment == null) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (entryName == null) { res.sendError(HttpServletResponse.SC_FORBIDDEN); return; } pathInfo = NEXT_PATH; httpSession.setAttribute(fullPrefix + DEPLOYMENT_ID, deployment.getProcessID()); } else if (pathInfo.equals(LOG_PATH)) { if (req.getParameter("cmd") != null && req.getParameter("cmd").equals("set")) { String level = req.getParameter("level"); if (level == null || (!level.equalsIgnoreCase("ERROR") && !level.equalsIgnoreCase("WARN") && !level.equalsIgnoreCase("INFO") && !level.equalsIgnoreCase("DEBUG"))) level = "INFO"; System.setProperty("org.eclipse.vtp.loglevel", level); } writeLogging(req, res); return; } else { String deploymentID = (String) httpSession.getAttribute(fullPrefix + DEPLOYMENT_ID); synchronized (this) { deployment = deploymentsByID.get(deploymentID); } if (deployment == null) { res.sendError(HttpServletResponse.SC_FORBIDDEN); return; } } if (subdialog) httpSession.setAttribute(fullPrefix + "subdialog", "true"); if (pathInfo.equals(INDEX_PATH)) { writeIndex(res, deployment); return; } ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); if (ServletFileUpload.isMultipartContent(new ServletRequestContext(req))) { System.out.println( "ServletFileUpload.isMultipartContent(new ServletRequestContext(httpRequest)) is true"); try { List items = upload.parseRequest(req); for (int i = 0; i < items.size(); i++) { FileItem fui = (FileItem) items.get(i); if (fui.isFormField() || "text/plain".equals(fui.getContentType())) { System.out.println("Form Field: " + fui.getFieldName() + " | " + fui.getString()); parameterValues.put(fui.getFieldName(), new String[] { fui.getString() }); } else { File temp = File.createTempFile(Guid.createGUID(), ".tmp"); fui.write(temp); parameterValues.put(fui.getFieldName(), new String[] { temp.getAbsolutePath() }); fui.delete(); System.out.println("File Upload: " + fui.getFieldName()); System.out.println("\tTemp file name: " + temp.getAbsolutePath()); System.out.println("\tContent Type: " + fui.getContentType()); System.out.println("\tSize: " + fui.getSize()); } } } catch (Exception e) { e.printStackTrace(); } } for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); parameterValues.put(key, req.getParameterValues(key)); } for (String key : parameterValues.keySet()) { String[] values = parameterValues.get(key); if (values == null || values.length == 0) System.out.println(key + " empty"); else { System.out.println(key + " " + values[0]); for (int i = 1; i < values.length; i++) System.out.println("\t" + values[i]); } } IDocument document = null; if (pathInfo.equals(ABORT_PATH)) document = deployment.abort(httpSession, req, res, prefix, depth.intValue(), variableValues, parameterValues); else if (pathInfo.equals(NEXT_PATH)) { if (brand == null && !newSession) document = deployment.next(httpSession, req, res, prefix, depth.intValue(), variableValues, parameterValues); else document = deployment.start(httpSession, req, res, prefix, depth.intValue(), variableValues, parameterValues, entryName, brand, subdialog); } else { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (document == null) { res.setStatus(HttpServletResponse.SC_NO_CONTENT); return; } else if (document instanceof ControllerDocument) { ControllerDocument cd = (ControllerDocument) document; if (cd.getTarget() == null) { @SuppressWarnings("unchecked") Map<String, Map<String, Object>> outgoing = (Map<String, Map<String, Object>>) httpSession .getAttribute(fullPrefix + "outgoing-data"); int newDepth = depth.intValue() - 1; if (newDepth == 0) httpSession.removeAttribute("connector.depth"); else httpSession.setAttribute("connector.depth", new Integer(newDepth)); String oldFullPrefix = fullPrefix; fullPrefix = prefix + newDepth + "."; Object[] params = (Object[]) httpSession.getAttribute(fullPrefix + "exitparams"); if (params != null) for (int i = 0; i < params.length; i += 2) parameterValues.put((String) params[i], (String[]) params[i + 1]); String[] paramNames = cd.getParameterNames(); for (int i = 0; i < paramNames.length; ++i) parameterValues.put(paramNames[i], cd.getParameterValues(paramNames[i])); String[] variableNames = cd.getVariableNames(); Map<Object, Object> variables = new HashMap<Object, Object>(variableNames.length); if (outgoing != null) { Map<String, Object> map = outgoing.get(cd.getParameterValues("exit")[0]); if (map != null) { for (int i = 0; i < variableNames.length; ++i) { Object mapping = map.get(variableNames[i]); if (mapping != null) variables.put(mapping, cd.getVariableValue(variableNames[i])); } } } deployment.end(httpSession, prefix, depth.intValue()); for (@SuppressWarnings("rawtypes") Enumeration e = httpSession.getAttributeNames(); e.hasMoreElements();) { String name = (String) e.nextElement(); if (name.startsWith(oldFullPrefix)) httpSession.removeAttribute(name); } invokeProcessEngine(req, res, httpSession, NEXT_PATH, variables, parameterValues, newDepth > 0); return; } else { String[] paramNames = cd.getParameterNames(); Object[] params = new Object[paramNames.length * 2]; for (int i = 0; i < params.length; i += 2) { params[i] = paramNames[i / 2]; params[i + 1] = cd.getParameterValues(paramNames[i / 2]); } httpSession.setAttribute(fullPrefix + "exitparams", params); String[] variableNames = cd.getVariableNames(); Map<Object, Object> variables = new HashMap<Object, Object>(variableNames.length); for (int i = 0; i < variableNames.length; ++i) variables.put(variableNames[i], cd.getVariableValue(variableNames[i])); httpSession.setAttribute("connector.depth", new Integer(depth.intValue() + 1)); fullPrefix = prefix + (depth.intValue() + 1) + "."; String deploymentId = cd.getTarget().substring(0, cd.getTarget().lastIndexOf('(') - 1); String entryPointName = cd.getTarget().substring(cd.getTarget().lastIndexOf('(') + 1, cd.getTarget().length() - 1); httpSession.setAttribute(fullPrefix + DEPLOYMENT_ID, deploymentId); httpSession.setAttribute(fullPrefix + ENTRY_POINT_NAME, entryPointName); Map<String, Map<String, Object>> outgoing = new HashMap<String, Map<String, Object>>(); String[] outPaths = cd.getOutgoingPaths(); for (int i = 0; i < outPaths.length; ++i) { Map<String, Object> map = new HashMap<String, Object>(); String[] names = cd.getOutgoingDataNames(outPaths[i]); for (int j = 0; j < names.length; ++j) map.put(names[j], cd.getOutgoingDataValue(outPaths[i], names[j])); outgoing.put(outPaths[i], map); } httpSession.setAttribute(fullPrefix + "outgoing-data", outgoing); invokeProcessEngine(req, res, httpSession, "/" + deploymentId + "/" + entryPointName, variables, parameterValues, true); return; } } res.setStatus(HttpServletResponse.SC_OK); if (!document.isCachable()) res.setHeader("Cache-Control", "max-age=0, no-cache"); res.setContentType(document.getContentType()); OutputStream writer = res.getOutputStream(); try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); XMLWriter xmlWriter = new XMLWriter(writer); xmlWriter.setCompactElements(true); transformer.transform(document.toXMLSource(), xmlWriter.toXMLResult()); if (reporter.isSeverityEnabled(IReporter.SEVERITY_INFO) && !document.isSecured()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); xmlWriter = new XMLWriter(baos); xmlWriter.setCompactElements(true); transformer.transform(document.toXMLSource(), xmlWriter.toXMLResult()); System.out.println(new String(baos.toByteArray(), "UTF-8")); } } catch (TransformerException e) { throw new ServletException(e); } writer.flush(); writer.close(); }
From source file:org.dasein.cloud.ibm.sce.SCEMethod.java
public @Nullable String put(@Nonnull String resource, @Nullable List<NameValuePair> parameters) 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() + ".post(" + resource + ")"); }/*from www.j a va 2s . c o m*/ if (wire.isDebugEnabled()) { wire.debug("POST --------------------------------------------------------> " + endpoint + resource); wire.debug(""); } try { HttpClient client = getClient(); HttpPut method = new HttpPut(endpoint + resource); method.addHeader("Content-Type", "application/x-www-form-urlencoded"); method.addHeader("Accept", "text/xml"); if (wire.isDebugEnabled()) { wire.debug(method.getRequestLine().toString()); for (Header header : method.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (parameters != null) { Iterator<NameValuePair> it = parameters.iterator(); StringBuilder str = new StringBuilder(); while (it.hasNext()) { NameValuePair p = it.next(); str.append(p.getName()).append("=").append(p.getValue()); if (it.hasNext()) { str.append("&"); } } wire.debug(str.toString()); wire.debug(""); } } if (parameters != null) { try { method.setEntity(new UrlEncodedFormEntity(parameters, "utf-8")); } catch (UnsupportedEncodingException e) { throw new InternalException(e); } } HttpResponse response; StatusLine status; try { APITrace.trace(provider, resource); response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { std.error("post(): 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("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) { std.error("post(): 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 if (status.getStatusCode() == HttpServletResponse.SC_NO_CONTENT) { return null; } else { HttpEntity entity = response.getEntity(); if (entity == null) { return null; } try { return EntityUtils.toString(entity); } catch (IOException e) { throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } } } finally { if (std.isTraceEnabled()) { std.trace("exit - " + SCEMethod.class.getName() + ".post()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("POST --------------------------------------------------------> " + endpoint + resource); } } }