Example usage for java.net HttpURLConnection HTTP_OK

List of usage examples for java.net HttpURLConnection HTTP_OK

Introduction

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

Prototype

int HTTP_OK

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

Click Source Link

Document

HTTP Status-Code 200: OK.

Usage

From source file:com.bigstep.datalake.KerberosIdentityAuthenticator.java

/**
 * Performs SPNEGO authentication against the specified URL.
 * <p>//from   w w w .jav  a  2  s  .c o  m
 * If a token is given it does a NOP and returns the given token.
 * <p>
 * If no token is given, it will perform the SPNEGO authentication sequence using an
 * HTTP <code>OPTIONS</code> request.
 *
 * @param url   the URl to authenticate against.
 * @param token the authentication token being used for the user.
 * @throws IOException             if an IO error occurred.
 * @throws AuthenticationException if an authentication error occurred.
 */
@Override
public void authenticate(URL url, AuthenticatedURL.Token token) throws IOException, AuthenticationException {
    if (!token.isSet()) {
        this.url = url;
        base64 = new Base64(0);
        conn = (HttpURLConnection) url.openConnection();
        if (connConfigurator != null) {
            conn = connConfigurator.configure(conn);
        }
        conn.setRequestMethod(AUTH_HTTP_METHOD);
        conn.connect();

        boolean needFallback = false;
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            LOG.debug("JDK performed authentication on our behalf.");
            // If the JDK already did the SPNEGO back-and-forth for
            // us, just pull out the token.
            AuthenticatedURL.extractToken(conn, token);
            if (isTokenKerberos(token)) {
                return;
            }
            needFallback = true;
        }
        if (!needFallback && isNegotiate()) {
            LOG.debug("Performing our own SPNEGO sequence.");
            doSpnegoSequence(token);
        } else {
            LOG.debug("Using fallback authenticator sequence.");
            Authenticator auth = getFallBackAuthenticator();
            // Make sure that the fall back authenticator have the same
            // ConnectionConfigurator, since the method might be overridden.
            // Otherwise the fall back authenticator might not have the information
            // to make the connection (e.g., SSL certificates)
            auth.setConnectionConfigurator(connConfigurator);
            auth.authenticate(url, token);
        }
    }
}

From source file:com.example.admin.processingboilerplate.JsonIO.java

public static JSONObject pushJson(String requestURL, String jsonDataName, JSONObject json) {
    try {//from w  ww  . j  av a2  s  . c om
        String boundary = "===" + System.currentTimeMillis() + "===";

        URL url = new URL(requestURL);
        //HttpURLConnection con = (HttpURLConnection) url.openConnection();
        URLConnection uc = (url).openConnection();
        HttpURLConnection con = requestURL.startsWith("https") ? (HttpsURLConnection) uc
                : (HttpURLConnection) uc;
        con.setUseCaches(false);
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        con.setRequestProperty("User-Agent", USER_AGENT);
        OutputStream outputStream = con.getOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);

        writer.append("--" + boundary).append(CRLF);
        writer.append("Content-Disposition: form-data; name=\"" + "data" + "\"").append(CRLF);
        writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
        writer.append(CRLF);
        writer.append(json.toString()).append(CRLF);
        writer.flush();

        writer.append(CRLF).flush();
        writer.append("--" + boundary + "--").append(CRLF);
        writer.close();
        int status = con.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            StringBuilder sb = load(con);
            try {
                json = new JSONObject(sb.toString());
                return json;
            } catch (JSONException e) {
                Log.e("loadJson", e.getMessage(), e);
                e.printStackTrace();
                return new JSONObject();
            }
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new JSONObject();
}

From source file:edu.usf.cutr.opentripplanner.android.pois.Nominatim.java

