Example usage for java.net Proxy NO_PROXY

List of usage examples for java.net Proxy NO_PROXY

Introduction

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

Prototype

Proxy NO_PROXY

To view the source code for java.net Proxy NO_PROXY.

Click Source Link

Document

A proxy setting that represents a DIRECT connection, basically telling the protocol handler not to use any proxying.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Proxy proxy = Proxy.NO_PROXY;
    Socket socket = new Socket(proxy);
}

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  v a2  s. c  om
            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.oracle.tutorial.jdbc.DatalinkSample.java

public static void main(String[] args) {

    JDBCTutorialUtilities myJDBCTutorialUtilities;
    Connection myConnection = null;
    Proxy myProxy;//from w  w w  .jav a 2  s  .c o m
    InetSocketAddress myProxyServer;

    if (args[0] == null) {
        System.err.println("Properties file not specified at command line");
        return;
    } else {
        try {
            myJDBCTutorialUtilities = new JDBCTutorialUtilities(args[0]);
        } catch (Exception e) {
            System.err.println("Problem reading properties file " + args[0]);
            e.printStackTrace();
            return;
        }
    }

    try {
        myConnection = myJDBCTutorialUtilities.getConnection();
        DatalinkSample myDatalinkSample = new DatalinkSample(myConnection, myJDBCTutorialUtilities);
        myDatalinkSample.addURLRow("Oracle", "http://www.oracle.com");

        // myProxyServer = new InetSocketAddress("www-proxy.example.com", 80);
        // myProxy = new Proxy(Proxy.Type.HTTP, myProxyServer);

        DatalinkSample.viewTable(myConnection, Proxy.NO_PROXY);
    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } catch (Exception ex) {
        System.out.println("Unexpected exception");
        ex.printStackTrace();
    } finally {
        JDBCTutorialUtilities.closeConnection(myConnection);
    }
}

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  ww  . j a v a 2  s  . c o m

    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:Main.java

/**
 * On some devices we have to hack:// w  w w.  j a v a  2 s  .c  o m
 * http://developers.sun.com/mobility/reference/techart/design_guidelines/http_redirection.html
 * @return the resolved url if any. Or null if it couldn't resolve the url
 * (within the specified time) or the same url if response code is OK
 */
public static String getResolvedUrl(String urlAsString, int timeout) {
    try {
        URL url = new URL(urlAsString);
        //using proxy may increase latency
        HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
        // force no follow

        hConn.setInstanceFollowRedirects(false);
        // the program doesn't care what the content actually is !!
        // http://java.sun.com/developer/JDCTechTips/2003/tt0422.html
        hConn.setRequestMethod("HEAD");
        // default is 0 => infinity waiting
        hConn.setConnectTimeout(timeout);
        hConn.setReadTimeout(timeout);
        hConn.connect();
        int responseCode = hConn.getResponseCode();
        hConn.getInputStream().close();
        if (responseCode == HttpURLConnection.HTTP_OK)
            return urlAsString;

        String loc = hConn.getHeaderField("Location");
        if (responseCode == HttpURLConnection.HTTP_MOVED_PERM && loc != null)
            return loc.replaceAll(" ", "+");

    } catch (Exception ex) {
    }
    return "";
}

From source file:Main.java

public static String[] getUrlInfos(String urlAsString, int timeout) {
    try {/*  w ww .j  a va2 s.c  om*/
        URL url = new URL(urlAsString);
        //using proxy may increase latency
        HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
        hConn.setRequestProperty("User-Agent", "Mozilla/5.0 Gecko/20100915 Firefox/3.6.10");

        // on android we got problems because of this
        // so disable that for now
        //            hConn.setRequestProperty("Accept-Encoding", "gzip, deflate");
        hConn.setConnectTimeout(timeout);
        hConn.setReadTimeout(timeout);
        // default length of bufferedinputstream is 8k
        byte[] arr = new byte[K4];
        InputStream is = hConn.getInputStream();

        if ("gzip".equals(hConn.getContentEncoding()))
            is = new GZIPInputStream(is);

        BufferedInputStream in = new BufferedInputStream(is, arr.length);
        in.read(arr);

        return getUrlInfosFromText(arr, hConn.getContentType());
    } catch (Exception ex) {
    }
    return new String[] { "", "" };
}

From source file:de.jetwick.util.Translate.java

public static String download(String urlAsString) {
    try {/* w  w  w .  jav  a 2s.  c om*/
        URL url = new URL(urlAsString);
        //using proxy may increase latency
        HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
        hConn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20100101 Firefox/7.0.1");
        hConn.addRequestProperty("Referer", "http://jetsli.de/crawler");

        hConn.setConnectTimeout(2000);
        hConn.setReadTimeout(2000);
        InputStream is = hConn.getInputStream();
        if ("gzip".equals(hConn.getContentEncoding()))
            is = new GZIPInputStream(is);

        return getInputStream(is);
    } catch (Exception ex) {
        return "";
    }
}

From source file:ch.cyberduck.core.socket.HttpProxyAwareSocket.java

public HttpProxyAwareSocket(final Proxy proxy) {
    super(proxy.type() == Proxy.Type.HTTP ? Proxy.NO_PROXY : proxy);
    this.proxy = proxy;
}

From source file:com.mebigfatguy.polycasso.URLFetcher.java

/**
 * retrieve arbitrary data found at a specific url
 * - either http or file urls/*from ww  w . j  av a2s.  co m*/
 * for http requests, sets the user-agent to mozilla to avoid
 * sites being cranky about a java sniffer
 * 
 * @param url the url to retrieve
 * @param proxyHost the host to use for the proxy
 * @param proxyPort the port to use for the proxy
 * @return a byte array of the content
 * 
 * @throws IOException the site fails to respond
 */
public static byte[] fetchURLData(String url, String proxyHost, int proxyPort) throws IOException {
    HttpURLConnection con = null;
    InputStream is = null;

    try {
        URL u = new URL(url);
        if (url.startsWith("file://")) {
            is = new BufferedInputStream(u.openStream());
        } else {
            Proxy proxy;
            if (proxyHost != null) {
                proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
            } else {
                proxy = Proxy.NO_PROXY;
            }
            con = (HttpURLConnection) u.openConnection(proxy);
            con.addRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6");
            con.addRequestProperty("Accept-Charset", "UTF-8");
            con.addRequestProperty("Accept-Language", "en-US,en");
            con.addRequestProperty("Accept", "text/html,image/*");
            con.setDoInput(true);
            con.setDoOutput(false);
            con.connect();

            is = new BufferedInputStream(con.getInputStream());
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(is, baos);
        return baos.toByteArray();
    } finally {
        IOUtils.closeQuietly(is);
        if (con != null) {
            con.disconnect();
        }
    }
}

From source file:com.clustercontrol.util.EndpointManager.java

public static void setProxy(String proxyHost, int proxyPort) {
    Proxy proxy = null;/*from w w  w  . j a va  2 s  .c o m*/
    if (proxyHost == null || proxyHost.length() == 0) {
        proxy = Proxy.NO_PROXY;
    } else {
        proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
    }
    getInstance().proxy = proxy;
}