Example usage for java.net InetSocketAddress createUnresolved

List of usage examples for java.net InetSocketAddress createUnresolved

Introduction

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

Prototype

public static InetSocketAddress createUnresolved(String host, int port) 

Source Link

Document

Creates an unresolved socket address from a hostname and a port number.

Usage

From source file:com.varaneckas.hawkscope.Version.java

/**
 * Asynchroniously checks if a newer version of Hawkscope is available
 * /*from  w  w w  .  j  a  v a 2  s .  c om*/
 * @return
 */
public static void checkForUpdate() {
    if (!cfg.checkForUpdates()) {
        return;
    }
    try {
        log.debug("Checking for updates...");
        URLConnection conn = null;
        final URL versionCheckUrl = new URL(VERSION_CHECK_URL);
        Proxy proxy = null;
        if (cfg.isHttpProxyInUse()) {
            proxy = new Proxy(Type.HTTP,
                    InetSocketAddress.createUnresolved(cfg.getHttpProxyHost(), cfg.getHttpProxyPort()));
            conn = versionCheckUrl.openConnection(proxy);
        } else {
            conn = versionCheckUrl.openConnection();
        }
        conn.setConnectTimeout(Constants.CONNECTION_TIMOUT);
        conn.setReadTimeout(Constants.CONNECTION_TIMOUT);
        final InputStream io = conn.getInputStream();
        int c = 0;
        final StringBuilder version = new StringBuilder();
        while ((c = io.read()) != -1) {
            version.append((char) c);
        }
        if (log.isDebugEnabled()) {
            log.debug("Check complete. Latest " + OSUtils.CURRENT_OS + " version: " + version.toString());
        }
        if (VERSION_NUMBER.compareTo(version.toString()) < 0) {
            log.info("Newer " + OSUtils.CURRENT_OS + " version available (" + version.toString()
                    + "). You should update Hawkscope!");
            isUpdateAvailable = true;
            updateVersion = version.toString();
        } else {
            log.info("You have the latest available version of Hawkscope: " + VERSION_NUMBER);
            isUpdateAvailable = false;
        }
        PluginManager.getInstance().checkPluginUpdates(PLUGIN_VERSION_CHECK_URL, proxy);
    } catch (final Exception e) {
        log.info("Failed checking for update: " + e.getMessage());
    }
}

From source file:org.apache.pulsar.proxy.server.LookupProxyHandler.java

private void performLookup(long clientRequestId, String topic, String brokerServiceUrl, boolean authoritative,
        int numberOfRetries) {
    if (numberOfRetries == 0) {
        proxyConnection.ctx().writeAndFlush(Commands.newLookupErrorResponse(ServerError.ServiceNotReady,
                "Reached max number of redirections", clientRequestId));
        return;/*from  w w  w. j a  va  2  s  .c om*/
    }

    URI brokerURI;
    try {
        brokerURI = new URI(brokerServiceUrl);
    } catch (URISyntaxException e) {
        proxyConnection.ctx().writeAndFlush(
                Commands.newLookupErrorResponse(ServerError.MetadataError, e.getMessage(), clientRequestId));
        return;
    }

    InetSocketAddress addr = InetSocketAddress.createUnresolved(brokerURI.getHost(), brokerURI.getPort());
    if (log.isDebugEnabled()) {
        log.debug("Getting connections to '{}' for Looking up topic '{}' with clientReq Id '{}'", addr, topic,
                clientRequestId);
    }
    proxyConnection.getConnectionPool().getConnection(addr).thenAccept(clientCnx -> {
        // Connected to backend broker
        long requestId = proxyConnection.newRequestId();
        ByteBuf command;
        command = Commands.newLookup(topic, authoritative, requestId);
        clientCnx.newLookup(command, requestId).thenAccept(result -> {
            String brokerUrl = connectWithTLS ? result.brokerUrlTls : result.brokerUrl;
            if (result.redirect) {
                // Need to try the lookup again on a different broker
                performLookup(clientRequestId, topic, brokerUrl, result.authoritative, numberOfRetries - 1);
            } else {
                // Reply the same address for both TLS non-TLS. The reason
                // is that whether we use TLS
                // and broker is independent of whether the client itself
                // uses TLS, but we need to force the
                // client
                // to use the appropriate target broker (and port) when it
                // will connect back.
                proxyConnection.ctx().writeAndFlush(Commands.newLookupResponse(brokerUrl, brokerUrl, true,
                        LookupType.Connect, clientRequestId, true /* this is coming from proxy */));
            }
        }).exceptionally(ex -> {
            log.warn("[{}] Failed to lookup topic {}: {}", clientAddress, topic, ex.getMessage());
            proxyConnection.ctx().writeAndFlush(Commands.newLookupErrorResponse(ServerError.ServiceNotReady,
                    ex.getMessage(), clientRequestId));
            return null;
        });
    }).exceptionally(ex -> {
        // Failed to connect to backend broker
        proxyConnection.ctx().writeAndFlush(
                Commands.newLookupErrorResponse(ServerError.ServiceNotReady, ex.getMessage(), clientRequestId));
        return null;
    });
}

