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.GitResetTest.java
@Test @Ignore("see bug 339397") public void testResetAutocrlfTrue() throws Exception { // "git config core.autocrlf true" Git git = new Git(db); StoredConfig config = git.getRepository().getConfig(); config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, Boolean.TRUE);//from w w w .j av a 2s . co m config.save(); URI workspaceLocation = createWorkspace(getMethodName()); String projectName = getMethodName(); JSONObject project = createProjectOrLink(workspaceLocation, projectName, gitDir.toString()); String projectId = project.getString(ProtocolConstants.KEY_ID); JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT); String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX); String gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS); String gitCommitUri = gitSection.getString(GitConstants.KEY_COMMIT); // CRLF JSONObject testTxt = getChild(project, "test.txt"); modifyFile(testTxt, "f" + "\r\n" + "older"); addFile(testTxt); // commit WebRequest request = GitCommitTest.getPostGitCommitRequest(gitCommitUri, "added new line - crlf", false); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // assert there is nothing to commit assertStatus(StatusResult.CLEAN, gitStatusUri); // create new file String fileName = "new.txt"; // TODO: don't create URIs out of thin air request = getPostFilesRequest(projectId + "/", getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); JSONObject file = new JSONObject(response.getText()); String location = file.optString(ProtocolConstants.KEY_LOCATION, null); assertNotNull(location); // LF JSONObject newTxt = getChild(project, "new.txt"); modifyFile(newTxt, "i'm" + "\n" + "new"); // "git add ." request = GitAddTest.getPutGitIndexRequest(gitIndexUri /* stage all */); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // reset request = getPostGitIndexRequest(gitIndexUri /* reset all */, ResetType.MIXED); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); assertStatus(new StatusResult().setUntracked(1), gitStatusUri); }
From source file:mobi.jenkinsci.alm.assembla.client.AssemblaClient.java
private String postData(final String dataSuffix, final byte[] postData, final ContentType contentType) throws IOException { loginWhenNecessary(true);// w ww . j av a 2s. c om final HttpPost post = new HttpPost(getTargetUrl(dataSuffix)); setRequestHeaders(post, true); post.setEntity(new ByteArrayEntity(postData, contentType)); try { final HttpResponse response = httpClient.execute(post, httpContext); switch (response.getStatusLine().getStatusCode()) { case HttpURLConnection.HTTP_CREATED: final ByteArrayOutputStream bout = new ByteArrayOutputStream(); final InputStream in = response.getEntity().getContent(); IOUtils.copy(in, bout); return new String(bout.toByteArray()); default: throw new IOException("Cannot POST " + dataSuffix + " to Assembla: " + response.getStatusLine()); } } finally { post.releaseConnection(); } }
From source file:org.eclipse.mylyn.internal.gerrit.core.client.GerritHttpClient.java
public <T> T execute(Request<T> request, boolean authenticateIfNeeded, IProgressMonitor monitor) throws IOException, GerritException { String openIdProvider = getOpenIdProvider(); hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor); for (int attempt = 0; attempt < 2; attempt++) { if (authenticateIfNeeded) { // force authentication if (needsAuthentication()) { AuthenticationCredentials credentials = location.getCredentials(AuthenticationType.REPOSITORY); if (openIdProvider != null || credentials != null) { authenticate(openIdProvider, monitor); }//from w w w . j av a 2 s. c om } if (!obtainedXsrfKey) { updateXsrfKey(monitor); } } HttpMethodBase method = request.createMethod(); if (obtainedXsrfKey) { // required to authenticate against Gerrit 2.6+ REST endpoints // harmless in previous versions method.setRequestHeader(X_GERRIT_AUTHORITY, xsrfKey); } try { // Execute the method. WebUtil.execute(httpClient, hostConfiguration, method, monitor); } catch (IOException e) { WebUtil.releaseConnection(method, monitor); throw e; } catch (RuntimeException e) { WebUtil.releaseConnection(method, monitor); throw e; } int code = method.getStatusCode(); if (code == HttpURLConnection.HTTP_OK || code == HttpURLConnection.HTTP_ACCEPTED || code == HttpURLConnection.HTTP_CREATED) { try { return request.process(method); } finally { WebUtil.releaseConnection(method, monitor); } } else if (code == HttpURLConnection.HTTP_NO_CONTENT) { try { return null; } finally { WebUtil.releaseConnection(method, monitor); } } else { try { request.handleError(method); } finally { WebUtil.releaseConnection(method, monitor); } if (code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN) { // login or re-authenticate due to an expired session authenticate(openIdProvider, monitor); } else { throw new GerritHttpException(code); } } } throw new GerritLoginException(); }
From source file:org.apache.nifi.processors.livy.ExecuteSparkInteractive.java
private JSONObject readJSONObjectFromUrlPOST(String urlString, LivySessionService livySessionService, Map<String, String> headers, String payload) throws IOException, JSONException { HttpURLConnection connection = livySessionService.getConnection(urlString); connection.setRequestMethod("POST"); connection.setDoOutput(true);//from ww w .j av a 2 s. c om for (Map.Entry<String, String> entry : headers.entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); } OutputStream os = connection.getOutputStream(); os.write(payload.getBytes()); os.flush(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK && connection.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new RuntimeException("Failed : HTTP error code : " + connection.getResponseCode() + " : " + connection.getResponseMessage()); } InputStream content = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(content, StandardCharsets.UTF_8)); String jsonText = IOUtils.toString(rd); return new JSONObject(jsonText); }
From source file:jetbrains.buildServer.vmgr.agent.Utils.java
public String executeVSIFLaunch(String[] vsifs, String url, boolean requireAuth, String user, String password, BuildProgressLogger logger, boolean dynamicUserId, String buildID, String workPlacePath) throws Exception { boolean notInTestMode = true; if (logger == null) { notInTestMode = false;/*from w ww .ja v a 2 s .c o m*/ } String apiURL = url + "/rest/sessions/launch"; for (int i = 0; i < vsifs.length; i++) { if (notInTestMode) { logger.message("vManager vAPI - Trying to launch vsif file: '" + vsifs[i] + "'"); } String input = "{\"vsif\":\"" + vsifs[i] + "\"}"; HttpURLConnection conn = getVAPIConnection(apiURL, requireAuth, user, password, "POST", dynamicUserId, buildID, workPlacePath, logger); OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK && conn.getResponseCode() != HttpURLConnection.HTTP_NO_CONTENT && conn.getResponseCode() != HttpURLConnection.HTTP_ACCEPTED && conn.getResponseCode() != HttpURLConnection.HTTP_CREATED && conn.getResponseCode() != HttpURLConnection.HTTP_PARTIAL && conn.getResponseCode() != HttpURLConnection.HTTP_RESET) { String reason = ""; if (conn.getResponseCode() == 503) reason = "vAPI process failed to connect to remote vManager server."; if (conn.getResponseCode() == 401) reason = "Authentication Error"; if (conn.getResponseCode() == 412) reason = "vAPI requires vManager 'Integration Server' license."; if (conn.getResponseCode() == 406) reason = "VSIF file '" + vsifs[i] + "' was not found on file system, or is not accessed by the vAPI process."; String errorMessage = "Failed : HTTP error code : " + conn.getResponseCode() + " (" + reason + ")"; if (notInTestMode) { logger.message(errorMessage); logger.message(conn.getResponseMessage()); BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); StringBuilder result = new StringBuilder(); String output; while ((output = br.readLine()) != null) { result.append(output); } logger.message(result.toString()); } System.out.println(errorMessage); return errorMessage; } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); StringBuilder result = new StringBuilder(); String output; while ((output = br.readLine()) != null) { result.append(output); } conn.disconnect(); JSONObject tmp = JSONObject.fromObject(result.toString()); String textOut = "Session Launch Success: Session ID: " + tmp.getString("value"); if (notInTestMode) { logger.message(textOut); } else { System.out.println(textOut); } } return "success"; }
From source file:com.murrayc.galaxyzoo.app.provider.client.ZooniverseClient.java
public boolean uploadClassificationSync(final String authName, final String authApiKey, final List<NameValuePair> nameValuePairs) throws UploadException { throwIfNoNetwork();/*from w w w. j a va 2s.c om*/ final HttpURLConnection conn; try { conn = openConnection(getPostUploadUri()); } catch (final IOException e) { Log.error("uploadClassificationSync(): Could not open connection", e); throw new UploadException("Could not open connection.", e); } try { conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); } catch (final IOException e) { Log.error("uploadClassificationSync: exception during HTTP connection", e); throw new UploadException("exception during HTTP connection", e); } //Add the authentication details to the headers; //Be careful: The server still returns OK_CREATED even if we provide the wrong Authorization here. //There doesn't seem to be any way to know if it's correct other than checking your recent //classifications in your profile. //See https://github.com/zooniverse/Galaxy-Zoo/issues/184 if ((authName != null) && (authApiKey != null)) { conn.setRequestProperty("Authorization", generateAuthorizationHeader(authName, authApiKey)); } try { writeParamsToHttpPost(conn, nameValuePairs); } catch (final IOException e) { Log.error("uploadClassificationSync: writeParamsToHttpPost() failed", e); throw new UploadException("writeParamsToHttpPost() failed.", e); } //TODO: Is this necessary? conn.connect(); //Get the response: InputStream in = null; try { //Note: At least with okhttp.mockwebserver, getInputStream() will throw an IOException (file //not found) if the response code was an error, such as HTTP_UNAUTHORIZED. in = conn.getInputStream(); final int responseCode = conn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_CREATED) { Log.error("uploadClassificationSync: Did not receive the 201 Created status code: " + conn.getResponseCode()); return false; } return true; } catch (final IOException e) { Log.error("uploadClassificationSync: exception during HTTP connection", e); throw new UploadException("exception during HTTP connection", e); } finally { if (in != null) { try { in.close(); } catch (final IOException e) { Log.error("uploadClassificationSync: exception while closing in", e); } } } }
From source file:org.eclipse.orion.server.tests.servlets.git.GitConfigTest.java
@Test public void testGetSingleConfigEntry() 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); JSONObject configEntry = listConfigEntries(entryLocation); assertConfigOption(configEntry, ENTRY_KEY, ENTRY_VALUE); }/* w ww.j a v a 2s.c o m*/ }
From source file:fr.mael.jiwigo.dao.impl.ImageDaoImpl.java
public void addSimple(File file, Integer category, String title, Integer level) throws JiwigoException { HttpPost httpMethod = new HttpPost(((SessionManagerImpl) sessionManager).getUrl()); // nameValuePairs.add(new BasicNameValuePair("method", "pwg.images.addSimple")); // for (int i = 0; i < parametres.length; i += 2) { // nameValuePairs.add(new BasicNameValuePair(parametres[i], parametres[i + 1])); // }//from w w w . j a va2 s. c o m // method.setEntity(new UrlEncodedFormEntity(nameValuePairs)); if (file != null) { MultipartEntity multipartEntity = new MultipartEntity(); // String string = nameValuePairs.toString(); // dirty fix to remove the enclosing entity{} // String substring = string.substring(string.indexOf("{"), // string.lastIndexOf("}") + 1); try { multipartEntity.addPart("method", new StringBody(MethodsEnum.ADD_SIMPLE.getLabel())); multipartEntity.addPart("category", new StringBody(category.toString())); multipartEntity.addPart("name", new StringBody(title)); if (level != null) { multipartEntity.addPart("level", new StringBody(level.toString())); } } catch (UnsupportedEncodingException e) { throw new JiwigoException(e); } // StringBody contentBody = new StringBody(substring, // Charset.forName("UTF-8")); // multipartEntity.addPart("entity", contentBody); FileBody fileBody = new FileBody(file); multipartEntity.addPart("image", fileBody); ((HttpPost) httpMethod).setEntity(multipartEntity); } HttpResponse response; StringBuilder sb = new StringBuilder(); try { response = ((SessionManagerImpl) sessionManager).getClient().execute(httpMethod); int responseStatusCode = response.getStatusLine().getStatusCode(); switch (responseStatusCode) { case HttpURLConnection.HTTP_CREATED: break; case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_BAD_REQUEST: throw new JiwigoException("status code was : " + responseStatusCode); case HttpURLConnection.HTTP_FORBIDDEN: throw new JiwigoException("status code was : " + responseStatusCode); case HttpURLConnection.HTTP_NOT_FOUND: throw new JiwigoException("status code was : " + responseStatusCode); default: throw new JiwigoException("status code was : " + responseStatusCode); } HttpEntity resultEntity = response.getEntity(); BufferedHttpEntity responseEntity = new BufferedHttpEntity(resultEntity); BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent())); String line; try { while ((line = reader.readLine()) != null) { sb.append(line); sb.append("\n"); } } finally { reader.close(); } } catch (ClientProtocolException e) { throw new JiwigoException(e); } catch (IOException e) { throw new JiwigoException(e); } String stringResult = sb.toString(); }
From source file:org.jvnet.hudson.plugins.m2release.nexus.StageClient.java
/** * Perform a staging action./*from www. j a v a 2s .co 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. */ private 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 = createPromoteRequestPayload(stage, description); 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:fi.cosky.sdk.API.java
private <T extends BaseData> T sendRequestWithAddedHeaders(Verb verb, String url, Class<T> tClass, Object object, HashMap<String, String> headers) throws IOException { URL serverAddress;/*from w w w. ja v a 2 s . c om*/ HttpURLConnection connection; BufferedReader br; String result = ""; try { serverAddress = new URL(url); connection = (HttpURLConnection) serverAddress.openConnection(); connection.setInstanceFollowRedirects(false); boolean doOutput = doOutput(verb); connection.setDoOutput(doOutput); connection.setRequestMethod(method(verb)); connection.setRequestProperty("Authorization", headers.get("authorization")); connection.addRequestProperty("Accept", "application/json"); if (doOutput) { connection.addRequestProperty("Content-Length", "0"); OutputStreamWriter os = new OutputStreamWriter(connection.getOutputStream()); os.write(""); os.flush(); os.close(); } connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER || connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) { Link location = parseLocationLinkFromString(connection.getHeaderField("Location")); Link l = new Link("self", "/tokens", "GET", "", true); ArrayList<Link> links = new ArrayList<Link>(); links.add(l); links.add(location); ResponseData data = new ResponseData(); data.setLocation(location); data.setLinks(links); return (T) data; } if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { System.out.println("Authentication expired: " + connection.getResponseMessage()); if (retry && this.tokenData != null) { retry = false; this.tokenData = null; if (authenticate()) { System.out.println( "Reauthentication success, will continue with " + verb + " request on " + url); return sendRequestWithAddedHeaders(verb, url, tClass, object, headers); } } else throw new IOException( "Tried to reauthenticate but failed, please check the credentials and status of NFleet-API"); } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) { System.out.println("ErrorCode: " + connection.getResponseCode() + " " + connection.getResponseMessage() + " " + url + ", verb: " + verb); String errorString = readErrorStreamAndCloseConnection(connection); throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class); } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) { if (retry) { System.out.println("Server responded with internal server error, trying again in " + RETRY_WAIT_TIME + " msec."); try { retry = false; Thread.sleep(RETRY_WAIT_TIME); return sendRequestWithAddedHeaders(verb, url, tClass, object, headers); } catch (InterruptedException e) { } } else { System.out.println("Server responded with internal server error, please contact dev@nfleet.fi"); } String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } result = readDataFromConnection(connection); } catch (MalformedURLException e) { throw e; } catch (ProtocolException e) { throw e; } catch (UnsupportedEncodingException e) { throw e; } catch (IOException e) { throw e; } return (T) gson.fromJson(result, tClass); }