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.stackmob.example.CreateVerifiedUser.java

@Override
public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) {

    String username = "";
    String password = "";
    String uuid = "";

    LoggerService logger = serviceProvider.getLoggerService(com.stackmob.example.CreateVerifiedUser.class);
    //Log the JSON object passed to the StackMob Logs
    logger.debug(request.getBody());//w  w w .  jav  a2 s .c o m

    // I'll be using these maps to print messages to console as feedback to the operation
    Map<String, SMValue> feedback = new HashMap<String, SMValue>();
    Map<String, String> errMap = new HashMap<String, String>();

    JSONParser parser = new JSONParser();
    try {
        Object obj = parser.parse(request.getBody());
        JSONObject jsonObject = (JSONObject) obj;

        //We use the username passed to query the StackMob datastore
        //and retrieve the user's name and email address
        username = (String) jsonObject.get("username");
        password = (String) jsonObject.get("password");
        uuid = (String) jsonObject.get("uuid");
    } catch (ParseException e) {
        return Util.internalErrorResponse("parse_exception", e, errMap); // error 500
    }

    if (Util.hasNulls(username, password, uuid)) {
        return Util.badRequestResponse(errMap);
    }

    // get the StackMob datastore service and assemble the query
    DataService dataService = serviceProvider.getDataService();

    // build a query
    List<SMCondition> query = new ArrayList<SMCondition>();
    query.add(new SMEquals("username", new SMString(username)));
    query.add(new SMEquals("uuid", new SMString(uuid)));

    List<SMObject> result;

    try {
        // return results from unverified user query
        result = dataService.readObjects("user_unverified", query);
        if (result != null && result.size() == 1) {

            SMObject newUserObject;

            try {
                // Create new User
                Map<String, SMValue> objMap = new HashMap<String, SMValue>();
                objMap.put("username", new SMString(username));
                objMap.put("password", new SMString(password));
                newUserObject = dataService.createObject("user", new SMObject(objMap));

                feedback.put("user_created", new SMString(newUserObject.toString()));

            } catch (InvalidSchemaException e) {
                return Util.internalErrorResponse("invalid_schema", e, errMap); // error 500 // http 500 - internal server error
            } catch (DatastoreException e) {
                return Util.internalErrorResponse("datastore_exception", e, errMap); // http 500 - internal server error
            } catch (Exception e) {
                return Util.internalErrorResponse("unknown_exception", e, errMap); // http 500 - internal server error
            }
        }
    } catch (InvalidSchemaException e) {
        return Util.internalErrorResponse("invalid_schema", e, errMap); // error 500 // http 500 - internal server error
    } catch (DatastoreException e) {
        return Util.internalErrorResponse("datastore_exception", e, errMap); // http 500 - internal server error
    } catch (Exception e) {
        return Util.internalErrorResponse("unknown_exception", e, errMap); // http 500 - internal server error
    }

    return new ResponseToProcess(HttpURLConnection.HTTP_OK, feedback);
}

From source file:com.alphabetbloc.accessmrs.tasks.CheckConnectivityTask.java

protected DataInputStream getServerStream() throws Exception {

    HttpPost request = new HttpPost(mServer);
    request.setEntity(new OdkAuthEntity());
    HttpResponse response = httpClient.execute(request);
    response.getStatusLine().getStatusCode();
    HttpEntity responseEntity = response.getEntity();
    responseEntity.getContentLength();//from w w  w  .jav a 2 s.c om

    DataInputStream zdis = new DataInputStream(new GZIPInputStream(responseEntity.getContent()));

    int status = zdis.readInt();
    if (status == HttpURLConnection.HTTP_UNAUTHORIZED) {
        zdis.close();
        throw new IOException("Access denied. Check your username and password.");
    } else if (status <= 0 || status >= HttpURLConnection.HTTP_BAD_REQUEST) {
        zdis.close();
        throw new IOException("Connection Failed. Please Try Again.");
    } else {
        assert (status == HttpURLConnection.HTTP_OK); // success
        return zdis;
    }
}

From source file:com.netflix.genie.server.resources.ApplicationConfigResource.java

/**
 * Get Application for given id.// w  ww. j  a  va 2s  .c  o m
 *
 * @param id unique id for application configuration
 * @return The application configuration
 * @throws GenieException For any error
 */