From source file:com.varaneckas.hawkscope.plugins.twitter.TwitterClient.java

/**
 * Gets an 24x24 image for User//from  w  w  w .j  av  a 2 s  .  c om
 * 
 * @param user
 * @return
 */
public Image getUserImage(final User user) {
    if (user == null) {
        return getTwitterIcon();
    }
    if (!userImages.containsKey(user.getName())) {
        final Configuration cfg = ConfigurationFactory.getConfigurationFactory().getConfiguration();
        Image i = null;
        try {
            if (!cfg.isHttpProxyInUse()) {
                i = new Image(Display.getCurrent(), user.getProfileImageURL().openStream());
            } else {
                Proxy p = new Proxy(Type.HTTP,
                        InetSocketAddress.createUnresolved(cfg.getHttpProxyHost(), cfg.getHttpProxyPort()));
                URLConnection con = user.getProfileImageURL().openConnection(p);
                con.setReadTimeout(3000);
                i = new Image(Display.getCurrent(), con.getInputStream());
            }
            i = new Image(Display.getCurrent(), i.getImageData().scaledTo(24, 24));
            userImages.put(user.getName(), i);
        } catch (final IOException e) {
            log.warn("Failed getting user icon: " + user.getName(), e);
            return getTwitterIcon();
        }
    }
    return userImages.get(user.getName());
}

From source file:io.tourniquet.junit.http.rules.HttpExchangeTest.java

@Test
public void testGetRequestURL() throws Exception {
    //prepare//from   www  . j  a v  a2 s  . com
    exchange.setRequestScheme("http");
    exchange.setDestinationAddress(InetSocketAddress.createUnresolved("somehost", 12345));
    exchange.setRequestURI("/requestUri");

    //act
    String uri = subject.getRequestURL();

    //assert
    assertEquals("http://somehost:12345/requestUri", uri);
}

From source file:com.buaa.cfs.utils.NetUtils.java

/**
 * Create a socket address with the given host and port.  The hostname might be replaced with another host that was
 * set via {@link #addStaticResolution(String, String)}.  The value of hadoop.security.token.service.use_ip will
 * determine whether the standard java host resolver is used, or if the fully qualified resolver is used.
 *
 * @param host the hostname or IP use to instantiate the object
 * @param port the port number/*from   w  ww .  ja  va  2s  . c om*/
 *
 * @return InetSocketAddress
 */
public static InetSocketAddress createSocketAddrForHost(String host, int port) {
    String staticHost = getStaticResolution(host);
    String resolveHost = (staticHost != null) ? staticHost : host;

    InetSocketAddress addr;
    try {
        InetAddress iaddr = SecurityUtil.getByName(resolveHost);
        // if there is a static entry for the host, make the returned
        // address look like the original given host
        if (staticHost != null) {
            iaddr = InetAddress.getByAddress(host, iaddr.getAddress());
        }
        addr = new InetSocketAddress(iaddr, port);
    } catch (UnknownHostException e) {
        addr = InetSocketAddress.createUnresolved(host, port);
    }
    return addr;
}

