Example usage for org.apache.http.auth UsernamePasswordCredentials UsernamePasswordCredentials

List of usage examples for org.apache.http.auth UsernamePasswordCredentials UsernamePasswordCredentials

Introduction

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

Prototype

public UsernamePasswordCredentials(final String userName, final String password) 

Source Link

Document

The constructor with the username and password arguments.

Usage

From source file:be.dnsbelgium.rdap.client.RDAPCLI.java

public static void main(String[] args) {

    LOGGER.debug("Create the command line parser");
    CommandLineParser parser = new GnuParser();

    LOGGER.debug("Create the options");
    Options options = new RDAPOptions(Locale.ENGLISH);

    try {/*from  w  w  w. j a v  a2 s  .  c  o  m*/
        LOGGER.debug("Parse the command line arguments");
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help")) {
            printHelp(options);
            return;
        }

        if (line.getArgs().length == 0) {
            throw new IllegalArgumentException("You must provide a query");
        }
        String query = line.getArgs()[0];

        Type type = (line.getArgs().length == 2) ? Type.valueOf(line.getArgs()[1].toUpperCase())
                : guessQueryType(query);

        LOGGER.debug("Query: {}, Type: {}", query, type);

        try {
            SSLContextBuilder sslContextBuilder = SSLContexts.custom();
            if (line.hasOption(RDAPOptions.TRUSTSTORE)) {
                sslContextBuilder.loadTrustMaterial(
                        RDAPClient.getKeyStoreFromFile(new File(line.getOptionValue(RDAPOptions.TRUSTSTORE)),
                                line.getOptionValue(RDAPOptions.TRUSTSTORE_TYPE, RDAPOptions.DEFAULT_STORETYPE),
                                line.getOptionValue(RDAPOptions.TRUSTSTORE_PASS, RDAPOptions.DEFAULT_PASS)));
            }
            if (line.hasOption(RDAPOptions.KEYSTORE)) {
                sslContextBuilder.loadKeyMaterial(
                        RDAPClient.getKeyStoreFromFile(new File(line.getOptionValue(RDAPOptions.KEYSTORE)),
                                line.getOptionValue(RDAPOptions.KEYSTORE_TYPE, RDAPOptions.DEFAULT_STORETYPE),
                                line.getOptionValue(RDAPOptions.KEYSTORE_PASS, RDAPOptions.DEFAULT_PASS)),
                        line.getOptionValue(RDAPOptions.KEYSTORE_PASS, RDAPOptions.DEFAULT_PASS).toCharArray());
            }
            SSLContext sslContext = sslContextBuilder.build();

            final String url = line.getOptionValue(RDAPOptions.URL);
            final HttpHost host = Utils.httpHost(url);

            HashSet<Header> headers = new HashSet<Header>();
            headers.add(new BasicHeader("Accept-Language",
                    line.getOptionValue(RDAPOptions.LANG, Locale.getDefault().toString())));
            HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultHeaders(headers)
                    .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext,
                            (line.hasOption(RDAPOptions.INSECURE) ? new AllowAllHostnameVerifier()
                                    : new BrowserCompatHostnameVerifier())));

            if (line.hasOption(RDAPOptions.USERNAME) && line.hasOption(RDAPOptions.PASSWORD)) {
                BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()),
                        new UsernamePasswordCredentials(line.getOptionValue(RDAPOptions.USERNAME),
                                line.getOptionValue(RDAPOptions.PASSWORD)));
                httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }

            RDAPClient rdapClient = new RDAPClient(httpClientBuilder.build(), url);
            ObjectMapper mapper = new ObjectMapper();

            JsonNode json = null;
            switch (type) {
            case DOMAIN:
                json = rdapClient.getDomainAsJson(query);
                break;
            case ENTITY:
                json = rdapClient.getEntityAsJson(query);
                break;
            case AUTNUM:
                json = rdapClient.getAutNum(query);
                break;
            case IP:
                json = rdapClient.getIp(query);
                break;
            case NAMESERVER:
                json = rdapClient.getNameserver(query);
                break;
            }
            PrintWriter out = new PrintWriter(System.out, true);
            if (line.hasOption(RDAPOptions.RAW)) {
                mapper.writer().writeValue(out, json);
            } else if (line.hasOption(RDAPOptions.PRETTY)) {
                mapper.writer(new DefaultPrettyPrinter()).writeValue(out, json);
            } else if (line.hasOption(RDAPOptions.YAML)) {
                DumperOptions dumperOptions = new DumperOptions();
                dumperOptions.setPrettyFlow(true);
                dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
                dumperOptions.setSplitLines(true);
                Yaml yaml = new Yaml(dumperOptions);
                Map data = mapper.convertValue(json, Map.class);
                yaml.dump(data, out);
            } else {
                mapper.writer(new MinimalPrettyPrinter()).writeValue(out, json);
            }
            out.flush();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            System.exit(-1);
        }
    } catch (org.apache.commons.cli.ParseException e) {
        printHelp(options);
        System.exit(-1);
    }
}

