Example usage for java.net HttpURLConnection HTTP_ACCEPTED

List of usage examples for java.net HttpURLConnection HTTP_ACCEPTED

Introduction

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

Prototype

int HTTP_ACCEPTED

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

Click Source Link

Document

HTTP Status-Code 202: Accepted.

Usage

From source file:jetbrains.buildServer.vmgr.agent.Utils.java

public String executeVSIFLaunch(String[] vsifs, String url, boolean requireAuth, String user, String password,
        BuildProgressLogger logger, boolean dynamicUserId, String buildID, String workPlacePath)
        throws Exception {

    boolean notInTestMode = true;
    if (logger == null) {
        notInTestMode = false;//from  w ww. ja  v  a  2s .c  o  m
    }

    String apiURL = url + "/rest/sessions/launch";

    for (int i = 0; i < vsifs.length; i++) {

        if (notInTestMode) {
            logger.message("vManager vAPI - Trying to launch vsif file: '" + vsifs[i] + "'");
        }
        String input = "{\"vsif\":\"" + vsifs[i] + "\"}";
        HttpURLConnection conn = getVAPIConnection(apiURL, requireAuth, user, password, "POST", dynamicUserId,
                buildID, workPlacePath, logger);
        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK
                && conn.getResponseCode() != HttpURLConnection.HTTP_NO_CONTENT
                && conn.getResponseCode() != HttpURLConnection.HTTP_ACCEPTED
                && conn.getResponseCode() != HttpURLConnection.HTTP_CREATED
                && conn.getResponseCode() != HttpURLConnection.HTTP_PARTIAL
                && conn.getResponseCode() != HttpURLConnection.HTTP_RESET) {
            String reason = "";
            if (conn.getResponseCode() == 503)
                reason = "vAPI process failed to connect to remote vManager server.";
            if (conn.getResponseCode() == 401)
                reason = "Authentication Error";
            if (conn.getResponseCode() == 412)
                reason = "vAPI requires vManager 'Integration Server' license.";
            if (conn.getResponseCode() == 406)
                reason = "VSIF file '" + vsifs[i]
                        + "' was not found on file system, or is not accessed by the vAPI process.";
            String errorMessage = "Failed : HTTP error code : " + conn.getResponseCode() + " (" + reason + ")";
            if (notInTestMode) {
                logger.message(errorMessage);
                logger.message(conn.getResponseMessage());

                BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

                StringBuilder result = new StringBuilder();
                String output;
                while ((output = br.readLine()) != null) {
                    result.append(output);
                }
                logger.message(result.toString());

            }

            System.out.println(errorMessage);
            return errorMessage;
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        StringBuilder result = new StringBuilder();
        String output;
        while ((output = br.readLine()) != null) {
            result.append(output);
        }

        conn.disconnect();

        JSONObject tmp = JSONObject.fromObject(result.toString());

        String textOut = "Session Launch Success: Session ID: " + tmp.getString("value");

        if (notInTestMode) {
            logger.message(textOut);
        } else {

            System.out.println(textOut);
        }

    }

    return "success";
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitCloneTest.java

@Test
/**/* w  ww  . ja v a  2 s  .c om*/
 * Test for a valid scp-like ssh URI.
 * @throws Exception
 */
public void testCloneValidScpSshUri() throws Exception {
    testUriCheck("git@github.com:eclipse/orion.server.git", HttpURLConnection.HTTP_ACCEPTED);
}

From source file:com.hp.ov.sdk.rest.http.core.client.HttpRestClient.java

/**
 * Gets the response from HPE OneView./*from   w  w  w.  j  a va  2  s  .  c o  m*/
 *
 * @param request
 *  Request information.
 * @param params
 *  connection parameters.
 * @param forceReturnTask
 *  Forces the check for the Location header (task) even when the response code is not 202.
 * @return
 */
private String getResponse(HttpUriRequest request, RestParams params, final boolean forceReturnTask) {
    CloseableHttpClient client = buildHttpClient(params);

    StringBuffer responseBody = new StringBuffer();
    try {
        HttpResponse response = client.execute(request);
        int responseCode = response.getStatusLine().getStatusCode();
        LOGGER.debug("Response code: " + responseCode);

        if (responseCode == HttpsURLConnection.HTTP_NO_CONTENT) {
            responseBody.append("{}");
        } else {
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String line = "";
            while ((line = rd.readLine()) != null) {
                responseBody.append(line);
            }
        }

        LOGGER.error("Response Body: " + responseBody.toString());
        checkResponse(responseCode);

        if (forceReturnTask || ((responseCode == HttpURLConnection.HTTP_ACCEPTED)
                && (responseBody.length() == 0) && response.containsHeader(LOCATION_HEADER))) {
            // Response contains a task
            String restUri = response.getFirstHeader(LOCATION_HEADER).getValue();
            restUri = restUri.substring(restUri.indexOf("/rest"));
            params.setUrl(UrlUtils.createRestUrl(params.getHostname(), restUri));
            params.setType(HttpMethodType.GET);

            return this.sendGetRequest(params, null, false);
        }

    } catch (IOException e) {
        LOGGER.error("IO Error: ", e);
        throw new SDKBadRequestException(SDKErrorEnum.badRequestError, null, null, null, SdkConstants.APPLIANCE,
                e);
    }

    return responseBody.toString();
}

From source file:jetbrains.buildServer.vmgr.agent.Utils.java

public String executeAPI(String jSON, String apiUrl, String url, boolean requireAuth, String user,
        String password, String requestMethod, BuildProgressLogger logger, boolean dynamicUserId,
        String buildID, String workPlacePath) throws Exception {

    try {//w w  w .j av  a2  s  .  c om

        boolean notInTestMode = true;
        if (logger == null) {
            notInTestMode = false;
        }

        String apiURL = url + "/rest" + apiUrl;

        if (notInTestMode) {
            logger.message("vManager vAPI - Trying to call vAPI '" + "/rest" + apiUrl + "'");
        }
        String input = jSON;
        HttpURLConnection conn = getVAPIConnection(apiURL, requireAuth, user, password, requestMethod,
                dynamicUserId, buildID, workPlacePath, logger);

        if ("PUT".equals(requestMethod) || "POST".equals(requestMethod)) {
            OutputStream os = conn.getOutputStream();
            os.write(input.getBytes());
            os.flush();
        }

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK
                && conn.getResponseCode() != HttpURLConnection.HTTP_NO_CONTENT
                && conn.getResponseCode() != HttpURLConnection.HTTP_ACCEPTED
                && conn.getResponseCode() != HttpURLConnection.HTTP_CREATED
                && conn.getResponseCode() != HttpURLConnection.HTTP_PARTIAL
                && conn.getResponseCode() != HttpURLConnection.HTTP_RESET) {
            String reason = "";
            if (conn.getResponseCode() == 503)
                reason = "vAPI process failed to connect to remote vManager server.";
            if (conn.getResponseCode() == 401)
                reason = "Authentication Error";
            if (conn.getResponseCode() == 415)
                reason = "The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.  Check if you selected the right request method (GET/POST/DELETE/PUT).";
            if (conn.getResponseCode() == 405)
                reason = "The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource.  Check if you selected the right request method (GET/POST/DELETE/PUT).";
            if (conn.getResponseCode() == 412)
                reason = "vAPI requires vManager 'Integration Server' license.";
            String errorMessage = "Failed : HTTP error code : " + conn.getResponseCode() + " (" + reason + ")";
            if (notInTestMode) {
                logger.message(errorMessage);
                logger.message(conn.getResponseMessage());
            }

            System.out.println(errorMessage);
            return errorMessage;
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        StringBuilder result = new StringBuilder();
        String output;
        while ((output = br.readLine()) != null) {
            result.append(output);
        }

        conn.disconnect();

        // Flush the output into workspace
        String fileOutput = workPlacePath + File.separator + buildID + File.separator + "vapi.output";

        FileWriter writer = new FileWriter(fileOutput);

        writer.append(result.toString());
        writer.flush();
        writer.close();

        String textOut = "API Call Success: Output was saved into: " + fileOutput;

        if (notInTestMode) {
            logger.message(textOut);
        } else {

            System.out.println(textOut);
        }

        return "success";

    } catch (Exception e) {
        e.printStackTrace();
        logger.error("Failed: Error: " + e.getMessage());
        return e.getMessage();
    }
}

From source file:com.smartbear.collaborator.issue.IssueRest.java

private static void checkResponseStatus(ClientResponse response) throws Exception {
    if (response == null) {
        throw new Exception("Response from Fisheye server is null or empty.");
    }//from   w ww .  ja  va  2s. c  o m

    if (response.getStatus() != HttpURLConnection.HTTP_OK
            && response.getStatus() != HttpURLConnection.HTTP_ACCEPTED
            && response.getStatus() != HttpURLConnection.HTTP_CREATED) {
        throw new Exception("Response status is " + response.getStatus());
    }
}

From source file:org.eclipse.hono.adapter.http.AbstractVertxBasedHttpProtocolAdapter.java

private void doUploadMessage(final RoutingContext ctx, final String tenant, final String deviceId,
        final Buffer payload, final String contentType, final Future<MessageSender> senderTracker,
        final String endpointName) {

    if (!isPayloadOfIndicatedType(payload, contentType)) {
        HttpUtils.badRequest(ctx,// ww w  . j a  va 2  s  .  c  om
                String.format("Content-Type %s does not match with the payload", contentType));
    } else {
        final Integer qosHeader = getQoSLevel(ctx.request().getHeader(Constants.HEADER_QOS_LEVEL));
        if (contentType == null) {
            HttpUtils.badRequest(ctx, String.format("%s header is missing", HttpHeaders.CONTENT_TYPE));
        } else if (qosHeader != null && qosHeader == HEADER_QOS_INVALID) {
            HttpUtils.badRequest(ctx, "Bad QoS Header Value");
        } else {

            final Device authenticatedDevice = getAuthenticatedDevice(ctx);
            final Future<JsonObject> tokenTracker = getRegistrationAssertion(tenant, deviceId,
                    authenticatedDevice);
            final Future<TenantObject> tenantConfigTracker = getTenantConfiguration(tenant);

            // AtomicBoolean to control if the downstream message was sent successfully
            final AtomicBoolean downstreamMessageSent = new AtomicBoolean(false);
            // AtomicReference to a Handler to be called to close an open command receiver link.
            final AtomicReference<Handler<Void>> closeLinkAndTimerHandlerRef = new AtomicReference<>();

            // Handler to be called with a received command. If the timer expired, null is provided as command.
            final Handler<Message> commandReceivedHandler = commandMessage -> {
                // reset the closeHandler reference, since it is not valid anymore at this time.
                closeLinkAndTimerHandlerRef.set(null);
                if (downstreamMessageSent.get()) {
                    // finish the request, since the response is now complete (command was added)
                    if (!ctx.response().closed()) {
                        ctx.response().end();
                    }
                }
            };

            CompositeFuture.all(tokenTracker, tenantConfigTracker, senderTracker).compose(ok -> {

                if (tenantConfigTracker.result().isAdapterEnabled(getTypeName())) {
                    final MessageSender sender = senderTracker.result();
                    final Message downstreamMessage = newMessage(
                            ResourceIdentifier.from(endpointName, tenant, deviceId),
                            sender.isRegistrationAssertionRequired(), ctx.request().uri(), contentType, payload,
                            tokenTracker.result(), HttpUtils.getTimeTilDisconnect(ctx));
                    customizeDownstreamMessage(downstreamMessage, ctx);

                    // first open the command receiver link (if needed)
                    return openCommandReceiverLink(ctx, tenant, deviceId, commandReceivedHandler)
                            .compose(closeLinkAndTimerHandler -> {
                                closeLinkAndTimerHandlerRef.set(closeLinkAndTimerHandler);

                                if (qosHeader == null) {
                                    return sender.send(downstreamMessage);
                                } else {
                                    return sender.sendAndWaitForOutcome(downstreamMessage);
                                }
                            });
                } else {
                    // this adapter is not enabled for the tenant
                    return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_FORBIDDEN));
                }
            }).compose(delivery -> {
                LOG.trace(
                        "successfully processed message for device [tenantId: {}, deviceId: {}, endpoint: {}]",
                        tenant, deviceId, endpointName);
                metrics.incrementProcessedHttpMessages(endpointName, tenant);
                ctx.response().setStatusCode(HttpURLConnection.HTTP_ACCEPTED);
                downstreamMessageSent.set(true);

                // if no command timer was created, the request now can be responded
                if (closeLinkAndTimerHandlerRef.get() == null) {
                    ctx.response().end();
                }

                return Future.succeededFuture();

            }).recover(t -> {

                LOG.debug("cannot process message for device [tenantId: {}, deviceId: {}, endpoint: {}]",
                        tenant, deviceId, endpointName, t);

                cancelResponseTimer(closeLinkAndTimerHandlerRef);

                if (ClientErrorException.class.isInstance(t)) {
                    final ClientErrorException e = (ClientErrorException) t;
                    ctx.fail(e.getErrorCode());
                } else {
                    metrics.incrementUndeliverableHttpMessages(endpointName, tenant);
                    HttpUtils.serviceUnavailable(ctx, 2);
                }
                return Future.failedFuture(t);
            });
        }
    }
}

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

/**
 * Executes a http get with to a given url, in contrast to the normal get it uses an http (accept)
 * status check of the response//from  w w  w.  jav  a2s  .  c  o m
 *
 * @param url the url path used for the api request
 * @return a string containing the response content
 */
public Object requestGetWithStatusAccepted(String url, Class type) throws SDKException {
    url = this.baseUrl + "/" + url;
    return requestGetWithStatus(url, new Integer(HttpURLConnection.HTTP_ACCEPTED), type);
}

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 w  w  . j a va  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();
    }
}

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 {//from w  w  w.j a  va2s  .co m

        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 w  w  w . j  a v  a 2  s  .  c om*/

        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) {

        }
    }
}