Java Code Examples for org.apache.http.auth.AuthenticationException

The following examples show how to use org.apache.http.auth.AuthenticationException. These examples are extracted from open source projects. 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 Project: hop   Source File: Wsdl.java    License: 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 2
Source Project: letv   Source File: TVMAuthenticator.java    License: 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 3
/**
 * 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 4
Source Project: hawkular-agent   Source File: JolokiaClientFactory.java    License: 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 5
Source Project: ghwatch   Source File: RemoteSystemClient.java    License: 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 6
Source Project: YiBo   Source File: LibRequestDirector.java    License: 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 7
Source Project: pentaho-kettle   Source File: Wsdl.java    License: 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 8
Source Project: pentaho-kettle   Source File: HTTPProtocolTest.java    License: 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 9
Source Project: hop   Source File: HttpProtocol.java    License: 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 10
Source Project: hop   Source File: Wsdl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Load and parse the WSDL file using the wsdlLocator.
 *
 * @param wsdlLocator A WSDLLocator instance.
 * @param username    to use for authentication
 * @param password    to use for authentication
 * @return wsdl Definition.
 * @throws WSDLException on error.
 */
private Definition parse(WSDLLocator wsdlLocator, String username, String password ) throws WSDLException,
  HopException, AuthenticationException {

  WSDLReader wsdlReader = getReader();
  try {

    return wsdlReader.readWSDL( wsdlLocator );
  } catch ( WSDLException we ) {
    readWsdl( wsdlReader, wsdlURI.toString(), username, password );
    return null;
  }
}
 
Example 11
Source Project: ats-framework   Source File: GGSSchemeBase.java    License: 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 12
Source Project: letv   Source File: rrrrrc.java    License: Apache License 2.0 5 votes vote down vote up
public void run() {
    try {
        this.b043Dн043Dннн.authenticate();
        if (((b0417041704170417ЗЗ + b0417ЗЗЗ0417З) * b0417041704170417ЗЗ) % bЗ041704170417ЗЗ != bЗЗЗЗ0417З) {
            b0417041704170417ЗЗ = bЗЗ04170417ЗЗ();
            bЗЗЗЗ0417З = bЗЗ04170417ЗЗ();
        }
    } catch (AuthenticationException e) {
        try {
            e.printStackTrace();
        } catch (Exception e2) {
            throw e2;
        }
    }
}
 
Example 13
@Override
@Deprecated
public Header authenticate(
    final Credentials credentials,
    final HttpRequest request) throws AuthenticationException {
    return authenticate(credentials, request, null);
}
 
Example 14
Source Project: reposilite   Source File: DeployControllerTest.java    License: 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 15
Source Project: reposilite   Source File: DeployControllerTest.java    License: 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 16
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 17
/**
 * 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 18
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 19
Source Project: arangodb-java-driver   Source File: HttpConnection.java    License: 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 20
Source Project: knox   Source File: HiveDispatchUtils.java    License: 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 21
Source Project: knox   Source File: ImpalaDispatchUtils.java    License: 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 22
Source Project: ghwatch   Source File: RemoteSystemClient.java    License: 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 23
Source Project: ghwatch   Source File: RemoteSystemClient.java    License: 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 24
Source Project: ghwatch   Source File: UnreadNotificationsService.java    License: 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 25
Source Project: ghwatch   Source File: AuthenticationManager.java    License: 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 26
Source Project: ghwatch   Source File: WatchedRepositoriesService.java    License: 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 27
Source Project: tutorials   Source File: HttpClientBasicPostLiveTest.java    License: 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 28
Source Project: tutorials   Source File: HttpClientPostingLiveTest.java    License: 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 29
Source Project: pentaho-kettle   Source File: HTTPProtocol.java    License: 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 30
Source Project: pentaho-kettle   Source File: HTTPProtocolTest.java    License: 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", "", "" ) );
}