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:aajavafx.CustomerMedicineController.java
@FXML private void handleSaveButton(ActionEvent event) { //labelError.setText(null); try {// w ww.j a v a2 s . c om String dosage = dose.getText(); dose.clear(); String stDate = startDate.getText(); startDate.clear(); String sched = schedule.getText(); schedule.clear(); Customers customer = (Customers) customerBox.getSelectionModel().getSelectedItem(); Medicines medicine = (Medicines) medicinesBox.getSelectionModel().getSelectedItem(); CustomersTakesMedicinesPK ctmPK = new CustomersTakesMedicinesPK(customer.getCuId(), medicine.getmedId()); CustomersTakesMedicines ctm = new CustomersTakesMedicines(ctmPK, dosage, stDate, Double.parseDouble(sched)); ctm.setCustomers(customer); ctm.setMedicines(medicine); //System.out.println(customerBox.getValue()); //String string = (String)customerBox.getValue(); //System.out.println("STRING VALUE: "+string); //int customerId = Integer.parseInt(""+string.charAt(0)); //System.out.println("CUSTOMER ID VALUE:"+customerId); //Customers customer = getCustomerByID(customerId); Gson gson = new Gson(); //......for ssl handshake.... CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password"); provider.setCredentials(AuthScope.ANY, credentials); //........ HttpClient httpClient = HttpClientBuilder.create().build(); HttpEntityEnclosingRequestBase HttpEntity = null; //this is the superclass for post, put, get, etc if (startDate.isEditable()) { //then we are posting a new record HttpEntity = new HttpPost(MedicineCustomerRootURL); //so make a http post object } else { //we are editing a record HttpEntity = new HttpPut(MedicineCustomerRootURL + startDate); //so make a http put object } String jsonString = new String(gson.toJson(ctm)); System.out.println("json string: " + jsonString); StringEntity postString = new StringEntity(jsonString); HttpEntity.setEntity(postString); HttpEntity.setHeader("Content-type", "application/json"); HttpResponse response = httpClient.execute(HttpEntity); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 204) { System.out.println("Customer binded to medicine successfully"); } else { System.out.println("Server error: " + response.getStatusLine()); } dose.setEditable(false); startDate.setEditable(false); schedule.setEditable(false); customerBox.setDisable(true); } catch (Exception ex) { System.out.println("Error: " + ex); } try { //refresh table tableCustomer.setItems(getCustomersTakesMedicines()); } catch (IOException ex) { Logger.getLogger(DevicesController.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(DevicesController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:MainFrame.HttpCommunicator.java
public boolean setPassword(String password, String group) throws IOException { String response = null;/*from w ww. j ava 2 s . co m*/ String hashPassword = md5Custom(password); JSONObject jsObj = new JSONObject(); jsObj.put("group", group); jsObj.put("newHash", hashPassword); if (SingleDataHolder.getInstance().isProxyActivated) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword)); HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider) .build(); HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress, SingleDataHolder.getInstance().proxyPort); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php"); post.setConfig(config); StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("apideskviewer.getAllLessons", head); HttpEntity entity = builder.build(); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = client.execute(post, responseHandler); System.out.println("responseBody : " + response); } else { HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php"); StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("apiDeskViewer.updateGroupAccess", head); HttpEntity entity = builder.build(); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = client.execute(post, responseHandler); System.out.println("responseBody : " + response); } if (response.equals(new String("\"success\""))) return true; else return false; }
From source file:org.sonatype.nexus.proxy.storage.remote.httpclient.HttpClientUtil.java
private static void configureAuthentication(final DefaultHttpClient httpClient, final String ctxPrefix, final RemoteStorageContext ctx, final RemoteAuthenticationSettings ras, final Logger logger, final String authScope) { if (ras != null) { List<String> authorisationPreference = new ArrayList<String>(2); authorisationPreference.add(AuthPolicy.DIGEST); authorisationPreference.add(AuthPolicy.BASIC); Credentials credentials = null;/* w w w .j a v a2s . c om*/ if (ras instanceof ClientSSLRemoteAuthenticationSettings) { // ClientSSLRemoteAuthenticationSettings cras = (ClientSSLRemoteAuthenticationSettings) ras; // TODO - implement this } else if (ras instanceof NtlmRemoteAuthenticationSettings) { final NtlmRemoteAuthenticationSettings nras = (NtlmRemoteAuthenticationSettings) ras; // Using NTLM auth, adding it as first in policies authorisationPreference.add(0, AuthPolicy.NTLM); logger(logger).info("... {}authentication setup for NTLM domain '{}'", authScope, nras.getNtlmDomain()); credentials = new NTCredentials(nras.getUsername(), nras.getPassword(), nras.getNtlmHost(), nras.getNtlmDomain()); ctx.putContextObject(ctxPrefix + CTX_KEY_NTLM_IS_IN_USE, Boolean.TRUE); } else if (ras instanceof UsernamePasswordRemoteAuthenticationSettings) { UsernamePasswordRemoteAuthenticationSettings uras = (UsernamePasswordRemoteAuthenticationSettings) ras; // Using Username/Pwd auth, will not add NTLM logger(logger).info("... {}authentication setup for remote storage with username '{}'", authScope, uras.getUsername()); credentials = new UsernamePasswordCredentials(uras.getUsername(), uras.getPassword()); } if (credentials != null) { httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); } httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authorisationPreference); } }
From source file:org.apache.reef.runtime.hdinsight.client.yarnrest.HDInsightInstance.java
private HttpClientContext getClientContext(final String hostname, final String username, final String password) throws IOException { final HttpHost targetHost = new HttpHost(hostname, 443, "https"); final HttpClientContext result = HttpClientContext.create(); // Setup credentials provider final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); result.setCredentialsProvider(credentialsProvider); // Setup preemptive authentication final AuthCache authCache = new BasicAuthCache(); final BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); result.setAuthCache(authCache);/*from www. java 2 s. co m*/ final HttpGet httpget = new HttpGet("/"); // Prime the cache try (final CloseableHttpResponse response = this.httpClient.execute(targetHost, httpget, result)) { // empty try block used to automatically close resources } return result; }
From source file:com.hortonworks.registries.auth.client.AuthenticatorTestCase.java
private SystemDefaultHttpClient getHttpClient() { final SystemDefaultHttpClient httpClient = new SystemDefaultHttpClient(); httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory(true)); Credentials use_jaas_creds = new Credentials() { public String getPassword() { return null; }//from w w w. jav a 2 s .c o m public Principal getUserPrincipal() { return null; } }; httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, use_jaas_creds); return httpClient; }
From source file:org.glassfish.jersey.apache.connector.AuthTest.java
@Test public void testAuthGet() { 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); cc.connectorProvider(new ApacheConnectorProvider()); Client client = ClientBuilder.newClient(cc); WebTarget r = client.target(getBaseUri()).path("test"); assertEquals("GET", r.request().get(String.class)); }
From source file:org.xmlsh.internal.commands.http.java
private void setOptions(DefaultHttpClient client, HttpHost host, Options opts) throws KeyManagementException, NoSuchAlgorithmException, UnrecoverableKeyException, CertificateException, FileNotFoundException, KeyStoreException, IOException { HttpParams params = client.getParams(); HttpConnectionParamBean connection = new HttpConnectionParamBean(params); if (opts.hasOpt("connectTimeout")) connection.setConnectionTimeout((int) (opts.getOptDouble("connectTimeout", 0) * 1000.)); if (opts.hasOpt("readTimeout")) connection.setSoTimeout((int) (opts.getOptDouble("readTimeout", 0) * 1000.)); /*//from www .java2 s . co m * if( opts.hasOpt("useCaches")) * client.setUseCaches( opts.getOpt("useCaches").getFlag()); * * * if( opts.hasOpt("followRedirects")) * * client.setInstanceFollowRedirects( * opts.getOpt("followRedirects").getFlag()); * * * * * * * String disableTrustProto = opts.getOptString("disableTrust", null); * * String keyStore = opts.getOptString("keystore", null); * String keyPass = opts.getOptString("keypass", null); * String sslProto = opts.getOptString("sslProto", "SSLv3"); * * if(disableTrustProto != null && client instanceof HttpsURLConnection ) * disableTrust( (HttpsURLConnection) client , disableTrustProto ); * * else * if( keyStore != null ) * setClient( (HttpsURLConnection) client , keyStore , keyPass , sslProto ); * */ String disableTrustProto = opts.getOptString("disableTrust", null); if (disableTrustProto != null) disableTrust(client, disableTrustProto); String user = opts.getOptString("user", null); String pass = opts.getOptString("password", null); if (user != null && pass != null) { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass); client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); /* * // Create AuthCache instance * AuthCache authCache = new BasicAuthCache(); * // Generate DIGEST scheme object, initialize it and add it to the local * // auth cache * DigestScheme digestAuth = new DigestScheme(); * // Suppose we already know the realm name * digestAuth.overrideParamter("realm", "some realm"); * // Suppose we already know the expected nonce value * digestAuth.overrideParamter("nonce", "whatever"); * authCache.put(host, digestAuth); * * // Add AuthCache to the execution context * BasicHttpContext localcontext = new BasicHttpContext(); * localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); */ } }
From source file:org.overlord.sramp.governance.shell.commands.Pkg2SrampCommand.java
/** * Uploads the BMRS package.//from ww w . j ava2 s . c o m * @param brmsBaseUrl * @param pkgName * @param tag * @param userId * @param password * @param client * @throws Exception */ public void uploadBrmsPackage(String brmsBaseUrl, String pkgName, String tag, String userId, String password, SrampAtomApiClient client) throws Exception { // http://localhost:8080/drools-guvnor/org.drools.guvnor.Guvnor/package/srampPackage/S_RAMP_0.0.3.0 String urlStr = brmsBaseUrl + "/org.drools.guvnor.Guvnor/package/" + pkgName + "/" + tag; //$NON-NLS-1$ //$NON-NLS-2$ Credentials credentials = new UsernamePasswordCredentials(userId, password); DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); ClientExecutor clientExecutor = new ApacheHttpClient4Executor(httpClient); fac = new ClientRequestFactory(clientExecutor, new URI(brmsBaseUrl)); Map<String, Packages.Package> brmsPkgMap = getPkgsFromBrms(brmsBaseUrl); if (!brmsPkgMap.containsKey(pkgName)) { print("Brms contains the following BRMS Packages"); //$NON-NLS-1$ for (String name : brmsPkgMap.keySet()) { print(" * " + name); //$NON-NLS-1$ } throw new Exception("Could not find package with name " + pkgName + " in BRMS"); //$NON-NLS-1$ //$NON-NLS-2$ } Packages.Package brmsPkg = brmsPkgMap.get(pkgName); print("Located BRMS package '" + pkgName + "' :"); //$NON-NLS-1$ //$NON-NLS-2$ print(" UUID ............: " + brmsPkg.getMetadata().getUuid()); //$NON-NLS-1$ print(" Version .........: " + brmsPkg.getMetadata().getVersionNumber()); //$NON-NLS-1$ print(" Author ..........: " + brmsPkg.getAuthor()); //$NON-NLS-1$ print(" Last published ..: " + brmsPkg.getPublished()); //$NON-NLS-1$ print(" Description .....: " + brmsPkg.getDescription()); //$NON-NLS-1$ // now uploading this into s-ramp @SuppressWarnings("deprecation") ExtendedArtifactType extendedArtifactType = (ExtendedArtifactType) ArtifactType.fromFileExtension("pkg") //$NON-NLS-1$ .newArtifactInstance(); extendedArtifactType.setUuid(brmsPkg.getMetadata().getUuid()); extendedArtifactType.setName(pkgName + ".pkg"); //$NON-NLS-1$ Property assetsProperty = new Property(); assetsProperty.setPropertyName(BrmsConstants.ASSET_INFO_XML); String assetsXml = getAssetsStringFromBrms(brmsBaseUrl, pkgName); //update the links String srampUrl = client.getEndpoint().substring(0, client.getEndpoint().lastIndexOf("/")); //$NON-NLS-1$ assetsXml = assetsXml.replaceAll(brmsBaseUrl, srampUrl + "/brms"); //$NON-NLS-1$ assetsProperty.setPropertyValue(assetsXml); extendedArtifactType.getProperty().add(assetsProperty); print("Reading " + pkgName + " from url " + urlStr); //$NON-NLS-1$ //$NON-NLS-2$ ClientResponse<InputStream> pkgResponse = getInputStream(urlStr); InputStream content = pkgResponse.getEntity(); BaseArtifactType artifact = client.uploadArtifact(extendedArtifactType, content); IOUtils.closeQuietly(content); print("Uploaded " + pkgName + " UUID=" + artifact.getUuid()); //$NON-NLS-1$ //$NON-NLS-2$ // Now obtaining the assets in the this package, and upload those // TODO set relationship to parent pkg Assets assets = getAssetsFromBrms(brmsBaseUrl, pkgName); //Upload the process AND process-image, making sure the uuid is identical to the one mentioned for (Assets.Asset asset : assets.getAsset()) { if (!"package".equalsIgnoreCase(asset.getMetadata().getFormat())) { //$NON-NLS-1$ //Upload the asset String fileName = asset.getTitle() + "." + asset.getMetadata().getFormat().toLowerCase(); //$NON-NLS-1$ String uuid = asset.getMetadata().getUuid(); //reading the asset from disk //http://localhost:8080/drools-guvnor/rest/packages/srampPackage/assets/ String assetURLStr = brmsBaseUrl + "/rest/packages/" + pkgName + "/assets/" + asset.getTitle() //$NON-NLS-1$//$NON-NLS-2$ + "/binary"; //$NON-NLS-1$ //print("Reading asset " + asset.getTitle() + " from url " + assetURLStr ); ClientResponse<InputStream> assetResponse = getInputStream(assetURLStr); InputStream assetInputStream = assetResponse.getEntity(); //upload the asset using the uuid @SuppressWarnings("deprecation") ArtifactType artifactType = ArtifactType.fromFileExtension(asset.getMetadata().getFormat()); BaseArtifactType baseArtifactType = artifactType.newArtifactInstance(); baseArtifactType.setName(fileName); baseArtifactType.setUuid(uuid); BaseArtifactType assetArtifact = client.uploadArtifact(baseArtifactType, assetInputStream); IOUtils.closeQuietly(assetInputStream); print("Uploaded asset " + assetArtifact.getUuid() + " " + assetArtifact.getName()); //$NON-NLS-1$ //$NON-NLS-2$ } } print("OK"); //$NON-NLS-1$ }
From source file:org.apache.hadoop.hbase.http.TestSpnegoHttpServer.java
@Test public void testAllowedClient() throws Exception { // Create the subject for the client final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(CLIENT_PRINCIPAL, clientKeytab); final Set<Principal> clientPrincipals = clientSubject.getPrincipals(); // Make sure the subject has a principal assertFalse(clientPrincipals.isEmpty()); // Get a TGT for the subject (might have many, different encryption types). The first should // be the default encryption type. Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class); assertFalse(privateCredentials.isEmpty()); KerberosTicket tgt = privateCredentials.iterator().next(); assertNotNull(tgt);// w w w . j a v a 2 s . c o m // The name of the principal final String principalName = clientPrincipals.iterator().next().getName(); // Run this code, logged in as the subject (the client) HttpResponse resp = Subject.doAs(clientSubject, new PrivilegedExceptionAction<HttpResponse>() { @Override public HttpResponse run() throws Exception { // Logs in with Kerberos via GSS GSSManager gssManager = GSSManager.getInstance(); // jGSS Kerberos login constant Oid oid = new Oid("1.2.840.113554.1.2.2"); GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME); GSSCredential credential = gssManager.createCredential(gssClient, GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY); HttpClientContext context = HttpClientContext.create(); Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build(); HttpClient client = HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry).build(); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential)); URL url = new URL(getServerURL(server), "/echo?a=b"); context.setTargetHost(new HttpHost(url.getHost(), url.getPort())); context.setCredentialsProvider(credentialsProvider); context.setAuthSchemeRegistry(authRegistry); HttpGet get = new HttpGet(url.toURI()); return client.execute(get, context); } }); assertNotNull(resp); assertEquals(HttpURLConnection.HTTP_OK, resp.getStatusLine().getStatusCode()); assertEquals("a:b", EntityUtils.toString(resp.getEntity()).trim()); }