List of usage examples for java.net HttpURLConnection HTTP_CREATED
int HTTP_CREATED
To view the source code for java.net HttpURLConnection HTTP_CREATED.
Click Source Link
From source file:com.flurry.proguard.UploadMapping.java
/** * Upload the archive to Flurry//ww w. j av a 2 s . co m * * @param file the archive to send * @param projectId the project's id * @param uploadId the the upload's id * @param token the Flurry auth token */ private static void sendToUploadService(File file, String projectId, String uploadId, String token) throws IOException { String uploadServiceUrl = String.format("%s/upload/%s/%s", UPLOAD_BASE, projectId, uploadId); List<Header> requestHeaders = getUploadServiceHeaders(file.length(), token); HttpPost postRequest = new HttpPost(uploadServiceUrl); postRequest.setEntity(new FileEntity(file)); try (CloseableHttpResponse response = executeHttpRequest(postRequest, requestHeaders)) { expectStatus(response, HttpURLConnection.HTTP_CREATED, HttpURLConnection.HTTP_ACCEPTED); } finally { postRequest.releaseConnection(); } }
From source file:it.geosolutions.geoserver.rest.HTTPUtils.java
/** * Send an HTTP request (PUT or POST) to a server. <BR> * Basic auth is used if both username and pw are not null. * <P>// w w w . j a va2s . c o m * Only * <UL> * <LI>200: OK</LI> * <LI>201: ACCEPTED</LI> * <LI>202: CREATED</LI> * </UL> * are accepted as successful codes; in these cases the response string will * be returned. * * @return the HTTP response or <TT>null</TT> on errors. */ private static String send(final EntityEnclosingMethod httpMethod, String url, RequestEntity requestEntity, String username, String pw) { HttpClient client = new HttpClient(); HttpConnectionManager connectionManager = client.getHttpConnectionManager(); try { setAuth(client, url, username, pw); connectionManager.getParams().setConnectionTimeout(5000); if (requestEntity != null) httpMethod.setRequestEntity(requestEntity); int status = client.executeMethod(httpMethod); switch (status) { case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_CREATED: case HttpURLConnection.HTTP_ACCEPTED: String response = IOUtils.toString(httpMethod.getResponseBodyAsStream()); // LOGGER.info("================= POST " + url); if (LOGGER.isInfoEnabled()) LOGGER.info("HTTP " + httpMethod.getStatusText() + ": " + response); return response; default: LOGGER.warn("Bad response: code[" + status + "]" + " msg[" + httpMethod.getStatusText() + "]" + " url[" + url + "]" + " method[" + httpMethod.getClass().getSimpleName() + "]: " + IOUtils.toString(httpMethod.getResponseBodyAsStream())); return null; } } catch (ConnectException e) { LOGGER.info("Couldn't connect to [" + url + "]"); return null; } catch (IOException e) { LOGGER.error("Error talking to " + url + " : " + e.getLocalizedMessage()); return null; } finally { if (httpMethod != null) httpMethod.releaseConnection(); connectionManager.closeIdleConnections(0); } }
From source file:org.onosproject.rest.resources.MastershipResourceTest.java
/** * Tests the result of the REST API GET for relinquishing mastership role. *//*from w w w . j av a2s. c om*/ @Test public void testRelinquishMastership() { mockService.relinquishMastershipSync(anyObject()); expectLastCall(); replay(mockService); final WebTarget wt = target(); final Response response = wt.path("mastership/" + deviceId1.toString() + "/relinquish").request().get(); assertThat(response.getStatus(), is(HttpURLConnection.HTTP_CREATED)); String location = response.getLocation().toString(); assertThat(location, Matchers.startsWith(deviceId1.toString())); }
From source file:org.eclipse.orion.server.tests.servlets.workspace.WorkspaceServiceTest.java
@Test public void testCopyProjectNonDefaultLocation() throws IOException, SAXException, JSONException { //create workspace String workspaceName = WorkspaceServiceTest.class.getName() + "#testCopyProjectNonDefaultLocation"; URI workspaceLocation = createWorkspace(workspaceName); String tmp = System.getProperty("java.io.tmpdir"); File projectLocation = new File(new File(tmp), "Orion-testCopyProjectNonDefaultLocation"); projectLocation.mkdir();/*from w ww . j a v a2 s . c om*/ toDelete.add(EFS.getLocalFileSystem().getStore(projectLocation.toURI())); ServletTestingSupport.allowedPrefixes = projectLocation.toString(); //create a project String sourceName = "My Project"; WebRequest request = getCreateProjectRequest(workspaceLocation, sourceName, projectLocation.toString()); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); String sourceLocation = response.getHeaderField(ProtocolConstants.HEADER_LOCATION); JSONObject responseObject = new JSONObject(response.getText()); String sourceContentLocation = responseObject.optString(ProtocolConstants.KEY_CONTENT_LOCATION); assertNotNull(sourceContentLocation); //add a file in the project String fileName = "file.txt"; request = getPostFilesRequest(toAbsoluteURI(sourceContentLocation), "{}", fileName); response = webConversation.getResource(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); assertEquals("Response should contain file metadata in JSON, but was " + response.getText(), "application/json", response.getContentType()); JSONObject fileResponseObject = new JSONObject(response.getText()); assertNotNull("No file information in response", fileResponseObject); checkFileMetadata(fileResponseObject, fileName, null, null, null, null, null, null, null, sourceName); // copy the project String destinationName = "Destination Project"; request = getCopyMoveProjectRequest(workspaceLocation, destinationName, sourceLocation, false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); String destinationLocation = response.getHeaderField(ProtocolConstants.HEADER_LOCATION); String destinationContentLocation = responseObject.optString(ProtocolConstants.KEY_CONTENT_LOCATION); //assert the copy took effect assertFalse(sourceLocation.equals(destinationLocation)); JSONObject resultObject = new JSONObject(response.getText()); assertEquals(destinationName, resultObject.getString(ProtocolConstants.KEY_NAME)); //ensure the source is still intact response = webConversation.getResponse(getGetRequest(sourceContentLocation + "?depth=1")); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); resultObject = new JSONObject(response.getText()); assertEquals(sourceName, resultObject.getString(ProtocolConstants.KEY_NAME)); JSONArray children = resultObject.getJSONArray(ProtocolConstants.KEY_CHILDREN); assertEquals(1, children.length()); JSONObject child = children.getJSONObject(0); assertEquals(fileName, child.getString(ProtocolConstants.KEY_NAME)); //ensure the destination is intact response = webConversation.getResponse(getGetRequest(destinationContentLocation + "?depth=1")); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); resultObject = new JSONObject(response.getText()); assertEquals(sourceName, resultObject.getString(ProtocolConstants.KEY_NAME)); children = resultObject.getJSONArray(ProtocolConstants.KEY_CHILDREN); assertEquals(1, children.length()); child = children.getJSONObject(0); assertEquals(fileName, child.getString(ProtocolConstants.KEY_NAME)); }
From source file:jp.realglobe.util.uploader.DirectoryUploader.java
/** * ?//ww w. j ava2s . c om * @param token1 ? * @param path ?? * @throws IOException ???????? * @throws HttpException HTTP */ private void upload(final String token1, final Path path) throws HttpException, IOException { try (CloseableHttpClient client = HttpClients.createDefault()) { final HttpPost post = new HttpPost(this.uploadUrl); post.setEntity(MultipartEntityBuilder.create().addTextBody("info", "{}") .addTextBody(Constants.UPLOAD_REQUEST_PART_TOKEN, token1) .addBinaryBody(Constants.UPLOAD_REQUEST_PART_DATA, path.toFile()).build()); LOG.info("Upload " + path); try (CloseableHttpResponse response = client.execute(post)) { if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_CREATED) { return; } LOG.warning(response.toString()); } } }
From source file:org.geosdi.geoplatform.publish.HttpUtilsLocal.java
/** * Send an HTTP request (PUT or POST) to a server. * <BR>Basic auth is used if both username and pw are not null. * <P>/*from ww w .j av a 2s. c o m*/ * Only <UL> * <LI>200: OK</LI> * <LI>201: ACCEPTED</LI> * <LI>202: CREATED</LI> * </UL> are accepted as successful codes; in these cases the response string will be returned. * * @return the HTTP response or <TT>null</TT> on errors. */ private static String send(final EntityEnclosingMethod httpMethod, String url, RequestEntity requestEntity, String username, String pw) { try { HttpClient client = new HttpClient(); setAuth(client, url, username, pw); // httpMethod = new PutMethod(url); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); if (requestEntity != null) { httpMethod.setRequestEntity(requestEntity); } int status = client.executeMethod(httpMethod); switch (status) { case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_CREATED: case HttpURLConnection.HTTP_ACCEPTED: String response = IOUtils.toString(httpMethod.getResponseBodyAsStream()); // LOGGER.info("================= POST " + url); LOGGER.info("HTTP " + httpMethod.getStatusText() + ": " + response); return response; default: LOGGER.warn("Bad response: code[" + status + "]" + " msg[" + httpMethod.getStatusText() + "]" + " url[" + url + "]" + " method[" + httpMethod.getClass().getSimpleName() + "]: " + IOUtils.toString(httpMethod.getResponseBodyAsStream())); return null; } } catch (ConnectException e) { LOGGER.info("Couldn't connect to [" + url + "]"); return null; } catch (IOException e) { LOGGER.error("Error talking to " + url + " : " + e.getLocalizedMessage()); return null; } finally { if (httpMethod != null) { httpMethod.releaseConnection(); } } }
From source file:com.cloudera.hoop.client.fs.HoopFileSystem.java
/** * Opens an FSDataOutputStream at the indicated Path with write-progress * reporting.//from w w w . j a v a 2 s. c om * <p/> * IMPORTANT: The <code>Progressable</code> parameter is not used. * * @param f the file name to open * @param permission * @param overwrite if a file with this name already exists, then if true, * the file will be overwritten, and if false an error will be thrown. * @param bufferSize the size of the buffer to be used. * @param replication required block replication for the file. * @param blockSize * @param progress * @throws IOException * @see #setPermission(Path, FsPermission) */ @Override public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { Map<String, String> params = new HashMap<String, String>(); params.put("op", "create"); params.put("overwrite", Boolean.toString(overwrite)); params.put("replication", Short.toString(replication)); params.put("blocksize", Long.toString(blockSize)); params.put("permission", permissionToString(permission)); HttpURLConnection conn = getConnection("POST", params, f); try { OutputStream os = new BufferedOutputStream(conn.getOutputStream(), bufferSize); return new HoopFSDataOutputStream(conn, os, HttpURLConnection.HTTP_CREATED, statistics); } catch (IOException ex) { validateResponse(conn, HttpURLConnection.HTTP_CREATED); throw ex; } }
From source file:de.rwth.dbis.acis.activitytracker.service.ActivityTrackerService.java
@POST @Path("/") @Consumes(MediaType.APPLICATION_JSON)// w w w . jav a 2 s .c o m @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "This method allows to create an activity", notes = "Returns the created activity") @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Activity created"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") }) public HttpResponse createActivity( @ApiParam(value = "Activity" + " entity as JSON", required = true) @ContentParam String activity) { Gson gson = new Gson(); DALFacade dalFacade = null; Activity activityToCreate = gson.fromJson(activity, Activity.class); //TODO validate activity try { dalFacade = getDBConnection(); Activity createdActivity = dalFacade.createActivity(activityToCreate); return new HttpResponse(gson.toJson(createdActivity), HttpURLConnection.HTTP_CREATED); } catch (Exception ex) { ActivityTrackerException atException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.ACTIVITIESERVICE, ErrorCode.UNKNOWN, ""); return new HttpResponse(ExceptionHandler.getInstance().toJSON(atException), HttpURLConnection.HTTP_INTERNAL_ERROR); } finally { closeDBConnection(dalFacade); } }
From source file:org.eclipse.orion.server.tests.servlets.git.GitConfigTest.java
@Test public void testAddConfigEntry() 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); JSONObject configResponse = listConfigEntries(gitConfigUri); JSONArray configEntries = configResponse.getJSONArray(ProtocolConstants.KEY_CHILDREN); // initial number of config entries int initialConfigEntriesCount = configEntries.length(); // set some dummy value final String ENTRY_KEY = "a.b.c"; final String ENTRY_VALUE = "v"; request = getPostGitConfigRequest(gitConfigUri, ENTRY_KEY, ENTRY_VALUE); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); configResponse = new JSONObject(response.getText()); String entryLocation = configResponse.getString(ProtocolConstants.KEY_LOCATION); assertConfigUri(entryLocation);//from w w w . j a v a 2s. c o m // get list of config entries again configResponse = listConfigEntries(gitConfigUri); configEntries = configResponse.getJSONArray(ProtocolConstants.KEY_CHILDREN); assertEquals(initialConfigEntriesCount + 1, configEntries.length()); entryLocation = null; for (int i = 0; i < configEntries.length(); i++) { JSONObject configEntry = configEntries.getJSONObject(i); if (ENTRY_KEY.equals(configEntry.getString(GitConstants.KEY_CONFIG_ENTRY_KEY))) { assertConfigOption(configEntry, ENTRY_KEY, ENTRY_VALUE); break; } } // double check org.eclipse.jgit.lib.Config config = getRepositoryForContentLocation(contentLocation).getConfig(); assertEquals(ENTRY_VALUE, config.getString("a", "b", "c")); } }