List of usage examples for org.apache.http.auth AuthScope AuthScope
public AuthScope(final String host, final int port, final String realm)
From source file:org.opennms.opennms.pris.plugins.defaults.source.HttpRequisitionMergeSource.java
private Requisition getRequisition(String url, String userName, String password) { Requisition requisition = null;/*from w w w.j a va2 s.com*/ if (url != null) { try { HttpClientBuilder builder = HttpClientBuilder.create(); // If username and password was found, inject the credentials if (userName != null && password != null) { CredentialsProvider provider = new BasicCredentialsProvider(); // Create the authentication scope AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM); // Create credential pair UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password); // Inject the credentials provider.setCredentials(scope, credentials); // Set the default credentials provider builder.setDefaultCredentialsProvider(provider); } HttpClient client = builder.build(); HttpGet request = new HttpGet(url); HttpResponse response = client.execute(request); try { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); JAXBContext jaxbContext = JAXBContext.newInstance(Requisition.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); requisition = (Requisition) jaxbUnmarshaller.unmarshal(bufferedReader); } catch (JAXBException e) { LOGGER.error("The response did not contain a valid requisition as xml.", e); } LOGGER.debug("Got Requisition {}", requisition); } catch (IOException ex) { LOGGER.error("Requesting requisition from {} failed", url, ex); return null; } } else { LOGGER.error("Parameter requisition.url is missing in requisition.properties"); return null; } return requisition; }
From source file:de.fuberlin.agcsw.heraclitus.svont.client.core.ChangeLog.java
public static void updateChangeLog(OntologyStore os, SVoNtProject sp, String user, String pwd) { //load the change log from server try {// w w w . j av a 2 s. c o m //1. fetch Changelog URI URI u = sp.getChangelogURI(); //2. search for change log owl files DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(u.getHost(), AuthScope.ANY_PORT, AuthScope.ANY_SCHEME), new UsernamePasswordCredentials(user, pwd)); HttpGet httpget = new HttpGet(u); System.out.println("executing request" + httpget.getRequestLine()); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String response = client.execute(httpget, responseHandler); System.out.println(response); List<String> files = ChangeLog.extractChangeLogFiles(response); ArrayList<ChangeLogElement> changelog = sp.getChangelog(); changelog.clear(); //4. sort the revisions for (int i = 0; i < files.size(); i++) { String fileName = files.get(i); System.out.println("rev sort: " + fileName); int rev = Integer.parseInt(fileName.split("\\.")[0]); changelog.add(new ChangeLogElement(URI.create(u + fileName), rev)); } Collections.sort(changelog, new SortChangeLogsElementsByRev()); //show sorted changelog System.out.print("["); for (ChangeLogElement cle : changelog) { System.out.print(cle.getRev() + ","); } System.out.println("]"); //5. map revision with SVN revisionInformations mapRevisionInformation(os, sp, changelog); //6. load change log files System.out.println("Load Changelog Files"); for (String s : files) { System.out.println(s); String req = u + s; httpget = new HttpGet(req); response = client.execute(httpget, responseHandler); // System.out.println(response); // save the changelog File persistent IFolder chlFold = sp.getChangeLogFolder(); IFile chlFile = chlFold.getFile(s); if (!chlFile.exists()) { chlFile.create(new ByteArrayInputStream(response.getBytes()), true, null); } os.getOntologyManager().loadOntology(new ReaderInputSource(new StringReader(response))); } System.out.println("Changelog Ontology successfully loaded"); //Show loaded onts Set<OWLOntology> onts = os.getOntologyManager().getOntologies(); for (OWLOntology o : onts) { System.out.println("loaded ont: " + o.getURI()); } //7 refresh possibly modified Mainontology os.getOntologyManager().reloadOntology(os.getMainOntologyLocalURI()); //8. recalculate Revision Information of the concept of this ontology sp.setRevisionMap(createConceptRevisionMap(os, sp)); sp.saveRevisionMap(); sp.saveRevisionInformationMap(); //9. show MetaInfos on ConceptTree ConceptTree.refreshConceptTree(os, os.getMainOntologyURI()); OntologyInformation.refreshOntologyInformation(os, os.getMainOntologyURI()); //shutdown http connection client.getConnectionManager().shutdown(); } catch (ClientProtocolException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (OWLOntologyCreationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (OWLReasonerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SVNException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SVNClientException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.teradata.tempto.internal.hadoop.hdfs.SpnegoHttpRequestsExecutor.java
private HttpContext createSpnegoAwareHttpContext() { HttpClientContext httpContext = HttpClientContext.create(); Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build(); httpContext.setAuthSchemeRegistry(authSchemeRegistry); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(null, -1, null), new NullCredentials()); httpContext.setCredentialsProvider(credentialsProvider); return httpContext; }
From source file:org.kaaproject.kaa.server.common.admin.HttpComponentsRequestFactoryBasicAuth.java
/** * Set credentials to field <code>credsProvider</code>. * * @param username the username, part of credentials * @param password the password, part of credentials *///w w w. j av a 2 s . co m public void setCredentials(String username, String password) { credsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort(), AuthScope.ANY_REALM), new UsernamePasswordCredentials(username, password)); }
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 w w w . j av a 2s. co 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.fcrepo.apix.registry.HttpClientFactory.java
/** * Construct a new HttpClient./*from w w w . ja v a2 s . c om*/ * * @return HttpClient impl. */ public CloseableHttpClient getClient() { final RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout) .setSocketTimeout(socketTimeout).build(); final CredentialsProvider provider = new BasicCredentialsProvider(); for (final AuthSpec authSpec : getAuthSpecs()) { LOG.debug("Using basic auth to {}://{}:{} with client", authSpec.scheme, authSpec.host, authSpec.port); final HttpHost host = new HttpHost(authSpec.host, authSpec.port, authSpec.scheme); provider.setCredentials(new AuthScope(host, AuthScope.ANY_REALM, authSpec.scheme), new UsernamePasswordCredentials(authSpec.username(), authSpec.passwd())); } return HttpClientBuilder.create().setDefaultRequestConfig(config) .addInterceptorLast(new HttpRequestInterceptor() { @Override public void process(final HttpRequest req, final HttpContext cxt) throws HttpException, IOException { if (!req.containsHeader(HttpHeaders.AUTHORIZATION)) { final String[] hostInfo = req.getFirstHeader(HttpHeaders.HOST).getValue().split(":"); final Credentials creds = provider.getCredentials(new AuthScope( new HttpHost(hostInfo[0], hostInfo.length > 1 ? Integer.valueOf(hostInfo[1]) : 80), AuthScope.ANY_REALM, "http")); if (creds != null) { req.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString( String.format("%s:%s", creds.getUserPrincipal().getName(), creds.getPassword()).getBytes())); LOG.debug("Added auth header"); } } } }).setDefaultCredentialsProvider(provider).build(); }
From source file:org.geomajas.layer.common.proxy.LayerHttpServiceImpl.java
public InputStream getStream(final String baseUrl, final LayerAuthentication authentication, final String layerId) throws IOException { // Create a HTTP client object, which will initiate the connection: final HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT); SystemDefaultHttpClient client = new SystemDefaultHttpClient(httpParams); String url = addCredentialsToUrl(baseUrl, authentication); // -- add basic authentication if (null != authentication && (LayerAuthenticationMethod.BASIC.equals(authentication.getAuthenticationMethod()) || LayerAuthenticationMethod.DIGEST.equals(authentication.getAuthenticationMethod()))) { // Set up the credentials: Credentials creds = new UsernamePasswordCredentials(authentication.getUser(), authentication.getPassword()); AuthScope scope = new AuthScope(parseDomain(url), parsePort(url), authentication.getRealm()); client.getCredentialsProvider().setCredentials(scope, creds); }/*from w ww.j a v a 2 s. co m*/ // -- add interceptors if any -- addInterceptors(client, baseUrl, layerId); // Create the GET method with the correct URL: HttpGet get = new HttpGet(url); // Execute the GET: HttpResponse response = client.execute(get); log.debug("Response: {} - {}", response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); return new LayerHttpServiceStream(response, client); }
From source file:org.activiti.webservice.WebServiceSendActivitiBehavior.java
public void execute(ActivityExecution execution) throws Exception { String endpointUrlValue = this.getStringFromField(this.endpointUrl, execution); String languageValue = this.getStringFromField(this.language, execution); String payloadExpressionValue = this.getStringFromField(this.payloadExpression, execution); String resultVariableValue = this.getStringFromField(this.resultVariable, execution); String usernameValue = this.getStringFromField(this.username, execution); String passwordValue = this.getStringFromField(this.password, execution); ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines(); Object payload = scriptingEngines.evaluate(payloadExpressionValue, languageValue, execution); if (endpointUrlValue.startsWith("vm:")) { LocalWebServiceClient client = this.getWebServiceContext().getClient(); WebServiceMessage message = new DefaultWebServiceMessage(payload, this.getWebServiceContext()); WebServiceMessage resultMessage = client.send(endpointUrlValue, message); Object result = resultMessage.getPayload(); if (resultVariableValue != null) { execution.setVariable(resultVariableValue, result); }/* w ww . j a va2s. com*/ } else { HttpClientBuilder clientBuilder = HttpClientBuilder.create(); if (usernameValue != null && passwordValue != null) { CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(usernameValue, passwordValue); provider.setCredentials(new AuthScope("localhost", -1, "webservice-realm"), credentials); clientBuilder.setDefaultCredentialsProvider(provider); } HttpClient client = clientBuilder.build(); HttpPost request = new HttpPost(endpointUrlValue); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(payload); oos.flush(); oos.close(); request.setEntity(new ByteArrayEntity(baos.toByteArray())); } catch (Exception e) { throw new ActivitiException("Error setting message payload", e); } byte[] responseBytes = null; try { // execute the POST request HttpResponse response = client.execute(request); responseBytes = IOUtils.toByteArray(response.getEntity().getContent()); } finally { // release any connection resources used by the method request.releaseConnection(); } if (responseBytes != null) { try { ByteArrayInputStream in = new ByteArrayInputStream(responseBytes); ObjectInputStream is = new ObjectInputStream(in); Object result = is.readObject(); if (resultVariableValue != null) { execution.setVariable(resultVariableValue, result); } } catch (Exception e) { throw new ActivitiException("Failed to read response value", e); } } } this.leave(execution); }