List of usage examples for java.net HttpURLConnection HTTP_NO_CONTENT
int HTTP_NO_CONTENT
To view the source code for java.net HttpURLConnection HTTP_NO_CONTENT.
Click Source Link
From source file:uk.ac.gate.cloud.client.RestClient.java
/** * Read a response or error message from the given connection, * handling any 303 redirect responses if <code>followRedirects</code> * is true.// ww w . ja v a2 s .c o m */ private <T> T readResponseOrError(HttpURLConnection connection, TypeReference<T> responseType, boolean followRedirects) throws RestClientException { InputStream stream = null; try { int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) { // successful response with no content storeHeaders(connection); return null; } String encoding = connection.getContentEncoding(); if ("gzip".equalsIgnoreCase(encoding)) { stream = new GZIPInputStream(connection.getInputStream()); } else { stream = connection.getInputStream(); } if (responseCode < 300 || responseCode >= 400 || !followRedirects) { try { return MAPPER.readValue(stream, responseType); } finally { storeHeaders(connection); stream.close(); } } else { // redirect - all redirects we care about from the GATE Cloud // APIs are 303. We have to follow them manually to make // authentication work properly. String location = connection.getHeaderField("Location"); // consume body IOUtils.copy(stream, new NullOutputStream()); IOUtils.closeQuietly(stream); // follow the redirect return get(location, responseType); } } catch (Exception e) { readError(connection); return null; // unreachable, as readError always throws exception } }
From source file:org.eclipse.orion.server.tests.servlets.site.HostingTest.java
@Test public void testRemoteProxyRequest() throws SAXException, IOException, JSONException, URISyntaxException { final String siteName = "My remote hosting site"; final String remoteRoot = "/remoteWeb", remotePrefPath = "/remotePref", remoteFilePath = "/remoteFile"; final JSONArray mappings = makeMappings(new String[][] { { remoteRoot, SERVER_LOCATION }, { remoteFilePath, SERVER_LOCATION + FILE_SERVLET_LOCATION }, { remotePrefPath, SERVER_LOCATION + "/prefs" } }); WebRequest createSiteReq = getCreateSiteRequest(siteName, workspaceId, mappings, null); WebResponse createSiteResp = webConversation.getResponse(createSiteReq); assertEquals(HttpURLConnection.HTTP_CREATED, createSiteResp.getResponseCode()); JSONObject siteObject = new JSONObject(createSiteResp.getText()); // Start the site String location = siteObject.getString(ProtocolConstants.HEADER_LOCATION); siteObject = startSite(location);/* w w w . java2 s . co m*/ final JSONObject hostingStatus = siteObject.getJSONObject(SiteConfigurationConstants.KEY_HOSTING_STATUS); final String hostedURL = hostingStatus.getString(SiteConfigurationConstants.KEY_HOSTING_STATUS_URL); // Access the remote URL through the site WebRequest getRemoteUrlReq = new GetMethodWebRequest(hostedURL + remoteRoot); WebResponse getRemoteUrlResp = webConversation.getResource(getRemoteUrlReq); final String lowerCaseContent = getRemoteUrlResp.getText().toLowerCase(); assertEquals("Looks like our orion jetty server", true, lowerCaseContent.contains("orion") || lowerCaseContent.contains("jetty")); // Test that we can invoke the Orion file API through the site, to create a file final String fileName = "fizz.txt"; final String fileContent = "Created through a site"; createFileOnServer(hostedURL + remoteFilePath + testProjectBaseLocation, fileName, fileContent); // Bugs 369813, 366098, 369811, 390732: ensure query parameters are passed through the site unmangled // For this we'll call the 'prefs' API which uses query parameters String prefKey = "foo[-]bar baz+quux"; String prefValue = "pref value"; String remotePrefUrl = hostedURL + remotePrefPath + "/user"; WebRequest putPrefReq = createSetPreferenceRequest(remotePrefUrl, prefKey, prefValue); setAuthentication(putPrefReq); WebResponse putPrefResp = webConversation.getResponse(putPrefReq); assertEquals(HttpURLConnection.HTTP_NO_CONTENT, putPrefResp.getResponseCode()); // Check pref value WebRequest getPrefReq = new GetMethodWebRequest(remotePrefUrl + "?key=" + URLEncoder.encode(prefKey)); setAuthentication(getPrefReq); WebResponse getPrefResp = webConversation.getResponse(getPrefReq); assertEquals(HttpURLConnection.HTTP_OK, getPrefResp.getResponseCode()); JSONObject prefObject = new JSONObject(getPrefResp.getText()); assertEquals("Pref obtained through site has correct value", prefObject.optString(prefKey), prefValue); // Stop the site stopSite(location); // Check that remote URL can't be accessed anymore WebRequest getRemoteUrl404Req = new GetMethodWebRequest(hostedURL + remoteRoot); WebResponse getRemoteUrl404Resp = webConversation.getResponse(getRemoteUrl404Req); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, getRemoteUrl404Resp.getResponseCode()); }
From source file:com.microsoft.azure.storage.table.TableOperation.java
private StorageRequest<CloudTableClient, TableOperation, TableResult> deleteImpl(final CloudTableClient client, final String tableName, final TableRequestOptions options, final OperationContext opContext) throws StorageException { final boolean isTableEntry = TableConstants.TABLES_SERVICE_TABLES_NAME.equals(tableName); final String tableIdentity = isTableEntry ? this.getEntity().writeEntity(opContext).get(TableConstants.TABLE_NAME).getValueAsString() : null;/*from w w w .j av a 2 s .c om*/ if (!isTableEntry) { Utility.assertNotNullOrEmpty(SR.ETAG_INVALID_FOR_DELETE, this.getEntity().getEtag()); Utility.assertNotNull(SR.PARTITIONKEY_MISSING_FOR_DELETE, this.getEntity().getPartitionKey()); Utility.assertNotNull(SR.ROWKEY_MISSING_FOR_DELETE, this.getEntity().getRowKey()); } final StorageRequest<CloudTableClient, TableOperation, TableResult> deleteRequest = new StorageRequest<CloudTableClient, TableOperation, TableResult>( options, client.getStorageUri()) { @Override public HttpURLConnection buildRequest(CloudTableClient client, TableOperation operation, OperationContext context) throws Exception { return TableRequest.delete(client.getTransformedEndPoint(context).getUri(this.getCurrentLocation()), options, null, context, tableName, generateRequestIdentity(isTableEntry, tableIdentity), operation.getEntity().getEtag()); } @Override public void signRequest(HttpURLConnection connection, CloudTableClient client, OperationContext context) throws Exception { StorageRequest.signTableRequest(connection, client, -1L, context); } @Override public TableResult preProcessResponse(TableOperation operation, CloudTableClient client, OperationContext context) throws Exception { if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) { throw TableServiceException.generateTableServiceException(this.getResult(), operation, this.getConnection().getErrorStream(), options.getTablePayloadFormat()); } return operation.parseResponse(null, this.getResult().getStatusCode(), null, opContext, options); } @Override public StorageExtendedErrorInformation parseErrorDetails() { return TableStorageErrorDeserializer.parseErrorDetails(this); } }; return deleteRequest; }
From source file:uk.ac.gate.cloud.client.RestClient.java
/** * Read a response or error message from the given connection, and * update the state of the given object. *//*from ww w . j a v a2s.c om*/ private void readResponseOrErrorForUpdate(HttpURLConnection connection, Object responseObject) throws RestClientException { InputStream stream = null; try { if (connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) { // successful response with no content return; } stream = connection.getInputStream(); try { MAPPER.readerForUpdating(responseObject).readValue(stream); } finally { stream.close(); } } catch (Exception e) { readError(connection); } }
From source file:org.openbaton.sdk.api.util.RestRequest.java
/** * Used to upload tar files to the NFVO for creating VNFPackages. * * @param f the tar file containing the VNFPackage * @return the created VNFPackage object * @throws SDKException//from www .j av a2 s . c o m */ public VNFPackage requestPostPackage(final File f) throws SDKException { CloseableHttpResponse response = null; HttpPost httpPost = null; try { try { checkToken(); } catch (IOException e) { log.error(e.getMessage(), e); throw new SDKException("Could not get token", e); } log.debug("Executing post on " + baseUrl); httpPost = new HttpPost(this.baseUrl); httpPost.setHeader(new BasicHeader("accept", "multipart/form-data")); httpPost.setHeader(new BasicHeader("project-id", projectId)); if (token != null) httpPost.setHeader(new BasicHeader("authorization", bearerToken.replaceAll("\"", ""))); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addBinaryBody("file", f); httpPost.setEntity(multipartEntityBuilder.build()); response = httpClient.execute(httpPost); } catch (ClientProtocolException e) { httpPost.releaseConnection(); throw new SDKException("Could not create VNFPackage from file " + f.getName(), e); } catch (IOException e) { httpPost.releaseConnection(); throw new SDKException("Could not create VNFPackage from file " + f.getName(), e); } // check response status checkStatus(response, HttpURLConnection.HTTP_OK); // return the response of the request String result = ""; if (response.getEntity() != null) try { result = EntityUtils.toString(response.getEntity()); } catch (IOException e) { e.printStackTrace(); } if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) { JsonParser jsonParser = new JsonParser(); JsonElement jsonElement = jsonParser.parse(result); result = mapper.toJson(jsonElement); log.debug("Uploaded the VNFPackage"); log.trace("received: " + result); log.trace("Casting it into: " + VNFPackage.class); httpPost.releaseConnection(); return mapper.fromJson(result, VNFPackage.class); } httpPost.releaseConnection(); return null; }
From source file:jetbrains.buildServer.vmgr.agent.Utils.java
public String executeAPI(String jSON, String apiUrl, String url, boolean requireAuth, String user, String password, String requestMethod, BuildProgressLogger logger, boolean dynamicUserId, String buildID, String workPlacePath) throws Exception { try {/* ww w .j a v a 2 s . c o m*/ boolean notInTestMode = true; if (logger == null) { notInTestMode = false; } String apiURL = url + "/rest" + apiUrl; if (notInTestMode) { logger.message("vManager vAPI - Trying to call vAPI '" + "/rest" + apiUrl + "'"); } String input = jSON; HttpURLConnection conn = getVAPIConnection(apiURL, requireAuth, user, password, requestMethod, dynamicUserId, buildID, workPlacePath, logger); if ("PUT".equals(requestMethod) || "POST".equals(requestMethod)) { 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() == 415) reason = "The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method. Check if you selected the right request method (GET/POST/DELETE/PUT)."; if (conn.getResponseCode() == 405) reason = "The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource. Check if you selected the right request method (GET/POST/DELETE/PUT)."; if (conn.getResponseCode() == 412) reason = "vAPI requires vManager 'Integration Server' license."; String errorMessage = "Failed : HTTP error code : " + conn.getResponseCode() + " (" + reason + ")"; if (notInTestMode) { logger.message(errorMessage); logger.message(conn.getResponseMessage()); } 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(); // Flush the output into workspace String fileOutput = workPlacePath + File.separator + buildID + File.separator + "vapi.output"; FileWriter writer = new FileWriter(fileOutput); writer.append(result.toString()); writer.flush(); writer.close(); String textOut = "API Call Success: Output was saved into: " + fileOutput; if (notInTestMode) { logger.message(textOut); } else { System.out.println(textOut); } return "success"; } catch (Exception e) { e.printStackTrace(); logger.error("Failed: Error: " + e.getMessage()); return e.getMessage(); } }
From source file:org.openrdf.http.server.ProtocolTest.java
private void putNamespace(String location, String namespace) throws Exception { // System.out.println("Put namespace to " + location); URL url = new URL(location); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); conn.setDoOutput(true);/* ww w. ja v a2 s.co m*/ InputStream dataStream = new ByteArrayInputStream(namespace.getBytes("UTF-8")); try { OutputStream connOut = conn.getOutputStream(); try { IOUtil.transfer(dataStream, connOut); } finally { connOut.close(); } } finally { dataStream.close(); } conn.connect(); int responseCode = conn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK && // 200 OK responseCode != HttpURLConnection.HTTP_NO_CONTENT) // 204 NO CONTENT { String response = "location " + location + " responded: " + conn.getResponseMessage() + " (" + responseCode + ")"; fail(response); } }
From source file:org.openrdf.http.server.ProtocolTest.java
private void deleteNamespace(String location) throws Exception { // System.out.println("Delete namespace at " + location); URL url = new URL(location); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("DELETE"); conn.setDoOutput(true);/* w w w.ja v a 2 s. co m*/ conn.connect(); int responseCode = conn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK && // 200 OK responseCode != HttpURLConnection.HTTP_NO_CONTENT) // 204 NO CONTENT { String response = "location " + location + " responded: " + conn.getResponseMessage() + " (" + responseCode + ")"; fail(response); } }
From source file:org.eclipse.hono.deviceregistry.FileBasedCredentialsService.java
@Override public void update(final String tenantId, final JsonObject newCredentials, final Handler<AsyncResult<CredentialsResult<JsonObject>>> resultHandler) { Objects.requireNonNull(tenantId); Objects.requireNonNull(newCredentials); Objects.requireNonNull(resultHandler); if (getConfig().isModificationEnabled()) { final String authId = newCredentials.getString(CredentialsConstants.FIELD_AUTH_ID); final String type = newCredentials.getString(CredentialsConstants.FIELD_TYPE); log.debug("updating credentials for device [tenant-id: {}, auth-id: {}, type: {}]", tenantId, authId, type);/* w w w . ja va 2 s.co m*/ final Map<String, JsonArray> credentialsForTenant = getCredentialsForTenant(tenantId); if (credentialsForTenant == null) { resultHandler .handle(Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_NOT_FOUND))); } else { final JsonArray credentialsForAuthId = credentialsForTenant.get(authId); if (credentialsForAuthId == null) { resultHandler.handle( Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_NOT_FOUND))); } else { // find credentials of given type boolean removed = false; final Iterator<Object> credentialsIterator = credentialsForAuthId.iterator(); while (credentialsIterator.hasNext()) { final JsonObject creds = (JsonObject) credentialsIterator.next(); if (creds.getString(CredentialsConstants.FIELD_TYPE).equals(type)) { credentialsIterator.remove(); removed = true; break; } } if (removed) { credentialsForAuthId.add(newCredentials); dirty = true; resultHandler.handle( Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_NO_CONTENT))); } else { resultHandler.handle( Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_NOT_FOUND))); } } } } else { resultHandler.handle(Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_FORBIDDEN))); } }
From source file:org.openbaton.sdk.api.util.RestRequest.java
/** * Executes a http delete with to a given id * * @param id the id path used for the api request *///from ww w.j a v a 2 s . co m public void requestDelete(final String id) throws SDKException { CloseableHttpResponse response = null; HttpDelete httpDelete = null; try { log.debug("baseUrl: " + baseUrl); log.debug("id: " + baseUrl + "/" + id); try { checkToken(); } catch (IOException e) { log.error(e.getMessage(), e); throw new SDKException("Could not get token", e); } // call the api here log.info("Executing delete on: " + this.baseUrl + "/" + id); httpDelete = new HttpDelete(this.baseUrl + "/" + id); httpDelete.setHeader(new BasicHeader("project-id", projectId)); if (token != null) httpDelete.setHeader(new BasicHeader("authorization", bearerToken.replaceAll("\"", ""))); response = httpClient.execute(httpDelete); // check response status checkStatus(response, HttpURLConnection.HTTP_NO_CONTENT); httpDelete.releaseConnection(); // return the response of the request } catch (IOException e) { // catch request exceptions here log.error(e.getMessage(), e); if (httpDelete != null) httpDelete.releaseConnection(); throw new SDKException("Could not http-delete", e); } catch (SDKException e) { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { token = null; if (httpDelete != null) httpDelete.releaseConnection(); requestDelete(id); return; } if (httpDelete != null) httpDelete.releaseConnection(); throw new SDKException("Could not http-delete or the api response was wrong", e); } }