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.sfs.SfsSingletonServer.java

protected Router createRouter(VertxContext<Server> vertxContext) {
    Vertx vertx = vertxContext.vertx();//from  w  ww .j a  v a  2 s.c o  m

    Router router = Router.router(vertx);

    router.get("/admin/001/healthcheck").handler(
            httpServerRequest -> httpServerRequest.response().setStatusCode(HttpURLConnection.HTTP_OK).end());

    // cluster stats
    router.get("/stats").handler(new SfsRequestHandler(vertxContext, new GetClusterStats()));

    // object admin method
    router.get("/metadata_accounts/*").handler(new SfsRequestHandler(vertxContext, new GetAccountMeta()));
    router.get("/metadata_containers/*").handler(new SfsRequestHandler(vertxContext, new GetContainerMeta()));
    router.get("/metadata_objects/*").handler(new SfsRequestHandler(vertxContext, new GetObjectMeta()));

    //re encrypt
    router.post("/reencrypt_masterkeys")
            .handler(new SfsRequestHandler(vertxContext, new ReEncryptMasterKeys()));
    router.post("/reencrypt_containerkeys")
            .handler(new SfsRequestHandler(vertxContext, new ReEncryptContainerKeys()));

    //repair
    router.post("/verify_repair_masterkeys")
            .handler(new SfsRequestHandler(vertxContext, new VerifyRepairMasterKeys()));
    router.postWithRegex("\\/verify_repair_objects\\/[^\\/]+\\/[^\\/]+\\/.+")
            .handler(new SfsRequestHandler(vertxContext, new VerifyRepairObjectExecute()));
    router.deleteWithRegex("\\/verify_repair_objects\\/[^\\/]+\\/[^\\/]+\\/.+")
            .handler(new SfsRequestHandler(vertxContext, new VerifyRepairObjectStop()));
    router.getWithRegex("\\/verify_repair_objects\\/[^\\/]+\\/[^\\/]+\\/.+")
            .handler(new SfsRequestHandler(vertxContext, new VerifyRepairObjectStop()));

    router.postWithRegex("\\/verify_repair_containers\\/[^\\/]+\\/[^\\/]+")
            .handler(new SfsRequestHandler(vertxContext, new VerifyRepairContainerExecute()));
    router.deleteWithRegex("\\/verify_repair_containers\\/[^\\/]+\\/[^\\/]+")
            .handler(new SfsRequestHandler(vertxContext, new VerifyRepairContainerStop()));
    router.getWithRegex("\\/verify_repair_containers\\/[^\\/]+\\/[^\\/]+")
            .handler(new SfsRequestHandler(vertxContext, new VerifyRepairContainerWait()));

    router.post("/verify_repair_containers")
            .handler(new SfsRequestHandler(vertxContext, new VerifyRepairAllContainersExecute()));
    router.delete("/verify_repair_containers")
            .handler(new SfsRequestHandler(vertxContext, new VerifyRepairAllContainersStop()));
    router.get("/verify_repair_containers")
            .handler(new SfsRequestHandler(vertxContext, new VerifyRepairAllContainersWait()));

    // container admin method
    router.post("/export_container/*").handler(new SfsRequestHandler(vertxContext, new ExportContainer()));
    router.post("/import_container/*").handler(new SfsRequestHandler(vertxContext, new ImportContainer()));

    // openstack keystone
    router.post("/v2.0/tokens").handler(new SfsRequestHandler(vertxContext, new PostTokens()));

    // openstack swift object methods
    router.getWithRegex("\\/openstackswift001\\/[^\\/]+\\/[^\\/]+\\/.+")
            .handler(new SfsRequestHandler(vertxContext, new GetObject()));
    router.headWithRegex("\\/openstackswift001\\/[^\\/]+\\/[^\\/]+\\/.+")
            .handler(new SfsRequestHandler(vertxContext, new HeadObject()));
    router.deleteWithRegex("\\/openstackswift001\\/[^\\/]+\\/[^\\/]+\\/.+")
            .handler(new SfsRequestHandler(vertxContext, new DeleteObject()));
    router.putWithRegex("\\/openstackswift001\\/[^\\/]+\\/[^\\/]+\\/.+")
            .handler(new SfsRequestHandler(vertxContext, new PutObject()));
    router.postWithRegex("\\/openstackswift001\\/[^\\/]+\\/[^\\/]+\\/.+")
            .handler(new SfsRequestHandler(vertxContext, new PostObject()));

    // openstack swift container methods
    router.getWithRegex("\\/openstackswift001\\/[^\\/]+\\/[^\\/]+")
            .handler(new SfsRequestHandler(vertxContext, new GetContainer()));
    router.headWithRegex("\\/openstackswift001\\/[^\\/]+\\/[^\\/]+")
            .handler(new SfsRequestHandler(vertxContext, new HeadContainer()));
    router.putWithRegex("\\/openstackswift001\\/[^\\/]+\\/[^\\/]+")
            .handler(new SfsRequestHandler(vertxContext, new PutContainer()));
    router.postWithRegex("\\/openstackswift001\\/[^\\/]+\\/[^\\/]+")
            .handler(new SfsRequestHandler(vertxContext, new PostContainer()));
    router.deleteWithRegex("\\/openstackswift001\\/[^\\/]+\\/[^\\/]+")
            .handler(new SfsRequestHandler(vertxContext, new DeleteOrDestroyContainer()));

    // openstack swift account methods
    router.getWithRegex("\\/openstackswift001\\/[^\\/]+")
            .handler(new SfsRequestHandler(vertxContext, new GetAccount()));
    router.headWithRegex("\\/openstackswift001\\/[^\\/]+")
            .handler(new SfsRequestHandler(vertxContext, new HeadAccount()));
    router.postWithRegex("\\/openstackswift001\\/[^\\/]+")
            .handler(new SfsRequestHandler(vertxContext, new PostAccount()));
    router.deleteWithRegex("\\/openstackswift001\\/[^\\/]+")
            .handler(new SfsRequestHandler(vertxContext, new DeleteAccount()));

    // node specific calls below. ie. A call to any node that requires a master will get routed to the master node

    // commands that must run on the master node
    router.post("/_internal_node_master_execute_job")
            .handler(new SfsRequestHandler(vertxContext, new MasterNodeExecuteJob()));
    router.post("/_internal_node_master_wait_for_job")
            .handler(new SfsRequestHandler(vertxContext, new MasterNodeWaitForJob()));
    router.post("/_internal_node_master_stop_job")
            .handler(new SfsRequestHandler(vertxContext, new MasterNodeStopJob()));

    // node stats methods
    router.get("/_internal_node/stats").handler(new SfsRequestHandler(vertxContext, new GetNodeStats()));

    // data node blob store methods
    router.delete("/_internal_node_data/blob").handler(new SfsRequestHandler(vertxContext, new DeleteBlob()));
    router.get("/_internal_node_data/blob").handler(new SfsRequestHandler(vertxContext, new GetBlob()));
    router.put("/_internal_node_data/blob").handler(new SfsRequestHandler(vertxContext, new PutBlob()));
    router.get("/_internal_node_data/blob/canwrite")
            .handler(new SfsRequestHandler(vertxContext, new CanWriteVolume()));
    router.get("/_internal_node_data/blob/canread")
            .handler(new SfsRequestHandler(vertxContext, new CanReadVolume()));
    router.put("/_internal_node_data/blob/ack").handler(new SfsRequestHandler(vertxContext, new AckBlob()));
    router.get("/_internal_node_data/blob/checksum")
            .handler(new SfsRequestHandler(vertxContext, new ChecksumBlob()));

    if (testMode) {
        router.post("/admin/001/refresh_index")
                .handler(new SfsRequestHandler(vertxContext, new RefreshIndex()));
        router.get("/admin/001/is_online")
                .handler(new SfsRequestHandler(vertxContext, sfsRequest -> Defer.aVoid()
                        .flatMap(aVoid1 -> sfsRequest.vertxContext().verticle().getClusterInfo().isOnline())
                        .doOnNext(isOnline -> {
                            if (Boolean.TRUE.equals(isOnline)) {
                                sfsRequest.response().setStatusCode(HttpURLConnection.HTTP_OK);
                            } else {
                                sfsRequest.response().setStatusCode(HttpURLConnection.HTTP_NO_CONTENT);
                            }
                        }).subscribe(new Terminus<Boolean>(sfsRequest) {
                            @Override
                            public void onNext(Boolean aBoolean) {

                            }
                        })));
    }

    return router;
}

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

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

    ByteArrayOutputStream entityStream = new ByteArrayOutputStream();
    try {//from   ww  w.j  av a 2  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.update(
                        client.getTransformedEndPoint(context).getUri(this.getCurrentLocation()), options, null,
                        context, 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.marketplace.core.VNFPackageManagement.java

private void deleteOnFitEagle(VNFPackageMetadata vnfPackageMetadata) {
    RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(10000).setConnectTimeout(60000)
            .build();/*ww w . j  a va  2  s  .co  m*/
    CloseableHttpResponse response = null;
    HttpDelete httpDelete = null;
    String url = "https://" + fitEagleIp + ":" + fitEaglePort + "/OpenBaton/upload/v2/"
            + vnfPackageMetadata.getRequirements().get("fiteagle-id");
    try {
        log.debug("Executing DELETE on " + url);
        httpDelete = new HttpDelete(url);
        //      httpPost.setHeader(new BasicHeader("Accept", "multipart/form-data"));
        //      httpPost.setHeader(new BasicHeader("Content-type", "multipart/form-data"));
        httpDelete.setHeader(new BasicHeader("username", userManagement.getCurrentUser()));
        httpDelete.setHeader(new BasicHeader("filename", vnfPackageMetadata.getVnfPackageFileName()));
        httpDelete.setHeader(new BasicHeader("name", vnfPackageMetadata.getName()));
        httpDelete.setHeader(
                new BasicHeader("package-id", vnfPackageMetadata.getRequirements().get("fiteagle-id")));

        CloseableHttpClient client = getHttpClientForSsl(config);

        response = client.execute(httpDelete);
    } catch (ClientProtocolException e) {
        httpDelete.releaseConnection();
        e.printStackTrace();
        log.error("Not able to delete VNFPackage");
        return;
    } catch (IOException e) {
        httpDelete.releaseConnection();
        e.printStackTrace();
        log.error("Not able to delete VNFPackage");
        return;
    }

    // check response status
    String result = "";
    if (response != null && response.getEntity() != null) {
        try {
            result = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
            httpDelete.releaseConnection();
            return;
        }
    }

    if (response != null && response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) {
        log.debug("Deleted the VNFPackage");
        log.debug("received: " + result);
    }
    httpDelete.releaseConnection();
}

From source file:org.openrdf.http.client.HTTPClient.java

public void deleteRepository(String repositoryID) throws HttpException, IOException, RepositoryException {

    HttpMethod method = new DeleteMethod(Protocol.getRepositoryLocation(serverURL, repositoryID));
    setDoAuthentication(method);//from   ww  w  .j a  va  2s.  c o m

    try {
        int httpCode = httpClient.executeMethod(method);

        if (httpCode == HttpURLConnection.HTTP_NO_CONTENT) {
            return;
        } else if (httpCode == HttpURLConnection.HTTP_FORBIDDEN) {
            ErrorInfo errInfo = getErrorInfo(method);
            throw new UnauthorizedException(errInfo.getErrorMessage());
        } else {
            ErrorInfo errInfo = getErrorInfo(method);
            throw new RepositoryException("Failed to delete repository: " + errInfo + " (" + httpCode + ")");
        }
    } finally {
        releaseConnection(method);
    }
}

From source file:org.openecomp.sdnc.sli.aai.AAIService.java

@Override
public boolean deleteVServerData(String tenant_id, String vserver_id, String cloudOwner, String cloudRegionId,
        String resourceVersion) throws AAIServiceException {
    boolean response = false;
    InputStream inputStream = null;

    try {/*from  w w  w .j  a v a 2  s. c  om*/
        String local_network_complexes_path = network_vserver_path.replace("{tenant-id}",
                encodeQuery(tenant_id));
        local_network_complexes_path = local_network_complexes_path.replace("{vserver-id}",
                encodeQuery(vserver_id));
        local_network_complexes_path = local_network_complexes_path.replace("{cloud-owner}",
                encodeQuery(cloudOwner));
        local_network_complexes_path = local_network_complexes_path.replace("{cloud-region-id}",
                encodeQuery(cloudRegionId));

        String request_url = target_uri + local_network_complexes_path;
        if (resourceVersion != null) {
            request_url = request_url + "?resource-version=" + resourceVersion;
        }
        URL http_req_url = new URL(request_url);

        HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.DELETE);

        LOGwriteFirstTrace(HttpMethod.DELETE, http_req_url.toString());
        LOGwriteDateTrace("tenant_id", tenant_id);
        LOGwriteDateTrace("vserver_id", vserver_id);
        LOGwriteDateTrace("cloud-owner", cloudOwner);
        LOGwriteDateTrace("cloud-region-id", cloudRegionId);

        // Check for errors
        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            inputStream = con.getInputStream();
        } else {
            inputStream = con.getErrorStream();
        }

        // Process the response
        LOG.debug("HttpURLConnection result:" + responseCode);
        if (inputStream == null)
            inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;

        ObjectMapper mapper = getObjectMapper();

        if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            StringBuilder stringBuilder = new StringBuilder();

            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
            response = true;
        } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
            LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
            response = false;
        } else {
            ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
            LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
            throw new AAIServiceException(responseCode, errorresponse);
        }

    } catch (AAIServiceException aaiexc) {
        throw aaiexc;
    } catch (Exception exc) {
        LOG.warn("deleteVServerData", exc);
        throw new AAIServiceException(exc);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (Exception exc) {

            }
        }
    }
    return response;
}

