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.openrdf.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  av  a2 s . c  o  m

    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();

    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 delete(String location) throws Exception {
    URL url = new URL(location);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("DELETE");

    conn.connect();/*ww  w  . j  av a 2s .  c o m*/

    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.rdf4j.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);/*from  w ww.j ava2 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();

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

/**
 * Create a plugins preference on the Orion server for the test user.
 * //from   www .  j  av a  2 s . c o m
 * @throws URISyntaxException
 * @throws IOException
 * @throws JSONException
 * @throws SAXException 
 */
@Test
public void testCreateTPluginsPref() throws URISyntaxException, IOException, JSONException, SAXException {
    WebConversation webConversation = new WebConversation();
    assertEquals(HttpURLConnection.HTTP_NO_CONTENT,
            createPluginsPref(webConversation, getOrionTestName(), getOrionTestName()));
}

From source file:org.eclipse.rdf4j.http.client.RDF4JProtocolSession.java

public synchronized void rollbackTransaction() throws RDF4JException, IOException, UnauthorizedException {
    checkRepositoryURL();//from   ww w.j  a v  a2  s . co m

    if (transactionURL == null) {
        throw new IllegalStateException("Transaction URL has not been set");
    }

    String requestURL = transactionURL;
    HttpDelete method = new HttpDelete(requestURL);

    try {
        final HttpResponse response = execute(method);
        try {
            int code = response.getStatusLine().getStatusCode();
            if (code == HttpURLConnection.HTTP_NO_CONTENT) {
                // we're done.
                transactionURL = null;
            } else {
                throw new RepositoryException("unable to rollback transaction. HTTP error code " + code);
            }
        } finally {
            EntityUtils.consumeQuietly(response.getEntity());
        }
    } finally {
        method.reset();
    }
}

From source file:CloudManagerAPI.java

private boolean isResponseSuccess(HttpURLConnection connection) throws IOException {
    int statusCode = connection.getResponseCode();

    return statusCode == HttpsURLConnection.HTTP_OK || statusCode == HttpsURLConnection.HTTP_ACCEPTED
            || statusCode == HttpURLConnection.HTTP_NO_CONTENT;
}

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

@Override
public void remove(final String tenantId, final String type, final String authId,
        final Handler<AsyncResult<CredentialsResult<JsonObject>>> resultHandler) {

    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(type);
    Objects.requireNonNull(authId);
    Objects.requireNonNull(resultHandler);

    if (getConfig().isModificationEnabled()) {
        final Map<String, JsonArray> credentialsForTenant = credentials.get(tenantId);
        if (credentialsForTenant == null) {
            resultHandler//from  w  w w .  j a  va2 s.c o  m
                    .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 if (removeCredentialsFromCredentialsArray(null, type, credentialsForAuthId)) {
                if (credentialsForAuthId.isEmpty()) {
                    credentialsForTenant.remove(authId); // do not leave empty array as value
                }
                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 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);/*  www .ja va  2 s.c om*/

    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:com.microsoft.azure.storage.table.TableOperation.java

private StorageRequest<CloudTableClient, TableOperation, TableResult> insertImpl(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;//w  ww .j a v a  2s  .c  o m

    // Inserts need row key and partition key
    if (!isTableEntry) {
        Utility.assertNotNull(SR.PARTITIONKEY_MISSING_FOR_INSERT, this.getEntity().getPartitionKey());
        Utility.assertNotNull(SR.ROWKEY_MISSING_FOR_INSERT, this.getEntity().getRowKey());
    }

    ByteArrayOutputStream entityStream = new ByteArrayOutputStream();
    try {
        TableEntitySerializer.writeSingleEntityToStream(entityStream, options, this.entity, isTableEntry,
                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.insert(
                        client.getTransformedEndPoint(opContext).getUri(this.getCurrentLocation()), options,
                        null, opContext, tableName, generateRequestIdentity(isTableEntry, tableIdentity),
                        operation.opType != TableOperationType.INSERT ? operation.getEntity().getEtag() : null,
                        operation.getEchoContent(), operation.opType.getUpdateType());
            }

            @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 (operation.opType == TableOperationType.INSERT) {
                    if (operation.getEchoContent()
                            && this.getResult().getStatusCode() == HttpURLConnection.HTTP_CREATED) {
                        // Insert should receive created if echo content is on
                        return new TableResult();
                    } else if (!operation.getEchoContent()
                            && this.getResult().getStatusCode() == HttpURLConnection.HTTP_NO_CONTENT) {
                        // Insert should receive no content if echo content is off
                        return operation.parseResponse(null, this.getResult().getStatusCode(),
                                this.getConnection().getHeaderField(TableConstants.HeaderConstants.ETAG),
                                opContext, options);
                    }
                } else if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NO_CONTENT) {
                    // InsertOrMerge and InsertOrReplace should always receive no content
                    return operation.parseResponse(null, this.getResult().getStatusCode(),
                            this.getConnection().getHeaderField(TableConstants.HeaderConstants.ETAG), opContext,
                            options);
                }

                throw TableServiceException.generateTableServiceException(this.getResult(), operation,
                        this.getConnection().getErrorStream(), options.getTablePayloadFormat());
            }

            @Override
            public TableResult postProcessResponse(HttpURLConnection connection, TableOperation operation,
                    CloudTableClient client, OperationContext context, TableResult result) throws Exception {
                if (operation.opType == TableOperationType.INSERT && operation.getEchoContent()) {
                    result = operation.parseResponse(this.getConnection().getInputStream(),
                            this.getResult().getStatusCode(),
                            this.getConnection().getHeaderField(TableConstants.HeaderConstants.ETAG), opContext,
                            options);
                }
                return result;
            }

            @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:net.sf.ehcache.constructs.web.filter.CachingFilterTest.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  ww w . ja  va 2s .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:9080/empty_caching_filter/SC_NO_CONTENT.jsp
 */
public void testNoContentJSPGzipFilter() throws Exception {

    String url = "http://localhost:9080/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);

}