Example usage for java.net Proxy Proxy

List of usage examples for java.net Proxy Proxy

Introduction

In this page you can find the example usage for java.net Proxy Proxy.

Prototype

public Proxy(Type type, SocketAddress sa) 

Source Link

Document

Creates an entry representing a PROXY connection.

Usage

From source file:Main.java

public static void main(String args[]) throws Exception {
    URL u = new URL("http://www.yourserver.com:80/abc/demo.htm");
    System.out.println("The URL is " + u);
    System.out.println("The file part is " + u.getFile());
    u.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.1.1.10", 10)));

}

From source file:com.hortonworks.registries.storage.tool.sql.DatabaseUserInitializer.java

public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(Option.builder("c").numberOfArgs(1).longOpt(OPTION_CONFIG_FILE_PATH)
            .desc("Config file path").build());

    options.addOption(Option.builder("m").numberOfArgs(1).longOpt(OPTION_MYSQL_JAR_URL_PATH)
            .desc("Mysql client jar url to download").build());

    options.addOption(Option.builder().hasArg().longOpt(OPTION_ADMIN_JDBC_URL)
            .desc("JDBC url to connect DBMS via admin.").build());

    options.addOption(Option.builder().hasArg().longOpt(OPTION_ADMIN_DB_USER)
            .desc("Admin user name: should be able to create and grant privileges.").build());

    options.addOption(Option.builder().hasArg().longOpt(OPTION_ADMIN_PASSWORD)
            .desc("Admin user's password: should be able to create and grant privileges.").build());

    options.addOption(//from  w w w. j a  va 2  s  . c o m
            Option.builder().hasArg().longOpt(OPTION_TARGET_USER).desc("Name of target user.").build());

    options.addOption(
            Option.builder().hasArg().longOpt(OPTION_TARGET_PASSWORD).desc("Password of target user.").build());

    options.addOption(
            Option.builder().hasArg().longOpt(OPTION_TARGET_DATABASE).desc("Target database.").build());

    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = parser.parse(options, args);

    String[] neededOptions = { OPTION_CONFIG_FILE_PATH, OPTION_MYSQL_JAR_URL_PATH, OPTION_ADMIN_JDBC_URL,
            OPTION_ADMIN_DB_USER, OPTION_ADMIN_PASSWORD, OPTION_TARGET_USER, OPTION_TARGET_PASSWORD,
            OPTION_TARGET_DATABASE };

    boolean optNotFound = Arrays.stream(neededOptions).anyMatch(opt -> !commandLine.hasOption(opt));
    if (optNotFound) {
        usage(options);
        System.exit(1);
    }

    String confFilePath = commandLine.getOptionValue(OPTION_CONFIG_FILE_PATH);
    String mysqlJarUrl = commandLine.getOptionValue(OPTION_MYSQL_JAR_URL_PATH);

    Optional<AdminOptions> adminOptionsOptional = AdminOptions.from(commandLine);
    if (!adminOptionsOptional.isPresent()) {
        usage(options);
        System.exit(1);
    }

    AdminOptions adminOptions = adminOptionsOptional.get();

    Optional<TargetOptions> targetOptionsOptional = TargetOptions.from(commandLine);
    if (!targetOptionsOptional.isPresent()) {
        usage(options);
        System.exit(1);
    }

    TargetOptions targetOptions = targetOptionsOptional.get();

    DatabaseType databaseType = findDatabaseType(adminOptions.getJdbcUrl());

    Map<String, Object> conf;
    try {
        conf = Utils.readConfig(confFilePath);
    } catch (IOException e) {
        System.err.println("Error occurred while reading config file: " + confFilePath);
        System.exit(1);
        throw new IllegalStateException("Shouldn't reach here");
    }

    String bootstrapDirPath = null;
    try {
        bootstrapDirPath = System.getProperty("bootstrap.dir");
        Proxy proxy = Proxy.NO_PROXY;
        String httpProxyUrl = (String) conf.get(HTTP_PROXY_URL);
        String httpProxyUsername = (String) conf.get(HTTP_PROXY_USERNAME);
        String httpProxyPassword = (String) conf.get(HTTP_PROXY_PASSWORD);
        if ((httpProxyUrl != null) && !httpProxyUrl.isEmpty()) {
            URL url = new URL(httpProxyUrl);
            proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(url.getHost(), url.getPort()));
            if ((httpProxyUsername != null) && !httpProxyUsername.isEmpty()) {
                Authenticator.setDefault(getBasicAuthenticator(url.getHost(), url.getPort(), httpProxyUsername,
                        httpProxyPassword));
            }
        }

        StorageProviderConfiguration storageProperties = StorageProviderConfiguration.get(
                adminOptions.getJdbcUrl(), adminOptions.getUsername(), adminOptions.getPassword(),
                adminOptions.getDatabaseType());

        MySqlDriverHelper.downloadMySQLJarIfNeeded(storageProperties, bootstrapDirPath, mysqlJarUrl, proxy);
    } catch (Exception e) {
        System.err.println("Error occurred while downloading MySQL jar. bootstrap dir: " + bootstrapDirPath);
        System.exit(1);
        throw new IllegalStateException("Shouldn't reach here");
    }

    try (Connection conn = getConnectionViaAdmin(adminOptions)) {
        DatabaseCreator databaseCreator = DatabaseCreatorFactory.newInstance(adminOptions.getDatabaseType(),
                conn);
        UserCreator userCreator = UserCreatorFactory.newInstance(adminOptions.getDatabaseType(), conn);

        String database = targetOptions.getDatabase();
        String username = targetOptions.getUsername();

        createDatabase(databaseCreator, database);
        createUser(targetOptions, userCreator, username);
        grantPrivileges(databaseCreator, database, username);
    }
}

