org.apache.http.auth.AUTH Java Examples

The following examples show how to use org.apache.http.auth.AUTH. 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: AbstractStreamingAnalyticsConnection.java    From streamsx.topology with Apache License 2.0 6 votes vote down vote up
protected boolean delete(String deleteJobUrl) throws IOException {
    boolean rc = false;
    String sReturn = "";

    Request request = Request
            .Delete(deleteJobUrl)
            .addHeader(AUTH.WWW_AUTH_RESP, getAuthorization())
            .useExpectContinue();

    Response response = executor.execute(request);
    HttpResponse hResponse = response.returnResponse();
    int rcResponse = hResponse.getStatusLine().getStatusCode();

    if (HttpStatus.SC_OK == rcResponse) {
        sReturn = EntityUtils.toString(hResponse.getEntity());
        rc = true;
    } else {
        rc = false;
    }
    traceLog.finest("Request: [" + deleteJobUrl + "]");
    traceLog.finest(rcResponse + ": " + sReturn);
    return rc;
}
 
Example #2
Source File: AbstractStreamingAnalyticsService.java    From streamsx.topology with Apache License 2.0 6 votes vote down vote up
/**
 * Submit an application bundle to execute as a job.
 */
protected JsonObject postJob(CloseableHttpClient httpClient,
        JsonObject service, File bundle, JsonObject jobConfigOverlay)
        throws IOException {

    String url = getJobSubmitUrl(httpClient, bundle);

    HttpPost postJobWithConfig = new HttpPost(url);
    postJobWithConfig.addHeader(AUTH.WWW_AUTH_RESP, getAuthorization());
    FileBody bundleBody = new FileBody(bundle, ContentType.APPLICATION_OCTET_STREAM);
    StringBody configBody = new StringBody(jobConfigOverlay.toString(), ContentType.APPLICATION_JSON);

    HttpEntity reqEntity = MultipartEntityBuilder.create()
            .addPart("bundle_file", bundleBody)
            .addPart("job_options", configBody).build();

    postJobWithConfig.setEntity(reqEntity);

    JsonObject jsonResponse = StreamsRestUtils.getGsonResponse(httpClient, postJobWithConfig);

    TRACE.info("Streaming Analytics service (" + getName() + "): submit job response:" + jsonResponse.toString());

    return jsonResponse;
}
 
Example #3
Source File: StreamsRestActions.java    From streamsx.topology with Apache License 2.0 6 votes vote down vote up
static Result<Job, JsonObject> submitJob(ApplicationBundle bundle, JsonObject jco) throws IOException {
	UploadedApplicationBundle uab = (UploadedApplicationBundle) bundle;
	
	JsonObject body = new JsonObject();
	body.addProperty("application", uab.getBundleId());
	body.addProperty("preview", false);		
	body.add("jobConfigurationOverlay", jco);
	
	final AbstractStreamsConnection conn = bundle.instance().connection();
	
	Request postBundle = Request.Post(bundle.instance().self() + "/jobs");
	postBundle.addHeader(AUTH.WWW_AUTH_RESP, conn.getAuthorization());
	postBundle.body(new StringEntity(body.toString(), ContentType.APPLICATION_JSON));		
	
	JsonObject response = requestGsonResponse(conn.executor, postBundle);
	
	Job job = Job.create(bundle.instance(), response.toString());
	
	if (!response.has(SubmissionResultsKeys.JOB_ID))
		response.addProperty(SubmissionResultsKeys.JOB_ID, job.getId());

	return new ResultImpl<Job, JsonObject>(true, job.getId(),
			() -> job, response);
}
 
Example #4
Source File: StreamsRestUtils.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a JSON response to an HTTP GET call
 * 
 * @param executor HTTP client executor to use for call
 * @param auth Authentication header contents, or null
 * @param inputString
 *            REST call to make
 * @return response from the inputString
 * @throws IOException
 */
static JsonObject getGsonResponse(Executor executor, String auth, String inputString)
        throws IOException {
    TRACE.fine("HTTP GET: " + inputString);
    Request request = Request.Get(inputString).useExpectContinue();
    
    if (null != auth) {
        request = request.addHeader(AUTH.WWW_AUTH_RESP, auth);
    }
    
    return requestGsonResponse(executor, request);
}
 
Example #5
Source File: StreamsRestUtils.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
private static InputStream rawStreamingGet(Executor executor,
        String auth, String url) throws IOException {
    TRACE.fine("HTTP GET: " + url);
    String accepted =
            ContentType.APPLICATION_OCTET_STREAM.getMimeType()
            + ","
            + "application/x-compressed";
    Request request = Request
            .Get(url)
            .addHeader("accept",accepted)
            .useExpectContinue();
    
    if (null != auth) {
        request = request.addHeader(AUTH.WWW_AUTH_RESP, auth);
    }
    
    Response response = executor.execute(request);
    HttpResponse hResponse = response.returnResponse();
    int rcResponse = hResponse.getStatusLine().getStatusCode();
    
    if (HttpStatus.SC_OK == rcResponse) {
        return hResponse.getEntity().getContent();
    } else {
        // all other errors...
        String httpError = "HttpStatus is " + rcResponse + " for url " + url;
        throw new RESTException(rcResponse, httpError);
    }
}
 
