Java Code Examples for org.eclipse.jetty.http.HttpStatus#OK_200

The following examples show how to use org.eclipse.jetty.http.HttpStatus#OK_200 . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DomainQuotaRoutes.java    From james-project with Apache License 2.0 6 votes vote down vote up
@GET
@ApiOperation(
    value = "Reading count and size at the same time",
    notes = "If there is no limitation for count and/or size, the returned value will be -1"
)
@ApiResponses(value = {
        @ApiResponse(code = HttpStatus.OK_200, message = "OK", response = QuotaDomainDTO.class),
        @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "The requested domain can not be found."),
        @ApiResponse(code = HttpStatus.METHOD_NOT_ALLOWED_405, message = "Domain Quota configuration not supported when virtual hosting is desactivated."),
        @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "Internal server error - Something went bad on the server side.")
})
public void defineGetQuota() {
    service.get(QUOTA_ENDPOINT, (request, response) -> {
        Domain domain = checkDomainExist(request);
        return domainQuotaService.getQuota(domain);
    }, jsonTransformer);
}
 
Example 2
Source File: DomainMappingsRoutes.java    From james-project with Apache License 2.0 6 votes vote down vote up
@GET
@Path(DOMAIN_MAPPINGS)
@ApiOperation(value = "Lists all domain mappings.")
@ApiResponses(value = {
    @ApiResponse(code = HttpStatus.OK_200, message = "Domain mappings.", responseContainer = "Map"),
    @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500,
        message = "Internal server error - Something went bad on the server side.")
})
public Map<String, List<String>> getAllMappings(Request request, Response response) throws RecipientRewriteTableException {
    return recipientRewriteTable.getAllMappings()
        .entrySet()
        .stream()
        .filter(mappingsEntry -> mappingsEntry.getValue().contains(Mapping.Type.Domain))
        .collect(Guavate.toImmutableMap(
            mappingsEntry -> mappingsEntry.getKey().getFixedDomain(),
            mappingsEntry -> toDomainList(mappingsEntry.getValue())
        ));
}
 
Example 3
Source File: DomainQuotaRoutes.java    From james-project with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/size")
@ApiOperation(value = "Reading per domain mail size limitation")
@ApiResponses(value = {
        @ApiResponse(code = HttpStatus.OK_200, message = "OK", response = Long.class),
        @ApiResponse(code = HttpStatus.NO_CONTENT_204, message = "No value defined"),
        @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "The requested domain can not be found."),
        @ApiResponse(code = HttpStatus.METHOD_NOT_ALLOWED_405, message = "Domain Quota configuration not supported when virtual hosting is desactivated."),
        @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "Internal server error - Something went bad on the server side.")
})
public void defineGetQuotaSize() {
    service.get(SIZE_ENDPOINT, (request, response) -> {
        Domain domain = checkDomainExist(request);
        Optional<QuotaSizeLimit> maxSizeQuota = domainQuotaService.getMaxSizeQuota(domain);
        if (maxSizeQuota.isPresent()) {
            return maxSizeQuota;
        }
        return Responses.returnNoContent(response);
    }, jsonTransformer);
}
 
Example 4
Source File: MailQueueRoutes.java    From james-project with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/{mailQueueName}")
@ApiImplicitParams({
    @ApiImplicitParam(required = true, dataType = "string", name = "mailQueueName", paramType = "path")
})
@ApiOperation(
    value = "Get a MailQueue details"
)
@ApiResponses(value = {
    @ApiResponse(code = HttpStatus.OK_200, message = "OK", response = MailQueueDTO.class),
    @ApiResponse(code = HttpStatus.BAD_REQUEST_400, message = "Invalid request for getting the mail queue."),
    @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "The MailQueue does not exist."),
    @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "Internal server error - Something went bad on the server side.")
})
public void getMailQueue(Service service) {
    service.get(BASE_URL + SEPARATOR + MAIL_QUEUE_NAME,
        (request, response) -> getMailQueue(request),
        jsonTransformer);
}
 