From source file:com.hortonworks.registries.storage.tool.sql.TablesInitializer.java

public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(Option.builder("s").numberOfArgs(1).longOpt(OPTION_SCRIPT_ROOT_PATH)
            .desc("Root directory of script path").build());

    options.addOption(Option.builder("c").numberOfArgs(1).longOpt(OPTION_CONFIG_FILE_PATH)
            .desc("Config file path").build());

    options.addOption(Option.builder("m").numberOfArgs(1).longOpt(OPTION_MYSQL_JAR_URL_PATH)
            .desc("Mysql client jar url to download").build());

    options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.CREATE.toString())
            .desc("Run sql migrations from scatch").build());

    options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.DROP.toString())
            .desc("Drop all the tables in the target database").build());

    options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.CHECK_CONNECTION.toString())
            .desc("Check the connection for configured data source").build());

    options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.MIGRATE.toString())
            .desc("Execute schema migration from last check point").build());

    options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.INFO.toString())
            .desc("Show the status of the schema migration compared to the target database").build());

    options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.VALIDATE.toString())
            .desc("Validate the target database changes with the migration scripts").build());

    options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.REPAIR.toString()).desc(
            "Repairs the DATABASE_CHANGE_LOG by removing failed migrations and correcting checksum of existing migration script")
            .build());/*from w w  w  . j  a va  2  s .  c  om*/

    options.addOption(Option.builder().hasArg(false).longOpt(DISABLE_VALIDATE_ON_MIGRATE)
            .desc("Disable flyway validation checks while running migrate").build());

    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = parser.parse(options, args);

    if (!commandLine.hasOption(OPTION_CONFIG_FILE_PATH) || !commandLine.hasOption(OPTION_SCRIPT_ROOT_PATH)) {
        usage(options);
        System.exit(1);
    }

    boolean isSchemaMigrationOptionSpecified = false;
    SchemaMigrationOption schemaMigrationOptionSpecified = null;
    for (SchemaMigrationOption schemaMigrationOption : SchemaMigrationOption.values()) {
        if (commandLine.hasOption(schemaMigrationOption.toString())) {
            if (isSchemaMigrationOptionSpecified) {
                System.out.println(
                        "Only one operation can be execute at once, please select one of 'create', ',migrate', 'validate', 'info', 'drop', 'repair', 'check-connection'.");
                System.exit(1);
            }
            isSchemaMigrationOptionSpecified = true;
            schemaMigrationOptionSpecified = schemaMigrationOption;
        }
    }

    if (!isSchemaMigrationOptionSpecified) {
        System.out.println(
                "One of the option 'create', ',migrate', 'validate', 'info', 'drop', 'repair', 'check-connection' must be specified to execute.");
        System.exit(1);
    }

    String confFilePath = commandLine.getOptionValue(OPTION_CONFIG_FILE_PATH);
    String scriptRootPath = commandLine.getOptionValue(OPTION_SCRIPT_ROOT_PATH);
    String mysqlJarUrl = commandLine.getOptionValue(OPTION_MYSQL_JAR_URL_PATH);

    StorageProviderConfiguration storageProperties;
    Map<String, Object> conf;
    try {
        conf = Utils.readConfig(confFilePath);

        StorageProviderConfigurationReader confReader = new StorageProviderConfigurationReader();
        storageProperties = confReader.readStorageConfig(conf);
    } catch (IOException e) {
        System.err.println("Error occurred while reading config file: " + confFilePath);
        System.exit(1);
        throw new IllegalStateException("Shouldn't reach here");
    }

    String bootstrapDirPath = null;
    try {
        bootstrapDirPath = System.getProperty("bootstrap.dir");
        Proxy proxy = Proxy.NO_PROXY;
        String httpProxyUrl = (String) conf.get(HTTP_PROXY_URL);
        String httpProxyUsername = (String) conf.get(HTTP_PROXY_USERNAME);
        String httpProxyPassword = (String) conf.get(HTTP_PROXY_PASSWORD);
        if ((httpProxyUrl != null) && !httpProxyUrl.isEmpty()) {
            URL url = new URL(httpProxyUrl);
            proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(url.getHost(), url.getPort()));
            if ((httpProxyUsername != null) && !httpProxyUsername.isEmpty()) {
                Authenticator.setDefault(getBasicAuthenticator(url.getHost(), url.getPort(), httpProxyUsername,
                        httpProxyPassword));
            }
        }
        MySqlDriverHelper.downloadMySQLJarIfNeeded(storageProperties, bootstrapDirPath, mysqlJarUrl, proxy);
    } catch (Exception e) {
        System.err.println("Error occurred while downloading MySQL jar. bootstrap dir: " + bootstrapDirPath);
        System.exit(1);
        throw new IllegalStateException("Shouldn't reach here");
    }

    boolean disableValidateOnMigrate = commandLine.hasOption(DISABLE_VALIDATE_ON_MIGRATE);
    if (disableValidateOnMigrate) {
        System.out.println("Disabling validation on schema migrate");
    }
    SchemaMigrationHelper schemaMigrationHelper = new SchemaMigrationHelper(
            SchemaFlywayFactory.get(storageProperties, scriptRootPath, !disableValidateOnMigrate));
    try {
        schemaMigrationHelper.execute(schemaMigrationOptionSpecified);
        System.out
                .println(String.format("\"%s\" option successful", schemaMigrationOptionSpecified.toString()));
    } catch (Exception e) {
        System.err.println(
                String.format("\"%s\" option failed : %s", schemaMigrationOptionSpecified.toString(), e));
        System.exit(1);
    }

}

