Example usage for org.springframework.http HttpStatus UNAUTHORIZED

List of usage examples for org.springframework.http HttpStatus UNAUTHORIZED

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus UNAUTHORIZED.

Prototype

HttpStatus UNAUTHORIZED

To view the source code for org.springframework.http HttpStatus UNAUTHORIZED.

Click Source Link

Document

401 Unauthorized .

Usage

From source file:org.springframework.social.twitter.api.impl.TwitterErrorHandler.java

private void handleClientErrors(ClientHttpResponse response) throws IOException {
    HttpStatus statusCode = response.getStatusCode();
    Map<String, Object> errorMap = extractErrorDetailsFromResponse(response);

    String errorText = "";
    if (errorMap.containsKey("error")) {
        errorText = (String) errorMap.get("error");
    } else if (errorMap.containsKey("errors")) {
        Object errors = errorMap.get("errors");
        if (errors instanceof List) {
            @SuppressWarnings("unchecked")
            List<Map<String, String>> errorsList = (List<Map<String, String>>) errors;
            errorText = errorsList.get(0).get("message");
        } else if (errors instanceof String) {
            errorText = (String) errors;
        }/*from  ww  w . ja v  a2s . com*/
    }

    if (statusCode == HttpStatus.BAD_REQUEST) {
        if (errorText.contains("Rate limit exceeded.")) {
            throw new RateLimitExceededException("twitter");
        }
    } else if (statusCode == HttpStatus.UNAUTHORIZED) {
        if (errorText == null) {
            throw new NotAuthorizedException("twitter", response.getStatusText());
        } else if (errorText.equals("Could not authenticate you.")) {
            throw new MissingAuthorizationException("twitter");
        } else if (errorText.equals("Could not authenticate with OAuth.")) { // revoked token
            throw new RevokedAuthorizationException("twitter");
        } else if (errorText.equals("Invalid / expired Token")) { // Note that Twitter doesn't actually expire tokens
            throw new InvalidAuthorizationException("twitter", errorText);
        } else {
            throw new NotAuthorizedException("twitter", errorText);
        }
    } else if (statusCode == HttpStatus.FORBIDDEN) {
        if (errorText.equals(DUPLICATE_STATUS_TEXT) || errorText.contains("You already said that")) {
            throw new DuplicateStatusException("twitter", errorText);
        } else if (errorText.equals(STATUS_TOO_LONG_TEXT) || errorText.contains(MESSAGE_TOO_LONG_TEXT)) {
            throw new MessageTooLongException(errorText);
        } else if (errorText.equals(INVALID_MESSAGE_RECIPIENT_TEXT)) {
            throw new InvalidMessageRecipientException(errorText);
        } else if (errorText.equals(DAILY_RATE_LIMIT_TEXT)) {
            throw new RateLimitExceededException("twitter");
        } else {
            throw new OperationNotPermittedException("twitter", errorText);
        }
    } else if (statusCode == HttpStatus.NOT_FOUND) {
        throw new ResourceNotFoundException("twitter", errorText);
    } else if (statusCode == HttpStatus.valueOf(ENHANCE_YOUR_CALM)
            || statusCode == HttpStatus.valueOf(TOO_MANY_REQUESTS)) {
        throw new RateLimitExceededException("twitter");
    }

}

From source file:org.venice.beachfront.bfapi.services.GeoServerProxyService.java

public ResponseEntity<byte[]> proxyRequest(HttpServletRequest request)
        throws MalformedURLException, IOException, URISyntaxException, UserException {
    String requestPath = request.getRequestURI();
    // Form the complete URI by piecing together the GeoServer URL with the API proxy request parameters
    URI requestUri = new URI(geoserverUrl.getProtocol(), null, geoserverUrl.getHost(), geoserverUrl.getPort(),
            requestPath, request.getQueryString(), null);
    // Double encoding takes place here. First, in the REST Request delivered to API by the client. Second, in the
    // translation to the URI object. Decode both of these steps to get the real, completely decoded request to
    // GeoServer.
    String decodedUrl = URLDecoder.decode(requestUri.toString(), "UTF-8");
    decodedUrl = URLDecoder.decode(decodedUrl.toString(), "UTF-8");
    piazzaLogger.log(String.format("Proxying request to GET GeoServer at URI %s", decodedUrl),
            Severity.INFORMATIONAL);
    try {/*from w  ww  .  ja v  a  2s.co  m*/
        ResponseEntity<byte[]> response = restTemplate.exchange(decodedUrl, HttpMethod.GET, requestHeaders,
                byte[].class);
        return response;
    } catch (HttpClientErrorException | HttpServerErrorException exception) {
        piazzaLogger.log(String.format("Received GeoServer error response, code=%d, length=%d, for URI %s",
                exception.getStatusCode().value(), exception.getResponseBodyAsString().length(), decodedUrl),
                Severity.ERROR);
        if (exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)
                || exception.getStatusCode().equals(HttpStatus.FORBIDDEN)) {
            throw new UserException("Bad Authentication with GeoServer", exception,
                    exception.getResponseBodyAsString(), HttpStatus.BAD_REQUEST);
        }
        throw new UserException("Upstream GeoServer error", exception, exception.getResponseBodyAsString(),
                exception.getStatusCode());
    }
}