Example 5
Source File: UserQuotaRoutes.java    From james-project with Apache License 2.0 6 votes vote down vote up
@GET
@ApiOperation(
    value = "Reading count and size at the same time",
    notes = "If there is no limitation for count and/or size, the returned value will be -1"
)
@ApiResponses(value = {
        @ApiResponse(code = HttpStatus.OK_200, message = "OK", response = QuotaDetailsDTO.class),
        @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "The user name does not exist."),
        @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "Internal server error - Something went bad on the server side.")
})
public void defineGetQuota() {
    service.get(QUOTA_ENDPOINT, (request, response) -> {
        Username username = checkUserExist(request);
        return userQuotaService.getQuota(username);
    }, jsonTransformer);
}
 
Example 6
Source File: MailRepositoriesRoutes.java    From james-project with Apache License 2.0 6 votes vote down vote up
@DELETE
@Path("/{encodedPath}/mails/{mailKey}")
@ApiOperation(value = "Deleting a specific mail from that mailRepository")
@ApiResponses(value = {
    @ApiResponse(code = HttpStatus.OK_200, message = "Mail is no more stored in the repository", response = List.class),
    @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "Internal server error - Something went bad on the server side."),
})
public void defineDeleteMail() {
    service.delete(MAIL_REPOSITORIES + "/:encodedPath/mails/:mailKey", (request, response) -> {
        MailRepositoryPath path = decodedRepositoryPath(request);
        MailKey mailKey = new MailKey(request.params("mailKey"));
        try {
            repositoryStoreService.deleteMail(path, mailKey);
            return Responses.returnNoContent(response);
        } catch (MailRepositoryStore.MailRepositoryStoreException | MessagingException e) {
            throw ErrorResponder.builder()
                .statusCode(HttpStatus.INTERNAL_SERVER_ERROR_500)
                .type(ErrorResponder.ErrorType.SERVER_ERROR)
                .cause(e)
                .message("Error while deleting mail")
                .haltError();
        }
    });
}
 
Example 7
Source File: MailRepositoriesRoutes.java    From james-project with Apache License 2.0 6 votes vote down vote up
@GET
@Produces("application/json, message/rfc822")
@Path("/{encodedPath}/mails/{mailKey}")
@ApiOperation(value = "Retrieving a specific mail details (this endpoint can accept both \"application/json\" or \"message/rfc822\")")
@ApiResponses(value = {
    @ApiResponse(code = HttpStatus.OK_200, message = "The list of all mails in a repository", response = List.class),
    @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "Internal server error - Something went bad on the server side."),
    @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "Not found - Could not retrieve the given mail.")
})
public void defineGetMail() {
    service.get(MAIL_REPOSITORIES + "/:encodedPath/mails/:mailKey", Constants.JSON_CONTENT_TYPE,
        (request, response) ->
            getMailAsJson(decodedRepositoryPath(request), new MailKey(request.params("mailKey")), request),
        jsonTransformer);

    service.get(MAIL_REPOSITORIES + "/:encodedPath/mails/:mailKey", Constants.RFC822_CONTENT_TYPE,
        (request, response) -> writeMimeMessage(
            getMailAsMimeMessage(
                decodedRepositoryPath(request),
                new MailKey(request.params("mailKey"))),
            response.raw()));
}
 
Example 8
Source File: DomainQuotaRoutes.java    From james-project with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/count")
@ApiOperation(value = "Reading per domain mail count limitation")
@ApiResponses(value = {
        @ApiResponse(code = HttpStatus.OK_200, message = "OK", response = Long.class),
        @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "The requested domain can not be found."),
        @ApiResponse(code = HttpStatus.METHOD_NOT_ALLOWED_405, message = "Domain Quota configuration not supported when virtual hosting is desactivated."),
        @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "Internal server error - Something went bad on the server side.")
})
public void defineGetQuotaCount() {
    service.get(COUNT_ENDPOINT, (request, response) -> {
        Domain domain = checkDomainExist(request);
        Optional<QuotaCountLimit> maxCountQuota = domainQuotaService.getMaxCountQuota(domain);
        if (maxCountQuota.isPresent()) {
            return maxCountQuota;
        }
        return Responses.returnNoContent(response);
    }, jsonTransformer);
}
 
