Example usage for org.apache.http.auth AuthScope ANY_PORT

List of usage examples for org.apache.http.auth AuthScope ANY_PORT

Introduction

In this page you can find the example usage for org.apache.http.auth AuthScope ANY_PORT.

Prototype

int ANY_PORT

To view the source code for org.apache.http.auth AuthScope ANY_PORT.

Click Source Link

Document

The -1 value represents any port.

Usage

From source file:org.opennms.opennms.pris.plugins.defaults.source.HttpRequisitionMergeSource.java

private Requisition getRequisition(String url, String userName, String password) {
    Requisition requisition = null;//  www .  ja va 2s.co m

    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:com.cloudhopper.httpclient.util.HttpSender.java

static public Response postXml(String url, String username, String password, String requestXml)
        throws Exception {
    ///*from w  ww.  ja  v  a2s. co  m*/
    // trust any SSL connection
    //
    TrustManager easyTrustManager = new X509TrustManager() {
        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme https = new Scheme("https", sf, 443);

    //SchemeRegistry sr = new SchemeRegistry();
    //sr.register(http);
    //sr.register(https);

    // create and initialize scheme registry
    //SchemeRegistry schemeRegistry = new SchemeRegistry();
    //schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    // create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    //ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
    //cm.setMaxTotalConnections(1);

    DefaultHttpClient client = new DefaultHttpClient();

    client.getConnectionManager().getSchemeRegistry().register(https);

    HttpPost post = new HttpPost(url);

    StringEntity postEntity = new StringEntity(requestXml, "ISO-8859-1");
    postEntity.setContentType("text/xml; charset=\"ISO-8859-1\"");
    post.addHeader("SOAPAction", "\"\"");
    post.setEntity(postEntity);

    long start = System.currentTimeMillis();

    client.getCredentialsProvider().setCredentials(new AuthScope(null, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));

    BasicHttpContext localcontext = new BasicHttpContext();

    // Generate BASIC scheme object and stick it to the local
    // execution context
    BasicScheme basicAuth = new BasicScheme();
    localcontext.setAttribute("preemptive-auth", basicAuth);

    // Add as the first request interceptor
    client.addRequestInterceptor(new PreemptiveAuth(), 0);

    HttpResponse httpResponse = client.execute(post, localcontext);
    HttpEntity responseEntity = httpResponse.getEntity();

    Response rsp = new Response();

    // set the status line and reason
    rsp.statusCode = httpResponse.getStatusLine().getStatusCode();
    rsp.statusLine = httpResponse.getStatusLine().getReasonPhrase();

    // get an input stream
    rsp.body = EntityUtils.toString(responseEntity);

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    client.getConnectionManager().shutdown();

    return rsp;
}

From source file:ca.sqlpower.enterprise.ServerInfoProvider.java

private static void init(URL url, String username, String password, CookieStore cookieStore)
        throws IOException {

    if (version.containsKey(generateServerKey(url, username, password)))
        return;/*w  w  w. ja v  a2s.c  o  m*/

    try {
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 2000);
        DefaultHttpClient httpClient = new DefaultHttpClient(params);
        httpClient.setCookieStore(cookieStore);
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        HttpUriRequest request = new HttpOptions(url.toURI());
        String responseBody = httpClient.execute(request, new BasicResponseHandler());

        // Decode the message
        String serverVersion;
        Boolean licensedServer;
        final String watermarkMessage;
        try {
            JSONObject jsonObject = new JSONObject(responseBody);
            serverVersion = jsonObject.getString(ServerProperties.SERVER_VERSION.toString());
            licensedServer = jsonObject.getBoolean(ServerProperties.SERVER_LICENSED.toString());
            watermarkMessage = jsonObject.getString(ServerProperties.SERVER_WATERMARK_MESSAGE.toString());
        } catch (JSONException e) {
            throw new IOException(e.getMessage());
        }

        // Save found values
        version.put(generateServerKey(url, username, password), new Version(serverVersion));
        licenses.put(generateServerKey(url, username, password), licensedServer);
        watermarkMessages.put(generateServerKey(url, username, password), watermarkMessage);

        // Notify the user if the server is not licensed.
        if (!licensedServer || (watermarkMessage != null && watermarkMessage.trim().length() > 0)) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    HyperlinkListener hyperlinkListener = new HyperlinkListener() {
                        @Override
                        public void hyperlinkUpdate(HyperlinkEvent e) {
                            try {
                                if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                                    if (e.getURL() != null) {
                                        BrowserUtil.launch(e.getURL().toString());
                                    }
                                }
                            } catch (IOException ex) {
                                throw new RuntimeException(ex);
                            }
                        }
                    };
                    HTMLUserPrompter htmlPrompter = new HTMLUserPrompter(UserPromptOptions.OK,
                            UserPromptResponse.OK, null, watermarkMessage, hyperlinkListener, "OK");
                    htmlPrompter.promptUser("");
                }
            });
        }

    } catch (URISyntaxException e) {
        throw new IOException(e.getLocalizedMessage());
    }
}

From source file:org.jfrog.build.client.PreemptiveHttpClient.java

