org.apache.http.auth.AuthenticationException Java Examples

The following examples show how to use org.apache.http.auth.AuthenticationException. 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: RemoteSystemClient.java    From ghwatch with Apache License 2.0 6 votes vote down vote up
protected static void processStandardHttpResponseCodes(HttpResponse httpResponse) throws AuthenticationException, IOException {
  int code = httpResponse.getStatusLine().getStatusCode();
  Log.d(TAG, "Response http code: " + code);
  if (code >= 200 && code <= 299)
    return;
  if (code == HttpStatus.SC_UNAUTHORIZED || code == HttpStatus.SC_FORBIDDEN) {
    String OTP = getHeaderValue(httpResponse, "X-GitHub-OTP");
    if (code == HttpStatus.SC_UNAUTHORIZED && OTP != null && OTP.contains("required")) {
      throw new OTPAuthenticationException(Utils.trimToNull(OTP.replace("required;", "")));
    }
    throw new AuthenticationException("Authentication problem: " + getResponseContentAsString(httpResponse));
  } else if (code == HttpStatus.SC_BAD_REQUEST || code == HttpStatus.SC_NOT_FOUND) {
    throw new InvalidObjectException("HttpCode=" + code + " message: " + getResponseContentAsString(httpResponse));
  } else {
    throw new IOException("HttpCode=" + code + " message: " + getResponseContentAsString(httpResponse));
  }
}
 
Example #2
Source File: HTTPProtocolTest.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
@Test
public void httpClientGetsClosed() throws IOException, AuthenticationException {
  CloseableHttpClient httpClient = Mockito.mock( CloseableHttpClient.class );
  CloseableHttpResponse response = Mockito.mock( CloseableHttpResponse.class );
  HTTPProtocol httpProtocol = new HTTPProtocol() {
    @Override CloseableHttpClient openHttpClient( String username, String password ) {
      return httpClient;
    }
  };
  String urlAsString = "http://url/path";
  when( httpClient.execute( Matchers.argThat( matchesGet() ) ) ).thenReturn( response );
  StatusLine statusLine = new BasicStatusLine( new ProtocolVersion( "http", 2, 0 ), HttpStatus.SC_OK, "blah" );
  BasicHttpEntity entity = new BasicHttpEntity();
  String content = "plenty of mocks for this test";
  entity.setContent( new ByteArrayInputStream( content.getBytes() ) );
  when( response.getEntity() ).thenReturn( entity );
  when( response.getStatusLine() ).thenReturn( statusLine );
  assertEquals( content, httpProtocol.get( urlAsString, "", "" ) );
  verify( httpClient ).close();
}
 
Example #3
Source File: JolokiaClientFactory.java    From hawkular-agent with Apache License 2.0 6 votes vote down vote up
@Override
public Header authenticate(Credentials credentials, HttpRequest request, HttpContext context)
        throws AuthenticationException {
    Args.notNull(credentials, "Credentials");
    Args.notNull(request, "HTTP request");

    // the bearer token is stored in the password field, not credentials.getUserPrincipal().getName()
    String bearerToken = credentials.getPassword();

    CharArrayBuffer buffer = new CharArrayBuffer(64);
    if (isProxy()) {
        buffer.append("Proxy-Authorization");
    } else {
        buffer.append("Authorization");
    }
    buffer.append(": Bearer ");
    buffer.append(bearerToken);

    return new BufferedHeader(buffer);
}
 
Example #4
Source File: Wsdl.java    From hop with Apache License 2.0 6 votes vote down vote up
private Definition readWsdl( WSDLReader wsdlReader, String uri, String username, String password ) throws WSDLException, HopException, AuthenticationException {

    try {
      HttpProtocol http = new HttpProtocol();
      Document doc = XmlHandler.loadXmlString( http.get( wsdlURI.toString(), username, password ), true, false );
      if ( doc != null ) {
        return ( wsdlReader.readWSDL( doc.getBaseURI(), doc ) );
      } else {
        throw new HopException( "Unable to get document." );
      }
    } catch ( MalformedURLException mue ) {
      throw new HopException( mue );
    } catch ( AuthenticationException ae ) {
      // re-throw this. If not IOException seems to catch it
      throw ae;
    } catch ( IOException ioe ) {
      throw new HopException( ioe );
    }
  }
 
