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.git.GitTest.java
protected WebResponse addRemote(String remotesLocation, String name, String uri, String fetchRefSpec, String pushUri, String pushRefSpec) throws JSONException, IOException, SAXException { assertRemoteUri(remotesLocation);// w w w . j a v a 2 s .c o m WebRequest request = GitRemoteTest.getPostGitRemoteRequest(remotesLocation, name, uri, fetchRefSpec, pushUri, pushRefSpec); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); return response; }
From source file:org.eclipse.orion.server.docker.server.DockerServer.java
private DockerResponse.StatusCode getDockerResponse(DockerResponse dockerResponse, HttpURLConnection httpURLConnection) { try {//from w ww. ja v a 2s.co m 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.eclipse.orion.server.tests.servlets.workspace.WorkspaceServiceTest.java
@Test public void testDeleteProject() throws IOException, SAXException, JSONException, URISyntaxException, CoreException { //create workspace String workspaceName = WorkspaceServiceTest.class.getName() + "#testDeleteProject"; URI workspaceLocation = createWorkspace(workspaceName); //create a project String projectName = "My Project"; WebRequest request = getCreateProjectRequest(workspaceLocation, projectName, null); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); String projectLocation = response.getHeaderField(ProtocolConstants.HEADER_LOCATION); JSONObject project = new JSONObject(response.getText()); //delete project request = new DeleteMethodWebRequest(toAbsoluteURI(projectLocation)); request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1"); setAuthentication(request);// w w w . j ava 2 s . co m response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); //ensure project does not appear in the workspace metadata request = new GetMethodWebRequest(addSchemeHostPort(workspaceLocation).toString()); setAuthentication(request); response = webConversation.getResponse(request); JSONObject workspace = new JSONObject(response.getText()); assertNotNull(workspace); JSONArray projects = workspace.getJSONArray(ProtocolConstants.KEY_PROJECTS); assertEquals(0, projects.length()); //ensure project content is deleted if (OrionConfiguration.getMetaStore() instanceof SimpleMetaStore) { // simple metastore, projects not in the same simple location anymore, so do not check } else { // legacy metastore, use what was in the original test String projectId = project.getString(ProtocolConstants.KEY_ID); IFileStore projectStore = EFS.getStore(makeLocalPathAbsolute(projectId)); assertFalse(projectStore.fetchInfo().exists()); } //deleting again should be safe (DELETE is idempotent) response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); //check user rights have been removed String testUser = getTestUserId(); try { //first we need to remove the global rights assigned to test user AuthorizationService.removeUserRight(testUser, "/"); AuthorizationService.removeUserRight(testUser, "/*"); IPath path = new Path(new URI(projectLocation).getPath()); //project location format is /workspace/<workspaceId>/project/<projectName> projectName = path.segment(3); assertFalse(AuthorizationService.checkRights(testUser, "/file/" + projectName, "PUT")); assertFalse(AuthorizationService.checkRights(testUser, "/file/" + projectName + "/*", "PUT")); } finally { //give test user global rights again AuthorizationService.addUserRight(testUser, "/"); AuthorizationService.addUserRight(testUser, "/*"); } }
From source file:org.eclipse.orion.server.tests.servlets.xfer.TransferTest.java
@Test public void testImportWithPost() throws CoreException, IOException, SAXException { //create a directory to upload to String directoryPath = "sample/testImportWithPost/path" + System.currentTimeMillis(); createDirectory(directoryPath);// w ww .ja v a2 s . co m //start the import URL entry = ServerTestsActivator.getContext().getBundle().getEntry("testData/importTest/client.zip"); File source = new File(FileLocator.toFileURL(entry).getPath()); long length = source.length(); InputStream in = new BufferedInputStream(new FileInputStream(source)); PostMethodWebRequest request = new PostMethodWebRequest(getImportRequestPath(directoryPath), in, "application/zip"); request.setHeaderField("Content-Length", "" + length); request.setHeaderField("Content-Type", "application/zip"); setAuthentication(request); WebResponse postResponse = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, postResponse.getResponseCode()); String location = postResponse.getHeaderField("Location"); assertNotNull(location); String type = postResponse.getHeaderField("Content-Type"); assertNotNull(type); assertTrue(type.contains("text/html")); //assert the file has been unzipped in the workspace assertTrue( checkFileExists(directoryPath + "/org.eclipse.e4.webide/static/js/navigate-tree/navigate-tree.js")); }
From source file:org.restcomm.app.utillib.Reporters.WebReporter.WebReporter.java
protected static boolean verifyConnectionResponse(HttpURLConnection connection) throws LibException { int responseCode = 0; try {/*from www . ja v a2 s. c om*/ responseCode = connection.getResponseCode(); } catch (Exception e) { LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "verifyConnectionResponse", "getResponseCode", e); throw new LibException(e); } String contents = ""; if (responseCode < HttpURLConnection.HTTP_OK || responseCode >= 400) { try { contents = readString(connection); LoggerUtil.logToFile(LoggerUtil.Level.WTF, TAG, "verifyResponse", "response = " + contents); if (contents != null) { JSONObject json = new JSONObject(contents); String message = json.optString(JSON_ERROR_KEY, "response had no error message"); throw new LibException(message); } //MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "verifyResponse", "error in request " // + responseCode + " " + message); throw new LibException("response " + responseCode); } catch (Exception e) { LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "verifyResponse", contents, e); throw new LibException(e); } } else { //If the response is valid, evaluate if we need to parse the content switch (responseCode) { case HttpURLConnection.HTTP_OK: return true; case HttpURLConnection.HTTP_CREATED: return true; case HttpURLConnection.HTTP_NO_CONTENT: return false; default: return false; } } }
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. ja v a 2s .co m*/ }
From source file:com.baracuda.piepet.nexusrelease.nexus.StageClient.java
/** * Perform a staging action./*from ww w . ja v a 2s. c o m*/ * * @param action the action to perform. * @param stage the stage on which to perform the action. * @param description description to pass to the server for the action (e.g. the description of the stage * repo). * @throws StageException if an exception occurs whilst performing the action. */ protected void performStageAction(StageAction action, Stage stage, String description) throws StageException { log.debug("Performing action {} on stage {}", new Object[] { action, stage }); try { URL url = action.getURL(nexusURL, stage); String payload; if (action == StageAction.PROMOTE && isAsyncClose()) { payload = createPromoteRequestPayload(stage, description, Boolean.FALSE); } else { payload = createPromoteRequestPayload(stage, description, null); } byte[] payloadBytes = payload.getBytes("UTF-8"); int contentLen = payloadBytes.length; HttpURLConnection conn = (HttpURLConnection) url.openConnection(); addAuthHeader(conn); conn.setRequestProperty("Content-Length", Integer.toString(contentLen)); conn.setRequestProperty("Content-Type", "application/xml; charset=UTF-8"); conn.setRequestProperty("Accept", "application/xml"); conn.setRequestMethod("POST"); conn.setDoOutput(true); OutputStream out = conn.getOutputStream(); out.write(payloadBytes); out.flush(); int status = conn.getResponseCode(); log.debug("Server returned HTTP Status {} for {} stage request to {}.", new Object[] { Integer.toString(status), action.name(), stage }); if (status == HttpURLConnection.HTTP_CREATED) { drainOutput(conn); conn.disconnect(); } else { log.warn("Server returned HTTP Status {} for {} stage request to {}.", new Object[] { Integer.toString(status), action.name(), stage }); drainOutput(conn); conn.disconnect(); throw new IOException(String.format("server responded with status:%s", Integer.toString(status))); } } catch (IOException ex) { String message = String.format("Failed to perform %s action to nexus stage(%s)", action.name(), stage.toString()); throw new StageException(message, ex); } }
From source file:org.eclipse.orion.server.tests.servlets.git.GitStatusTest.java
@Test public void testFileLogFromStatus() throws Exception { 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()); // add new files to the local repository so they can be deleted and removed in the test later on // missing String missingFileName = "missing.txt"; request = getPutFileRequest(folder.getString(ProtocolConstants.KEY_LOCATION) + missingFileName, "you'll miss me"); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject missingTxt = getChild(folder, missingFileName); addFile(missingTxt);/* ww w . ja v a2 s.c o m*/ String removedFileName = "removed.txt"; request = getPutFileRequest(folder.getString(ProtocolConstants.KEY_LOCATION) + removedFileName, "I'll be removed"); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject removedTxt = getChild(folder, removedFileName); addFile(removedTxt); // git section for the folder JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT); String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD); request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "committing all changes", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // make the file missing deleteFile(missingTxt); // remove the file Repository repository = getRepositoryForContentLocation(cloneContentLocation); Git git = new Git(repository); RmCommand rm = git.rm(); rm.addFilepattern(removedFileName); rm.call(); // untracked file String untrackedFileName = "untracked.txt"; request = getPostFilesRequest(folder.getString(ProtocolConstants.KEY_LOCATION), getNewFileJSON(untrackedFileName).toString(), untrackedFileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); // added file String addedFileName = "added.txt"; request = getPostFilesRequest(folder.getString(ProtocolConstants.KEY_LOCATION), getNewFileJSON(addedFileName).toString(), addedFileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); JSONObject addedTxt = getChild(folder, addedFileName); addFile(addedTxt); // changed file JSONObject testTxt = getChild(folder, "test.txt"); modifyFile(testTxt, "change"); addFile(testTxt); // modified file modifyFile(testTxt, "second change, in working tree"); // get status assertStatus( new StatusResult().setAddedNames(addedFileName).setAddedLogLengths(0) .setChangedNames("test.txt").setChangedLogLengths(1).setMissingNames(missingFileName) .setMissingLogLengths(1).setModifiedNames("test.txt").setModifiedLogLengths(1) .setRemovedNames(removedFileName).setRemovedLogLengths(1) .setUntrackedNames(untrackedFileName).setUntrackedLogLengths(0), folder.getJSONObject(GitConstants.KEY_GIT).getString(GitConstants.KEY_STATUS)); } }
From source file:org.apache.hadoop.crypto.key.kms.KMSClientProvider.java
private KeyVersion createKeyInternal(String name, byte[] material, Options options) throws NoSuchAlgorithmException, IOException { checkNotEmpty(name, "name"); checkNotNull(options, "options"); Map<String, Object> jsonKey = new HashMap<String, Object>(); jsonKey.put(KMSRESTConstants.NAME_FIELD, name); jsonKey.put(KMSRESTConstants.CIPHER_FIELD, options.getCipher()); jsonKey.put(KMSRESTConstants.LENGTH_FIELD, options.getBitLength()); if (material != null) { jsonKey.put(KMSRESTConstants.MATERIAL_FIELD, Base64.encodeBase64String(material)); }//from ww w . j a v a2 s . c o m if (options.getDescription() != null) { jsonKey.put(KMSRESTConstants.DESCRIPTION_FIELD, options.getDescription()); } if (options.getAttributes() != null && !options.getAttributes().isEmpty()) { jsonKey.put(KMSRESTConstants.ATTRIBUTES_FIELD, options.getAttributes()); } URL url = createURL(KMSRESTConstants.KEYS_RESOURCE, null, null, null); HttpURLConnection conn = createConnection(url, HTTP_POST); conn.setRequestProperty(CONTENT_TYPE, APPLICATION_JSON_MIME); Map response = call(conn, jsonKey, HttpURLConnection.HTTP_CREATED, Map.class); return parseJSONKeyVersion(response); }
From source file:org.eclipse.orion.server.tests.servlets.xfer.TransferTest.java
@Test public void testImportFilesWithOverride() throws CoreException, IOException, SAXException { //create a directory to upload to String directoryPath = "sample/directory/path" + System.currentTimeMillis(); createDirectory(directoryPath);//from w w w .j av a2 s . c om //create a file that is to be overwritten String fileContents = "This is the file contents"; createFile(directoryPath + "/client.zip", fileContents); //start the import URL entry = ServerTestsActivator.getContext().getBundle().getEntry("testData/importTest/client.zip"); File source = new File(FileLocator.toFileURL(entry).getPath()); long length = source.length(); InputStream in = new BufferedInputStream(new FileInputStream(source)); PostMethodWebRequest request = new PostMethodWebRequest(getImportRequestPath(directoryPath), in, "application/zip"); request.setHeaderField("Content-Length", "" + length); request.setHeaderField("Content-Type", "application/octet-stream"); request.setHeaderField("Slug", "client.zip"); request.setHeaderField("X-Xfer-Options", "raw,overwrite-older"); setAuthentication(request); WebResponse postResponse = webConversation.getResponse(request); //assert the server accepts the override assertEquals(HttpURLConnection.HTTP_CREATED, postResponse.getResponseCode()); String location = postResponse.getHeaderField("Location"); assertNotNull(location); String type = postResponse.getHeaderField("Content-Type"); assertNotNull(type); //assert the file is still present in the workspace assertTrue(checkFileExists(directoryPath + "/client.zip")); //assert that imported file was overwritten assertFalse( checkContentEquals(createTempFile("expectedFile", fileContents), directoryPath + "/client.zip")); assertTrue(checkContentEquals(source, directoryPath + "/client.zip")); }