Example usage for com.google.common.net InetAddresses forString

List of usage examples for com.google.common.net InetAddresses forString

Introduction

In this page you can find the example usage for com.google.common.net InetAddresses forString.

Prototype

public static InetAddress forString(String ipString) 

Source Link

Document

Returns the InetAddress having the given string representation.

Usage

From source file:fr.letroll.ttorrentandroid.common.protocol.http.HTTPAnnounceRequestMessage.java

@Nonnull
public static HTTPAnnounceRequestMessage fromParams(@Nonnull Multimap<String, String> params)
        throws MessageValidationException {

    byte[] infoHash = toBytes(params, "info_hash", ErrorMessage.FailureReason.MISSING_HASH);
    byte[] peerId = toBytes(params, "peer_id", ErrorMessage.FailureReason.MISSING_PEER_ID);

    // Default 'uploaded' and 'downloaded' to 0 if the client does
    // not provide it (although it should, according to the spec).
    long uploaded = toLong(params, "uploaded", 0, null);
    long downloaded = toLong(params, "downloaded", 0, null);
    // Default 'left' to -1 to avoid peers entering the COMPLETED
    // state when they don't provide the 'left' parameter.
    long left = toLong(params, "left", -1, null);

    boolean compact = toBoolean(params, "compact");
    boolean noPeerId = toBoolean(params, "no_peer_id");

    int numWant = toInt(params, "numwant", AnnounceRequestMessage.DEFAULT_NUM_WANT, null);

    AnnounceEvent event = AnnounceEvent.NONE;
    if (params.containsKey("event"))
        event = AnnounceEvent.getByName(toString(params, "event", null));

    List<InetSocketAddress> addresses = new ArrayList<InetSocketAddress>();
    int port = toInt(params, "port", -1, ErrorMessage.FailureReason.MISSING_PORT);

    MAIN: {//from  www.  j av a2 s.  c  o  m
        String ip = toString(params, "ip", null);
        if (ip != null)
            addresses.add(new InetSocketAddress(InetAddresses.forString(ip), port));
    }

    IP4: {
        Collection<String> ips = params.get("ipv4");
        if (ips != null)
            for (String ip : ips)
                addresses.add(toInetSocketAddress(ip, port));
    }

    IP6: {
        Collection<String> ips = params.get("ipv6");
        if (ips != null)
            for (String ip : ips)
                addresses.add(toInetSocketAddress(ip, port));
    }

    DEFAULT: {
        if (addresses.isEmpty())
            addresses.add(new InetSocketAddress(port));
    }

    return new HTTPAnnounceRequestMessage(infoHash, peerId, addresses, uploaded, downloaded, left, compact,
            noPeerId, event, numWant);
}

From source file:org.rhq.enterprise.server.cloud.StorageNodeManagerBean.java

@Override
@TransactionAttribute(TransactionAttributeType.NEVER)
public void linkResource(Resource resource) {
    Configuration pluginConfig = configurationManager.getPluginConfiguration(resource.getId());
    String address = pluginConfig.getSimpleValue(RHQ_STORAGE_ADDRESS_PROPERTY);

    if (log.isInfoEnabled()) {
        log.info("Linking " + resource + " to storage node at " + address);
    }//  w ww .j a  va 2s  . c  o m
    try {
        StorageNode storageNode = storageNodeManager.findStorageNodeByAddress(address);
        if (storageNode == null) {
            if (InetAddresses.isInetAddress(address)) {
                String hostName = InetAddresses.forString(address).getHostName();
                log.info("Did not find storage node with address [" + address + "]. Searching by hostname ["
                        + hostName + "]");
                storageNode = storageNodeManager.findStorageNodeByAddress(hostName);
            } else {
                String ipAddress = InetAddress.getByName(address).getHostAddress();
                log.info("Did not find storage node with address [" + address + "] Searching by IP address ["
                        + ipAddress + "]");
                storageNode = storageNodeManager.findStorageNodeByAddress(ipAddress);
            }
        }

        if (storageNode != null) {
            if (log.isInfoEnabled()) {
                log.info(storageNode + " is an existing storage node. No cluster maintenance is necessary.");
            }
            storageNode.setAddress(address);
            storageNode.setResource(resource);
            storageNode.setOperationMode(OperationMode.NORMAL);
            storageNodeManager.linkExistingStorageNodeToResource(storageNode);

        } else {
            StorageClusterSettings clusterSettings = storageClusterSettingsManager
                    .getClusterSettings(subjectManager.getOverlord());
            storageNode = storageNodeManager.createStorageNode(resource, clusterSettings);

            if (log.isInfoEnabled()) {
                log.info("Scheduling cluster maintenance to deploy " + storageNode
                        + " into the storage cluster...");
            }
            if (clusterSettings.getAutomaticDeployment()) {
                log.info("Deploying " + storageNode);
                storageNodeManager.deployStorageNode(subjectManager.getOverlord(), storageNode);
            } else {
                log.info("Automatic deployment is disabled. " + storageNode + " will not become part of the "
                        + "cluster until it is deployed.");
            }
        }
    } catch (UnknownHostException e) {
        throw new RuntimeException("Could not resolve address [" + address + "]. The resource " + resource
                + " cannot be linked to a storage node", e);
    }
}

