List of usage examples for org.apache.http.impl.client BasicCredentialsProvider setCredentials
public void setCredentials(final AuthScope authscope, final Credentials credentials)
From source file:org.bimserver.build.CreateGitHubRelease.java
public static void main(String[] args) { String username = args[0];/*from w w w. j a va 2 s . c o m*/ String password = args[1]; String repo = args[2]; String project = args[3]; String tagname = args[4]; String name = args[5]; String body = args[6]; String draft = args[7]; String prerelease = args[8]; String filesString = args[9]; String[] filenames = filesString.split(";"); GitHubClient gitHubClient = new GitHubClient("api.github.com"); gitHubClient.setCredentials(username, password); Map<String, String> map = new HashMap<String, String>(); map.put("tag_name", tagname); // map.put("target_commitish", "test"); map.put("name", name); map.put("body", body); // map.put("draft", draft); // map.put("prerelease", prerelease); try { String string = "/repos/" + repo + "/" + project + "/releases"; System.out.println(string); JsonObject gitHubResponse = gitHubClient.post(string, map, JsonObject.class); System.out.println(gitHubResponse); String id = gitHubResponse.get("id").getAsString(); HttpHost httpHost = new HttpHost("uploads.github.com", 443, "https"); BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider(); basicCredentialsProvider.setCredentials(new AuthScope(httpHost), new UsernamePasswordCredentials(username, password)); HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier(); SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); CloseableHttpClient client = HttpClients.custom() .setDefaultCredentialsProvider(basicCredentialsProvider) .setHostnameVerifier((X509HostnameVerifier) hostnameVerifier).setSSLSocketFactory(sslsf) .build(); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(httpHost, basicAuth); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(basicCredentialsProvider); context.setAuthCache(authCache); for (String filename : filenames) { File file = new File(filename); String url = "https://uploads.github.com/repos/" + repo + "/" + project + "/releases/" + id + "/assets?name=" + file.getName(); HttpPost post = new HttpPost(url); post.setHeader("Accept", "application/vnd.github.manifold-preview"); post.setHeader("Content-Type", "application/zip"); post.setEntity(new InputStreamEntity(new FileInputStream(file), file.length())); HttpResponse execute = client.execute(httpHost, post, context); execute.getEntity().getContent().close(); } } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } }
From source file:be.dnsbelgium.rdap.client.RDAPCLI.java
public static void main(String[] args) { LOGGER.debug("Create the command line parser"); CommandLineParser parser = new GnuParser(); LOGGER.debug("Create the options"); Options options = new RDAPOptions(Locale.ENGLISH); try {/*from www .j av a 2 s . c o m*/ LOGGER.debug("Parse the command line arguments"); CommandLine line = parser.parse(options, args); if (line.hasOption("help")) { printHelp(options); return; } if (line.getArgs().length == 0) { throw new IllegalArgumentException("You must provide a query"); } String query = line.getArgs()[0]; Type type = (line.getArgs().length == 2) ? Type.valueOf(line.getArgs()[1].toUpperCase()) : guessQueryType(query); LOGGER.debug("Query: {}, Type: {}", query, type); try { SSLContextBuilder sslContextBuilder = SSLContexts.custom(); if (line.hasOption(RDAPOptions.TRUSTSTORE)) { sslContextBuilder.loadTrustMaterial( RDAPClient.getKeyStoreFromFile(new File(line.getOptionValue(RDAPOptions.TRUSTSTORE)), line.getOptionValue(RDAPOptions.TRUSTSTORE_TYPE, RDAPOptions.DEFAULT_STORETYPE), line.getOptionValue(RDAPOptions.TRUSTSTORE_PASS, RDAPOptions.DEFAULT_PASS))); } if (line.hasOption(RDAPOptions.KEYSTORE)) { sslContextBuilder.loadKeyMaterial( RDAPClient.getKeyStoreFromFile(new File(line.getOptionValue(RDAPOptions.KEYSTORE)), line.getOptionValue(RDAPOptions.KEYSTORE_TYPE, RDAPOptions.DEFAULT_STORETYPE), line.getOptionValue(RDAPOptions.KEYSTORE_PASS, RDAPOptions.DEFAULT_PASS)), line.getOptionValue(RDAPOptions.KEYSTORE_PASS, RDAPOptions.DEFAULT_PASS).toCharArray()); } SSLContext sslContext = sslContextBuilder.build(); final String url = line.getOptionValue(RDAPOptions.URL); final HttpHost host = Utils.httpHost(url); HashSet<Header> headers = new HashSet<Header>(); headers.add(new BasicHeader("Accept-Language", line.getOptionValue(RDAPOptions.LANG, Locale.getDefault().toString()))); HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultHeaders(headers) .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext, (line.hasOption(RDAPOptions.INSECURE) ? new AllowAllHostnameVerifier() : new BrowserCompatHostnameVerifier()))); if (line.hasOption(RDAPOptions.USERNAME) && line.hasOption(RDAPOptions.PASSWORD)) { BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()), new UsernamePasswordCredentials(line.getOptionValue(RDAPOptions.USERNAME), line.getOptionValue(RDAPOptions.PASSWORD))); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } RDAPClient rdapClient = new RDAPClient(httpClientBuilder.build(), url); ObjectMapper mapper = new ObjectMapper(); JsonNode json = null; switch (type) { case DOMAIN: json = rdapClient.getDomainAsJson(query); break; case ENTITY: json = rdapClient.getEntityAsJson(query); break; case AUTNUM: json = rdapClient.getAutNum(query); break; case IP: json = rdapClient.getIp(query); break; case NAMESERVER: json = rdapClient.getNameserver(query); break; } PrintWriter out = new PrintWriter(System.out, true); if (line.hasOption(RDAPOptions.RAW)) { mapper.writer().writeValue(out, json); } else if (line.hasOption(RDAPOptions.PRETTY)) { mapper.writer(new DefaultPrettyPrinter()).writeValue(out, json); } else if (line.hasOption(RDAPOptions.YAML)) { DumperOptions dumperOptions = new DumperOptions(); dumperOptions.setPrettyFlow(true); dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); dumperOptions.setSplitLines(true); Yaml yaml = new Yaml(dumperOptions); Map data = mapper.convertValue(json, Map.class); yaml.dump(data, out); } else { mapper.writer(new MinimalPrettyPrinter()).writeValue(out, json); } out.flush(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); System.exit(-1); } } catch (org.apache.commons.cli.ParseException e) { printHelp(options); System.exit(-1); } }
From source file:com.ibm.watson.developer_cloud.retrieve_and_rank.v1.utils.HttpSolrClientUtils.java
/** * Creates the {@link HttpClient} to use with the Solrj * * @param url the Solr server url//from w ww .ja va 2 s . c om * @param username the {@link RetrieveAndRank} service username * @param password the {@link RetrieveAndRank} service password * @return the {@link HttpClient} */ public static HttpClient createHttpClient(String url, String username, String password) { URI scopeUri = URI.create(url); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(scopeUri.getHost(), scopeUri.getPort()), new UsernamePasswordCredentials(username, password)); HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(128).setMaxConnPerRoute(32) .setDefaultRequestConfig( RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build()) .setDefaultCredentialsProvider(credentialsProvider) .addInterceptorFirst(new PreemptiveAuthInterceptor()); return builder.build(); }
From source file:com.ibm.watson.retrieveandrank.app.rest.UtilityFunctions.java
public static HttpClientBuilder createHTTPBuilder(URI uri, String username, String password) { final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(username, password)); final HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(128).setMaxConnPerRoute(32) .setDefaultRequestConfig(/* ww w. ja v a 2 s . c o m*/ RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build()); builder.setDefaultCredentialsProvider(credentialsProvider); builder.addInterceptorFirst(new PreemptiveAuthInterceptor()); return builder; }
From source file:org.springframework.cloud.stream.binder.rabbit.admin.RabbitManagementUtils.java
public static RestTemplate buildRestTemplate(String adminUri, String user, String password) { BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(user, password)); HttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); // Set up pre-emptive basic Auth because the rabbit plugin doesn't currently support challenge/response for PUT // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local; from the apache docs... // auth cache BasicScheme basicAuth = new BasicScheme(); URI uri;//from w w w. ja v a 2 s . c o m try { uri = new URI(adminUri); } catch (URISyntaxException e) { throw new RabbitAdminException("Invalid URI", e); } authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), basicAuth); // Add AuthCache to the execution context final HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient) { @Override protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { return localContext; } }); restTemplate.setMessageConverters( Collections.<HttpMessageConverter<?>>singletonList(new MappingJackson2HttpMessageConverter())); return restTemplate; }
From source file:org.apache.jena.jdbc.remote.connections.TestRemoteEndpointConnectionWithAuth.java
/** * Setup for the tests by allocating a Fuseki instance to work with * @throws IOException /*from w ww .jav a2s.c o m*/ */ @BeforeClass public static void setup() throws IOException { SecurityHandler sh = FusekiTestAuth.makeSimpleSecurityHandler("/*", USER, PASSWORD); FusekiTestAuth.setupServer(true, sh); BasicCredentialsProvider credsProv = new BasicCredentialsProvider(); credsProv.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USER, PASSWORD)); client = HttpClients.custom().setDefaultCredentialsProvider(credsProv).build(); }
From source file:io.github.jonestimd.neo4j.client.http.ApacheHttpDriver.java
private static BasicCredentialsProvider credentialsProvider(String userName, String password, String host, int port) { BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(userName, password)); return credentialsProvider; }
From source file:com.ibm.watson.apis.conversation_enhanced.utils.HttpSolrClientUtils.java
/** * Creates the {@link HttpClient} to use with the Solrj * * @param url the Solr server url//from ww w.j a v a2 s. c o m * @param username the {@link RetrieveAndRank} service username * @param password the {@link RetrieveAndRank} service password * @return the {@link HttpClient} */ private static HttpClient createHttpClient(String url, String username, String password) { final URI scopeUri = URI.create(url); logger.info(Messages.getString("HttpSolrClientUtils.CREATING_HTTP_CLIENT")); //$NON-NLS-1$ final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(scopeUri.getHost(), scopeUri.getPort()), new UsernamePasswordCredentials(username, password)); final HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(128).setMaxConnPerRoute(32) .setDefaultRequestConfig( RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build()) .setDefaultCredentialsProvider(credentialsProvider) .addInterceptorFirst(new PreemptiveAuthInterceptor()); return builder.build(); }
From source file:org.apache.jena.jdbc.remote.results.TestRemoteEndpointResultsWithAuth.java
/** * Setup for the tests by allocating a Fuseki instance to work with * /*from w ww . j a v a2 s . com*/ * @throws SQLException * @throws IOException */ @BeforeClass public static void setup() throws SQLException, IOException { SecurityHandler sh = FusekiTestAuth.makeSimpleSecurityHandler("/*", USER, PASSWORD); FusekiTestAuth.setupServer(true, sh); BasicCredentialsProvider credsProv = new BasicCredentialsProvider(); credsProv.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USER, PASSWORD)); client = HttpClients.custom().setDefaultCredentialsProvider(credsProv).build(); connection = new RemoteEndpointConnection(FusekiTestAuth.serviceQuery(), FusekiTestAuth.serviceUpdate(), null, null, null, null, client, JenaConnection.DEFAULT_HOLDABILITY, JdbcCompatibility.DEFAULT, null, null); connection.setJdbcCompatibilityLevel(JdbcCompatibility.HIGH); }
From source file:org.springframework.cloud.deployer.admin.shell.command.support.HttpClientUtils.java
/** * Ensures that the passed-in {@link RestTemplate} is using the Apache HTTP Client. If the optional {@code username} AND * {@code password} are not empty, then a {@link BasicCredentialsProvider} will be added to the {@link CloseableHttpClient}. * * Furthermore, you can set the underlying {@link SSLContext} of the {@link HttpClient} allowing you to accept self-signed * certificates./* w ww .j ava2s . c o m*/ * * @param restTemplate Must not be null * @param username Can be null * @param password Can be null * @param skipSslValidation Use with caution! If true certificate warnings will be ignored. */ public static void prepareRestTemplate(RestTemplate restTemplate, String username, String password, boolean skipSslValidation) { Assert.notNull(restTemplate, "The provided RestTemplate must not be null."); final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); if (StringUtils.hasText(username) && StringUtils.hasText(password)) { final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } if (skipSslValidation) { httpClientBuilder.setSSLContext(HttpClientUtils.buildCertificateIgnoringSslContext()); httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier()); } final CloseableHttpClient httpClient = httpClientBuilder.build(); final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); restTemplate.setRequestFactory(requestFactory); }