From source file:org.datagator.api.client.backend.DataGatorService.java

public static void main(String[] args) throws Exception {
    UsernamePasswordCredentials auth = null;
    String credentials = environ.DATAGATOR_CREDENTIALS;
    if (credentials != null) {
        String[] tuple = credentials.split(".", 1);
        if (tuple.length > 1) {
            auth = new UsernamePasswordCredentials(tuple[0], tuple[1]);
        } else if (tuple.length > 0) {
            auth = new UsernamePasswordCredentials(tuple[0], null);
        }//from w w  w.j a  v a2  s. co m
    }

    final DataGatorService service;
    if (auth != null) {
        service = new DataGatorService(auth);
    } else {
        service = new DataGatorService();
    }

    CloseableHttpResponse response = service.get("/");
    response.getEntity().writeTo(System.out);
    response.close();

    // JsonParser parser = json.createParser(stream);
}

From source file:com.cloudhopper.httpclient.util.HttpPostMain.java

static public void main(String[] args) throws Exception {
    ////from ww  w . j  a  va  2 s .  com
    // target urls
    //
    String strURL = "http://209.226.31.233:9009/SendSmsService/b98183b99a1f473839ce569c78b84dbd";

    // Username: Twitter
    // Password: Twitter123

    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);

    //        for (int i = 0; i < 1; i++) {
    //
    // create a new ticket id
    //
    //String ticketId = TicketUtil.generate(1, System.currentTimeMillis());

    /**
    StringBuilder string0 = new StringBuilder(200)
        .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
        .append("<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n")
        .append("       <S:Header>\n")
        .append("               <ns3:TransactionID xmlns:ns4=\"http://vmp.vzw.com/schema\"\n")
        .append("xmlns:ns3=\"http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4\">" + ticketId + "</ns3:TransactionID>\n")
        .append("       </S:Header>\n")
        .append("       <S:Body>\n")
        .append("               <ns2:OptinReq xmlns:ns4=\"http://schemas.xmlsoap.org/soap/envelope/\"\n")
        .append("xmlns:ns3=\"http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4\"\n")
        .append("xmlns:ns2=\"http://vmp.vzw.com/schema\">\n")
        .append("                      <ns2:VASPID>twitter</ns2:VASPID>\n")
        .append("                      <ns2:VASID>tm33t!</ns2:VASID>\n")
        .append("                      <ns2:ShortCode>800080008001</ns2:ShortCode>\n")
        .append("                      <ns2:Number>9257089093</ns2:Number>\n")
        .append("                      <ns2:Source>provider</ns2:Source>\n")
        .append("                      <ns2:Message/>\n")
        .append("               </ns2:OptinReq>\n")
        .append("       </S:Body>\n")
        .append("</S:Envelope>");
     */

    // simple send sms
    StringBuilder string1 = new StringBuilder(200).append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
            .append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:loc=\"http://www.csapi.org/schema/parlayx/sms/send/v2_3/local\">\n")
            .append("   <soapenv:Header/>\n").append("   <soapenv:Body>\n").append("      <loc:sendSms>\n")
            .append("         <loc:addresses>tel:+16472260233</loc:addresses>\n")
            .append("         <loc:senderName>6388</loc:senderName>\n")
            .append("         <loc:message>Test Message &</loc:message>\n").append("      </loc:sendSms>\n")
            .append("   </soapenv:Body>\n").append("</soapenv:Envelope>\n");

    // startSmsNotification - place to deliver SMS to

    String req = string1.toString();
    logger.debug("Request XML -> \n" + req);

    HttpPost post = new HttpPost(strURL);

    StringEntity postEntity = new StringEntity(req, "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("209.226.31.233", AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("Twitter", "Twitter123"));

    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();

    //
    // was the request OK?
    //
    if (httpResponse.getStatusLine().getStatusCode() != 200) {
        logger.error("Request failed with StatusCode=" + httpResponse.getStatusLine().getStatusCode());
    }

    // get an input stream
    String responseBody = EntityUtils.toString(responseEntity);

    long stop = System.currentTimeMillis();

    logger.debug("----------------------------------------");
    logger.debug("Response took " + (stop - start) + " ms");
    logger.debug(responseBody);
    logger.debug("----------------------------------------");
    //        }

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

From source file:com.emc.cto.ridagent.rid.test.TestScript.java

public static void main(String args[]) throws SAXException, ParserConfigurationException, URISyntaxException,
        ClientProtocolException, IOException {
    String xmlData = "  <iodef-rid:RID lang=\"en\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:iodef-rid=\"urn:ietf:params:xml:ns:iodef-rid-2.0\" xmlns:iodef=\"urn:ietf:params:xml:ns:iodef-1.42\" xsi:schemaLocation=\"urn:ietf:params:xml:ns:iodef-rid-2.0 iodef-rid-2.0.xsd\">";
    xmlData = xmlData + "<iodef-rid:RIDPolicy MsgType=\"Report\" MsgDestination=\"RIDSystem\">";
    xmlData = xmlData + "<iodef-rid:PolicyRegion region=\"IntraConsortium\"/>";
    xmlData = xmlData + " <iodef:Node>";
    xmlData = xmlData + "   <iodef:NodeName>192.168.1.1</iodef:NodeName>";
    xmlData = xmlData + " </iodef:Node>";
    xmlData = xmlData + "<iodef-rid:TrafficType type=\"Network\"/>";
    xmlData = xmlData + "</iodef-rid:RIDPolicy>";
    xmlData = xmlData + "</iodef-rid:RID>";
    String id = TestScript.httpSend(xmlData, "https://ridtest.emc.com:4590/");
    HttpGet httpget = new HttpGet("http://localhost:1280/federation/RID/" + id + "/report.xml");

    DefaultHttpClient httpclient = new DefaultHttpClient();
    Credentials defaultcreds = new UsernamePasswordCredentials("Administrator", "secret");
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            defaultcreds);//from   w  ww . j a  v a2s.  c o  m
    httpget.setHeader("User-Agent", "EMC RID System");

    HttpResponse response = httpclient.execute(httpget);
    if (response.getEntity() != null) {

        int code = response.getStatusLine().getStatusCode();
        if (code == 404) {
            System.out.println("Error has occured! Document not found in the xDB");

        } else if (code == 200) {
            System.out.println("Document Successfully saved in the database");

        } else {
            System.out.println("Error could not be determined");
        }
    }
}

