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.mobile.godot.core.controller.CoreController.java

public synchronized void removeCoOwner(String carName, String coOwnerUsername, LoginBean login) {

    String servlet = "RemoveCoOwner";
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("carName", carName));
    params.add(new BasicNameValuePair("coOwnerUsername", coOwnerUsername));
    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.COOWNER_REMOVED);
    mMessageMap.append(HttpURLConnection.HTTP_UNAUTHORIZED, GodotMessage.Error.UNAUTHORIZED);

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

}

From source file:org.openremote.modeler.beehive.Beehive30API.java

/**
 * Downloads a user artifact archive from Beehive server and stores it to a local resource
 * cache. // w w  w .java2 s .  c  o  m
 *
 * @param userAccount   reference to information about user and account being accessed
 * @param cache         the cache to store the user resources to
 *
 * @throws ConfigurationException
 *              If designer configuration error prevents the service from executing
 *              normally. Often a fatal error type that should be logged/notified to
 *              admins, configuration corrected and application re-deployed.
 *
 * @throws NetworkException
 *              If (possibly recoverable) network errors occured during the service
 *              operation. Network errors may be recoverable in which case this operation
 *              could be re-attempted. See {@link NetworkException.Severity} for an
 *              indication of the network error type.
 *
 * @throws CacheOperationException
 *              If there was a failure in writing the downloaded resources to cache.
 *
 *
 */
@Override
public void downloadResources(UserAccount userAccount, ResourceCache cache)
        throws ConfigurationException, NetworkException, CacheOperationException {

    // TODO :
    //    - Must use HTTPS

    // Construct the request...

    HttpClient httpClient = new DefaultHttpClient();

    URI beehiveArchiveURI;

    try {
        beehiveArchiveURI = new URI(config.getBeehiveRESTRootUrl() + "user/"
                + userAccount.getUsernamePassword().getUsername() + "/openremote.zip");
    }

    catch (URISyntaxException e) {
        throw new ConfigurationException("Incorrect Beehive REST URL defined in config.properties : {0}", e,
                e.getMessage());
    }

    HttpGet httpGet = new HttpGet(beehiveArchiveURI);

    // Authenticate...

    addHTTPAuthenticationHeader(httpGet, userAccount.getUsernamePassword().getUsername(),
            userAccount.getUsernamePassword().getPassword());

    // Collect some network statistics...

    long starttime = System.currentTimeMillis();

    // HTTP GET to Beehive...

    HttpResponse response;

    try {
        response = httpClient.execute(httpGet);
    }

    catch (IOException e) {
        throw new NetworkException(
                "Network error while downloading account (OID = {0}) archive from Beehive "
                        + "(URL : {1}) : {2}",
                e,

                userAccount.getAccount().getOid(), beehiveArchiveURI, e.getMessage());
    }

    // Make sure we got a response and a proper HTTP return code...

    if (response == null) {
        throw new NetworkException(NetworkException.Severity.SEVERE,
                "Beehive did not respond to HTTP GET request, URL : {0} {1}", beehiveArchiveURI,
                printUser(userAccount));
    }

    StatusLine statusLine = response.getStatusLine();

    if (statusLine == null) {
        throw new NetworkException(NetworkException.Severity.SEVERE,
                "There was no status from Beehive to HTTP GET request, URL : {0} {1}", beehiveArchiveURI,
                printUser(userAccount));
    }

    int httpResponseCode = statusLine.getStatusCode();

    // Deal with the HTTP OK (200) case.

    if (httpResponseCode == HttpURLConnection.HTTP_OK) {
        HttpEntity httpEntity = response.getEntity();

        if (httpEntity == null) {
            throw new NetworkException(NetworkException.Severity.SEVERE,
                    "No content received from Beehive to HTTP GET request, URL : {0} {1}", beehiveArchiveURI,
                    printUser(userAccount));
        }

        // Download to cache...

        BufferedInputStream httpInput;

        try {
            CacheWriteStream cacheStream = cache.openWriteStream();

            httpInput = new BufferedInputStream(httpEntity.getContent());

            byte[] buffer = new byte[4096];
            int bytecount = 0, len;
            long contentLength = httpEntity.getContentLength();

            try {
                while ((len = httpInput.read(buffer)) != -1) {
                    try {
                        cacheStream.write(buffer, 0, len);
                    }

                    catch (IOException e) {
                        throw new CacheOperationException("Writing archive to cache failed : {0}", e,
                                e.getMessage());
                    }

                    bytecount += len;
                }

                // MUST mark complete for cache to accept the incoming archive...

                cacheStream.markCompleted();
            }

            finally {
                try {
                    cacheStream.close();
                }

                catch (Throwable t) {
                    serviceLog.warn("Unable to close resource archive cache stream : {0}", t, t.getMessage());
                }

                if (httpInput != null) {
                    try {
                        httpInput.close();
                    }

                    catch (Throwable t) {
                        serviceLog.warn("Unable to close HTTP input stream from Beehive URL ''{0}'' : {1}", t,
                                beehiveArchiveURI, t.getMessage());
                    }
                }
            }

            if (contentLength >= 0) {
                if (bytecount != contentLength) {
                    serviceLog.warn(
                            "Expected content length was {0} bytes but wrote {1} bytes to cache stream ''{2}''.",
                            contentLength, bytecount, cacheStream);
                }
            }

            // Record network performance stats...

            long endtime = System.currentTimeMillis();

            float kbytes = ((float) bytecount) / 1000;
            float seconds = ((float) (endtime - starttime)) / 1000;
            float kbpersec = kbytes / seconds;

            String kilobytes = new DecimalFormat("###########0.00").format(kbytes);
            String nettime = new DecimalFormat("##########0.000").format(seconds);
            String persectime = new DecimalFormat("##########0.000").format(kbpersec);

            downloadPerfLog.info("Downloaded " + kilobytes + " kilobytes in " + nettime + " seconds ("
                    + persectime + "kb/s)");
        }

        catch (IOException e) {
            // HTTP request I/O error...

            throw new NetworkException("Download of Beehive archive failed : {0}", e, e.getMessage());
        }
    }

    // Assuming 404 indicates a new user... quietly return, nothing to download...

    // TODO : MODELER-286

    else if (httpResponseCode == HttpURLConnection.HTTP_NOT_FOUND) {
        serviceLog.info("No user data found. Return code 404. Assuming new user account...");

        return;
    }

    else {
        // TODO :
        //
        //   Currently assumes any other HTTP return code is a standard network error.
        //   This could be improved by handling more specific error codes (some are
        //   fatal, some are recoverable) such as 500 Internal Error (permanent) or
        //   307 Temporary Redirect
        //
        // TODO :
        //
        //   Should handle authentication errors in their own branch, not in this generic block

        throw new NetworkException(
                "Failed to download Beehive archive from URL ''{0}'' {1}, " + "HTTP Response code: {2}",

                beehiveArchiveURI, printUser(userAccount), httpResponseCode);
    }
}

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