From source file:org.openecomp.sdnc.sli.aai.AAIService.java

@Override
public boolean postPInterfaceData(String hostname, String interfaceName, PInterface request)
        throws AAIServiceException {
    InputStream inputStream = null;

    try {/* w  w  w.  ja va2 s .  c  om*/

        ObjectMapper mapper = getObjectMapper();
        String json_text = mapper.writeValueAsString(request);

        SSLSocketFactory sockFact = CTX.getSocketFactory();

        String request_url = target_uri + p_interface_path;
        String encoded_vnf = encodeQuery(hostname);
        request_url = request_url.replace("{hostname}", encoded_vnf);
        encoded_vnf = encodeQuery(interfaceName);
        request_url = request_url.replace("{interface-name}", encoded_vnf);
        URL http_req_url = new URL(request_url);

        HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);

        OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
        osw.write(json_text);
        osw.flush();
        osw.close();

        LOGwriteFirstTrace("PUT", request_url);
        LOGwriteDateTrace("hostname", hostname);
        LOGwriteDateTrace("interface-name", interfaceName);
        LOGwriteDateTrace("PInterface", json_text);

        // Check for errors
        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED
                || responseCode == HttpURLConnection.HTTP_ACCEPTED
                || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            inputStream = con.getInputStream();
        } else {
            inputStream = con.getErrorStream();
        }

        // Process the response
        BufferedReader reader;
        String line = null;
        reader = new BufferedReader(new InputStreamReader(inputStream));

        if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED
                || responseCode == HttpURLConnection.HTTP_ACCEPTED
                || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            StringBuilder stringBuilder = new StringBuilder();

            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            LOGwriteEndingTrace(responseCode, "SUCCESS",
                    (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
            return true;
        } else {
            ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
            LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));

            throw new AAIServiceException(responseCode, errorresponse);
        }
    } catch (AAIServiceException aaiexc) {
        throw aaiexc;
    } catch (Exception exc) {
        LOG.warn("postPInterfaceData", exc);
        throw new AAIServiceException(exc);
    } finally {
        try {
            if (inputStream != null)
                inputStream.close();
        } catch (Exception exc) {

        }
    }
}