From source file:com.twitter.aurora.scheduler.app.SchedulerIT.java

@Before
public void mySetUp() throws Exception {
    control = createControl();//from w ww.  jav a 2s .c om
    addTearDown(new TearDown() {
        @Override
        public void tearDown() {
            if (mainException.get().isPresent()) {
                RuntimeException e = mainException.get().get();
                LOG.log(Level.SEVERE, "Scheduler main exited with an exception", e);
                fail(e.getMessage());
            }
            control.verify();
        }
    });
    backupDir = FileUtils.createTempDir();
    addTearDown(new TearDown() {
        @Override
        public void tearDown() throws Exception {
            org.apache.commons.io.FileUtils.deleteDirectory(backupDir);
        }
    });

    driver = control.createMock(SchedulerDriver.class);
    driverFactory = control.createMock(DriverFactory.class);
    log = control.createMock(Log.class);
    logStream = control.createMock(Stream.class);
    streamMatcher = LogOpMatcher.matcherFor(logStream);
    entrySerializer = new EntrySerializer(LogStorageModule.MAX_LOG_ENTRY_SIZE.get());

    zkClient = createZkClient();

    Module testModule = new AbstractModule() {
        @Override
        protected void configure() {
            bind(DriverFactory.class).toInstance(driverFactory);
            bind(Log.class).toInstance(log);
            bind(ThriftConfiguration.class).toInstance(new ThriftConfiguration() {
                @Override
                public Optional<? extends InputStream> getSslKeyStream() throws IOException {

                    return Optional.of(com.google.common.io.Resources
                            .getResource(getClass(), "AuroraTestKeyStore").openStream());
                }

                @Override
                public int getServingPort() {
                    return 0;
                }
            });
            bind(ExecutorConfig.class).toInstance(new ExecutorConfig("/executor/thermos"));
            install(new BackupModule(backupDir, SnapshotStoreImpl.class));
        }
    };

    ClientConfig zkClientConfig = ClientConfig
            .create(ImmutableList.of(InetSocketAddress.createUnresolved("localhost", getPort())))
            .withCredentials(ZooKeeperClient.digestCredentials("mesos", "mesos"));
    injector = Guice.createInjector(ImmutableList.<Module>builder()
            .addAll(SchedulerMain.getModules(CLUSTER_NAME, SERVERSET_PATH, zkClientConfig))
            .add(new LifecycleModule()).add(new AppLauncherModule())
            .add(new ZooKeeperClientModule(zkClientConfig)).add(testModule).build());
    lifecycle = injector.getInstance(Lifecycle.class);
}

From source file:com.twitter.common.zookeeper.testing.ZooKeeperTestServer.java

/**
 * Returns a new authenticated zookeeper client connected to the in-process zookeeper server with
 * a custom {@code sessionTimeout} and a custom {@code chrootPath}.
 *///from  w ww.  j ava  2 s  .  c  om
public final ZooKeeperClient createClient(Amount<Integer, Time> sessionTimeout, Credentials credentials,
        Optional<String> chrootPath) {
    final ZooKeeperClient client = new ZooKeeperClient(sessionTimeout, credentials, chrootPath,
            Arrays.asList(InetSocketAddress.createUnresolved("127.0.0.1", port)));
    shutdownRegistry.addAction(new ExceptionalCommand<InterruptedException>() {
        @Override
        public void execute() {
            client.close();
        }
    });
    return client;
}

From source file:org.apache.aurora.scheduler.app.SchedulerIT.java

