Example usage for java.net HttpURLConnection HTTP_NO_CONTENT

List of usage examples for java.net HttpURLConnection HTTP_NO_CONTENT

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_NO_CONTENT.

Prototype

int HTTP_NO_CONTENT

To view the source code for java.net HttpURLConnection HTTP_NO_CONTENT.

Click Source Link

Document

HTTP Status-Code 204: No Content.

Usage

From source file:com.ontotext.s4.client.HttpClient.java

/**
* Make an API request and return the raw data from the response as an
* InputStream.//from ww w  .ja  v  a2s.  co  m
*
* @param target the URL to request (relative URLs will resolve against the {@link #getBaseUrl() base URL}).
* @param method the request method (GET, POST, DELETE, etc.)
* @param requestBody the object that should be serialized to JSON as the request body.
*          If <code>null</code> no request body is sent
* @param extraHeaders any additional HTTP headers, specified as an alternating sequence of header names and values
* @return for a successful response, the response stream, or <code>null</code> for a 201 response
* @throws HttpClientException if an exception occurs during processing,
*           or the server returns a 4xx or 5xx error response
*/
public InputStream requestForStream(String target, String method, Object requestBody, String... extraHeaders)
        throws HttpClientException {

    try {
        HttpURLConnection connection = sendRequest(target, method, requestBody, extraHeaders);
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            // successful response with no content
            return null;
        } else if (responseCode >= 400) {
            readError(connection);
            return null; // not reachable, readError always throws exception
        } else if (responseCode >= 300) {
            // redirect - all redirects we care about from the S4
            // APIs are 303. We have to follow them manually to make
            // authentication work properly.
            String location = connection.getHeaderField("Location");
            // consume body
            InputStream stream = connection.getInputStream();
            IOUtils.copy(stream, new NullOutputStream());
            IOUtils.closeQuietly(stream);
            // follow the redirect
            return requestForStream(location, method, requestBody, extraHeaders);
        } else {
            return connection.getInputStream();
        }
    } catch (IOException e) {
        throw new HttpClientException(e);
    }
}

From source file:io.confluent.kafka.schemaregistry.client.rest.RestService.java

/**
 * @param requestUrl        HTTP connection will be established with this url.
 * @param method            HTTP method ("GET", "POST", "PUT", etc.)
 * @param requestBodyData   Bytes to be sent in the request body.
 * @param requestProperties HTTP header properties.
 * @param responseFormat    Expected format of the response to the HTTP request.
 * @param <T>               The type of the deserialized response to the HTTP request.
 * @return The deserialized response to the HTTP request, or null if no data is expected.
 *///from  w ww.  ja  v a2 s . c o m
private <T> T sendHttpRequest(String requestUrl, String method, byte[] requestBodyData,
        Map<String, String> requestProperties, TypeReference<T> responseFormat)
        throws IOException, RestClientException {
    log.debug(String.format("Sending %s with input %s to %s", method,
            requestBodyData == null ? "null" : new String(requestBodyData), requestUrl));

    HttpURLConnection connection = null;
    try {
        URL url = new URL(requestUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(method);

        // connection.getResponseCode() implicitly calls getInputStream, so always set to true.
        // On the other hand, leaving this out breaks nothing.
        connection.setDoInput(true);

        for (Map.Entry<String, String> entry : requestProperties.entrySet()) {
            connection.setRequestProperty(entry.getKey(), entry.getValue());
        }

        connection.setUseCaches(false);

        if (requestBodyData != null) {
            connection.setDoOutput(true);
            OutputStream os = null;
            try {
                os = connection.getOutputStream();
                os.write(requestBodyData);
                os.flush();
            } catch (IOException e) {
                log.error("Failed to send HTTP request to endpoint: " + url, e);
                throw e;
            } finally {
                if (os != null)
                    os.close();
            }
        }

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream is = connection.getInputStream();
            T result = jsonDeserializer.readValue(is, responseFormat);
            is.close();
            return result;
        } else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            return null;
        } else {
            InputStream es = connection.getErrorStream();
            ErrorMessage errorMessage;
            try {
                errorMessage = jsonDeserializer.readValue(es, ErrorMessage.class);
            } catch (JsonProcessingException e) {
                errorMessage = new ErrorMessage(JSON_PARSE_ERROR_CODE, e.getMessage());
            }
            es.close();
            throw new RestClientException(errorMessage.getMessage(), responseCode, errorMessage.getErrorCode());
        }

    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:org.sonar.server.qualityprofile.ws.ActivateRuleActionTest.java

@Test
public void activate_rule_in_specific_organization() {
    userSession.logIn().addPermission(OrganizationPermission.ADMINISTER_QUALITY_PROFILES, organization);
    QualityProfileDto qualityProfile = dbTester.qualityProfiles().insert(organization);
    RuleKey ruleKey = RuleTesting.randomRuleKey();
    TestRequest request = wsActionTester.newRequest().setMethod("POST").setParam("rule_key", ruleKey.toString())
            .setParam("profile_key", qualityProfile.getKey()).setParam("severity", "BLOCKER")
            .setParam("params", "key1=v1;key2=v2").setParam("reset", "false");

    TestResponse response = request.execute();

    assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT);
    ArgumentCaptor<RuleActivation> captor = ArgumentCaptor.forClass(RuleActivation.class);
    Mockito.verify(ruleActivator).activate(any(DbSession.class), captor.capture(), eq(qualityProfile.getKey()));
    assertThat(captor.getValue().getRuleKey()).isEqualTo(ruleKey);
    assertThat(captor.getValue().getSeverity()).isEqualTo(Severity.BLOCKER);
    assertThat(captor.getValue().getParameters()).containsExactly(entry("key1", "v1"), entry("key2", "v2"));
    assertThat(captor.getValue().isReset()).isFalse();
}