@GET
@Path("/{id}")
@ApiOperation(value = "Find an application by id", notes = "Get the application by id if it exists", response = Application.class)
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "OK", response = Application.class),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Application not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid id supplied"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public Application getApplication(
        @ApiParam(value = "Id of the application to get.", required = true) @PathParam("id") final String id)
        throws GenieException {
    LOG.info("Called to get Application for id " + id);
    return this.applicationConfigService.getApplication(id);
}

From source file:com.stackmob.example.SendGrid.java

@Override
public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) {
    int responseCode = 0;
    String responseBody = "";
    String username = "";
    String subject = "";
    String text = "";
    String from = "";
    String to = "";
    String toname = "";
    String body = "";
    String url = "";

    LoggerService logger = serviceProvider.getLoggerService(SendGrid.class);
    //Log the JSON object passed to the StackMob Logs
    logger.debug(request.getBody());//www . j  a  v a  2s . c o m

    JSONParser parser = new JSONParser();
    try {
        Object obj = parser.parse(request.getBody());
        JSONObject jsonObject = (JSONObject) obj;

        //We use the username passed to query the StackMob datastore
        //and retrieve the user's name and email address
        username = (String) jsonObject.get("username");

        // The following values could be static or dynamic
        subject = (String) jsonObject.get("subject");
        text = (String) jsonObject.get("text");
        from = (String) jsonObject.get("from");
    } catch (ParseException e) {
        logger.error(e.getMessage(), e);
        responseCode = -1;
        responseBody = e.getMessage();
    }

    if (username == null || username.isEmpty()) {
        HashMap<String, String> errParams = new HashMap<String, String>();
        errParams.put("error", "the username passed was empty or null");
        return new ResponseToProcess(HttpURLConnection.HTTP_BAD_REQUEST, errParams); // http 400 - bad request
    }

    // get the StackMob datastore service and assemble the query
    DataService dataService = serviceProvider.getDataService();

    // build a query
    List<SMCondition> query = new ArrayList<SMCondition>();
    query.add(new SMEquals("username", new SMString(username)));

    SMObject userObject;
    List<SMObject> result;
    try {
        // return results from user query
        result = dataService.readObjects("user", query);
        if (result != null && result.size() == 1) {
            userObject = result.get(0);
            to = userObject.getValue().get("email").toString();
            toname = userObject.getValue().get("name").toString();
        } else {
            HashMap<String, String> errMap = new HashMap<String, String>();
            errMap.put("error", "no user found");
            errMap.put("detail", "no matches for the username passed");
            return new ResponseToProcess(HttpURLConnection.HTTP_OK, errMap); // http 500 - internal server error
        }

    } catch (InvalidSchemaException e) {
        HashMap<String, String> errMap = new HashMap<String, String>();
        errMap.put("error", "invalid_schema");
        errMap.put("detail", e.toString());
        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errMap); // http 500 - internal server error
    } catch (DatastoreException e) {
        HashMap<String, String> errMap = new HashMap<String, String>();
        errMap.put("error", "datastore_exception");
        errMap.put("detail", e.toString());
        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errMap); // http 500 - internal server error
    } catch (Exception e) {
        HashMap<String, String> errMap = new HashMap<String, String>();
        errMap.put("error", "unknown");
        errMap.put("detail", e.toString());
        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errMap); // http 500 - internal server error
    }

    if (subject == null || subject.equals("")) {
        logger.error("Subject is missing");
    }

    //Encode any parameters that need encoding (i.e. subject, toname, text)
    try {
        subject = URLEncoder.encode(subject, "UTF-8");
        text = URLEncoder.encode(text, "UTF-8");
        toname = URLEncoder.encode(toname, "UTF-8");

    } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage(), e);
    }

    String queryParams = "api_user=" + API_USER + "&api_key=" + API_KEY + "&to=" + to + "&toname=" + toname
            + "&subject=" + subject + "&text=" + text + "&from=" + from;

    url = "https://www.sendgrid.com/api/mail.send.json?" + queryParams;

    Header accept = new Header("Accept-Charset", "utf-8");
    Header content = new Header("Content-Type", "application/x-www-form-urlencoded");

    Set<Header> set = new HashSet();
    set.add(accept);
    set.add(content);

    try {
        HttpService http = serviceProvider.getHttpService();

        PostRequest req = new PostRequest(url, set, body);

        HttpResponse resp = http.post(req);
        responseCode = resp.getCode();
        responseBody = resp.getBody();

    } catch (TimeoutException e) {
        logger.error(e.getMessage(), e);
        responseCode = -1;
        responseBody = e.getMessage();

    } catch (AccessDeniedException e) {
        logger.error(e.getMessage(), e);
        responseCode = -1;
        responseBody = e.getMessage();

    } catch (MalformedURLException e) {
        logger.error(e.getMessage(), e);
        responseCode = -1;
        responseBody = e.getMessage();

    } catch (ServiceNotActivatedException e) {
        logger.error(e.getMessage(), e);
        responseCode = -1;
        responseBody = e.getMessage();
    }

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("response_body", responseBody);

    return new ResponseToProcess(responseCode, map);
}

