Example usage for com.google.common.net HostAndPort fromParts

List of usage examples for com.google.common.net HostAndPort fromParts

Introduction

In this page you can find the example usage for com.google.common.net HostAndPort fromParts.

Prototype

public static HostAndPort fromParts(String host, int port) 

Source Link

Document

Build a HostAndPort instance from separate host and port values.

Usage

From source file:brooklyn.networking.portforwarding.PortForwarderIptables.java

@Override
public HostAndPort openPortForwarding(HostAndPort targetSide, Optional<Integer> optionalPublicPort,
        Protocol protocol, Cidr accessingCidr) {
    // TODO Could check old mapping, and re-use that public port
    PortForwardManager pfw = getPortForwardManager();

    int publicPort;
    if (optionalPublicPort.isPresent()) {
        publicPort = optionalPublicPort.get();
        pfw.acquirePublicPortExplicit(forwarderIp, publicPort);
    } else {//from   w  ww  . j  a v a  2 s. c o  m
        publicPort = pfw.acquirePublicPort(forwarderIp);
    }

    systemCreatePortForwarding(HostAndPort.fromParts(forwarderIp, publicPort), targetSide, accessingCidr);

    return HostAndPort.fromParts(forwarderIp, publicPort);
}

From source file:com.lambdaworks.redis.models.role.RoleParser.java

private static ReplicationPartner getMasterSlaveReplicationPartner(Collection<?> slaveOutput) {
    Iterator<?> iterator = slaveOutput.iterator();

    String ip = getStringFromIterator(iterator, "");
    long port = getLongFromIterator(iterator, 0);
    long replicationOffset = getLongFromIterator(iterator, 0);

    return new ReplicationPartner(HostAndPort.fromParts(ip, Math.toIntExact(port)), replicationOffset);
}

From source file:net.myrrix.common.PartitionsUtils.java

/**
 * Reads partition information from an XML status document from the cluster, which includes information
 * on partitions and their replicas./*from   w w w .j  a va 2s . c o  m*/
 * 
 * @param url URL holding cluster status as an XML document
 * @return a {@link List} of partitions, each of which is a {@link List} of replicas in a partition,
 *  each represented as a {@link HostAndPort}
 * @throws IOException if the URL can't be accessed or its XML content parsed
 */
public static List<List<HostAndPort>> parsePartitionsFromStatus(URL url) throws IOException {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IllegalStateException(e);
    }

    Document doc;
    Reader reader = new InputStreamReader(url.openStream(), Charsets.UTF_8);
    try {
        doc = builder.parse(new InputSource(reader));
    } catch (SAXException saxe) {
        throw new IllegalStateException(saxe);
    } finally {
        reader.close();
    }

    Element docElement = doc.getDocumentElement();
    docElement.normalize();

    List<List<HostAndPort>> result = Lists.newArrayList();

    NodeList partitionElements = docElement.getElementsByTagName("partition");
    for (int i = 0; i < partitionElements.getLength(); i++) {
        List<HostAndPort> partitionResult = Lists.newArrayList();
        result.add(partitionResult);
        Element partitionElement = (Element) partitionElements.item(i);
        NodeList replicaElements = partitionElement.getElementsByTagName("replica");
        for (int j = 0; j < replicaElements.getLength(); j++) {
            Node replicaElement = replicaElements.item(j);
            String[] hostPort = COLON.split(replicaElement.getTextContent());
            partitionResult.add(HostAndPort.fromParts(hostPort[0], Integer.parseInt(hostPort[1])));
        }
    }

    return result;
}

From source file:org.graylog2.system.stats.mongo.MongoProbe.java

