List of usage examples for org.apache.http.auth AuthScope ANY
AuthScope ANY
To view the source code for org.apache.http.auth AuthScope ANY.
Click Source Link
From source file:org.glassfish.jersey.apache.connector.AuthTest.java
@Test public void testPreemptiveAuth() { CredentialsProvider credentialsProvider = new org.apache.http.impl.client.BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("name", "password")); ClientConfig cc = new ClientConfig(); cc.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider) .property(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, true); cc.connectorProvider(new ApacheConnectorProvider()); Client client = ClientBuilder.newClient(cc); WebTarget r = client.target(getBaseUri()); assertEquals("GET", r.request().get(String.class)); }
From source file:com.cloudbees.plugins.binarydeployer.http.HttpRepository.java
@Override protected void deploy(List<Binary> binaries, Run run) throws IOException { CloseableHttpClient client = null;/*w ww. j a va 2 s .c om*/ try { if (credentialsId == null || credentialsId.isEmpty()) { client = HttpClients.createDefault(); } else { BasicCredentialsProvider credentials = new BasicCredentialsProvider(); StandardUsernamePasswordCredentials credentialById = CredentialsProvider.findCredentialById( credentialsId, StandardUsernamePasswordCredentials.class, run, Lists.<DomainRequirement>newArrayList()); credentials.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( credentialById.getUsername(), credentialById.getPassword().getPlainText())); client = HttpClients.custom().setDefaultCredentialsProvider(credentials).disableAutomaticRetries() .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)).build(); } for (Binary binary : binaries) { BufferedHttpEntity entity = new BufferedHttpEntity( new InputStreamEntity(binary.getFile().open(), binary.getFile().length())); HttpPost post = new HttpPost(remoteLocation + binary.getName()); post.setEntity(entity); CloseableHttpResponse response = null; try { response = client.execute(post); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { log.fine("Deployed " + binary.getName() + " to " + remoteLocation); } else { log.warning("Cannot deploy file " + binary.getName() + ". Response from target was " + statusCode); run.setResult(Result.FAILURE); throw new IOException(response.getStatusLine().toString()); } } finally { if (response != null) { response.close(); } } } } finally { if (client != null) { client.close(); } } }
From source file:org.fabrician.maven.plugins.GridlibUploadMojo.java
public void execute() throws MojoExecutionException { String username = brokerUsername; String password = brokerPassword; if (serverId != null && !"".equals(serverId)) { // TODO: implement server_id throw new MojoExecutionException("serverId is not yet supported"); } else if (brokerUsername == null || "".equals(brokerUsername) || brokerPassword == null || "".equals(brokerPassword)) { throw new MojoExecutionException("serverId or brokerUsername and brokerPassword must be set"); }/*from www .ja va 2 s . com*/ DirectoryScanner ds = new DirectoryScanner(); ds.setIncludes(mIncludes); ds.setExcludes(mExcludes); ds.setBasedir("."); ds.setCaseSensitive(true); ds.scan(); String[] files = ds.getIncludedFiles(); if (files == null) { getLog().info("No files found to upload"); } else { getLog().info("Found " + files.length + " file to upload"); for (String file : files) { File gridlibFilename = new File(file); getLog().info("Uploading " + gridlibFilename + " to " + brokerUrl); DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); Credentials cred = new UsernamePasswordCredentials(username, password); httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, cred); try { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("gridlibOverwrite", new StringBody(String.valueOf(gridlibOverwrite), Charset.forName("UTF-8"))); entity.addPart("gridlibArchive", new FileBody(gridlibFilename)); HttpPost method = new HttpPost(brokerUrl); method.setEntity(entity); HttpResponse response = httpclient.execute(method); StatusLine status = response.getStatusLine(); int code = status.getStatusCode(); if (code >= 400 && code <= 500) { throw new MojoExecutionException( "Failed to upload " + gridlibFilename + " to " + brokerUrl + ": " + code); } } catch (Exception e) { throw new MojoExecutionException(e.getMessage()); } } } }
From source file:org.apache.sling.testing.tools.http.RequestExecutor.java
public RequestExecutor execute(Request r) throws ClientProtocolException, IOException { clear();/*from ww w. j a v a2s .co m*/ r.customizeIfNeeded(); request = r.getRequest(); // Optionally setup for basic authentication if (r.getUsername() != null) { httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(r.getUsername(), r.getPassword())); // And add request interceptor to have preemptive authentication httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0); } else { // Make sure existing credentials are not reused - but looks like we // cannot set null as credentials httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(getClass().getName(), getClass().getSimpleName())); httpClient.removeRequestInterceptorByClass(PreemptiveAuthInterceptor.class); } // Setup redirects httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, r.getRedirects()); // Execute request response = httpClient.execute(request); entity = response.getEntity(); if (entity != null) { consumeEntity(); } return this; }
From source file:com.farmafene.commons.cas.URLAuthenticationHandler.java
/** * {@inheritDoc}//from ww w. j a v a2 s . c om * * @see org.jasig.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler#authenticateUsernamePasswordInternal(org.jasig.cas.authentication.principal.UsernamePasswordCredentials) */ @Override protected boolean authenticateUsernamePasswordInternal(UsernamePasswordCredentials credentials) throws AuthenticationException { long initTime = System.currentTimeMillis(); boolean authenticateUsernamePasswordInternal = false; HttpContext context = new BasicHttpContext(); HttpClientFactory f = new HttpClientFactory(); f.setLoginURL(loginURL); f.setProxyHost(proxyHost); f.setProxyPort(proxyPort); DefaultHttpClient httpClient = f.getClient(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); org.apache.http.auth.UsernamePasswordCredentials cred = new org.apache.http.auth.UsernamePasswordCredentials( credentials.getUsername(), credentials.getPassword()); credsProvider.setCredentials(AuthScope.ANY, cred); List<String> n = new ArrayList<String>(); n.add(AuthPolicy.BASIC); n.add(AuthPolicy.DIGEST); httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, n); context.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider); HttpGet httpGet = new HttpGet(loginURL); HttpResponse httpResponse = null; try { httpResponse = httpClient.execute(httpGet, context); if (httpResponse.getStatusLine().getStatusCode() == 200) { authenticateUsernamePasswordInternal = true; } } catch (ClientProtocolException e) { logger.error("Error: ", e); } catch (IOException e) { logger.error("Error: ", e); } if (logger.isDebugEnabled()) { logger.debug("Total time: " + (System.currentTimeMillis() - initTime) + " ms, " + this); } return authenticateUsernamePasswordInternal; }
From source file:io.openvidu.java.client.OpenVidu.java
/** * @param urlOpenViduServer Public accessible IP where your instance of OpenVidu * Server is up an running * @param secret Secret used on OpenVidu Server initialization *///from w w w. ja va 2 s .co m public OpenVidu(String urlOpenViduServer, String secret) { OpenVidu.urlOpenViduServer = urlOpenViduServer; if (!OpenVidu.urlOpenViduServer.endsWith("/")) { OpenVidu.urlOpenViduServer += "/"; } this.secret = secret; TrustStrategy trustStrategy = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }; CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("OPENVIDUAPP", this.secret); provider.setCredentials(AuthScope.ANY, credentials); SSLContext sslContext; try { sslContext = new SSLContextBuilder().loadTrustMaterial(null, trustStrategy).build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { throw new RuntimeException(e); } RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder = requestBuilder.setConnectTimeout(30000); requestBuilder = requestBuilder.setConnectionRequestTimeout(30000); OpenVidu.httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestBuilder.build()) .setConnectionTimeToLive(30, TimeUnit.SECONDS).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) .setSSLContext(sslContext).setDefaultCredentialsProvider(provider).build(); }
From source file:pl.psnc.synat.wrdz.common.https.HttpsClientHelper.java
/** * Gets HTTPS client that can authenticate in WRDZ modules. * // w w w .ja va 2 s. c o m * @param module * module that wants to be authenticated * @return HTTPS client */ public synchronized HttpClient getHttpsClient(WrdzModule module) { DefaultHttpClient httpClient = httpsClients.get(module); if (httpClient == null) { logger.debug("HTTPS client for module " + module.name() + " is not yet initialized"); try { SSLSocketFactory socketFactory; if (config.getHttpsVerifyHostname()) { socketFactory = new SSLSocketFactory(new TrustAllStrategy()); } else { socketFactory = new SSLSocketFactory(new TrustAllStrategy(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } Scheme scheme = new Scheme("https", 443, socketFactory); PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(); connectionManager.getSchemeRegistry().register(scheme); String cipher = config.getModulesPassword(); byte[] key = SECRET.getBytes("utf-8"); Cipher c = Cipher.getInstance("AES"); SecretKeySpec k = new SecretKeySpec(key, "AES"); c.init(Cipher.DECRYPT_MODE, k); byte[] decrypted = c.doFinal(Base64.decodeBase64(cipher)); String password = new String(decrypted, "utf-8"); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(module.name(), password); httpClient = new DefaultHttpClient(connectionManager); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); httpsClients.put(module, httpClient); } catch (Exception e) { throw new WrdzRuntimeException(e.getMessage(), e); } } return httpClient; }
From source file:io.fabric8.itests.paxexam.basic.FabricMavenProxyTest.java
@Test public void testUpload() throws Exception { String featureLocation = System.getProperty("feature.location"); System.out.println("Testing with feature from:" + featureLocation); System.out.println(executeCommand("fabric:create -n --wait-for-provisioning")); //System.out.println(executeCommand("shell:info")); //System.out.println(executeCommand("fabric:info")); //System.out.println(executeCommand("fabric:profile-list")); ServiceProxy<FabricService> fabricProxy = ServiceProxy.createServiceProxy(bundleContext, FabricService.class); try {//from w ww. ja v a 2 s.c o m Set<ContainerProxy> containers = ContainerBuilder.create(fabricProxy, 2).withName("maven") .withProfiles("fabric").assertProvisioningResult().build(); try { List<String> uploadUrls = new ArrayList<String>(); ServiceProxy<CuratorFramework> curatorProxy = ServiceProxy.createServiceProxy(bundleContext, CuratorFramework.class); try { CuratorFramework curator = curatorProxy.getService(); List<String> children = ZooKeeperUtils.getChildren(curator, ZkPath.MAVEN_PROXY.getPath("upload")); for (String child : children) { String uploadeUrl = ZooKeeperUtils.getSubstitutedPath(curator, ZkPath.MAVEN_PROXY.getPath("upload") + "/" + child); uploadUrls.add(uploadeUrl); } } finally { curatorProxy.close(); } //Pick a random maven proxy from the list. Random random = new Random(); int index = random.nextInt(uploadUrls.size()); String targetUrl = uploadUrls.get(index); String uploadUrl = targetUrl + "itest/itest/1.0/itest-1.0-features.xml"; System.out.println("Using URI: " + uploadUrl); DefaultHttpClient client = new DefaultHttpClient(); HttpPut put = new HttpPut(uploadUrl); client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin")); FileNIOEntity entity = new FileNIOEntity(new File(featureLocation), "text/xml"); put.setEntity(entity); HttpResponse response = client.execute(put); System.out.println("Response:" + response.getStatusLine()); Assert.assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 202); System.out.println(executeCommand( "fabric:profile-edit --repositories mvn:itest/itest/1.0/xml/features default")); System.out.println(executeCommand("fabric:profile-edit --features example-cbr default")); Provision.containerStatus(containers, PROVISION_TIMEOUT); } finally { ContainerBuilder.destroy(containers); } } finally { fabricProxy.close(); } }
From source file:com.sun.jersey.client.apache4.impl.AuthTest.java
public void testPreemptiveAuth() { ResourceConfig rc = new DefaultResourceConfig(PreemptiveAuthResource.class); rc.getProperties().put(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, LoggingFilter.class.getName()); startServer(rc);//from ww w . j a va 2 s . c o m CredentialsProvider credentialsProvider = new org.apache.http.impl.client.BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("name", "password")); DefaultApacheHttpClient4Config config = new DefaultApacheHttpClient4Config(); config.getProperties().put(ApacheHttpClient4Config.PROPERTY_CREDENTIALS_PROVIDER, credentialsProvider); config.getProperties().put(ApacheHttpClient4Config.PROPERTY_PREEMPTIVE_BASIC_AUTHENTICATION, true); ApacheHttpClient4 c = ApacheHttpClient4.create(config); WebResource r = c.resource(getUri().build()); assertEquals("GET", r.get(String.class)); }
From source file:org.overlord.dtgov.jbpm.util.HttpClientWorkItemHandler.java
/** * Calls an HTTP endpoint. The address of the endpoint should be set in the * parameter map passed into the workItem by the BPMN workflow. Both * this parameters 'Url' as well as the method 'Method' are required * parameters./* w ww . ja va 2 s .c o m*/ */ @Override public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { Governance governance = new Governance(); ClientResponse<?> response = null; Map<String, Object> results = new HashMap<String, Object>(); try { // extract required parameters String urlStr = (String) workItem.getParameter("Url"); //$NON-NLS-1$ String method = (String) workItem.getParameter("Method"); //$NON-NLS-1$ if (urlStr == null || method == null) { throw new Exception(Messages.i18n.format("HttpClientWorkItemHandler.MissingParams")); //$NON-NLS-1$ } urlStr = urlStr.toLowerCase(); urlStr = urlStr.replaceAll("\\{governance.url\\}", governance.getGovernanceUrl()); //$NON-NLS-1$ Map<String, Object> params = workItem.getParameters(); // replace tokens in the urlStr, the replacement value of the token // should be set in the parameters Map for (String key : params.keySet()) { // break out if there are no (more) tokens in the urlStr if (!urlStr.contains("{")) //$NON-NLS-1$ break; // replace the token if it is referenced in the urlStr String variable = "{" + key.toLowerCase() + "}"; //$NON-NLS-1$ //$NON-NLS-2$ if (urlStr.contains(variable)) { String escapedVariable = "\\{" + key.toLowerCase() + "\\}"; //$NON-NLS-1$ //$NON-NLS-2$ String urlEncodedParam = URLEncoder.encode((String) params.get(key), "UTF-8").replaceAll("%2F", //$NON-NLS-1$//$NON-NLS-2$ "*2F"); //$NON-NLS-1$ urlStr = urlStr.replaceAll(escapedVariable, urlEncodedParam); } } if (urlStr.contains("{")) //$NON-NLS-1$ throw new Exception(Messages.i18n.format("HttpClientWorkItemHandler.IncorrectParams", urlStr)); //$NON-NLS-1$ // call http endpoint log.info(Messages.i18n.format("HttpClientWorkItemHandler.CallingTo", method, urlStr)); //$NON-NLS-1$ DefaultHttpClient httpClient = new DefaultHttpClient(); String username = governance.getOverlordUser(); String password = governance.getOverlordPassword(); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient); ClientRequest request = new ClientRequest(urlStr, executor); request.setHttpMethod(method); response = request.execute(); int responseCode = response.getResponseStatus().getStatusCode(); if (responseCode >= 200 && responseCode < 300) { Map<String, ValueEntity> map = (Map<String, ValueEntity>) response .getEntity(new GenericType<HashMap<String, ValueEntity>>() { }); for (String key : map.keySet()) { if (map.get(key).getValue() != null) { results.put(key, map.get(key).getValue()); } } log.info("reply=" + results); //$NON-NLS-1$ } else { results.put("Status", "ERROR " + responseCode); //$NON-NLS-1$ //$NON-NLS-2$ results.put("StatusMsg", //$NON-NLS-1$ Messages.i18n.format("HttpClientWorkItemHandler.UnreachableEndpoint", urlStr)); //$NON-NLS-1$ log.error(Messages.i18n.format("HttpClientWorkItemHandler.UnreachableEndpoint", urlStr)); //$NON-NLS-1$ } } catch (Exception e) { log.error(e.getMessage(), e); } finally { if (response != null) response.releaseConnection(); } // notify manager that work item has been completed manager.completeWorkItem(workItem.getId(), results); }