List of usage examples for org.apache.http.auth AuthScope AuthScope
public AuthScope(final String host, final int port)
From source file:org.opensaml.security.httpclient.HttpClientSecurityParameters.java
/** * A convenience method to set a (single) username and password used for BASIC authentication. * To disable BASIC authentication pass null for the credentials instance. * // w w w . ja v a2s . c om * <p> * If the <code>authScope</code> is null, an {@link AuthScope} will be generated which specifies * any host, port, scheme and realm. * </p> * * <p>To specify multiple usernames and passwords for multiple host, port, scheme, and realm combinations, instead * provide an instance of {@link CredentialsProvider} via {@link #setCredentialsProvider(CredentialsProvider)}.</p> * * @param credentials the username and password credentials * @param scope the HTTP client auth scope with which to scope the credentials, may be null */ public void setBasicCredentialsWithScope(@Nullable final UsernamePasswordCredentials credentials, @Nullable final AuthScope scope) { if (credentials != null) { AuthScope authScope = scope; if (authScope == null) { authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT); } BasicCredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(authScope, credentials); credentialsProvider = provider; } else { credentialsProvider = null; } }
From source file:com.networkmanagerapp.RestartWifi.java
/** * Requests the restart of WIFI in the background * @param arg0 the data to process in the background * @throws IOException caught locally. Catch throws NullPointerException, also caught internally. *///from w w w . j av a2 s.c o m @Override protected void onHandleIntent(Intent arg0) { mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); showNotification(); try { String password = PreferenceManager.getDefaultSharedPreferences(this).getString("password_preference", ""); String ip = PreferenceManager.getDefaultSharedPreferences(this).getString("ip_preference", "192.168.1.1"); String enc = URLEncoder.encode(ip, "utf-8"); String scriptUrl = "http://" + enc + ":1080/cgi-bin/wifi.sh"; HttpParams httpParams = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. int timeoutConnection = 3000; HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 5000; HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket); HttpHost targetHost = new HttpHost(enc, 1080, "http"); DefaultHttpClient client = new DefaultHttpClient(httpParams); client.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("root", password)); HttpGet request = new HttpGet(scriptUrl); client.execute(targetHost, request); } catch (IOException ex) { try { Log.e("Network Manager reboot", ex.getLocalizedMessage()); } catch (NullPointerException e) { Log.e("Network Manager reboot", "Rebooting, " + e.getLocalizedMessage()); } } finally { mNM.cancel(R.string.wifi_service_restarted); stopSelf(); } }
From source file:org.jboss.as.test.integration.web.security.jaspi.WebSecurityJaspiWithFailingAuthModuleTestCase.java
protected void makeCall(String user, String pass, int expectedStatusCode) throws Exception { BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials(user, pass)); try (CloseableHttpClient httpclient = HttpClientBuilder.create() .setDefaultCredentialsProvider(credentialsProvider).build()) { HttpGet httpget = new HttpGet(url.toExternalForm() + "secured/"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); assertEquals(expectedStatusCode, statusLine.getStatusCode()); EntityUtils.consume(entity);/*from w ww. ja va2 s .co m*/ } }
From source file:com.serphacker.serposcope.scraper.http.ScrapClientProxiesIT.java
@Test public void testHttpProxyAuthWithSiteAuth() throws Exception { String username = "uuu"; String password = "ppp"; String url = "https://httpbin.org/basic-auth/" + username + "/" + password; try (ScrapClient cli = new ScrapClient()) { cli.setCredentials(new AuthScope("httpbin.org", 443), new UsernamePasswordCredentials(username, password)); cli.setProxy(new HttpProxy("127.0.0.1", 3128, "user", "pass")); assertEquals(200, cli.get(url)); assertEquals(200, cli.get(url)); }// w w w . j a v a 2s. co m }
From source file:jp.sf.fess.solr.plugin.suggest.util.SolrConfigUtil.java
public static SuggestUpdateConfig getUpdateHandlerConfig(final SolrConfig config) { final SuggestUpdateConfig suggestUpdateConfig = new SuggestUpdateConfig(); final Node solrServerNode = config.getNode("updateHandler/suggest/solrServer", false); if (solrServerNode != null) { try {/*from w w w .jav a2 s .c o m*/ final Node classNode = solrServerNode.getAttributes().getNamedItem("class"); String className; if (classNode != null) { className = classNode.getTextContent(); } else { className = "org.codelibs.solr.lib.server.SolrLibHttpSolrServer"; } @SuppressWarnings("unchecked") final Class<? extends SolrServer> clazz = (Class<? extends SolrServer>) Class.forName(className); final String arg = config.getVal("updateHandler/suggest/solrServer/arg", false); SolrServer solrServer; if (StringUtils.isNotBlank(arg)) { final Constructor<? extends SolrServer> constructor = clazz.getConstructor(String.class); solrServer = constructor.newInstance(arg); } else { solrServer = clazz.newInstance(); } final String username = config.getVal("updateHandler/suggest/solrServer/credentials/username", false); final String password = config.getVal("updateHandler/suggest/solrServer/credentials/password", false); if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password) && solrServer instanceof SolrLibHttpSolrServer) { final SolrLibHttpSolrServer solrLibHttpSolrServer = (SolrLibHttpSolrServer) solrServer; final URL u = new URL(arg); final AuthScope authScope = new AuthScope(u.getHost(), u.getPort()); final Credentials credentials = new UsernamePasswordCredentials(username, password); solrLibHttpSolrServer.setCredentials(authScope, credentials); solrLibHttpSolrServer.addRequestInterceptor(new PreemptiveAuthInterceptor()); } final NodeList childNodes = solrServerNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { final Node node = childNodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { final String name = node.getNodeName(); if (!"arg".equals(name) && !"credentials".equals(name)) { final String value = node.getTextContent(); final Node typeNode = node.getAttributes().getNamedItem("type"); final Method method = clazz.getMethod( "set" + name.substring(0, 1).toUpperCase() + name.substring(1), getMethodArgClass(typeNode)); method.invoke(solrServer, getMethodArgValue(typeNode, value)); } } } if (solrServer instanceof SolrLibHttpSolrServer) { ((SolrLibHttpSolrServer) solrServer).init(); } suggestUpdateConfig.setSolrServer(solrServer); } catch (final Exception e) { throw new FessSuggestException("Failed to load SolrServer.", e); } } final String labelFields = config.getVal("updateHandler/suggest/labelFields", false); if (StringUtils.isNotBlank(labelFields)) { suggestUpdateConfig.setLabelFields(labelFields.trim().split(",")); } final String roleFields = config.getVal("updateHandler/suggest/roleFields", false); if (StringUtils.isNotBlank(roleFields)) { suggestUpdateConfig.setRoleFields(roleFields.trim().split(",")); } final String expiresField = config.getVal("updateHandler/suggest/expiresField", false); if (StringUtils.isNotBlank(expiresField)) { suggestUpdateConfig.setExpiresField(expiresField); } final String segmentField = config.getVal("updateHandler/suggest/segmentField", false); if (StringUtils.isNotBlank(segmentField)) { suggestUpdateConfig.setSegmentField(segmentField); } final String updateInterval = config.getVal("updateHandler/suggest/updateInterval", false); if (StringUtils.isNotBlank(updateInterval) && StringUtils.isNumeric(updateInterval)) { suggestUpdateConfig.setUpdateInterval(Long.parseLong(updateInterval)); } //set suggestFieldInfo final NodeList nodeList = config.getNodeList("updateHandler/suggest/suggestFieldInfo", true); for (int i = 0; i < nodeList.getLength(); i++) { try { final SuggestUpdateConfig.FieldConfig fieldConfig = new SuggestUpdateConfig.FieldConfig(); final Node fieldInfoNode = nodeList.item(i); final NamedNodeMap fieldInfoAttributes = fieldInfoNode.getAttributes(); final Node fieldNameNode = fieldInfoAttributes.getNamedItem("fieldName"); final String fieldName = fieldNameNode.getNodeValue(); if (StringUtils.isBlank(fieldName)) { continue; } fieldConfig.setTargetFields(fieldName.trim().split(",")); if (logger.isInfoEnabled()) { for (final String s : fieldConfig.getTargetFields()) { logger.info("fieldName : " + s); } } final NodeList fieldInfoChilds = fieldInfoNode.getChildNodes(); for (int j = 0; j < fieldInfoChilds.getLength(); j++) { final Node fieldInfoChildNode = fieldInfoChilds.item(j); final String fieldInfoChildNodeName = fieldInfoChildNode.getNodeName(); if ("tokenizerFactory".equals(fieldInfoChildNodeName)) { //field tokenier settings final SuggestUpdateConfig.TokenizerConfig tokenizerConfig = new SuggestUpdateConfig.TokenizerConfig(); final NamedNodeMap tokenizerFactoryAttributes = fieldInfoChildNode.getAttributes(); final Node tokenizerClassNameNode = tokenizerFactoryAttributes.getNamedItem("class"); final String tokenizerClassName = tokenizerClassNameNode.getNodeValue(); tokenizerConfig.setClassName(tokenizerClassName); if (logger.isInfoEnabled()) { logger.info("tokenizerFactory : " + tokenizerClassName); } final Map<String, String> args = new HashMap<String, String>(); for (int k = 0; k < tokenizerFactoryAttributes.getLength(); k++) { final Node attribute = tokenizerFactoryAttributes.item(k); final String key = attribute.getNodeName(); final String value = attribute.getNodeValue(); if (!"class".equals(key)) { args.put(key, value); } } if (!args.containsKey(USER_DICT_PATH)) { final String userDictPath = System.getProperty(SuggestConstants.USER_DICT_PATH, ""); if (StringUtils.isNotBlank(userDictPath)) { args.put(USER_DICT_PATH, userDictPath); } final String userDictEncoding = System.getProperty(SuggestConstants.USER_DICT_ENCODING, ""); if (StringUtils.isNotBlank(userDictEncoding)) { args.put(USER_DICT_ENCODING, userDictEncoding); } } tokenizerConfig.setArgs(args); fieldConfig.setTokenizerConfig(tokenizerConfig); } else if ("suggestReadingConverter".equals(fieldInfoChildNodeName)) { //field reading converter settings final NodeList converterNodeList = fieldInfoChildNode.getChildNodes(); for (int k = 0; k < converterNodeList.getLength(); k++) { final SuggestUpdateConfig.ConverterConfig converterConfig = new SuggestUpdateConfig.ConverterConfig(); final Node converterNode = converterNodeList.item(k); if (!"converter".equals(converterNode.getNodeName())) { continue; } final NamedNodeMap converterAttributes = converterNode.getAttributes(); final Node classNameNode = converterAttributes.getNamedItem("class"); final String className = classNameNode.getNodeValue(); converterConfig.setClassName(className); if (logger.isInfoEnabled()) { logger.info("converter : " + className); } final Map<String, String> properties = new HashMap<String, String>(); for (int l = 0; l < converterAttributes.getLength(); l++) { final Node attribute = converterAttributes.item(l); final String key = attribute.getNodeName(); final String value = attribute.getNodeValue(); if (!"class".equals(key)) { properties.put(key, value); } } converterConfig.setProperties(properties); if (logger.isInfoEnabled()) { logger.info("converter properties = " + properties); } fieldConfig.addConverterConfig(converterConfig); } } else if ("suggestNormalizer".equals(fieldInfoChildNodeName)) { //field normalizer settings final NodeList normalizerNodeList = fieldInfoChildNode.getChildNodes(); for (int k = 0; k < normalizerNodeList.getLength(); k++) { final SuggestUpdateConfig.NormalizerConfig normalizerConfig = new SuggestUpdateConfig.NormalizerConfig(); final Node normalizerNode = normalizerNodeList.item(k); if (!"normalizer".equals(normalizerNode.getNodeName())) { continue; } final NamedNodeMap normalizerAttributes = normalizerNode.getAttributes(); final Node classNameNode = normalizerAttributes.getNamedItem("class"); final String className = classNameNode.getNodeValue(); normalizerConfig.setClassName(className); if (logger.isInfoEnabled()) { logger.info("normalizer : " + className); } final Map<String, String> properties = new HashMap<String, String>(); for (int l = 0; l < normalizerAttributes.getLength(); l++) { final Node attribute = normalizerAttributes.item(l); final String key = attribute.getNodeName(); final String value = attribute.getNodeValue(); if (!"class".equals(key)) { properties.put(key, value); } } normalizerConfig.setProperties(properties); if (logger.isInfoEnabled()) { logger.info("normalize properties = " + properties); } fieldConfig.addNormalizerConfig(normalizerConfig); } } } suggestUpdateConfig.addFieldConfig(fieldConfig); } catch (final Exception e) { throw new FessSuggestException("Failed to load Suggest Field Info.", e); } } return suggestUpdateConfig; }
From source file:com.garethahealy.resteastpathparamescape.utils.RestFactory.java
protected HttpClientContext getBasicAuthContext(URI uri, String userName, String password) { HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(userName, password)); // Create AuthCache instance // Generate BASIC scheme object and add it to the local auth cache AuthCache authCache = new BasicAuthCache(); authCache.put(targetHost, new BasicScheme()); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache);//w ww .j av a 2s .c om return context; }
From source file:com.google.code.maven.plugin.http.client.ProxyTest.java
@Test public void testPrepare() { proxy.setHost("localhost"); proxy.setPort(8080);/*from w ww. j av a 2s. co m*/ DefaultHttpClient client = new DefaultHttpClient(); proxy.prepare(client); HttpHost httpHost = (HttpHost) client.getParams().getParameter(ConnRoutePNames.DEFAULT_PROXY); Assert.assertNotNull(httpHost); Assert.assertEquals(httpHost.getHostName(), proxy.getHost()); Assert.assertEquals(httpHost.getPort(), proxy.getPort()); Assert.assertEquals(httpHost.getSchemeName(), HttpHost.DEFAULT_SCHEME_NAME); Credentials credentials = new Credentials(); credentials.setLogin("login"); credentials.setPassword("password"); proxy.setCredentials(credentials); client = new DefaultHttpClient(); proxy.prepare(client); httpHost = (HttpHost) client.getParams().getParameter(ConnRoutePNames.DEFAULT_PROXY); Assert.assertNotNull(httpHost); Assert.assertEquals(httpHost.getHostName(), proxy.getHost()); Assert.assertEquals(httpHost.getPort(), proxy.getPort()); Assert.assertEquals(httpHost.getSchemeName(), HttpHost.DEFAULT_SCHEME_NAME); org.apache.http.auth.Credentials credentials2 = client.getCredentialsProvider() .getCredentials(new AuthScope("localhost", 8080)); Assert.assertNotNull(credentials2); Assert.assertEquals("login", credentials2.getUserPrincipal().getName()); Assert.assertEquals("password", credentials2.getPassword()); }
From source file:com.cisco.cta.taxii.adapter.httpclient.CredentialsProviderFactoryTest.java
@Test public void proxyWithNTLMAuth() throws MalformedURLException { ProxySettings proxySettings = new ProxySettings(); proxySettings.setAuthenticationType(ProxyAuthenticationType.NTLM); proxySettings.setUrl(new URL("http://localhost:8001/")); proxySettings.setUsername("tester"); proxySettings.setPassword("testPass"); CredentialsProviderFactory factory = new CredentialsProviderFactory(taxiiSettings, proxySettings); CredentialsProvider credsProvider = factory.build(); Credentials creds = credsProvider.getCredentials(new AuthScope("localhost", 8001)); assertThat(creds.getUserPrincipal().getName(), is("tester")); assertThat(creds.getPassword(), is("testPass")); }
From source file:org.droidparts.http.worker.HttpClientWorker.java
@Override public void authenticateBasic(String user, String password) { AuthScope authScope = new AuthScope(ANY_HOST, ANY_PORT); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, password); httpClient.getCredentialsProvider().setCredentials(authScope, credentials); }
From source file:org.commonjava.maven.galley.transport.htcli.internal.TLLocationCredentialsProvider.java
public HttpLocation getLocation(final String host, final int port) { // logger.info( "Looking up repository def under authscope: {}:{}", host, port ); final Map<AuthScope, HttpLocation> repos = repositories.get(); if (repos == null) { return null; }//from ww w. j a v a 2 s. com //TODO: Seems like multiple repos with same host/port could easily cause confusion if they're not configured the same way later on... return repos.get(new AuthScope(host, port)); }