當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpStatus.SC_UNAUTHORIZED屬性代碼示例

本文整理匯總了Java中org.apache.http.HttpStatus.SC_UNAUTHORIZED屬性的典型用法代碼示例。如果您正苦於以下問題:Java HttpStatus.SC_UNAUTHORIZED屬性的具體用法?Java HttpStatus.SC_UNAUTHORIZED怎麽用?Java HttpStatus.SC_UNAUTHORIZED使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在org.apache.http.HttpStatus的用法示例。


在下文中一共展示了HttpStatus.SC_UNAUTHORIZED屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: retryRequest

@Override
public boolean retryRequest(final HttpResponse response, final int executionCount, final HttpContext context) {
    switch(response.getStatusLine().getStatusCode()) {
        case HttpStatus.SC_UNAUTHORIZED:
            if(executionCount <= MAX_RETRIES) {
                try {
                    log.info(String.format("Attempt to refresh OAuth tokens for failure %s", response));
                    service.setTokens(service.refresh());
                    return true;
                }
                catch(BackgroundException e) {
                    log.warn(String.format("Failure refreshing OAuth tokens. %s", e.getDetail()));
                    return false;
                }
            }
            break;
    }
    return false;
}
 
開發者ID:iterate-ch,項目名稱:cyberduck,代碼行數:19,代碼來源:OAuth2ErrorResponseInterceptor.java

示例2: buildSwaggerJson

public Optional<Swagger> buildSwaggerJson() {
	RestClient invoker = new RestClient(mUserInput);
	EndpointResponse response = invoker.invoke();

	if (response.getStatus() == HttpStatus.SC_UNAUTHORIZED) {
		logger.error(
				"Endpoint requires authentication, please provide authentication details by -a command line option or for more details see help.");
	}
	Swagger finalSwagger;

	if (new File(mUserInput.swaggerJSONFilePath()).exists()) {
		finalSwagger = new SwaggerUpdater().update(mUserInput.swaggerJSONFilePath(),
				generateFirstTimeSwaggerFile(response));
	} else {
		finalSwagger = generateFirstTimeSwaggerFile(response);
	}

	return Optional.of(finalSwagger);
}
 
開發者ID:pegasystems,項目名稱:api2swagger,代碼行數:19,代碼來源:SwaggerGenerator.java

示例3: createResponse

@SuppressWarnings("unchecked")
@Override
public Response createResponse() {
    JSONObject errorJson = new JSONObject();

    errorJson.put(Key.ERROR, this.error);

    String errDesc = String.format("[%s] - %s", this.code, this.message);
    errorJson.put(Key.ERROR_DESCRIPTION, errDesc);

    int statusCode = parseCode(this.code);
    ResponseBuilder rb = Response.status(statusCode)
            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
            .entity(errorJson.toJSONString());

    // レルム値が設定されていれば、WWW-Authenticateヘッダーを返卻する。
    // __tokenエンドポイントでは、認証失敗時(401返卻時)には、同ヘッダーに Auth SchemeがBasicの値を返卻するため、ここでは固定値とする。
    if (this.realm != null && statusCode == HttpStatus.SC_UNAUTHORIZED) {
        rb = rb.header(HttpHeaders.WWW_AUTHENTICATE, Scheme.BASIC + " realm=\"" + this.realm + "\"");
    }
    return rb.build();
}
 
開發者ID:personium,項目名稱:personium-core,代碼行數:22,代碼來源:PersoniumCoreAuthnException.java

示例4: isAuthenticationRequested

public boolean isAuthenticationRequested(
        final HttpResponse response,
        final HttpContext context) {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }
    int status = response.getStatusLine().getStatusCode();
    return status == HttpStatus.SC_UNAUTHORIZED;
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:9,代碼來源:DefaultTargetAuthenticationHandler.java

示例5: map

