org.apache.http.HttpStatus#SC_UNAUTHORIZED源码实例Demo

下面列出了org.apache.http.HttpStatus#SC_UNAUTHORIZED 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: cloudstack   文件: BrocadeVcsApi.java
protected HttpResponse executeMethod(HttpRequestBase method) throws BrocadeVcsApiException {
    HttpResponse response = null;
    try {
        response = _client.execute(method);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            method.releaseConnection();
            response = _client.execute(method);
        }
    } catch (final IOException e) {
        s_logger.error("IOException caught while trying to connect to the Brocade Switch", e);
        method.releaseConnection();
        throw new BrocadeVcsApiException("API call to Brocade Switch Failed", e);
    }

    return response;
}
 
源代码2 项目: pacbot   文件: HttpUtil.java
/**
 * Post.
 *
 * @param url            the url
 * @param requestBody            the request body
 * @param token the token
 * @param tokeType the toke type
 * @return the string
 * @throws Exception             the exception
 */
public static String post(String url, String requestBody,String token,String tokeType) throws Exception {
    try {
        CloseableHttpClient httpClient = getHttpClient();
        if(httpClient!=null){
            HttpPost httppost = new HttpPost(url);
            httppost.setHeader("Content-Type", ContentType.APPLICATION_JSON.toString());
            if(!Strings.isNullOrEmpty(token)){
                httppost.addHeader("Authorization", tokeType+" "+token);
            }
            httppost.setEntity(new StringEntity(requestBody));
            HttpResponse httpresponse = httpClient.execute(httppost);
            if( httpresponse.getStatusLine().getStatusCode()==HttpStatus.SC_UNAUTHORIZED){
                throw new UnAuthorisedException();
            }
            return EntityUtils.toString(httpresponse.getEntity());
        }
    } catch (Exception e) {
    	
        LOGGER.error("Error getting the data " , e);
        throw e;
    }
    return null;

}
 
源代码3 项目: pacbot   文件: HttpUtil.java
/**
 * Gets the.
 *
 * @param uri            the uri
 * @param bearerToken the bearer token
 * @return the string
 * @throws Exception the exception
 */
public static String get(String uri ,String bearerToken) throws Exception  {
    HttpGet httpGet = new HttpGet(uri);
    httpGet.addHeader("content-type", "application/json");
    httpGet.addHeader("cache-control", "no-cache");
    if(!Strings.isNullOrEmpty(bearerToken)){
        httpGet.addHeader("Authorization", "Bearer "+bearerToken);
    }
    CloseableHttpClient httpClient = getHttpClient();
    if(httpClient!=null){
        HttpResponse httpResponse;
        try {
           
            httpResponse = httpClient.execute(httpGet);
            if( httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_UNAUTHORIZED){
                throw new UnAuthorisedException();
            }
            return EntityUtils.toString(httpResponse.getEntity());
        } catch (Exception e) {
            LOGGER.error("Error getting the data " , e);
            throw e;
        }
    }
    return "{}";
}
 
源代码4 项目: hop   文件: HttpProtocol.java
/**
 * Performs a get on urlAsString using username and password as credentials.
 * <p>
 * If the status code returned not -1 and 401 then the contents are returned. If the status code is 401 an
 * AuthenticationException is thrown.
 * <p>
 * All other values of status code are not dealt with but logic can be added as needed.
 *
 * @param urlAsString
 * @param username
 * @param password
 * @return
 * @throws AuthenticationException
 * @throws IOException
 */
