Example usage for java.net InetSocketAddress InetSocketAddress

List of usage examples for java.net InetSocketAddress InetSocketAddress

Introduction

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

Prototype

private InetSocketAddress(int port, String hostname) 

Source Link

Usage

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  www.  j  ava 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:wh.contrib.RewardOptimizerHttpClient.java

public static void main(String[] args) throws Exception {
    HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 64 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.USER_AGENT,
                    "HttpComponents/1.1 (RewardOptimizer - karlthepagan@gmail.com)");

    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params);

    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());

    // We are going to use this object to synchronize between the 
    // I/O event and main threads
    RequestCount requestCount = new RequestCount(1);

    BufferingHttpClientHandler handler = new BufferingHttpClientHandler(httpproc,
            new MyHttpRequestExecutionHandler(requestCount), new DefaultConnectionReuseStrategy(), params);

    handler.setEventListener(new EventLogger());

    final IOEventDispatch ioEventDispatch = new DefaultClientIOEventDispatch(handler, params);

    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }//from w w w.  j a va  2s  . c  o  m
            System.out.println("Shutdown");
        }

    });
    t.start();

    List<SessionRequest> reqs = new ArrayList<SessionRequest>();
    //        reqs.add(ioReactor.connect(
    //                new InetSocketAddress("www.yahoo.com", 80), 
    //                null, 
    //                new HttpHost("www.yahoo.com"),
    //                null));
    //        reqs.add(ioReactor.connect(
    //                new InetSocketAddress("www.google.com", 80), 
    //                null,
    //                new HttpHost("www.google.ch"),
    //                null));
    //        reqs.add(ioReactor.connect(
    //                new InetSocketAddress("www.apache.org", 80), 
    //                null,
    //                new HttpHost("www.apache.org"),
    //                null));

    reqs.add(ioReactor.connect(new InetSocketAddress("www.wowhead.com", 80), null,
            new HttpHost("www.wowhead.com"), null));

    // Block until all connections signal
    // completion of the request execution
    synchronized (requestCount) {
        while (requestCount.getValue() > 0) {
            requestCount.wait();
        }
    }

    System.out.println("Shutting down I/O reactor");

    ioReactor.shutdown();

    System.out.println("Done");
}

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());/*  w w w.  j a  va 2 s  .  co 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:com.github.brandtg.switchboard.FileLogAggregator.java

/** Main. */
public static void main(String[] args) throws Exception {
    Options opts = new Options();
    opts.addOption("h", "help", false, "Prints help message");
    opts.addOption("f", "file", true, "File to output aggregated logs to");
    opts.addOption("s", "separator", true, "Line separator in log");
    CommandLine cli = new GnuParser().parse(opts, args);

    if (cli.getArgs().length == 0 || cli.hasOption("help")) {
        new HelpFormatter().printHelp("usage: [opts] sourceHost:port ...", opts);
        System.exit(1);/*w w  w.  ja  v  a 2s.c o m*/
    }

    // Parse sources
    Set<InetSocketAddress> sources = new HashSet<>();
    for (int i = 0; i < cli.getArgs().length; i++) {
        String[] tokens = cli.getArgs()[i].split(":");
        sources.add(new InetSocketAddress(tokens[0], Integer.valueOf(tokens[1])));
    }

    // Parse output stream
    OutputStream outputStream;
    if (cli.hasOption("file")) {
        outputStream = new FileOutputStream(cli.getOptionValue("file"));
    } else {
        outputStream = System.out;
    }

    // Separator
    String separator = cli.getOptionValue("separator", "\n");
    if (separator.length() != 1) {
        throw new IllegalArgumentException("Separator must only be 1 character");
    }

    final FileLogAggregator fileLogAggregator = new FileLogAggregator(sources, separator.charAt(0),
            outputStream);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                fileLogAggregator.stop();
            } catch (Exception e) {
                LOG.error("Error when stopping log aggregator", e);
            }
        }
    });

    fileLogAggregator.start();
}

From source file:com.algollabs.rgx.java