@Test
public void testSlaveHttp() throws Exception {
    Configuration conf = new Configuration();
    String confDir = createTestDir();
    conf.set(WebServerTask.AUTHENTICATION_KEY, "none");
    conf.set(WebServerTask.HTTP_PORT_KEY, 0);
    conf.set(WebServerTask.HTTPS_PORT_KEY, -1);
    final WebServerTask ws = createSlaveWebServerTask(confDir, conf);
    try {/*from   w w w.  ja va 2  s  . c o  m*/
        ws.initTask();
        new Thread() {
            @Override
            public void run() {
                ws.runTask();
            }
        }.start();
        waitForStart(ws);
        HttpURLConnection conn = (HttpURLConnection) new URL(
                "http://127.0.0.1:" + ws.getServerURI().getPort() + "/ping").openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        Assert.assertNull(runtimeInfo.getSSLContext());
    } finally {
        ws.stopTask();
    }
}

From source file:com.aokyu.dev.pocket.PocketClient.java

public AddResponse add(AccessToken accessToken, AddRequest addRequest)
        throws IOException, InvalidRequestException, PocketException {
    String endpoint = PocketServer.getEndpoint(RequestType.ADD);
    URL requestUrl = new URL(endpoint);
    HttpHeaders headers = new HttpHeaders();
    headers.put(HttpHeader.CONTENT_TYPE, ContentType.JSON_WITH_UTF8.get());
    headers.put(HttpHeader.X_ACCEPT, ContentType.JSON.get());
    headers.put(HttpHeader.HOST, requestUrl.getHost());

    addRequest.put(AddRequest.Parameter.ACCESS_TOKEN, accessToken.get());
    addRequest.put(AddRequest.Parameter.CONSUMER_KEY, mConsumerKey.get());

    HttpParameters parameters = addRequest.getHttpParameters();

    HttpRequest request = new HttpRequest(HttpMethod.POST, requestUrl, headers, parameters);

    HttpResponse response = null;//from  w w w .  j a va  2  s  . c o  m
    JSONObject jsonObj = null;
    Map<String, List<String>> responseHeaders = null;
    try {
        response = mClient.execute(request);
        if (response.getStatusCode() == HttpURLConnection.HTTP_OK) {
            jsonObj = response.getResponseAsJSONObject();
            responseHeaders = response.getHeaderFields();
        } else {
            ErrorResponse error = new ErrorResponse(response);
            mErrorHandler.handleResponse(error);
        }
    } catch (JSONException e) {
        throw new PocketException(e.getMessage());
    } finally {
        if (response != null) {
            response.disconnect();
        }
    }

    AddResponse addResponse = null;
    if (jsonObj != null) {
        try {
            addResponse = new AddResponse(jsonObj, responseHeaders);
        } catch (JSONException e) {
            throw new PocketException(e.getMessage());
        }
    }

    return addResponse;
}