From source file:Utils.java

private static void installProxySelector(final String hostName, final int portNum) {
    ProxySelector.setDefault(new ProxySelector() {
        public List select(URI uri) {
            List list = new ArrayList();
            list.add(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(hostName, portNum)));
            return list;
        }//from   ww  w.  j av  a  2 s. co  m

        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
        }
    });
}

From source file:com.orange.clara.pivotaltrackermirror.util.ProxyUtil.java

public static Proxy getProxy() throws Exception {
    if (PROXY_HOST == null) {
        return null;
    }//w  ww.j  a v a  2  s. c  o m
    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, PROXY_PORT));
    if (PROXY_USER == null) {
        return proxy;
    }
    loadAuthenticator();
    return proxy;
}

From source file:ProxyAuthenticator.java

private static void downloadFromUrl(String urlString) throws Exception {
    InputStream is = null;/*from www  . java2s.co  m*/
    FileOutputStream fos = null;

    URL url = new URL(urlString);

    System.out.println("Reading..." + url);

    Authenticator.setDefault(new ProxyAuthenticator("username", "password"));

    SocketAddress addr = new InetSocketAddress("your proxyserver ip address", 80);
    Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);

    is = conn.getInputStream();

    String filename = getOutputFileName(url);

    fos = new FileOutputStream(filename);

    byte[] readData = new byte[1024];

    int i = is.read(readData);

    while (i != -1) {
        fos.write(readData, 0, i);
        i = is.read(readData);
    }

    System.out.println("Created file: " + filename);
    System.out.println("Completed");
}