public JSONArray requestPlaces(String paramName, String left, String top, String right, String bottom) {
    StringBuilder builder = new StringBuilder();

    String encodedParamName;/*from w w  w  . j  a v a2  s. c  o m*/
    String encodedParamLeft = "";
    String encodedParamTop = "";
    String encodedParamRight = "";
    String encodedParamBottom = "";
    try {
        encodedParamName = URLEncoder.encode(paramName, OTPApp.URL_ENCODING);
        if ((left != null) && (top != null) && (right != null) && (bottom != null)) {
            encodedParamLeft = URLEncoder.encode(left, OTPApp.URL_ENCODING);
            encodedParamTop = URLEncoder.encode(top, OTPApp.URL_ENCODING);
            encodedParamRight = URLEncoder.encode(right, OTPApp.URL_ENCODING);
            encodedParamBottom = URLEncoder.encode(bottom, OTPApp.URL_ENCODING);
        }
    } catch (UnsupportedEncodingException e1) {
        Log.e(OTPApp.TAG, "Error encoding Nominatim request");
        e1.printStackTrace();
        return null;
    }

    request += "&q=" + encodedParamName;
    if ((left != null) && (top != null) && (right != null) && (bottom != null)) {
        request += "&viewbox=" + encodedParamLeft + "," + encodedParamTop + "," + encodedParamRight + ","
                + encodedParamBottom;
        request += "&bounded=1";
    }

    request += "&key=" + mApiKey;

    Log.d(OTPApp.TAG, request);

    HttpURLConnection urlConnection = null;

    try {
        URL url = new URL(request);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(OTPApp.HTTP_CONNECTION_TIMEOUT);
        urlConnection.setReadTimeout(OTPApp.HTTP_SOCKET_TIMEOUT);
        urlConnection.connect();
        int status = urlConnection.getResponseCode();

        if (status == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } else {
            Log.e(OTPApp.TAG, "Error obtaining Nominatim response, status code: " + status);
        }
    } catch (IOException e) {
        e.printStackTrace();
        Log.e(OTPApp.TAG, "Error obtaining Nominatim response" + e.toString());
        return null;
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    Log.d(OTPApp.TAG, builder.toString());

    JSONArray json = null;
    try {
        json = new JSONArray(builder.toString());
    } catch (JSONException e) {
        Log.e(OTPApp.TAG, "Error parsing Nominatim data " + e.toString());
    }

    return json;
}

From source file:org.jboss.additional.testsuite.jdkall.present.web.servlet.buffersize.ResponseBufferSizeTestCase.java

@Test
@OperateOnDeployment(DEPLOYMENT)//  ww  w  .  j  av  a 2 s  .  com
public void increaseBufferSizeTest(@ArquillianResource URL url) throws Exception {
    URL testURL = new URL(
            url.toString() + "ResponseBufferSizeServlet?" + ResponseBufferSizeServlet.SIZE_CHANGE_PARAM_NAME
                    + "=1.5" + "&" + ResponseBufferSizeServlet.DATA_LENGTH_IN_PERCENTS_PARAM_NAME + "=0.8"); // more than original size, less than new buffer size

    final HttpGet request = new HttpGet(testURL.toString());
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    CloseableHttpResponse response = null;

    try {
        response = httpClient.execute(request);
        Assert.assertEquals("Failed to access " + testURL, HttpURLConnection.HTTP_OK,
                response.getStatusLine().getStatusCode());
        String content = EntityUtils.toString(response.getEntity());
        Assert.assertFalse(content.contains(ResponseBufferSizeServlet.RESPONSE_COMMITED_MESSAGE));
        final Header[] transferEncodingHeaders = response.getHeaders("Transfer-Encoding");
        final Header[] contentLengthHeader = response.getHeaders("Content-Length");

        for (Header transferEncodingHeader : transferEncodingHeaders) {
            Assert.assertNotEquals(
                    "Transfer-Encoding shouldn't be chunked as set BufferSize shouldn't be filled yet, "
                            + "probably caused due https://bugzilla.redhat.com/show_bug.cgi?id=1212566",
                    "chunked", transferEncodingHeader.getValue());
        }

        Assert.assertFalse("Content-Length header not specified", contentLengthHeader.length == 0);
    } finally {
        IOUtils.closeQuietly(response);
        httpClient.close();
    }
}

From source file:org.eclipse.hono.service.registration.RegistrationHttpEndpoint.java

private void doGetDevice(final RoutingContext ctx) {

    final String deviceId = getDeviceIdParam(ctx);
    final String tenantId = getTenantParam(ctx);
    final HttpServerResponse response = ctx.response();
    final JsonObject requestMsg = EventBusMessage.forOperation(RegistrationConstants.ACTION_GET)
            .setTenant(tenantId).setDeviceId(deviceId).toJson();

    sendAction(ctx, requestMsg, (status, registrationResult) -> {
        response.setStatusCode(status);/*from   w w  w  . java  2  s  .c o m*/
        switch (status) {
        case HttpURLConnection.HTTP_OK:
            HttpUtils.setResponseBody(ctx.response(), registrationResult);
        default:
            response.end();
        }
    });
}

From source file:org.pentaho.di.trans.steps.http.HTTPTest.java

@Before
public void setup() throws Exception {
    HttpClientManager.HttpClientBuilderFacade builder = mock(HttpClientManager.HttpClientBuilderFacade.class);

    HttpClientManager manager = mock(HttpClientManager.class);
    doReturn(builder).when(manager).createBuilder();

    CloseableHttpClient client = mock(CloseableHttpClient.class);
    doReturn(client).when(builder).build();

    CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    doReturn(response).when(client).execute(any(HttpGet.class));

    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream(DATA.getBytes()));
    doReturn(entity).when(response).getEntity();

    mockStatic(HttpClientManager.class);
    when(HttpClientManager.getInstance()).thenReturn(manager);

    setInternalState(data, "realUrl", "http://pentaho.com");
    setInternalState(data, "argnrs", new int[0]);

    doReturn(false).when(meta).isUrlInField();
    doReturn("body").when(meta).getFieldName();

    doReturn(false).when(log).isDetailed();

    doCallRealMethod().when(http).callHttpService(any(RowMetaInterface.class), any(Object[].class));
    doReturn(HttpURLConnection.HTTP_OK).when(http).requestStatusCode(any(CloseableHttpResponse.class));
    doReturn(new Header[0]).when(http).searchForHeaders(any(CloseableHttpResponse.class));
    setInternalState(http, "log", log);
    setInternalState(http, "data", data);
    setInternalState(http, "meta", meta);
}

From source file:de.rwth.dbis.acis.activitytracker.service.ActivityTrackerService.java

@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)//w w  w  .  j a va 2s .  c o m
@ApiOperation(value = "This method returns a list of activities", notes = "Default the latest ten activities will be returned")
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of activities"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") })
//TODO add filter
public HttpResponse getActivities(
        @ApiParam(value = "Before cursor pagination", required = false) @DefaultValue("-1") @QueryParam("before") int before,
        @ApiParam(value = "After cursor pagination", required = false) @DefaultValue("-1") @QueryParam("after") int after,
        @ApiParam(value = "Limit of elements of components", required = false) @DefaultValue("10") @QueryParam("limit") int limit,
        @ApiParam(value = "User authorization token", required = false) @DefaultValue("") @HeaderParam("authorization") String authorizationToken) {

    DALFacade dalFacade = null;
    try {
        if (before != -1 && after != -1) {
            ExceptionHandler.getInstance().throwException(ExceptionLocation.ACTIVITIESERVICE,
                    ErrorCode.WRONG_PARAMETER, "both: before and after parameter not possible");
        }
        int cursor = before != -1 ? before : after;
        Pageable.SortDirection sortDirection = after != -1 ? Pageable.SortDirection.ASC
                : Pageable.SortDirection.DESC;

        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(20);
        CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();

        dalFacade = getDBConnection();
        Gson gson = new Gson();
        ExecutorService executor = Executors.newCachedThreadPool();

        int getObjectCount = 0;
        PaginationResult<Activity> activities;
        List<ActivityEx> activitiesEx = new ArrayList<>();
        Pageable pageInfo = new PageInfo(cursor, limit, "", sortDirection);
        while (activitiesEx.size() < limit && getObjectCount < 5) {
            pageInfo = new PageInfo(cursor, limit, "", sortDirection);
            activities = dalFacade.findActivities(pageInfo);
            getObjectCount++;
            cursor = sortDirection == Pageable.SortDirection.ASC ? cursor + limit : cursor - limit;
            if (cursor < 0) {
                cursor = 0;
            }
            activitiesEx.addAll(
                    getObjectBodies(httpclient, executor, authorizationToken, activities.getElements()));
        }

        executor.shutdown();
        if (activitiesEx.size() > limit) {
            activitiesEx = activitiesEx.subList(0, limit);
        }
        PaginationResult<ActivityEx> activitiesExResult = new PaginationResult<>(pageInfo, activitiesEx);

        HttpResponse response = new HttpResponse(gson.toJson(activitiesExResult.getElements()),
                HttpURLConnection.HTTP_OK);
        Map<String, String> parameter = new HashMap<>();
        parameter.put("limit", String.valueOf(limit));
        response = this.addPaginationToHtppResponse(activitiesExResult, "", parameter, response);

        return response;

    } catch (ActivityTrackerException atException) {
        return new HttpResponse(ExceptionHandler.getInstance().toJSON(atException),
                HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (Exception ex) {
        ActivityTrackerException atException = ExceptionHandler.getInstance().convert(ex,
                ExceptionLocation.ACTIVITIESERVICE, ErrorCode.UNKNOWN, ex.getMessage());
        return new HttpResponse(ExceptionHandler.getInstance().toJSON(atException),
                HttpURLConnection.HTTP_INTERNAL_ERROR);
    } finally {
        closeDBConnection(dalFacade);
    }
}

From source file:de.innovationgate.igutils.pingback.PingBackClient.java

private String determinePingBackURI(String targetURI) throws PingBackException {
    HttpClient client = WGFactory.getHttpClientFactory().createHttpClient();
    GetMethod pingbackTargetGET = new GetMethod(targetURI);
    pingbackTargetGET.setFollowRedirects(false);
    try {//from  w  ww.  ja v a2s .  c om
        int responseCode = client.executeMethod(pingbackTargetGET);
        if (responseCode != HttpURLConnection.HTTP_OK) {
            if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
                throw new PingBackException(PingBackException.ERROR_ACCESS_DENIED,
                        "Access denied on target '" + targetURI + "'.");
            } else if (responseCode == HttpURLConnection.HTTP_BAD_GATEWAY) {
                throw new PingBackException(PingBackException.ERROR_UPSTREAM_SERVER_COMMUNICATION_ERROR,
                        "Unable to determine ping back target for post. Get request on '" + targetURI
                                + "' returned '" + responseCode + "'.");
            } else {
                throw new PingBackException(PingBackException.ERROR_TARGET_URI_CANNOT_BE_USED_AS_TARGET,
                        "Unable to determine ping back target for post. Get request on '" + targetURI
                                + "' returned '" + responseCode + "'.");
            }
        }

        Header header = pingbackTargetGET.getResponseHeader("X-Pingback");
        if (header != null && header.getValues().length > 0) {
            // retrieve ping back url from header
            HeaderElement headerElement = header.getValues()[0];
            return headerElement.getName();
        } else {
            // retrieve ping back url from link tag

            // check for textual content
            checkTextualContentType(pingbackTargetGET);

            // retrieve input reader an try to find link tag
            InputStream sourceIn = pingbackTargetGET.getResponseBodyAsStream();
            String searchTerm = "<link rel=\"pingback\" href=\"";
            if (sourceIn == null) {
                throw new PingBackException(PingBackException.ERROR_TARGET_URI_CANNOT_BE_USED_AS_TARGET,
                        "TargetURL '" + targetURI + "' cannot be parsed for link tag.");
            } else {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        pingbackTargetGET.getResponseBodyAsStream(), pingbackTargetGET.getResponseCharSet()));
                String line = reader.readLine();
                while (line != null) {
                    String orgLine = line;
                    line = line.toLowerCase();
                    int start = line.indexOf(searchTerm);
                    if (start != -1) {
                        if (start + searchTerm.length() <= line.length()) {
                            start = start + searchTerm.length();
                            int end = line.indexOf("\"", start);
                            if (end != -1) {
                                String href = orgLine.substring(start, end);
                                href = href.replaceAll("&amp;", "&");
                                href = href.replaceAll("&lt;", "<");
                                href = href.replaceAll("&gt;", ">");
                                href = href.replaceAll("&quot;", "\"");
                                return href;
                            } else {
                                throw new PingBackException(
                                        PingBackException.ERROR_TARGET_URI_CANNOT_BE_USED_AS_TARGET,
                                        "TargetURL '" + targetURI + "' returned an unparsable link-tag");
                            }
                        } else {
                            throw new PingBackException(
                                    PingBackException.ERROR_TARGET_URI_CANNOT_BE_USED_AS_TARGET,
                                    "TargetURL '" + targetURI + "' returned an unparsable link-tag");
                        }
                    }
                    // if endof head reached - cancel search
                    if (line.indexOf("</head>") != -1 || line.indexOf("<body>") != -1) {
                        throw new PingBackException(PingBackException.ERROR_TARGET_URI_CANNOT_BE_USED_AS_TARGET,
                                "TargetURL '" + targetURI + "' is not pingback-enabled.");
                    }
                    line = reader.readLine();
                }
                throw new PingBackException(PingBackException.ERROR_TARGET_URI_CANNOT_BE_USED_AS_TARGET,
                        "TargetURL '" + targetURI + "' is not pingback-enabled.");
            }
        }
    } catch (HttpException e) {
        throw new PingBackException(PingBackException.ERROR_GENERIC,
                "Unable to determine ping back target for post.", e);
    } catch (IOException e) {
        throw new PingBackException(PingBackException.ERROR_GENERIC,
                "Unable to determine ping back target for post.", e);
    }
}

From source file:org.hawkular.metrics.clients.ptrans.backend.RestForwardingHandlerITest.java

private JsonNode findNumericDataOnServer() throws IOException {
    HttpURLConnection urlConnection = (HttpURLConnection) new URL(findNumericDataUrl).openConnection();
    urlConnection.connect();//from w w  w.  ja va2 s . c  om
    int responseCode = urlConnection.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_OK) {
        return null;
    }
    ObjectMapper objectMapper = new ObjectMapper();
    try (InputStream inputStream = urlConnection.getInputStream()) {
        return objectMapper.readTree(inputStream);
    }
}