public String get( String urlAsString, String username, String password )
  throws IOException, AuthenticationException {

  HttpClient httpClient;
  HttpGet getMethod = new HttpGet( urlAsString );
  if ( !Utils.isEmpty( username ) ) {
    HttpClientManager.HttpClientBuilderFacade clientBuilder = HttpClientManager.getInstance().createBuilder();
    clientBuilder.setCredentials( username, password );
    httpClient = clientBuilder.build();
  } else {
    httpClient = HttpClientManager.getInstance().createDefaultClient();
  }
  HttpResponse httpResponse = httpClient.execute( getMethod );
  int statusCode = httpResponse.getStatusLine().getStatusCode();
  StringBuilder bodyBuffer = new StringBuilder();

  if ( statusCode != -1 ) {
    if ( statusCode != HttpStatus.SC_UNAUTHORIZED ) {
      // the response
      InputStreamReader inputStreamReader = new InputStreamReader( httpResponse.getEntity().getContent() );

      int c;
      while ( ( c = inputStreamReader.read() ) != -1 ) {
        bodyBuffer.append( (char) c );
      }
      inputStreamReader.close();

    } else {
      throw new AuthenticationException();
    }
  }

  // Display response
  return bodyBuffer.toString();
}
 
源代码5 项目: mycore   文件: MCRDataciteClient.java
public URI resolveDOI(final MCRDigitalObjectIdentifier doiParam) throws MCRPersistentIdentifierException {

        URI requestURI = getRequestURI("/doi/" + doiParam.asString());
        HttpGet get = new HttpGet(requestURI);
        try (CloseableHttpClient httpClient = getHttpClient()) {
            CloseableHttpResponse response = httpClient.execute(get);
            HttpEntity entity = response.getEntity();
            StatusLine statusLine = response.getStatusLine();
            switch (statusLine.getStatusCode()) {
                case HttpStatus.SC_OK:
                    try (Scanner scanner = new Scanner(entity.getContent(), "UTF-8")) {
                        String uriString = scanner.nextLine();
                        return new URI(uriString);
                    }
                case HttpStatus.SC_NO_CONTENT:
                    throw new MCRIdentifierUnresolvableException(doiParam.asString(),
                        "The identifier " + doiParam.asString() + " is currently not resolvable");
                case HttpStatus.SC_NOT_FOUND:
                    throw new MCRIdentifierUnresolvableException(doiParam.asString(),
                        "The identifier " + doiParam.asString() + " was not found in the Datacenter!");
                case HttpStatus.SC_UNAUTHORIZED:
                    throw new MCRDatacenterAuthenticationException();
                case HttpStatus.SC_INTERNAL_SERVER_ERROR:
                    throw new MCRDatacenterException(
                        String.format(Locale.ENGLISH, "Datacenter error while resolving doi: \"%s\" : %s",
                            doiParam.asString(), getStatusString(response)));
                default:
                    throw new MCRDatacenterException(String.format(Locale.ENGLISH,
                        "Unknown error while resolving doi: \"%s\" : %s", doiParam.asString(),
                        getStatusString(response)));
            }
        } catch (IOException | URISyntaxException ex) {
            throw new MCRDatacenterException(
                String.format(Locale.ENGLISH, "Unknown error while resolving doi: \"%s\"", doiParam.asString()), ex);
        }
    }
 
源代码6 项目: pentaho-reporting   文件: CookiesHandlerFilter.java
@Override
public ClientResponse handle( ClientRequest request ) throws ClientHandlerException {
  List<Object> authorizationHeader = request.getHeaders().get( "Authorization" );
  String authToken = (String) authorizationHeader.get( 0 );
  // If we have cookies, inject them. When session is expired, basic auth
  // header is not used instead of the expired cookies, so we just use
  // them as a token.
  List<Object> cookiesList = getCachedCookiesByAuthToken( authToken );
  if ( cookiesList != null ) {
    request.getHeaders().put( "Cookie", cookiesList );
    request.getHeaders().remove( "Authorization" );
  }
  ClientResponse response = getNext().handle( request );
  // If session has expired, remove cookies, put back basic auth header,
  // try one more time and save new cookies.
  if ( response.getStatus() == HttpStatus.SC_UNAUTHORIZED ) {
    logger.warn( "Request to" + request.getURI() + "returned Unauthorized." );
    if ( logger.isDebugEnabled() ) {
      logger.debug( "http status=" + response.getStatus() + " response=" + response.getEntity( String.class ) );
    }
    request.getHeaders().remove( "Cookie" );
    request.getHeaders().put( "Authorization", authorizationHeader );
    logger.warn( "Trying one more time" );
    response = getNext().handle( request );
    if ( response.getStatus() == HttpStatus.SC_UNAUTHORIZED ) {
      logger.error( "Request to" + request.getURI() + "returned Unauthorized 2nd time." );
      logger.error( "http status=" + response.getStatus() + " response=" + response.getEntity( String.class ) );
    }
  }
  // always use the new cookies.
  if ( response.getCookies() != null && response.getCookies().isEmpty() == false ) {
    cookiesList = new ArrayList<Object>();
    cookiesList.addAll( response.getCookies() );
    setCookiesByAuthToken( authToken, cookiesList );
  }
  return response;
}
 