From source file:com.gargoylesoftware.htmlunit.httpclient.SocksConnectionSocketFactory.java

static Socket createSocketWithSocksProxy(final HttpHost socksProxy) {
    final InetSocketAddress address = new InetSocketAddress(socksProxy.getHostName(), socksProxy.getPort());
    final Proxy proxy = new Proxy(Proxy.Type.SOCKS, address);
    return new Socket(proxy);
}

From source file:com.serphacker.serposcope.scraper.http.extensions.ScrapClientPlainConnectionFactory.java

@Override
public Socket createSocket(final HttpContext context) throws IOException {
    InetSocketAddress socksaddr = (InetSocketAddress) context.getAttribute("proxy.socks");

    if (socksaddr != null) {
        return new Socket(new Proxy(Proxy.Type.SOCKS, socksaddr));
    } else {/*from   ww w.j  a  va  2s.c om*/
        return new Socket();
    }
}

From source file:disko.utils.DiscoProxySettings.java

/**
 * /*w  w w .  ja  va  2 s  .  c om*/
 * <p>
 * Convenience method to open a URL connection by using the
 * proxy settings. If proxyHost is null, the default is to  just
 * call <code>url.openConnection</code>.
 * </p>
 *
 * @param url
 * @return
 */
public static URLConnection newConnection(URL url) throws IOException {
    URLConnection connection;
    String externalForm = url.toExternalForm();
    url = new URL(externalForm.replace(" ", "%20"));
    if (DiscoProxySettings.proxyHost != null) {
        connection = url.openConnection(new Proxy(Proxy.Type.HTTP,
                new InetSocketAddress(DiscoProxySettings.proxyHost, DiscoProxySettings.proxyPort)));
        if (DiscoProxySettings.proxyUser != null) {
            String enc = new String(Base64.encodeBase64(
                    new String(DiscoProxySettings.proxyUser + ":" + DiscoProxySettings.proxyPassword)
                            .getBytes()));
            connection.setRequestProperty("Proxy-Authorization", "Basic " + enc);
        }
    } else
        connection = url.openConnection();
    return connection;
}

From source file:popo.defcon.MsgMeCDC.java

String readPage() {
    try {/*from   www . j  av a 2s . co  m*/
        URL site = new URL("http://cdc.iitkgp.ernet.in/notice/");
        Proxy p = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.3.100.207", 8080));
        HttpURLConnection notice_board = (HttpURLConnection) site.openConnection(p);
        // System.out.println("Proxy in Use: "+notice_board.usingProxy());
        BufferedReader in = new BufferedReader(new InputStreamReader(notice_board.getInputStream()));
        //System.out.println(in.toString());
        String temp;
        StringBuilder http = new StringBuilder();
        // int line = 1;
        while ((temp = in.readLine()) != null) {
            http.append('\n').append(temp);
            //System.out.println("reading line no" + line++);
        }
        //System.out.println(http);
        return (http.toString());
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}