public MongoStats mongoStats() {
    final List<ServerAddress> serverAddresses = mongoClient.getServerAddressList();
    final List<HostAndPort> servers = Lists.newArrayListWithCapacity(serverAddresses.size());
    for (ServerAddress serverAddress : serverAddresses) {
        servers.add(HostAndPort.fromParts(serverAddress.getHost(), serverAddress.getPort()));
    }/*from ww w  .ja  v  a2s .co m*/

    final DatabaseStats dbStats;
    final CommandResult dbStatsResult = db.command("dbStats");
    if (dbStatsResult.ok()) {
        final BasicDBObject extentFreeListMap = (BasicDBObject) dbStatsResult.get("extentFreeList");
        final DatabaseStats.ExtentFreeList extentFreeList;
        if (extentFreeListMap == null) {
            extentFreeList = null;
        } else {
            extentFreeList = DatabaseStats.ExtentFreeList.create(extentFreeListMap.getInt("num"),
                    extentFreeListMap.getInt("totalSize"));
        }

        final BasicDBObject dataFileVersionMap = (BasicDBObject) dbStatsResult.get("dataFileVersion");
        final DatabaseStats.DataFileVersion dataFileVersion;
        if (dataFileVersionMap == null) {
            dataFileVersion = null;
        } else {
            dataFileVersion = DatabaseStats.DataFileVersion.create(dataFileVersionMap.getInt("major"),
                    dataFileVersionMap.getInt("minor"));
        }

        dbStats = DatabaseStats.create(dbStatsResult.getString("db"), dbStatsResult.getLong("collections"),
                dbStatsResult.getLong("objects"), dbStatsResult.getDouble("avgObjSize"),
                dbStatsResult.getLong("dataSize"), dbStatsResult.getLong("storageSize"),
                dbStatsResult.getLong("numExtents"), dbStatsResult.getLong("indexes"),
                dbStatsResult.getLong("indexSize"),
                dbStatsResult.containsField("fileSize") ? dbStatsResult.getLong("fileSize") : null,
                dbStatsResult.containsField("nsSizeMB") ? dbStatsResult.getLong("nsSizeMB") : null,
                extentFreeList, dataFileVersion);
    } else {
        LOG.debug("Couldn't retrieve MongoDB dbStats: {}", dbStatsResult.getErrorMessage());
        dbStats = null;
    }

    final ServerStatus serverStatus;
    final CommandResult serverStatusResult = adminDb.command("serverStatus");
    if (serverStatusResult.ok()) {
        final BasicDBObject connectionsMap = (BasicDBObject) serverStatusResult.get("connections");
        final ServerStatus.Connections connections = ServerStatus.Connections.create(
                connectionsMap.getInt("current"), connectionsMap.getInt("available"),
                connectionsMap.containsField("totalCreated") ? connectionsMap.getLong("totalCreated") : null);

        final BasicDBObject networkMap = (BasicDBObject) serverStatusResult.get("network");
        final ServerStatus.Network network = ServerStatus.Network.create(networkMap.getInt("bytesIn"),
                networkMap.getInt("bytesOut"), networkMap.getInt("numRequests"));

        final BasicDBObject memoryMap = (BasicDBObject) serverStatusResult.get("mem");
        final ServerStatus.Memory memory = ServerStatus.Memory.create(memoryMap.getInt("bits"),
                memoryMap.getInt("resident"), memoryMap.getInt("virtual"), memoryMap.getBoolean("supported"),
                memoryMap.getInt("mapped"), memoryMap.getInt("mappedWithJournal"));

        final BasicDBObject storageEngineMap = (BasicDBObject) serverStatusResult.get("storageEngine");
        final ServerStatus.StorageEngine storageEngine;
        if (storageEngineMap == null) {
            storageEngine = ServerStatus.StorageEngine.DEFAULT;
        } else {
            storageEngine = ServerStatus.StorageEngine.create(storageEngineMap.getString("name"));
        }

        final int uptime = serverStatusResult.getInt("uptime", 0);
        serverStatus = ServerStatus.create(serverStatusResult.getString("host"),
                serverStatusResult.getString("version"), serverStatusResult.getString("process"),
                serverStatusResult.getLong("pid", 0), uptime,
                serverStatusResult.getLong("uptimeMillis", uptime * 1000L),
                serverStatusResult.getInt("uptimeEstimate"),
                new DateTime(serverStatusResult.getDate("localTime")), connections, network, memory,
                storageEngine);
    } else {
        LOG.debug("Couldn't retrieve MongoDB serverStatus: {}", serverStatusResult.getErrorMessage());
        serverStatus = null;
    }

    // TODO Collection stats? http://docs.mongodb.org/manual/reference/command/collStats/
    return MongoStats.create(servers, buildInfo, hostInfo, serverStatus, dbStats);
}

