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.orion.server.tests.metastore.RemoteMetaStoreTests.java

/**
 * Create a git clone in a project on the Orion server for the test user.
 * /*  w w w. j a  v a 2  s.c om*/
 * @throws URISyntaxException
 * @throws IOException
 * @throws JSONException
 * @throws SAXException 
 */
@Test
public void testCreateWGitClone() throws URISyntaxException, IOException, JSONException, SAXException {
    WebConversation webConversation = new WebConversation();
    assertEquals(HttpURLConnection.HTTP_NO_CONTENT,
            createGitClone(webConversation, getOrionTestName(), getOrionTestName(), "Project"));
}

From source file:org.eclipse.rdf4j.http.server.ProtocolTest.java

private void putFile(String location, String file) throws Exception {
    System.out.println("Put file to " + location);

    URL url = new URL(location);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("PUT");
    conn.setDoOutput(true);/*w w w.  j  a v a 2  s . c om*/

    RDFFormat dataFormat = Rio.getParserFormatForFileName(file).orElse(RDFFormat.RDFXML);
    conn.setRequestProperty("Content-Type", dataFormat.getDefaultMIMEType());

    InputStream dataStream = ProtocolTest.class.getResourceAsStream(file);
    try {
        OutputStream connOut = conn.getOutputStream();

        try {
            IOUtil.transfer(dataStream, connOut);
        } finally {
            connOut.close();
        }
    } finally {
        dataStream.close();
    }

    conn.connect();

    int responseCode = conn.getResponseCode();

    // HTTP 200 or 204
    if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_NO_CONTENT) {
        String response = "location " + location + " responded: " + conn.getResponseMessage() + " ("
                + responseCode + ")";
        fail(response);
    }
}

From source file:org.eclipse.hono.deviceregistry.FileBasedCredentialsService.java

@Override
public void removeAll(final String tenantId, final String deviceId,
        final Handler<AsyncResult<CredentialsResult<JsonObject>>> resultHandler) {

    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(deviceId);
    Objects.requireNonNull(resultHandler);

    if (getConfig().isModificationEnabled()) {

        final Map<String, JsonArray> credentialsForTenant = credentials.get(tenantId);
        if (credentialsForTenant == null) {
            resultHandler//from w  w  w .  ja  v  a2  s.co  m
                    .handle(Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_NOT_FOUND)));
        } else {

            boolean removedAnyElement = false;

            // delete based on type (no authId provided) - this might consume more time on large data sets and is thus
            // handled explicitly
            for (final JsonArray credentialsForAuthId : credentialsForTenant.values()) {
                if (removeCredentialsFromCredentialsArray(deviceId, CredentialsConstants.SPECIFIER_WILDCARD,
                        credentialsForAuthId)) {
                    removedAnyElement = true;
                }
            }

            // there might be empty credentials arrays left now, so remove them in a second run
            cleanupEmptyCredentialsArrays(credentialsForTenant);

            if (removedAnyElement) {
                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.eclipse.rdf4j.http.server.ProtocolTest.java

private void delete(String location) throws Exception {
    URL url = new URL(location);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("DELETE");

    conn.connect();/*  w w  w  .  ja v a2s .com*/

    int responseCode = conn.getResponseCode();

    // HTTP 200 or 204
    if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_NO_CONTENT) {
        String response = "location " + location + " responded: " + conn.getResponseMessage() + " ("
                + responseCode + ")";
        fail(response);
    }
}

From source file:es.uma.lcc.lockpic.MainActivity.java

protected Cookie getAuthCookie(String authToken) throws ClientProtocolException, IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    Cookie retCookie = null;/*from   w  w w. java 2s  .c  o m*/
    String cookieUrl = BASEURL + "/_ah/login?continue=" + URLEncoder.encode(BASEURL, "UTF-8") + "&auth="
            + URLEncoder.encode(authToken, "UTF-8");
    HttpGet httpget = new HttpGet(cookieUrl);
    HttpResponse response = httpClient.execute(httpget);
    if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK
            || response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_NO_CONTENT) {

        if (httpClient.getCookieStore().getCookies().size() > 0) {
            retCookie = httpClient.getCookieStore().getCookies().get(0);
        }
    }

    // store the cookie
    SharedPreferences settings = getSharedPreferences(SETTINGS_FILENAME, MODE_PRIVATE);
    Editor editor = settings.edit();
    editor.putString("cookie_value", retCookie.getValue());
    editor.putString("cookie_expiry",
            new SimpleDateFormat("yyyy.MM.dd-HH:mm.ss", Locale.US).format(retCookie.getExpiryDate()));
    editor.commit();

    return retCookie;
}

From source file:org.eclipse.orion.server.docker.server.DockerServer.java