Example #5
Source File: Wsdl.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
private Definition readWsdl( WSDLReader wsdlReader, String uri, String username, String password ) throws WSDLException, KettleException, AuthenticationException {

    try {
      HTTPProtocol http = new HTTPProtocol();
      Document doc = XMLHandler.loadXMLString( http.get( wsdlURI.toString(), username, password ), true, false );
      if ( doc != null ) {
        return ( wsdlReader.readWSDL( doc.getBaseURI(), doc ) );
      } else {
        throw new KettleException( "Unable to get document." );
      }
    } catch ( MalformedURLException mue ) {
      throw new KettleException( mue );
    } catch ( AuthenticationException ae ) {
      // re-throw this. If not IOException seems to catch it
      throw ae;
    } catch ( IOException ioe ) {
      throw new KettleException( ioe );
    }
  }
 
Example #6
Source File: AbstractHACCommunicationManager.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Send HTTP GET request to {@link #endpointUrl}, updates {@link #csrfToken}
 * token
 *
 * @return true if {@link #endpointUrl} is accessible
 * @throws IOException
 * @throws ClientProtocolException
 * @throws AuthenticationException
 */
protected void fetchCsrfTokenFromHac() throws ClientProtocolException, IOException, AuthenticationException {
	final HttpGet getRequest = new HttpGet(getEndpointUrl());

	try {
		final HttpResponse response = httpClient.execute(getRequest, getContext());
		final String responseString = new BasicResponseHandler().handleResponse(response);
		csrfToken = getCsrfToken(responseString);

		if (StringUtil.isBlank(csrfToken)) {
			throw new AuthenticationException(ErrorMessage.CSRF_TOKEN_CANNOT_BE_OBTAINED);
		}
	} catch (UnknownHostException error) {
		final String errorMessage = error.getMessage();
		final Matcher matcher = HACPreferenceConstants.HOST_REGEXP_PATTERN.matcher(getEndpointUrl());

		if (matcher.find() && matcher.group(1).equals(errorMessage)) {
			throw new UnknownHostException(
					String.format(ErrorMessage.UNKNOWN_HOST_EXCEPTION_MESSAGE_FORMAT, matcher.group(1)));
		}
		throw error;
	}
}
 
Example #7
Source File: TVMAuthenticator.java    From letv with Apache License 2.0 6 votes vote down vote up
public Token authenticate() throws AuthenticationException {
    Token bьььь044Cь = Token.bьььь044Cь(Type.SHORT_TERM);
    bьььь044Cь.loadToken(this.b04140414Д0414ДД);
    b0439ййййй(bьььь044Cь);
    if (bьььь044Cь.isTokenExpired()) {
        Log.d(bДД04140414ДД, "Credentials expired or do not exist. Requesting new token.");
        rrcrcc login = new cccrrr(this.b04140414Д0414ДД, this.bД041404140414ДД, ccccrr.getAppName(), ccccrr.useSSL()).login(this.bД0414Д0414ДД.getUserName(), this.bД0414Д0414ДД.getPassword());
        if (login.requestUnauthorized()) {
            b0449щ0449044904490449();
            throw new AuthenticationException();
        } else if (login.requestTimedOut()) {
            bщ04490449044904490449();
            if (((bХ0425Х042504250425 + b04250425Х042504250425) * bХ0425Х042504250425) % bХХ0425042504250425 != bХ04250425042504250425) {
                bХ0425Х042504250425 = 30;
                bХ04250425042504250425 = 78;
            }
            return bьььь044Cь;
        }
    }
    bщщ0449044904490449(bьььь044Cь);
    return bьььь044Cь;
}
 
Example #8
Source File: LibRequestDirector.java    From YiBo with Apache License 2.0 6 votes vote down vote up
private void processChallenges(
        final Map<String, Header> challenges,
        final AuthState authState,
        final AuthenticationHandler authHandler,
        final HttpResponse response,
        final HttpContext context)
            throws MalformedChallengeException, AuthenticationException {

    AuthScheme authScheme = authState.getAuthScheme();
    if (authScheme == null) {
        // Authentication not attempted before
        authScheme = authHandler.selectScheme(challenges, response, context);
        authState.setAuthScheme(authScheme);
    }
    String id = authScheme.getSchemeName();

    Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH));
    if (challenge == null) {
        throw new AuthenticationException(id +
            " authorization challenge expected, but not found");
    }
    authScheme.processChallenge(challenge);
    if (DEBUG) {
    	Logger.debug("Authorization challenge processed");
    }
}
 