From source file:se.anyro.tagtider.utils.Http.java

public static DefaultHttpClient getClient() {
    if (client == null) {
        client = new DefaultHttpClient();
        Credentials creds = new UsernamePasswordCredentials("tagtider", "codemocracy");
        AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
        client.getCredentialsProvider().setCredentials(scope, creds);
    }//w w w  . j av a  2 s .  c  o m
    return client;
}

From source file:org.devtcg.five.util.AuthHelper.java

public static void setCredentials(FailfastHttpClient client, SourceItem source) {
    /*/*w  w w. j  a  v a2  s . c  o  m*/
     * The password we set here is actually a Base64-encoded SHA1 hash of
     * the plain text password. In a sense, we're using our own manual
     * digest authentication instead of the one supported by the HTTP
     * protocol.
     */
    client.getCredentialsProvider().setCredentials(new AuthScope(source.getHost(), source.getPort()),
            new UsernamePasswordCredentials("fiveuser", source.getPassword()));
}

From source file:com.jonbanjo.cups.operations.AuthHeader.java

static void makeAuthHeader(HttpRequest request, AuthInfo auth) {

    if (auth.reason == AuthInfo.AUTH_NOT_SUPPORTED) {
        return;/*www .  j a  v  a 2 s .c om*/
    }

    if (auth.username.equals("") || (auth.password.equals(""))) {
        auth.reason = AuthInfo.AUTH_REQUIRED;
        return;
    }

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(auth.username, auth.password);
    if (auth.getType().equals("Basic")) {
        BasicScheme basicScheme = new BasicScheme();
        try {
            auth.setAuthHeader(basicScheme.authenticate(creds, request));
        } catch (Exception e) {
            System.err.println(e.toString());
            auth.reason = AuthInfo.AUTH_BAD;
        }
    } else if (auth.getType().equals("Digest")) {
        try {
            DigestScheme digestScheme = new DigestScheme();
            digestScheme.processChallenge(auth.getHttpHeader());
            auth.setAuthHeader(digestScheme.authenticate(creds, request));
            String test0 = auth.getHttpHeader().getValue();
            String test1 = auth.getAuthHeader().getValue();
            System.out.println();
        } catch (Exception e) {
            System.err.println(e.toString());
            auth.reason = AuthInfo.AUTH_BAD;
        }
    } else {
        auth.reason = AuthInfo.AUTH_NOT_SUPPORTED;
    }
}

