Example usage for java.net HttpURLConnection HTTP_UNAUTHORIZED

List of usage examples for java.net HttpURLConnection HTTP_UNAUTHORIZED

Introduction

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

Prototype

int HTTP_UNAUTHORIZED

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

Click Source Link

Document

HTTP Status-Code 401: Unauthorized.

Usage

From source file:org.sofun.core.security.oauth.OAuthSofunProvider.java

@Override
public void checkTimestamp(OAuthToken token, long timestamp) throws OAuthException {
    if (token.getTimestamp() > timestamp)
        throw new OAuthException(HttpURLConnection.HTTP_UNAUTHORIZED, "Invalid timestamp " + timestamp);
}

From source file:i5.las2peer.services.gamificationApplicationService.GamificationApplicationService.java

/**
 * Create a new app// w w  w .  j a  v  a  2 s.c om
 * 
 * @param contentType form content type
 * @param formData form data
 * @return Application data in JSON
 */
@POST
@Path("/data")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "createApplication", notes = "Method to create a new application")
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Cannot connect to database"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Database Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Error in parsing form data"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "App ID already exist"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "App ID cannot be empty"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Error checking app ID exist"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"),
        @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "New application created") })
public HttpResponse createApplication(
        @ApiParam(value = "Application detail in multiple/form-data type", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType,
        @ApiParam(value = "Content of form data", required = true) @ContentParam byte[] formData) {

    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/applications/data");
    long randomLong = new Random().nextLong(); //To be able to match 

    JSONObject objResponse = new JSONObject();
    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    String appid = null;
    String appdesc = null;
    String commtype = null;
    Connection conn = null;

    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }

    Map<String, FormDataPart> parts;
    try {
        conn = dbm.getConnection();

        parts = MultipartHelper.getParts(formData, contentType);
        FormDataPart partAppID = parts.get("appid");
        if (partAppID != null) {
            // these data belong to the (optional) file id text input form element
            appid = partAppID.getContent();
            // appid must be unique
            System.out.println(appid);
            if (applicationAccess.isAppIdExist(conn, appid)) {
                // app id already exist
                objResponse.put("message", "App ID already exist");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }

            FormDataPart partAppDesc = parts.get("appdesc");
            if (partAppDesc != null) {
                appdesc = partAppDesc.getContent();
            } else {
                appdesc = "";
            }
            FormDataPart partCommType = parts.get("commtype");
            if (partAppDesc != null) {
                commtype = partCommType.getContent();
            } else {
                commtype = "def_type";
            }

            ApplicationModel newApp = new ApplicationModel(appid, appdesc, commtype);

            try {
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_1, "" + randomLong);
                applicationAccess.addNewApplication(conn, newApp);
                applicationAccess.addMemberToApp(conn, newApp.getId(), name);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_2, "" + randomLong);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_3, "" + name);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_4, "" + newApp.getId());

                objResponse.put("message", "New application created");
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_CREATED);

            } catch (SQLException e) {
                e.printStackTrace();
                objResponse.put("message", "Cannot Add New Application. Database Error. " + e.getMessage());
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
        } else {
            // app id cannot be empty
            objResponse.put("message", "Cannot Add New Application. App ID cannot be empty.");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
        }
    } catch (IOException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot Add New Application. Error in parsing form data. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (SQLException e) {
        e.printStackTrace();
        objResponse.put("message",
                "Cannot Add New Application. Error checking app ID exist. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }
}

From source file:co.cask.cdap.client.rest.RestStreamClientTest.java

@Test
public void testNotAuthorizedUnknownTokenSetTTL() throws IOException {
    AuthenticationClient authClient = Mockito.mock(AuthenticationClient.class);
    AccessToken accessToken = Mockito.mock(AccessToken.class);
    Mockito.when(authClient.getAccessToken()).thenReturn(accessToken);
    Mockito.when(accessToken.getValue()).thenReturn("test");
    Mockito.when(accessToken.getTokenType()).thenReturn("Bearer");
    streamClient = RestStreamClient.builder(testServerHost, testServerPort).authClient(authClient).build();
    try {//from  w  w  w.j ava  2s .  co  m
        streamClient.setTTL(TestUtils.AUTH_STREAM_NAME, STREAM_TTL);
        Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
        Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, e.getStatusCode());
    }
}

From source file:me.philio.ghost.ui.LoginFragment.java

@Override
public void failure(RetrofitError error) {
    Log.d(TAG, "Authentication failed");

    // Parse error JSON
    ErrorResponse errorResponse = (ErrorResponse) error.getBodyAs(ErrorResponse.class);

    // Extract the first error message (at time of writing there is only ever one)
    String errorMsg = null;/*  w  w w  .  j a v  a  2  s .c o m*/
    if (errorResponse != null && errorResponse.errors != null && errorResponse.errors.size() > 0) {
        String rawMsg = errorResponse.errors.get(0).message;
        errorMsg = Html.fromHtml(rawMsg).toString();
    }

    // Show user an error
    int status = 0;
    if (error.getResponse() != null) {
        status = error.getResponse().getStatus();
    }
    switch (status) {
    case HttpURLConnection.HTTP_NOT_FOUND:
        mEditEmail.setError(errorMsg != null ? errorMsg : getString(R.string.error_incorrect_email));
        break;
    case HttpURLConnection.HTTP_FORBIDDEN:
        mEditEmail.setError(errorMsg != null ? errorMsg : getString(R.string.error_incorrect_email));
        break;
    case HttpURLConnection.HTTP_UNAUTHORIZED:
        mEditPassword.setError(errorMsg != null ? errorMsg : getString(R.string.error_invalid_password));
        break;
    }

    // Enable button and hide progress bar
    mBtnLogin.setEnabled(true);
    ((LoginActivity) getActivity()).setToolbarProgressBarVisibility(false);
}

From source file:org.openmrs.web.filter.initialization.TestInstallUtil.java

/**
 * @param urlString//w w  w . ja  v  a  2  s. c  o m
 * @param openmrsUsername
 * @param openmrsPassword
 * @return input stream
 * @throws MalformedURLException
 * @throws IOException
 */
protected static InputStream getResourceInputStream(String urlString, String openmrsUsername,
        String openmrsPassword) throws MalformedURLException, IOException, APIException {

    HttpURLConnection urlConnection = (HttpURLConnection) new URL(urlString).openConnection();
    urlConnection.setRequestMethod("POST");
    urlConnection.setConnectTimeout(15000);
    urlConnection.setUseCaches(false);
    urlConnection.setDoOutput(true);

    String requestParams = "username=" + Base64.encode(openmrsUsername.getBytes(Charset.forName("UTF-8")))
            + "&password=" + Base64.encode(openmrsPassword.getBytes(Charset.forName("UTF-8")));

    OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
    out.write(requestParams);
    out.flush();
    out.close();

    if (log.isInfoEnabled()) {
        log.info("Http response message:" + urlConnection.getResponseMessage() + ", Code:"
                + urlConnection.getResponseCode());
    }

    if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
        throw new APIAuthenticationException("Invalid username or password");
    } else if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) {
        throw new APIException("error.occurred.on.remote.server", (Object[]) null);
    }

    return urlConnection.getInputStream();
}