From source file:org.openecomp.sdnc.sli.aai.AAIService.java

@Override
public boolean postSitePairSetData(String linkName, SitePairSet request) throws AAIServiceException {
    InputStream inputStream = null;

    try {/*from  ww w  .j a v  a2s . c  o  m*/

        ObjectMapper mapper = getObjectMapper();
        String json_text = mapper.writeValueAsString(request);

        SSLSocketFactory sockFact = CTX.getSocketFactory();

        String request_url = target_uri + site_pair_set_path;
        String encoded_vnf = encodeQuery(linkName);
        request_url = request_url.replace("{site-pair-set-id}", encoded_vnf);
        URL http_req_url = new URL(request_url);

        HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);

        OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
        osw.write(json_text);
        osw.flush();
        osw.close();

        LOGwriteFirstTrace("PUT", request_url);
        LOGwriteDateTrace("link-name", linkName);
        LOGwriteDateTrace("SitePairSet", json_text);

        // Check for errors
        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED
                || responseCode == HttpURLConnection.HTTP_ACCEPTED
                || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            inputStream = con.getInputStream();
        } else {
            inputStream = con.getErrorStream();
        }

        // Process the response
        BufferedReader reader;
        String line = null;
        reader = new BufferedReader(new InputStreamReader(inputStream));

        if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED
                || responseCode == HttpURLConnection.HTTP_ACCEPTED
                || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            StringBuilder stringBuilder = new StringBuilder();

            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            LOGwriteEndingTrace(responseCode, "SUCCESS",
                    (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
            return true;
        } else {
            ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
            LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));

            throw new AAIServiceException(responseCode, errorresponse);
        }
    } catch (AAIServiceException aaiexc) {
        throw aaiexc;
    } catch (Exception exc) {
        LOG.warn("postSitePairSetData", exc);
        throw new AAIServiceException(exc);
    } finally {
        try {
            if (inputStream != null)
                inputStream.close();
        } catch (Exception exc) {

        }
    }
}