源代码7 项目: sync-service   文件: SwiftManagerHTTPS.java
@Override
public void deleteChunk(Workspace workspace, String chunkName) throws Exception {

    if (!isTokenActive()) {
        login();
    }

    HttpClient httpClient = new DefaultHttpClient();

    String url = this.storageUrl + "/" + workspace.getSwiftContainer() + "/" + chunkName;

    try {

        HttpDelete request = new HttpDelete(url);
        request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);

        HttpResponse response = httpClient.execute(request);

        SwiftResponse swiftResponse = new SwiftResponse(response);

        if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new UnauthorizedException("401 User unauthorized");
        }

        if (swiftResponse.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            throw new ObjectNotFoundException("404 Not Found");
        }

        if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
            throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
源代码8 项目: nexus-public   文件: ProxyFacetSupport.java
/**
 * May throw {@link ProxyServiceException} based on response statuses.
 */
private void mayThrowProxyServiceException(final HttpResponse httpResponse) {
  final StatusLine status = httpResponse.getStatusLine();
  if (HttpStatus.SC_UNAUTHORIZED == status.getStatusCode()
      || HttpStatus.SC_PAYMENT_REQUIRED == status.getStatusCode()
      || HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED == status.getStatusCode()
      || HttpStatus.SC_INTERNAL_SERVER_ERROR <= status.getStatusCode()) {
    throw new ProxyServiceException(httpResponse);
  }
}
 
源代码9 项目: swagger-brake   文件: HttpClientErrorHandler.java
@Override
public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
    int statusCode = response.getStatusLine().getStatusCode();
    if (HttpStatus.SC_UNAUTHORIZED == statusCode) {
        if (log.isDebugEnabled()) {
            String body = EntityUtils.toString(response.getEntity());
            log.debug("Unauthorized access with response\n{}", body);
        }
        throw new UnauthorizedException("Request unauthorized");
    }
}
 
/**
 * This sends an authentication request to the server and unmarshals the result.
 * 
 * @return the result of the authentication request, when the authentication was
 * 		successfull.
 * @throws IndegoAuthenticationException in case of wrong authentication informations
 * @throws IndegoException in case of any unexpected event
 */
private AuthenticationResponse doAuthenticate () throws IndegoAuthenticationException, IndegoException
{
    try {
        HttpPost httpPost = new HttpPost(baseUrl + "authenticate");
        httpPost.addHeader("Authorization", "Basic " + authentication);

        AuthenticationRequest authRequest = new AuthenticationRequest();
        authRequest.setDevice("");
        authRequest.setOsType("Android");
        authRequest.setOsVersion("4.0");
        authRequest.setDeviceManufacturer("unknown");
        authRequest.setDeviceType("unknown");
        String json = mapper.writeValueAsString(authRequest);
        httpPost.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));

        CloseableHttpResponse response = httpClient.execute(httpPost);

        int status = response.getStatusLine().getStatusCode();
        if ( status == HttpStatus.SC_UNAUTHORIZED ) {
            throw new IndegoAuthenticationException("Was not able to authenticate");
        }
        if ( status != HttpStatus.SC_OK && status != HttpStatus.SC_CREATED ) {
            throw new IndegoAuthenticationException("The request failed with error: "
                    + response.getStatusLine().toString());
        }

        String responseContents = EntityUtils.toString(response.getEntity());
        AuthenticationResponse authResponse = mapper.readValue(responseContents,
                AuthenticationResponse.class);

        return authResponse;
    }
    catch (IOException ex) {
        throw new IndegoException(ex);
    }
}
 