private void startScheduler() throws Exception {
    // TODO(wfarner): Try to accomplish all this by subclassing SchedulerMain and actually using
    // AppLauncher.
    Module testModule = new AbstractModule() {
        @Override/*  w w  w .  j  a  v  a2 s  .  c  om*/
        protected void configure() {
            bind(DriverFactory.class).toInstance(driverFactory);
            bind(DriverSettings.class).toInstance(SETTINGS);
            bind(Log.class).toInstance(log);
            bind(ExecutorConfig.class).toInstance(new ExecutorConfig("/executor/thermos"));
            install(new BackupModule(backupDir, SnapshotStoreImpl.class));
        }
    };
    ClientConfig zkClientConfig = ClientConfig
            .create(ImmutableList.of(InetSocketAddress.createUnresolved("localhost", getPort())))
            .withCredentials(ZooKeeperClient.digestCredentials("mesos", "mesos"));
    final SchedulerMain main = SchedulerMain.class.newInstance();
    injector = Guice.createInjector(ImmutableList.<Module>builder()
            .addAll(main.getModules(CLUSTER_NAME, SERVERSET_PATH, zkClientConfig, STATS_URL_PREFIX))
            .add(new LifecycleModule()).add(new AppLauncherModule())
            .add(new ZooKeeperClientModule(zkClientConfig)).add(testModule).build());
    injector.injectMembers(main);
    lifecycle = injector.getInstance(Lifecycle.class);

    injector.getInstance(Key.get(ExceptionalCommand.class, StartupStage.class)).execute();

    // Mimic AppLauncher running main.
    executor.submit(new Runnable() {
        @Override
        public void run() {
            try {
                main.run();
            } catch (RuntimeException e) {
                mainException.set(Optional.of(e));
                executor.shutdownNow();
            }
        }
    });
    addTearDown(new TearDown() {
        @Override
        public void tearDown() throws Exception {
            lifecycle.shutdown();
            new ExecutorServiceShutdown(executor, Amount.of(10L, Time.SECONDS)).execute();
        }
    });
}

From source file:com.datatorrent.stram.StreamingContainerManagerTest.java