From source file:org.opendaylight.netvirt.sfc.classifier.providers.OpenFlow13Provider.java

public Flow createIngressClassifierAclFlow(NodeId nodeId, MatchBuilder match, Long port, String sffIpStr,
        long nsp, short nsi) {
    OpenFlow13Utils.addMatchInPort(match, nodeId, port);

    Long ipl = InetAddresses.coerceToInteger(InetAddresses.forString(sffIpStr)) & 0xffffffffL;
    List<Action> actionList = new ArrayList<>();
    actionList.add(OpenFlow13Utils.createActionNxPushNsh(actionList.size()));
    actionList.add(OpenFlow13Utils.createActionNxLoadNshMdtype(NSH_MDTYPE_ONE, actionList.size()));
    actionList.add(OpenFlow13Utils.createActionNxLoadNsp((int) nsp, actionList.size()));
    actionList.add(OpenFlow13Utils.createActionNxLoadNsi(nsi, actionList.size()));
    actionList.add(OpenFlow13Utils.createActionNxLoadNshc1(DEFAULT_NSH_CONTEXT_VALUE, actionList.size()));
    actionList.add(OpenFlow13Utils.createActionNxLoadNshc2(DEFAULT_NSH_CONTEXT_VALUE, actionList.size()));
    actionList.add(OpenFlow13Utils.createActionNxLoadReg0(ipl, actionList.size()));
    actionList.add(/* www  .  ja va 2 s.c o m*/
            OpenFlow13Utils.createActionResubmitTable(NwConstants.LPORT_DISPATCHER_TABLE, actionList.size()));

    InstructionsBuilder isb = OpenFlow13Utils.wrapActionsIntoApplyActionsInstruction(actionList);

    return OpenFlow13Utils.createFlowBuilder(NwConstants.INGRESS_SFC_CLASSIFIER_ACL_TABLE,
            INGRESS_CLASSIFIER_ACL_PRIORITY, INGRESS_CLASSIFIER_ACL_COOKIE, INGRESS_CLASSIFIER_ACL_FLOW_NAME,
            String.valueOf(flowIdInc.getAndIncrement()), match, isb).build();

}

From source file:io.prestosql.plugin.cassandra.CassandraTestingUtils.java