private DefaultHttpClient createHttpClient(String userName, String password, int timeout) {
    BasicHttpParams params = new BasicHttpParams();
    int timeoutMilliSeconds = timeout * 1000;
    HttpConnectionParams.setConnectionTimeout(params, timeoutMilliSeconds);
    HttpConnectionParams.setSoTimeout(params, timeoutMilliSeconds);
    DefaultHttpClient client = new DefaultHttpClient(params);

    if (userName != null && !"".equals(userName)) {
        client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(userName, password));
        localContext = new BasicHttpContext();

        // Generate BASIC scheme object and stick it to the local execution context
        BasicScheme basicAuth = new BasicScheme();
        localContext.setAttribute("preemptive-auth", basicAuth);

        // Add as the first request interceptor
        client.addRequestInterceptor(new PreemptiveAuth(), 0);
    }//  w  w  w.  j  a  v  a  2 s.c o m
    boolean requestSentRetryEnabled = Boolean.parseBoolean(System.getProperty("requestSentRetryEnabled"));
    if (requestSentRetryEnabled) {
        client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, requestSentRetryEnabled));
    }
    // set the following user agent with each request
    String userAgent = "ArtifactoryBuildClient/" + CLIENT_VERSION;
    HttpProtocolParams.setUserAgent(client.getParams(), userAgent);
    return client;
}

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  a  v a  2  s  . co  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:osh.busdriver.mielegateway.MieleGatewayDispatcher.java

/**
 * CONSTRUCTOR//  ww w  . j a va  2s . c o m
 * @param logger
 * @param address
 * @throws MalformedURLException
 */
public MieleGatewayDispatcher(String gatewayHostAndPort, String username, String password,
        OSHGlobalLogger logger) {
    super();

    this.homebusUrl = "http://" + gatewayHostAndPort + "/homebus/?language=en";

    this.httpCredsProvider = new BasicCredentialsProvider();
    this.httpCredsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));
    this.httpcontext = new BasicHttpContext();
    this.httpcontext.setAttribute(ClientContext.CREDS_PROVIDER, httpCredsProvider);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

    ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);

    this.httpclient = new DefaultHttpClient(cm);
    this.httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); // Default to HTTP 1.1 (connection persistence)
    this.httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
    this.httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000);
    this.httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000);

    this.logger = logger;

    //this.parser = new MieleGatewayParser("http://" + device + "/homebus");
    this.deviceData = new HashMap<Integer, MieleDeviceHomeBusData>();

    new Thread(this, "MieleGatewayDispatcher for " + gatewayHostAndPort).start();
}

From source file:org.opensaml.security.httpclient.HttpClientSecurityParameters.java

/**
 * A convenience method to set a (single) username and password used for BASIC authentication.
 * To disable BASIC authentication pass null for the credentials instance.
 * /*from  ww w.j  a  v  a2  s .  co m*/
 * <p>
 * If the <code>authScope</code> is null, an {@link AuthScope} will be generated which specifies
 * any host, port, scheme and realm.
 * </p>
 * 
 * <p>To specify multiple usernames and passwords for multiple host, port, scheme, and realm combinations, instead 
 * provide an instance of {@link CredentialsProvider} via {@link #setCredentialsProvider(CredentialsProvider)}.</p>
 * 
 * @param credentials the username and password credentials
 * @param scope the HTTP client auth scope with which to scope the credentials, may be null
 */
public void setBasicCredentialsWithScope(@Nullable final UsernamePasswordCredentials credentials,
        @Nullable final AuthScope scope) {

    if (credentials != null) {
        AuthScope authScope = scope;
        if (authScope == null) {
            authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
        }
        BasicCredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(authScope, credentials);
        credentialsProvider = provider;
    } else {
        credentialsProvider = null;
    }

}

From source file:com.microsoft.teamfoundation.plugin.impl.TfsClient.java

private Client getClient(URI uri, TfsClientFactoryImpl.ServiceProvider provider, String username,
        TfsSecret password) {//from  w  ww .ja  v a2  s .  c om
    ClientConfig clientConfig = new ClientConfig();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    if (TfsClientFactoryImpl.ServiceProvider.TFS == provider) {
        /* NTLM auth for on premise installation */
        credentialsProvider.setCredentials(
                new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM, AuthSchemes.NTLM),
                new NTCredentials(username, password.getSecret(), uri.getHost(), ""));

        logger.info("Using NTLM authentication for on premise TeamFoundationServer");

    } else if (TfsClientFactoryImpl.ServiceProvider.VSO == provider) {
        // Basic Auth for VSO services
        credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password.getSecret()));

        logger.info("Using user/pass authentication for Visual Studio Online services");

        // Preemptive send basic auth header, or we will be redirected for oauth login
        clientConfig.property(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, true);
    }

    clientConfig.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED);

    if (System.getProperty(PROXY_URL_PROPERTY) != null) {
        clientConfig.property(ClientProperties.PROXY_URI, System.getProperty(PROXY_URL_PROPERTY));
        clientConfig.property(ApacheClientProperties.SSL_CONFIG, getSslConfigurator());
    }

    clientConfig.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider);
    clientConfig.connectorProvider(new ApacheConnectorProvider());

    return ClientBuilder.newClient(clientConfig);
}

From source file:org.openrepose.commons.utils.http.ServiceClient.java

private HttpClient getClientWithBasicAuth() throws ServiceClientException {
    HttpClientResponse clientResponse = null;

    try {/*from   w  ww .j a  v a2s.co m*/

        clientResponse = httpClientService.getClient(connectionPoolId);
        final HttpClient client = clientResponse.getHttpClient();

        if (!StringUtilities.isEmpty(targetHostUri) && !StringUtilities.isEmpty(username)
                && !StringUtilities.isEmpty(password)) {

            client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, AuthPolicy.BASIC);

            CredentialsProvider credsProvider = new BasicCredentialsProvider();

            credsProvider.setCredentials(new AuthScope(targetHostUri, AuthScope.ANY_PORT),
                    new UsernamePasswordCredentials(username, password));
            client.getParams().setParameter("http.authentication.credential-provider", credsProvider);

        }

        return client;

    } catch (HttpClientNotFoundException e) {
        LOG.error("Failed to obtain an HTTP default client connection");
        throw new ServiceClientException("Failed to obtain an HTTP default client connection", e);
    } finally {
        if (clientResponse != null) {
            httpClientService.releaseClient(clientResponse);
        }
    }

}