源代码11 项目: YiBo   文件: TencentErrorAdaptor.java
private static int translateErrorCode(int retCode, int errorCode) {
	int libErrorCode = retCode;
	if (errorCode > 0) {
		if (retCode == 3) {
			// 二级错误字段【验签失败】
			switch (errorCode) {
			case 1: // 无效TOKEN,被吊销
				libErrorCode = LibResultCode.OAUTH_TOKEN_REVOKED;
				break;
			case 2: // 请求重放
				libErrorCode = LibResultCode.OAUTH_NONCE_USED;
				break;
			case 3: // access_token不存在
				libErrorCode = LibResultCode.OAUTH_TOKEN_REJECTED;
				break;
			case 4: // access_token超时
				libErrorCode = LibResultCode.OAUTH_TOKEN_EXPIRED;
				break;
			case 5: // oauth 版本不对
				libErrorCode = LibResultCode.OAUTH_VERSION_REJECTED;
				break;
			case 6: // 签名方法不对
				libErrorCode = LibResultCode.OAUTH_SIGNATURE_METHOD_REJECTED;
				break;
			case 7: // 参数错
				libErrorCode = LibResultCode.OAUTH_PARAMETER_REJECTED;
				break;
			case 9: // 验证签名失败
				libErrorCode = LibResultCode.OAUTH_SIGNATURE_INVALID;
				break;
			case 10: // 网络错误
				libErrorCode = LibResultCode.NET_ISSUE;
				break;
			case 11: // 参数长度不对
				libErrorCode = LibResultCode.OAUTH_PARAMETER_REJECTED;
				break;
			case 8:
			case 12:
			case 13:
			case 14:
			case 15: // 处理失败
				libErrorCode = LibResultCode.SC_INTERNAL_SERVER_ERROR;
				break;
			}
		} else if (retCode == 4) {
			// 二级错误字段【发表接口】
			switch (errorCode) {
			case 4: // 表示有过多脏话
				libErrorCode = LibResultCode.API_MB_CONTENT_ILLEGAL;
				break;
			case 5: // 禁止访问,如城市,uin黑名单限制等
				libErrorCode = LibResultCode.API_MB_PERMISSION_ACCESS_DENIED;
				break;
			case 6: // 删除时:该记录不存在。发表时:父节点已不存在
				libErrorCode = LibResultCode.API_MB_ITEM_NOT_EXIST;
				break;
			case 8: // 内容超过最大长度:420字节 (以进行短url处理后的长度计)
				libErrorCode = LibResultCode.API_MB_CONTENT_OVER_LENGTH;
				break;
			case 9: // 包含垃圾信息:广告,恶意链接、黑名单号码等
				libErrorCode = LibResultCode.API_MB_CONTENT_ILLEGAL;
				break;
			case 10: // 发表太快,被频率限制
				libErrorCode = LibResultCode.API_MB_INVOKE_RATE_TOO_QUICK;
				break;
			case 11: // 源消息已删除,如转播或回复时
				libErrorCode = LibResultCode.API_MB_TWEET_NOT_EXIST;
				break;
			case 12: // 源消息审核中
				libErrorCode = LibResultCode.API_MB_ITEM_REVIEWING;
				break;
			case 13: // 重复发表
				libErrorCode = LibResultCode.API_MB_TWEET_REPEAT;
				break;
			}
		}
	} else {
		switch (retCode) {
		case 1: // 参数错误
			libErrorCode = HttpStatus.SC_BAD_REQUEST;
			break;
		case 2: // 频率受限
			libErrorCode = LibResultCode.API_MB_RATE_LIMITED;
			break;
		case 3: // 鉴权失败
			libErrorCode = HttpStatus.SC_UNAUTHORIZED;
			break;
		case 4: // 服务器内部错误
			libErrorCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
			break;
		}
	}
	return libErrorCode;
}
 