Example 9
Source File: EmissaryResponse.java    From emissary with Apache License 2.0 6 votes vote down vote up
public String getContentString() {
    if (content == null) {
        return null;
    }
    try {
        if (status == HttpStatus.OK_200) {
            return content.toString();
        } else {
            return "Bad request -> status: " + status + " message: " + content.toString();
        }
    } catch (Exception e) {
        logger.error("Error getting string content", e);
        return e.getMessage();
    }

}
 
Example 10
Source File: DLPConfigurationRoutes.java    From james-project with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/{senderDomain}")
@ApiOperation(value = "Return a DLP configuration for a given senderDomain")
@ApiImplicitParams({
    @ApiImplicitParam(required = true, dataType = "string", name = "senderDomain", paramType = "path")
})
@ApiResponses(value = {
    @ApiResponse(code = HttpStatus.OK_200, message = "OK. DLP configuration is returned", response = DLPConfigurationDTO.class),
    @ApiResponse(code = HttpStatus.BAD_REQUEST_400, message = "Invalid senderDomain in request",
        response = ErrorResponder.ErrorDetail.class),
    @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "The domain does not exist.",
        response = ErrorResponder.ErrorDetail.class),
    @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500,
        message = "Internal server error - Something went bad on the server side.",
        response = ErrorResponder.ErrorDetail.class)
})
public void defineList(Service service) {
    service.get(SPECIFIC_DLP_RULE_DOMAIN, (request, response) -> {
        Domain senderDomain = parseDomain(request);
        DLPRules dlpConfigurations = Mono.from(dlpConfigurationStore.list(senderDomain)).block();

        DLPConfigurationDTO dto = DLPConfigurationDTO.toDTO(dlpConfigurations);
        response.status(HttpStatus.OK_200);
        response.header(CONTENT_TYPE, JSON_CONTENT_TYPE);
        return dto;
    }, jsonTransformer);
}
 
Example 11
Source File: GlobalQuotaRoutes.java    From james-project with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/size")
@ApiOperation(value = "Reading per quotaroot mail size limitation")
@ApiResponses(value = {
        @ApiResponse(code = HttpStatus.OK_200, message = "OK", response = Long.class),
        @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "Internal server error - Something went bad on the server side.")
})
public void defineGetQuotaSize() {
    service.get(SIZE_ENDPOINT, this::getQuotaSize, jsonTransformer);
}
 
Example 12
Source File: HealthCheckRoutes.java    From james-project with Apache License 2.0 5 votes vote down vote up
@GET
@ApiOperation(value = "Validate all health checks")
@ApiResponses(value = {
    @ApiResponse(code = HttpStatus.OK_200, message = "OK"),
    @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500,
        message = "Internal server error - When one check has failed.")
})
public Object validateHealthChecks(Request request, Response response) {
    List<Result> results = executeHealthChecks().collectList().block();
    ResultStatus status = retrieveAggregationStatus(results);
    response.status(getCorrespondingStatusCode(status));
    return new HeathCheckAggregationExecutionResultDto(status, mapResultToDto(results));
}
 
Example 13
Source File: DomainsRoutes.java    From james-project with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/{domainName}/aliases")
@ApiOperation(value = "Getting all aliases for a domain")
@ApiImplicitParams({
    @ApiImplicitParam(required = true, dataType = "string", name = "domainName", paramType = "path")
})
@ApiResponses(value = {
    @ApiResponse(code = HttpStatus.OK_200, message = "OK", response = List.class),
    @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "The domain does not exist."),
    @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500,
        message = "Internal server error - Something went bad on the server side.")
})
public void defineListAliases(Service service) {
    service.get(DOMAIN_ALIASES, this::listDomainAliases, jsonTransformer);
}
 