From source file:i5.las2peer.services.gamificationGamifierService.GamificationGamifierService.java

@POST
@Path("/repo")
@Produces(MediaType.APPLICATION_JSON)/*  w w  w.j  a v  a2s .com*/
@ApiOperation(value = "memberLoginValidation", notes = "Simple function to validate a member login.")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Member is registered"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "User data error to be retrieved"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Cannot connect to database"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "User data error to be retrieved. Not JSON object") })
public HttpResponse updateRepository(
        @ApiParam(value = "Data in JSON", required = true) @ContentParam byte[] contentB) {
    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/gamifier/repo");
    long randomLong = new Random().nextLong(); //To be able to match
    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    // take username as default name
    String name = userAgent.getLoginName();
    System.out.println("User name : " + name);
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }

    L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_9, "" + randomLong);

    JSONObject objResponse = new JSONObject();
    String content = new String(contentB);
    if (content.equals(null)) {
        objResponse.put("message", "Cannot update repository. Cannot parse json data into string");
        //L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        L2pLogger.logEvent(this, Event.AGENT_UPLOAD_FAILED, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    }

    //      if(!initializeDBConnection()){
    //         objResponse.put("message", "Cannot connect to database");
    //         L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
    //         return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    //      }

    JSONObject obj;
    String originRepositoryName;
    String newRepositoryName;
    String fileContent;
    String appId;
    String epURL;
    String aopScript;

    try {
        obj = (JSONObject) JSONValue.parseWithException(content);
        originRepositoryName = stringfromJSON(obj, "originRepositoryName");
        newRepositoryName = stringfromJSON(obj, "newRepositoryName");
        //fileContent = stringfromJSON(obj,"fileContent");
        appId = stringfromJSON(obj, "appId");
        epURL = stringfromJSON(obj, "epURL");
        aopScript = stringfromJSON(obj, "aopScript");
    } catch (ParseException e) {
        e.printStackTrace();
        objResponse.put("message",
                "Cannot update repository. Cannot parse json data into string. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (IOException e) {
        e.printStackTrace();
        objResponse.put("message",
                "Cannot update repository. Cannot parse json data into string. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
    // check if repo exist
    TreeWalk treeWalk = null;
    Repository newRepository = null;
    Repository originRepository = null;

    // helper variables
    // variables holding content to be modified and added to repository later
    String widget = null;
    try {
        RepositoryHelper.deleteRemoteRepository(newRepositoryName, gitHubOrganizationNewRepo, gitHubUserNewRepo,
                gitHubPasswordNewRepo);
    } catch (GitHubException e) {
        //e.printStackTrace();      
    }

    try {

        PersonIdent caeUser = new PersonIdent(gitHubUserNewRepo, gitHubUserMailNewRepo);

        originRepository = RepositoryHelper.getRemoteRepository(originRepositoryName, gitHubOrganizationOrigin);
        newRepository = RepositoryHelper.generateNewRepository(newRepositoryName, gitHubOrganizationNewRepo,
                gitHubUserNewRepo, gitHubPasswordNewRepo);
        File originDir = originRepository.getDirectory();
        // now load the TreeWalk containing the origin repository content
        treeWalk = RepositoryHelper.getRepositoryContent(originRepositoryName, gitHubOrganizationOrigin);

        //System.out.println("PATH " + treeWalk.getPathString());
        System.out.println("PATH2 " + originDir.getParent());
        System.out.println("PATH3 " + newRepository.getDirectory().getParent());
        // treeWalk.setFilter(PathFilter.create("frontend/"));
        ObjectReader reader = treeWalk.getObjectReader();
        // walk through the tree and retrieve the needed templates
        while (treeWalk.next()) {
            ObjectId objectId = treeWalk.getObjectId(0);
            ObjectLoader loader = reader.open(objectId);
            switch (treeWalk.getNameString()) {
            case "widget.xml":
                widget = new String(loader.getBytes(), "UTF-8");
                break;
            }
        }

        // replace widget.xml 
        //widget = createWidgetCode(widget, htmlElementTemplate, yjsImports, gitHubOrganization, repositoryName, frontendComponent);
        widget = RepositoryHelper.appendWidget(widget, gitHubOrganizationNewRepo, newRepositoryName);

        RepositoryHelper.copyFolder(originRepository.getDirectory().getParentFile(),
                newRepository.getDirectory().getParentFile());

        String aopfilestring = RepositoryHelper.readFile("../GamificationGamifierService/jsfiles/aop.pack.js",
                Charset.forName("UTF-8"));
        String oidcwidgetfilestring = RepositoryHelper
                .readFile("../GamificationGamifierService/jsfiles/oidc-widget.js", Charset.forName("UTF-8"));
        String gamifierstring = RepositoryHelper.readFile("../GamificationGamifierService/jsfiles/gamifier.js",
                Charset.forName("UTF-8"));

        gamifierstring = gamifierstring.replace("$Application_Id$", appId);
        gamifierstring = gamifierstring.replace("$Endpoint_URL$", epURL);
        gamifierstring = gamifierstring.replace("$AOP_Script$", aopScript);

        // add files to new repository
        newRepository = RepositoryHelper.createTextFileInRepository(newRepository, "", "widget.xml", widget);
        newRepository = RepositoryHelper.createTextFileInRepository(newRepository, "gamification/",
                "aop.pack.js", aopfilestring);
        newRepository = RepositoryHelper.createTextFileInRepository(newRepository, "gamification/",
                "oidc-widget.js", oidcwidgetfilestring);
        newRepository = RepositoryHelper.createTextFileInRepository(newRepository, "gamification/",
                "gamifier.js", gamifierstring);

        // stage file
        Git.wrap(newRepository).add().addFilepattern(".").call();

        // commit files
        Git.wrap(newRepository).commit().setMessage("Generated new repo  ").setCommitter(caeUser).call();

        // push (local) repository content to GitHub repository "gh-pages" branch
        RepositoryHelper.pushToRemoteRepository(newRepository, gitHubUserNewRepo, gitHubPasswordNewRepo,
                "master", "gh-pages");

        // close all open resources
    } catch (GitHubException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        objResponse.put("message", "Cannot update repository. Github exception. " + e1.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (IOException e1) {
        e1.printStackTrace();
        objResponse.put("message", "Cannot update repository. Github exception. " + e1.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (Exception e) {
        objResponse.put("message", "Cannot update repository. Github exception. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } finally {
        newRepository.close();
        originRepository.close();
        treeWalk.close();
    }

    objResponse.put("message", "Updated");
    L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_10, "" + randomLong);
    L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_22, "" + appId);
    L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_23, "" + name);

    return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);

}

From source file:org.jboss.test.web.test.WebIntegrationUnitTestCase.java

/** Access the http://{host}/jbosstest/restricted/SecureServlet
 *///from w w w.  j a v a  2s  . c o m
public void testSecureServletWithNoLogin() throws Exception {
    String baseURL = "http://" + getServerHost() + ":" + Integer.getInteger("web.port", 8080) + '/';
    URL url = new URL(baseURL + "jbosstest/restricted/SecureServlet");
    HttpUtils.accessURL(url, REALM, HttpURLConnection.HTTP_UNAUTHORIZED);
}

From source file:org.eclipse.hono.client.impl.HonoClientImpl.java

private void connect(final ProtonClientOptions options,
        final Handler<AsyncResult<HonoClient>> connectionHandler,
        final Handler<ProtonConnection> disconnectHandler) {

    context.runOnContext(connect -> {

        if (isConnectedInternal()) {
            LOG.debug("already connected to server [{}:{}]", connectionFactory.getHost(),
                    connectionFactory.getPort());
            connectionHandler.handle(Future.succeededFuture(this));
        } else if (connecting.compareAndSet(false, true)) {

            if (options == null) {
                // by default, try to re-connect forever
                clientOptions = new ProtonClientOptions().setConnectTimeout(200).setReconnectAttempts(-1)
                        .setReconnectInterval(Constants.DEFAULT_RECONNECT_INTERVAL_MILLIS);
            } else {
                clientOptions = options;
            }/*from  w w w .j  a  va2  s .c  om*/

            connectionFactory.connect(clientOptions,
                    remoteClose -> onRemoteClose(remoteClose, disconnectHandler),
                    failedConnection -> onRemoteDisconnect(failedConnection, disconnectHandler), conAttempt -> {
                        connecting.compareAndSet(true, false);
                        if (conAttempt.failed()) {
                            if (conAttempt.cause() instanceof SecurityException) {
                                // SASL handshake has failed
                                connectionHandler.handle(Future.failedFuture(
                                        new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED,
                                                "failed to authenticate with server")));
                            } else {
                                reconnect(conAttempt.cause(), connectionHandler, disconnectHandler);
                            }
                        } else {
                            // make sure we try to re-connect as often as we tried to connect initially
                            reconnectAttempts = new AtomicInteger(0);
                            final ProtonConnection newConnection = conAttempt.result();
                            if (shuttingDown.get()) {
                                // if client was shut down in the meantime, we need to immediately
                                // close again the newly created connection
                                newConnection.closeHandler(null);
                                newConnection.disconnectHandler(null);
                                newConnection.close();
                                connectionHandler.handle(Future.failedFuture(new ClientErrorException(
                                        HttpURLConnection.HTTP_CONFLICT, "client is already shut down")));
                            } else {
                                setConnection(newConnection);
                                connectionHandler.handle(Future.succeededFuture(this));
                            }
                        }
                    });
        } else {
            LOG.debug("already trying to connect to server ...");
            connectionHandler.handle(Future.failedFuture(
                    new ClientErrorException(HttpURLConnection.HTTP_CONFLICT, "already connecting to server")));
        }
    });
}

From source file:net.mceoin.cominghome.api.NestUtil.java

private static String getNestAwayStatusCall(String access_token) {

    String away_status = "";

    String urlString = "https://developer-api.nest.com/structures?auth=" + access_token;
    log.info("url=" + urlString);

    StringBuilder builder = new StringBuilder();
    boolean error = false;
    String errorResult = "";

    HttpURLConnection urlConnection = null;
    try {/*w  ww . ja v a  2 s .c om*/
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0");
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setConnectTimeout(15000);
        urlConnection.setReadTimeout(15000);
        //            urlConnection.setChunkedStreamingMode(0);

        //            urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8");

        boolean redirect = false;

        // normally, 3xx is redirect
        int status = urlConnection.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == 307 // Temporary redirect
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        //            System.out.println("Response Code ... " + status);

        if (redirect) {

            // get redirect url from "location" header field
            String newUrl = urlConnection.getHeaderField("Location");

            // open the new connnection again
            urlConnection = (HttpURLConnection) new URL(newUrl).openConnection();
            urlConnection.setRequestMethod("PUT");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            //                urlConnection.setChunkedStreamingMode(0);

            //                System.out.println("Redirect to URL : " + newUrl);

        }

        int statusCode = urlConnection.getResponseCode();

        log.info("statusCode=" + statusCode);
        if ((statusCode == HttpURLConnection.HTTP_OK)) {
            error = false;

            InputStream response;
            response = urlConnection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            log.info("response=" + builder.toString());
            JSONObject object = new JSONObject(builder.toString());

            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                JSONObject structure = object.getJSONObject(key);

                if (structure.has("away")) {
                    away_status = structure.getString("away");
                } else {
                    log.info("missing away");
                }
            }

        } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            // bad auth
            error = true;
            errorResult = "Unauthorized";
        } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) {
            error = true;
            InputStream response;
            response = urlConnection.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            log.info("response=" + builder.toString());
            JSONObject object = new JSONObject(builder.toString());

            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("error")) {
                    // error = Internal Error on bad structure_id
                    errorResult = object.getString("error");
                    log.info("errorResult=" + errorResult);
                }
            }
        } else {
            error = true;
            errorResult = Integer.toString(statusCode);
        }

    } catch (IOException e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("IOException: " + errorResult);
    } catch (Exception e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("Exception: " + errorResult);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }

    if (error)
        away_status = "Error: " + errorResult;
    return away_status;
}

From source file:com.flurry.proguard.UploadProGuardMapping.java

/**
 * Ensure that a response had an expected status
 *
 * @param response the API response//from ww w  .  j a v a2s . c o  m
 * @param validStatuses the list of acceptable statuses
 */
private static void expectStatus(HttpResponse response, Integer... validStatuses) {
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        failWithError("The provided token is expired");
    }
    if (!Arrays.asList(validStatuses).contains(statusCode)) {
        String responseString;
        try {
            responseString = "Response Body: " + EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            responseString = "IO Exception while reading the response body.";
        }
        failWithError("Request failed: {} {}", statusCode, responseString);
    }
}