public BackgroundException map(final Throwable failure, final StringBuilder buffer, final int statusCode) {
    switch(statusCode) {
        case HttpStatus.SC_UNAUTHORIZED:
            return new LoginFailureException(buffer.toString(), failure);
        case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
            return new ProxyLoginFailureException(buffer.toString(), failure);
        case HttpStatus.SC_FORBIDDEN:
        case HttpStatus.SC_NOT_ACCEPTABLE:
            return new AccessDeniedException(buffer.toString(), failure);
        case HttpStatus.SC_CONFLICT:
            return new ConflictException(buffer.toString(), failure);
        case HttpStatus.SC_NOT_FOUND:
        case HttpStatus.SC_GONE:
        case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE:
            return new NotfoundException(buffer.toString(), failure);
        case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE:
        case HttpStatus.SC_INSUFFICIENT_STORAGE:
        case HttpStatus.SC_PAYMENT_REQUIRED:
            return new QuotaException(buffer.toString(), failure);
        case HttpStatus.SC_UNPROCESSABLE_ENTITY:
        case HttpStatus.SC_BAD_REQUEST:
        case HttpStatus.SC_REQUEST_URI_TOO_LONG:
        case HttpStatus.SC_METHOD_NOT_ALLOWED:
        case HttpStatus.SC_NOT_IMPLEMENTED:
            return new InteroperabilityException(buffer.toString(), failure);
        case HttpStatus.SC_REQUEST_TIMEOUT:
        case HttpStatus.SC_GATEWAY_TIMEOUT:
        case HttpStatus.SC_BAD_GATEWAY:
            return new ConnectionTimeoutException(buffer.toString(), failure);
        case HttpStatus.SC_INTERNAL_SERVER_ERROR:
        case HttpStatus.SC_SERVICE_UNAVAILABLE:
        case 429:
            // Too Many Requests. Rate limiting
        case 509:
            // Bandwidth Limit Exceeded
            return new RetriableAccessDeniedException(buffer.toString(), failure);
        default:
            return new InteroperabilityException(buffer.toString(), failure);
    }
}
 
開發者ID:iterate-ch,項目名稱:cyberduck,代碼行數:40,代碼來源:HttpResponseExceptionMappingService.java

示例6: handleResponse

@Override
public AuthenticationResponse handleResponse(final HttpResponse response) throws IOException {
    if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        Charset charset = HTTP.DEF_CONTENT_CHARSET;
        ContentType contentType = ContentType.get(response.getEntity());
        if(contentType != null) {
            if(contentType.getCharset() != null) {
                charset = contentType.getCharset();
            }
        }
        try {
            final JsonParser parser = new JsonParser();
            final JsonObject json = parser.parse(new InputStreamReader(response.getEntity().getContent(), charset)).getAsJsonObject();
            final String token = json.getAsJsonPrimitive("token").getAsString();
            final String endpoint = json.getAsJsonPrimitive("endpoint").getAsString();
            return new AuthenticationResponse(response, token,
                    Collections.singleton(new Region(null, URI.create(endpoint), null, true)));
        }
        catch(JsonParseException e) {
            throw new IOException(e.getMessage(), e);
        }
    }
    else if(response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED
            || response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
        throw new AuthorizationException(new Response(response));
    }
    throw new GenericException(new Response(response));
}
 
開發者ID:iterate-ch,項目名稱:cyberduck,代碼行數:28,代碼來源:HubicAuthenticationResponseHandler.java

示例7: testComponentPermission

private Pair<Boolean, String> testComponentPermission(Xray xrayClient) throws IOException {
    try {
        Components testComponent = new ComponentsImpl();
        testComponent.addComponent("testComponent", "");
        xrayClient.summary().component(testComponent);
    } catch (HttpResponseException e) {
        switch (e.getStatusCode()) {
            case HttpStatus.SC_UNAUTHORIZED:
                return Pair.of(false, e.getMessage() + ". Please check your credentials.");
            case HttpStatus.SC_FORBIDDEN:
                return Pair.of(false, e.getMessage() + ". Please make sure that the user has 'View Components' permission in Xray.");
        }
    }
    return Pair.of(true, "");
}
 
開發者ID:JFrogDev,項目名稱:jfrog-idea-plugin,代碼行數:15,代碼來源:XrayGlobalConfiguration.java

示例8: getCurrentUser