Example 14
Source File: Response.java    From onedev with MIT License 5 votes vote down vote up
protected void recycle()
{
    _status = HttpStatus.OK_200;
    _reason = null;
    _locale = null;
    _mimeType = null;
    _characterEncoding = null;
    _contentType = null;
    _outputType = OutputType.NONE;
    _contentLength = -1;
    _out.recycle();
    _fields.clear();
    _encodingFrom = EncodingFrom.NOT_SET;
}
 
Example 15
Source File: FrontierSiliconRadioConnection.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Performs a request to the radio with addition parameters.
 *
 * Typically used for changing parameters.
 *
 * @param REST
 *            API requestString, e.g. "SET/netRemote.sys.power"
 * @param params
 *            , e.g. "value=1"
 * @return request result
 * @throws IOException if the request failed.
 */
public FrontierSiliconRadioApiResult doRequest(String requestString, String params) throws IOException {
    // 3 retries upon failure
    for (int i = 0; i < 3; i++) {
        if (!isLoggedIn && !doLogin()) {
            continue; // not logged in and login was not successful - try again!
        }

        final String url = "http://" + hostname + ":" + port + FrontierSiliconRadioConstants.CONNECTION_PATH + "/"
                + requestString + "?pin=" + pin + "&sid=" + sessionId
                + (params == null || params.trim().length() == 0 ? "" : "&" + params);

        logger.trace("calling url: '{}'", url);

        Request request = httpClient.newRequest(url).method(HttpMethod.GET).timeout(SOCKET_TIMEOUT,
                TimeUnit.MILLISECONDS);

        try {
            ContentResponse response = request.send();
            final int statusCode = response.getStatus();
            if (statusCode != HttpStatus.OK_200) {
                /*-
                 * Issue: https://github.com/eclipse/smarthome/issues/2548
                 * If the session expired, we might get a 404 here. That's ok, remember that we are not logged-in
                 * and try again. Print warning only if this happens in the last iteration.
                 */
                if (i >= 2) {
                    String reason = response.getReason();
                    logger.warn("Method failed: {}  {}", statusCode, reason);
                }
                isLoggedIn = false;
                continue;
            }

            final String responseBody = response.getContentAsString();
            if (!responseBody.isEmpty()) {
                logger.trace("got result: {}", responseBody);
            } else {
                logger.debug("got empty result");
                isLoggedIn = false;
                continue;
            }

            final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody);
            if (result.isStatusOk()) {
                return result;
            }

            isLoggedIn = false;
            continue; // try again
        } catch (Exception e) {
            logger.error("Fatal transport error: {}", e.toString());
            throw new IOException(e);
        }
    }
    isLoggedIn = false; // 3 tries failed. log in again next time, maybe our session went invalid (radio restarted?)
    return null;
}
 
Example 16
Source File: OAuthConnector.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
private AccessTokenResponse doRequest(final String grantType, HttpClient httpClient, final Request request,
        Fields fields) throws OAuthResponseException, OAuthException, IOException {

    int statusCode = 0;
    String content = "";
    try {
        final FormContentProvider entity = new FormContentProvider(fields);
        final ContentResponse response = AccessController
                .doPrivileged((PrivilegedExceptionAction<ContentResponse>) () -> {
                    Request requestWithContent = request.content(entity);
                    return requestWithContent.send();
                });

        statusCode = response.getStatus();
        content = response.getContentAsString();

        if (statusCode == HttpStatus.OK_200) {
            AccessTokenResponse jsonResponse = gson.fromJson(content, AccessTokenResponse.class);
            jsonResponse.setCreatedOn(LocalDateTime.now()); // this is not supplied by the response
            logger.info("grant type {} to URL {} success", grantType, request.getURI());
            return jsonResponse;
        } else if (statusCode == HttpStatus.BAD_REQUEST_400) {
            OAuthResponseException errorResponse = gson.fromJson(content, OAuthResponseException.class);
            logger.error("grant type {} to URL {} failed with error code {}, description {}", grantType,
                    request.getURI(), errorResponse.getError(), errorResponse.getErrorDescription());

            throw errorResponse;
        } else {
            logger.error("grant type {} to URL {} failed with HTTP response code {}", grantType, request.getURI(),
                    statusCode);
            throw new OAuthException("Bad http response, http code " + statusCode);
        }
    } catch (PrivilegedActionException pae) {
        Exception underlyingException = pae.getException();
        if (underlyingException instanceof InterruptedException || underlyingException instanceof TimeoutException
                || underlyingException instanceof ExecutionException) {
            throw new IOException("Exception in oauth communication, grant type " + grantType, underlyingException);
        }
        // Dont know what exception it is, wrap it up and throw it out
        throw new OAuthException("Exception in oauth communication, grant type " + grantType, underlyingException);
    } catch (JsonSyntaxException e) {
        throw new OAuthException(String.format(
                "Unable to deserialize json into AccessTokenResponse/ OAuthResponseException. httpCode: %i json: %s",
                statusCode, content), e);
    }
}
 