源代码12 项目: storm-crawler   文件: FileResponse.java
public FileResponse(String u, Metadata md, FileProtocol fileProtocol)
        throws IOException {

    metadata = new Metadata();
    content = new byte[0];
    statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;

    URL url = new URL(u);

    if (!url.getPath().equals(url.getFile())) {
        LOG.warn("url.getPath() != url.getFile(): {}.", url);
    }

    String path = "".equals(url.getPath()) ? "/" : url.getPath();

    File file = new File(
            URLDecoder.decode(path, fileProtocol.getEncoding()));

    if (!file.exists()) {
        statusCode = HttpStatus.SC_NOT_FOUND;
        return;
    }

    if (!file.canRead()) {
        statusCode = HttpStatus.SC_UNAUTHORIZED;
        return;
    }

    if (!file.equals(file.getCanonicalFile())) {
        metadata.setValue(HttpHeaders.LOCATION, file.getCanonicalFile()
                .toURI().toURL().toString());
        statusCode = HttpStatus.SC_MULTIPLE_CHOICES;
        return;
    }

    if (file.isDirectory()) {
        getDirAsHttpResponse(file);
    } else if (file.isFile()) {
        getFileAsHttpResponse(file);
    } else {
        statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        return;
    }
}
 
源代码13 项目: divide   文件: AuthServerLogic.java
/**
     * Checks username/password against that stored in DB, if same return
     * token, if token expired create new.
     * @param credentials
     * @return authentication token
     */

    public Credentials userSignIn(Credentials credentials) throws DAOException {
            Credentials dbCreds = getUserByEmail(dao,credentials.getEmailAddress());
            if (dbCreds == null){
                throw new DAOException(HttpStatus.SC_UNAUTHORIZED,"User Doesnt exist");
            }
            else {
                //check if we are resetting the password
                if(dbCreds.getValidation()!=null && dbCreds.getValidation().equals(credentials.getValidation())){
                    credentials.decryptPassword(keyManager.getPrivateKey()); //decrypt the password
                    dbCreds.setPassword(BCrypt.hashpw(credentials.getPassword(), BCrypt.gensalt(10))); //set the new password
                }
                //else check password
                else {
                    String en = credentials.getPassword();
                    credentials.decryptPassword(keyManager.getPrivateKey()); //decrypt the password
                    String de = credentials.getPassword();
                    String ha = BCrypt.hashpw(de, BCrypt.gensalt(10));
                    System.out.println("Comparing passwords.\n" +
                            "Encrypted: " + en + "\n" +
                            "Decrypted: " + de + "\n" +
                            "Hashed:    " + ha + "\n" +
                            "Stored:    " + dbCreds.getPassword());
                    if (!BCrypt.checkpw(de, dbCreds.getPassword())){
                        throw new DAOException(HttpStatus.SC_UNAUTHORIZED,"User Already Exists");
                    }
                }

//              check if token is expired, if so return/set new
                AuthTokenUtils.AuthToken token;
                try {
                    token = new AuthTokenUtils.AuthToken(keyManager.getSymmetricKey(),dbCreds.getAuthToken());
                } catch (AuthenticationException e) {
                    throw new DAOException(HttpStatus.SC_INTERNAL_SERVER_ERROR,"internal error");
                }
                if (c.getTime().getTime() > token.expirationDate) {
                    dbCreds.setAuthToken(AuthTokenUtils.getNewToken(keyManager.getSymmetricKey(), dbCreds));
                    dao.save(dbCreds);
                }

                return dbCreds;
            }
    }
 