From source file:org.apache.hadoop.gateway.hive.HiveDispatchUtils.java

public static void addCredentialsToRequest(HttpUriRequest request) {
    String principal = SubjectUtils.getCurrentEffectivePrincipalName();
    if (principal != null) {
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(principal,
                PASSWORD_PLACEHOLDER);/*w  w  w .  j  a va2 s.com*/
        request.addHeader(BasicScheme.authenticate(credentials, "US-ASCII", false));
    }
}

From source file:com.machinepublishers.jbrowserdriver.ProxyAuth.java

static void add(final ProxyConfig proxy) {
    if (proxy != null && !proxy.directConnection() && proxy.credentials()) {
        synchronized (lock) {
            proxies.put(proxy.hostAndPort(), new UsernamePasswordCredentials(proxy.user(), proxy.password()));
        }//w  w w .j a  v  a  2s  .  c  om
    }
}

From source file:com.clonephpscrapper.utility.FetchPageWithProxy.java

public static String fetchPageSourcefromClientGoogle(URI newurl) throws IOException, InterruptedException {

    int portNo = generateRandomPort();
    CredentialsProvider credsprovider = new BasicCredentialsProvider();
    credsprovider.setCredentials(new AuthScope("195.154.161.103", portNo),
            new UsernamePasswordCredentials("mongoose", "Fjh30fi"));
    HttpHost proxy = new HttpHost("195.154.161.103", portNo);
    //-----------------------------------------------------------------------
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).build();

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsprovider)
            .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0")
            .setDefaultRequestConfig(requestConfig).setProxy(proxy).build();
    String responsebody = "";
    String responsestatus = null;
    int count = 0;
    try {//from  w  w  w . j  a v a  2s .c o  m
        HttpGet httpget = new HttpGet(newurl);
        httpget.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        httpget.addHeader("Accept-Encoding", "gzip, deflate");
        httpget.addHeader("Accept-Language", "en-US,en;q=0.5");
        httpget.addHeader("Connection", "keep-alive");

        System.out.println("Response status " + httpget.getRequestLine());
        CloseableHttpResponse resp = httpclient.execute(httpget);
        responsestatus = resp.getStatusLine().toString();
        if (responsestatus.contains("503") || responsestatus.contains("502") || responsestatus.contains("403")
                || responsestatus.contains("400") || responsestatus.contains("407")
                || responsestatus.contains("401") || responsestatus.contains("402")
                || responsestatus.contains("404") || responsestatus.contains("405")
                || responsestatus.contains("SSLHandshakeException") || responsestatus.contains("999")
                || responsestatus.contains("ClientProtocolException")
                || responsestatus.contains("SocketTimeoutException") || "".equals(responsestatus)) {
            Thread.sleep(10000);
            do {
                count++;
                responsebody = fetchPageSourcefromClientGoogleSecond(newurl);
                if (responsebody == null) {
                    Thread.sleep(10000);
                    System.out.println("PROX FAILURE");
                }
                if (count > 20) {
                    Thread.sleep(1000);
                    break;
                }
            } while (responsebody == null || "".equals(responsebody));
        } else {
            HttpEntity entity = resp.getEntity();
            System.out.println(resp.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    responsebody = new StringBuilder().append(responsebody).append(inputLine).toString();
                }
                // writeResponseFile(responsebody, pagename);
            }
            EntityUtils.consume(entity);
        }
    } catch (IOException | IllegalStateException e) {
        System.out.println("Exception = " + e);
        do {
            count++;
            responsebody = fetchPageSourcefromClientGoogleSecond(newurl);
            if (responsebody == null) {
                System.out.println("PROX FAILURE");
            }
            if (count > 15) {
                Thread.sleep(50000);
                //                    responsebody = fetchPageSourcefromClientGoogleSecond(newurl);
                break;
            }
        } while (responsebody == null || "".equals(responsebody));
    } finally {
        httpclient.close();
    }
    return responsebody;
}