From source file:org.eclipse.hono.service.credentials.CredentialsHttpEndpoint.java

private void removeCredentials(final RoutingContext ctx) {

    final String tenantId = getTenantParam(ctx);
    final String type = getTypeParam(ctx);
    final String authId = getAuthIdParam(ctx);

    logger.debug("removeCredentials [tenant: {}, type: {}, authId: {}]", tenantId, type, authId);

    final JsonObject payload = new JsonObject();
    payload.put(CredentialsConstants.FIELD_TYPE, type);
    payload.put(CredentialsConstants.FIELD_AUTH_ID, authId);

    final JsonObject requestMsg = EventBusMessage
            .forOperation(CredentialsConstants.CredentialsAction.remove.toString()).setTenant(tenantId)
            .setJsonPayload(payload).toJson();

    sendAction(ctx, requestMsg,/*w  w  w. java  2 s.co m*/
            getDefaultResponseHandler(ctx, status -> status == HttpURLConnection.HTTP_NO_CONTENT, null));
}

From source file:wherehows.common.kafka.schemaregistry.client.rest.RestService.java

/**
 * @param baseUrl           HTTP connection will be established with this url.
 * @param method            HTTP method ("GET", "POST", "PUT", etc.)
 * @param requestBodyData   Bytes to be sent in the request body.
 * @param requestProperties HTTP header properties.
 * @param responseFormat    Expected format of the response to the HTTP request.
 * @param <T>               The type of the deserialized response to the HTTP request.
 * @return The deserialized response to the HTTP request, or null if no data is expected.
 *//*from w  w w.  j  a v a2 s. c o  m*/
private <T> T sendHttpRequest(String baseUrl, String method, byte[] requestBodyData,
        Map<String, String> requestProperties, TypeReference<T> responseFormat)
        throws IOException, RestClientException {
    log.debug(String.format("Sending %s with input %s to %s", method,
            requestBodyData == null ? "null" : new String(requestBodyData), baseUrl));

    HttpURLConnection connection = null;
    try {
        URL url = new URL(baseUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(method);

        // connection.getResponseCode() implicitly calls getInputStream, so always set to true.
        // On the other hand, leaving this out breaks nothing.
        connection.setDoInput(true);

        for (Map.Entry<String, String> entry : requestProperties.entrySet()) {
            connection.setRequestProperty(entry.getKey(), entry.getValue());
        }

        connection.setUseCaches(false);

        if (requestBodyData != null) {
            connection.setDoOutput(true);
            OutputStream os = null;
            try {
                os = connection.getOutputStream();
                os.write(requestBodyData);
                os.flush();
            } catch (IOException e) {
                log.error("Failed to send HTTP request to endpoint: " + url, e);
                throw e;
            } finally {
                if (os != null)
                    os.close();
            }
        }

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream is = connection.getInputStream();
            T result = responseFormat != null ? jsonDeserializer.readValue(is, responseFormat)
                    : (T) IOUtils.toString(is);
            is.close();
            return result;
        } else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            return null;
        } else {
            InputStream es = connection.getErrorStream();
            ErrorMessage errorMessage;
            try {
                errorMessage = jsonDeserializer.readValue(es, ErrorMessage.class);
            } catch (JsonProcessingException e) {
                errorMessage = new ErrorMessage(JSON_PARSE_ERROR_CODE, e.getMessage());
            }
            es.close();
            throw new RestClientException(errorMessage.getMessage(), responseCode, errorMessage.getErrorCode());
        }

    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:org.eclipse.orion.server.tests.metastore.RemoteMetaStoreTests.java

/**
 * Create a git close on the Orion server for the test user. Also creates an operation in the metastore for the user.
 * /*from w w  w .j a v a  2  s  . co m*/
 * @param webConversation
 * @param login
 * @param password
 * @param project
 * @return
 * @throws URISyntaxException
 * @throws IOException
 * @throws JSONException
 * @throws SAXException 
 */
protected int createGitClone(WebConversation webConversation, String login, String password, String project)
        throws URISyntaxException, IOException, JSONException, SAXException {
    assertEquals(HttpURLConnection.HTTP_OK, login(webConversation, login, password));

    String name = "ahunter orion";
    JSONObject json = new JSONObject();
    json.put("GitUrl", "https://github.com/ahunter-orion/ahunter-orion.github.com.git");
    json.put("Location", "/workspace/" + getWorkspaceId(login));
    WebRequest request = new PostMethodWebRequest(getOrionServerURI("/gitapi/clone/"),
            IOUtilities.toInputStream(json.toString()), "application/json");
    request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_ACCEPTED, response.getResponseCode());

    JSONObject responseJsonObject = new JSONObject(response.getText());
    String location = responseJsonObject.getString("Location");
    JSONObject task = new JSONObject();
    task.put("expires", System.currentTimeMillis() + 86400000);
    task.put("Name", "Cloning repository " + name);
    json = new JSONObject();
    json.put(location, task);
    request = new PutMethodWebRequest(getOrionServerURI("/prefs/user/operations/"),
            IOUtilities.toInputStream(json.toString()), "application/json");
    request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode());

    System.out.println("Created Git Clone: " + name + " at Location: " + location);
    return response.getResponseCode();
}