From source file:org.openecomp.sdnc.sli.aai.AAIService.java

@Override
public boolean postServiceData(String linkName, Service request) throws AAIServiceException {
    InputStream inputStream = null;

    try {// w  ww .j  a v  a  2s .co m

        ObjectMapper mapper = getObjectMapper();
        String json_text = mapper.writeValueAsString(request);

        SSLSocketFactory sockFact = CTX.getSocketFactory();

        String request_url = target_uri + service_path;
        String encoded_vnf = encodeQuery(linkName);
        request_url = request_url.replace("{service-id}", encoded_vnf);
        URL http_req_url = new URL(request_url);

        HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);

        OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
        osw.write(json_text);
        osw.flush();
        osw.close();

        LOGwriteFirstTrace("PUT", request_url);
        LOGwriteDateTrace("service-id", linkName);
        LOGwriteDateTrace("Service", json_text);

        // Check for errors
        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED
                || responseCode == HttpURLConnection.HTTP_ACCEPTED
                || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            inputStream = con.getInputStream();
        } else {
            inputStream = con.getErrorStream();
        }

        // Process the response
        BufferedReader reader;
        String line = null;
        reader = new BufferedReader(new InputStreamReader(inputStream));

        if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED
                || responseCode == HttpURLConnection.HTTP_ACCEPTED
                || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            StringBuilder stringBuilder = new StringBuilder();

            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            LOGwriteEndingTrace(responseCode, "SUCCESS",
                    (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
            return true;
        } else {
            ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
            LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));

            throw new AAIServiceException(responseCode, errorresponse);
        }
    } catch (AAIServiceException aaiexc) {
        throw aaiexc;
    } catch (Exception exc) {
        LOG.warn("postServiceData", exc);
        throw new AAIServiceException(exc);
    } finally {
        try {
            if (inputStream != null)
                inputStream.close();
        } catch (Exception exc) {

        }
    }
}