Example #9
Source File: MonitoringClientBuilder.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
private Header basicSchema(HttpPost request) {
    try {
        return new BasicScheme().authenticate(getCredentials(configurationProvider), request, null);
    } catch (AuthenticationException e) {
        LOG.error("Could not initialize BasicSchema");
    }
    return null;
}
 
Example #10
Source File: RemoteSystemClient.java    From ghwatch with Apache License 2.0 5 votes vote down vote up
public static Response<String> deleteToURL(Context context, GHCredentials apiCredentials, String url, Map<String, String> headers)
        throws URISyntaxException, IOException, AuthenticationException {
  if (!Utils.isInternetConnectionAvailable(context))
    throw new NoRouteToHostException("Network not available");

  try {
    URI uri = new URI(url);
    DefaultHttpClient httpClient = prepareHttpClient(uri);

    HttpDelete httpPut = new HttpDelete(uri);
    setAuthenticationHeader(httpPut, apiCredentials);
    setHeaders(httpPut, requestGzipCompression(headers));

    // create response object here to measure request duration
    Response<String> ret = new Response<String>();
    ret.requestStartTime = System.currentTimeMillis();

    HttpResponse httpResponse = httpClient.execute(httpPut);

    parseResponseHeaders(context, httpResponse, ret);

    processStandardHttpResponseCodes(httpResponse);

    ret.data = getResponseContentAsString(httpResponse);

    ret.snapRequestDuration();
    writeReponseInfo(ret, context);
    return ret;
  } catch (IOException e) {
    logGithubAPiCallError(context, e);
    throw e;
  }
}
 
Example #11
Source File: DeployControllerTest.java    From reposilite with Apache License 2.0 5 votes vote down vote up
private void shouldReturn200AndSuccessMessage(String uri, String username, String password, String content) throws IOException, AuthenticationException {
    HttpResponse deployResponse = put(uri, username, password, content);
    assertEquals(HttpStatus.SC_OK, deployResponse.getStatusLine().getStatusCode());

    String result = IOUtils.toString(deployResponse.getEntity().getContent(), StandardCharsets.UTF_8);
    assertNotNull(result);
    assertEquals("Success", result);

    if (StringUtils.isEmpty(content)) {
        return;
    }

    assertEquals(HttpStatus.SC_OK, super.getAuthenticated(uri, username, password).getStatusCode());
    assertEquals(content, super.getAuthenticated(uri, username, password).parseAsString());
}
 
Example #12
Source File: RemoteSystemClient.java    From ghwatch with Apache License 2.0 5 votes vote down vote up
public static Response<?> postNoData(Context context, GHCredentials apiCredentials, String url, Map<String, String> headers) throws
        URISyntaxException, IOException, AuthenticationException {
  if (!Utils.isInternetConnectionAvailable(context))
    throw new NoRouteToHostException("Network not available");
  Log.d(TAG, "Going to perform POST request to " + url);

  try {
    URI uri = new URI(url);
    DefaultHttpClient httpClient = prepareHttpClient(uri);

    HttpPost httpPost = new HttpPost(uri);
    setAuthenticationHeader(httpPost, apiCredentials);
    setHeaders(httpPost, headers);

    // create response object here to measure request duration
    Response<String> ret = new Response<String>();
    ret.requestStartTime = System.currentTimeMillis();

    HttpResponse httpResponse = httpClient.execute(httpPost);
    parseResponseHeaders(context, httpResponse, ret);

    processStandardHttpResponseCodes(httpResponse);

    ret.snapRequestDuration();
    writeReponseInfo(ret, context);
    return ret;
  } catch (IOException e) {
    logGithubAPiCallError(context, e);
    throw e;
  }
}
 
Example #13
Source File: ImpalaDispatchUtils.java    From knox with Apache License 2.0 5 votes vote down vote up
public static void addCredentialsToRequest(HttpUriRequest request) {
  String principal = SubjectUtils.getCurrentEffectivePrincipalName();
  if ( principal != null ) {
    UsernamePasswordCredentials credentials =
        new UsernamePasswordCredentials(principal, PASSWORD_PLACEHOLDER);
    try {
      request.addHeader(new BasicScheme().authenticate(credentials, request, null));
    } catch (AuthenticationException e) {
      // impossible
    }
  }
}
 