public Single<User> getCurrentUser(RoutingContext routingContext) {
    String authorizationHeader = RequestReader.getHeaderValue(routingContext, RequestReader.AUTHORIZATION_HEADER);

    if (authorizationHeader == null) {
        throw new ServiceException(HttpStatus.SC_UNAUTHORIZED, "No authorization token provided");
    }

    AuthorizationToken token = authorizationTokenFactory.fromAuthorizationHeader(authorizationHeader);

    return Single.just((User) authenticationFacade.authenticate(token).getAuthenticatable())
            .flatMap((user) -> userFacade.read(user.getId()));
}
 
開發者ID:Atypon-OpenSource,項目名稱:wayf-cloud,代碼行數:12,代碼來源:UserRouting.java

示例9: authenticatedAsPublisher

public static Publisher authenticatedAsPublisher(AuthenticatedEntity authenticatable) {
    if (authenticatable != null
            && authenticatable.getAuthenticatable() != null
            && Publisher.class.isAssignableFrom(authenticatable.getAuthenticatable().getClass())) {
        return (Publisher) authenticatable.getAuthenticatable();
    }

    throw new ServiceException(HttpStatus.SC_UNAUTHORIZED, "An authenticated Publisher is required");
}
 
開發者ID:Atypon-OpenSource,項目名稱:wayf-cloud,代碼行數:9,代碼來源:AuthenticatedEntity.java

示例10: authenticatedAsAdmin

public static User authenticatedAsAdmin(AuthenticatedEntity authenticatable) {
    if (authenticatable != null
            && authenticatable.getAuthenticatable() != null
            && User.class.isAssignableFrom(authenticatable.getAuthenticatable().getClass())) {
        return (User) authenticatable.getAuthenticatable();
    }

    throw new ServiceException(HttpStatus.SC_UNAUTHORIZED, "An authenticated Administrator is required");
}
 
開發者ID:Atypon-OpenSource,項目名稱:wayf-cloud,代碼行數:9,代碼來源:AuthenticatedEntity.java

示例11: authenticate

@Override
public AuthenticatedEntity authenticate(AuthenticationCredentials credentials) {
    LOG.debug("Authenticating credentials");

    // Use the cached version of credentials to leverage better equals and hashcode
    if (PasswordCredentials.class.isAssignableFrom(credentials.getClass())) {
        credentials = new CachedPasswordCredentials((PasswordCredentials) credentials);
    } else if (AuthorizationToken.class.isAssignableFrom(credentials.getClass())) {
        credentials = new CachedAuthorizationToken((AuthorizationToken) credentials);
    } else {
        throw new ServiceException(HttpStatus.SC_BAD_REQUEST, "Invalid authentication credentials");
    }

    try {
        AuthenticatedEntity authenticatedEntity = persistence.get(credentials).blockingGet();

        if (authenticatedEntity == null) {
            throw new ServiceException(HttpStatus.SC_UNAUTHORIZED, "Could not authenticate credentials");
        }

        if (!isStillValid(authenticatedEntity)) {
            throw new ServiceException(HttpStatus.SC_UNAUTHORIZED, "Expired credentials");
        }

        return authenticatedEntity;
    } catch (Exception e) {
        throw new ServiceException(HttpStatus.SC_UNAUTHORIZED, "Could not authenticate credentials", e);
    }
}
 
開發者ID:Atypon-OpenSource,項目名稱:wayf-cloud,代碼行數:29,代碼來源:AuthenticationFacadeImpl.java

示例12: TargetAuthenticationStrategy