From source file:com.lucidworks.security.authentication.client.KerberosAuthenticator.java

/**
 * Performs SPNEGO authentication against the specified URL.
 * <p/>//  w ww.  j av  a 2s .  c  om
 * 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();

        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);
            return;
        } else if (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:org.openremote.android.test.console.net.ORConnectionTest.java

/**
 * Tests a basic GET through {@link ORConnection#checkURLWithHTTPProtocol} method. Attempts to
 * reach the welcome page of a publicly deployed controller.
 *
 * @throws IOException see checkURLWithHTTPProtocol javadoc for details
 *//*from  w w  w.  j  av  a 2  s  . c  om*/
public void testURLConnectionBasicGET() throws IOException {
    HttpResponse response = ORConnection.checkURLWithHTTPProtocol(activity, ORHttpMethod.GET,
            TEST_CONTROLLER_URL, NO_HTTP_AUTH);

    assertNotNullResponse(response, TEST_CONTROLLER_URL);
    assertHttpReturnCode(response, HttpURLConnection.HTTP_OK);
    assertNotZeroResponseBody(response);
    assertHttpContentType(response, TEXTHTML_MIME_TYPE);
}

From source file:com.epam.catgenome.manager.externaldb.HttpDataManager.java

private String getHttpResult(final int status, final String location, final HttpURLConnection conn)
        throws IOException, ExternalDbUnavailableException {
    String result;/*  w w w.ja va2  s  .co m*/
    if (status == HttpURLConnection.HTTP_OK) {
        LOGGER.info("HTTP_OK reply from destination server");

        InputStream inputStream = conn.getInputStream();
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();

        String inputStr;
        while ((inputStr = streamReader.readLine()) != null) {
            responseStrBuilder.append(inputStr);
        }

        result = responseStrBuilder.toString();

    } else {

        LOGGER.severe("Unexpected HTTP status:" + conn.getResponseMessage() + " for " + location);
        throw new ExternalDbUnavailableException(String.format("Unexpected HTTP status: %d %s for URL %s",
                status, conn.getResponseMessage(), location));

    }
    return result;
}

From source file:com.trafficspaces.api.controller.Connector.java

public String sendRequest(String path, String contentType, String method, String data)
        throws IOException, TrafficspacesAPIException {

    URL url = new URL(endPoint.baseURI + path);

    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    httpCon.setDoOutput(true);/*from w  w w. ja va  2 s  .  c om*/
    httpCon.setRequestMethod(method.toUpperCase());

    String basicAuth = "Basic " + Base64.encodeBytes((endPoint.username + ":" + endPoint.password).getBytes());
    httpCon.setRequestProperty("Authorization", basicAuth);

    httpCon.setRequestProperty("Content-Type", contentType + "; charset=UTF-8");
    httpCon.setRequestProperty("Accept", contentType);

    if (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT")) {
        httpCon.setRequestProperty("Content-Length", String.valueOf(data.length()));
        OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
        out.write(data);
        out.close();
    } else {
        httpCon.connect();
    }

    char[] responseData = null;
    try {
        responseData = readResponseData(httpCon.getInputStream(), "UTF-8");
    } catch (FileNotFoundException fnfe) {
        // HTTP 404. Ignore and return null
    }
    String responseDataString = null;
    if (responseData != null) {
        int responseCode = httpCon.getResponseCode();
        String redirectURL = null;
        if ((responseCode == HttpURLConnection.HTTP_MOVED_PERM
                || responseCode == HttpURLConnection.HTTP_MOVED_PERM
                || responseCode == HttpURLConnection.HTTP_CREATED)
                && (redirectURL = httpCon.getHeaderField("Location")) != null) {
            //System.out.println("Response code = " +responseCode + ". Redirecting to " + redirectURL);
            return sendRequest(redirectURL, contentType);
        }
        if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_CREATED) {
            throw new TrafficspacesAPIException(
                    "HTTP Error: " + responseCode + "; Data: " + new String(responseData));
        }
        //System.out.println("Headers: " + httpCon.getHeaderFields());
        //System.out.println("Data: " + new String(responseData));
        responseDataString = new String(responseData);
    }
    return responseDataString;
}

