Example usage for org.apache.http.conn.ssl AllowAllHostnameVerifier AllowAllHostnameVerifier

List of usage examples for org.apache.http.conn.ssl AllowAllHostnameVerifier AllowAllHostnameVerifier

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl AllowAllHostnameVerifier AllowAllHostnameVerifier.

Prototype

AllowAllHostnameVerifier

Source Link

Usage

From source file:com.google.oacurl.Login.java

public static void main(String[] args) throws Exception {
    LoginOptions options = new LoginOptions();
    try {//from w  w w .ja va2s  .c o  m
        options.parse(args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.exit(-1);
    }

    if (options.isHelp()) {
        new HelpFormatter().printHelp(" ", options.getOptions());
        System.exit(0);
    }

    if (options.isInsecure()) {
        SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
    }

    LoggingConfig.init(options.isVerbose());
    if (options.isWirelogVerbose()) {
        LoggingConfig.enableWireLog();
    }

    ServiceProviderDao serviceProviderDao = new ServiceProviderDao();
    ConsumerDao consumerDao = new ConsumerDao(options);
    AccessorDao accessorDao = new AccessorDao();

    String serviceProviderFileName = options.getServiceProviderFileName();
    if (serviceProviderFileName == null) {
        if (options.isBuzz()) {
            // Buzz has its own provider because it has a custom authorization URL
            serviceProviderFileName = "BUZZ";
        } else if (options.getVersion() == OAuthVersion.V2) {
            serviceProviderFileName = "GOOGLE_V2";
        } else {
            serviceProviderFileName = "GOOGLE";
        }
    }

    // We have a wee library of service provider properties files bundled into
    // the resources, so we set up the PropertiesProvider to search for them
    // if the file cannot be found.
    OAuthServiceProvider serviceProvider = serviceProviderDao.loadServiceProvider(
            new PropertiesProvider(serviceProviderFileName, ServiceProviderDao.class, "services/").get());
    OAuthConsumer consumer = consumerDao
            .loadConsumer(new PropertiesProvider(options.getConsumerFileName()).get(), serviceProvider);
    OAuthAccessor accessor = accessorDao.newAccessor(consumer);

    OAuthClient client = new OAuthClient(new HttpClient4());

    LoginCallbackServer callbackServer = null;

    boolean launchedBrowser = false;

    try {
        if (!options.isNoServer()) {
            callbackServer = new LoginCallbackServer(options);
            callbackServer.start();
        }

        String callbackUrl;
        if (options.getCallback() != null) {
            callbackUrl = options.getCallback();
        } else if (callbackServer != null) {
            callbackUrl = callbackServer.getCallbackUrl();
        } else {
            callbackUrl = null;
        }

        OAuthEngine engine;
        switch (options.getVersion()) {
        case V1:
            engine = new V1OAuthEngine();
            break;
        case V2:
            engine = new V2OAuthEngine();
            break;
        case WRAP:
            engine = new WrapOAuthEngine();
            break;
        default:
            throw new IllegalArgumentException("Unknown version: " + options.getVersion());
        }

        do {
            String authorizationUrl = engine.getAuthorizationUrl(client, accessor, options, callbackUrl);

            if (!options.isNoServer()) {
                callbackServer.setAuthorizationUrl(authorizationUrl);
            }

            if (!launchedBrowser) {
                String url = options.isDemo() ? callbackServer.getDemoUrl() : authorizationUrl;

                if (options.isNoBrowser()) {
                    System.out.println(url);
                    System.out.flush();
                } else {
                    launchBrowser(options, url);
                }

                launchedBrowser = true;
            }

            accessor.accessToken = null;

            logger.log(Level.INFO, "Waiting for verification token...");
            String verifier;
            if (options.isNoServer()) {
                System.out.print("Verification token: ");
                BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                verifier = "";
                while (verifier.isEmpty()) {
                    String line = reader.readLine();
                    if (line == null) {
                        System.exit(-1);
                    }
                    verifier = line.trim();
                }
            } else {
                verifier = callbackServer.waitForVerifier(accessor, -1);
                if (verifier == null) {
                    System.err.println("Wait for verifier interrupted");
                    System.exit(-1);
                }
            }
            logger.log(Level.INFO, "Verification token received: " + verifier);

            boolean success = engine.getAccessToken(accessor, client, callbackUrl, verifier);

            if (success) {
                if (callbackServer != null) {
                    callbackServer.setTokenStatus(TokenStatus.VALID);
                }

                Properties loginProperties = new Properties();
                accessorDao.saveAccessor(accessor, loginProperties);
                consumerDao.saveConsumer(consumer, loginProperties);
                loginProperties.put("oauthVersion", options.getVersion().toString());
                new PropertiesProvider(options.getLoginFileName()).overwrite(loginProperties);
            } else {
                if (callbackServer != null) {
                    callbackServer.setTokenStatus(TokenStatus.INVALID);
                }
            }
        } while (options.isDemo());
    } catch (OAuthProblemException e) {
        OAuthUtil.printOAuthProblemException(e);
    } finally {
        if (callbackServer != null) {
            callbackServer.stop();
        }
    }
}

From source file:org.bimserver.build.CreateGitHubRelease.java

public static void main(String[] args) {
    String username = args[0];/*from  ww w  .j  a va2s . c  o  m*/
    String password = args[1];
    String repo = args[2];
    String project = args[3];
    String tagname = args[4];
    String name = args[5];
    String body = args[6];
    String draft = args[7];
    String prerelease = args[8];
    String filesString = args[9];
    String[] filenames = filesString.split(";");

    GitHubClient gitHubClient = new GitHubClient("api.github.com");
    gitHubClient.setCredentials(username, password);

    Map<String, String> map = new HashMap<String, String>();
    map.put("tag_name", tagname);
    // map.put("target_commitish", "test");
    map.put("name", name);
    map.put("body", body);
    //      map.put("draft", draft);
    //      map.put("prerelease", prerelease);
    try {
        String string = "/repos/" + repo + "/" + project + "/releases";
        System.out.println(string);
        JsonObject gitHubResponse = gitHubClient.post(string, map, JsonObject.class);
        System.out.println(gitHubResponse);
        String id = gitHubResponse.get("id").getAsString();

        HttpHost httpHost = new HttpHost("uploads.github.com", 443, "https");

        BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
        basicCredentialsProvider.setCredentials(new AuthScope(httpHost),
                new UsernamePasswordCredentials(username, password));

        HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier();

        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        CloseableHttpClient client = HttpClients.custom()
                .setDefaultCredentialsProvider(basicCredentialsProvider)
                .setHostnameVerifier((X509HostnameVerifier) hostnameVerifier).setSSLSocketFactory(sslsf)
                .build();

        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(httpHost, basicAuth);

        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(basicCredentialsProvider);
        context.setAuthCache(authCache);

        for (String filename : filenames) {
            File file = new File(filename);
            String url = "https://uploads.github.com/repos/" + repo + "/" + project + "/releases/" + id
                    + "/assets?name=" + file.getName();
            HttpPost post = new HttpPost(url);
            post.setHeader("Accept", "application/vnd.github.manifold-preview");
            post.setHeader("Content-Type", "application/zip");
            post.setEntity(new InputStreamEntity(new FileInputStream(file), file.length()));
            HttpResponse execute = client.execute(httpHost, post, context);
            execute.getEntity().getContent().close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
}

From source file:com.google.oacurl.Fetch.java

public static void main(String[] args) throws Exception {
    FetchOptions options = new FetchOptions();
    CommandLine line = options.parse(args);
    args = line.getArgs();/*from w w w  .j  a v a2  s  .c o  m*/

    if (options.isHelp()) {
        new HelpFormatter().printHelp("url", options.getOptions());
        System.exit(0);
    }

    if (args.length != 1) {
        new HelpFormatter().printHelp("url", options.getOptions());
        System.exit(-1);
    }

    if (options.isInsecure()) {
        SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
    }

    LoggingConfig.init(options.isVerbose());
    if (options.isVerbose()) {
        LoggingConfig.enableWireLog();
    }

    String url = args[0];

    ServiceProviderDao serviceProviderDao = new ServiceProviderDao();
    ConsumerDao consumerDao = new ConsumerDao();
    AccessorDao accessorDao = new AccessorDao();

    Properties loginProperties = null;
    try {
        loginProperties = new PropertiesProvider(options.getLoginFileName()).get();
    } catch (FileNotFoundException e) {
        System.err.println(".oacurl.properties file not found in homedir");
        System.err.println("Make sure you've run oacurl-login first!");
        System.exit(-1);
    }

    OAuthServiceProvider serviceProvider = serviceProviderDao.nullServiceProvider();
    OAuthConsumer consumer = consumerDao.loadConsumer(loginProperties, serviceProvider);
    OAuthAccessor accessor = accessorDao.loadAccessor(loginProperties, consumer);

    OAuthClient client = new OAuthClient(new HttpClient4(SingleClient.HTTP_CLIENT_POOL));

    OAuthVersion version = (loginProperties.containsKey("oauthVersion"))
            ? OAuthVersion.valueOf(loginProperties.getProperty("oauthVersion"))
            : OAuthVersion.V1;

    OAuthEngine engine;
    switch (version) {
    case V1:
        engine = new V1OAuthEngine();
        break;
    case V2:
        engine = new V2OAuthEngine();
        break;
    case WRAP:
        engine = new WrapOAuthEngine();
        break;
    default:
        throw new IllegalArgumentException("Unknown version: " + version);
    }

    try {
        OAuthMessage request;

        List<Entry<String, String>> related = options.getRelated();

        Method method = options.getMethod();
        if (method == Method.POST || method == Method.PUT) {
            InputStream bodyStream;
            if (related != null) {
                bodyStream = new MultipartRelatedInputStream(related);
            } else if (options.getFile() != null) {
                bodyStream = new FileInputStream(options.getFile());
            } else {
                bodyStream = System.in;
            }
            request = newRequestMessage(accessor, method, url, bodyStream, engine);
            request.getHeaders().add(new OAuth.Parameter("Content-Type", options.getContentType()));
        } else {
            request = newRequestMessage(accessor, method, url, null, engine);
        }

        List<Parameter> headers = options.getHeaders();
        addHeadersToRequest(request, headers);

        HttpResponseMessage httpResponse;
        if (version == OAuthVersion.V1) {
            OAuthResponseMessage response;
            response = client.access(request, ParameterStyle.AUTHORIZATION_HEADER);
            httpResponse = response.getHttpResponse();
        } else {
            HttpMessage httpRequest = new HttpMessage(request.method, new URL(request.URL),
                    request.getBodyAsStream());
            httpRequest.headers.addAll(request.getHeaders());
            httpResponse = client.getHttpClient().execute(httpRequest, client.getHttpParameters());
            httpResponse = HttpMessageDecoder.decode(httpResponse);
        }

        System.err.flush();

        if (options.isInclude()) {
            Map<String, Object> dump = new HashMap<String, Object>();
            httpResponse.dump(dump);
            System.out.print(dump.get(HttpMessage.RESPONSE));
        }

        // Dump the bytes in the response's encoding.
        InputStream bodyStream = httpResponse.getBody();
        byte[] buf = new byte[1024];
        int count;
        while ((count = bodyStream.read(buf)) > -1) {
            System.out.write(buf, 0, count);
        }
    } catch (OAuthProblemException e) {
        OAuthUtil.printOAuthProblemException(e);
    }
}

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 {// ww w.j  a  va2 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:com.vmware.vim25.ws.ApacheTrustSelfSigned.java

public static SSLConnectionSocketFactory trust() {
    SSLContextBuilder builder = new SSLContextBuilder();
    log.trace("Set SSL Context Builder to trust self signed certs.");
    try {//from  w ww  .ja va2s .co  m
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        log.trace("Added Self Signed Strategy to builder.");
    } catch (NoSuchAlgorithmException e) {
        log.error("NoSuchAlgorithm caught trying to add SelfSignedStrategy.", e);
        return null;
    } catch (KeyStoreException e) {
        log.error("KeyStoreException caught trying to add TrustSelfSignedStrategy.", e);
        return null;
    }
    SSLConnectionSocketFactory sslConnectionSocketFactory;
    try {
        sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(),
                new AllowAllHostnameVerifier());
        log.trace("Added SSLConnectionSocketFactory to builder.");
    } catch (NoSuchAlgorithmException e) {
        log.error("Error trying to trust self signed certs.", e);
        return null;
    } catch (KeyManagementException e) {
        log.error("Error trying to trust self signed certs.", e);
        return null;
    }
    log.trace("Created self signed trust.");
    return sslConnectionSocketFactory;
}

From source file:models.Collection.java

public static RestResponse findByID(Long id, String token) throws IOException {
    RestResponse restResponse = new RestResponse();
    //TODO insecure ssl hack
    HttpClient httpClient = new DefaultHttpClient();
    SSLSocketFactory sf = (SSLSocketFactory) httpClient.getConnectionManager().getSchemeRegistry()
            .getScheme("https").getSocketFactory();
    sf.setHostnameVerifier(new AllowAllHostnameVerifier());

    HttpGet request = new HttpGet(Application.baseRestUrl + "/collections/" + id + "?expand=all");
    request.setHeader("Accept", "application/json");
    request.addHeader("Content-Type", "application/json");
    request.addHeader("rest-dspace-token", token);
    HttpResponse httpResponse = httpClient.execute(request);

    JsonNode collNode = Json.parse(httpResponse.getEntity().getContent());

    Collection collection = new Collection();

    if (collNode.size() > 0) {
        collection = Collection.parseCollectionFromJSON(collNode);
    }/*  www  .  j  a v  a2s.co  m*/

    restResponse.httpResponse = httpResponse;
    restResponse.endpoint = request.getURI().toString();

    ObjectMapper mapper = new ObjectMapper();
    String pretty = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(collection);
    restResponse.jsonString = pretty;

    restResponse.modelObject = collection;

    return restResponse;
}

From source file:com.toastcoders.vcumeter.ws.util.ApacheTrustSelfSignedSSL.java

/**
 * Method that intentionally break SSL by accepting any self signed SSL
 * certs. This is how the default VMware certs are signed.
 *
 * @return//w w w.  j  a  va  2  s .c o  m
 */
public static SSLConnectionSocketFactory trust() {
    SSLContextBuilder builder = new SSLContextBuilder();
    log.trace("Set SSL Context Builder to trust self signed certs.");
    try {
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        log.trace("Added Self Signed Strategy to builder.");
    } catch (NoSuchAlgorithmException e) {
        log.error("NoSuchAlgorithm caught trying to add SelfSignedStrategy.", e);
        return null;
    } catch (KeyStoreException e) {
        log.error("KeyStoreException caught trying to add TrustSelfSignedStrategy.", e);
        return null;
    }
    SSLConnectionSocketFactory sslConnectionSocketFactory;
    try {
        sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(),
                new AllowAllHostnameVerifier());
        log.trace("Added SSLConnectionSocketFactory to builder.");
    } catch (NoSuchAlgorithmException e) {
        log.error("Error trying to trust self signed certs.", e);
        return null;
    } catch (KeyManagementException e) {
        log.error("Error trying to trust self signed certs.", e);
        return null;
    }
    log.trace("Created self signed trust.");
    return sslConnectionSocketFactory;
}

From source file:org.apache.camel.component.http4.HttpsTwoDifferentSslContextParametersGetTest.java

@Override
protected JndiRegistry createRegistry() throws Exception {
    JndiRegistry registry = super.createRegistry();
    registry.bind("x509HostnameVerifier", new AllowAllHostnameVerifier());
    registry.bind("sslContextParameters", new SSLContextParameters());
    registry.bind("sslContextParameters2", new SSLContextParameters());

    return registry;
}

From source file:com.spokenpic.net.ssl.TrustAllSSLSocketFactory.java

public TrustAllSSLSocketFactory()
        throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    super(null);//  w w w. ja v a  2s.  com
    try {
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, new TrustManager[] { new TrustAllManager() }, null);
        factory = sslcontext.getSocketFactory();
        setHostnameVerifier(new AllowAllHostnameVerifier());
    } catch (Exception ex) {
    }
}

From source file:org.apache.camel.component.http4.HttpsTwoComponentsSslContextParametersGetTest.java

@Override
protected JndiRegistry createRegistry() throws Exception {
    JndiRegistry registry = super.createRegistry();
    registry.bind("x509HostnameVerifier", new AllowAllHostnameVerifier());
    registry.bind("sslContextParameters", new SSLContextParameters());
    registry.bind("sslContextParameters2", new SSLContextParameters());

    registry.bind("http4s-foo", new HttpComponent());
    registry.bind("http4s-bar", new HttpComponent());

    return registry;
}