From source file:org.venice.beachfront.bfapi.services.IABrokerPassthroughService.java

public ResponseEntity<String> passthroughRequest(HttpMethod method, HttpServletRequest request)
        throws MalformedURLException, IOException, URISyntaxException, UserException {
    // URI to ia-Broker will strip out the /ia prefix that the bf-api uses to denote ia-broker proxying
    // Single data source right now, which is planet. In the future, we will switch on the sensor/item type to
    // determine the source (or have the source just injected)
    String requestPath = request.getRequestURI().replaceAll("/ia/", "/");
    URI uri = new URI(IA_BROKER_PROTOCOL, null, IA_BROKER_SERVER, IA_BROKER_PORT, requestPath,
            request.getQueryString(), null);
    String body = IOUtils.toString(request.getReader());
    piazzaLogger.log(String.format("Proxying request to IA Broker at URI %s", uri.toString()),
            Severity.INFORMATIONAL);
    try {//from w  ww. ja v a  2  s. c o m
        ResponseEntity<String> response = restTemplate.exchange(uri, method, new HttpEntity<String>(body),
                String.class);
        piazzaLogger.log(
                String.format("Received IA Broker response, code=%d, length=%d, for URI %s",
                        response.getStatusCodeValue(),
                        response.getBody() == null ? 0 : response.getBody().length(), uri.toString()),
                Severity.INFORMATIONAL);
        return response;
    } catch (HttpClientErrorException | HttpServerErrorException exception) {
        piazzaLogger.log(String.format("Received IA Broker error response, code=%d, length=%d, for URI %s",
                exception.getStatusCode().value(), exception.getResponseBodyAsString().length(),
                uri.toString()), Severity.ERROR);
        if (exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)
                || exception.getStatusCode().equals(HttpStatus.FORBIDDEN)) {
            throw new UserException(exception.getResponseBodyAsString(), exception,
                    exception.getResponseBodyAsString(), HttpStatus.PRECONDITION_FAILED);
        }
        throw new UserException("Upstream image broker error", exception, exception.getResponseBodyAsString(),
                exception.getStatusCode());
    }
}

From source file:org.venice.beachfront.bfapi.services.OAuthServiceTests.java

@Test
public void testRequestAccessTokenUserError() {
    String mockAuthCode = "mock-auth-code-123";

    Mockito.when(this.restTemplate.exchange(Mockito.eq(this.oauthTokenUrl), Mockito.eq(HttpMethod.POST),
            Mockito.any(), Mockito.eq(AccessTokenResponseBody.class)))
            .then(new Answer<ResponseEntity<AccessTokenResponseBody>>() {
                @Override/* w  w  w .  ja  va  2 s .co m*/
                public ResponseEntity<AccessTokenResponseBody> answer(InvocationOnMock invocation) {
                    throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED);
                }
            });

    try {
        oauthService.requestAccessToken(mockAuthCode);
        fail("request should not have succeeded");
    } catch (UserException ex) {
        assertEquals(HttpStatus.UNAUTHORIZED, ex.getRecommendedStatusCode());
    }
}

From source file:org.venice.beachfront.bfapi.services.OAuthServiceTests.java