private DockerResponse.StatusCode getDockerResponse(DockerResponse dockerResponse,
        HttpURLConnection httpURLConnection) {
    try {//from ww w . j  a  v a 2  s  .c o  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.restcomm.app.utillib.Reporters.WebReporter.WebReporter.java

protected static boolean verifyConnectionResponse(HttpURLConnection connection) throws LibException {
    int responseCode = 0;
    try {/*ww  w.j a  v  a 2s. c  o m*/
        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:net.sf.ehcache.constructs.web.filter.SimpleCachingHeadersPageCachingFilterTest.java

/**
 * Servlets and JSPs can send content even when the response is set to no content.
 * 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   www  . ja v a 2  s . c  om*/
 * <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:9090/empty_caching_filter/SC_NO_CONTENT.jsp
 */
@Test
public void testNoContentJSPGzipFilter() throws Exception {

    String url = buildUrl("/empty_caching_filter/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);
    String responseBody = httpMethod.getResponseBodyAsString();
    assertEquals(null, responseBody);
    assertNull(httpMethod.getResponseHeader("Content-Encoding"));
    assertNotNull(httpMethod.getResponseHeader("Last-Modified").getValue());
    checkNullOrZeroContentLength(httpMethod);

}

From source file:com.microsoft.azure.storage.table.TableOperation.java

private StorageRequest<CloudTableClient, TableOperation, TableResult> mergeImpl(final CloudTableClient client,
        final String tableName, final TableRequestOptions options, final OperationContext opContext)
        throws StorageException {
    Utility.assertNotNullOrEmpty(SR.ETAG_INVALID_FOR_MERGE, this.getEntity().getEtag());
    Utility.assertNotNull(SR.PARTITIONKEY_MISSING_FOR_MERGE, this.getEntity().getPartitionKey());
    Utility.assertNotNull(SR.ROWKEY_MISSING_FOR_MERGE, this.getEntity().getRowKey());

    ByteArrayOutputStream entityStream = new ByteArrayOutputStream();
    try {// w w w .j av  a2  s  .c  o  m
        TableEntitySerializer.writeSingleEntityToStream(entityStream, options, this.getEntity(), false,
                opContext);
        // We need to buffer once and use it for all retries instead of serializing the entity every single time. 
        // In the future, this could also be used to calculate transactional MD5 for table operations.
        final byte[] entityBytes = entityStream.toByteArray();

        final StorageRequest<CloudTableClient, TableOperation, TableResult> putRequest = new StorageRequest<CloudTableClient, TableOperation, TableResult>(
                options, client.getStorageUri()) {

            @Override
            public HttpURLConnection buildRequest(CloudTableClient client, TableOperation operation,
                    OperationContext context) throws Exception {
                this.setSendStream(new ByteArrayInputStream(entityBytes));
                this.setLength((long) entityBytes.length);
                return TableRequest.merge(
                        client.getTransformedEndPoint(opContext).getUri(this.getCurrentLocation()), options,
                        null, opContext, tableName, generateRequestIdentity(false, null),
                        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(),
                        this.getConnection().getHeaderField(TableConstants.HeaderConstants.ETAG), opContext,
                        options);
            }

            @Override
            public StorageExtendedErrorInformation parseErrorDetails() {
                return TableStorageErrorDeserializer.parseErrorDetails(this);
            }
        };

        return putRequest;
    } catch (IOException e) {
        // The request was not even made. There was an error while trying to read the entity. Just throw.
        StorageException translatedException = StorageException.translateClientException(e);
        throw translatedException;
    }
}

From source file:org.openbaton.sdk.api.util.RestRequest.java

/**
 * Executes a http put with to a given id, while serializing the object content as json and
 * returning the response//from   w  ww  .j ava 2s  .co  m
 *
 * @param id the id path used for the api request
 * @param object the object content to be serialized as json
 * @return a string containing the response content
 */
public Serializable requestPut(final String id, final Serializable object) throws SDKException {
    CloseableHttpResponse response = null;
    HttpPut httpPut = null;
    try {
        log.trace("Object is: " + object);
        String fileJSONNode = mapper.toJson(object);

        try {
            checkToken();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new SDKException("Could not get token", e);
        }

        // call the api here
        log.debug("Executing put on: " + this.baseUrl + "/" + id);
        httpPut = new HttpPut(this.baseUrl + "/" + id);
        httpPut.setHeader(new BasicHeader("accept", "application/json"));
        httpPut.setHeader(new BasicHeader("Content-Type", "application/json"));
        httpPut.setHeader(new BasicHeader("project-id", projectId));
        if (token != null)
            httpPut.setHeader(new BasicHeader("authorization", bearerToken.replaceAll("\"", "")));
        httpPut.setEntity(new StringEntity(fileJSONNode));

        response = httpClient.execute(httpPut);

        // check response status
        checkStatus(response, HttpURLConnection.HTTP_ACCEPTED);
        // return the response of the request
        String result = "";
        if (response.getEntity() != null)
            result = EntityUtils.toString(response.getEntity());

        if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) {
            response.close();
            httpPut.releaseConnection();
            JsonParser jsonParser = new JsonParser();
            JsonElement jsonElement = jsonParser.parse(result);
            result = mapper.toJson(jsonElement);
            log.trace("received: " + result);

            log.trace("Casting it into: " + object.getClass());
            return mapper.fromJson(result, object.getClass());
        }
        response.close();
        httpPut.releaseConnection();
        return null;
    } catch (IOException e) {
        // catch request exceptions here
        log.error(e.getMessage(), e);
        if (httpPut != null)
            httpPut.releaseConnection();
        throw new SDKException("Could not http-put or the api response was wrong or open the object properly",
                e);
    } catch (SDKException e) {
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            token = null;
            if (httpPut != null)
                httpPut.releaseConnection();
            return requestPut(id, object);
        } else {
            if (httpPut != null)
                httpPut.releaseConnection();
            throw new SDKException(
                    "Could not http-put or the api response was wrong or open the object properly", e);
        }
    } finally {
        if (httpPut != null)
            httpPut.releaseConnection();
    }
}