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:org.eclipse.hono.service.tenant.TenantHttpEndpoint.java

private void updateTenant(final RoutingContext ctx) {

    final String tenantId = getTenantIdFromContext(ctx);

    doTenantHttpRequest(ctx, tenantId, TenantConstants.TenantAction.update,
            status -> status == HttpURLConnection.HTTP_NO_CONTENT, null);
}

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

@Test
public void activate_rule_in_default_organization() {
    userSession.logIn().addPermission(OrganizationPermission.ADMINISTER_QUALITY_PROFILES, defaultOrganization);
    QualityProfileDto qualityProfile = dbTester.qualityProfiles().insert(defaultOrganization);
    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.orion.server.tests.prefs.PreferenceTest.java

@Test
public void testPutSingle() throws IOException, JSONException {
    List<String> locations = getTestPreferenceNodes();
    for (String location : locations) {
        //put a value that isn't currently defined
        WebRequest request = createSetPreferenceRequest(location, "Name", "Frodo");
        setAuthentication(request);/*  w w  w  .  jav a2 s .com*/
        WebResponse response = webConversation.getResource(request);
        assertEquals("1." + location, HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode());

        //doing a get should succeed
        request = new GetMethodWebRequest(location + "?key=Name");
        setAuthentication(request);
        response = webConversation.getResource(request);
        assertEquals("2." + location, HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject result = new JSONObject(response.getText());
        assertEquals("3." + location, "Frodo", result.optString("Name"));

        //setting a value to the empty string
        request = createSetPreferenceRequest(location, "Name", "");
        setAuthentication(request);
        response = webConversation.getResource(request);
        assertEquals("4." + location, HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode());
        request = new GetMethodWebRequest(location + "?key=Name");
        setAuthentication(request);
        response = webConversation.getResource(request);
        assertEquals("5." + location, HttpURLConnection.HTTP_OK, response.getResponseCode());
        result = new JSONObject(response.getText());
        assertEquals("6." + location, "", result.optString("Name"));

        //putting with forbidden URL characters in key and value
        request = createSetPreferenceRequest(location, "Na=me", "Fr&do");
        setAuthentication(request);
        response = webConversation.getResource(request);
        assertEquals("1." + location, HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode());

        //doing a get should succeed
        request = new GetMethodWebRequest(location + "?key=Na%3Dme");
        setAuthentication(request);
        response = webConversation.getResource(request);
        result = new JSONObject(response.getText());
        assertEquals("3." + location, "Fr&do", result.optString("Na=me"));
    }
}

From source file:org.eclipse.hono.service.tenant.TenantHttpEndpoint.java

private void removeTenant(final RoutingContext ctx) {

    final String tenantId = getTenantIdFromContext(ctx);

    doTenantHttpRequest(ctx, tenantId, TenantConstants.TenantAction.remove,
            status -> status == HttpURLConnection.HTTP_NO_CONTENT, null);
}

From source file:io.joynr.messaging.bounceproxy.monitoring.BounceProxyPerformanceReporter.java

/**
 * Sends an HTTP request to the monitoring service to report performance
 * measures of a bounce proxy instance.// ww  w.  jav a  2 s .  c  o m
 * 
 * @throws IOException
 */
private void sendPerformanceReportAsHttpRequest() throws IOException {

    final String url = bounceProxyControllerUrl.buildReportPerformanceUrl();
    logger.debug("Using monitoring service URL: {}", url);

    Map<String, Integer> performanceMap = bounceProxyPerformanceMonitor.getAsKeyValuePairs();
    String serializedMessage = objectMapper.writeValueAsString(performanceMap);

    HttpPost postReportPerformance = new HttpPost(url.trim());
    // using http apache constants here because JOYNr constants are in
    // libjoynr which should not be included here
    postReportPerformance.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    postReportPerformance.setEntity(new StringEntity(serializedMessage, "UTF-8"));

    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(postReportPerformance);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if (statusCode != HttpURLConnection.HTTP_NO_CONTENT) {
            logger.error("Failed to send performance report: {}", response);
            throw new JoynrHttpException(statusCode, "Failed to send performance report.");
        }

    } finally {
        if (response != null) {
            response.close();
        }
    }
}

From source file:io.confluent.kafkarest.tools.ConsumerPerformance.java

private <T> T request(String target, String method, byte[] entity, String entityLength,
        TypeReference<T> responseFormat) {
    HttpURLConnection connection = null;
    try {//from www .ja  v a  2s.  c om
        URL url = new URL(target);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(method);
        if (entity != null) {
            connection.setRequestProperty("Content-Type", Versions.KAFKA_MOST_SPECIFIC_DEFAULT);
            connection.setRequestProperty("Content-Length", entityLength);
        }
        connection.setDoInput(true);
        connection.setUseCaches(false);
        if (entity != null) {
            connection.setDoOutput(true);
            OutputStream os = connection.getOutputStream();
            os.write(entity);
            os.flush();
            os.close();
        }

        int responseStatus = connection.getResponseCode();
        if (responseStatus >= 400) {
            InputStream es = connection.getErrorStream();
            ErrorMessage errorMessage = jsonDeserializer.readValue(es, ErrorMessage.class);
            es.close();
            throw new RuntimeException(String.format("Unexpected HTTP error status %d for %s request to %s: %s",
                    responseStatus, method, target, errorMessage.getMessage()));
        }
        if (responseStatus != HttpURLConnection.HTTP_NO_CONTENT) {
            InputStream is = connection.getInputStream();
            T result = serializer.readValue(is, responseFormat);
            is.close();
            return result;
        }
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

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

@Test
public void deactivate_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("organization", organization.getKey()).setParam("rule_key", ruleKey.toString())
            .setParam("profile_key", qualityProfile.getKey());

    TestResponse response = request.execute();

    assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT);
    ArgumentCaptor<ActiveRuleKey> captor = ArgumentCaptor.forClass(ActiveRuleKey.class);
    Mockito.verify(ruleActivator).deactivateAndUpdateIndex(any(DbSession.class), captor.capture());
    assertThat(captor.getValue().ruleKey()).isEqualTo(ruleKey);
    assertThat(captor.getValue().qProfile()).isEqualTo(qualityProfile.getKey());
}

From source file:net.sf.ehcache.constructs.web.filter.GzipFilterTest.java

/**
 * JSPs and Servlets can send bodies when the response is SC_NOT_MODIFIED.
 * In this case there should not be a body but there is. Orion seems to kill the body
 * after is has left the Servlet filter chain. To avoid wget going into an inifinite
 * retry loop, and presumably some other web clients, the content length should be 0
 * and the body 0./*from  w ww .ja v  a2  s  .  co  m*/
 * <p/>
 * Manual test: wget -d --server-response --timestamping --header='If-modified-Since: Fri, 13 May 3006 23:54:18 GMT' --header='Accept-Encoding: gzip' http://localhost:9080/empty_gzip/SC_NO_CONTENT.jsp
 */
public void testNoContentJSPGzipFilter() throws Exception {

    String url = "http://localhost:9080/empty_gzip/SC_NO_CONTENT.jsp";
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod = new GetMethod(url);
    httpMethod.addRequestHeader("If-modified-Since", "Fri, 13 May 3006 23:54:18 GMT");
    httpMethod.addRequestHeader("Accept-Encoding", "gzip");
    int responseCode = httpClient.executeMethod(httpMethod);
    assertEquals(HttpURLConnection.HTTP_NO_CONTENT, responseCode);
    byte[] responseBody = httpMethod.getResponseBody();
    assertEquals(null, responseBody);
    assertNull(httpMethod.getResponseHeader("Content-Encoding"));
    assertNotNull(httpMethod.getResponseHeader("Last-Modified").getValue());
    checkNullOrZeroContentLength(httpMethod);
}

From source file:play.modules.resteasy.crud.RESTResource.java

/**
 * Returns a NO_CONTENT response
 */
protected Response noContent() {
    return status(HttpURLConnection.HTTP_NO_CONTENT);
}

From source file:de.unidue.inf.is.ezdl.dlservices.library.manager.referencesystems.bibsonomy.BibsonomyUtils.java

/** send DELETE REQUEST */
String sendDeleteRequest(String url) throws Exception {
    String sresponse;/*from  www.  ja v  a2  s .  c  o m*/

    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpDelete httpdelete = new HttpDelete(url);

        // add authorization header
        httpdelete.addHeader("Authorization", authHeader);

        HttpResponse response = httpclient.execute(httpdelete);

        // Check status code
        if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK
                || response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_NO_CONTENT) {
            if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_NO_CONTENT) {
                sresponse = "";
            } else {
                HttpEntity entity = response.getEntity();

                sresponse = readResponseStream(entity.getContent());
            }
            httpclient.getConnectionManager().shutdown();
        } else {
            HttpEntity entity = response.getEntity();
            sresponse = readResponseStream(entity.getContent());
            String httpcode = Integer.toString(response.getStatusLine().getStatusCode());
            httpclient.getConnectionManager().shutdown();
            throw new ReferenceSystemException(httpcode, "Bibsonomy Error", JSONUtils.parseError(sresponse));
        }
    } catch (UnknownHostException e) {
        throw new ReferenceSystemException("", "Unknow Host Exception", e.toString());
    }
    return sresponse;
}