From source file:com.polyvi.xface.extension.advancedfiletransfer.XFileDownloader.java

/**
 * ??(?????/* ww w.jav  a2 s  .com*/
 * ??????)
 */
private void initDownloadInfo() {
    int totalSize = 0;
    if (isFirst(mUrl)) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(mUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(TIME_OUT_MILLISECOND);
            connection.setRequestMethod("GET");
            System.getProperties().setProperty("http.nonProxyHosts", url.getHost());
            //cookie?
            setCookieProperty(connection, mUrl);
            if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
                totalSize = connection.getContentLength();
                if (-1 != totalSize) {
                    mDownloadInfo = new XFileDownloadInfo(totalSize, 0, mUrl);
                    // ?mDownloadInfo??
                    mFileTransferRecorder.saveDownloadInfo(mDownloadInfo);
                } else {
                    XLog.e(CLASS_NAME, "cannot get totalSize");
                }
                // temp
                File file = new File(mLocalFilePath + TEMP_FILE_SUFFIX);
                if (file.exists()) {
                    file.delete();
                }
            }
        } catch (IOException e) {
            XLog.e(CLASS_NAME, e.getMessage());
        } finally {
            if (null != connection) {
                connection.disconnect();
            }
        }
    } else {
        // ?url?
        mDownloadInfo = mFileTransferRecorder.getDownloadInfo(mUrl);
        totalSize = mDownloadInfo.getTotalSize();
        mDownloadInfo.setCompleteSize(getCompleteSize(mLocalFilePath + TEMP_FILE_SUFFIX));
    }
    mBufferSize = getSingleTransferLength(totalSize);
}

From source file:hanulhan.cas.client.CasRestActions.java

public String doLoginCasRest() {

    jsonStatus = new JsonStatus();
    String myUrlParameters = "username=uhansen01&password=Ava030374Lon_";
    CookieHandler.setDefault(new CookieManager());
    StringBuilder myResult;/*from  w  w  w  .  j  av a  2 s .c om*/
    String myServiceTicketUrl = null;
    String myTgt = "";
    String myServiceTicket = "";
    List<NameValuePair> postParams = new ArrayList<>();
    HttpResponse myResponse;

    // GET the TGT
    try {
        myResponse = sendPost(CAS_SERVER_URL + "/v1/tickets?" + myUrlParameters, postParams);
        if (myResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_CREATED) {
            myResult = getHttpResponseResult(myResponse);
            if (myResult != null && myResult.length() > 0) {
                myServiceTicketUrl = getServiceTicketUrl(myResult.toString());
                if (myServiceTicketUrl != null && myServiceTicketUrl.length() > 0) {
                    LOGGER.log(Level.INFO, "ServiceTicketURL: " + myServiceTicketUrl);
                    myTgt = getTGT(myServiceTicketUrl);
                    if (myTgt != null && myTgt.length() > 0) {
                        LOGGER.log(Level.INFO, "TGT: " + myTgt);
                    }
                }
            } else {
                LOGGER.log(Level.ERROR, "Status Code: " + myResponse.getStatusLine().getStatusCode());
            }
        }
    } catch (Exception ex) {
        LOGGER.log(Level.ERROR, ex);
    }

    // Get the ServiceTicket
    try {
        if (myTgt != null && myTgt.length() > 0) {
            postParams.add(new BasicNameValuePair("service", CAS_SERVICE));
            myResponse = sendPost(myServiceTicketUrl, postParams);
            if (myResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
                myServiceTicket = getHttpResponseResult(myResponse).toString();
                LOGGER.log(Level.INFO, "ServiceTicket: " + myServiceTicket);
                redirectUrl = GET_URL + "?authServiceTicket=" + myServiceTicket + "&authService=" + CAS_SERVICE;
                LOGGER.log(Level.INFO, "ServiceURL: " + redirectUrl);
            }
        }
    } catch (Exception ex) {
        LOGGER.log(Level.ERROR, ex);
    }

    return SUCCESS;

}

