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:i5.las2peer.services.gamificationQuestService.GamificationQuestService.java
/** * Update a quest/*from w w w .j av a2 s .c o m*/ * @param appId applicationId * @param questId questId * @param contentB data * @return HttpResponse with the returnString */ @PUT @Path("/{appId}/{questId}") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_JSON) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Quest Updated"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Error occured"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Bad request"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") }) @ApiOperation(value = "updateQuest", notes = "A method to update a quest with details") public HttpResponse updateQuest( @ApiParam(value = "Application ID to store a new quest", required = true) @PathParam("appId") String appId, @ApiParam(value = "Quest ID") @PathParam("questId") String questId, @ApiParam(value = "Quest detail in JSON", required = true) @ContentParam byte[] contentB) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "PUT " + "gamification/quests/" + appId + "/" + questId); long randomLong = new Random().nextLong(); //To be able to match // parse given multipart form data JSONObject objResponse = new JSONObject(); Connection conn = null; String content = new String(contentB); if (content.equals(null)) { objResponse.put("message", "Cannot update quest. Cannot parse json data into string"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } String questname; String questdescription; String queststatus; String questachievementid; boolean questquestflag = false; String questquestidcompleted = null; boolean questpointflag = false; int questpointvalue = 0; List<Pair<String, Integer>> questactionids = new ArrayList<Pair<String, Integer>>(); UserAgent userAgent = (UserAgent) getContext().getMainAgent(); String name = userAgent.getLoginName(); if (name.equals("anonymous")) { return unauthorizedMessage(); } try { conn = dbm.getConnection(); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_18, "" + randomLong); try { if (!questAccess.isAppIdExist(conn, appId)) { logger.info("App not found >> "); objResponse.put("message", "Cannot update quest. App not found"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } } catch (SQLException e1) { e1.printStackTrace(); logger.info( "Cannot check whether application ID exist or not. Database error. >> " + e1.getMessage()); objResponse.put("message", "Cannot check whether application ID exist or not. Database error. " + e1.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } if (questId == null) { logger.info("quest ID cannot be null >> "); objResponse.put("message", "Cannot update quest. quest ID cannot be null"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } QuestModel quest = questAccess.getQuestWithId(conn, appId, questId); if (!questAccess.isQuestIdExist(conn, appId, questId)) { objResponse.put("message", "Cannot update quest. Failed to update the quest. Quest ID is not exist!"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } JSONObject obj = (JSONObject) JSONValue.parseWithException(content); try { questname = stringfromJSON(obj, "questname"); quest.setName(questname); } catch (IOException e) { e.printStackTrace(); logger.info("Cannot parse questname"); } try { queststatus = stringfromJSON(obj, "queststatus"); quest.setStatus(QuestStatus.valueOf(queststatus)); } catch (IOException e) { e.printStackTrace(); } try { questachievementid = stringfromJSON(obj, "questachievementid"); quest.setAchievementId(questachievementid); } catch (IOException e) { e.printStackTrace(); } questdescription = (String) obj.get("questdescription"); if (!questdescription.equals(null)) { quest.setDescription(questdescription); } questquestidcompleted = (String) obj.get("questidcompleted"); if (questquestflag) { if (questquestidcompleted.equals(null) || questquestidcompleted.equals("")) { objResponse.put("message", "Cannot update quest. Completed quest ID cannot be null if it is selected"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } questquestflag = boolfromJSON(obj, "questquestflag"); questpointflag = boolfromJSON(obj, "questpointflag"); questpointvalue = intfromJSON(obj, "questpointvalue"); quest.setQuestFlag(questquestflag); quest.setPointFlag(questpointflag); quest.setQuestIdCompleted(questquestidcompleted); quest.setPointValue(questpointvalue); try { questactionids = listPairfromJSON(obj, "questactionids", "action", "times"); quest.setActionIds(questactionids); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } questAccess.updateQuest(conn, appId, quest); logger.info("Quest Updated "); objResponse.put("message", "Quest updated " + questId); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_19, "" + randomLong); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_28, "" + name); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_29, "" + appId); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK); } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot update quest. DB Error. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (ParseException e) { e.printStackTrace(); objResponse.put("message", "Cannot update quest. ParseExceptionr. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (IOException e) { e.printStackTrace(); objResponse.put("message", "Cannot update quest. Problem with the model. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } // always close connections finally { try { conn.close(); } catch (SQLException e) { logger.printStackTrace(e); } } }
From source file:org.eclipse.orion.server.tests.servlets.workspace.WorkspaceServiceTest.java
@Test public void testCreateWorkspaceNullName() throws IOException, SAXException, JSONException { //request with null workspace name is not allowed WebRequest request = getCreateWorkspaceRequest(null); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode()); assertEquals("application/json", response.getContentType()); //expecting a status response JSONObject responseObject = new JSONObject(response.getText()); assertNotNull("No error response", responseObject); assertEquals("Error", responseObject.optString("Severity")); assertNotNull(responseObject.optString("message")); }
From source file:org.apache.hadoop.mapred.TestShuffleHandler.java
/** * simulate a reducer that sends an invalid shuffle-header - sometimes a wrong * header_name and sometimes a wrong version * //from w ww . j av a2 s. c o m * @throws Exception exception */ @Test(timeout = 10000) public void testIncompatibleShuffleVersion() throws Exception { final int failureNum = 3; Configuration conf = new Configuration(); conf.setInt(ShuffleHandler.SHUFFLE_PORT_CONFIG_KEY, 0); ShuffleHandler shuffleHandler = new ShuffleHandler(); shuffleHandler.init(conf); shuffleHandler.start(); // simulate a reducer that closes early by reading a single shuffle header // then closing the connection URL url = new URL( "http://127.0.0.1:" + shuffleHandler.getConfig().get(ShuffleHandler.SHUFFLE_PORT_CONFIG_KEY) + "/mapOutput?job=job_12345_1&reduce=1&map=attempt_12345_1_m_1_0"); for (int i = 0; i < failureNum; ++i) { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty(ShuffleHeader.HTTP_HEADER_NAME, i == 0 ? "mapreduce" : "other"); conn.setRequestProperty(ShuffleHeader.HTTP_HEADER_VERSION, i == 1 ? "1.0.0" : "1.0.1"); conn.connect(); Assert.assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, conn.getResponseCode()); } shuffleHandler.stop(); shuffleHandler.close(); }
From source file:rapture.kernel.DocApiImpl.java
@Override public DocumentWithMeta revertDoc(CallingContext context, String docUri) { RaptureURI internalUri = new RaptureURI(docUri, Scheme.DOCUMENT); Repository repository = getRepoFromCache(internalUri.getAuthority()); if (repository == null) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, apiMessageCatalog.getMessage("NoSuchRepo", internalUri.toAuthString())); //$NON-NLS-1$ }/* w w w . j ava 2s . co m*/ return repository.revertDoc(internalUri.getDocPath(), null); }
From source file:com.day.cq.wcm.foundation.impl.Rewriter.java
/** * Process a page./*from w w w. j a v a 2 s . c o m*/ */ public void rewrite(HttpServletRequest request, HttpServletResponse response) throws IOException { try { targetURL = new URI(target); } catch (URISyntaxException e) { IOException ioe = new IOException("Bad URI syntax: " + target); ioe.initCause(e); throw ioe; } setHostPrefix(targetURL); HttpClient httpClient = new HttpClient(); HttpState httpState = new HttpState(); HostConfiguration hostConfig = new HostConfiguration(); HttpMethodBase httpMethod; // define host hostConfig.setHost(targetURL.getHost(), targetURL.getPort()); // create http method String method = (String) request.getAttribute("cq.ext.app.method"); if (method == null) { method = request.getMethod(); } method = method.toUpperCase(); boolean isPost = "POST".equals(method); String urlString = targetURL.getPath(); StringBuffer query = new StringBuffer(); if (targetURL.getQuery() != null) { query.append("?"); query.append(targetURL.getQuery()); } //------------ GET --------------- if ("GET".equals(method)) { // add internal props Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); if (query.length() == 0) { query.append("?"); } else { query.append("&"); } query.append(Text.escape(name)); query.append("="); query.append(Text.escape(value)); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration<String> e = request.getParameterNames(); while (e.hasMoreElements()) { String name = e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { if (query.length() == 0) { query.append("?"); } else { query.append("&"); } query.append(Text.escape(name)); query.append("="); query.append(Text.escape(values[i])); } } } httpMethod = new GetMethod(urlString + query); //------------ POST --------------- } else if ("POST".equals(method)) { PostMethod m = new PostMethod(urlString + query); httpMethod = m; String contentType = request.getContentType(); boolean mp = contentType != null && contentType.toLowerCase().startsWith("multipart/"); if (mp) { //------------ MULTPART POST --------------- List<Part> parts = new LinkedList<Part>(); Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); parts.add(new StringPart(name, value)); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration<String> e = request.getParameterNames(); while (e.hasMoreElements()) { String name = e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { parts.add(new StringPart(name, values[i])); } } } m.setRequestEntity( new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), m.getParams())); } else { //------------ NORMAL POST --------------- // add internal props Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); m.addParameter(name, value); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration e = request.getParameterNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { m.addParameter(name, values[i]); } } } } } else { log.error("Unsupported method ''{0}''", method); throw new IOException("Unsupported http method " + method); } log.debug("created http connection for method {0} to {1}", method, urlString + query); // add some request headers httpMethod.addRequestHeader("User-Agent", request.getHeader("User-Agent")); httpMethod.setFollowRedirects(!isPost); httpMethod.getParams().setSoTimeout(soTimeout); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout); // send request httpClient.executeMethod(hostConfig, httpMethod, httpState); String contentType = httpMethod.getResponseHeader("Content-Type").getValue(); log.debug("External app responded: {0}", httpMethod.getStatusLine()); log.debug("External app contenttype: {0}", contentType); // check response code int statusCode = httpMethod.getStatusCode(); if (statusCode >= HttpURLConnection.HTTP_BAD_REQUEST) { PrintWriter writer = response.getWriter(); writer.println("External application returned status code: " + statusCode); return; } else if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM) { String location = httpMethod.getResponseHeader("Location").getValue(); if (location == null) { response.sendError(HttpURLConnection.HTTP_NOT_FOUND); return; } response.sendRedirect(rewriteURL(location, false)); return; } // open input stream InputStream in = httpMethod.getResponseBodyAsStream(); // check content type if (contentType != null && contentType.startsWith("text/html")) { rewriteHtml(in, contentType, response); } else { // binary mode if (contentType != null) { response.setContentType(contentType); } OutputStream outs = response.getOutputStream(); try { byte buf[] = new byte[8192]; int len; while ((len = in.read(buf)) != -1) { outs.write(buf, 0, len); } } finally { if (in != null) { in.close(); } } } }
From source file:rapture.kernel.DocApiImpl.java
@Override public Map<String, String> getDocRepoStatus(CallingContext context, String docRepoUri) { RaptureURI internalUri = new RaptureURI(docRepoUri, Scheme.DOCUMENT); Repository repository = getRepoFromCache(internalUri.getAuthority()); if (repository == null) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, apiMessageCatalog.getMessage("NoSuchRepo", internalUri.toAuthString())); //$NON-NLS-1$ }// ww w . j av a 2s .co m return repository.getStatus(); }
From source file:org.eclipse.orion.server.tests.servlets.git.GitConfigTest.java
@Test public void testRequestWithMissingArguments() throws Exception { URI workspaceLocation = createWorkspace(getMethodName()); IPath[] clonePaths = createTestProjects(workspaceLocation); for (IPath clonePath : clonePaths) { // clone a repo String contentLocation = clone(clonePath).getString(ProtocolConstants.KEY_CONTENT_LOCATION); // get project metadata WebRequest request = getGetRequest(contentLocation); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject project = new JSONObject(response.getText()); JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT); String gitConfigUri = gitSection.getString(GitConstants.KEY_CONFIG); final String ENTRY_KEY = "a.b.c"; final String ENTRY_VALUE = "v"; // missing key request = getPostGitConfigRequest(gitConfigUri, null, ENTRY_VALUE); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode()); // missing value request = getPostGitConfigRequest(gitConfigUri, ENTRY_KEY, null); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode()); // missing key and value request = getPostGitConfigRequest(gitConfigUri, null, null); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode()); // add some config request = getPostGitConfigRequest(gitConfigUri, ENTRY_KEY, ENTRY_VALUE); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); JSONObject configResponse = new JSONObject(response.getText()); String entryLocation = configResponse.getString(ProtocolConstants.KEY_LOCATION); // put without value request = getPutGitConfigRequest(entryLocation, null); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode()); }//from w ww .j a v a 2 s . co m }
From source file:org.eclipse.orion.server.docker.server.DockerServer.java
private DockerResponse.StatusCode getDockerResponse(DockerResponse dockerResponse, HttpURLConnection httpURLConnection) { try {// w ww .j av a2 s . c om int responseCode = httpURLConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { dockerResponse.setStatusCode(DockerResponse.StatusCode.OK); return DockerResponse.StatusCode.OK; } else if (responseCode == HttpURLConnection.HTTP_CREATED) { dockerResponse.setStatusCode(DockerResponse.StatusCode.CREATED); return DockerResponse.StatusCode.CREATED; } else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) { dockerResponse.setStatusCode(DockerResponse.StatusCode.STARTED); return DockerResponse.StatusCode.STARTED; } else if (responseCode == HttpURLConnection.HTTP_BAD_REQUEST) { dockerResponse.setStatusCode(DockerResponse.StatusCode.BAD_PARAMETER); dockerResponse.setStatusMessage(httpURLConnection.getResponseMessage()); return DockerResponse.StatusCode.BAD_PARAMETER; } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) { dockerResponse.setStatusCode(DockerResponse.StatusCode.NO_SUCH_CONTAINER); dockerResponse.setStatusMessage(httpURLConnection.getResponseMessage()); return DockerResponse.StatusCode.NO_SUCH_CONTAINER; } else if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) { dockerResponse.setStatusCode(DockerResponse.StatusCode.SERVER_ERROR); dockerResponse.setStatusMessage(httpURLConnection.getResponseMessage()); return DockerResponse.StatusCode.SERVER_ERROR; } else { throw new RuntimeException("Unknown status code :" + responseCode); } } catch (IOException e) { setDockerResponse(dockerResponse, e); if (e instanceof ConnectException && e.getLocalizedMessage().contains("Connection refused")) { // connection refused means the docker server is not running. dockerResponse.setStatusCode(DockerResponse.StatusCode.CONNECTION_REFUSED); return DockerResponse.StatusCode.CONNECTION_REFUSED; } } return DockerResponse.StatusCode.SERVER_ERROR; }
From source file:org.betaconceptframework.astroboa.resourceapi.resource.TopicResource.java
private Response generateTopicResponseUsingTopicInstance(String topicIdOrName, Output output, String callback, boolean prettyPrint) { try {// www.j av a 2s .co m Topic topic = findTopicByTopicIdOrName(topicIdOrName); if (topic == null) { throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND); } topic.getChildren(); StringBuilder topicAsXMLOrJSONBuilder = new StringBuilder(); switch (output) { case XML: { if (StringUtils.isBlank(callback)) { topicAsXMLOrJSONBuilder.append(topic.xml(prettyPrint)); } else { ContentApiUtils.generateXMLP(topicAsXMLOrJSONBuilder, topic.xml(prettyPrint), callback); } break; } case JSON: if (StringUtils.isBlank(callback)) { topicAsXMLOrJSONBuilder.append(topic.json(prettyPrint)); } else { ContentApiUtils.generateJSONP(topicAsXMLOrJSONBuilder, topic.json(prettyPrint), callback); } break; } return ContentApiUtils.createResponse(topicAsXMLOrJSONBuilder, output, callback, null); } catch (Exception e) { logger.error("Topic IdOrName: " + topicIdOrName, e); throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST); } }
From source file:rapture.kernel.StructuredApiImpl.java
/** * Used in joins to get a single authority and the docpaths as a List * * @param tableUris//from w ww .ja v a 2 s.c o m * @return */ private Pair<String, List<String>> getAuthorityAndDocPaths(List<String> tableUris) { if (CollectionUtils.isEmpty(tableUris)) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, apiMessageCatalog.getMessage("NullEmpty", "list of tableUris")); //$NON-NLS-1$ //$NON-NLS-2$ } // we assume the join is across the same DB provider RaptureURI uri = new RaptureURI(tableUris.get(0), Scheme.STRUCTURED); List<String> docPaths = new ArrayList<>(); for (String tableUri : tableUris) { RaptureURI ruri = new RaptureURI(tableUri, Scheme.STRUCTURED); docPaths.add(ruri.getDocPath()); } return Pair.of(uri.getAuthority(), docPaths); }