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:co.cask.cdap.client.rest.RestStreamClientTest.java

@Test
public void testNotAuthorizedTruncate() throws IOException {
    try {//from   w  w  w  .  j a va2 s  . c om
        streamClient.truncate(TestUtils.AUTH_STREAM_NAME);
        Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
        Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, e.getStatusCode());
    }
}

From source file:org.apache.maven.wagon.providers.http.LightweightHttpWagon.java

public boolean resourceExists(String resourceName) throws TransferFailedException, AuthorizationException {
    HttpURLConnection headConnection;

    try {//www.  ja v a  2s  .  co  m
        URL url = new URL(buildUrl(new Resource(resourceName).getName()));
        headConnection = (HttpURLConnection) url.openConnection(this.proxy);

        addHeaders(headConnection);

        headConnection.setRequestMethod("HEAD");
        headConnection.setDoOutput(true);

        int statusCode = headConnection.getResponseCode();

        switch (statusCode) {
        case HttpURLConnection.HTTP_OK:
            return true;

        case HttpURLConnection.HTTP_FORBIDDEN:
            throw new AuthorizationException("Access denied to: " + url);

        case HttpURLConnection.HTTP_NOT_FOUND:
            return false;

        case HttpURLConnection.HTTP_UNAUTHORIZED:
            throw new AuthorizationException("Access denied to: " + url);

        default:
            throw new TransferFailedException(
                    "Failed to look for file: " + buildUrl(resourceName) + ". Return code is: " + statusCode);
        }
    } catch (IOException e) {
        throw new TransferFailedException("Error transferring file: " + e.getMessage(), e);
    }
}

From source file:org.openhab.binding.digitalstrom.internal.lib.manager.impl.ConnectionManagerImpl.java

@Override
public boolean checkConnection(int code) {
    switch (code) {
    case HttpURLConnection.HTTP_INTERNAL_ERROR:
    case HttpURLConnection.HTTP_OK:
        if (!connectionEstablished) {
            connectionEstablished = true;
            onConnectionResumed();//from w w  w .  java2 s  .c o  m
        }
        break;
    case HttpURLConnection.HTTP_UNAUTHORIZED:
        connectionEstablished = false;
        break;
    case HttpURLConnection.HTTP_FORBIDDEN:
        getNewSessionToken();
        if (sessionToken != null) {
            if (!connectionEstablished) {
                onConnectionResumed();
                connectionEstablished = true;
            }
        } else {
            if (this.genAppToken) {
                onNotAuthenticated();
            }
            connectionEstablished = false;
        }
        break;
    case ConnectionManager.MALFORMED_URL_EXCEPTION:
        onConnectionLost(ConnectionListener.INVALID_URL);
        connectionEstablished = false;
        break;
    case ConnectionManager.CONNECTION_EXCEPTION:
    case ConnectionManager.SOCKET_TIMEOUT_EXCEPTION:
        onConnectionLost(ConnectionListener.CONNECTON_TIMEOUT);
        connectionEstablished = false;
        break;
    case ConnectionManager.GENERAL_EXCEPTION:
        if (connListener != null) {
            connListener.onConnectionStateChange(ConnectionListener.CONNECTION_LOST);
        }
        break;
    case ConnectionManager.UNKNOWN_HOST_EXCEPTION:
        if (connListener != null) {
            onConnectionLost(ConnectionListener.UNKNOWN_HOST);
        }
        break;
    case ConnectionManager.AUTHENTIFICATION_PROBLEM:
        if (connListener != null) {
            if (config.getAppToken() != null) {
                connListener.onConnectionStateChange(ConnectionListener.NOT_AUTHENTICATED,
                        ConnectionListener.WRONG_APP_TOKEN);
            } else {
                connListener.onConnectionStateChange(ConnectionListener.NOT_AUTHENTICATED,
                        ConnectionListener.WRONG_USER_OR_PASSWORD);
            }
        }
        break;
    case HttpURLConnection.HTTP_NOT_FOUND:
        onConnectionLost(ConnectionListener.HOST_NOT_FOUND);
        connectionEstablished = false;
        break;
    }
    return connectionEstablished;
}

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

@Test
public void testNotAuthorizedEmptyTokenTruncate() 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(StringUtils.EMPTY);
    Mockito.when(accessToken.getTokenType()).thenReturn("Bearer");
    streamClient = RestStreamClient.builder(testServerHost, testServerPort).authClient(authClient).build();
    try {/*w ww.j  av a2  s  .  c o m*/
        streamClient.truncate(TestUtils.AUTH_STREAM_NAME);
        Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
        Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, e.getStatusCode());
    }
}

From source file:org.eclipse.mylyn.internal.gerrit.core.client.GerritHttpClient.java

public <T> T execute(Request<T> request, boolean authenticateIfNeeded, IProgressMonitor monitor)
        throws IOException, GerritException {
    String openIdProvider = getOpenIdProvider();

    hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor);

    for (int attempt = 0; attempt < 2; attempt++) {
        if (authenticateIfNeeded) {
            // force authentication
            if (needsAuthentication()) {
                AuthenticationCredentials credentials = location.getCredentials(AuthenticationType.REPOSITORY);
                if (openIdProvider != null || credentials != null) {
                    authenticate(openIdProvider, monitor);
                }// www.j  ava 2s.c o  m
            }
            if (!obtainedXsrfKey) {
                updateXsrfKey(monitor);
            }
        }

        HttpMethodBase method = request.createMethod();
        if (obtainedXsrfKey) {
            // required to authenticate against Gerrit 2.6+ REST endpoints
            // harmless in previous versions
            method.setRequestHeader(X_GERRIT_AUTHORITY, xsrfKey);
        }
        try {
            // Execute the method.
            WebUtil.execute(httpClient, hostConfiguration, method, monitor);
        } catch (IOException e) {
            WebUtil.releaseConnection(method, monitor);
            throw e;
        } catch (RuntimeException e) {
            WebUtil.releaseConnection(method, monitor);
            throw e;
        }

        int code = method.getStatusCode();
        if (code == HttpURLConnection.HTTP_OK || code == HttpURLConnection.HTTP_ACCEPTED
                || code == HttpURLConnection.HTTP_CREATED) {
            try {
                return request.process(method);
            } finally {
                WebUtil.releaseConnection(method, monitor);
            }
        } else if (code == HttpURLConnection.HTTP_NO_CONTENT) {
            try {
                return null;
            } finally {
                WebUtil.releaseConnection(method, monitor);
            }

        } else {
            try {
                request.handleError(method);
            } finally {
                WebUtil.releaseConnection(method, monitor);
            }
            if (code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN) {
                // login or re-authenticate due to an expired session
                authenticate(openIdProvider, monitor);
            } else {
                throw new GerritHttpException(code);
            }
        }
    }

    throw new GerritLoginException();
}

From source file:org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerRestClient.java

public boolean delete(String sessionId, String dataspacePath, String path, List<String> includes,
        List<String> excludes) throws Exception {
    StringBuffer uriTmpl = (new StringBuffer()).append(restEndpointURL)
            .append(addSlashIfMissing(restEndpointURL)).append("data/").append(dataspacePath).append('/');
    ResteasyClient client = new ResteasyClientBuilder().httpEngine(httpEngine).providerFactory(providerFactory)
            .build();/*from ww w .  j a va2s  .  co m*/
    ResteasyWebTarget target = client.target(uriTmpl.toString()).path(path);
    if (includes != null && !includes.isEmpty()) {
        target = target.queryParam("includes", includes.toArray(new Object[includes.size()]));
    }
    if (excludes != null && !excludes.isEmpty()) {
        target = target.queryParam("excludes", excludes.toArray(new Object[excludes.size()]));
    }
    Response response = null;
    try {
        response = target.request().header("sessionid", sessionId).delete();
        if (response.getStatus() != HttpURLConnection.HTTP_NO_CONTENT) {
            if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) {
                throw new NotConnectedRestException("User not authenticated or session timeout.");
            } else {
                throwException(String.format("Cannot delete file(s). Status code: %s", response.getStatus()),
                        response);
            }
        }
        return true;
    } finally {
        if (response != null) {
            response.close();
        }
    }
}

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

@Test
public void testNotAuthorizedUnknownTokenTruncate() 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 a v  a  2s  .com*/
        streamClient.truncate(TestUtils.AUTH_STREAM_NAME);
        Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
        Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, e.getStatusCode());
    }
}

From source file:i5.las2peer.services.gamificationLevelService.GamificationLevelService.java

/**
 * Get a level data with specific ID from database
 * @param appId applicationId//from  w  ww  .j av a  2  s.c om
 * @param levelNum level number
 * @return HttpResponse Returned as JSON object
 */
@GET
@Path("/{appId}/{levelNum}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Found a level"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "getlevelWithNum", notes = "Get level details with specific level number", response = LevelModel.class)
public HttpResponse getlevelWithNum(@ApiParam(value = "Application ID") @PathParam("appId") String appId,
        @ApiParam(value = "Level number") @PathParam("levelNum") int levelNum) {

    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99,
            "GET " + "gamification/levels/" + appId + "/" + levelNum);
    long randomLong = new Random().nextLong(); //To be able to match

    LevelModel level = null;
    Connection conn = null;

    JSONObject objResponse = new JSONObject();
    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    try {
        conn = dbm.getConnection();
        try {
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_16, "" + randomLong);

            try {
                if (!levelAccess.isAppIdExist(conn, appId)) {
                    objResponse.put("message", "Cannot fetched level. App not found");
                    L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                    return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
                }
            } catch (SQLException e1) {
                e1.printStackTrace();
                objResponse.put("message",
                        "Cannot fetched level. Cannot check whether application ID exist or not. Database error. "
                                + e1.getMessage());
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
            if (!levelAccess.isLevelNumExist(conn, appId, levelNum)) {
                objResponse.put("message", "Cannot fetched level. level not found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
            level = levelAccess.getLevelWithNumber(conn, appId, levelNum);
            if (level != null) {
                ObjectMapper objectMapper = new ObjectMapper();
                //Set pretty printing of json
                objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

                String levelString = objectMapper.writeValueAsString(level);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_17, "" + randomLong);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_26, "" + name);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_27, "" + appId);
                return new HttpResponse(levelString, HttpURLConnection.HTTP_OK);
            } else {
                objResponse.put("message", "Cannot fetched level. Cannot find level with " + levelNum);
                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 fetched level. DB Error. " + e.getMessage());
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);

        }

    } catch (JsonProcessingException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot fetched level. JSON processing error. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (SQLException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot fetched level. DB Error. " + 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:com.googlecode.batchfb.impl.Batch.java

/**
 * Constructs the batch query and executes it, possibly asynchronously.
 * @return an asynchronous handle to the raw batch result, whatever it may be.
 *//* w  w w. j  av a2 s  .c  o  m*/
private Later<JsonNode> createFetcher() {
    final RequestBuilder call = new GraphRequestBuilder(getGraphEndpoint(), HttpMethod.POST, this.timeout,
            this.retries);

    // This actually creates the correct JSON structure as an array
    String batchValue = JSONUtils.toJSON(this.graphRequests, this.mapper);
    if (log.isLoggable(Level.FINEST))
        log.finest("Batch request is: " + batchValue);

    this.addParams(call, new Param[] { new Param("batch", batchValue) });

    final HttpResponse response;
    try {
        response = call.execute();
    } catch (IOException ex) {
        throw new IOFacebookException(ex);
    }

    return new Later<JsonNode>() {
        @Override
        public JsonNode get() throws FacebookException {
            try {
                if (response.getResponseCode() == HttpURLConnection.HTTP_OK
                        || response.getResponseCode() == HttpURLConnection.HTTP_BAD_REQUEST
                        || response.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {

                    // If it was an error, we will recognize it in the content later.
                    // It's possible we should capture all 4XX codes here.
                    JsonNode result = mapper.readTree(response.getContentStream());

                    if (log.isLoggable(Level.FINEST))
                        log.finest("Response is: " + result);

                    return result;
                } else {
                    throw new IOFacebookException("Unrecognized error " + response.getResponseCode() + " from "
                            + call + " :: " + StringUtils.read(response.getContentStream()));
                }
            } catch (IOException e) {
                throw new IOFacebookException("Error calling " + call, e);
            }
        }
    };
}

From source file:fi.cosky.sdk.API.java

private <T extends BaseData> T sendRequestWithAddedHeaders(Verb verb, String url, Class<T> tClass,
        Object object, HashMap<String, String> headers) throws IOException {
    URL serverAddress;//from w  ww.  j a  v a  2 s  .  co m
    HttpURLConnection connection;
    BufferedReader br;
    String result = "";
    try {
        serverAddress = new URL(url);
        connection = (HttpURLConnection) serverAddress.openConnection();
        connection.setInstanceFollowRedirects(false);
        boolean doOutput = doOutput(verb);
        connection.setDoOutput(doOutput);
        connection.setRequestMethod(method(verb));
        connection.setRequestProperty("Authorization", headers.get("authorization"));
        connection.addRequestProperty("Accept", "application/json");

        if (doOutput) {
            connection.addRequestProperty("Content-Length", "0");
            OutputStreamWriter os = new OutputStreamWriter(connection.getOutputStream());
            os.write("");
            os.flush();
            os.close();
        }
        connection.connect();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER
                || connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
            Link location = parseLocationLinkFromString(connection.getHeaderField("Location"));
            Link l = new Link("self", "/tokens", "GET", "", true);
            ArrayList<Link> links = new ArrayList<Link>();
            links.add(l);
            links.add(location);
            ResponseData data = new ResponseData();
            data.setLocation(location);
            data.setLinks(links);
            return (T) data;
        }

        if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            System.out.println("Authentication expired: " + connection.getResponseMessage());
            if (retry && this.tokenData != null) {
                retry = false;
                this.tokenData = null;
                if (authenticate()) {
                    System.out.println(
                            "Reauthentication success, will continue with " + verb + " request on " + url);
                    return sendRequestWithAddedHeaders(verb, url, tClass, object, headers);
                }
            } else
                throw new IOException(
                        "Tried to reauthenticate but failed, please check the credentials and status of NFleet-API");
        }

        if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST
                && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) {
            System.out.println("ErrorCode: " + connection.getResponseCode() + " "
                    + connection.getResponseMessage() + " " + url + ", verb: " + verb);

            String errorString = readErrorStreamAndCloseConnection(connection);
            throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class);
        } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) {
            if (retry) {
                System.out.println("Server responded with internal server error, trying again in "
                        + RETRY_WAIT_TIME + " msec.");
                try {
                    retry = false;
                    Thread.sleep(RETRY_WAIT_TIME);
                    return sendRequestWithAddedHeaders(verb, url, tClass, object, headers);
                } catch (InterruptedException e) {

                }
            } else {
                System.out.println("Server responded with internal server error, please contact dev@nfleet.fi");
            }

            String errorString = readErrorStreamAndCloseConnection(connection);
            throw new IOException(errorString);
        }

        result = readDataFromConnection(connection);
    } catch (MalformedURLException e) {
        throw e;
    } catch (ProtocolException e) {
        throw e;
    } catch (UnsupportedEncodingException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    }
    return (T) gson.fromJson(result, tClass);
}