From source file:io.bazel.rules.closure.webfiles.server.WebfilesServer.java

/** Runs webfiles server in event loop. */
public void runForever() throws IOException, InterruptedException {
    WebfilesServerInfo params = config.get();
    HostAndPort bind = HostAndPort.fromString(params.getBind()).withDefaultPort(80);
    try (ServerSocket socket = network.createServerSocket(bind, !params.getFailIfPortInUse())) {
        if (params.getNoReloader()) {
            metadataLoader.loadMetadataIntoObjectGraph();
        } else {/*from  w  ww.jav  a  2s  .  c om*/
            metadataReloader.spawn();
        }
        HostAndPort address = HostAndPort.fromParts(bind.getHost(), socket.getLocalPort());
        synchronized (this) {
            checkState(actualAddress == null);
            actualAddress = address;
            notify();
        }
        logger.info(String.format("\n%sClosure Rules %s%s%s\n%sListening on: %shttp://%s/%s\n\n", BLUE, BOLD,
                WebfilesServer.class.getSimpleName(), RESET, BLUE, BOLD, NetworkUtils.createUrlAddress(address),
                RESET));
        while (true) {
            httpServer.handleOneConnection(socket);
        }
    }
}

From source file:org.kududb.client.MiniKuduCluster.java

/**
 * Start the specified number of master servers with ports starting from a specified
 * number. Finds free web and RPC ports up front for all of the masters first, then
 * starts them on those ports, populating 'masters' map.
 * @param masterStartPort the starting point of the port range for the masters
 * @param numMasters number of masters to start
 * @param baseDirPath the base directory where the mini cluster stores its data
 * @return the next free port/*www.j ava 2s .  co m*/
 * @throws Exception if we are unable to start the masters
 */
private int startMasters(int masterStartPort, int numMasters, String baseDirPath) throws Exception {
    LOG.info("Starting {} masters...", numMasters);
    // Get the list of web and RPC ports to use for the master consensus configuration:
    // request NUM_MASTERS * 2 free ports as we want to also reserve the web
    // ports for the consensus configuration.
    List<Integer> ports = TestUtils.findFreePorts(masterStartPort, numMasters * 2);
    int lastFreePort = ports.get(ports.size() - 1);
    List<Integer> masterRpcPorts = Lists.newArrayListWithCapacity(numMasters);
    List<Integer> masterWebPorts = Lists.newArrayListWithCapacity(numMasters);
    for (int i = 0; i < numMasters * 2; i++) {
        if (i % 2 == 0) {
            masterRpcPorts.add(ports.get(i));
            masterHostPorts.add(HostAndPort.fromParts("127.0.0.1", ports.get(i)));
        } else {
            masterWebPorts.add(ports.get(i));
        }
    }
    masterAddresses = NetUtil.hostsAndPortsToString(masterHostPorts);
    for (int i = 0; i < numMasters; i++) {
        long now = System.currentTimeMillis();
        String dataDirPath = baseDirPath + "/master-" + i + "-" + now;
        String flagsPath = TestUtils.getFlagsPath();
        // The web port must be reserved in the call to findFreePorts above and specified
        // to avoid the scenario where:
        // 1) findFreePorts finds RPC ports a, b, c for the 3 masters.
        // 2) start master 1 with RPC port and let it bind to any (specified as 0) web port.
        // 3) master 1 happens to bind to port b for the web port, as master 2 hasn't been
        // started yet and findFreePort(s) is "check-time-of-use" (it does not reserve the
        // ports, only checks that when it was last called, these ports could be used).
        List<String> masterCmdLine = Lists.newArrayList(TestUtils.findBinary("kudu-master"),
                "--flagfile=" + flagsPath, "--fs_wal_dir=" + dataDirPath, "--fs_data_dirs=" + dataDirPath,
                "--rpc_bind_addresses=127.0.0.1:" + masterRpcPorts.get(i),
                "--webserver_port=" + masterWebPorts.get(i));
        if (numMasters > 1) {
            masterCmdLine.add("--master_addresses=" + masterAddresses);
        }
        masterProcesses.put(masterRpcPorts.get(i),
                configureAndStartProcess(masterCmdLine.toArray(new String[masterCmdLine.size()])));

        if (flagsPath.startsWith(baseDirPath)) {
            // We made a temporary copy of the flags; delete them later.
            pathsToDelete.add(flagsPath);
        }
        pathsToDelete.add(dataDirPath);
    }
    return lastFreePort + 1;
}

