List of usage examples for javax.servlet.http HttpServletResponse SC_ACCEPTED
int SC_ACCEPTED
To view the source code for javax.servlet.http HttpServletResponse SC_ACCEPTED.
Click Source Link
From source file:org.apache.axis2.transport.http.AxisServlet.java
/** * Processing for faults/*from ww w .j ava 2s.c o m*/ * * @param msgContext * @param res * @param out * @param e */ void processAxisFault(MessageContext msgContext, HttpServletResponse res, OutputStream out, AxisFault e) { try { // If the fault is not going along the back channel we should be 202ing if (AddressingHelper.isFaultRedirected(msgContext)) { res.setStatus(HttpServletResponse.SC_ACCEPTED); } else { String status = (String) msgContext.getProperty(Constants.HTTP_RESPONSE_STATE); if (status == null) { res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } else { res.setStatus(Integer.parseInt(status)); } AxisBindingOperation axisBindingOperation = (AxisBindingOperation) msgContext .getProperty(Constants.AXIS_BINDING_OPERATION); if (axisBindingOperation != null) { AxisBindingMessage fault = axisBindingOperation .getFault((String) msgContext.getProperty(Constants.FAULT_NAME)); if (fault != null) { Integer code = (Integer) fault.getProperty(WSDL2Constants.ATTR_WHTTP_CODE); if (code != null) { res.setStatus(code.intValue()); } } } } handleFault(msgContext, out, e); } catch (AxisFault e2) { log.info(e2); } }
From source file:org.openrepose.common.auth.openstack.AuthenticationServiceClient.java
@Override public AuthGroups getGroups(String userId, String tracingHeader) throws AuthServiceException { final Map<String, String> headers = new HashMap<>(); AuthGroups authGroups;/*from ww w . j av a 2s. c om*/ try { headers.put(ACCEPT_HEADER, MediaType.APPLICATION_XML); headers.put(AUTH_TOKEN_HEADER, getAdminToken(tracingHeader, false)); if (tracingHeader != null) { headers.put(CommonHttpHeader.TRACE_GUID.toString(), tracingHeader); } ServiceClientResponse serviceResponse = akkaServiceClient.get(GROUPS_PREFIX + userId, targetHostUri + "/users/" + userId + "/RAX-KSGRP", headers); switch (serviceResponse.getStatus()) { case HttpServletResponse.SC_OK: authGroups = getAuthGroups(serviceResponse); break; case HttpServletResponse.SC_UNAUTHORIZED: LOG.error("Unable to get groups for user: " + serviceResponse.getStatus() + " :admin token expired. Retrieving new admin token and retrying groups retrieval..."); headers.put(AUTH_TOKEN_HEADER, getAdminToken(tracingHeader, true)); serviceResponse = akkaServiceClient.get(GROUPS_PREFIX + userId, targetHostUri + "/users/" + userId + "/RAX-KSGRP", headers); if (serviceResponse.getStatus() == HttpServletResponse.SC_ACCEPTED) { authGroups = getAuthGroups(serviceResponse); } else { delegationMessage.set("Unable to get groups for user id: " + userId + ". Status code: " + serviceResponse.getStatus()); LOG.error("Still unable to get groups: " + serviceResponse.getStatus()); throw new AuthServiceException("Unable to retrieve groups for user. Response from " + targetHostUri + ": " + serviceResponse.getStatus()); } break; case HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE: case FilterDirector.SC_TOO_MANY_REQUESTS: // (413 | 429) delegationMessage.set("Unable to get groups for user id: " + userId + ". Status code: " + serviceResponse.getStatus()); throw buildAuthServiceOverLimitException(serviceResponse); default: delegationMessage.set("Unable to get groups for user id: " + userId + ". Status code: " + serviceResponse.getStatus()); LOG.error("Unable to get groups for user id: " + userId + " Status code: " + serviceResponse.getStatus()); throw new AuthServiceException("Unable to retrieve groups for user. Response from " + targetHostUri + ": " + serviceResponse.getStatus()); } } catch (AkkaServiceClientException e) { throw new AuthServiceException("Unable to get groups.", e); } return authGroups; }
From source file:org.ajax4jsf.webapp.BaseFilter.java
/** * Execute the filter.// w w w. j ava 2 s . c om */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { long startTimeMills = 0; // Detect case of request - normal, AJAX, AJAX - JavaScript // TODO - detect first processing in filter. HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; if (log.isDebugEnabled()) { startTimeMills = System.currentTimeMillis(); log.debug(Messages.getMessage(Messages.FILTER_START_INFO, new Date(startTimeMills), httpServletRequest.getRequestURI())); } if (request.getAttribute(FILTER_PERFORMED) != Boolean.TRUE) { // mark - and not processing same request twice. try { request.setAttribute(FILTER_PERFORMED, Boolean.TRUE); String ajaxPushHeader = httpServletRequest.getHeader(AJAX_PUSH_KEY_HEADER); // check for a push check request. if (httpServletRequest.getMethod().equals("HEAD") && null != ajaxPushHeader) { PushEventsCounter listener = eventsManager.getListener(ajaxPushHeader); // To avoid XmlHttpRequest parsing exceptions. httpServletResponse.setContentType("text/plain"); if (listener.isPerformed()) { listener.processed(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.setHeader(AJAX_PUSH_STATUS_HEADER, AJAX_PUSH_READY); if (log.isDebugEnabled()) { log.debug("Occurs event for a id " + ajaxPushHeader); } } else { // Response code - 'No content' httpServletResponse.setStatus(HttpServletResponse.SC_ACCEPTED); if (log.isDebugEnabled()) { log.debug("No event for a id " + ajaxPushHeader); } } httpServletResponse.setContentLength(0); } else // check for resource request if (!getResourceService().serviceResource(httpServletRequest, httpServletResponse)) { // Not request to resource - perform filtering. // first stage - detect/set encoding of request. Same as in // Myfaces External Context. setupRequestEncoding(httpServletRequest); processUploadsAndHandleRequest(httpServletRequest, httpServletResponse, chain); } } finally { // Remove filter marker from response, to enable sequence calls ( for example, forward to error page ) request.removeAttribute(FILTER_PERFORMED); Object ajaxContext = request.getAttribute(AjaxContext.AJAX_CONTEXT_KEY); if (null != ajaxContext && ajaxContext instanceof AjaxContext) { ((AjaxContext) ajaxContext).release(); request.removeAttribute(AjaxContext.AJAX_CONTEXT_KEY); } } } else { if (log.isDebugEnabled()) { log.debug(Messages.getMessage(Messages.FILTER_NO_XML_CHAIN_2)); } chain.doFilter(request, response); } if (log.isDebugEnabled()) { startTimeMills = System.currentTimeMillis() - startTimeMills; log.debug(Messages.getMessage(Messages.FILTER_STOP_INFO, "" + startTimeMills, httpServletRequest.getRequestURI())); } }
From source file:com.imaginary.home.device.hue.HueMethod.java
public JSONObject put(@Nonnull String resource, JSONObject body) throws HueException { Logger std = Hue.getLogger(HueMethod.class); Logger wire = Hue.getWireLogger(HueMethod.class); if (std.isTraceEnabled()) { std.trace("enter - " + HueMethod.class.getName() + ".put(" + resource + ")"); }//from w w w.ja v a 2 s . co m if (wire.isDebugEnabled()) { wire.debug(""); wire.debug(">>> [PUT (" + (new Date()) + ")] -> " + hue.getAPIEndpoint() + resource); } try { HttpClient client = getClient(); HttpPut method = new HttpPut(hue.getAPIEndpoint() + resource); method.addHeader("Content-Type", "application/json"); try { if (body != null) { //noinspection deprecation method.setEntity(new StringEntity(body.toString(), "application/json", "UTF-8")); } } catch (UnsupportedEncodingException e) { throw new HueException(e); } if (wire.isDebugEnabled()) { wire.debug(method.getRequestLine().toString()); for (Header header : method.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (body != null) { try { wire.debug(EntityUtils.toString(method.getEntity())); } catch (IOException ignore) { } wire.debug(""); } } HttpResponse response; StatusLine status; try { response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { std.error("PUT: Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); if (std.isTraceEnabled()) { e.printStackTrace(); } throw new HueException(e); } if (std.isDebugEnabled()) { std.debug("PUT: 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_NO_CONTENT) { return null; } else if (status.getStatusCode() != HttpServletResponse.SC_OK && status.getStatusCode() != HttpServletResponse.SC_CREATED && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) { std.error("PUT: Expected NO_CONTENT or CREATED or OK or ACCEPTED for PUT request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); if (entity == null) { throw new HueException(status.getStatusCode(), "An error was returned without explanation"); } String json; try { json = EntityUtils.toString(entity); } catch (IOException e) { throw new HueException(status.getStatusCode(), e.getMessage()); } if (wire.isDebugEnabled()) { wire.debug(json); wire.debug(""); } throw new HueException(status.getStatusCode(), json); } else { try { String json = EntityUtils.toString(response.getEntity()); if (wire.isDebugEnabled()) { wire.debug(json); wire.debug(""); } if (json.startsWith("[")) { JSONArray arr = new JSONArray(json); if (arr.length() > 0) { JSONObject ob = arr.getJSONObject(0); if (ob.has("error")) { ob = ob.getJSONObject("error"); if (ob.has("description")) { throw new HueException(ob.getString("description")); } } return ob; } return null; } return new JSONObject(json); } catch (IOException e) { throw new HueException(status.getStatusCode(), e.getMessage()); } catch (JSONException e) { throw new HueException(status.getStatusCode(), e.getMessage()); } } } finally { if (std.isTraceEnabled()) { std.trace("exit - " + HueMethod.class.getName() + ".put()"); } if (wire.isDebugEnabled()) { wire.debug("<<< [PUT (" + (new Date()) + ")] -> " + hue.getAPIEndpoint() + resource + " <--------------------------------------------------------------------------------------"); wire.debug(""); } } }
From source file:org.dasein.cloud.ibm.sce.SCEMethod.java
public @Nullable String post(@Nonnull String resource, @Nonnull 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 + ")"); }/* ww w. ja v a2s . c om*/ if (wire.isDebugEnabled()) { wire.debug("POST --------------------------------------------------------> " + endpoint + resource); wire.debug(""); } try { HttpClient client = getClient(); HttpPost post = new HttpPost(endpoint + resource); post.addHeader("Content-Type", "application/x-www-form-urlencoded"); post.addHeader("Accept", "text/xml"); if (wire.isDebugEnabled()) { wire.debug(post.getRequestLine().toString()); for (Header header : post.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 { post.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(post); 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); } } }
From source file:com.imaginary.home.cloud.CloudTest.java
private void setupCommand() throws Exception { HashMap<String, Object> action = new HashMap<String, Object>(); action.put("action", testCommandId == null ? "flipOn" : "flipOff"); action.put("arguments", new ArrayList<Map<String, Object>>()); HttpClient client = getClient();// w w w. j a v a 2 s .c o m HttpPut method = new HttpPut(cloudAPI + "/device/" + testDeviceId); 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", apiKeyId); method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"), "put:/device/" + testDeviceId + ":" + apiKeyId + ":" + timestamp + ":" + VERSION)); //noinspection deprecation method.setEntity(new StringEntity((new JSONObject(action)).toString(), "application/json", "UTF-8")); 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_ACCEPTED) { String json = EntityUtils.toString(response.getEntity()); JSONArray list = new JSONArray(json); JSONObject cmd = list.getJSONObject(0); testCommandId = cmd.getString("commandId"); } else { Assert.fail("Failed to setup test command (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); } }
From source file:com.geoxp.oss.client.OSSClient.java
public static boolean init(String ossURL, byte[] secret, String sshKeyFingerprint) throws OSSException { SSHAgentClient agent = null;//from www .ja va 2 s . c o m HttpClient httpclient = newHttpClient(); try { agent = new SSHAgentClient(); List<SSHKey> sshkeys = agent.requestIdentities(); // // If no SSH Key fingerprint was provided, try all SSH keys available in the agent // List<String> fingerprints = new ArrayList<String>(); if (null == sshKeyFingerprint) { for (SSHKey key : sshkeys) { fingerprints.add(key.fingerprint); } } else { fingerprints.add(sshKeyFingerprint.toLowerCase().replaceAll("[^0-9a-f]", "")); } int idx = 0; for (String fingerprint : fingerprints) { idx++; // // Ask the SSH agent for the SSH key blob // byte[] keyblob = null; for (SSHKey key : sshkeys) { if (key.fingerprint.equals(fingerprint)) { keyblob = key.blob; break; } } // // Throw an exception if this condition is encountered as it can only happen if // there was a provided fingerprint which is not in the agent. // if (null == keyblob) { throw new OSSException("SSH Key " + sshKeyFingerprint + " was not found by your SSH agent."); } // // Retrieve OSS RSA key // RSAPublicKey pubkey = getOSSRSA(ossURL); // // Build the initialization token // // <TS> <SECRET> <SSH Signing Key Blob> <SSH Signature Blob> // ByteArrayOutputStream token = new ByteArrayOutputStream(); byte[] tsdata = nowBytes(); token.write(CryptoHelper.encodeNetworkString(tsdata)); token.write(CryptoHelper.encodeNetworkString(secret)); token.write(CryptoHelper.encodeNetworkString(keyblob)); byte[] sigblob = agent.sign(keyblob, token.toByteArray()); token.write(CryptoHelper.encodeNetworkString(sigblob)); // // Encrypt the token with a random AES256 key // byte[] aeskey = new byte[32]; CryptoHelper.getSecureRandom().nextBytes(aeskey); byte[] wrappedtoken = CryptoHelper.wrapAES(aeskey, token.toByteArray()); // // Encrypt the random key with OSS' RSA key // byte[] sealedaeskey = CryptoHelper.encryptRSA(pubkey, aeskey); // // Create the token // token.reset(); token.write(CryptoHelper.encodeNetworkString(wrappedtoken)); token.write(CryptoHelper.encodeNetworkString(sealedaeskey)); // // Base64 encode the encryptedtoken // String b64token = new String(Base64.encode(token.toByteArray()), "UTF-8"); // // Send request to OSS // URIBuilder builder = new URIBuilder(ossURL + GuiceServletModule.SERVLET_PATH_INIT); builder.addParameter("token", b64token); URI uri = builder.build(); String qs = uri.getRawQuery(); HttpPost post = new HttpPost( uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + uri.getPath()); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(new StringEntity(qs)); httpclient = newHttpClient(); HttpResponse response = httpclient.execute(post); HttpEntity resEntity = response.getEntity(); String content = EntityUtils.toString(resEntity, "UTF-8"); post.reset(); if (HttpServletResponse.SC_ACCEPTED == response.getStatusLine().getStatusCode()) { return false; } else if (HttpServletResponse.SC_OK != response.getStatusLine().getStatusCode()) { // Only throw an exception if this is the last SSH key we could try if (idx == fingerprints.size()) { throw new OSSException("None of the provided keys (" + idx + ") could be used to initialize this Open Secret Server. Latest error message was: " + response.getStatusLine().getReasonPhrase()); } else { continue; } } return true; } } catch (OSSException osse) { throw osse; } catch (Exception e) { throw new OSSException(e); } finally { if (null != httpclient) { httpclient.getConnectionManager().shutdown(); } if (null != agent) { agent.close(); } } return false; }
From source file:org.dasein.cloud.azure.AzureMethod.java
public String post(@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 va 2s.c om*/ if (wire.isDebugEnabled()) { wire.debug("POST --------------------------------------------------------> " + endpoint + account + resource); wire.debug(""); } String requestId = null; try { HttpClient client = getClient(); String url = endpoint + account + resource; HttpPost post = new HttpPost(url); post.addHeader("x-ms-version", "2012-03-01"); //If it is networking configuration services if (url.endsWith("/services/networking/media")) { post.addHeader("Content-Type", "text/plain;charset=UTF-8"); } else { post.addHeader("Content-Type", "application/xml;charset=UTF-8"); } if (wire.isDebugEnabled()) { wire.debug(post.getRequestLine().toString()); for (Header header : post.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (body != null) { wire.debug(body); wire.debug(""); } } if (body != null) { try { if (url.endsWith("/services/networking/media")) { post.setEntity(new StringEntity(body, "text/plain", "utf-8")); } else { post.setEntity(new StringEntity(body, "application/xml", "utf-8")); } } catch (UnsupportedEncodingException e) { throw new InternalException(e); } } HttpResponse response; StatusLine status; try { response = client.execute(post); 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()); if (h.getName().equalsIgnoreCase("x-ms-request-id")) { requestId = 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); } } return requestId; }
From source file:org.alfresco.rest.api.tests.TestDownloads.java
public void cancel(String downloadId) throws Exception { cancel(HttpServletResponse.SC_ACCEPTED, downloadId); }