Example #6
Source File: AbstractStreamingAnalyticsService.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
JsonObject getServiceStatus(CloseableHttpClient httpClient)
          throws IOException, IllegalStateException {
      String url = getStatusUrl(httpClient);

      HttpGet getStatus = new HttpGet(url);
      getStatus.addHeader(AUTH.WWW_AUTH_RESP, getAuthorization());

      return StreamsRestUtils.getGsonResponse(httpClient, getStatus);
}
 
Example #7
Source File: RestUtils.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a JSON response to an HTTP GET call
 * 
 * @param executor HTTP client executor to use for call
 * @param auth Authentication header contents, or null
 * @param inputString
 *            REST call to make
 * @return response from the inputString
 * @throws IOException
 */
static JsonObject getGsonResponse(Executor executor, String auth, String url)
        throws IOException {
    TRACE.fine("HTTP GET: " + url);
    Request request = Request.Get(url).useExpectContinue();
    
    if (null != auth) {
        request = request.addHeader(AUTH.WWW_AUTH_RESP, auth);
    }
    
    return requestGsonResponse(executor, request);
}
 
Example #8
Source File: StreamsRestUtils.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a JSON response to an HTTP GET call
 * 
 * @param executor HTTP client executor to use for call
 * @param auth Authentication header contents, or null
 * @param inputString
 *            REST call to make
 * @return response from the inputString
 * @throws IOException
 */
static JsonObject getGsonResponse(Executor executor, String auth, String inputString)
        throws IOException {
    TRACE.fine("HTTP GET: " + inputString);
    Request request = Request.Get(inputString).useExpectContinue();

    if (null != auth) {
        request = request.addHeader(AUTH.WWW_AUTH_RESP, auth);
    }

    return requestGsonResponse(executor, request);
}
 
Example #9
Source File: StreamsRestActions.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
static Toolkit uploadToolkit(StreamsBuildService connection, File path) throws IOException {
  // Make sure it is a directory
  if (! path.isDirectory()) {
    throw new IllegalArgumentException("The specified toolkit path '" + path.toString() + "' is not a directory.");
  }

  // Make sure it contains toolkit.xml
  File toolkit = new File(path, "toolkit.xml");
  if (! toolkit.isFile()) {
    throw new IllegalArgumentException("The specified toolkit path '" + path.toString() + "' is not a toolkit.");
  }

  String toolkitsURL = connection.getToolkitsURL();
  Request post = Request.Post(toolkitsURL);
  post.addHeader(AUTH.WWW_AUTH_RESP, connection.getAuthorization());
  post.bodyStream(DirectoryZipInputStream.fromPath(path.toPath()), ContentType.create("application/zip"));

  Response response = connection.getExecutor().execute(post);
  HttpResponse httpResponse = response.returnResponse();
  int statusCode = httpResponse.getStatusLine().getStatusCode();
  // TODO The API is supposed to return CREATED, but there is a bug and it
  // returns OK.  When the bug is fixed, change this to accept only OK
  if (statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_OK) {
    String message = EntityUtils.toString(httpResponse.getEntity());
    throw RESTException.create(statusCode, message);
  }
  
  HttpEntity entity = httpResponse.getEntity();
  try (Reader r = new InputStreamReader(entity.getContent())) {
    JsonObject jresponse = new Gson().fromJson(r, JsonObject.class);
    EntityUtils.consume(entity);
    List<Toolkit> toolkitList = Toolkit.createToolkitList(connection, jresponse);

    // We expect a list of zero or one element.
    if (toolkitList.size() == 0) {
      return null;
    }
    return toolkitList.get(0);
  }
}
 
Example #10
Source File: StreamsRestActions.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
static ApplicationBundle uploadBundle(Instance instance, File bundle) throws IOException {
		
Request postBundle = Request.Post(instance.self() + "/applicationbundles");
postBundle.addHeader(AUTH.WWW_AUTH_RESP, instance.connection().getAuthorization());
postBundle.body(new FileEntity(bundle, ContentType.create("application/x-jar")));

JsonObject response = requestGsonResponse(instance.connection().executor, postBundle);

UploadedApplicationBundle uab = Element.createFromResponse(instance.connection(), response, UploadedApplicationBundle.class);
uab.setInstance(instance);
return uab;
  }
 
Example #11
Source File: SyntheticMonitorService.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private HttpClientContext getHttpClientContext() throws Exception {
    HttpProxyConfig httpProxyConfig = configRepository.getHttpProxyConfig();
    if (httpProxyConfig.host().isEmpty() || httpProxyConfig.username().isEmpty()) {
        return HttpClientContext.create();
    }

    // perform preemptive proxy authentication

    int proxyPort = MoreObjects.firstNonNull(httpProxyConfig.port(), 80);
    HttpHost proxyHost = new HttpHost(httpProxyConfig.host(), proxyPort);

    BasicScheme basicScheme = new BasicScheme();
    basicScheme.processChallenge(new BasicHeader(AUTH.PROXY_AUTH, "BASIC realm="));
    BasicAuthCache authCache = new BasicAuthCache();
    authCache.put(proxyHost, basicScheme);

    String password = httpProxyConfig.encryptedPassword();
    if (!password.isEmpty()) {
        password = Encryption.decrypt(password, configRepository.getLazySecretKey());
    }
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(proxyHost),
            new UsernamePasswordCredentials(httpProxyConfig.username(), password));
    HttpClientContext context = HttpClientContext.create();
    context.setAuthCache(authCache);
    context.setCredentialsProvider(credentialsProvider);
    return context;
}