List of usage examples for org.apache.commons.httpclient HttpStatus SC_INTERNAL_SERVER_ERROR
int SC_INTERNAL_SERVER_ERROR
To view the source code for org.apache.commons.httpclient HttpStatus SC_INTERNAL_SERVER_ERROR.
Click Source Link
From source file:org.fusesource.restygwt.server.FlakyConnectionServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { log.fine("GET: flakyMODE"); if (currentNumberOfServerFailures < NUMBER_OF_SERVER_FAILURES_TO_SIMULATE) { log.fine("respond code: " + HttpStatus.SC_INTERNAL_SERVER_ERROR + " with purpose"); ++currentNumberOfServerFailures; response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } else {/*from w ww . j ava 2s . c o m*/ log.fine("response: " + DUMMY_RESPONSE); response.getWriter().print(DUMMY_RESPONSE); } }
From source file:org.gss_project.gss.server.rest.Webdav.java
@Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.addHeader("DAV", "1,2"); StringBuffer methodsAllowed = new StringBuffer(); try {/* www . j a v a 2s. c om*/ methodsAllowed = determineMethodsAllowed(req); } catch (RpcException e) { resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR); return; } resp.addHeader("Allow", methodsAllowed.toString()); resp.addHeader("MS-Author-Via", "DAV"); }
From source file:org.gss_project.gss.server.rest.Webdav.java
/** * Copy a resource.//from ww w . j av a2s. c o m * * @param req Servlet request * @param resp Servlet response * @return boolean true if the copy is successful * @throws IOException */ private boolean copyResource(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Parsing destination header String destinationPath = req.getHeader("Destination"); if (destinationPath == null) { resp.sendError(WebdavStatus.SC_BAD_REQUEST); return false; } // Remove url encoding from destination destinationPath = RequestUtil.URLDecode(destinationPath, "UTF8"); int protocolIndex = destinationPath.indexOf("://"); if (protocolIndex >= 0) { // if the Destination URL contains the protocol, we can safely // trim everything upto the first "/" character after "://" int firstSeparator = destinationPath.indexOf("/", protocolIndex + 4); if (firstSeparator < 0) destinationPath = "/"; else destinationPath = destinationPath.substring(firstSeparator); } else { String hostName = req.getServerName(); if (hostName != null && destinationPath.startsWith(hostName)) destinationPath = destinationPath.substring(hostName.length()); int portIndex = destinationPath.indexOf(":"); if (portIndex >= 0) destinationPath = destinationPath.substring(portIndex); if (destinationPath.startsWith(":")) { int firstSeparator = destinationPath.indexOf("/"); if (firstSeparator < 0) destinationPath = "/"; else destinationPath = destinationPath.substring(firstSeparator); } } // Normalize destination path (remove '.' and '..') destinationPath = RequestUtil.normalize(destinationPath); String contextPath = req.getContextPath(); if (contextPath != null && destinationPath.startsWith(contextPath)) destinationPath = destinationPath.substring(contextPath.length()); String pathInfo = req.getPathInfo(); if (pathInfo != null) { String servletPath = req.getServletPath(); if (servletPath != null && destinationPath.startsWith(servletPath)) destinationPath = destinationPath.substring(servletPath.length()); } if (logger.isDebugEnabled()) logger.debug("Dest path :" + destinationPath); if (destinationPath.toUpperCase().startsWith("/WEB-INF") || destinationPath.toUpperCase().startsWith("/META-INF")) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return false; } String path = getRelativePath(req); if (path.toUpperCase().startsWith("/WEB-INF") || path.toUpperCase().startsWith("/META-INF")) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return false; } if (destinationPath.equals(path)) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return false; } // Parsing overwrite header boolean overwrite = true; String overwriteHeader = req.getHeader("Overwrite"); if (overwriteHeader != null) if (overwriteHeader.equalsIgnoreCase("T")) overwrite = true; else overwrite = false; User user = getUser(req); // Overwriting the destination boolean exists = true; try { getService().getResourceAtPath(user.getId(), destinationPath, true); } catch (ObjectNotFoundException e) { exists = false; } catch (RpcException e) { resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR); return false; } if (overwrite) { // Delete destination resource, if it exists if (exists) { if (!deleteResource(destinationPath, req, resp, true)) return false; } else resp.setStatus(WebdavStatus.SC_CREATED); } else // If the destination exists, then it's a conflict if (exists) { resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED); return false; } else resp.setStatus(WebdavStatus.SC_CREATED); // Copying source to destination. Hashtable<String, Integer> errorList = new Hashtable<String, Integer>(); boolean result; try { result = copyResource(errorList, path, destinationPath, req); } catch (RpcException e) { resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR); return false; } if (!result || !errorList.isEmpty()) { sendReport(req, resp, errorList); return false; } return true; }
From source file:org.homeautomation.doormanager.manager.api.DoorManagerManagerService.java
/** * This will give link to generated agent * * @param deviceName name of the device which is to be created * @param sketchType name of sketch type * @return link to generated agent// w w w. j ava 2 s . co m */ @Path("manager/device/{sketch_type}/generate_link") @GET public Response generateSketchLink(@QueryParam("deviceName") String deviceName, @PathParam("sketch_type") String sketchType) { try { ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType); ResponsePayload responsePayload = new ResponsePayload(); responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer( "Sending Requested sketch by type: " + sketchType + " and id: " + zipFile.getDeviceId() + "."); responsePayload.setResponseContent(zipFile.getDeviceId()); return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); } catch (IllegalArgumentException ex) { return Response.status(HttpStatus.SC_BAD_REQUEST).entity(ex.getMessage()).build(); } catch (DeviceManagementException ex) { log.error("Error occurred while creating device with name " + deviceName + "\n", ex); return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build(); } catch (AccessTokenException ex) { log.error(ex.getMessage(), ex); return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build(); } catch (DeviceControllerException ex) { log.error(ex.getMessage(), ex); return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build(); } }
From source file:org.homeautomation.firealarm.manager.api.ManagerService.java
/** * This will give link to generated agent * * @param deviceName name of the device which is to be created * @param sketchType name of sketch type * @return link to generated agent//from w ww . j a va 2 s. c o m */ @Path("manager/device/{sketch_type}/generate_link") @GET public Response generateSketchLink(@QueryParam("deviceName") String deviceName, @PathParam("sketch_type") String sketchType) { try { ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType); ResponsePayload responsePayload = new ResponsePayload(); responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer( "Sending Requested sketch by type: " + sketchType + " and id: " + zipFile.getDeviceId() + "."); responsePayload.setResponseContent(zipFile.getDeviceId()); return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); } catch (IllegalArgumentException ex) { return Response.status(HttpStatus.SC_BAD_REQUEST).entity(ex.getMessage()).build(); } catch (DeviceManagementException ex) { log.error("Error occurred while creating device with name " + deviceName + "\n", ex); return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build(); } catch (AccessTokenException ex) { log.error(ex.getMessage(), ex); return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build(); } catch (DeviceControllerException ex) { log.error(ex.getMessage(), ex); return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build(); } }
From source file:org.hydracache.client.transport.HttpTransportTest.java
@Test(expected = InternalHydraException.class) public void ensureInternalErrorThrowsException() throws Exception { HttpTransport transport = new HttpTransport(); transport.establishConnection("localhost", 90); HttpClient mockHttpClient = mock(HttpClient.class); when(mockHttpClient.executeMethod(any(HttpMethod.class))).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); transport.httpClient = mockHttpClient; RequestMessage requestMessage = new RequestMessage(); requestMessage.setMethod("delete"); requestMessage.setPath("testPath"); transport.sendRequest(requestMessage); }
From source file:org.infoscoop.gadgets.servlet.HttpRequestHandler.java
/** * Dispatch the request//from w w w.j av a2 s .c o m * * @param method HTTP method to execute * @param requestItem TODO */ private HttpApiResponse execute(String method, HttpApiRequest httpApiRequest, BaseRequestItem requestItem) { if (httpApiRequest.href == null) { throw new ProtocolException(HttpServletResponse.SC_BAD_REQUEST, "href parameter is missing"); } // Canonicalize the path Uri href = normalizeUrl(httpApiRequest.href); try { HttpRequest req = new HttpRequest(href); req.setMethod(method); // Copy over allowed headers for (Map.Entry<String, List<String>> header : httpApiRequest.headers.entrySet()) { if (!BAD_HEADERS.contains(header.getKey().trim().toUpperCase())) { for (String value : header.getValue()) { req.addHeader(header.getKey(), value); } } } // Extract the gadget URI from the request or the security token Uri gadgetUri = getGadgetUri(requestItem.getToken(), httpApiRequest); if (gadgetUri == null) { throw new ProtocolException(HttpServletResponse.SC_BAD_REQUEST, "Gadget URI not specified in request"); } req.setGadget(gadgetUri); // Detect the authz parsing if (httpApiRequest.authz != null) { req.setAuthType(AuthType.parse(httpApiRequest.authz)); } HttpResponse results = null; String oauthApprovalUrl = null; try { if (httpApiRequest.body != null) { req.setPostBody(httpApiRequest.body.getBytes("UTF-8")); } Map<String, String> proxyParams = new HashMap<String, String>(); final AuthType authz = req.getAuthType(); req.setSecurityToken(requestItem.getToken()); if (authz == AuthType.OAUTH2) { Map<String, String> authSettings = getAuthSettings(requestItem); OAuth2Arguments oauth2Args = new OAuth2Arguments(authz, authSettings); req.setOAuth2Arguments(oauth2Args); proxyParams.put("OAUTH_SERVICE_NAME", (String) authSettings.get("OAUTH_SERVICE_NAME")); proxyParams.put("hostPrefix", req.getSecurityToken().getContainer()); proxyParams.put("userAuthorizationURL", requestItem.getParameter("userAuthorizationURL")); proxyParams.put("accessTokenURL", requestItem.getParameter("accessTokenURL")); proxyParams.put("OAUTH2_SCOPE", requestItem.getParameter("OAUTH2_SCOPE")); } else if (authz == AuthType.OAUTH) { Map<String, String> authSettings = getAuthSettings(requestItem); OAuthArguments oauthArgs = new OAuthArguments(authz, authSettings); oauthArgs.setSignOwner(httpApiRequest.signOwner); oauthArgs.setSignViewer(httpApiRequest.signViewer); req.setOAuthArguments(oauthArgs); proxyParams.put("OAUTH_SERVICE_NAME", oauthArgs.getServiceName()); proxyParams.put("hostPrefix", req.getSecurityToken().getContainer()); proxyParams.put("requestTokenURL", requestItem.getParameter("requestTokenURL")); proxyParams.put("requestTokenMethod", requestItem.getParameter("requestTokenMethod")); proxyParams.put("userAuthorizationURL", requestItem.getParameter("userAuthorizationURL")); proxyParams.put("accessTokenURL", requestItem.getParameter("accessTokenURL")); proxyParams.put("accessTokenMethod", requestItem.getParameter("accessTokenMethod")); } String contentType = req.getContentType(); String uri = req.getUri().toString(); proxyParams.put("moduleId", req.getSecurityToken().getAppId()); proxyParams.put("gadgetUrl", req.getGadget().toString()); proxyParams.put("authz", authz.name()); proxyParams.put("url", uri); proxyParams.put("contentType", contentType); proxyParams.put("httpMethod", req.getMethod()); proxyParams.put("postData", req.getPostBodyAsString()); String uid = SecurityController.getPrincipalByType("UIDPrincipal").getName(); // execute request JSONObject resJson = JsonProxyServlet.invokeJSONProxyRequest(uid, proxyParams, req.getHeaders()); resJson = resJson.getJSONObject(uri); JSONObject headersJson = new JSONObject(); if (resJson.has("headers")) headersJson = resJson.getJSONObject("headers"); if (resJson.has("oauthApprovalUrl")) oauthApprovalUrl = resJson.getString("oauthApprovalUrl"); int rc = resJson.getInt("rc"); results = makeResponse(rc, headersJson, resJson.getString("body")); } catch (Exception e) { log.error(e.getMessage(), e); throw new ProtocolException(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage(), e); } HttpApiResponse httpApiResponse = new HttpApiResponse(results, transformBody(httpApiRequest, results), httpApiRequest); Map<String, String> meta = new HashMap<String, String>(); if (oauthApprovalUrl != null) meta.put("oauthApprovalUrl", oauthApprovalUrl); httpApiResponse.setMetadata(meta); // Renew the security token if we can if (requestItem.getToken() != null) { String updatedAuthToken = requestItem.getToken().getUpdatedToken(); if (updatedAuthToken != null) { httpApiResponse.token = updatedAuthToken; } } return httpApiResponse; } catch (GadgetException ge) { log.error(ge.getMessage(), ge); throw new ProtocolException(ge.getHttpStatusCode(), ge.getMessage(), ge); } }
From source file:org.jetbrains.tfsIntegration.webservice.WebServiceHelper.java
public static void httpGet(final URI serverUri, final String downloadUrl, final OutputStream outputStream, Credentials credentials, final HttpClient httpClient) throws TfsException, IOException { TFSVcs.assertTrue(downloadUrl != null); setupHttpClient(credentials, serverUri, httpClient); HttpMethod method = new GetMethod(downloadUrl); try {// www . j a v a 2s. co m int statusCode = httpClient.executeMethod(method); if (statusCode == HttpStatus.SC_OK) { StreamUtil.copyStreamContent(getInputStream(method), outputStream); } else if (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) { throw new OperationFailedException(method.getResponseBodyAsString()); } else { throw TfsExceptionManager.createHttpTransportErrorException(statusCode, null); } } finally { // enforce connection release since GZipInputStream may not trigger underlying AutoCloseInputStream.close() method.releaseConnection(); } }
From source file:org.jetbrains.tfsIntegration.webservice.WebServiceHelper.java
public static void httpPost(final @NotNull String uploadUrl, final @NotNull Part[] parts, final @Nullable OutputStream outputStream, Credentials credentials, URI serverUri, final HttpClient httpClient) throws IOException, TfsException { setupHttpClient(credentials, serverUri, httpClient); PostMethod method = new PostMethod(uploadUrl); try {// www . j a va 2 s . c o m method.setRequestHeader("X-TFS-Version", "1.0.0.0"); method.setRequestHeader("accept-language", "en-US"); method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); int statusCode = httpClient.executeMethod(method); if (statusCode == HttpStatus.SC_OK) { if (outputStream != null) { StreamUtil.copyStreamContent(getInputStream(method), outputStream); } } else if (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) { throw new OperationFailedException(method.getResponseBodyAsString()); } else { throw TfsExceptionManager.createHttpTransportErrorException(statusCode, null); } } finally { method.releaseConnection(); } }
From source file:org.kei.android.phone.cellhistory.towers.request.OpenCellIdRequestEntity.java
@Override public int decode(final String url, final HttpConnection connection, final int timeout) throws Exception { int ret = OK; final GetMethod getMethod = new GetMethod(url); getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false)); // socket timeout (connection timeout already set in HttpClient) getMethod.getParams().setSoTimeout(timeout); final int resCode = getMethod.execute(new HttpState(), connection); final InputStream response = getMethod.getResponseBodyAsStream(); final DataInputStream dis = new DataInputStream(response); if (resCode == HttpStatus.SC_OK) { final int av = dis.available(); final byte[] json = new byte[av]; dis.readFully(json);//from w w w . j a v a 2 s. c o m final String sjson = new String(json); final String ljson = sjson.toLowerCase(Locale.US); if (ljson.indexOf("err") == -1) { final JSONObject object = new JSONObject(sjson); String lat, lng; lat = object.getString("lat"); lng = object.getString("lon"); ti.setCellLatitude(Double.parseDouble(lat)); ti.setCellLongitude(Double.parseDouble(lng)); } else if (ljson.indexOf("not found") != -1) ret = NOT_FOUND; else ret = EXCEPTION; } else if (resCode == HttpStatus.SC_NOT_FOUND) ret = NOT_FOUND; else if (resCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) ret = BAD_REQUEST; else ret = EXCEPTION; getMethod.releaseConnection(); return ret; }