From source file:org.openecomp.sdnc.sli.aai.AAIService.java

private boolean deleteAAIEntity(URL url, String caller) throws AAIServiceException {

    if (url == null) {
        throw new NullPointerException();
    }//w ww .j  ava2 s  .c o m

    boolean response = false;
    InputStream inputStream = null;

    try {
        URL http_req_url = url;

        HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.DELETE);

        //            SSLSocketFactory sockFact = CTX.getSocketFactory();
        //            con.setSSLSocketFactory( sockFact );

        LOGwriteFirstTrace("DELETE", http_req_url.toString());

        // Check for errors
        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            inputStream = con.getInputStream();
        } else {
            inputStream = con.getErrorStream();
        }

        // Process the response
        LOG.debug("HttpURLConnection result:" + responseCode);
        if (inputStream == null)
            inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;

        ObjectMapper mapper = getObjectMapper();

        if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            StringBuilder stringBuilder = new StringBuilder();

            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
            response = true;
        } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
            LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
            response = false;
        } else {
            ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
            LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
            throw new AAIServiceException(responseCode, errorresponse);
        }

    } catch (AAIServiceException aaiexc) {
        throw aaiexc;
    } catch (Exception exc) {
        LOG.warn(caller, exc);
        throw new AAIServiceException(exc);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (Exception exc) {

            }
        }
    }
    return response;
}