From source file:org.ow2.proactive_grid_cloud_portal.rm.RMRestTest.java

@Test
public void testShutdown_NoPreemptParameter() throws Exception {
    RMProxyUserInterface rm = mock(RMProxyUserInterface.class);
    when(rm.shutdown(false)).thenReturn(new BooleanWrapper(true));

    String sessionId = SharedSessionStoreTestUtils.createValidSession(rm);
    HttpResponse response = callHttpGetMethod("shutdown", sessionId);

    assertEquals(HttpURLConnection.HTTP_OK, response.getStatusLine().getStatusCode());
    verify(rm).shutdown(false);/*from  w ww.  ja  v a  2 s.  c  om*/
}

From source file:com.nimbits.user.GoogleAuthentication.java

private Cookie getAuthCookie(final String gaeAppBaseUrl, final String gaeAppLoginUrl, final String authToken)
        throws NimbitsException {
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    Cookie retObj = null;/*ww w  .  ja  va2 s .  c om*/
    final String cookieUrl;
    try {
        cookieUrl = gaeAppLoginUrl + "?continue=" + URLEncoder.encode(gaeAppBaseUrl, Const.CONST_ENCODING)
                + "&auth=" + URLEncoder.encode(authToken, Const.CONST_ENCODING);

        //
        //      String cookieUrl = gaeAppLoginUrl + "?continue="
        //      + URLEncoder.encode(gaeAppBaseUrl,Const.CONST_ENCODING) + "&auth=" + authToken;
        //httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
        final HttpGet httpget = new HttpGet(cookieUrl);
        final HttpResponse response = httpClient.execute(httpget);

        if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK
                || response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_NO_CONTENT) {

            for (final Cookie cookie : httpClient.getCookieStore().getCookies()) {
                if (cookie.getName().equals(Parameters.acsid.getText())) {
                    retObj = cookie;
                    break;
                }

            }
        } else if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) {
            throw new NimbitsException("invalid token");

        } else {
            throw new NimbitsException(
                    "Error getting cookie: status code:" + response.getStatusLine().getStatusCode());
        }

        httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
    } catch (UnsupportedEncodingException e) {
        throw new NimbitsException(e.getMessage());
    } catch (ClientProtocolException e) {
        throw new NimbitsException(e.getMessage());
    } catch (IOException e) {
        throw new NimbitsException(e.getMessage());
    }

    return retObj;

}

From source file:de.unidue.inf.is.ezdl.dlservices.library.manager.referencesystems.bibsonomy.BibsonomyUtils.java

/** send a POST request and return the response as string */
String sendPutRequest(String url, String bodytext) throws Exception {
    String sresponse;/* w  ww . j  a va2  s. c  o m*/

    HttpClient httpclient = new DefaultHttpClient();
    HttpPut httpput = new HttpPut(url);

    // add authorization header
    httpput.addHeader("Authorization", authHeader);

    StringEntity body = new StringEntity(bodytext);
    httpput.setEntity(body);

    HttpResponse response = httpclient.execute(httpput);

    // check statuscode
    if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK
            || response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_CREATED) {
        HttpEntity entity = response.getEntity();
        sresponse = readResponseStream(entity.getContent());
        httpclient.getConnectionManager().shutdown();
    } else {
        HttpEntity entity = response.getEntity();
        sresponse = readResponseStream(entity.getContent());
        String httpcode = Integer.toString(response.getStatusLine().getStatusCode());
        httpclient.getConnectionManager().shutdown();
        throw new ReferenceSystemException(httpcode, "Bibsonomy Error", XMLUtils.parseError(sresponse));
    }
    return sresponse;

}