@Test
public void testRequestOAuthProfileUserError() {
    String mockAccessToken = "mock-access-token-321";

    Mockito.when(this.restTemplate.exchange(Mockito.eq(this.oauthProfileUrl), Mockito.eq(HttpMethod.GET),
            Mockito.any(), Mockito.eq(String.class))).then(new Answer<ResponseEntity<String>>() {
                @Override/*from w  w w  .  j  a v  a 2 s.c o m*/
                public ResponseEntity<String> answer(InvocationOnMock invocation) {
                    throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED);
                }
            });

    try {
        oauthService.requestOAuthProfile(mockAccessToken);
        fail("request should not have succeeded");
    } catch (UserException ex) {
        assertEquals(HttpStatus.UNAUTHORIZED, ex.getRecommendedStatusCode());
    }
}

From source file:org.venice.beachfront.bfapi.services.PiazzaService.java

/**
 * Gets the status of the Piazza Job with the specified Job ID
 * /* w ww.  java 2 s .com*/
 * @param jobId
 *            The Job ID
 * @return The status of the Job, as returned by Piazza
 */
public StatusMetadata getJobStatus(String jobId) throws UserException {
    String piazzaJobUrl = String.format("%s/job/%s", PIAZZA_URL, jobId);
    piazzaLogger.log(String.format("Checking Piazza Job Status for Job %s", jobId), Severity.INFORMATIONAL);
    HttpHeaders headers = createPiazzaHeaders(PIAZZA_API_KEY);
    HttpEntity<String> request = new HttpEntity<>(headers);

    // Execute the Request
    ResponseEntity<String> response = null;
    try {
        response = restTemplate.exchange(URI.create(piazzaJobUrl), HttpMethod.GET, request, String.class);
    } catch (HttpClientErrorException | HttpServerErrorException exception) {
        HttpStatus recommendedErrorStatus = exception.getStatusCode();
        if (recommendedErrorStatus.equals(HttpStatus.UNAUTHORIZED)) {
            recommendedErrorStatus = HttpStatus.BAD_REQUEST; // 401 Unauthorized logs out the client, and we don't
            // want that
        }

        String message = String.format("There was an error fetching Job Status from Piazza. (%d) id=%s",
                exception.getStatusCode().value(), jobId);

        throw new UserException(message, exception.getMessage(), recommendedErrorStatus);
    }

    // Parse out the Status from the Response
    try {
        JsonNode responseJson = objectMapper.readTree(response.getBody());
        StatusMetadata status = new StatusMetadata(responseJson.get("data").get("status").asText());
        // Parse additional information depending on status
        if (status.isStatusSuccess()) {
            // If the status is complete, attach the Data ID of the shoreline detection
            status.setDataId(responseJson.get("data").get("result").get("dataId").asText());
        } else if (status.isStatusError()) {
            // If the status is errored, then attach the error information
            JsonNode messageNode = responseJson.get("data").get("message");
            if (messageNode != null) {
                status.setErrorMessage(messageNode.asText());
            } else {
                status.setErrorMessage(
                        "The Job contained an Error status but the cause was unable to be parsed from the response object.");
            }
            // If there is a detailed error message available in the Result field Data ID, fetch that ID.
            JsonNode resultNode = responseJson.get("data").get("result");
            if (resultNode != null && resultNode.get("dataId") != null) {
                status.setDataId(resultNode.get("dataId").asText());
            }
        }
        return status;
    } catch (IOException | NullPointerException exception) {
        String error = String
                .format("There was an error parsing the Piazza response when Requesting Job %s Status.", jobId);
        piazzaLogger.log(error, Severity.ERROR);
        throw new UserException(error, exception.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.venice.beachfront.bfapi.services.PiazzaService.java

/**
 * Returns the list of all algorithm services that have been registed with the Beachfront Piazza API Key
 * //ww w.  jav a2s  .  c o m
 * @return List of algorithms available for use in Beachfront
 */
public List<Algorithm> getRegisteredAlgorithms() throws UserException {
    String piazzaServicesUrl = String.format("%s/service/me", PIAZZA_URL);
    piazzaLogger.log("Checking Piazza Registered Algorithms.", Severity.INFORMATIONAL);
    HttpHeaders headers = createPiazzaHeaders(PIAZZA_API_KEY);
    HttpEntity<String> request = new HttpEntity<>(headers);

    // Execute the Request
    ResponseEntity<String> response = null;
    try {
        response = restTemplate.exchange(URI.create(piazzaServicesUrl), HttpMethod.GET, request, String.class);
    } catch (HttpClientErrorException | HttpServerErrorException exception) {
        piazzaLogger.log(String.format("Error fetching Algorithms from Piazza with Code %s, Response was %s",
                exception.getStatusText(), exception.getResponseBodyAsString()), Severity.ERROR);

        HttpStatus recommendedErrorStatus = exception.getStatusCode();
        if (recommendedErrorStatus.equals(HttpStatus.UNAUTHORIZED)) {
            recommendedErrorStatus = HttpStatus.BAD_REQUEST; // 401 Unauthorized logs out the client, and we don't
            // want that
        }

        String message = String.format("There was an error fetching Algorithm List from Piazza. (%d)",
                exception.getStatusCode().value());
        throw new UserException(message, exception.getMessage(), recommendedErrorStatus);
    }

    // Ensure the response succeeded
    if (!response.getStatusCode().is2xxSuccessful()) {
        // Error occurred - report back to the user
        throw new UserException("Piazza returned a non-OK status when requesting registered Algorithm List.",
                response.getStatusCode().toString(), response.getStatusCode());
    }

    // Parse out the Algorithms from the Response
    try {
        JsonNode responseJson = objectMapper.readTree(response.getBody());
        JsonNode algorithmJsonArray = responseJson.get("data");
        List<Algorithm> algorithms = new ArrayList<>();
        for (JsonNode algorithmJson : algorithmJsonArray) {
            // For each Registered Service, wrap it in the Algorithm Object and add to the list
            algorithms.add(getAlgorithmFromServiceNode(algorithmJson));
        }
        piazzaLogger.log(
                String.format("Returning full Piazza algorithm list. Found %s Algorithms.", algorithms.size()),
                Severity.INFORMATIONAL);
        return algorithms;
    } catch (IOException exception) {
        String error = "There was an error parsing the Piazza response when Requesting registered Algorithm List.";
        piazzaLogger.log(error, Severity.ERROR);
        throw new UserException(error, exception.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.venice.beachfront.bfapi.services.PiazzaService.java

/**
 * Gets the registered algorithm from Piazza based on the Service ID. This can return services that are not owned by
 * the currently configured Piazza API Key
 * /*from   www. j  av  a2s  .com*/
 * @param serviceId
 *            Service ID to fetch
 * @return The Service
 */
public Algorithm getRegisteredAlgorithm(String serviceId) throws UserException {
    String piazzaServiceUrl = String.format("%s/service/%s", PIAZZA_URL, serviceId);
    piazzaLogger.log(String.format("Checking Piazza Registered Algorithm %s.", serviceId),
            Severity.INFORMATIONAL);
    HttpHeaders headers = createPiazzaHeaders(PIAZZA_API_KEY);
    HttpEntity<String> request = new HttpEntity<>(headers);

    // Execute the Request
    ResponseEntity<String> response = null;
    try {
        response = restTemplate.exchange(URI.create(piazzaServiceUrl), HttpMethod.GET, request, String.class);
    } catch (HttpClientErrorException | HttpServerErrorException exception) {
        piazzaLogger.log(
                String.format("Error fetching Algorithm %s from Piazza with Code %s, Response was %s",
                        serviceId, exception.getStatusText(), exception.getResponseBodyAsString()),
                Severity.ERROR);

        HttpStatus recommendedErrorStatus = exception.getStatusCode();
        if (recommendedErrorStatus.equals(HttpStatus.UNAUTHORIZED)) {
            recommendedErrorStatus = HttpStatus.BAD_REQUEST; // 401 Unauthorized logs out the client, and we don't
            // want that
        }

        String message = String.format("There was an error fetching Algorithm from Piazza. (%d) id=%s",
                exception.getStatusCode().value(), serviceId);
        throw new UserException(message, exception.getMessage(), recommendedErrorStatus);
    }

    // Ensure the response succeeded
    if (!response.getStatusCode().is2xxSuccessful()) {
        // Error occurred - report back to the user
        throw new UserException(String
                .format("Piazza returned a non-OK status when requesting registered Algorithm %s.", serviceId),
                response.getStatusCode().toString(), response.getStatusCode());
    }

    // Parse out the Algorithms from the Response
    try {
        JsonNode responseJson = objectMapper.readTree(response.getBody());
        JsonNode algorithmJson = responseJson.get("data");
        return getAlgorithmFromServiceNode(algorithmJson);
    } catch (IOException exception) {
        String error = String.format(
                "There was an error parsing the Piazza response when Requesting registered Algorithm %s.",
                serviceId);
        piazzaLogger.log(error, Severity.ERROR);
        throw new UserException(error, exception.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.venice.beachfront.bfapi.services.PiazzaService.java

/**
 * Calls the data/file endpoint to download data from Piazza for the specified Data ID.
 * <p>//  w w  w  .j  a  v a  2s.  c o m
 * Piazza Data IDs for a successful job are the raw GeoJSON of the shoreline detection vectors for a successful Job
 * execution.
 * <p>
 * Piazza Data IDs for an unsuccessful job will contain the detailed JSON information for an error message on an
 * algorithm execution. This contains the stack trace and other information from the algorithm itself that details
 * the errors.
 * 
 * @param dataId
 *            Data ID
 * @return The bytes of the ingested data
 */
public byte[] downloadData(String dataId) throws UserException {
    String piazzaDataUrl = String.format("%s/file/%s", PIAZZA_URL, dataId);
    piazzaLogger.log(String.format("Requesting data %s bytes from Piazza at %s", dataId, piazzaDataUrl),
            Severity.INFORMATIONAL);
    HttpHeaders headers = createPiazzaHeaders(PIAZZA_API_KEY);
    HttpEntity<String> request = new HttpEntity<>(headers);

    // Execute the Request
    ResponseEntity<String> response = null;
    try {
        response = restTemplate.exchange(URI.create(piazzaDataUrl), HttpMethod.GET, request, String.class);
    } catch (HttpClientErrorException | HttpServerErrorException exception) {
        piazzaLogger.log(
                String.format(
                        "Error downloading Data Bytes for Data %s from Piazza. Failed with Code %s and Body %s",
                        dataId, exception.getStatusText(), exception.getResponseBodyAsString()),
                Severity.ERROR);

        HttpStatus recommendedErrorStatus = exception.getStatusCode();
        if (recommendedErrorStatus.equals(HttpStatus.UNAUTHORIZED)) {
            recommendedErrorStatus = HttpStatus.BAD_REQUEST; // 401 Unauthorized logs out the client, and we don't
            // want that
        }

        String message = String.format(
                "There was an upstream error fetching data bytes from Piazza. (%d) id=%s",
                exception.getStatusCode().value(), dataId);

        throw new UserException(message, exception.getMessage(), recommendedErrorStatus);
    }

    byte[] data = response.getBody().getBytes();
    piazzaLogger.log(String.format("Successfully retrieved Bytes for Data %s from Piazza. File size was %s",
            dataId, data.length), Severity.INFORMATIONAL);
    return data;
}

From source file:org.venice.beachfront.bfapi.services.PiazzaService.java

/**
 * Returns all of the Statistics for the Beachfront Algorithm as reported by the Piazza Task-Managed service.
 * /*from  w  w w .ja v  a2s. c o  m*/
 * @return JSON block containing statistics. This contains, at least, the number of jobs in that algorithms queue.
 */
public JsonNode getAlgorithmStatistics(String algorithmId) throws UserException {
    String piazzaTaskUrl = String.format("%s/service/%s/task/metadata", PIAZZA_URL, algorithmId);
    piazzaLogger.log(
            String.format("Fetching Algorithm Tasks Metadata for %s at URL %s", algorithmId, piazzaTaskUrl),
            Severity.INFORMATIONAL);
    HttpHeaders headers = createPiazzaHeaders(PIAZZA_API_KEY);
    HttpEntity<String> request = new HttpEntity<>(headers);

    // Execute the Request
    ResponseEntity<String> response = null;
    try {
        response = restTemplate.exchange(URI.create(piazzaTaskUrl), HttpMethod.GET, request, String.class);
    } catch (HttpClientErrorException | HttpServerErrorException exception) {
        HttpStatus recommendedErrorStatus = exception.getStatusCode();
        if (recommendedErrorStatus.equals(HttpStatus.UNAUTHORIZED)) {
            recommendedErrorStatus = HttpStatus.BAD_REQUEST; // 401 Unauthorized logs out the client, and we don't
            // want that
        }

        String message = String.format("There was an error fetching Service Metadata from Piazza (%d) id=%s",
                exception.getStatusCode().value(), algorithmId);
        throw new UserException(message, exception.getMessage(), recommendedErrorStatus);
    }

    try {
        return objectMapper.readTree(response.getBody());
    } catch (IOException exception) {
        String error = String.format("There was an error parsing the Service Metadata for service %s.",
                algorithmId);
        piazzaLogger.log(error, Severity.ERROR);
        throw new UserException(error, exception, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}