From source file:org.eclipse.orion.server.tests.prefs.PreferenceTest.java

/**
 * Tests setting JSON objects as preference values
 * //from w  w  w . ja  va2  s. c o m
 * @throws IOException
 * @throws JSONException
 */
@Test
public void testPutJSON() throws IOException, JSONException {
    List<String> locations = getTestPreferenceNodes();
    for (String location : locations) {
        //PUT http://myserver:8080/prefs/user/cm/configurations/jslint.config
        //{"properties":{"options":"foo:true, bar:false"}}
        JSONObject value = new JSONObject();
        String options = "foo:true, bar:false";
        value.put("options", options);
        JSONObject prefs = new JSONObject();
        prefs.put("properties", value);
        String inString = prefs.toString();
        WebRequest request = new PutMethodWebRequest(location, IOUtilities.toInputStream(inString),
                "application/json");
        setAuthentication(request);
        WebResponse response = webConversation.getResource(request);
        assertEquals("1." + location, HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode());

        //GET http://myserver:8080/prefs/user/cm/configurations/jslint.config
        //should return: same value we put in
        request = new GetMethodWebRequest(location);
        setAuthentication(request);
        response = webConversation.getResource(request);
        assertEquals("2." + location, HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject resultObject = new JSONObject(response.getText());
        assertTrue("3." + location, resultObject.has("properties"));
        JSONObject resultValue = resultObject.getJSONObject("properties");
        Object resultOptions = resultValue.get("options");
        assertEquals("4." + location, options, resultOptions);

    }
    //
    //but...
    //
    //GET http://myserver:8080/prefs/user/cm/configurations/jslint.config
    //{
    //  "properties" : "{\"options\":\"foo:true, bar:false\"}"
    //}
}

From source file:org.apache.maven.wagon.providers.http.LightweightHttpWagon.java

protected void finishPutTransfer(Resource resource, InputStream input, OutputStream output)
        throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException {
    try {/*from   w  w w  .j av  a  2s  . co  m*/
        int statusCode = putConnection.getResponseCode();

        switch (statusCode) {
        // Success Codes
        case HttpURLConnection.HTTP_OK: // 200
        case HttpURLConnection.HTTP_CREATED: // 201
        case HttpURLConnection.HTTP_ACCEPTED: // 202
        case HttpURLConnection.HTTP_NO_CONTENT: // 204
            break;

        case HttpURLConnection.HTTP_FORBIDDEN:
            throw new AuthorizationException("Access denied to: " + buildUrl(resource.getName()));

        case HttpURLConnection.HTTP_NOT_FOUND:
            throw new ResourceDoesNotExistException(
                    "File: " + buildUrl(resource.getName()) + " does not exist");

            // add more entries here
        default:
            throw new TransferFailedException("Failed to transfer file: " + buildUrl(resource.getName())
                    + ". Return code is: " + statusCode);
        }
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_PUT);

        throw new TransferFailedException("Error transferring file: " + e.getMessage(), e);
    }
}

From source file:org.eclipse.hono.client.impl.RegistrationClientImpl.java

/**
 * Invokes the <em>Update Device Registration</em> operation of Hono's
 * <a href="https://www.eclipse.org/hono/api/Device-Registration-API">Device Registration API</a>
 * on the service represented by the <em>sender</em> and <em>receiver</em> links.
 *///  w  w w .  j a  v  a2s. c o  m
@Override
public final Future<Void> update(final String deviceId, final JsonObject data) {

    Objects.requireNonNull(deviceId);

    final Future<RegistrationResult> regResultTracker = Future.future();
    createAndSendRequest(RegistrationConstants.ACTION_UPDATE, createDeviceIdProperties(deviceId), data,
            regResultTracker.completer());
    return regResultTracker.map(response -> {
        switch (response.getStatus()) {
        case HttpURLConnection.HTTP_NO_CONTENT:
            return null;
        default:
            throw StatusCodeMapper.from(response);
        }
    });
}