Example 17
Source File: HttpUtil.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Download the data from an URL.
 *
 * @param url the URL of the data to be downloaded
 * @param contentTypeRegex the REGEX the content type must match; null to ignore the content type
 * @param scanTypeInContent true to allow the scan of data to determine the content type if not found in the headers
 * @param maxContentLength the maximum data size in bytes to trigger the download; any negative value to ignore the
 *            data size
 * @param timeout the socket timeout in milliseconds to wait for data
 * @return a RawType object containing the downloaded data, null if the content type does not match the expected
 *         type or the data size is too big
 */
public static RawType downloadData(String url, String contentTypeRegex, boolean scanTypeInContent,
        long maxContentLength, int timeout) {
    final ProxyParams proxyParams = prepareProxyParams();

    RawType rawData = null;
    try {
        ContentResponse response = executeUrlAndGetReponse("GET", url, null, null, null, timeout,
                proxyParams.proxyHost, proxyParams.proxyPort, proxyParams.proxyUser, proxyParams.proxyPassword,
                proxyParams.nonProxyHosts);
        byte[] data = response.getContent();
        if (data == null) {
            data = new byte[0];
        }
        long length = data.length;
        String mediaType = response.getMediaType();
        LOGGER.debug("Media download response: status {} content length {} media type {} (URL {})",
                response.getStatus(), length, mediaType, url);

        if (response.getStatus() != HttpStatus.OK_200 || length == 0) {
            LOGGER.debug("Media download failed: unexpected return code {} (URL {})", response.getStatus(), url);
            return null;
        }

        if (maxContentLength >= 0 && length > maxContentLength) {
            LOGGER.debug("Media download aborted: content length {} too big (URL {})", length, url);
            return null;
        }

        String contentType = mediaType;
        if (contentTypeRegex != null) {
            if ((contentType == null || contentType.isEmpty()) && scanTypeInContent) {
                // We try to get the type from the data
                contentType = guessContentTypeFromData(data);
                LOGGER.debug("Media download: content type from data: {} (URL {})", contentType, url);
            }
            if (contentType != null && contentType.isEmpty()) {
                contentType = null;
            }
            if (contentType == null) {
                LOGGER.debug("Media download aborted: unknown content type (URL {})", url);
                return null;
            } else if (!contentType.matches(contentTypeRegex)) {
                LOGGER.debug("Media download aborted: unexpected content type \"{}\" (URL {})", contentType, url);
                return null;
            }
        } else if (contentType == null || contentType.isEmpty()) {
            contentType = RawType.DEFAULT_MIME_TYPE;
        }

        rawData = new RawType(data, contentType);

        LOGGER.debug("Media downloaded: size {} type {} (URL {})", rawData.getBytes().length, rawData.getMimeType(),
                url);
    } catch (IOException e) {
        LOGGER.debug("Media download failed (URL {}) : {}", url, e.getMessage());
    }
    return rawData;
}
 
Example 18
Source File: FrontierSiliconRadioConnection.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Perform login/establish a new session. Uses the PIN number and when successful saves the assigned sessionID for
 * future requests.
 *
 * @return <code>true</code> if login was successful; <code>false</code> otherwise.
 * @throws IOException if communication with the radio failed, e.g. because the device is not reachable.
 */