public TargetAuthenticationStrategy() {
    super(HttpStatus.SC_UNAUTHORIZED, AUTH.WWW_AUTH, AuthPNames.TARGET_AUTH_PREF);
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:3,代碼來源:TargetAuthenticationStrategy.java

示例13: map

@Override
public BackgroundException map(final B2ApiException e) {
    final StringBuilder buffer = new StringBuilder();
    this.append(buffer, e.getMessage());
    switch(e.getStatus()) {
        case HttpStatus.SC_FORBIDDEN:
            if("cap_exceeded".equalsIgnoreCase(e.getCode())
                    || "storage_cap_exceeded".equalsIgnoreCase(e.getCode())
                    || "transaction_cap_exceeded".equalsIgnoreCase(e.getCode())) {// Reached the storage cap that you set
                return new QuotaException(buffer.toString(), e);
            }
            break;
        case HttpStatus.SC_BAD_REQUEST:
            if("file_not_present".equalsIgnoreCase(e.getCode())) {
                return new NotfoundException(buffer.toString(), e);
            }
            if("bad_bucket_id".equalsIgnoreCase(e.getCode())) {
                return new NotfoundException(buffer.toString(), e);
            }
            if("cap_exceeded".equalsIgnoreCase(e.getCode())) {// Reached the storage cap that you set
                return new QuotaException(buffer.toString(), e);
            }
            if("too_many_buckets".equalsIgnoreCase(e.getCode())) {// Reached the storage cap that you set
                return new QuotaException(buffer.toString(), e);
            }
            if("bad_request".equalsIgnoreCase(e.getCode())) {
                if("sha1 did not match data received".equalsIgnoreCase(e.getMessage())) {
                    return new ChecksumException(buffer.toString(), e);
                }
            }
            break;
        case HttpStatus.SC_UNAUTHORIZED:
            if("expired_auth_token".equalsIgnoreCase(e.getCode())) {
                return new ExpiredTokenException(buffer.toString(), e);
            }
            break;
        default:
            if(e.getRetry() != null) {
                // Too Many Requests (429)
                return new RetriableAccessDeniedException(buffer.toString(), Duration.ofSeconds(e.getRetry()), e);
            }
            break;
    }
    return new HttpResponseExceptionMappingService().map(new HttpResponseException(e.getStatus(), buffer.toString()));
}
 
開發者ID:iterate-ch,項目名稱:cyberduck,代碼行數:45,代碼來源:B2ExceptionMappingService.java

示例14: createPublisherDeviceRelationship

public Single<Device> createPublisherDeviceRelationship(RoutingContext routingContext) {
    LOG.debug("Received request to create publisher/device relationship");

    String localId = RequestReader.readPathArgument(routingContext, LOCAL_ID_PARAM);

    AuthorizationToken token = RequestContextAccessor.get().getAuthorizationToken();
    if (token == null) {
        throw new ServiceException(HttpStatus.SC_BAD_REQUEST, "An Authorization token is required");
    }

    LOG.debug("Token value [{}]", token.getValue());

    String publisherCode = null;

    try {
        Algorithm.HMAC256(jwtSecret);
        DecodedJWT jwt = JWT.decode(token.getValue());

        publisherCode = jwt.getClaim(ClientJsFacade.PUBLISHER_CODE_KEY).asString();
    } catch (Exception e) {
        throw new ServiceException(HttpStatus.SC_UNAUTHORIZED, "Could not authenticate token", e);
    }

    LOG.debug("Publisher code {}", publisherCode);

    return publisherFacade.lookupCode(publisherCode)
            .flatMap((publisher) -> {

                String hashedLocalId = deviceFacade.encryptLocalId(publisher.getId(), localId);

                return deviceFacade.relateLocalIdToDevice(publisher, hashedLocalId)
                        .map((device) -> {
                            String globalId = device.getGlobalId();

                            Cookie cookie = new CookieImpl(RequestReader.DEVICE_ID, globalId)
                                    .setDomain(wayfDomain)
                                    .setMaxAge(158132000l)
                                    .setPath("/");

                            String requestOrigin = RequestReader.getHeaderValue(routingContext, "Origin");

                            LOG.debug("Request origin [{}]", requestOrigin);

                            if (requestOrigin == null || requestOrigin.isEmpty()) {
                                throw new ServiceException(HttpStatus.SC_BAD_REQUEST, "Origin header is required");
                            }

                            routingContext.response().putHeader("Access-Control-Allow-Origin", requestOrigin);

                            routingContext.addCookie(cookie);
                            device.setGlobalId(null);

                            return device;
                        });

            });
}
 
開發者ID:Atypon-OpenSource,項目名稱:wayf-cloud,代碼行數:57,代碼來源:DeviceRoutingProvider.java

示例15: UnauthorizedException

public UnauthorizedException() {        
    super(HttpStatus.SC_UNAUTHORIZED);
}
 
開發者ID:tdsis,項目名稱:lambda-forest,代碼行數:3,代碼來源:UnauthorizedException.java


注:本文中的org.apache.http.HttpStatus.SC_UNAUTHORIZED屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。