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.site.SiteTest.java
@Test /**/* w ww . ja va 2 s .c o m*/ * Attempt to create site with no workspace, expect 400 Bad Request */ public void testCreateSiteNoWorkspace() throws SAXException, IOException { final String siteName = "My great website"; final String hostHint = "mySite"; WebRequest request = getCreateSiteRequest(siteName, null, null, hostHint); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode()); }
From source file:org.cellprofiler.subimager.ImageWriterHandler.java
public void handle(HttpExchange exchange) throws IOException { if (!exchange.getRequestMethod().equals("POST")) { reportError(exchange, HttpURLConnection.HTTP_BAD_METHOD, "<html><body>writeimage only accepts HTTP post</body></html>"); return;/*from w ww . j av a 2 s . c o m*/ } final String contentType = exchange.getRequestHeaders().getFirst("Content-Type"); if (contentType == null) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, "<html><body>No Content-type request header</body></html>"); return; } if (!contentType.startsWith(MULTIPART_FORM_DATA)) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, "<html><body>Content type must be " + MULTIPART_FORM_DATA + ".</body></html>"); return; } int idx = contentType.indexOf(BOUNDARY_EQUALS, MULTIPART_FORM_DATA.length()); if (idx == -1) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, "<html><body>Did not find boundary identifier in multipart/form-data content type.</body></html>"); return; } final String contentEncoding = exchange.getRequestHeaders().getFirst("Content-Encoding"); String contentLengthString = exchange.getRequestHeaders().getFirst("Content-Length"); if (contentLengthString == null) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, "<html><body>No Content-Length request header</body></html>"); return; } try { Integer.parseInt(contentLengthString); } catch (NumberFormatException e) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, String .format("<html><body>Content length was not a number: %s</body></html>", contentLengthString)); return; } final int contentLength = Integer.parseInt(contentLengthString); final InputStream requestBodyStream = exchange.getRequestBody(); FileUpload upload = new FileUpload(); FileItemIterator fileItemIterator; String omeXML = null; URI uri = null; int index = 0; NDImage ndimage = null; String compression = DEFAULT_COMPRESSION; try { fileItemIterator = upload.getItemIterator(new RequestContext() { public String getCharacterEncoding() { return contentEncoding; } public String getContentType() { return contentType; } public int getContentLength() { return contentLength; } public InputStream getInputStream() throws IOException { return requestBodyStream; } }); while (fileItemIterator.hasNext()) { FileItemStream fis = fileItemIterator.next(); String name = fis.getFieldName(); if (name.equals(NAME_IMAGE)) { String imageContentType = fis.getContentType(); if (imageContentType == null) { reportError(exchange, HttpURLConnection.HTTP_UNSUPPORTED_TYPE, "<html><body>Image form-data field must have a content type.</body></html>"); return; } try { InputStream is = SubimagerUtils.getInputStream(exchange, fis); if (is == null) return; ndimage = NDImage.decode(is); } catch (MalformedStreamException e) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, "<html><body>Failed to read body for part, " + name + ".</body></html>"); } catch (IOException e) { reportError(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR, "<html><body>Failed to read multipart body data</body></html>"); return; } catch (org.cellprofiler.subimager.NDImage.FormatException e) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, "<html><body>Image data was not in correct format: " + e.getMessage() + "</body></html>"); return; } } else { String partDataString = SubimagerUtils.readFully(exchange, fis); if (partDataString == null) return; if (name.equals(NAME_INDEX)) { try { index = Integer.parseInt(partDataString); } catch (NumberFormatException e) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, "<html><body>Index form-data field must be a number: " + partDataString + ".</body></html>"); return; } } else if (name.equals(NAME_OMEXML)) { omeXML = partDataString; } else if (name.equals(NAME_URL)) { try { uri = new URI(partDataString); } catch (URISyntaxException e) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, "<html><body>Improperly formatted URL: " + partDataString + ".</body></html>"); return; } } else if (name.equals(NAME_COMPRESSION)) { compression = partDataString; } } } if (ndimage == null) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, "<html><body>Request did not have an image part</body></html>"); return; } if (uri == null) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, "<html><body>Request did not have a URL part</body></html>"); return; } if (omeXML == null) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, "<html><body>Request did not have an omexml part</body></html>"); return; } writeImage(exchange, ndimage, uri, omeXML, index, compression); } catch (FileUploadException e) { reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, String .format("<html><body>Parsing error in multipart message: %s</body></html>", e.getMessage())); return; } }
From source file:play.modules.resteasy.crud.RESTResource.java
/** * Throws BAD_REQUEST if the given parameters are not null or are not empty collections * @param objects the objects to check/*from w w w.ja v a2s . c o m*/ */ protected void checkEmpty(Object... objects) { for (Object o : objects) { if (o == null) continue; if (o instanceof Collection && ((Collection<?>) o).isEmpty()) continue; throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST); } }
From source file:eu.codeplumbers.cosi.services.CosiFileDownloadService.java
@Override protected void onHandleIntent(Intent intent) { // Do the task here Log.i(CosiFileDownloadService.class.getName(), "Cosi Service running"); // Release the wake lock provided by the WakefulBroadcastReceiver. WakefulBroadcastReceiver.completeWakefulIntent(intent); Device device = Device.registeredDevice(); // cozy register device url fileUrl = device.getUrl() + "/ds-api/data/"; // concatenate username and password with colon for authentication final String credentials = device.getLogin() + ":" + device.getPassword(); authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); showNotification();// w w w . j av a 2s .c om if (isNetworkAvailable()) { try { ArrayList<String> fileStrings = intent.getStringArrayListExtra("fileToDownload"); for (int i = 0; i < fileStrings.size(); i++) { File file = File.load(File.class, Long.valueOf(fileStrings.get(i))); String binaryRemoteId = file.getRemoteId(); if (!binaryRemoteId.isEmpty()) { mBuilder.setProgress(100, 0, false); mBuilder.setContentText("Downloading file: " + file.getName()); mNotifyManager.notify(notification_id, mBuilder.build()); URL urlO = null; try { urlO = new URL(fileUrl + binaryRemoteId + "/binaries/file"); HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoInput(true); conn.setRequestMethod("GET"); conn.connect(); int lenghtOfFile = conn.getContentLength(); // read the response int status = conn.getResponseCode(); if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { EventBus.getDefault() .post(new FileSyncEvent(SERVICE_ERROR, conn.getResponseMessage())); stopSelf(); } else { int count = 0; InputStream in = new BufferedInputStream(conn.getInputStream(), 8192); java.io.File newFile = file.getLocalPath(); if (!newFile.exists()) { newFile.createNewFile(); } // Output stream to write file OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + java.io.File.separator + Constants.APP_DIRECTORY + java.io.File.separator + "files" + file.getPath() + "/" + file.getName()); byte data[] = new byte[1024]; long total = 0; while ((count = in.read(data)) != -1) { total += count; mBuilder.setProgress(lenghtOfFile, (int) total, false); mBuilder.setContentText("Downloading file: " + file.getName()); mNotifyManager.notify(notification_id, mBuilder.build()); // writing data to file output.write(data, 0, count); } // flushing output output.flush(); // closing streams output.close(); in.close(); file.setDownloaded(true); file.save(); } } catch (MalformedURLException e) { EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } } } mNotifyManager.cancel(notification_id); EventBus.getDefault().post(new FileSyncEvent(REFRESH, "Sync OK")); } catch (Exception e) { e.printStackTrace(); mSyncRunning = false; EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); } } else { mSyncRunning = false; EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, "No Internet connection")); mBuilder.setContentText("Sync failed because no Internet connection was available"); mNotifyManager.notify(notification_id, mBuilder.build()); } }
From source file:org.eclipse.orion.server.tests.servlets.git.GitCommitTest.java
@Test public void testCommitEmptyComment() throws Exception { URI workspaceLocation = createWorkspace(getMethodName()); String projectName = getMethodName(); JSONObject project = createProjectOrLink(workspaceLocation, projectName, gitDir.toString()); JSONObject testTxt = getChild(project, "test.txt"); modifyFile(testTxt, "change to commit"); JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT); String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD); addFile(testTxt);// w w w .ja va2 s. com // commit with a null message WebRequest request = getPostGitCommitRequest(gitHeadUri /* all */, "", false); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode()); }
From source file:com.alphabetbloc.accessmrs.tasks.CheckConnectivityTask.java
protected DataInputStream getServerStream() throws Exception { HttpPost request = new HttpPost(mServer); request.setEntity(new OdkAuthEntity()); HttpResponse response = httpClient.execute(request); response.getStatusLine().getStatusCode(); HttpEntity responseEntity = response.getEntity(); responseEntity.getContentLength();// ww w.j a v a2s . com DataInputStream zdis = new DataInputStream(new GZIPInputStream(responseEntity.getContent())); int status = zdis.readInt(); if (status == HttpURLConnection.HTTP_UNAUTHORIZED) { zdis.close(); throw new IOException("Access denied. Check your username and password."); } else if (status <= 0 || status >= HttpURLConnection.HTTP_BAD_REQUEST) { zdis.close(); throw new IOException("Connection Failed. Please Try Again."); } else { assert (status == HttpURLConnection.HTTP_OK); // success return zdis; } }
From source file:rapture.kernel.StructuredApiImpl.java
@Override public Boolean structuredRepoExists(CallingContext context, String repoURI) { RaptureURI uri = new RaptureURI(repoURI, Scheme.STRUCTURED); if (uri.hasDocPath()) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, apiMessageCatalog.getMessage("NoDocPath", repoURI)); //$NON-NLS-1$ }// w w w . j a va2 s . com return getRepoFromCache(uri.getAuthority()) != null; }
From source file:org.eclipse.hono.service.registration.BaseRegistrationService.java
private Future<EventBusMessage> processRegisterRequest(final EventBusMessage request) { final String tenantId = request.getTenant(); final String deviceId = request.getDeviceId(); final JsonObject payload = getRequestPayload(request.getJsonPayload()); if (tenantId == null || deviceId == null) { return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST)); } else {//from ww w .j av a2s . c o m log.debug("registering device [{}] for tenant [{}]", deviceId, tenantId); final Future<RegistrationResult> result = Future.future(); addDevice(tenantId, deviceId, payload, result.completer()); return result.map(res -> { return request.getResponse(res.getStatus()).setDeviceId(deviceId) .setCacheDirective(res.getCacheDirective()); }); } }
From source file:org.eclipse.orion.server.tests.servlets.git.GitResetTest.java
@Test public void testResetNull() throws Exception { URI workspaceLocation = createWorkspace(getMethodName()); String projectName = getMethodName(); JSONObject project = createProjectOrLink(workspaceLocation, projectName, gitDir.toString()); JSONObject testTxt = getChild(project, "test.txt"); modifyFile(testTxt, "hello"); JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT); String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX); WebRequest request = getPostGitIndexRequest(gitIndexUri, null, null, (String) null); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode()); }
From source file:rapture.kernel.ScriptApiImpl.java
@Override public void createScriptLink(CallingContext context, String fromScriptURI, String toScriptURI) { if (doesScriptExist(context, fromScriptURI)) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, String.format("Script %s already exists", fromScriptURI)); } else {/*www.j a va 2 s. c o m*/ RaptureURI internalURI = new RaptureURI(fromScriptURI, Scheme.SCRIPT); RaptureScript s = new RaptureScript(); s.setLanguage(RaptureScriptLanguage.REFLEX); s.setPurpose(RaptureScriptPurpose.LINK); s.setName(internalURI.getDocPath()); s.setScript(toScriptURI); s.setAuthority(internalURI.getAuthority()); RaptureScriptStorage.add(internalURI, s, context.getUser(), Messages.getString("Script.createdScript")); //$NON-NLS-1$ } }