From source file:brooklyn.networking.portforwarding.PortForwarderIptables.java

protected boolean systemCreatePortForwarding(HostAndPort publicSide, Location targetVm, int targetPort,
        Cidr cidr) {// w w w.  ja va  2s . c o  m
    String targetIp = ((MachineLocation) targetVm).getAddress().getHostAddress();
    if (targetIp == null) {
        log.warn("Skipping creation of port forward rule for " + targetVm + " port " + targetPort
                + " because location's IP cannot be resolved");
        // throw?
        return false;
    }

    return systemCreatePortForwarding(publicSide, HostAndPort.fromParts(targetIp, targetPort), cidr);
}

From source file:ezbake.security.service.EzSecurityLauncher.java

String getHostName() throws IOException {
    String hostName = InetAddress.getLocalHost().getCanonicalHostName();
    return HostAndPort.fromParts(hostName, this.port).toString();
}

From source file:org.jclouds.virtualbox.functions.admin.StartVBoxIfNotAlreadyRunning.java

public void cleanUpHost() {
    // kill previously started vboxwebsrv (possibly dirty session)
    URI provider = providerSupplier.get();
    NodeMetadata hostNodeMetadata = hardcodedHostToHostNodeMetadata.apply(host.get());
    List<Statement> statements = new ImmutableList.Builder<Statement>().add(findPid("vboxwebsrv")).add(kill())
            .build();/*  w  w w . ja va  2  s .  c  o  m*/
    StatementList statementList = new StatementList(statements);

    if (socketTester.apply(HostAndPort.fromParts(provider.getHost(), provider.getPort()))) {
        logger.debug(String.format("shutting down previously started vboxwewbsrv at %s", provider));
        ExecResponse execResponse = runScriptOnNodeFactory
                .create(hostNodeMetadata, statementList, runAsRoot(false)).init().call();
        if (execResponse.getExitStatus() != 0)
            throw new RuntimeException(String.format(
                    "Cannot shutdown a running vboxwebsrv at %s. ExecResponse: %s", provider, execResponse));
    }
}

From source file:ratpack.test.http.internal.DefaultTestHttpClient.java

private ReceivedResponse sendRequest(final String method, String path) {
    try {// ww w .  ja  va  2 s.c  o m
        URI uri = builder(path).params(params).build();

        response = client.request(uri, Duration.ofMinutes(60),
                Action.join(defaultRequestConfig, request, requestSpec -> {
                    requestSpec.method(method);

                    String encodedCookie = cookies.isEmpty() ? "" : ClientCookieEncoder.encode(cookies);

                    requestSpec.getHeaders().add(HttpHeaderConstants.COOKIE, encodedCookie);
                    requestSpec.getHeaders().add(HttpHeaderConstants.HOST,
                            HostAndPort.fromParts(uri.getHost(), uri.getPort()).toString());
                }));
    } catch (Throwable throwable) {
        throw uncheck(throwable);
    }

    List<String> cookieHeaders = response.getHeaders().getAll("Set-Cookie");
    for (String cookieHeader : cookieHeaders) {
        Set<Cookie> decodedCookies = ServerCookieDecoder.decode(cookieHeader);
        for (Cookie decodedCookie : decodedCookies) {
            if (cookies.contains(decodedCookie)) {
                cookies.remove(decodedCookie);
            }
            if (!decodedCookie.isDiscard()) {
                cookies.add(decodedCookie);
            }
        }
    }

    return response;
}