源代码14 项目: FcmJava   文件: DefaultHttpClient.java
private void evaluateResponse(HttpResponse httpResponse) {

        // Early exit, if there is no HTTP Response:
        if (httpResponse == null) {
            return;
        }

        // Early exit, if we can't determine the Status:
        if (httpResponse.getStatusLine() == null) {
            return;
        }

        // Get the HTTP Status Code:
        int httpStatusCode = httpResponse.getStatusLine().getStatusCode();

        // Is it OK? So we can exit here:
        if (httpStatusCode == HttpStatus.SC_OK) {
            return;
        }

        // The Error Reason:
        String reasonPhrase = httpResponse.getStatusLine().getReasonPhrase();

        // If it is a Bad Request, we could not retry it:
        if (httpStatusCode == HttpStatus.SC_BAD_REQUEST) {
            throw new FcmBadRequestException(reasonPhrase);
        }

        // If we are unauthorized, we could not retry it:
        if (httpStatusCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new FcmAuthenticationException(reasonPhrase);
        }

        // Any Status Code between 500 and 600 could be retried:
        if (httpStatusCode >= 500 && httpStatusCode < 600) {

            // Holds the Duration, which has been sent by the Server:
            OutParameter<Duration> result = new OutParameter<>();

            // Try to determine the next interval we can send at:
            if (RetryHeaderUtils.tryDetermineRetryDelay(httpResponse, result)) {
                throw new FcmRetryAfterException(httpStatusCode, reasonPhrase, result.get());
            }
        }

        throw new FcmGeneralException(httpStatusCode, reasonPhrase);
    }
 
源代码15 项目: sync-service   文件: SwiftManagerHTTPS.java
private String getWorkspacePermissions(User user, Workspace workspace) throws Exception {

        if (!isTokenActive()) {
            login();
        }

        TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] certificate, String authType) {
                return true;
            }
        };

        SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", 5000, sf));
        ClientConnectionManager ccm = new SingleClientConnManager(registry);

        HttpClient httpClient = new DefaultHttpClient(ccm);

        String url = this.storageUrl + "/" + workspace.getSwiftContainer();

        try {

            HttpHead request = new HttpHead(url);
            request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);

            HttpResponse response = httpClient.execute(request);

            SwiftResponse swiftResponse = new SwiftResponse(response);

            if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                throw new UnauthorizedException("404 User unauthorized");
            }

            if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
                throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
            }

            // We suppose there are the same permissions for read and write
            Header containerWriteHeader = swiftResponse.getResponseHeader(SwiftResponse.X_CONTAINER_WRITE);

            if (containerWriteHeader == null) {
                return "";
            }

            return containerWriteHeader.getValue();

        } finally {
            httpClient.getConnectionManager().shutdown();
        }
    }
 
源代码16 项目: cosmic   文件: HttpStatusCodeHelper.java
public static boolean isUnauthorized(final int statusCode) {
    return statusCode == HttpStatus.SC_UNAUTHORIZED;
}
 