public boolean doLogin() throws IOException {
    isLoggedIn = false; // reset login flag

    final String url = "http://" + hostname + ":" + port + FrontierSiliconRadioConstants.CONNECTION_PATH
            + "/CREATE_SESSION?pin=" + pin;

    logger.trace("opening URL: {}", url);

    Request request = httpClient.newRequest(url).method(HttpMethod.GET).timeout(SOCKET_TIMEOUT,
            TimeUnit.MILLISECONDS);

    try {
        ContentResponse response = request.send();
        int statusCode = response.getStatus();
        if (statusCode != HttpStatus.OK_200) {
            String reason = response.getReason();
            logger.debug("Communication with radio failed: {} {}", statusCode, reason);
            if (statusCode == HttpStatus.FORBIDDEN_403) {
                throw new IllegalStateException("Radio does not allow connection, maybe wrong pin?");
            }
            throw new IOException("Communication with radio failed, return code: " + statusCode);
        }

        final String responseBody = response.getContentAsString();
        if (!responseBody.isEmpty()) {
            logger.trace("login response: {}", responseBody);
        }

        final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody);
        if (result.isStatusOk()) {
            logger.trace("login successful");
            sessionId = result.getSessionId();
            isLoggedIn = true;
            return true; // login successful :-)
        }

    } catch (Exception e) {
        logger.debug("Fatal transport error: {}", e.toString());
        throw new IOException(e);
    }

    return false; // login not successful
}
 
Example 19
Source File: OAuthConnector.java    From openhab-core with Eclipse Public License 2.0 4 votes vote down vote up
private AccessTokenResponse doRequest(final String grantType, HttpClient httpClient, final Request request,
        Fields fields) throws OAuthResponseException, OAuthException, IOException {
    int statusCode = 0;
    String content = "";
    try {
        final FormContentProvider entity = new FormContentProvider(fields);
        final ContentResponse response = AccessController
                .doPrivileged((PrivilegedExceptionAction<ContentResponse>) () -> {
                    Request requestWithContent = request.content(entity);
                    return requestWithContent.send();
                });

        statusCode = response.getStatus();
        content = response.getContentAsString();

        if (statusCode == HttpStatus.OK_200) {
            AccessTokenResponse jsonResponse = gson.fromJson(content, AccessTokenResponse.class);
            jsonResponse.setCreatedOn(LocalDateTime.now()); // this is not supplied by the response
            logger.debug("grant type {} to URL {} success", grantType, request.getURI());
            return jsonResponse;
        } else if (statusCode == HttpStatus.BAD_REQUEST_400) {
            OAuthResponseException errorResponse = gson.fromJson(content, OAuthResponseException.class);
            logger.error("grant type {} to URL {} failed with error code {}, description {}", grantType,
                    request.getURI(), errorResponse.getError(), errorResponse.getErrorDescription());

            throw errorResponse;
        } else {
            logger.error("grant type {} to URL {} failed with HTTP response code {}", grantType, request.getURI(),
                    statusCode);
            throw new OAuthException("Bad http response, http code " + statusCode);
        }
    } catch (PrivilegedActionException pae) {
        Exception underlyingException = pae.getException();
        if (underlyingException instanceof InterruptedException || underlyingException instanceof TimeoutException
                || underlyingException instanceof ExecutionException) {
            throw new IOException("Exception in oauth communication, grant type " + grantType, underlyingException);
        }
        // Dont know what exception it is, wrap it up and throw it out
        throw new OAuthException("Exception in oauth communication, grant type " + grantType, underlyingException);
    } catch (JsonSyntaxException e) {
        throw new OAuthException(String.format(
                "Unable to deserialize json into AccessTokenResponse/ OAuthResponseException. httpCode: %i json: %s",
                statusCode, content), e);
    }
}
 
Example 20
Source File: RadioServiceDummy.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
public RadioServiceDummy() {
    this.httpStatus = HttpStatus.OK_200;
}