@Test
public void testGenerateDeployInfo() {
    TestGeneratorInputOperator o1 = dag.addOperator("o1", TestGeneratorInputOperator.class);
    GenericTestOperator o2 = dag.addOperator("o2", GenericTestOperator.class);
    GenericTestOperator o3 = dag.addOperator("o3", GenericTestOperator.class);
    GenericTestOperator o4 = dag.addOperator("o4", GenericTestOperator.class);

    dag.setOutputPortAttribute(o1.outport, PortContext.BUFFER_MEMORY_MB, 256);
    dag.addStream("o1.outport", o1.outport, o2.inport1);
    dag.setOutputPortAttribute(o1.outport, PortContext.SPIN_MILLIS, 99);

    dag.addStream("o2.outport1", o2.outport1, o3.inport1).setLocality(Locality.CONTAINER_LOCAL);
    dag.addStream("o3.outport1", o3.outport1, o4.inport1).setLocality(Locality.THREAD_LOCAL);

    dag.getAttributes().put(LogicalPlan.CONTAINERS_MAX_COUNT, 2);
    dag.setAttribute(OperatorContext.STORAGE_AGENT, new MemoryStorageAgent());
    Assert.assertEquals("number operators", 4, dag.getAllOperators().size());
    Assert.assertEquals("number root operators", 1, dag.getRootOperators().size());

    StreamingContainerManager dnm = new StreamingContainerManager(dag);
    Assert.assertEquals("number containers", 2, dnm.getPhysicalPlan().getContainers().size());

    dnm.assignContainer(new ContainerResource(0, "container1Id", "host1", 1024, 0, null),
            InetSocketAddress.createUnresolved("host1", 9001));
    dnm.assignContainer(new ContainerResource(0, "container2Id", "host2", 1024, 0, null),
            InetSocketAddress.createUnresolved("host2", 9002));

    StreamingContainerAgent sca1 = dnm/*from  w w  w  .  ja v a  2  s  .com*/
            .getContainerAgent(dnm.getPhysicalPlan().getContainers().get(0).getExternalId());
    StreamingContainerAgent sca2 = dnm
            .getContainerAgent(dnm.getPhysicalPlan().getContainers().get(1).getExternalId());

    Assert.assertEquals("", dnm.getPhysicalPlan().getContainers().get(0), sca1.container);
    Assert.assertEquals("", PTContainer.State.ALLOCATED, sca1.container.getState());
    List<OperatorDeployInfo> c1 = sca1.getDeployInfoList(sca1.container.getOperators());

    Assert.assertEquals("number operators assigned to c1", 1, c1.size());
    OperatorDeployInfo o1DI = getNodeDeployInfo(c1, dag.getMeta(o1));
    Assert.assertNotNull(o1 + " assigned to " + sca1.container.getExternalId(), o1DI);
    Assert.assertEquals("type " + o1DI, OperatorDeployInfo.OperatorType.INPUT, o1DI.type);
    Assert.assertEquals("inputs " + o1DI.name, 0, o1DI.inputs.size());
    Assert.assertEquals("outputs " + o1DI.name, 1, o1DI.outputs.size());
    Assert.assertNotNull("contextAttributes " + o1DI.name, o1DI.contextAttributes);

    OutputDeployInfo c1o1outport = o1DI.outputs.get(0);
    Assert.assertNotNull("stream connection for container1", c1o1outport);
    Assert.assertEquals("stream connection for container1", "o1.outport", c1o1outport.declaredStreamId);
    Assert.assertEquals("stream connects to upstream host", sca1.container.host, c1o1outport.bufferServerHost);
    Assert.assertEquals("stream connects to upstream port", sca1.container.bufferServerAddress.getPort(),
            c1o1outport.bufferServerPort);
    Assert.assertNotNull("contextAttributes " + c1o1outport, c1o1outport.contextAttributes);
    Assert.assertEquals("contextAttributes " + c1o1outport, Integer.valueOf(99),
            c1o1outport.contextAttributes.get(PortContext.SPIN_MILLIS));

    List<OperatorDeployInfo> c2 = sca2.getDeployInfoList(sca2.container.getOperators());
    Assert.assertEquals("number operators assigned to container", 3, c2.size());
    OperatorDeployInfo o2DI = getNodeDeployInfo(c2, dag.getMeta(o2));
    OperatorDeployInfo o3DI = getNodeDeployInfo(c2, dag.getMeta(o3));
    Assert.assertNotNull(dag.getMeta(o2) + " assigned to " + sca2.container.getExternalId(), o2DI);
    Assert.assertNotNull(dag.getMeta(o3) + " assigned to " + sca2.container.getExternalId(), o3DI);

    Assert.assertTrue("The buffer server memory for container 1",
            256 == sca1.getInitContext().getValue(ContainerContext.BUFFER_SERVER_MB));
    Assert.assertTrue("The buffer server memory for container 2",
            0 == sca2.getInitContext().getValue(ContainerContext.BUFFER_SERVER_MB));
    // buffer server input o2 from o1
    InputDeployInfo c2o2i1 = getInputDeployInfo(o2DI, "o1.outport");
    Assert.assertNotNull("stream connection for container2", c2o2i1);
    Assert.assertEquals("stream connects to upstream host", sca1.container.host, c2o2i1.bufferServerHost);
    Assert.assertEquals("stream connects to upstream port", sca1.container.bufferServerAddress.getPort(),
            c2o2i1.bufferServerPort);
    Assert.assertEquals("portName " + c2o2i1, dag.getMeta(o2).getMeta(o2.inport1).getPortName(),
            c2o2i1.portName);
    Assert.assertNull("partitionKeys " + c2o2i1, c2o2i1.partitionKeys);
    Assert.assertEquals("sourceNodeId " + c2o2i1, o1DI.id, c2o2i1.sourceNodeId);
    Assert.assertEquals("sourcePortName " + c2o2i1, TestGeneratorInputOperator.OUTPUT_PORT,
            c2o2i1.sourcePortName);
    Assert.assertNotNull("contextAttributes " + c2o2i1, c2o2i1.contextAttributes);

    // inline input o3 from o2
    InputDeployInfo c2o3i1 = getInputDeployInfo(o3DI, "o2.outport1");
    Assert.assertNotNull("input from o2.outport1", c2o3i1);
    Assert.assertEquals("portName " + c2o3i1, GenericTestOperator.IPORT1, c2o3i1.portName);
    Assert.assertNotNull("stream connection for container2", c2o3i1);
    Assert.assertNull("bufferServerHost " + c2o3i1, c2o3i1.bufferServerHost);
    Assert.assertEquals("bufferServerPort " + c2o3i1, 0, c2o3i1.bufferServerPort);
    Assert.assertNull("partitionKeys " + c2o3i1, c2o3i1.partitionKeys);
    Assert.assertEquals("sourceNodeId " + c2o3i1, o2DI.id, c2o3i1.sourceNodeId);
    Assert.assertEquals("sourcePortName " + c2o3i1, GenericTestOperator.OPORT1, c2o3i1.sourcePortName);
    Assert.assertEquals("locality " + c2o3i1, Locality.CONTAINER_LOCAL, c2o3i1.locality);

    // THREAD_LOCAL o4.inport1
    OperatorDeployInfo o4DI = getNodeDeployInfo(c2, dag.getMeta(o4));
    Assert.assertNotNull(dag.getMeta(o4) + " assigned to " + sca2.container.getExternalId(), o4DI);
    InputDeployInfo c2o4i1 = getInputDeployInfo(o4DI, "o3.outport1");
    Assert.assertNotNull("input from o3.outport1", c2o4i1);
    Assert.assertEquals("portName " + c2o4i1, GenericTestOperator.IPORT1, c2o4i1.portName);
    Assert.assertNotNull("stream connection for container2", c2o4i1);
    Assert.assertNull("bufferServerHost " + c2o4i1, c2o4i1.bufferServerHost);
    Assert.assertEquals("bufferServerPort " + c2o4i1, 0, c2o4i1.bufferServerPort);
    Assert.assertNull("partitionKeys " + c2o4i1, c2o4i1.partitionKeys);
    Assert.assertEquals("sourceNodeId " + c2o4i1, o3DI.id, c2o4i1.sourceNodeId);
    Assert.assertEquals("sourcePortName " + c2o4i1, GenericTestOperator.OPORT1, c2o4i1.sourcePortName);
    Assert.assertEquals("locality " + c2o4i1, Locality.THREAD_LOCAL, c2o4i1.locality);

}

