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:eu.semlibproject.annotationserver.restapis.ServicesAPI.java

/**
 * Implement a simple proxy/*from w  w  w .j a  v a 2  s  .co  m*/
 *
 * @param requestedURL the requested URL
 * @param req the HttpServletRequest
 * @return
 */
@GET
@Path("proxy")
public Response proxy(@QueryParam(SemlibConstants.URL_PARAM) String requestedURL,
        @Context HttpServletRequest req) {

    BufferedReader in = null;

    try {
        URL url = new URL(requestedURL);
        URLConnection urlConnection = url.openConnection();

        int proxyConnectionTimeout = ConfigManager.getInstance().getProxyAPITimeout();

        // Set base properties
        urlConnection.setUseCaches(false);
        urlConnection.setConnectTimeout(proxyConnectionTimeout * 1000); // set max response timeout 15 sec

        String acceptedDataFormat = req.getHeader(SemlibConstants.HTTP_HEADER_ACCEPT);
        if (StringUtils.isNotBlank(acceptedDataFormat)) {
            urlConnection.addRequestProperty(SemlibConstants.HTTP_HEADER_ACCEPT, acceptedDataFormat);
        }

        // Open the connection
        urlConnection.connect();

        if (urlConnection instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;

            int statusCode = httpConnection.getResponseCode();
            if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP
                    || statusCode == HttpURLConnection.HTTP_MOVED_PERM) {
                // Follow the redirect
                String newLocation = httpConnection.getHeaderField(SemlibConstants.HTTP_HEADER_LOCATION);
                httpConnection.disconnect();

                if (StringUtils.isNotBlank(newLocation)) {
                    return this.proxy(newLocation, req);
                } else {
                    return Response.status(statusCode).build();
                }
            } else if (statusCode == HttpURLConnection.HTTP_OK) {

                // Send the response
                StringBuilder sbf = new StringBuilder();

                // Check if the contentType is supported
                boolean contentTypeSupported = false;
                String contentType = httpConnection.getHeaderField(SemlibConstants.HTTP_HEADER_CONTENT_TYPE);
                List<String> supportedMimeTypes = ConfigManager.getInstance().getProxySupportedMimeTypes();
                if (contentType != null) {
                    for (String cMime : supportedMimeTypes) {
                        if (contentType.equals(cMime) || contentType.contains(cMime)) {
                            contentTypeSupported = true;
                            break;
                        }
                    }
                }

                if (!contentTypeSupported) {
                    httpConnection.disconnect();
                    return Response.status(Status.NOT_ACCEPTABLE).build();
                }

                String contentEncoding = httpConnection.getContentEncoding();
                if (StringUtils.isBlank(contentEncoding)) {
                    contentEncoding = "UTF-8";
                }

                InputStreamReader inStrem = new InputStreamReader((InputStream) httpConnection.getContent(),
                        Charset.forName(contentEncoding));
                in = new BufferedReader(inStrem);

                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    sbf.append(inputLine);
                    sbf.append("\r\n");
                }

                in.close();
                httpConnection.disconnect();

                return Response.status(statusCode).header(SemlibConstants.HTTP_HEADER_CONTENT_TYPE, contentType)
                        .entity(sbf.toString()).build();

            } else {
                httpConnection.disconnect();
                return Response.status(statusCode).build();
            }
        }

        return Response.status(Status.BAD_REQUEST).build();

    } catch (MalformedURLException ex) {
        logger.log(Level.SEVERE, null, ex);
        return Response.status(Status.BAD_REQUEST).build();
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ex) {
                logger.log(Level.SEVERE, null, ex);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }
        }
    }
}

From source file:de.escidoc.core.test.sb.SearchTestBase.java

/**
 * Wait until the given id exists in the given index.
 * //from   www.  j av  a2  s  .  com
 * @param id
 *            resource id
 * @param indexName
 *            name of the index
 * @param checkExists
 *            true for existence check, false for nonexistence
 * @param maxTimeToWait
 *            maximum time to wait in milliseconds
 * @throws Exception
 *             Thrown if the connection to the indexer failed.
 */
private void waitForIndexer(final String id, final String indexName, final boolean checkExists,
        final long maxTimeToWait) throws Exception {
    long time = System.currentTimeMillis();
    String query = "PID=" + id + " or distinction.rootPid=" + id;
    String httpUrl = getFrameworkUrl() + de.escidoc.core.test.common.client.servlet.Constants.SEARCH_BASE_URI
            + "/" + indexName + "?query=" + URLEncoder.encode(query, DEFAULT_CHARSET);

    for (;;) {
        HttpResponse httpRes = HttpHelper.executeHttpRequest(
                de.escidoc.core.test.common.client.servlet.Constants.HTTP_METHOD_GET, httpUrl, null, null,
                null);

        if (httpRes.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
            Pattern numberOfRecordsPattern = Pattern.compile("numberOfRecords>(.*?)<");
            Matcher m = numberOfRecordsPattern.matcher(EntityUtils.toString(httpRes.getEntity(), HTTP.UTF_8));

            if (m.find()) {
                if (checkExists && (Integer.parseInt(m.group(1)) > 0)) {
                    break;
                } else if (!checkExists && (Integer.parseInt(m.group(1)) == 0)) {
                    break;
                }
            }
        }
        if ((System.currentTimeMillis() - time) > maxTimeToWait) {
            break;
        }
    }
}