private static void insertTestData(CassandraSession session, SchemaTableName table, Date date, int rowsCount) {
    for (Integer rowNumber = 1; rowNumber <= rowsCount; rowNumber++) {
        Insert insert = QueryBuilder.insertInto(table.getSchemaName(), table.getTableName())
                .value("key", "key " + rowNumber.toString())
                .value("typeuuid", UUID.fromString(String.format("00000000-0000-0000-0000-%012d", rowNumber)))
                .value("typeinteger", rowNumber).value("typelong", rowNumber.longValue() + 1000)
                .value("typebytes", ByteBuffer.wrap(Ints.toByteArray(rowNumber)).asReadOnlyBuffer())
                .value("typetimestamp", date).value("typeansi", "ansi " + rowNumber)
                .value("typeboolean", rowNumber % 2 == 0)
                .value("typedecimal", new BigDecimal(Math.pow(2, rowNumber)))
                .value("typedouble", Math.pow(4, rowNumber)).value("typefloat", (float) Math.pow(8, rowNumber))
                .value("typeinet", InetAddresses.forString("127.0.0.1"))
                .value("typevarchar", "varchar " + rowNumber).value("typevarint", BigInteger.TEN.pow(rowNumber))
                .value("typetimeuuid",
                        UUID.fromString(String.format("d2177dd0-eaa2-11de-a572-001b779c76e%d", rowNumber)))
                .value("typelist", ImmutableList.of("list-value-1" + rowNumber, "list-value-2" + rowNumber))
                .value("typemap", ImmutableMap.of(rowNumber, rowNumber + 1L, rowNumber + 2, rowNumber + 3L))
                .value("typeset", ImmutableSet.of(false, true));

        session.execute(insert);//  w  w  w .  j  a  v a  2 s.co m
    }
    assertEquals(session.execute("SELECT COUNT(*) FROM " + table).all().get(0).getLong(0), rowsCount);
}

From source file:com.vmware.photon.controller.cloudstore.xenon.entity.SubnetAllocatorService.java

private void seedWithOneAvailableSubnet(String rootCidr) throws InterruptedException, TimeoutException,
        BadRequestException, DocumentNotFoundException, UnknownHostException {

    SubnetUtils subnetUtils = new SubnetUtils(rootCidr);
    SubnetUtils.SubnetInfo subnetInfo = subnetUtils.getInfo();
    Long lowIp, highIp;/* w w  w  .j  a v a 2  s.c o  m*/

    InetAddress lowIpAddress = InetAddresses.forString(subnetInfo.getLowAddress());
    if (lowIpAddress instanceof Inet4Address) {
        lowIp = IpHelper.ipToLong((Inet4Address) lowIpAddress);
    } else {
        throw new IllegalArgumentException("lowIpAddress not an IPv4 address");
    }

    InetAddress highIpAddress = InetAddresses.forString(subnetInfo.getHighAddress());
    if (highIpAddress instanceof Inet4Address) {
        highIp = IpHelper.ipToLong((Inet4Address) highIpAddress);
    } else {
        throw new IllegalArgumentException("highIpAddress not an IPv4 address");
    }

    DhcpSubnetService.State subnet = new DhcpSubnetService.State();
    subnet.lowIp = lowIp;
    subnet.highIp = highIp;

    Operation postOperation = Operation.createPost(this, DhcpSubnetService.FACTORY_LINK).setBody(subnet);
    ServiceUtils.doServiceOperation(this, postOperation);
}

From source file:com.eucalyptus.vm.dns.RecursiveDnsResolver.java