源代码17 项目: sync-service   文件: SwiftManagerHTTPS.java
@Override
public void login() throws EndpointNotFoundException, UnauthorizedException, UnexpectedStatusCodeException,
        IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, UnrecoverableKeyException {

    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {
            return true;
        }
    };

    SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("https", 5000, sf));
    ClientConnectionManager ccm = new SingleClientConnManager(registry);

    HttpClient httpClient = new DefaultHttpClient(ccm);

    try {
        HttpPost request = new HttpPost(authUrl);

        String body = String
                .format("{\"auth\": {\"passwordCredentials\": {\"username\": \"%s\", \"password\": \"%s\"}, \"tenantName\":\"%s\"}}",
                user, password, tenant);
        StringEntity entity = new StringEntity(body);
        entity.setContentType("application/json");
        request.setEntity(entity);
        HttpResponse response = httpClient.execute(request);

        SwiftResponse swiftResponse = new SwiftResponse(response);

        if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new UnauthorizedException("404 User unauthorized");
        }

        if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
            throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
        }

        String responseBody = swiftResponse.getResponseBodyAsString();

        Gson gson = new Gson();
        LoginResponseObject loginResponse = gson.fromJson(responseBody, LoginResponseObject.class);

        this.authToken = loginResponse.getAccess().getToken().getId();

        Boolean endpointFound = false;

        for (ServiceObject service : loginResponse.getAccess().getServiceCatalog()) {

            if (service.getType().equals("object-store")) {
                this.storageUrl = service.getEndpoints().get(0).getPublicURL();
                endpointFound = true;
                break;
            }
        }

        // get the token issue swift date
        DateTimeZone.setDefault(DateTimeZone.UTC);
        DateTimeFormatter dateStringFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS");
        DateTime issuedAt = dateStringFormat.parseDateTime(loginResponse.getAccess().getToken().getIssuedAt());

        // get the token expiration swift date
        dateStringFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");
        DateTime expiresAt = dateStringFormat.parseDateTime(loginResponse.getAccess().getToken().getExpires());

        // calculate the period between these two dates and add it to our
        // current time because datetime can differ from Swift and this
        // device
        Period period = new Period(issuedAt, expiresAt);
        expirationDate = DateTime.now().plus(period);

        if (!endpointFound) {
            throw new EndpointNotFoundException();
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
源代码18 项目: flink-crawler   文件: ExceptionUtils.java
public static FetchStatus mapHttpStatusToFetchStatus(int httpStatus) {
    switch (httpStatus) {
        case HttpStatus.SC_OK:
            return FetchStatus.FETCHED;

        case HttpStatus.SC_FORBIDDEN:
            return FetchStatus.HTTP_FORBIDDEN;

        case HttpStatus.SC_UNAUTHORIZED:
        case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
            return FetchStatus.HTTP_UNAUTHORIZED;

        case HttpStatus.SC_NOT_FOUND:
            return FetchStatus.HTTP_NOT_FOUND;

        case HttpStatus.SC_GONE:
            return FetchStatus.HTTP_GONE;

        case HttpStatus.SC_TEMPORARY_REDIRECT:
        case HttpStatus.SC_MOVED_TEMPORARILY:
        case HttpStatus.SC_SEE_OTHER:
            return FetchStatus.HTTP_TOO_MANY_REDIRECTS;

        case HttpStatus.SC_MOVED_PERMANENTLY:
            return FetchStatus.HTTP_MOVED_PERMANENTLY;

        default:
            if (httpStatus < 300) {
                LOGGER.warn("Invalid HTTP status for exception: " + httpStatus);
                return FetchStatus.HTTP_SERVER_ERROR;
            } else if (httpStatus < 400) {
                return FetchStatus.HTTP_REDIRECTION_ERROR;
            } else if (httpStatus < 500) {
                return FetchStatus.HTTP_CLIENT_ERROR;
            } else if (httpStatus < 600) {
                return FetchStatus.HTTP_SERVER_ERROR;
            } else {
                LOGGER.warn("Unknown status: " + httpStatus);
                return FetchStatus.HTTP_SERVER_ERROR;
            }
    }
}
 
源代码19 项目: sync-service   文件: SwiftManager.java
@Override
public void grantUserToWorkspace(User owner, User user, Workspace workspace) throws Exception {

    if (!isTokenActive()) {
        login();
    }

    String permissions = getWorkspacePermissions(owner, workspace);

    String tenantUser = Config.getSwiftTenant() + ":" + user.getSwiftUser();

    if (permissions.contains(tenantUser)) {
        return;
    }

    permissions += "," + tenantUser;

    HttpClient httpClient = new DefaultHttpClient();
    String url = this.storageUrl + "/" + workspace.getSwiftContainer();

    try {

        HttpPut request = new HttpPut(url);
        request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);
        request.setHeader(SwiftResponse.X_CONTAINER_READ, permissions);
        request.setHeader(SwiftResponse.X_CONTAINER_WRITE, permissions);

        HttpResponse response = httpClient.execute(request);

        SwiftResponse swiftResponse = new SwiftResponse(response);

        if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new UnauthorizedException("404 User unauthorized");
        }

        if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
            throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
源代码20 项目: davmail   文件: ExchangeFormAuthenticator.java
/**
 * Test authentication mode : form based or basic.
 *
 * @param url        exchange base URL
 * @param httpClient httpClient instance
 * @return true if basic authentication detected
 */
protected boolean isHttpAuthentication(HttpClient httpClient, String url) {
    return DavGatewayHttpClientFacade.getHttpStatus(httpClient, url) == HttpStatus.SC_UNAUTHORIZED;
}