Example #14
Source File: HiveDispatchUtils.java    From knox with Apache License 2.0 5 votes vote down vote up
public static void addCredentialsToRequest(HttpUriRequest request) {
  String principal = SubjectUtils.getCurrentEffectivePrincipalName();
  if ( principal != null ) {
    UsernamePasswordCredentials credentials =
        new UsernamePasswordCredentials(principal, PASSWORD_PLACEHOLDER);
    try {
      request.addHeader(new BasicScheme().authenticate(credentials, request, null));
    } catch (AuthenticationException e) {
      // impossible
    }
  }
}
 
Example #15
Source File: UnreadNotificationsService.java    From ghwatch with Apache License 2.0 5 votes vote down vote up
/**
 * @param lastModified timestamp used in "If-Modified-Since" http header, can be null
 * @return null if lastModified used and nothing new
 * @throws InvalidObjectException
 * @throws NoRouteToHostException
 * @throws AuthenticationException
 * @throws IOException
 * @throws JSONException
 * @throws URISyntaxException
 */
protected NotificationStream readNotificationStreamFromServer(String lastModified) throws InvalidObjectException, NoRouteToHostException,
        AuthenticationException, IOException, JSONException, URISyntaxException {

  NotificationStreamParser.IRepoVisibilityAdapter rva = createRepoVisibilityAdapter();

  String url = prepareNotificationLoadingURL(rva);

  Map<String, String> headers = null;
  if (lastModified != null) {
    headers = new HashMap<String, String>();
    headers.put("If-Modified-Since", lastModified);
  }

  Response<JSONArray> resp = RemoteSystemClient.getJSONArrayFromUrl(context, authenticationManager.getGhApiCredentials(context), url, headers);

  if (resp.notModified)
    return null;

  NotificationStream ns = NotificationStreamParser.parseNotificationStream(null, resp.data, rva);
  ns.setLastModified(resp.lastModified);
  if (lastModified == null)
    ns.setLastFullUpdateTimestamp(System.currentTimeMillis());

  //handle paging
  while (resp.linkNext != null) {
    resp = RemoteSystemClient.getJSONArrayFromUrl(context, authenticationManager.getGhApiCredentials(context), resp.linkNext, headers);
    NotificationStreamParser.parseNotificationStream(ns, resp.data, rva);
  }

  return ns;
}
 
Example #16
Source File: AbstractHACCommunicationManager.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves csrf token from response body
 *
 * @param responseBody
 *            response body of GET method
 * @return csrf token
 * @throws AuthenticationException
 */
protected String getCsrfToken(String responseBody) throws AuthenticationException {
	if (StringUtil.isBlank(responseBody)) {
		throw new AuthenticationException(ErrorMessage.CSRF_RESPONSE_CANNOT_BE_BLANK);
	}

	final Document document = Jsoup.parse(responseBody);
	return document.select(Meta.CSRF_META_TAG).attr(Meta.CSRF_META_TAG_CONTENT);
}
 
Example #17
Source File: LocalhostrUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
public static void fileUpload() throws IOException {

        File file = new File("/home/vigneshwaran/VIGNESH/nu-test5.txt");
        DefaultHttpClient httpclient = new DefaultHttpClient();

        UsernamePasswordCredentials upc = new UsernamePasswordCredentials("[email protected]", "");


        HttpPost httppost = new HttpPost("http://api.localhostr.com/file");
        try {
            httppost.addHeader(new BasicScheme().authenticate(upc, httppost));
        } catch (AuthenticationException ex) {
            Logger.getLogger(LocalhostrUploaderPlugin.class.getName()).log(Level.SEVERE, null, ex);
        }

        MultipartEntity mpEntity = new MultipartEntity();
        ContentBody cbFile = new FileBody(file);
        mpEntity.addPart("name", new StringBody(file.getName()));
        mpEntity.addPart("file", cbFile);


        httppost.setEntity(mpEntity);
        System.out.println("Now uploading your file into localhost...........................");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        System.out.println(response.getStatusLine());
        if (resEntity != null) {

            String tmp = EntityUtils.toString(resEntity);
            System.out.println(tmp);
            downloadlink = tmp.substring(tmp.indexOf("http:"));
            downloadlink = downloadlink.substring(0, downloadlink.indexOf("\""));
            System.out.println("download link : " + downloadlink);

        }
//           uploadresponse = response.getLastHeader("Location").getValue();
//        System.out.println("Upload response : " + uploadresponse);
    }
 
