当前位置: 首页>>代码示例>>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;未经允许,请勿转载。