@Override
public DnsResponse lookupRecords(final DnsRequest request) {
    final Record query = request.getQuery();
    final Name name = query.getName();
    final int type = query.getType();
    final InetAddress source = request.getRemoteAddress();
    if (!enabled || !Subnets.isSystemManagedAddress(source))
        return DnsResponse.forName(query.getName()).recursive().refused();

    final Cache cache = new NonExpiringCache();
    Lookup aLookup = new Lookup(name, type);
    aLookup.setCache(cache);/*from   w  w  w.  j av  a 2  s  .  c o m*/
    Record[] found = aLookup.run();
    List<Record> queriedrrs = Arrays.asList(found != null ? found : new Record[] {});
    List<Name> cnames = (List<Name>) (aLookup.getAliases().length > 0 ? Arrays.asList(aLookup.getAliases())
            : Lists.newArrayList());
    final Set<Record> answer = Sets.newLinkedHashSet();
    final Set<Record> authority = Sets.newLinkedHashSet();
    final Set<Record> additional = Sets.newLinkedHashSet();

    boolean iamAuthority = false;
    for (Record aRec : queriedrrs) {
        List<Record> nsRecs = lookupNSRecords(aRec.getName(), cache);
        for (Record nsRec : nsRecs) {
            if (nsRec.getName().equals(DomainNames.externalSubdomain()))
                iamAuthority = true;
            authority.add(nsRec);
            Lookup nsLookup = new Lookup(((NSRecord) nsRec).getTarget(), type);
            nsLookup.setCache(cache);
            Record[] nsAnswers = nsLookup.run();
            if (nsAnswers != null) {
                additional.addAll(Arrays.asList(nsAnswers));
            }
        }
    }

    for (Name cnameRec : cnames) {
        SetResponse sr = cache.lookupRecords(cnameRec, Type.CNAME, Credibility.ANY);
        if (sr != null && sr.isSuccessful() && sr.answers() != null) {
            for (RRset result : sr.answers()) {
                Iterator rrs = result.rrs(false);
                if (rrs != null) {
                    for (Object record : ImmutableSet.copyOf(rrs)) {
                        answer.add((Record) record);
                    }
                }
            }
        }
    }

    for (Record record : ImmutableSet.copyOf(queriedrrs)) {
        if (iamAuthority && DomainNames.isExternalSubdomain(record.getName())) {
            final Name resolvedName = record.getName();
            try {
                final Name instanceDomain = InstanceDomainNames.lookupInstanceDomain(resolvedName);
                final InetAddress publicIp = InstanceDomainNames
                        .toInetAddress(resolvedName.relativize(instanceDomain));
                final VmInstance vm = VmInstances.lookupByPublicIp(publicIp.getHostAddress());
                final InetAddress instanceAddress = InetAddresses.forString(vm.getPrivateAddress());
                final Record privateARecord = DomainNameRecords.addressRecord(resolvedName, instanceAddress);
                answer.add(privateARecord);
            } catch (final Exception ex) {
                answer.add(record);
                continue;
            }
        } else {
            answer.add(record);
        }
    }

    if ((aLookup.getResult() == Lookup.SUCCESSFUL || aLookup.getResult() == Lookup.TYPE_NOT_FOUND)
            && queriedrrs.size() == 0) {
        List<Record> nsRecs = lookupNSRecords(name, cache);
        for (Record nsRec : nsRecs) {
            authority.add(nsRec);
        }
    }

    DnsResponse response = DnsResponse.forName(query.getName()).recursive()
            .withAuthority(Lists.newArrayList(authority)).withAdditional(Lists.newArrayList(additional))
            .answer(Lists.newArrayList(answer));

    if (aLookup.getResult() == Lookup.HOST_NOT_FOUND && queriedrrs.size() == 0) {
        response = DnsResponse.forName(query.getName()).recursive().withAuthority(Lists.newArrayList(authority))
                .nxdomain();
    }
    return response;
}

From source file:org.apache.cassandra.locator.YamlFileNetworkTopologySnitch.java

/**
 * Loads the topology configuration file.
 *
 * @throws ConfigurationException/*from   w w w  .  j a  v  a 2s.c om*/
 *             on failure
 */
