List of usage examples for org.apache.http.impl.client AbstractHttpClient getCredentialsProvider
public synchronized final CredentialsProvider getCredentialsProvider()
From source file:com.rightscale.provider.rest.DashboardSession.java
private void setupBasicAuth(StatefulClient client) { AuthScope authScope = new AuthScope(_baseURI.getHost(), AuthScope.ANY_PORT, AuthScope.ANY_REALM); UsernamePasswordCredentials creds = new UsernamePasswordCredentials(_username, _password); AbstractHttpClient realClient = (AbstractHttpClient) client.getRealClient(); realClient.getCredentialsProvider().setCredentials(authScope, creds); realClient.addRequestInterceptor(createBasicAuthInterceptor(), 0); }
From source file:jp.ambrosoli.quickrestclient.apache.service.ApacheHttpService.java
public HttpResponse execute(final HttpRequest request) { HttpParams httpParams = this.createHttpParams(); this.setProtocolVersion(httpParams, request.getProtocol()); this.setTimeout(httpParams, request.getTimeout()); this.setProxy(httpParams, request.getProxyInfo()); this.setCharset(httpParams, request.getCharset()); URI uri = request.getUri();// ww w .j a v a 2s .c o m HttpUriRequest httpUriRequest = this.createHttpUriRequest(uri, request.getMethod(), request.getParams(), request.getCharset()); this.setHeaders(httpUriRequest, request.getHeaders()); SchemeRegistry schreg = this.createSchemeRegistry(uri); ClientConnectionManager conman = this.createClientConnectionManager(httpParams, schreg); AbstractHttpClient client = this.createHttpClient(conman, httpParams); this.setCredentialsAuthenticate(uri, request.getAuthInfo(), client.getCredentialsProvider()); try { return client.execute(httpUriRequest, new ApacheResponseHandler()); } catch (SocketTimeoutException e) { throw new SocketTimeoutRuntimeException(e); } catch (IOException e) { throw new IORuntimeException(e); } finally { conman.shutdown(); } }
From source file:org.cvasilak.jboss.mobile.app.service.UploadToJBossServerService.java
@Override protected void onHandleIntent(Intent intent) { // initialize // extract details Server server = intent.getParcelableExtra("server"); String directory = intent.getStringExtra("directory"); String filename = intent.getStringExtra("filename"); // get the json parser from the application JsonParser jsonParser = new JsonParser(); // start the ball rolling... final NotificationManager mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); final NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setTicker(String.format(getString(R.string.notif_ticker), filename)) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_notif_large)) .setSmallIcon(R.drawable.ic_stat_notif_small) .setContentTitle(String.format(getString(R.string.notif_title), filename)) .setContentText(getString(R.string.notif_content_init)) // to avoid NPE on android 2.x where content intent is required // set an empty content intent .setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0)).setOngoing(true); // notify user that upload is starting mgr.notify(NOTIFICATION_ID, builder.build()); // reset ticker for any subsequent notifications builder.setTicker(null);/*from ww w . j av a 2 s . c o m*/ AbstractHttpClient client = CustomHTTPClient.getHttpClient(); // enable digest authentication if (server.getUsername() != null && !server.getUsername().equals("")) { Credentials credentials = new UsernamePasswordCredentials(server.getUsername(), server.getPassword()); client.getCredentialsProvider().setCredentials( new AuthScope(server.getHostname(), server.getPort(), AuthScope.ANY_REALM), credentials); } final File file = new File(directory, filename); final long length = file.length(); try { CustomMultiPartEntity multipart = new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, new CustomMultiPartEntity.ProgressListener() { @Override public void transferred(long num) { // calculate percentage //System.out.println("transferred: " + num); int progress = (int) ((num * 100) / length); builder.setContentText(String.format(getString(R.string.notif_content), progress)); mgr.notify(NOTIFICATION_ID, builder.build()); } }); multipart.addPart(file.getName(), new FileBody(file)); HttpPost httpRequest = new HttpPost(server.getHostPort() + "/management/add-content"); httpRequest.setEntity(multipart); HttpResponse serverResponse = client.execute(httpRequest); BasicResponseHandler handler = new BasicResponseHandler(); JsonObject reply = jsonParser.parse(handler.handleResponse(serverResponse)).getAsJsonObject(); if (!reply.has("outcome")) { throw new RuntimeException(getString(R.string.invalid_response)); } else { // remove the 'upload in-progress' notification mgr.cancel(NOTIFICATION_ID); String outcome = reply.get("outcome").getAsString(); if (outcome.equals("success")) { String BYTES_VALUE = reply.get("result").getAsJsonObject().get("BYTES_VALUE").getAsString(); Intent resultIntent = new Intent(this, UploadCompletedActivity.class); // populate it resultIntent.putExtra("server", server); resultIntent.putExtra("BYTES_VALUE", BYTES_VALUE); resultIntent.putExtra("filename", filename); resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); // the notification id for the 'completed upload' notification // each completed upload will have a different id int notifCompletedID = (int) System.currentTimeMillis(); builder.setContentTitle(getString(R.string.notif_title_uploaded)) .setContentText(String.format(getString(R.string.notif_content_uploaded), filename)) .setContentIntent( // we set the (2nd param request code to completedID) // see http://tinyurl.com/kkcedju PendingIntent.getActivity(this, notifCompletedID, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT)) .setAutoCancel(true).setOngoing(false); mgr.notify(notifCompletedID, builder.build()); } else { JsonElement elem = reply.get("failure-description"); if (elem.isJsonPrimitive()) { throw new RuntimeException(elem.getAsString()); } else if (elem.isJsonObject()) throw new RuntimeException( elem.getAsJsonObject().get("domain-failure-description").getAsString()); } } } catch (Exception e) { builder.setContentText(e.getMessage()).setAutoCancel(true).setOngoing(false); mgr.notify(NOTIFICATION_ID, builder.build()); } }
From source file:org.eclipse.mylyn.commons.repositories.http.core.HttpUtil.java
public static void configureProxy(AbstractHttpClient client, RepositoryLocation location) { Assert.isNotNull(client);/* w w w . j a v a 2 s . c om*/ Assert.isNotNull(location); String url = location.getUrl(); Assert.isNotNull(url, "The location url must not be null"); //$NON-NLS-1$ String host = NetUtil.getHost(url); Proxy proxy; if (NetUtil.isUrlHttps(url)) { proxy = location.getProxyForHost(host, IProxyData.HTTPS_PROXY_TYPE); } else { proxy = location.getProxyForHost(host, IProxyData.HTTP_PROXY_TYPE); } if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) { InetSocketAddress address = (InetSocketAddress) proxy.address(); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(address.getHostName(), address.getPort())); if (proxy instanceof AuthenticatedProxy) { AuthenticatedProxy authProxy = (AuthenticatedProxy) proxy; Credentials credentials = getCredentials(authProxy.getUserName(), authProxy.getPassword(), address.getAddress(), false); if (credentials instanceof NTCredentials) { AuthScope proxyAuthScopeNTLM = new AuthScope(address.getHostName(), address.getPort(), AuthScope.ANY_REALM, AuthPolicy.NTLM); client.getCredentialsProvider().setCredentials(proxyAuthScopeNTLM, credentials); AuthScope proxyAuthScopeAny = new AuthScope(address.getHostName(), address.getPort(), AuthScope.ANY_REALM); Credentials usernamePasswordCredentials = getCredentials(authProxy.getUserName(), authProxy.getPassword(), address.getAddress(), true); client.getCredentialsProvider().setCredentials(proxyAuthScopeAny, usernamePasswordCredentials); } else { AuthScope proxyAuthScope = new AuthScope(address.getHostName(), address.getPort(), AuthScope.ANY_REALM); client.getCredentialsProvider().setCredentials(proxyAuthScope, credentials); } } } else { client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, null); } }
From source file:net.sourceforge.jwbf.mediawiki.live.LoginTest.java
/** * Login on last MW with SSL and htaccess. * //w w w .j a va 2 s .co m * @throws Exception * a */ @Test public final void loginWikiMWLastSSLAndHtaccess() throws Exception { AbstractHttpClient httpClient = getSSLFakeHttpClient(); Version latest = Version.getLatest(); URL u = new URL(getValue("wiki_url_latest").replace("http", "https")); assertEquals("https", u.getProtocol()); int port = 443; { // test if authentication required HttpHost targetHost = new HttpHost(u.getHost(), port, u.getProtocol()); HttpGet httpget = new HttpGet(u.getPath()); HttpResponse resp = httpClient.execute(targetHost, httpget); assertEquals(401, resp.getStatusLine().getStatusCode()); resp.getEntity().consumeContent(); } httpClient.getCredentialsProvider().setCredentials(new AuthScope(u.getHost(), port), new UsernamePasswordCredentials(BotFactory.getWikiUser(latest), BotFactory.getWikiPass(latest))); HttpActionClient sslFakeClient = new HttpActionClient(httpClient, u); bot = new MediaWikiBot(sslFakeClient); bot.login(BotFactory.getWikiUser(latest), BotFactory.getWikiPass(latest)); assertTrue(bot.isLoggedIn()); }
From source file:net.sourceforge.jwbf.mediawiki.live.LoginIT.java
/** * Login on last MW with SSL and htaccess. */// www . j av a 2 s . c o m @Test public final void loginWikiMWLastSSLAndHtaccess() throws Exception { AbstractHttpClient httpClient = getSSLFakeHttpClient(); Version latest = Version.getLatest(); String url = getValueOrSkip("wiki_url_latest").replace("http", "https"); assumeReachable(url); URL u = new URL(url); assertEquals("https", u.getProtocol()); int port = 443; TestHelper.assumeReachable(u); { // test if authentication required HttpHost targetHost = new HttpHost(u.getHost(), port, u.getProtocol()); HttpGet httpget = new HttpGet(u.getPath()); HttpResponse resp = httpClient.execute(targetHost, httpget); assertEquals(401, resp.getStatusLine().getStatusCode()); resp.getEntity().consumeContent(); } httpClient.getCredentialsProvider().setCredentials(new AuthScope(u.getHost(), port), new UsernamePasswordCredentials(BotFactory.getWikiUser(latest), BotFactory.getWikiPass(latest))); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); HttpActionClient sslFakeClient = new HttpActionClient(clientBuilder, u); bot = new MediaWikiBot(sslFakeClient); bot.login(BotFactory.getWikiUser(latest), BotFactory.getWikiPass(latest)); assertTrue(bot.isLoggedIn()); }
From source file:org.eclipse.mylyn.commons.http.HttpUtil.java
public static HttpContext getHttpContext(AbstractHttpClient client, AbstractWebLocation location, HttpContext previousContext, IProgressMonitor progressMonitor) { Assert.isNotNull(client);//w w w . ja v a 2s . co m Assert.isNotNull(location); String url = location.getUrl(); String host = getHost(url); int port = getPort(url); configureHttpClientConnectionManager(client); HttpContext context = previousContext; if (context == null) { context = new BasicHttpContext(); } configureHttpClientProxy(client, context, location); AuthenticationCredentials authCreds = location.getCredentials(AuthenticationType.HTTP); if (authCreds != null) { AuthScope authScope = new AuthScope(host, port, AuthScope.ANY_REALM); Credentials credentials = getHttpClientCredentials(authCreds, host); if (credentials instanceof NTCredentials) { List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.NTLM); authpref.add(AuthPolicy.BASIC); authpref.add(AuthPolicy.DIGEST); client.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref); } else { List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.BASIC); authpref.add(AuthPolicy.DIGEST); authpref.add(AuthPolicy.NTLM); client.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref); } client.getCredentialsProvider().setCredentials(authScope, credentials); } if (isRepositoryHttps(url)) { Scheme sch = new Scheme("https", HTTPS_PORT, sslSocketFactory); //$NON-NLS-1$ client.getConnectionManager().getSchemeRegistry().register(sch); } else { Scheme sch = new Scheme("http", HTTP_PORT, socketFactory); //$NON-NLS-1$ client.getConnectionManager().getSchemeRegistry().register(sch); } return context; }
From source file:org.eclipse.mylyn.commons.http.HttpUtil.java
private static void configureHttpClientProxy(AbstractHttpClient client, HttpContext context, AbstractWebLocation location) {// w w w .jav a 2 s .co m String host = getHost(location.getUrl()); Proxy proxy; if (isRepositoryHttps(location.getUrl())) { proxy = location.getProxyForHost(host, IProxyData.HTTPS_PROXY_TYPE); } else { proxy = location.getProxyForHost(host, IProxyData.HTTP_PROXY_TYPE); } if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) { InetSocketAddress address = (InetSocketAddress) proxy.address(); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(address.getHostName(), address.getPort())); if (proxy instanceof AuthenticatedProxy) { AuthenticatedProxy authProxy = (AuthenticatedProxy) proxy; Credentials credentials = getCredentials(authProxy.getUserName(), authProxy.getPassword(), address.getAddress()); if (credentials instanceof NTCredentials) { List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.NTLM); authpref.add(AuthPolicy.BASIC); authpref.add(AuthPolicy.DIGEST); client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref); } else { List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.BASIC); authpref.add(AuthPolicy.DIGEST); authpref.add(AuthPolicy.NTLM); client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref); } AuthScope proxyAuthScope = new AuthScope(address.getHostName(), address.getPort(), AuthScope.ANY_REALM); client.getCredentialsProvider().setCredentials(proxyAuthScope, credentials); } } else { client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, null); } }
From source file:org.apache.axis2.transport.http.impl.httpclient4.HTTPSenderImpl.java
protected void setAuthenticationInfo(AbstractHttpClient agent, MessageContext msgCtx) throws AxisFault { HTTPAuthenticator authenticator; Object obj = msgCtx.getProperty(HTTPConstants.AUTHENTICATE); if (obj != null) { if (obj instanceof HTTPAuthenticator) { authenticator = (HTTPAuthenticator) obj; String username = authenticator.getUsername(); String password = authenticator.getPassword(); String host = authenticator.getHost(); String domain = authenticator.getDomain(); int port = authenticator.getPort(); String realm = authenticator.getRealm(); /* If retrying is available set it first */ isAllowedRetry = authenticator.isAllowedRetry(); Credentials creds;//ww w . ja va2 s. c o m // TODO : Set preemptive authentication, but its not recommended in HC 4 if (host != null) { if (domain != null) { /* Credentials for NTLM Authentication */ agent.getAuthSchemes().register("ntlm", new NTLMSchemeFactory()); creds = new NTCredentials(username, password, host, domain); } else { /* Credentials for Digest and Basic Authentication */ creds = new UsernamePasswordCredentials(username, password); } agent.getCredentialsProvider().setCredentials(new AuthScope(host, port, realm), creds); } else { if (domain != null) { /* * Credentials for NTLM Authentication when host is * ANY_HOST */ agent.getAuthSchemes().register("ntlm", new NTLMSchemeFactory()); creds = new NTCredentials(username, password, AuthScope.ANY_HOST, domain); agent.getCredentialsProvider() .setCredentials(new AuthScope(AuthScope.ANY_HOST, port, realm), creds); } else { /* Credentials only for Digest and Basic Authentication */ creds = new UsernamePasswordCredentials(username, password); agent.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), creds); } } /* Customizing the priority Order */ List schemes = authenticator.getAuthSchemes(); if (schemes != null && schemes.size() > 0) { List authPrefs = new ArrayList(3); for (int i = 0; i < schemes.size(); i++) { if (schemes.get(i) instanceof AuthPolicy) { authPrefs.add(schemes.get(i)); continue; } String scheme = (String) schemes.get(i); authPrefs.add(authenticator.getAuthPolicyPref(scheme)); } agent.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authPrefs); } } else { throw new AxisFault("HttpTransportProperties.Authenticator class cast exception"); } } }
From source file:org.apache.axis2.transport.http.impl.httpclient4.HTTPProxyConfigurator.java
/** * Configure HTTP Proxy settings of commons-httpclient HostConfiguration. * Proxy settings can be get from axis2.xml, Java proxy settings or can be * override through property in message context. * <p/>//from w ww. j av a 2 s.c om * HTTP Proxy setting element format: <parameter name="Proxy"> * <Configuration> <ProxyHost>example.org</ProxyHost> * <ProxyPort>3128</ProxyPort> <ProxyUser>EXAMPLE/John</ProxyUser> * <ProxyPassword>password</ProxyPassword> <Configuration> <parameter> * * @param messageContext * in message context for * @param httpClient * instance * @throws org.apache.axis2.AxisFault * if Proxy settings are invalid */ public static void configure(MessageContext messageContext, AbstractHttpClient httpClient) throws AxisFault { Credentials proxyCredentials = null; String proxyHost = null; String nonProxyHosts = null; Integer proxyPort = -1; String proxyUser = null; String proxyPassword = null; // Getting configuration values from Axis2.xml Parameter proxySettingsFromAxisConfig = messageContext.getConfigurationContext().getAxisConfiguration() .getParameter(HTTPTransportConstants.ATTR_PROXY); if (proxySettingsFromAxisConfig != null) { OMElement proxyConfiguration = getProxyConfigurationElement(proxySettingsFromAxisConfig); proxyHost = getProxyHost(proxyConfiguration); proxyPort = getProxyPort(proxyConfiguration); proxyUser = getProxyUser(proxyConfiguration); proxyPassword = getProxyPassword(proxyConfiguration); if (proxyUser != null) { if (proxyPassword == null) { proxyPassword = ""; } proxyCredentials = new UsernamePasswordCredentials(proxyUser, proxyPassword); int proxyUserDomainIndex = proxyUser.indexOf("\\"); if (proxyUserDomainIndex > 0) { String domain = proxyUser.substring(0, proxyUserDomainIndex); if (proxyUser.length() > proxyUserDomainIndex + 1) { String user = proxyUser.substring(proxyUserDomainIndex + 1); proxyCredentials = new NTCredentials(user, proxyPassword, proxyHost, domain); } } } } // If there is runtime proxy settings, these settings will override // settings from axis2.xml HttpTransportProperties.ProxyProperties proxyProperties = (HttpTransportProperties.ProxyProperties) messageContext .getProperty(HTTPConstants.PROXY); if (proxyProperties != null) { String proxyHostProp = proxyProperties.getProxyHostName(); if (proxyHostProp == null || proxyHostProp.length() <= 0) { throw new AxisFault("HTTP Proxy host is not available. Host is a MUST parameter"); } else { proxyHost = proxyHostProp; } proxyPort = proxyProperties.getProxyPort(); // Overriding credentials String userName = proxyProperties.getUserName(); String password = proxyProperties.getPassWord(); String domain = proxyProperties.getDomain(); if (userName != null && password != null && domain != null) { proxyCredentials = new NTCredentials(userName, password, proxyHost, domain); } else if (userName != null && domain == null) { proxyCredentials = new UsernamePasswordCredentials(userName, password); } } // Overriding proxy settings if proxy is available from JVM settings String host = System.getProperty(HTTPTransportConstants.HTTP_PROXY_HOST); if (host != null) { proxyHost = host; } String port = System.getProperty(HTTPTransportConstants.HTTP_PROXY_PORT); if (port != null) { proxyPort = Integer.parseInt(port); } if (proxyCredentials != null) { // TODO : Set preemptive authentication, but its not recommended in HC 4 httpClient.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, true); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, proxyCredentials); HttpHost proxy = new HttpHost(proxyHost, proxyPort); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } }