Java Code Examples for org.apache.http.HttpStatus#SC_UNAUTHORIZED

The following examples show how to use org.apache.http.HttpStatus#SC_UNAUTHORIZED . 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: BrocadeVcsApi.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 2
Source File: HttpUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * 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;

}
 
Example 3
Source File: HttpUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * 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 "{}";
}
 
Example 4
Source File: HttpProtocol.java    From hop with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 5
Source File: IndegoController.java    From iot-device-bosch-indego-controller with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 6
Source File: HttpClientErrorHandler.java    From swagger-brake with Apache License 2.0 5 votes vote down vote up
@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");
    }
}
 
Example 7
Source File: MCRDataciteClient.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
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);
        }
    }
 
Example 8
Source File: ProxyFacetSupport.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example 9
Source File: CookiesHandlerFilter.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
@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;
}
 
Example 10
Source File: SwiftManagerHTTPS.java    From sync-service with Apache License 2.0 5 votes vote down vote up
@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();
    }
}
 
Example 11
Source File: SwiftManager.java    From sync-service with Apache License 2.0 4 votes vote down vote up
@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();
    }
}
 
Example 12
Source File: ExceptionUtils.java    From flink-crawler with Apache License 2.0 4 votes vote down vote up
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;
            }
    }
}
 
Example 13
Source File: SwiftManagerHTTPS.java    From sync-service with Apache License 2.0 4 votes vote down vote up
@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();
    }
}
 
Example 14
Source File: HttpStatusCodeHelper.java    From cosmic with Apache License 2.0 4 votes vote down vote up
public static boolean isUnauthorized(final int statusCode) {
    return statusCode == HttpStatus.SC_UNAUTHORIZED;
}
 
Example 15
Source File: SwiftManagerHTTPS.java    From sync-service with Apache License 2.0 4 votes vote down vote up
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();
        }
    }
 
Example 16
Source File: DefaultHttpClient.java    From FcmJava with MIT License 4 votes vote down vote up
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);
    }
 
Example 17
Source File: AuthServerLogic.java    From divide with Apache License 2.0 4 votes vote down vote up
/**
     * 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;
            }
    }
 
Example 18
Source File: FileResponse.java    From storm-crawler with Apache License 2.0 4 votes vote down vote up
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;
    }
}
 
Example 19
Source File: TencentErrorAdaptor.java    From YiBo with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example 20
Source File: ExchangeFormAuthenticator.java    From davmail with GNU General Public License v2.0 2 votes vote down vote up
/**
 * 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;
}