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:org.eclipse.orion.server.tests.servlets.workspace.WorkspaceServiceTest.java
@Test public void testCopyProject() throws IOException, SAXException, JSONException { //create workspace String workspaceName = WorkspaceServiceTest.class.getName() + "#testCopyProject"; URI workspaceLocation = createWorkspace(workspaceName); //create a project String sourceName = "Source Project"; WebRequest request = getCreateProjectRequest(workspaceLocation, sourceName, null); 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()); // 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());//from w ww .jav a 2 s.c o m 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:org.pixmob.freemobile.netstat.SyncService.java
private void registerDevice(String deviceId) throws IOException { final JSONObject json = new JSONObject(); try {//from w w w .ja v a 2 s . c o m json.put("brand", Build.BRAND); json.put("model", Build.MODEL); } catch (JSONException e) { final IOException ioe = new IOException("Failed to prepare device registration request"); ioe.initCause(e); throw ioe; } final byte[] rawJson = json.toString().getBytes("UTF-8"); Log.i(TAG, "Registering device"); final String url = createServerUrl("/device/" + deviceId); final HttpClient client = createHttpClient(); try { client.put(url).expect(HttpURLConnection.HTTP_CREATED).content(rawJson, "application/json").execute(); } catch (HttpClientException e) { final IOException ioe = new IOException("Failed to register device " + deviceId); ioe.initCause(e); throw ioe; } }
From source file:org.eclipse.orion.server.tests.servlets.git.GitConfigTest.java
@Test public void testUpdateConfigEntryUsingPOST() 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); // 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()); JSONObject configResponse = new JSONObject(response.getText()); String entryLocation = configResponse.getString(ProtocolConstants.KEY_LOCATION); // update config entry using POST final String NEW_ENTRY_VALUE = "valueABC"; request = getPostGitConfigRequest(gitConfigUri, ENTRY_KEY, NEW_ENTRY_VALUE); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CONFLICT, response.getResponseCode()); // get value of config entry JSONObject configEntry = listConfigEntries(entryLocation); // assert unchanged assertConfigOption(configEntry, ENTRY_KEY, ENTRY_VALUE); }/* w w w .j a va 2s . c om*/ }
From source file:org.eclipse.orion.server.tests.servlets.files.CoreFilesTest.java
@Test public void testCreateFileOverwrite() throws CoreException, IOException, SAXException, JSONException { String directoryPath = "sample/directory/path" + System.currentTimeMillis(); createDirectory(directoryPath);// ww w . jav a 2 s .com String fileName = "testfile.txt"; WebRequest request = getPostFilesRequest(directoryPath, getNewFileJSON(fileName).toString(), fileName); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); //creating again at the same location should succeed but return OK rather than CREATED request = getPostFilesRequest(directoryPath, getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); //creating with no-overwrite should fail if it already exists request = getPostFilesRequest(directoryPath, getNewFileJSON(fileName).toString(), fileName); request.setHeaderField("X-Create-Options", "no-overwrite"); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, response.getResponseCode()); }
From source file:org.eclipse.hono.deviceregistry.FileBasedCredentialsService.java
private CredentialsResult<JsonObject> addCredentialsResult(final String tenantId, final JsonObject credentialsToAdd) { final String authId = credentialsToAdd.getString(CredentialsConstants.FIELD_AUTH_ID); final String type = credentialsToAdd.getString(CredentialsConstants.FIELD_TYPE); log.debug("adding credentials for device [tenant-id: {}, auth-id: {}, type: {}]", tenantId, authId, type); final Map<String, JsonArray> credentialsForTenant = getCredentialsForTenant(tenantId); final JsonArray authIdCredentials = getAuthIdCredentials(authId, credentialsForTenant); // check if credentials already exist with the type and auth-id from the payload for (final Object credentialsObj : authIdCredentials) { final JsonObject credentials = (JsonObject) credentialsObj; if (credentials.getString(CredentialsConstants.FIELD_TYPE).equals(type)) { return CredentialsResult.from(HttpURLConnection.HTTP_CONFLICT); }/*w w w . j a v a2 s. c om*/ } authIdCredentials.add(credentialsToAdd); dirty = true; return CredentialsResult.from(HttpURLConnection.HTTP_CREATED); }
From source file:com.google.ytd.picasa.PicasaApiHelper.java
public PhotoEntry doResumableUpload(com.google.ytd.model.PhotoEntry photoEntry) throws IllegalArgumentException { if (util.isNullOrEmpty(photoEntry.getResumableUploadUrl())) { throw new IllegalArgumentException(String .format("No resumable upload URL found for " + "PhotoEntry id '%s'.", photoEntry.getId())); }/*from ww w. ja v a 2s .c o m*/ try { URL url = new URL(photoEntry.getResumableUploadUrl()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); connection.setRequestMethod("PUT"); connection.setRequestProperty("Content-Range", "bytes */*"); // Response code 308 is specific to this use case and doesn't appear to have a // HttpURLConnection constant. if (connection.getResponseCode() == 308) { long previousByte = 0; String rangeHeader = connection.getHeaderField("Range"); if (!util.isNullOrEmpty(rangeHeader)) { LOG.info("Range header in 308 response is " + rangeHeader); String[] rangeHeaderSplits = rangeHeader.split("-", 2); if (rangeHeaderSplits.length == 2) { previousByte = Long.valueOf(rangeHeaderSplits[1]).longValue() + 1; } } connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setDoOutput(true); connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); connection.setRequestMethod("PUT"); byte[] bytes; String contentRangeHeader; if (photoEntry.getBlobKey() != null) { long lastByte = previousByte + CHUNK_SIZE; if (lastByte > (photoEntry.getOriginalFileSize() - 1)) { lastByte = photoEntry.getOriginalFileSize() - 1; } contentRangeHeader = String.format("bytes %d-%d/%d", previousByte, lastByte, photoEntry.getOriginalFileSize()); BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService(); bytes = blobstoreService.fetchData(photoEntry.getBlobKey(), previousByte, lastByte); } else { bytes = dataChunkDao.getBytes(photoEntry.getId(), previousByte); if (bytes == null) { throw new IllegalArgumentException(String.format("PhotoEntry with id '%s' does not " + "have a valid blob key. Additionally, there is no DataChunk entry for the " + "initial byte '%d'.", photoEntry.getId(), previousByte)); } contentRangeHeader = String.format("bytes %d-%d/%d", previousByte, previousByte + bytes.length - 1, photoEntry.getOriginalFileSize()); } connection.setRequestProperty("Content-Length", String.valueOf(bytes.length)); LOG.info("Using the following for Content-Range header: " + contentRangeHeader); connection.setRequestProperty("Content-Range", contentRangeHeader); OutputStream outputStream = connection.getOutputStream(); outputStream.write(bytes); outputStream.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) { LOG.info("Resumable upload is complete and successful."); return (PhotoEntry) ParseUtil.readEntry(new ParseSource(connection.getInputStream())); } } else if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) { // It's possible that the Picasa upload associated with the specific resumable upload URL // had previously completed successfully. In that case, the response to the initial */* PUT // will be a 201 Created with the new PhotoEntry. This is probably an edge case. LOG.info("Resumable upload is complete and successful."); return (PhotoEntry) ParseUtil.readEntry(new ParseSource(connection.getInputStream())); } else { // The IllegalArgumentException should be treated by the calling code as // something that is not recoverable, which is to say the resumable upload attempt // should be stopped. throw new IllegalArgumentException(String.format("HTTP POST to %s returned status %d (%s).", url.toString(), connection.getResponseCode(), connection.getResponseMessage())); } } catch (MalformedURLException e) { LOG.log(Level.WARNING, "", e); throw new IllegalArgumentException(e); } catch (IOException e) { LOG.log(Level.WARNING, "", e); } catch (ServiceException e) { LOG.log(Level.WARNING, "", e); } return null; }
From source file:org.openrdf.http.client.SesameSession.java
public synchronized void beginTransaction(IsolationLevel isolationLevel) throws OpenRDFException, IOException, UnauthorizedException { checkRepositoryURL();//w w w . j a va 2 s . c o m if (transactionURL != null) { throw new IllegalStateException("Transaction URL is already set"); } HttpPost method = new HttpPost(Protocol.getTransactionsLocation(getRepositoryURL())); method.setHeader("Content-Type", Protocol.FORM_MIME_TYPE + "; charset=utf-8"); List<NameValuePair> params = new ArrayList<NameValuePair>(); if (isolationLevel != null) { params.add(new BasicNameValuePair(Protocol.ISOLATION_LEVEL_PARAM_NAME, isolationLevel.getURI().stringValue())); } method.setEntity(new UrlEncodedFormEntity(params, UTF8)); HttpResponse response = execute(method); int code = response.getStatusLine().getStatusCode(); try { if (code == HttpURLConnection.HTTP_CREATED) { transactionURL = response.getFirstHeader("Location").getValue(); if (transactionURL == null) { throw new RepositoryException("no valid transaction ID received in server response."); } } else { throw new RepositoryException("unable to start transaction. HTTP error code " + code); } } finally { EntityUtils.consume(response.getEntity()); } }
From source file:org.eclipse.orion.server.tests.servlets.git.GitPushTest.java
@Test public void testPushBranch() throws Exception { URI workspaceLocation = createWorkspace(getMethodName()); String workspaceId = workspaceIdFromLocation(workspaceLocation); // clone1: create JSONObject project1 = createProjectOrLink(workspaceLocation, getMethodName() + "1", null); IPath clonePath1 = getClonePath(workspaceId, project1); JSONObject clone1 = clone(clonePath1); String cloneLocation1 = clone1.getString(ProtocolConstants.KEY_LOCATION); String branchesLocation1 = clone1.getString(GitConstants.KEY_BRANCH); // get project1 metadata WebRequest request = getGetRequest(project1.getString(ProtocolConstants.KEY_CONTENT_LOCATION)); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); project1 = new JSONObject(response.getText()); JSONObject gitSection1 = project1.optJSONObject(GitConstants.KEY_GIT); assertNotNull(gitSection1);//w ww. j av a 2 s. c o m String gitIndexUri1 = gitSection1.getString(GitConstants.KEY_INDEX); String gitHeadUri1 = gitSection1.getString(GitConstants.KEY_HEAD); // clone1: branch 'a' response = branch(branchesLocation1, "a"); JSONObject branch = new JSONObject(response.getText()); checkoutBranch(cloneLocation1, "a"); // clone1: change JSONObject testTxt1 = getChild(project1, "test.txt"); modifyFile(testTxt1, "branch 'a' change"); // clone1: add request = GitAddTest.getPutGitIndexRequest(gitIndexUri1); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // clone1: commit request = GitCommitTest.getPostGitCommitRequest(gitHeadUri1, "incoming branch 'a' commit", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // clone1: push by remote branch JSONArray remoteBranchLocations = branch.getJSONArray(GitConstants.KEY_REMOTE); assertEquals(1, remoteBranchLocations.length()); String remoteBranchLocation = remoteBranchLocations.getJSONObject(0) .getJSONArray(ProtocolConstants.KEY_CHILDREN).getJSONObject(0) .getString(ProtocolConstants.KEY_LOCATION); ServerStatus pushStatus = push(remoteBranchLocation, Constants.HEAD, false); assertTrue(pushStatus.isOK()); // clone1: get the remote branch name request = getGetRequest(remoteBranchLocation); response = webConversation.getResponse(request); JSONObject remoteBranch1 = new JSONObject(response.getText()); String remoteBranchName1 = remoteBranch1.getString(ProtocolConstants.KEY_NAME); // clone2 JSONObject project2 = createProjectOrLink(workspaceLocation, getMethodName() + "2", null); IPath clonePath2 = getClonePath(workspaceId, project2); JSONObject clone2 = clone(clonePath2); String cloneLocation2 = clone2.getString(ProtocolConstants.KEY_LOCATION); String branchesLocation2 = clone2.getString(GitConstants.KEY_BRANCH); // get project2 metadata request = getGetRequest(project2.getString(ProtocolConstants.KEY_CONTENT_LOCATION)); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); project2 = new JSONObject(response.getText()); JSONObject gitSection2 = project2.optJSONObject(GitConstants.KEY_GIT); assertNotNull(gitSection2); // create a local branch 'a' tracking remoteBranchName1 and checkout 'a' response = branch(branchesLocation2, "a", remoteBranchName1); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); response = checkoutBranch(cloneLocation2, "a"); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject testTxt2 = getChild(project2, "test.txt"); request = getGetRequest(testTxt2.getString(ProtocolConstants.KEY_LOCATION)); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); assertEquals("branch 'a' change", response.getText()); }
From source file:org.dspace.identifier.EZIDIdentifierProvider.java
@Override public String mint(Context context, DSpaceObject dso) throws IdentifierException { log.debug("mint for {}", dso); // Compose the request EZIDRequest request;/*w w w . j a va2 s. c om*/ try { request = createRequest(context, dso); } catch (URISyntaxException ex) { log.error(ex.getMessage()); throw new IdentifierException("DOI request not sent: " + ex.getMessage()); } // Send the request EZIDResponse response; try { Map<String, String> ezidMetadata = fillMetadataDefaults(crosswalkMetadata(dso), context, dso); response = request.mint(ezidMetadata); } catch (IOException ex) { log.error("Failed to send EZID request: {}", ex.getMessage()); throw new IdentifierException("DOI request not sent: " + ex.getMessage()); } catch (URISyntaxException ex) { log.error("Failed to send EZID request: {}", ex.getMessage()); throw new IdentifierException("DOI request not sent: " + ex.getMessage()); } // Good response? if (HttpURLConnection.HTTP_CREATED != response.getHttpStatusCode()) { log.error("EZID server responded: {} {}: {}", new String[] { String.valueOf(response.getHttpStatusCode()), response.getHttpReasonPhrase(), response.getEZIDStatusValue() }); throw new IdentifierException( "DOI not created: " + response.getHttpReasonPhrase() + ": " + response.getEZIDStatusValue()); } // Extract the DOI from the content blob if (response.isSuccess()) { String value = response.getEZIDStatusValue(); int end = value.indexOf('|'); // Following pipe is "shadow ARK" if (end < 0) { end = value.length(); } String doi = value.substring(0, end).trim(); String uri = uriForId(context, dso, doi); return uri; } else { log.error("EZID responded: {}", response.getEZIDStatusValue()); throw new IdentifierException("No DOI returned"); } }
From source file:org.eclipse.orion.server.tests.servlets.files.CoreFilesTest.java
@Test public void testCreateTopLevelFile() throws CoreException, IOException, SAXException, JSONException { String directoryPath = "sample" + System.currentTimeMillis(); createDirectory(directoryPath);//from w ww.j a va 2 s . c o m String fileName = "testfile.txt"; WebRequest request = getPostFilesRequest(directoryPath, getNewFileJSON(fileName).toString(), fileName); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); assertTrue("Create file response was OK, but the file does not exist", checkFileExists(directoryPath + "/" + fileName)); assertEquals("Response should contain file metadata in JSON, but was " + response.getText(), "application/json", response.getContentType()); JSONObject responseObject = new JSONObject(response.getText()); assertNotNull("No file information in response", responseObject); checkFileMetadata(responseObject, fileName, null, null, null, null, null, null, null, null); //should be able to perform GET on location header to obtain metadata String location = response.getHeaderField("Location"); request = getGetRequest(location + "?parts=meta"); response = webConversation.getResource(request); assertNotNull(location); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); responseObject = new JSONObject(response.getText()); assertNotNull("No direcory information in response", responseObject); checkFileMetadata(responseObject, fileName, null, null, null, null, null, null, null, null); }