Example #18
Source File: HttpConnection.java    From arangodb-java-driver with Apache License 2.0 5 votes vote down vote up
public Credentials addCredentials(final HttpRequestBase httpRequest) {
    Credentials credentials = null;
    if (user != null) {
        credentials = new UsernamePasswordCredentials(user, password != null ? password : "");
        try {
            httpRequest.addHeader(new BasicScheme().authenticate(credentials, httpRequest, null));
        } catch (final AuthenticationException e) {
            throw new ArangoDBException(e);
        }
    }
    return credentials;
}
 
Example #19
Source File: DeployControllerTest.java    From reposilite with Apache License 2.0 5 votes vote down vote up
private void shouldReturn401AndGivenMessage(String uri, String username, String password, String content, String message) throws IOException, AuthenticationException {
    HttpResponse response = put(uri, username, password, content);
    assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());

    String result = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
    assertNotNull(result);
    assertTrue(result.contains(message));
}
 
Example #20
Source File: AuthenticationManager.java    From ghwatch with Apache License 2.0 5 votes vote down vote up
private String remoteLogin(Context context, GHCredentials cred, String otp) throws JSONException, NoRouteToHostException, AuthenticationException,
    ClientProtocolException, URISyntaxException, IOException {
  Map<String, String> headers = null;
  otp = Utils.trimToNull(otp);
  if (otp != null) {
    headers = new HashMap<String, String>();
    headers.put("X-GitHub-OTP", otp);
  }
  String content = GH_AUTH_REQ_CONTENT.replace("*fp*", System.currentTimeMillis() + "");
  Response<String> resp = RemoteSystemClient.putToURL(context, cred, GH_AUTH_REQ_URL, headers, content);
  JSONObject jo = new JSONObject(resp.data);
  return jo.getString("token");
}
 
Example #21
Source File: BackportWindowsNegotiateScheme.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Deprecated
public Header authenticate(
    final Credentials credentials,
    final HttpRequest request) throws AuthenticationException {
    return authenticate(credentials, request, null);
}
 
Example #22
Source File: WatchedRepositoriesService.java    From ghwatch with Apache License 2.0 5 votes vote down vote up
protected WatchedRepositories readFromServer(String url) throws InvalidObjectException, NoRouteToHostException, AuthenticationException, IOException,
    JSONException, URISyntaxException {

  Response<JSONArray> resp = RemoteSystemClient.getJSONArrayFromUrl(context, authenticationManager.getGhApiCredentials(context), url, null);

  if (resp.notModified)
    return null;

  WatchedRepositories ns = WatchedRepositoriesParser.parseNotificationStream(resp.data);
  ns.setLastFullUpdateTimestamp(System.currentTimeMillis());
  return ns;
}
 
Example #23
Source File: HttpClientBasicPostLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException, AuthenticationException {
    final HttpPost request = new HttpPost(SAMPLE_URL);
    request.setEntity(new StringEntity("in the body of the POST"));
    final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("username", "password");
    request.addHeader(new BasicScheme().authenticate(creds, request, null));
    instance.execute(request);
}
 
Example #24
Source File: HttpClientPostingLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws IOException, AuthenticationException {
    final CloseableHttpClient client = HttpClients.createDefault();
    final HttpPost httpPost = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION);

    httpPost.setEntity(new StringEntity("test post"));
    final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
    httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null));

    final CloseableHttpResponse response = client.execute(httpPost);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}
 