From source file:org.apache.hadoop.yarn.server.nodemanager.TestLinuxContainerExecutorWithMocks.java

@Test(timeout = 5000)
public void testStartLocalizer() throws IOException {

    InetSocketAddress address = InetSocketAddress.createUnresolved("localhost", 8040);
    Path nmPrivateCTokensPath = new Path("file:///bin/nmPrivateCTokensPath");

    try {//from  w  ww .  ja va  2s.  c  o m
        mockExec.startLocalizer(
                new LocalizerStartContext.Builder().setNmPrivateContainerTokens(nmPrivateCTokensPath)
                        .setNmAddr(address).setUser("test").setAppId("application_0").setLocId("12345")
                        .setDirsHandler(dirsHandler).setUserFolder("testFolder").build());

        List<String> result = readMockParams();
        Assert.assertEquals(result.size(), 19);
        Assert.assertEquals(result.get(0), YarnConfiguration.DEFAULT_NM_NONSECURE_MODE_LOCAL_USER);
        Assert.assertEquals(result.get(1), "testFolder");
        Assert.assertEquals(result.get(2), "0");
        Assert.assertEquals(result.get(3), "application_0");
        Assert.assertEquals(result.get(4), "/bin/nmPrivateCTokensPath");
        Assert.assertEquals(result.get(8), "-classpath");
        Assert.assertEquals(result.get(11), "-Xmx256m");
        Assert.assertEquals(result.get(12),
                "org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.ContainerLocalizer");
        Assert.assertEquals(result.get(13), "test");
        Assert.assertEquals(result.get(14), "testFolder");
        Assert.assertEquals(result.get(15), "application_0");
        Assert.assertEquals(result.get(16), "12345");
        Assert.assertEquals(result.get(17), "localhost");
        Assert.assertEquals(result.get(18), "8040");

    } catch (InterruptedException e) {
        LOG.error("Error:" + e.getMessage(), e);
        Assert.fail();
    }
}