From source file:org.openecomp.sdnc.sli.aai.AAIService.java

public boolean sendNotify(NotifyEvent event, String serviceInstanceId, String pathCode)
        throws AAIServiceException {
    InputStream inputStream = null;

    try {/*from ww  w  .  ja v  a2  s  .  com*/

        String selfLink = selflink_fqdn;
        if (SELFLINK_AVPN != null && SELFLINK_AVPN.equals(pathCode)) {
            selfLink = selflink_avpn;
        }
        selfLink = selfLink.replace("{service-instance-id}", encodeQuery(serviceInstanceId));
        event.setSelflink(selfLink);

        ObjectMapper mapper = getObjectMapper();
        String json_text = mapper.writeValueAsString(event);

        SSLSocketFactory sockFact = CTX.getSocketFactory();

        String request_url = target_uri + ubb_notify_path;
        URL http_req_url = new URL(request_url);

        HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.PUT);

        OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
        osw.write(json_text);
        osw.flush();
        osw.close();

        LOGwriteFirstTrace("PUT", request_url);
        LOGwriteDateTrace("NotifyEvent", json_text);

        // Check for errors
        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED
                || responseCode == HttpURLConnection.HTTP_ACCEPTED
                || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            inputStream = con.getInputStream();
        } else {
            inputStream = con.getErrorStream();
        }

        // Process the response
        BufferedReader reader;
        String line = null;
        reader = new BufferedReader(new InputStreamReader(inputStream));

        if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED
                || responseCode == HttpURLConnection.HTTP_ACCEPTED
                || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            StringBuilder stringBuilder = new StringBuilder();

            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            LOGwriteEndingTrace(responseCode, "SUCCESS",
                    (stringBuilder != null) ? stringBuilder.toString() : "{no-data}");
            return true;
        } else {
            ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
            LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));

            throw new AAIServiceException(responseCode, errorresponse);
        }
    } catch (AAIServiceException aaiexc) {
        throw aaiexc;
    } catch (Exception exc) {
        LOG.warn("sendNotify", exc);
        throw new AAIServiceException(exc);
    } finally {
        try {
            if (inputStream != null)
                inputStream.close();
        } catch (Exception exc) {

        }
    }
}