List of usage examples for org.apache.http.auth NTCredentials NTCredentials
public NTCredentials(final String userName, final String password, final String workstation, final String domain)
From source file:de.codecentric.elasticsearch.plugin.kerberosrealm.AbstractUnitTest.java
protected final CloseableHttpClient getHttpClient(final boolean useSpnego) throws Exception { final CredentialsProvider credsProvider = new BasicCredentialsProvider(); final HttpClientBuilder hcb = HttpClients.custom(); if (useSpnego) { //SPNEGO/Kerberos setup log.debug("SPNEGO activated"); final AuthSchemeProvider nsf = new SPNegoSchemeFactory(true);// new NegotiateSchemeProvider(); final Credentials jaasCreds = new JaasCredentials(); credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds); credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM), new NTCredentials("Guest", "Guest", "Guest", "Guest")); final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build(); hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry); }//from w ww. j a va 2 s . com hcb.setDefaultCredentialsProvider(credsProvider); hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(10 * 1000).build()); final CloseableHttpClient httpClient = hcb.build(); return httpClient; }
From source file:org.apache.manifoldcf.crawler.connectors.meridio.meridiowrapper.MeridioWrapper.java
/** The Meridio Wrapper constructor that calls the Meridio login method * *@param log a handle to a Log4j logger *@param meridioDmwsUrl the URL to the Meridio Document Management Web Service *@param meridioRmwsUrl the URL to the Meridio Records Management Web Service *@param dmwsProxyHost the proxy for DMWS, or null if none *@param dmwsProxyPort the proxy port for DMWS, or -1 if default *@param rmwsProxyHost the proxy for RMWS, or null if none *@param rmwsProxyPort the proxy port for RMWS, or -1 if default *@param userName the username of the user to log in as, must include the Windows, e.g. domain\\user *@param password the password of the user who is logging in *@param clientWorkstation an identifier for the client workstation, could be the IP address, for auditing purposes *@param protocolFactory the protocol factory object to use for https communication *@param engineConfigurationFile the engine configuration object to use to communicate with the web services * *@throws RemoteException if an error is encountered logging into Meridio *//*from w w w . ja va 2 s. c om*/ public MeridioWrapper(Logger log, URL meridioDmwsUrl, URL meridioRmwsUrl, URL meridioManifoldCFWSUrl, String dmwsProxyHost, String dmwsProxyPort, String rmwsProxyHost, String rmwsProxyPort, String mcwsProxyHost, String mcwsProxyPort, String userName, String password, String clientWorkstation, javax.net.ssl.SSLSocketFactory mySSLFactory, Class resourceClass, String engineConfigurationFile) throws RemoteException, NumberFormatException { // Initialize local instance variables oLog = log; this.engineConfiguration = new ResourceProvider(resourceClass, engineConfigurationFile); this.clientWorkstation = clientWorkstation; // Set up the pool. // We have a choice: We can either have one httpclient instance, which gets reinitialized for every service // it connects with (because each one has a potentially different proxy setup), OR we can have a different // httpclient for each service. The latter approach is obviously the more efficient, so I've chosen to do it // that way. PoolingClientConnectionManager localConnectionManager = new PoolingClientConnectionManager(); localConnectionManager.setMaxTotal(1); if (mySSLFactory != null) { SSLSocketFactory myFactory = new SSLSocketFactory(mySSLFactory, new BrowserCompatHostnameVerifier()); Scheme myHttpsProtocol = new Scheme("https", 443, myFactory); localConnectionManager.getSchemeRegistry().register(myHttpsProtocol); } connectionManager = localConnectionManager; // Parse the user and password values int index = userName.indexOf("\\"); String domainUser; String domain; if (index != -1) { domainUser = userName.substring(index + 1); domain = userName.substring(0, index); if (oLog != null && oLog.isDebugEnabled()) oLog.debug("Meridio: User is '" + domainUser + "', domain is '" + domain + "'"); } else { domain = null; domainUser = userName; if (oLog != null && oLog.isDebugEnabled()) oLog.debug("Meridio: User is '" + domainUser + "'; there is no domain specified"); } if (oLog != null && oLog.isDebugEnabled()) { if (password != null && password.length() > 0) oLog.debug("Meridio: Password exists"); else oLog.debug("Meridio: Password is null"); } // Initialize the three httpclient objects // dmws first BasicHttpParams dmwsParams = new BasicHttpParams(); dmwsParams.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true); dmwsParams.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false); dmwsParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); dmwsParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 900000); dmwsParams.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); DefaultHttpClient localDmwsHttpClient = new DefaultHttpClient(connectionManager, dmwsParams); // No retries localDmwsHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { return false; } }); localDmwsHttpClient.setRedirectStrategy(new DefaultRedirectStrategy()); if (domainUser != null) { localDmwsHttpClient.getCredentialsProvider().setCredentials( new AuthScope(meridioDmwsUrl.getHost(), meridioDmwsUrl.getPort()), new NTCredentials(domainUser, password, currentHost, domain)); } // Initialize proxy if (dmwsProxyHost != null && dmwsProxyHost.length() > 0) { int port = (dmwsProxyPort == null || dmwsProxyPort.length() == 0) ? 8080 : Integer.parseInt(dmwsProxyPort); // Configure proxy authentication if (domainUser != null && domainUser.length() > 0) { localDmwsHttpClient.getCredentialsProvider().setCredentials(new AuthScope(dmwsProxyHost, port), new NTCredentials(domainUser, password, currentHost, domain)); } HttpHost proxy = new HttpHost(dmwsProxyHost, port); localDmwsHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } dmwsHttpClient = localDmwsHttpClient; // rmws BasicHttpParams rmwsParams = new BasicHttpParams(); rmwsParams.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true); rmwsParams.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false); rmwsParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); rmwsParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 900000); rmwsParams.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); DefaultHttpClient localRmwsHttpClient = new DefaultHttpClient(connectionManager, rmwsParams); // No retries localRmwsHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { return false; } }); localRmwsHttpClient.setRedirectStrategy(new DefaultRedirectStrategy()); if (domainUser != null) { localRmwsHttpClient.getCredentialsProvider().setCredentials( new AuthScope(meridioRmwsUrl.getHost(), meridioRmwsUrl.getPort()), new NTCredentials(domainUser, password, currentHost, domain)); } // Initialize proxy if (rmwsProxyHost != null && rmwsProxyHost.length() > 0) { int port = (rmwsProxyPort == null || rmwsProxyPort.length() == 0) ? 8080 : Integer.parseInt(rmwsProxyPort); // Configure proxy authentication if (domainUser != null && domainUser.length() > 0) { localRmwsHttpClient.getCredentialsProvider().setCredentials(new AuthScope(rmwsProxyHost, port), new NTCredentials(domainUser, password, currentHost, domain)); } HttpHost proxy = new HttpHost(rmwsProxyHost, port); localRmwsHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } rmwsHttpClient = localRmwsHttpClient; // mcws if (meridioManifoldCFWSUrl != null) { BasicHttpParams mcwsParams = new BasicHttpParams(); mcwsParams.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true); mcwsParams.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false); mcwsParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); mcwsParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 900000); mcwsParams.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); DefaultHttpClient localMcwsHttpClient = new DefaultHttpClient(connectionManager, mcwsParams); // No retries localMcwsHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { return false; } }); localMcwsHttpClient.setRedirectStrategy(new DefaultRedirectStrategy()); if (domainUser != null) { localMcwsHttpClient.getCredentialsProvider().setCredentials( new AuthScope(meridioManifoldCFWSUrl.getHost(), meridioManifoldCFWSUrl.getPort()), new NTCredentials(domainUser, password, currentHost, domain)); } // Initialize proxy if (mcwsProxyHost != null && mcwsProxyHost.length() > 0) { int port = (mcwsProxyPort == null || mcwsProxyPort.length() == 0) ? 8080 : Integer.parseInt(mcwsProxyPort); // Configure proxy authentication if (domainUser != null && domainUser.length() > 0) { localMcwsHttpClient.getCredentialsProvider().setCredentials(new AuthScope(mcwsProxyHost, port), new NTCredentials(domainUser, password, currentHost, domain)); } HttpHost proxy = new HttpHost(mcwsProxyHost, port); localMcwsHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } mcwsHttpClient = localMcwsHttpClient; } else mcwsHttpClient = null; // Set up the stub handles /*================================================================= * Get a handle to the DMWS *================================================================*/ MeridioDMLocator meridioDMLocator = new MeridioDMLocator(engineConfiguration); MeridioDMSoapStub meridioDMWebService = new MeridioDMSoapStub(meridioDmwsUrl, meridioDMLocator); meridioDMWebService.setPortName(meridioDMLocator.getMeridioDMSoapWSDDServiceName()); meridioDMWebService.setUsername(userName); meridioDMWebService.setPassword(password); meridioDMWebService._setProperty(HTTPCLIENT_PROPERTY, dmwsHttpClient); meridioDMWebService_ = meridioDMWebService; /*================================================================= * Get a handle to the RMWS *================================================================*/ MeridioRMLocator meridioRMLocator = new MeridioRMLocator(engineConfiguration); MeridioRMSoapStub meridioRMWebService = new MeridioRMSoapStub(meridioRmwsUrl, meridioRMLocator); meridioRMWebService.setPortName(meridioRMLocator.getMeridioRMSoapWSDDServiceName()); meridioRMWebService.setUsername(userName); meridioRMWebService.setPassword(password); meridioRMWebService._setProperty(HTTPCLIENT_PROPERTY, rmwsHttpClient); meridioRMWebService_ = meridioRMWebService; /*================================================================= * Get a handle to the MeridioMetaCarta Web Service *================================================================*/ if (meridioManifoldCFWSUrl != null) { MetaCartaLocator meridioMCWS = new MetaCartaLocator(engineConfiguration); Service McWsService = null; MetaCartaSoapStub meridioMetaCartaWebService = new MetaCartaSoapStub(meridioManifoldCFWSUrl, McWsService); meridioMetaCartaWebService.setPortName(meridioMCWS.getMetaCartaSoapWSDDServiceName()); meridioMetaCartaWebService.setUsername(userName); meridioMetaCartaWebService.setPassword(password); meridioMetaCartaWebService._setProperty(HTTPCLIENT_PROPERTY, mcwsHttpClient); meridioMCWS_ = meridioMetaCartaWebService; } this.loginUnified(); }
From source file:org.apache.manifoldcf.meridio.MeridioWrapper.java
/** The Meridio Wrapper constructor that calls the Meridio login method * *@param log a handle to a Log4j logger *@param meridioDmwsUrl the URL to the Meridio Document Management Web Service *@param meridioRmwsUrl the URL to the Meridio Records Management Web Service *@param dmwsProxyHost the proxy for DMWS, or null if none *@param dmwsProxyPort the proxy port for DMWS, or -1 if default *@param rmwsProxyHost the proxy for RMWS, or null if none *@param rmwsProxyPort the proxy port for RMWS, or -1 if default *@param userName the username of the user to log in as, must include the Windows, e.g. domain\\user *@param password the password of the user who is logging in *@param clientWorkstation an identifier for the client workstation, could be the IP address, for auditing purposes *@param protocolFactory the protocol factory object to use for https communication *@param engineConfigurationFile the engine configuration object to use to communicate with the web services * *@throws RemoteException if an error is encountered logging into Meridio *//*w w w. j av a2 s.c om*/ public MeridioWrapper(Logger log, URL meridioDmwsUrl, URL meridioRmwsUrl, URL meridioManifoldCFWSUrl, String dmwsProxyHost, String dmwsProxyPort, String rmwsProxyHost, String rmwsProxyPort, String mcwsProxyHost, String mcwsProxyPort, String userName, String password, String clientWorkstation, javax.net.ssl.SSLSocketFactory mySSLFactory, Class resourceClass, String engineConfigurationFile) throws RemoteException, NumberFormatException { // Initialize local instance variables oLog = log; this.engineConfiguration = new ResourceProvider(resourceClass, engineConfigurationFile); this.clientWorkstation = clientWorkstation; SSLConnectionSocketFactory myFactory = null; if (mySSLFactory != null) { myFactory = new SSLConnectionSocketFactory(mySSLFactory, new BrowserCompatHostnameVerifier()); } // Set up the pool. // We have a choice: We can either have one httpclient instance, which gets reinitialized for every service // it connects with (because each one has a potentially different proxy setup), OR we can have a different // httpclient for each service. The latter approach is obviously the more efficient, so I've chosen to do it // that way. // Parse the user and password values int index = userName.indexOf("\\"); String domainUser; String domain; if (index != -1) { domainUser = userName.substring(index + 1); domain = userName.substring(0, index); if (oLog != null && oLog.isDebugEnabled()) oLog.debug("Meridio: User is '" + domainUser + "', domain is '" + domain + "'"); } else { domain = null; domainUser = userName; if (oLog != null && oLog.isDebugEnabled()) oLog.debug("Meridio: User is '" + domainUser + "'; there is no domain specified"); } if (oLog != null && oLog.isDebugEnabled()) { if (password != null && password.length() > 0) oLog.debug("Meridio: Password exists"); else oLog.debug("Meridio: Password is null"); } int socketTimeout = 900000; int connectionTimeout = 300000; dmwsConnectionManager = new PoolingHttpClientConnectionManager(); rmwsConnectionManager = new PoolingHttpClientConnectionManager(); mcwsConnectionManager = new PoolingHttpClientConnectionManager(); // Initialize the three httpclient objects CredentialsProvider dmwsCredentialsProvider = new BasicCredentialsProvider(); CredentialsProvider rmwsCredentialsProvider = new BasicCredentialsProvider(); RequestConfig.Builder dmwsRequestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true) .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true) .setExpectContinueEnabled(false).setConnectTimeout(connectionTimeout) .setConnectionRequestTimeout(socketTimeout); RequestConfig.Builder rmwsRequestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true) .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).setExpectContinueEnabled(true) .setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(socketTimeout); // Set up credentials if (domainUser != null) { dmwsCredentialsProvider.setCredentials( new AuthScope(meridioDmwsUrl.getHost(), meridioDmwsUrl.getPort()), new NTCredentials(domainUser, password, currentHost, domain)); rmwsCredentialsProvider.setCredentials( new AuthScope(meridioRmwsUrl.getHost(), meridioRmwsUrl.getPort()), new NTCredentials(domainUser, password, currentHost, domain)); } // Initialize DMWS proxy if (dmwsProxyHost != null && dmwsProxyHost.length() > 0) { int port = (dmwsProxyPort == null || dmwsProxyPort.length() == 0) ? 8080 : Integer.parseInt(dmwsProxyPort); // Configure proxy authentication if (domainUser != null && domainUser.length() > 0) { dmwsCredentialsProvider.setCredentials(new AuthScope(dmwsProxyHost, port), new NTCredentials(domainUser, password, currentHost, domain)); } HttpHost proxy = new HttpHost(dmwsProxyHost, port); dmwsRequestBuilder.setProxy(proxy); } // Initialize RMWS proxy if (rmwsProxyHost != null && rmwsProxyHost.length() > 0) { int port = (rmwsProxyPort == null || rmwsProxyPort.length() == 0) ? 8080 : Integer.parseInt(rmwsProxyPort); // Configure proxy authentication if (domainUser != null && domainUser.length() > 0) { rmwsCredentialsProvider.setCredentials(new AuthScope(rmwsProxyHost, port), new NTCredentials(domainUser, password, currentHost, domain)); } HttpHost proxy = new HttpHost(rmwsProxyHost, port); rmwsRequestBuilder.setProxy(proxy); } dmwsHttpClient = HttpClients.custom().setConnectionManager(dmwsConnectionManager).setMaxConnTotal(1) .disableAutomaticRetries().setDefaultRequestConfig(dmwsRequestBuilder.build()) .setDefaultSocketConfig( SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build()) .setDefaultCredentialsProvider(dmwsCredentialsProvider).setSSLSocketFactory(myFactory) .setRequestExecutor(new HttpRequestExecutor(socketTimeout)) .setRedirectStrategy(new DefaultRedirectStrategy()).build(); rmwsHttpClient = HttpClients.custom().setConnectionManager(rmwsConnectionManager).setMaxConnTotal(1) .disableAutomaticRetries().setDefaultRequestConfig(rmwsRequestBuilder.build()) .setDefaultSocketConfig( SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build()) .setDefaultCredentialsProvider(rmwsCredentialsProvider).setSSLSocketFactory(myFactory) .setRequestExecutor(new HttpRequestExecutor(socketTimeout)) .setRedirectStrategy(new DefaultRedirectStrategy()).build(); if (meridioManifoldCFWSUrl != null) { CredentialsProvider mcwsCredentialsProvider = new BasicCredentialsProvider(); RequestConfig.Builder mcwsRequestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true) .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true) .setExpectContinueEnabled(true).setConnectTimeout(connectionTimeout) .setConnectionRequestTimeout(socketTimeout); if (domainUser != null) { mcwsCredentialsProvider.setCredentials( new AuthScope(meridioManifoldCFWSUrl.getHost(), meridioManifoldCFWSUrl.getPort()), new NTCredentials(domainUser, password, currentHost, domain)); } // Initialize MCWS proxy if (mcwsProxyHost != null && mcwsProxyHost.length() > 0) { int port = (mcwsProxyPort == null || mcwsProxyPort.length() == 0) ? 8080 : Integer.parseInt(mcwsProxyPort); // Configure proxy authentication if (domainUser != null && domainUser.length() > 0) { mcwsCredentialsProvider.setCredentials(new AuthScope(mcwsProxyHost, port), new NTCredentials(domainUser, password, currentHost, domain)); } HttpHost proxy = new HttpHost(mcwsProxyHost, port); mcwsRequestBuilder.setProxy(proxy); } mcwsHttpClient = HttpClients.custom().setConnectionManager(mcwsConnectionManager).setMaxConnTotal(1) .disableAutomaticRetries().setDefaultRequestConfig(mcwsRequestBuilder.build()) .setDefaultSocketConfig( SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build()) .setDefaultCredentialsProvider(mcwsCredentialsProvider).setSSLSocketFactory(myFactory) .setRequestExecutor(new HttpRequestExecutor(socketTimeout)) .setRedirectStrategy(new DefaultRedirectStrategy()).build(); } // Set up the stub handles /*================================================================= * Get a handle to the DMWS *================================================================*/ MeridioDMLocator meridioDMLocator = new MeridioDMLocator(engineConfiguration); MeridioDMSoapStub meridioDMWebService = new MeridioDMSoapStub(meridioDmwsUrl, meridioDMLocator); meridioDMWebService.setPortName(meridioDMLocator.getMeridioDMSoapWSDDServiceName()); meridioDMWebService.setUsername(userName); meridioDMWebService.setPassword(password); meridioDMWebService._setProperty(HTTPCLIENT_PROPERTY, dmwsHttpClient); meridioDMWebService_ = meridioDMWebService; /*================================================================= * Get a handle to the RMWS *================================================================*/ MeridioRMLocator meridioRMLocator = new MeridioRMLocator(engineConfiguration); MeridioRMSoapStub meridioRMWebService = new MeridioRMSoapStub(meridioRmwsUrl, meridioRMLocator); meridioRMWebService.setPortName(meridioRMLocator.getMeridioRMSoapWSDDServiceName()); meridioRMWebService.setUsername(userName); meridioRMWebService.setPassword(password); meridioRMWebService._setProperty(HTTPCLIENT_PROPERTY, rmwsHttpClient); meridioRMWebService_ = meridioRMWebService; /*================================================================= * Get a handle to the MeridioMetaCarta Web Service *================================================================*/ if (meridioManifoldCFWSUrl != null) { MetaCartaLocator meridioMCWS = new MetaCartaLocator(engineConfiguration); Service McWsService = null; MetaCartaSoapStub meridioMetaCartaWebService = new MetaCartaSoapStub(meridioManifoldCFWSUrl, McWsService); meridioMetaCartaWebService.setPortName(meridioMCWS.getMetaCartaSoapWSDDServiceName()); meridioMetaCartaWebService.setUsername(userName); meridioMetaCartaWebService.setPassword(password); meridioMetaCartaWebService._setProperty(HTTPCLIENT_PROPERTY, mcwsHttpClient); meridioMCWS_ = meridioMetaCartaWebService; } this.loginUnified(); }
From source file:lucee.commons.net.http.httpclient4.HTTPEngine4Impl.java
public static void setNTCredentials(DefaultHttpClient client, String username, String password, String workStation, String domain) { // set Username and Password if (!StringUtil.isEmpty(username, true)) { if (password == null) password = ""; CredentialsProvider cp = client.getCredentialsProvider(); cp.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new NTCredentials(username, password, workStation, domain)); //httpMethod.setDoAuthentication( true ); }/*from ww w . ja v a2 s .c om*/ }
From source file:org.eclipse.mylyn.commons.repositories.http.core.HttpUtil.java
static Credentials getCredentials(final String username, final String password, final InetAddress address, boolean forceUserNamePassword) { int i = username.indexOf("\\"); //$NON-NLS-1$ if (i > 0 && i < username.length() - 1 && address != null && !forceUserNamePassword) { String hostName = address.getHostName(); try {// w ww . ja va 2 s. c o m InetAddress localHost = InetAddress.getLocalHost(); if (localHost != null) { hostName = localHost.getHostName(); } } catch (UnknownHostException e) { StatusHandler.log(new Status(IStatus.ERROR, ID_PLUGIN, "Unable to get hostname. Defaulting to servers host.", e)); //$NON-NLS-1$ } if (hostName == null) { hostName = address.getHostName(); } return new NTCredentials(username.substring(i + 1), password, hostName, username.substring(0, i)); } else { return new UsernamePasswordCredentials(username, password); } }
From source file:com.norconex.collector.http.client.impl.GenericHttpClientFactory.java
protected CredentialsProvider createCredentialsProvider() { CredentialsProvider credsProvider = null; //--- Proxy --- if (StringUtils.isNotBlank(proxyUsername)) { credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(proxyUsername, proxyPassword)); }//w ww . j a v a2 s. c o m //--- Auth --- if (StringUtils.isNotBlank(authUsername) && !AUTH_METHOD_FORM.equalsIgnoreCase(authMethod)) { if (credsProvider == null) { credsProvider = new BasicCredentialsProvider(); } Credentials creds = null; if (AUTH_METHOD_NTLM.equalsIgnoreCase(authMethod)) { creds = new NTCredentials(authUsername, authPassword, authWorkstation, authDomain); } else { creds = new UsernamePasswordCredentials(authUsername, authPassword); } credsProvider.setCredentials(new AuthScope(authHostname, authPort, authRealm, authMethod), creds); } return credsProvider; }
From source file:lucee.commons.net.http.httpclient.HTTPEngine4Impl.java
public static void setNTCredentials(HttpClientBuilder builder, String username, String password, String workStation, String domain) { // set Username and Password if (!StringUtil.isEmpty(username, true)) { if (password == null) password = ""; CredentialsProvider cp = new BasicCredentialsProvider(); builder.setDefaultCredentialsProvider(cp); cp.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new NTCredentials(username, password, workStation, domain)); }/* w w w . ja va 2 s .c o m*/ }
From source file:org.switchyard.component.resteasy.util.ClientInvoker.java
/** * Create a RESTEasy invoker client.//from ww w. jav a 2 s.c o m * * @param basePath The base path for the class * @param resourceClass The JAX-RS Resource Class * @param method The JAX-RS Resource Class's method * @param model Configuration model */ public ClientInvoker(String basePath, Class<?> resourceClass, Method method, RESTEasyBindingModel model) { Set<String> httpMethods = IsHttpMethod.getHttpMethods(method); _baseUri = createUri(basePath); if ((httpMethods == null || httpMethods.size() == 0) && method.isAnnotationPresent(Path.class) && method.getReturnType().isInterface()) { _subResourcePath = createSubResourcePath(basePath, method); } else if (httpMethods == null || httpMethods.size() != 1) { throw RestEasyMessages.MESSAGES .youMustUseAtLeastOneButNoMoreThanOneHttpMethodAnnotationOn(method.toString()); } _httpMethod = httpMethods.iterator().next(); _resourceClass = resourceClass; _method = method; try { _uri = (UriBuilder) URIBUILDER_CLASS.newInstance(); } catch (InstantiationException ie) { throw new RuntimeException(ie); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } _uri.uri(_baseUri); if (_resourceClass.isAnnotationPresent(Path.class)) { _uri.path(_resourceClass); } if (_method.isAnnotationPresent(Path.class)) { _uri.path(_method); } _providerFactory = new ResteasyProviderFactory(); boolean useBuiltins = true; // use builtin @Provider classes by default if (model.getContextParamsConfig() != null) { Map<String, String> contextParams = model.getContextParamsConfig().toMap(); // Set use builtin @Provider classes String registerBuiltins = contextParams.get(ResteasyContextParameters.RESTEASY_USE_BUILTIN_PROVIDERS); if (registerBuiltins != null) { useBuiltins = Boolean.parseBoolean(registerBuiltins); } // Register @Provider classes List<Class<?>> providerClasses = RESTEasyUtil.getProviderClasses(contextParams); if (providerClasses != null) { for (Class<?> pc : providerClasses) { _providerFactory.registerProvider(pc); } } List<ClientErrorInterceptor> interceptors = RESTEasyUtil.getClientErrorInterceptors(contextParams); if (interceptors != null) { for (ClientErrorInterceptor interceptor : interceptors) { _providerFactory.addClientErrorInterceptor(interceptor); } } } if (useBuiltins) { _providerFactory.setRegisterBuiltins(true); RegisterBuiltin.register(_providerFactory); } _extractorFactory = new DefaultEntityExtractorFactory(); _extractor = _extractorFactory.createExtractor(_method); _marshallers = ClientMarshallerFactory.createMarshallers(_resourceClass, _method, _providerFactory, null); _accepts = MediaTypeHelper.getProduces(_resourceClass, method, null); ClientInvokerInterceptorFactory.applyDefaultInterceptors(this, _providerFactory, _resourceClass, _method); // Client executor SchemeRegistry schemeRegistry = new SchemeRegistry(); int port = _baseUri.getPort(); if (_baseUri.getScheme().startsWith("https")) { if (port == -1) { port = 443; } SSLSocketFactory sslFactory = getSSLSocketFactory(model.getSSLContextConfig()); if (sslFactory == null) { sslFactory = SSLSocketFactory.getSocketFactory(); } schemeRegistry.register(new Scheme(_baseUri.getScheme(), port, sslFactory)); } else { if (port == -1) { port = 80; } schemeRegistry.register(new Scheme(_baseUri.getScheme(), port, PlainSocketFactory.getSocketFactory())); } PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry); cm.setMaxTotal(200); cm.setDefaultMaxPerRoute(20); HttpClient httpClient = new DefaultHttpClient(cm); _executor = new ApacheHttpClient4Executor(httpClient); // register ApacheHttpClient4ExceptionMapper manually for local instance of ResteasyProviderFactory Type exceptionType = Types.getActualTypeArgumentsOfAnInterface(ApacheHttpClient4ExceptionMapper.class, ClientExceptionMapper.class)[0]; _providerFactory.addClientExceptionMapper(new ApacheHttpClient4ExceptionMapper(), exceptionType); // Authentication settings if (model.hasAuthentication()) { // Set authentication AuthScope authScope = null; Credentials credentials = null; if (model.isBasicAuth()) { authScope = createAuthScope(model.getBasicAuthConfig().getHost(), model.getBasicAuthConfig().getPort(), model.getBasicAuthConfig().getRealm()); credentials = new UsernamePasswordCredentials(model.getBasicAuthConfig().getUser(), model.getBasicAuthConfig().getPassword()); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); authCache.put(new HttpHost(authScope.getHost(), authScope.getPort()), new BasicScheme(ChallengeState.TARGET)); BasicHttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.AUTH_CACHE, authCache); ((ApacheHttpClient4Executor) _executor).setHttpContext(context); } else { authScope = createAuthScope(model.getNtlmAuthConfig().getHost(), model.getNtlmAuthConfig().getPort(), model.getNtlmAuthConfig().getRealm()); credentials = new NTCredentials(model.getNtlmAuthConfig().getUser(), model.getNtlmAuthConfig().getPassword(), "", model.getNtlmAuthConfig().getDomain()); } ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope, credentials); } else { ProxyModel proxy = model.getProxyConfig(); if (proxy != null) { HttpHost proxyHost = null; if (proxy.getPort() != null) { proxyHost = new HttpHost(proxy.getHost(), Integer.valueOf(proxy.getPort()).intValue()); } else { proxyHost = new HttpHost(proxy.getHost(), -1); } if (proxy.getUser() != null) { AuthScope authScope = new AuthScope(proxy.getHost(), Integer.valueOf(proxy.getPort()).intValue(), AuthScope.ANY_REALM); Credentials credentials = new UsernamePasswordCredentials(proxy.getUser(), proxy.getPassword()); AuthCache authCache = new BasicAuthCache(); authCache.put(proxyHost, new BasicScheme(ChallengeState.PROXY)); ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope, credentials); BasicHttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.AUTH_CACHE, authCache); ((ApacheHttpClient4Executor) _executor).setHttpContext(context); } httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost); } } Integer timeout = model.getTimeout(); if (timeout != null) { HttpParams httpParams = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, timeout); HttpConnectionParams.setSoTimeout(httpParams, timeout); } }
From source file:org.orbeon.oxf.resources.handler.HTTPURLConnection.java
public void connect() throws IOException { if (!connected) { final String userInfo = url.getUserInfo(); final boolean isAuthenticationRequestedWithUsername = username != null && !username.equals(""); // Create the HTTP client and HTTP context for the client (we expect this to be fairly lightweight) final DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpParams); final HttpContext httpContext = new BasicHttpContext(); // Set cookie store, creating a new one if none was provided to us if (cookieStore == null) cookieStore = new BasicCookieStore(); httpClient.setCookieStore(cookieStore); // Set proxy and host authentication if (proxyAuthState != null) httpContext.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState); if (userInfo != null || isAuthenticationRequestedWithUsername) { // Make authentication preemptive; interceptor is added first, as the Authentication header is added // by HttpClient's RequestTargetAuthentication which is itself an interceptor, so our interceptor // needs to run before RequestTargetAuthentication, otherwise RequestTargetAuthentication won't find // the appropriate AuthState/AuthScheme/Credentials in the HttpContext // Don't add the interceptor if we don't want preemptive authentication! if (!"false".equals(preemptiveAuthentication)) { httpClient.addRequestInterceptor(preemptiveAuthHttpRequestInterceptor, 0); }//from www. j a va 2 s .c o m CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider); final AuthScope authScope = new AuthScope(url.getHost(), url.getPort()); final Credentials credentials; if (userInfo != null) { // Set username and optional password specified on URL final int separatorPosition = userInfo.indexOf(":"); String username = separatorPosition == -1 ? userInfo : userInfo.substring(0, separatorPosition); String password = separatorPosition == -1 ? "" : userInfo.substring(separatorPosition + 1); // If the username/password contain special character, those character will be encoded, since we // are getting this from a URL. Now do the decoding. username = URLDecoder.decode(username, "utf-8"); password = URLDecoder.decode(password, "utf-8"); credentials = new UsernamePasswordCredentials(username, password); } else { // Set username and password specified externally credentials = domain == null ? new UsernamePasswordCredentials(username, password == null ? "" : password) : new NTCredentials(username, password, url.getHost(), domain); } credentialsProvider.setCredentials(authScope, credentials); } // If method has not been set, use GET // This can happen e.g. when this connection handler is used from URLFactory if (method == null) setRequestMethod("GET"); // Set all headers, final boolean skipAuthorizationHeader = userInfo != null || username != null; for (final Map.Entry<String, String[]> currentEntry : requestProperties.entrySet()) { final String currentHeaderName = currentEntry.getKey(); final String[] currentHeaderValues = currentEntry.getValue(); for (final String currentHeaderValue : currentHeaderValues) { // Skip over Authorization header if user authentication specified if (skipAuthorizationHeader && currentHeaderName.toLowerCase() .equals(Connection.AUTHORIZATION_HEADER.toLowerCase())) continue; method.addHeader(currentHeaderName, currentHeaderValue); } } // Create request entity with body if (method instanceof HttpEntityEnclosingRequest) { // Use the body that was set directly, or the result of writing to the OutputStream final byte[] body = (requestBody != null) ? requestBody : (os != null) ? os.toByteArray() : null; if (body != null) { final Header contentTypeHeader = method.getFirstHeader("Content-Type"); // Header names are case-insensitive for comparison if (contentTypeHeader == null) throw new ProtocolException("Can't set request entity: Content-Type header is missing"); final ByteArrayEntity byteArrayEntity = new ByteArrayEntity(body); byteArrayEntity.setContentType(contentTypeHeader); ((HttpEntityEnclosingRequest) method).setEntity(byteArrayEntity); } } // Make request httpResponse = httpClient.execute(method, httpContext); connected = true; } }
From source file:com.clustercontrol.http.util.GetHttpResponse.java
/** * URL??/*w w w . jav a 2s. co m*/ * * @param url URL * @param timeout * @return * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws KeyManagementException * @throws IOException * @throws ClientProtocolException */ public boolean execute(String url, String post) { Response result = new Response(); try { CloseableHttpClient client = getHttpClient(); result.url = url; if (m_authType != null && !AuthType.NONE.equals(m_authType)) { URI uri = new URI(url); Credentials credential = null; String authSchema = null; switch (m_authType) { case BASIC: credential = new UsernamePasswordCredentials(m_authUser, m_authPassword); authSchema = "basic"; break; case NTLM: credential = new NTCredentials(m_authUser, m_authPassword, null, null); authSchema = "ntlm"; break; case DIGEST: credential = new UsernamePasswordCredentials(m_authUser, m_authPassword); authSchema = "digest"; break; default: m_log.warn("Auth type is unexpected value. AuthType = " + m_authType.name()); } if (credential != null) { AuthScope scope = new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM, authSchema); if (m_cledentialProvider.getCredentials(scope) == null) { m_cledentialProvider.setCredentials(scope, credential); } } } HttpRequestBase request = null; if (post != null && !post.isEmpty()) { List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); for (String ss : post.split("&")) { int index = ss.indexOf("="); if (index <= 0) { continue; } urlParameters.add(new BasicNameValuePair(ss.substring(0, index), ss.substring(index + 1))); } if (m_log.isTraceEnabled()) { m_log.trace("post1=" + post + ", post2=" + urlParameters); } HttpPost requestPost = new HttpPost(url); Charset charset = Consts.UTF_8; try { charset = Charset.forName( HinemosPropertyUtil.getHinemosPropertyStr("monitor.http.post.charset", "UTF-8")); } catch (UnsupportedCharsetException e) { m_log.warn("UnsupportedCharsetException " + e.getMessage()); } requestPost.setEntity(new UrlEncodedFormEntity(urlParameters, charset)); requestPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"); request = requestPost; } else { request = new HttpGet(url); } // Execute the method. try { long start = HinemosTime.currentTimeMillis(); HttpResponse response = client.execute(request); result.responseTime = HinemosTime.currentTimeMillis() - start; result.statusCode = response.getStatusLine().getStatusCode(); // Header Header[] headers = response.getAllHeaders(); if (headers != null && headers.length > 0) { StringBuffer header = new StringBuffer(); for (int i = 0; i < headers.length; i++) { header.append((i != 0 ? "\n" : "") + headers[i]); } result.headerString = header.toString(); result.headers = Arrays.asList(headers); } if (result.statusCode == HttpStatus.SC_OK) { result.success = true; // Content-Type?text?????Body? Header header = response.getFirstHeader(HTTP.CONTENT_TYPE); boolean contentTypeFlag = false; String[] contentTypes = HinemosPropertyUtil .getHinemosPropertyStr(TARGET_CONTENT_TYPE_KEY, "text").split(","); if (header != null && header.getValue() != null) { String value = header.getValue(); for (String contentType : contentTypes) { if (value.indexOf(contentType) != -1) { contentTypeFlag = true; break; } } } if (contentTypeFlag) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (InputStream in = response.getEntity().getContent()) { byte[] buffer = new byte[BUFF_SIZE]; while (out.size() < BODY_MAX_SIZE) { int len = in.read(buffer); if (len < 0) { break; } out.write(buffer, 0, len); } } // ????HTTP ? meta ??????? // HTTP ?? // // Content-Type: text/html; charset=euc-jp // // meta ? // // <meta http-equiv="Content-Type" content="text/html; charset=euc-jp"> // <meta charset="euc-jp"> // // HTML ???meta ????? // // ???????????????? // ??????????????????? // ???????????????? // // ?????????????????? // // 1. HTTP ? Content-Type ? charset ???????? // ????????? // // 2. ????????"JISAutoDetect" ??? // ???? // // 3. ??????meta ?? // // 4. meta ?????????? // ???????? // ??????????? String charset = "JISAutoDetect"; Matcher m = chasetPattern.matcher(header.getValue()); if (m.matches()) charset = m.group(1); String content = new String(out.toByteArray(), charset); CharsetParser parser = new CharsetParser(); ParserDelegator p = new ParserDelegator(); p.parse(new StringReader(content), parser, true); if (parser.charset != null && !charset.equals(parser.charset)) { charset = parser.charset; content = new String(out.toByteArray(), charset); } result.responseBody = content; } else { result.errorMessage = MessageConstant.MESSAGE_FAIL_TO_CHECK_NOT_TEXT.getMessage(); } } else { result.errorMessage = response.getStatusLine().toString(); } } finally { request.releaseConnection(); } } catch (UnsupportedEncodingException e) { m_log.info("execute(): " + e.getMessage() + " class=" + e.getClass().getName()); result.errorMessage = "http receiving failure. (unsupported encoding)"; result.exception = e; } catch (IOException e) { m_log.info("execute(): Fatal transport error. " + e.getMessage() + " class=" + e.getClass().getName()); result.errorMessage = "http requesting failure. (I/O error : unreachable or timeout)"; result.exception = e; } catch (Exception e) { m_log.info("execute(): " + e.getMessage() + " class=" + e.getClass().getName()); result.errorMessage = "http requesting failure. " + e.getMessage() + "(" + e.getClass().getSimpleName() + ")"; result.exception = e; } m_requestResult = result; return m_requestResult.success; }