From source file:com.QuarkLabs.BTCeClient.exchangeApi.AuthRequest.java

/**
 * Makes any request, which require authentication
 *
 * @param method    Method of Trade API//from www. j av  a 2 s  . c o  m
 * @param arguments Additional arguments, which can exist for this method
 * @return Response of type JSONObject
 * @throws JSONException
 */
@Nullable
public JSONObject makeRequest(@NotNull String method, Map<String, String> arguments) throws JSONException {

    if (key.length() == 0 || secret.length() == 0) {
        return new JSONObject("{success:0,error:'No key/secret provided'}");
    }

    if (arguments == null) {
        arguments = new HashMap<>();
    }

    arguments.put("method", method);
    arguments.put("nonce", "" + ++nonce);
    String postData = "";
    for (Iterator<Map.Entry<String, String>> it = arguments.entrySet().iterator(); it.hasNext();) {
        Map.Entry<String, String> ent = it.next();
        if (postData.length() > 0) {
            postData += "&";
        }
        postData += ent.getKey() + "=" + ent.getValue();
    }
    try {
        _key = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA512");
    } catch (UnsupportedEncodingException uee) {
        System.err.println("Unsupported encoding exception: " + uee.toString());
        return null;
    }

    try {
        mac = Mac.getInstance("HmacSHA512");
    } catch (NoSuchAlgorithmException nsae) {
        System.err.println("No such algorithm exception: " + nsae.toString());
        return null;
    }

    try {
        mac.init(_key);
    } catch (InvalidKeyException ike) {
        System.err.println("Invalid key exception: " + ike.toString());
        return null;
    }

    HttpURLConnection connection = null;
    BufferedReader bufferedReader = null;
    DataOutputStream wr = null;
    try {
        connection = (HttpURLConnection) (new URL(TRADE_API_URL)).openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Key", key);
        byte[] array = mac.doFinal(postData.getBytes("UTF-8"));
        connection.setRequestProperty("Sign", byteArrayToHexString(array));
        wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(postData);
        wr.flush();
        InputStream response = connection.getInputStream();
        StringBuilder sb = new StringBuilder();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            String line;
            bufferedReader = new BufferedReader(new InputStreamReader(response));
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            return new JSONObject(sb.toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (wr != null) {
            try {
                wr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return null;
}

From source file:org.opencastproject.capture.impl.jobs.AgentConfigurationJob.java

/**
 * Pushes the agent's capabilities to the remote state service. {@inheritDoc}
 * /*ww  w .jav  a  2 s  . co  m*/
 * @see org.quartz.Job#execute(JobExecutionContext)
 * @throws JobExecutionException
 */
public void execute(JobExecutionContext ctx) throws JobExecutionException {
    uniqueID = getStatePushCount();
    ConfigurationManager config = (ConfigurationManager) ctx.getMergedJobDataMap()
            .get(JobParameters.CONFIG_SERVICE);
    CaptureAgent agent = (CaptureAgent) ctx.getMergedJobDataMap().get(JobParameters.STATE_SERVICE);
    TrustedHttpClient client = (TrustedHttpClient) ctx.getMergedJobDataMap().get(JobParameters.TRUSTED_CLIENT);

    if (client == null) {
        logger.error(
                "TrustedHttpClient was null so we won't be able to update the agent capabilities until it is updated.");
        return;
    }

    // Figure out where we're sending the data
    String url = config.getItem(CaptureParameters.AGENT_STATE_REMOTE_ENDPOINT_URL);
    if (url == null) {
        logger.warn("#" + uniqueID + " - URL for {} is invalid, unable to push capabilities to remote server.",
                CaptureParameters.AGENT_STATE_REMOTE_ENDPOINT_URL);
        return;
    }
    try {
        if (url.charAt(url.length() - 1) == '/') {
            url += config.getItem(CaptureParameters.AGENT_NAME) + "/configuration";
        } else {
            url += "/" + config.getItem(CaptureParameters.AGENT_NAME) + "/configuration";
        }
    } catch (StringIndexOutOfBoundsException e) {
        logger.warn("#" + uniqueID + " - Unable to build valid capabilities endpoint for agents.");
        return;
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    HttpResponse resp = null;
    try {
        agent.getDefaultAgentProperties().storeToXML(baos,
                "Capabilities for the agent " + agent.getAgentName());
    } catch (IOException e) {
        logger.warn("#" + uniqueID + " - Unable to serialize agent capabilities!");
        return;
    }
    HttpPost remoteServer = new HttpPost(url);
    try {
        List<NameValuePair> formParams = new LinkedList<NameValuePair>();
        formParams.add(new BasicNameValuePair("configuration", baos.toString()));
        remoteServer.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        logger.warn("#" + uniqueID
                + " - Unable to send agent capapbillities because correct encoding scheme is not supported!");
        return;
    }
    try {
        resp = client.execute(remoteServer);
        if (resp.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) {
            logger.info("#" + uniqueID + " - Capabilities push to {} failed with code {}.", url,
                    resp.getStatusLine().getStatusCode());
        }
    } catch (TrustedHttpClientException e) {
        logger.warn("#" + uniqueID + " - Unable to post capabilities to {}, message reads: {}.", url, e);
    } finally {
        if (resp != null) {
            client.close(resp);
        }
    }
}

From source file:com.streamsets.datacollector.http.SlaveWebServerTaskIT.java

private static void verifyWebServerTask(final WebServerTask ws, SlaveRuntimeInfo runtimeInfo) throws Exception {
    try {/*from   www .j  av  a 2s  .  co  m*/
        ws.initTask();
        new Thread() {
            @Override
            public void run() {
                ws.runTask();
            }
        }.start();
        waitForStart(ws);
        HttpsURLConnection conn = (HttpsURLConnection) new URL(
                "https://127.0.0.1:" + ws.getServerURI().getPort() + "/ping").openConnection();
        TestWebServerTaskHttpHttps.configureHttpsUrlConnection(conn);
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        Assert.assertNotNull(runtimeInfo.getSSLContext());
    } finally {
        ws.stopTask();
    }
}

From source file:com.mobile.godot.core.controller.CoreController.java

public synchronized void removeCar(String carName, LoginBean login) {

    String servlet = "RemoveCar";
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("carName", carName));
    params.add(new BasicNameValuePair("username", login.getUsername()));
    params.add(new BasicNameValuePair("password", login.getPassword()));
    SparseIntArray mMessageMap = new SparseIntArray();
    mMessageMap.append(HttpURLConnection.HTTP_OK, GodotMessage.Entity.CAR_REMOVED);
    mMessageMap.append(HttpURLConnection.HTTP_UNAUTHORIZED, GodotMessage.Error.UNAUTHORIZED);

    GodotAction action = new GodotAction(servlet, params, mMessageMap, mHandler);
    Thread tAction = new Thread(action);
    tAction.start();/*  ww w  .  java  2 s. c  o  m*/

}

From source file:net.joala.net.EmbeddedWebservice.java

/**
 * Start the webservice./* w w w.j ava2s.  c om*/
 */
public void start() {
    checkState(server != null, "Server cannot be restarted.");
    server.start();
    preparedResponsesHttpHandler.feedResponses(statusCode(HttpURLConnection.HTTP_OK));
    final DefaultHttpClient httpClient = getStartupHttpClient();
    try {
        getStartupCondition(httpClient).assumeThat(equalTo(HttpURLConnection.HTTP_OK));
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    LOG.info("Started embedded webservice at port {} with context {}.", port, context);
}

From source file:net.sf.okapi.filters.drupal.DrupalConnector.java

public boolean updateNode(Node node) {
    try {/* w w  w  .  j  a  va 2 s  .  co m*/
        URL url = new URL(host + String.format("rest/node/" + node.getNid()));
        HttpURLConnection conn = createConnection(url, "PUT", true);

        OutputStream os = conn.getOutputStream();
        os.write(node.toString().getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            System.out.println(conn.getResponseCode());
            System.out.println(conn.getResponseMessage());
            throw new RuntimeException("Operation failed: " + conn.getResponseCode());
        }

        conn.disconnect();
        return true;
    } catch (Throwable e) {
        throw new RuntimeException("Error in updateNode(): " + e.getMessage(), e);
    }
}

From source file:rogerthat.topdesk.bizz.Util.java

public static String getTopdeskApiKey() throws IOException, ParseException {
    final Settings settings = Settings.get();
    final String loginString = "Basic " + Base64.encodeBytes(
            (settings.get("TOPDESK_USERNAME") + ":" + settings.get("TOPDESK_PASSWORD")).getBytes());
    log.info("loginString: " + loginString);
    URLFetchService urlFetch = URLFetchServiceFactory.getURLFetchService();
    URL url = new URL(settings.get("TOPDESK_API_URL") + "/login");
    HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET, FetchOptions.Builder.withDeadline(30));
    request.addHeader(new HTTPHeader("Authorization", loginString));
    HTTPResponse response = urlFetch.fetch(request);
    String content = getContent(response);
    if (response.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new TopdeskApiException(
                "Could not login\n Response code " + response.getResponseCode() + "\nContent:" + content);
    } else {/* www  .j  a v a  2 s.  co m*/
        return content;
    }
}