List of usage examples for java.net HttpURLConnection HTTP_BAD_REQUEST
int HTTP_BAD_REQUEST
To view the source code for java.net HttpURLConnection HTTP_BAD_REQUEST.
Click Source Link
From source file:org.eclipse.orion.server.tests.servlets.git.GitBlameTest.java
@Test public void testBlameNoCommits() throws IOException, SAXException, JSONException, CoreException { URI workspaceLocation = createWorkspace(getMethodName()); IPath[] clonePaths = createTestProjects(workspaceLocation); for (IPath clonePath : clonePaths) { //clone a repo JSONObject clone = clone(clonePath); String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION); //get project/folder metadata WebRequest request = getGetRequest(cloneContentLocation); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject folder = new JSONObject(response.getText()); // get blameUri JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT); String gitBlameUri = gitSection.getString(GitConstants.KEY_BLAME); // blame request request = getGetGitBlameRequest(gitBlameUri); response = webConversation.getResource(request); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode()); // test//ww w . ja v a2 s . co m JSONObject blameObject = new JSONObject(response.getText()); assertEquals(blameObject.length(), 4); assertEquals(blameObject.get("Severity"), "Error"); assertEquals(blameObject.get("HttpCode"), 400); assertEquals(blameObject.get("Code"), 0); } }
From source file:co.cask.cdap.client.rest.RestStreamClientTest.java
@Test public void testBadRequestGetTTL() throws IOException { try {/*w w w . ja v a2s . c om*/ streamClient.getTTL(TestUtils.BAD_REQUEST_STREAM_NAME); Assert.fail("Expected HttpFailureException"); } catch (HttpFailureException e) { Assert.assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, e.getStatusCode()); } }
From source file:org.wso2.carbon.registry.app.ResourceServlet.java
/** * Logic that will be executed for a get request. * * @param request the HTTP Servlet request. * @param response the HTTP Servlet response. * * @throws IOException if an error occurred. *//*from ww w . j a v a2 s .co m*/ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { try { String uri = request.getRequestURI(); int idx = uri.indexOf("resource"); String path = uri.substring(idx + 8); if (path == null) { String msg = "Could not get the resource content. Path is not specified."; log.error(msg); response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST); return; } Resource resource; try { UserRegistry registry = Utils.getRegistry(request); try { path = new URI(path).normalize().toString(); } catch (URISyntaxException e) { log.error("Unable to normalize requested resource path: " + path, e); } String decodedPath = URLDecoder.decode(path, RegistryConstants.DEFAULT_CHARSET_ENCODING); CurrentSession.setUserRealm(registry.getUserRealm()); CurrentSession.setUser(registry.getUserName()); try { if (!AuthorizationUtils.authorize( RegistryUtils.getAbsolutePath(registry.getRegistryContext(), decodedPath), ActionConstants.GET)) { response.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\""); return; } resource = registry.get(decodedPath); } finally { CurrentSession.removeUserRealm(); CurrentSession.removeUser(); } } catch (AuthorizationFailedException e) { log.error(e.getMessage()); response.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\""); return; } catch (RegistryException e) { String msg = "Error retrieving the resource " + path + ". " + e.getMessage(); log.error(msg, e); throw e; } if (resource instanceof Collection) { String msg = "Could not get the resource content. Path " + path + " refers to a collection."; log.error(msg); response.setStatus(HttpURLConnection.HTTP_NOT_IMPLEMENTED); return; } // date based conditional get long ifModifiedSinceValue = request.getDateHeader("If-Modified-Since"); long lastModifiedValue = resource.getLastModified().getTime(); if (ifModifiedSinceValue > 0) { // convert the time values from milliseconds to seconds ifModifiedSinceValue /= 1000; lastModifiedValue /= 1000; /* condition to check we have latest updates in terms of dates */ if (ifModifiedSinceValue >= lastModifiedValue) { /* no need to response with data */ response.setStatus(HttpURLConnection.HTTP_NOT_MODIFIED); return; } } response.setDateHeader("Last-Modified", lastModifiedValue); // eTag based conditional get String ifNonMatchValue = request.getHeader("if-none-match"); String currentETag = Utils.calculateEntityTag(resource); if (ifNonMatchValue != null) { if (ifNonMatchValue.equals(currentETag)) { /* the version is not modified */ response.setStatus(HttpURLConnection.HTTP_NOT_MODIFIED); return; } } response.setHeader("ETag", currentETag); if (resource.getMediaType() != null && resource.getMediaType().length() > 0) { response.setContentType(resource.getMediaType()); } else { response.setHeader("Content-Disposition", "attachment; filename=" + RegistryUtils.getResourceName(path)); response.setContentType("application/download"); } InputStream contentStream = null; if (resource.getContent() != null) { contentStream = resource.getContentStream(); } if (contentStream != null) { try { ServletOutputStream servletOutputStream = response.getOutputStream(); byte[] contentChunk = new byte[RegistryConstants.DEFAULT_BUFFER_SIZE]; int byteCount; while ((byteCount = contentStream.read(contentChunk)) != -1) { servletOutputStream.write(contentChunk, 0, byteCount); } response.flushBuffer(); servletOutputStream.flush(); } finally { contentStream.close(); } } else { Object content = resource.getContent(); if (content != null) { if (content instanceof byte[]) { ServletOutputStream servletOutputStream = response.getOutputStream(); servletOutputStream.write((byte[]) content); response.flushBuffer(); servletOutputStream.flush(); } else { PrintWriter writer = response.getWriter(); writer.write(content.toString()); writer.flush(); } } } resource.discard(); } catch (RegistryException e) { String msg = "Failed to get resource content. " + e.getMessage(); log.error(msg, e); response.setStatus(HttpURLConnection.HTTP_INTERNAL_ERROR); } }
From source file:rapture.kernel.UserApiImpl.java
@Override public RaptureUser changeMyPassword(CallingContext context, String oldHashPassword, String newHashPassword) { RaptureUser usr = Kernel.getAdmin().getTrusted().getUser(context, context.getUser()); if (usr != null) { if (usr.getHashPassword().equals(oldHashPassword)) { usr.setHashPassword(newHashPassword); RaptureUserStorage.add(usr, context.getUser(), "Updated my password"); return usr; } else {//w w w .ja v a2s . co m throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_UNAUTHORIZED, "Bad Password"); } } else { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, "Could not find user record"); } }
From source file:i5.las2peer.services.userManagement.UserManagement.java
/** * // w w w. jav a 2s .c o m * createUser * * * @return HttpResponse * */ @POST @Path("/create") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.TEXT_PLAIN) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_CONFLICT, message = "userExists"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "authorizationNeeded"), @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "userCreated"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "internal"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "malformedRequest") }) @ApiOperation(value = "createUser", notes = "") public HttpResponse createUser() { // userExists boolean userExists_condition = true; if (userExists_condition) { String error = "Some String"; HttpResponse userExists = new HttpResponse(error, HttpURLConnection.HTTP_CONFLICT); return userExists; } // authorizationNeeded boolean authorizationNeeded_condition = true; if (authorizationNeeded_condition) { String error = "Some String"; HttpResponse authorizationNeeded = new HttpResponse(error, HttpURLConnection.HTTP_UNAUTHORIZED); return authorizationNeeded; } // userCreated boolean userCreated_condition = true; if (userCreated_condition) { JSONObject User = new JSONObject(); HttpResponse userCreated = new HttpResponse(User.toJSONString(), HttpURLConnection.HTTP_CREATED); return userCreated; } // internal boolean internal_condition = true; if (internal_condition) { String error = "Some String"; HttpResponse internal = new HttpResponse(error, HttpURLConnection.HTTP_INTERNAL_ERROR); return internal; } // malformedRequest boolean malformedRequest_condition = true; if (malformedRequest_condition) { String malformation = "Some String"; HttpResponse malformedRequest = new HttpResponse(malformation, HttpURLConnection.HTTP_BAD_REQUEST); return malformedRequest; } return null; }
From source file:com.cognifide.aet.rest.XUnitServlet.java
@Override protected void process(DBKey dbKey, HttpServletRequest request, HttpServletResponse response) throws IOException { final String correlationId = request.getParameter(Helper.CORRELATION_ID_PARAM); final String suiteName = request.getParameter(Helper.SUITE_PARAM); response.setCharacterEncoding(Charsets.UTF_8.toString()); try {/* w ww .ja v a 2s .c om*/ final Suite suite = getSuite(dbKey, correlationId, suiteName); generateXUnitAndRespondWithIt(dbKey, response, suite); } catch (RestServiceException e) { LOGGER.error("Failed to process request!", e); response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST); response.getWriter().write(responseAsJson(e.getMessage())); } }
From source file:com.vmware.photon.controller.api.frontend.backends.EntityLockXenonBackend.java
@Override public void setTaskLock(BaseEntity entity, TaskEntity task) throws ConcurrentTaskException { checkNotNull(entity, "Entity cannot be null."); checkNotNull(task, "TaskEntity cannot be null."); EntityLockService.State state = new EntityLockService.State(); state.ownerTaskId = task.getId();//ww w. j a v a2 s. c o m state.entityId = entity.getId(); state.entityKind = entity.getKind(); state.documentSelfLink = entity.getId(); state.lockOperation = EntityLockService.State.LockOperation.ACQUIRE; try { task.getLockedEntityIds().add(entity); // POST to the entity lock service will be converted to a PUT if the lock already exists xenonClient.post(EntityLockServiceFactory.SELF_LINK, state); logger.info("Entity Lock with entityId : {} and taskId: {} has been set", state.entityId, state.ownerTaskId); } catch (XenonRuntimeException e) { if (e.getCompletedOperation().getStatusCode() == HttpURLConnection.HTTP_BAD_REQUEST) { String errorMessage = e.getCompletedOperation().getBody(ServiceErrorResponse.class).message; if (StringUtils.isNotBlank(errorMessage) && errorMessage.contains(EntityLockService.LOCK_TAKEN_MESSAGE)) { task.getLockedEntityIds().remove(entity); throw new ConcurrentTaskException(); } } throw e; } }
From source file:rapture.blob.mongodb.MongoDBBlobStore.java
@Override public InputStream getBlob(CallingContext context, RaptureURI blobUri) { try {/*www .jav a2 s. com*/ return blobHandler.getBlob(context, blobUri.getDocPath()); } catch (MongoException e) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, mongoMsgCatalog.getMessage("ReadError", new String[] { blobUri.getDocPath(), e.getMessage() })); } }
From source file:org.cm.podd.report.util.RequestDataUtil.java
public static ResponseObject post(String path, String query, String json, String token) { JSONObject jsonObj = null;/*ww w . j av a 2s. co m*/ int statusCode = 0; //SharedPreferences settings = PoddApplication.getAppContext().getSharedPreferences("PoddPrefsFile", 0); String serverUrl = settings.getString("serverUrl", BuildConfig.SERVER_URL); String reqUrl = ""; if (path.contains("http://") || path.contains("https://")) { reqUrl = String.format("%s%s", path, query == null ? "" : "?" + query); } else { reqUrl = String.format("%s%s%s", serverUrl, path, query == null ? "" : "?" + query); } Log.i(TAG, "submit url=" + reqUrl); Log.i(TAG, "post data=" + json); HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpClient client = new DefaultHttpClient(params); try { HttpPost post = new HttpPost(reqUrl); post.setHeader("Content-Type", "application/json"); if (token != null) { post.setHeader("Authorization", "Token " + token); } post.setEntity(new StringEntity(json, HTTP.UTF_8)); HttpResponse response; response = client.execute(post); HttpEntity entity = response.getEntity(); // Detect server complaints statusCode = response.getStatusLine().getStatusCode(); Log.v(TAG, "status code=" + statusCode); if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_CREATED || statusCode == HttpURLConnection.HTTP_BAD_REQUEST) { InputStream in = entity.getContent(); String resp = FileUtil.convertInputStreamToString(in); jsonObj = new JSONObject(resp); entity.consumeContent(); } } catch (ClientProtocolException e) { Log.e(TAG, "error post data", e); } catch (IOException e) { Log.e(TAG, "Can't connect server", e); } catch (JSONException e) { Log.e(TAG, "error convert json", e); } finally { client.getConnectionManager().shutdown(); } return new ResponseObject(statusCode, jsonObj); }
From source file:rapture.kernel.StructuredApiImpl.java
@Override public void createStructuredRepo(CallingContext context, String repoURI, String config) { checkParameter("URI", repoURI); checkParameter("Config", config); RaptureURI internalURI = new RaptureURI(repoURI, Scheme.STRUCTURED); String authority = internalURI.getAuthority(); if ((authority == null) || authority.isEmpty()) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, apiMessageCatalog.getMessage("NoAuthority")); //$NON-NLS-1$ }// w ww .j a v a2 s.c o m if (internalURI.hasDocPath()) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, apiMessageCatalog.getMessage("NoDocPath", repoURI)); //$NON-NLS-1$ } // TODO write a config validator if (structuredRepoExists(context, repoURI)) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, apiMessageCatalog.getMessage("Exists", internalURI.toShortString())); //$NON-NLS-1$ } StructuredRepoConfig structured = new StructuredRepoConfig(); structured.setAuthority(authority); structured.setConfig(config); StructuredRepoConfigStorage.add(structured, context.getUser(), "Create Structured repository"); }