From source file:jetbrains.buildServer.commitPublisher.github.api.impl.GitHubApiImpl.java

@NotNull
private <T> T processResponse(@NotNull HttpUriRequest request, @NotNull final Class<T> clazz)
        throws IOException {
    setDefaultHeaders(request);/*from   w  w w.j  a  v  a 2s  .co  m*/
    try {
        logRequest(request, null);

        final HttpResponse execute = myClient.execute(request);
        if (execute.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) {
            logFailedResponse(request, null, execute);
            throw new IOException("Failed to complete request to GitHub. Status: " + execute.getStatusLine());
        }

        final HttpEntity entity = execute.getEntity();
        if (entity == null) {
            logFailedResponse(request, null, execute);
            throw new IOException(
                    "Failed to complete request to GitHub. Empty response. Status: " + execute.getStatusLine());
        }

        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            entity.writeTo(bos);
            final String json = bos.toString("utf-8");
            LOG.debug("Parsing json for " + request.getURI().toString() + ": " + json);
            return myGson.fromJson(json, clazz);
        } finally {
            EntityUtils.consume(entity);
        }
    } finally {
        request.abort();
    }
}

From source file:i5.las2peer.services.loadStoreGraphService.LoadStoreGraphService.java

/**
 * //www.j  a  v  a2 s  . c o m
 * loadGraph
 * 
 * @param id a String
 * 
 * @return HttpResponse
 * 
 */
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.TEXT_PLAIN)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "graphNotFound"),
        @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "graphLoaded"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "internalError") })
@ApiOperation(value = "loadGraph", notes = "")
public HttpResponse loadGraph(@PathParam("id") String id) {
    String result = "";
    String columnName = "";
    String selectquery = "";
    int columnCount = 0;
    Connection conn = null;
    PreparedStatement stmnt = null;
    ResultSet rs = null;
    ResultSetMetaData rsmd = null;
    try {
        // get connection from connection pool
        conn = dbm.getConnection();
        selectquery = "SELECT * FROM graphs WHERE graphId = " + id + " ;";

        // prepare statement
        stmnt = conn.prepareStatement(selectquery);

        // retrieve result set
        rs = stmnt.executeQuery();
        rsmd = (ResultSetMetaData) rs.getMetaData();
        columnCount = rsmd.getColumnCount();
        // process result set
        if (rs.next()) {
            JSONObject ro = new JSONObject();
            for (int i = 1; i <= columnCount; i++) {
                result = rs.getString(i);
                columnName = rsmd.getColumnName(i);
                // setup resulting JSON Object
                ro.put(columnName, result);
            }
            HttpResponse graphLoaded = new HttpResponse(ro.toJSONString(), HttpURLConnection.HTTP_OK);
            return graphLoaded;
        } else {
            // return HTTP Response on error
            String er = "No result for graph with id " + id;
            HttpResponse graphNotFound = new HttpResponse(er, HttpURLConnection.HTTP_NOT_FOUND);
            return graphNotFound;
        }

    } catch (Exception e) {
        String er = "Internal error: " + e.getMessage();
        HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR);
        return internalError;
    } finally {
        // free resources
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                Context.logError(this, e.getMessage());
                String er = "Internal error: " + e.getMessage();
                HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR);
                return internalError;
            }
        }
        if (stmnt != null) {
            try {
                stmnt.close();
            } catch (Exception e) {
                Context.logError(this, e.getMessage());
                String er = "Internal error: " + e.getMessage();
                HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR);
                return internalError;
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                Context.logError(this, e.getMessage());
                String er = "Internal error: " + e.getMessage();
                HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR);
                return internalError;
            }
        }
    }
}