public static void main(String[] args) throws Exception {
    CommandLine cli;//from w w  w  .ja v  a2 s  .c o m

    // create the command line parser
    CommandLineParser parser = new GnuParser();

    // create the Options
    options.addOption("h", "help", false, "print this help message");
    options.addOption("d", "daemonize", false, "run rgx:Java as a daemon");
    options.addOption(OptionBuilder.withLongOpt("pattern")
            .withDescription("Java regular expression raw pattern").hasArg().withArgName("PATTERN").create());

    options.addOption(OptionBuilder.withLongOpt("subject")
            .withDescription("subject to test the pattern against").hasArg().withArgName("SUBJECT").create());

    options.addOption(
            OptionBuilder.withLongOpt("interface").withDescription("the interface to bind to when daemonized")
                    .hasArg().withArgName("INTERFACE").create());

    options.addOption(OptionBuilder.withLongOpt("port").withDescription("the port to bind to when daemonized")
            .hasArg().withArgName("PORT").create());

    try {
        // parse the command line arguments
        cli = parser.parse(options, args);
    } catch (ParseException exp) {
        System.out.println("Unexpected exception:" + exp.getMessage());
        return;
    }

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

    if (cli.hasOption("daemonize")) {
        String port = "9400";
        String host = "0.0.0.0";

        if (cli.hasOption("port")) {
            port = cli.getOptionValue("port");
        }
        if (cli.hasOption("interface")) {
            host = cli.getOptionValue("interface");
        }

        Container container = new rgx();
        Server server = new ContainerServer(container);
        Connection connection = new SocketConnection(server);
        SocketAddress address = new InetSocketAddress(host, Integer.parseInt(port));

        connection.connect(address);

        System.out.println("Accepting requests on " + host + ":" + port);
    } else {
        String ptrn = null;
        String subj = null;
        String flags = null;

        if (!cli.hasOption("pattern") || !cli.hasOption("subject")) {
            printHelp();
            return;
        }

        ptrn = cli.getOptionValue("pattern");
        subj = cli.getOptionValue("subject");

        if (cli.hasOption("flags"))
            flags = cli.getOptionValue("flags");

        System.out.println(new Construct(ptrn, subj, flags, false).test());
    }
}

From source file:Main.java

public static SocketChannel connect(int port) throws IOException {
    SocketAddress sa = new InetSocketAddress("127.0.0.1", port);
    return SocketChannel.open(sa);
}

From source file:Main.java

public static boolean isPortOpen(final String ip, final int port, final int timeout) {
    try {// www.  j a v a 2s  . co m
        Socket socket = new Socket();
        socket.connect(new InetSocketAddress(ip, port), timeout);
        socket.close();
        return true;
    }

    catch (ConnectException ce) {
        ce.printStackTrace();
        return false;
    }

    catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }
}

From source file:Main.java

public static boolean isPortOpen(final String ip, final int port, final int timeout) {
    try {/*  w  w w . ja v  a 2s.c o m*/
        Socket socket = new Socket();
        socket.connect(new InetSocketAddress(ip, port), timeout);
        socket.close();
        return true;
    }

    catch (ConnectException ce) {
        //ce.printStackTrace();
        return false;
    }

    catch (Exception ex) {
        //ex.printStackTrace();
        return false;
    }
}

From source file:edu.umass.cs.reconfiguration.reconfigurationpackets.CreateServiceName.java

public static void main(String[] args) {
    try {/* w ww  .ja v a2  s  .  c om*/
        Util.assertAssertionsEnabled();
        InetSocketAddress isa = new InetSocketAddress(InetAddress.getByName("localhost"), 2345);
        int numNames = 1000;
        String[] reconfigurators = { "RC43", "RC22", "RC78", "RC21", "RC143" };
        String namePrefix = "someName";
        String defaultState = "default_initial_state";
        String[] names = new String[numNames];
        String[] states = new String[numNames];
        for (int i = 0; i < numNames; i++) {
            names[i] = namePrefix + i;
            states[i] = defaultState + i;
        }
        CreateServiceName bcreate1 = new CreateServiceName(isa, "random0", 0, "hello");
        HashMap<String, String> nameStates = new HashMap<String, String>();
        for (int i = 0; i < names.length; i++)
            nameStates.put(names[i], states[i]);
        CreateServiceName bcreate2 = new CreateServiceName(isa, names[0], 0, states[0], nameStates);
        System.out.println(bcreate1.toString());
        System.out.println(bcreate2.toString());

        // translate a batch into consistent constituent batches
        Collection<Set<String>> batches = ConsistentReconfigurableNodeConfig.splitIntoRCGroups(
                new HashSet<String>(Arrays.asList(names)), new HashSet<String>(Arrays.asList(reconfigurators)));
        int totalSize = 0;
        int numBatches = 0;
        for (Set<String> batch : batches)
            System.out.println("batch#" + numBatches++ + " of size " + batch.size() + " (totalSize = "
                    + (totalSize += batch.size()) + ")" + " = " + batch);
        assert (totalSize == numNames);
        System.out.println(bcreate2.getSummary());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static Socket getSocket(Context context, String proxyHost, int proxyPort) throws IOException {
    Socket sock = new Socket();

    sock.connect(new InetSocketAddress(proxyHost, proxyPort), 10000);

    return sock;//from   ww  w  .j  av  a2s .  com
}