Example #25
Source File: GGSSchemeBase.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 * @deprecated (4.2) Use {@link ContextAwareAuthScheme#authenticate(Credentials, HttpRequest, org.apache.http.protocol.HttpContext)}
 */
@Deprecated
public Header authenticate(
                            final Credentials credentials,
                            final HttpRequest request ) throws AuthenticationException {

    return authenticate(credentials, request, null);
}
 
Example #26
Source File: HTTPProtocol.java    From pentaho-kettle 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 The url to connect to
 * @param username Basic Authentication username
 * @param password Basic Authentication password
 * @return If the status code returned not -1 and 401 then the contents are returned. If the status code is 401 an
 * AuthenticationException is thrown.
 * @throws AuthenticationException
 * @throws IOException
 */
public String get( String urlAsString, String username, String password )
  throws IOException, AuthenticationException {

  HttpGet getMethod = new HttpGet( urlAsString );
  try ( CloseableHttpClient httpClient = openHttpClient( username, password ) ) {
    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 #27
Source File: HTTPProtocolTest.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Test
public void getsAResponse() throws IOException, AuthenticationException {
  stubFor( get( urlEqualTo( "/some/thing" ) )
    .willReturn( aResponse()
      .withHeader( "Content-Type", "text/plain" )
      .withBody( HELLO_WORLD ) ) );
  HTTPProtocol httpProtocol = new HTTPProtocol();
  assertEquals( HELLO_WORLD, httpProtocol.get( "http://localhost:55555/some/thing", "", "" ) );
}
 
Example #28
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 #29
Source File: Http4SignatureAuthScheme.java    From httpsig-java with The Unlicense 4 votes vote down vote up
public Header authenticate(Credentials credentials, HttpRequest request)
        throws AuthenticationException {

    if (credentials instanceof SignerCredentials) {
        Signer signer = ((SignerCredentials) credentials).getSigner();
        String headers = this.getParameter(Constants.HEADERS);
        String algorithms = this.getParameter(Constants.ALGORITHMS);

        Challenge challenge = new Challenge(this.getRealm(), Constants.parseTokens(headers), Challenge.parseAlgorithms(algorithms));

        if (this.rotate) {
            this.rotate = false;
            if (!signer.rotateKeys(challenge, this.lastAuthz)) {
                signer.rotateKeys(challenge);
                return null;
            }
        }

        RequestContent.Builder sigBuilder = new RequestContent.Builder();
        sigBuilder.setRequestTarget(request.getRequestLine().getMethod(),
                request.getRequestLine().getUri());

        for (Header header : request.getAllHeaders()) {
            if (header.getName().toLowerCase().equals("connection")) {
                sigBuilder.addHeader("connection", header.getValue().toLowerCase());
            } else {
                sigBuilder.addHeader(header.getName(), header.getValue());
            }
        }

        if (sigBuilder.build().getDate() == null) {
            sigBuilder.addDateNow();
            request.addHeader(Constants.HEADER_DATE, sigBuilder.build().getDate());
        }

        Authorization authorization = signer.sign(sigBuilder.build());
        this.lastAuthz = authorization;
        if (authorization != null) {
            return new BasicHeader(Constants.AUTHORIZATION, authorization.getHeaderValue());
        }
    }

    return null;
}
 
Example #30
Source File: RemoteSystemClient.java    From ghwatch with Apache License 2.0 4 votes vote down vote up
public static Response<String> putToURL(Context context, GHCredentials apiCredentials, String url, Map<String, String> headers, String content)
        throws URISyntaxException, IOException, AuthenticationException {
  if (!Utils.isInternetConnectionAvailable(context))
    throw new NoRouteToHostException("Network not available");

  Log.d(TAG, "Going to perform PUT request to " + url);

  try {
    URI uri = new URI(url);
    DefaultHttpClient httpClient = prepareHttpClient(uri);


    HttpPut httpPut = new HttpPut(uri);

    setAuthenticationHeader(httpPut, apiCredentials);
    setJsonContentTypeHeader(httpPut);
    setHeaders(httpPut, requestGzipCompression(headers));

    if (content != null)
      httpPut.setEntity(new StringEntity(content, "UTF-8"));

    // create response object here to measure request duration
    Response<String> ret = new Response<String>();
    ret.requestStartTime = System.currentTimeMillis();

    HttpResponse httpResponse = httpClient.execute(httpPut);

    parseResponseHeaders(context, httpResponse, ret);

    processStandardHttpResponseCodes(httpResponse);

    ret.data = getResponseContentAsString(httpResponse);

    ret.snapRequestDuration();
    writeReponseInfo(ret, context);
    return ret;
  } catch (IOException e) {
    logGithubAPiCallError(context, e);
    throw e;
  }
}