private synchronized void loadTopologyConfiguration() throws ConfigurationException {
    logger.debug("Loading topology configuration from {}", topologyConfigFilename);

    final TypeDescription topologyConfigTypeDescription = new TypeDescription(TopologyConfig.class);
    topologyConfigTypeDescription.putListPropertyType("topology", Datacenter.class);

    final TypeDescription topologyTypeDescription = new TypeDescription(Datacenter.class);
    topologyTypeDescription.putListPropertyType("racks", Rack.class);

    final TypeDescription rackTypeDescription = new TypeDescription(Rack.class);
    rackTypeDescription.putListPropertyType("nodes", Node.class);

    final Constructor configConstructor = new Constructor(TopologyConfig.class);
    configConstructor.addTypeDescription(topologyConfigTypeDescription);
    configConstructor.addTypeDescription(topologyTypeDescription);
    configConstructor.addTypeDescription(rackTypeDescription);

    final InputStream configFileInputStream = getClass().getClassLoader()
            .getResourceAsStream(topologyConfigFilename);
    if (configFileInputStream == null) {
        throw new ConfigurationException("Could not read topology config file " + topologyConfigFilename);
    }
    Yaml yaml;
    TopologyConfig topologyConfig;
    try {
        yaml = new Yaml(configConstructor);
        topologyConfig = (TopologyConfig) yaml.load(configFileInputStream);
    } finally {
        FileUtils.closeQuietly(configFileInputStream);
    }
    final Map<InetAddress, NodeData> nodeDataMap = new HashMap<InetAddress, NodeData>();

    if (topologyConfig.topology == null) {
        throw new ConfigurationException("Topology configuration file is missing the topology section");
    }

    for (final Datacenter datacenter : topologyConfig.topology) {
        if (datacenter.dc_name == null) {
            throw new ConfigurationException(
                    "Topology configuration file is missing a data center name for some data center");
        }

        for (final Rack rack : datacenter.racks) {
            if (rack.rack_name == null) {
                throw new ConfigurationException(String.format(
                        "Topology configuration file is missing a rack name for some rack under data center '%s'",
                        datacenter.dc_name));
            }

            for (final Node node : rack.nodes) {
                if (node.broadcast_address == null) {
                    throw new ConfigurationException(String.format(
                            "Topology configuration file is missing a broadcast address for some node under data center '%s' rack '%s'",
                            datacenter.dc_name, rack.rack_name));
                }

                final InetAddress endpoint = InetAddresses.forString(node.broadcast_address);
                final InetAddress dcLocalAddress = node.dc_local_address == null ? null
                        : InetAddresses.forString(node.dc_local_address);

                final NodeData nodeData = new NodeData();
                nodeData.datacenter = datacenter.dc_name;
                nodeData.rack = rack.rack_name;
                nodeData.dcLocalAddress = dcLocalAddress;

                if (nodeDataMap.put(endpoint, nodeData) != null) {
                    throw new ConfigurationException(String.format(
                            "IP address '%s' appears more than once in the topology configuration file",
                            endpoint));
                }

                if (dcLocalAddress != null && nodeDataMap.put(dcLocalAddress, nodeData) != null) {
                    throw new ConfigurationException(String.format(
                            "IP address '%s' appears more than once in the topology configuration file",
                            dcLocalAddress));
                }
            }
        }
    }

    final NodeData localNodeData = nodeDataMap.get(FBUtilities.getBroadcastAddress());
    if (localNodeData == null) {
        throw new ConfigurationException("Topology configuration missing information for the local node");
    }

    final NodeData defaultNodeData = new NodeData();

    if (topologyConfig.default_dc_name == null) {
        throw new ConfigurationException("default_dc_name must be specified");
    }
    if (topologyConfig.default_rack_name == null) {
        throw new ConfigurationException("default_rack_name must be specified");
    }

    defaultNodeData.datacenter = topologyConfig.default_dc_name;
    defaultNodeData.rack = topologyConfig.default_rack_name;

    // YAML configuration looks good; now make the changes

    this.nodeDataMap = nodeDataMap;
    this.localNodeData = localNodeData;
    this.defaultNodeData = defaultNodeData;
    maybeSetApplicationState();

    if (logger.isDebugEnabled()) {
        logger.debug("Built topology map from config file: localNodeData={}, nodeDataMap={}", localNodeData,
                nodeDataMap);
    }

    if (gossiperInitialized) {
        StorageService.instance.gossipSnitchInfo();
    }
}

From source file:com.ethlo.geodata.GeodataServiceImpl.java

@Override
public GeoLocation findByIp(String ip) {
    if (!InetAddresses.isInetAddress(ip)) {
        return null;
    }/* w  w  w  .  j  av  a  2  s  . c o  m*/

    final InetAddress address = InetAddresses.forString(ip);
    final boolean isLocalAddress = address.isLoopbackAddress() || address.isAnyLocalAddress();
    if (isLocalAddress) {
        return null;
    }

    final long ipLong = UnsignedInteger.fromIntBits(InetAddresses.coerceToInteger(InetAddresses.forString(ip)))
            .longValue();

    final Long id = ipRanges.get(ipLong);
    return id != null ? findById(id) : null;
}

From source file:google.registry.rde.RdeFixtures.java

static HostResource makeHostResource(FakeClock clock, String fqhn, String ip) {
    clock.advanceOneMilli();//from  ww w . j av  a2 s.  co m
    return persistResourceWithCommitLog(new HostResource.Builder().setRepoId(generateNewContactHostRoid())
            .setCreationClientId("LawyerCat").setCreationTimeForTest(clock.nowUtc())
            .setCurrentSponsorClientId("BusinessCat").setFullyQualifiedHostName(Idn.toASCII(fqhn))
            .setInetAddresses(ImmutableSet.of(InetAddresses.forString(ip)))
            .setLastTransferTime(DateTime.parse("1910-01-01T00:00:00Z")).setLastEppUpdateClientId("CeilingCat")
            .setLastEppUpdateTime(clock.nowUtc())
            .setStatusValues(ImmutableSet.of(StatusValue.OK, StatusValue.PENDING_UPDATE)).build());
}

From source file:org.opendaylight.netvirt.ipv6service.IfMgr.java

public void addRouterIntf(Uuid portId, Uuid rtrId, Uuid snetId, Uuid networkId, IpAddress fixedIp,
        String macAddress, String deviceOwner) {
    LOG.debug("addRouterIntf portId {}, rtrId {}, snetId {}, networkId {}, ip {}, mac {}", portId, rtrId,
            snetId, networkId, fixedIp, macAddress);
    //Save the interface ipv6 address in its fully expanded format
    Ipv6Address addr = new Ipv6Address(
            InetAddresses.forString(fixedIp.getIpv6Address().getValue()).getHostAddress());
    fixedIp = new IpAddress(addr);

    VirtualPort intf = vintfs.get(portId);
    boolean newIntf = false;
    if (intf == null) {
        intf = new VirtualPort();
        if (intf != null) {
            vintfs.put(portId, intf);/*from  www .  jav  a2 s  .  c  o  m*/
        } else {
            LOG.error("Create rtr intf failed for :{}", portId);
            return;
        }
        intf.setIntfUUID(portId).setSubnetInfo(snetId, fixedIp).setNetworkID(networkId)
                .setMacAddress(macAddress).setRouterIntfFlag(true).setDeviceOwner(deviceOwner);
        intf.setPeriodicTimer();
        newIntf = true;
        MacAddress ifaceMac = MacAddress.getDefaultInstance(macAddress);
        Ipv6Address llAddr = ipv6Utils.getIpv6LinkLocalAddressFromMac(ifaceMac);
        /* A new router interface is created. This is basically triggered when an
        IPv6 subnet is associated to the router. Check if network is already hosting
        any VMs. If so, on all the hosts that have VMs on the network, program the
        icmpv6 punt flows in IPV6_TABLE(45).
         */
        programIcmpv6RSPuntFlows(intf, Ipv6Constants.ADD_FLOW);
        programIcmpv6NSPuntFlowForAddress(intf, llAddr, Ipv6Constants.ADD_FLOW);
    } else {
        intf.setSubnetInfo(snetId, fixedIp);
    }

    VirtualRouter rtr = vrouters.get(rtrId);
    VirtualSubnet snet = vsubnets.get(snetId);

    if (rtr != null && snet != null) {
        snet.setRouter(rtr);
        intf.setSubnet(snetId, snet);
        rtr.addSubnet(snet);
    } else if (snet != null) {
        intf.setSubnet(snetId, snet);
        addUnprocessed(unprocessedRouterIntfs, rtrId, intf);
    } else {
        addUnprocessed(unprocessedRouterIntfs, rtrId, intf);
        addUnprocessed(unprocessedSubnetIntfs, snetId, intf);
    }

    vrouterv6IntfMap.put(networkId, intf);
    programIcmpv6NSPuntFlowForAddress(intf, fixedIp.getIpv6Address(), Ipv6Constants.ADD_FLOW);

    if (newIntf) {
        LOG.debug("start the periodic RA Timer for routerIntf {}", portId);
        transmitUnsolicitedRA(intf);
    }
    return;
}