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:com.gemini.provision.network.openstack.NetworkProviderOpenStackImpl.java

@Override
public List<GeminiNetwork> getExternalGateways(GeminiTenant tenant, GeminiEnvironment env) {
    //authenticate the session with the OpenStack installation
    OSClient os = OSFactory.builder().endpoint(env.getEndPoint())
            .credentials(env.getAdminUserName(), env.getAdminPassword()).tenantName(tenant.getName())
            .authenticate();//from www  .j  a va  2s  .  co m
    if (os == null) {
        Logger.error("Failed to authenticate Tenant: {}",
                ToStringBuilder.reflectionToString(tenant, ToStringStyle.MULTI_LINE_STYLE));
        return null;
    }

    List<? extends Network> networks = os.networking().network().list();
    List<GeminiNetwork> gateways = new ArrayList();

    //map the list of network gateways and their subnets to gemini equivalents
    networks.stream().filter(osn -> osn.isRouterExternal()).forEach(osn -> {
        GeminiNetwork gn = null;
        try {
            gn = env.getOrphanNetworks().stream().filter(n -> n.getCloudID().equals(osn.getId())) //filter on the OpenStack network object cloud id
                    .findFirst().get();
        } catch (NoSuchElementException ex) {
            //not an error, just log the event. the network object will be created below
            Logger.debug("Gateway {} not mapped in Gemini models, creating one...", osn.getName());
        }

        if (gn == null) {
            //the network has not created in gemini data model - create and it's subnets, etc
            GeminiNetwork newGn = new GeminiNetwork();
            newGn.setName(osn.getName());
            newGn.setCloudID(osn.getId());
            if (osn.getNetworkType() != null) {
                newGn.setNetworkType(osn.getNetworkType().name());
            }
            //add the subnets to the new network. List all subnets and filter by the parent network id
            List<? extends Subnet> osSubnets = os.networking().subnet().list();
            osSubnets.stream().filter(osSubnet -> osSubnet != null)
                    .filter(osSubnet -> osSubnet.getNetworkId().equals(osn.getId())).forEach(osSubnet -> {
                        GeminiSubnet gs = new GeminiSubnet();
                        gs.setCloudID(osSubnet.getId());
                        gs.setParent(newGn);
                        gs.setCidr(osSubnet.getCidr());
                        osSubnet.getAllocationPools().stream().forEach(ap -> {
                            GeminiSubnetAllocationPool geminiAp = new GeminiSubnetAllocationPool(
                                    InetAddresses.forString(ap.getStart()),
                                    InetAddresses.forString(ap.getEnd()));
                            geminiAp.setParent(gs);
                            gs.addAllocationPool(geminiAp);
                        });
                        gs.setParent(newGn);
                        newGn.addSubnet(gs);
                    });
            gn = newGn;
            env.addGateway(newGn);
        }
        //TODO: When gn != null, do we need to check if subnet objects are correctly captured
        //      in the Gemini data model
        gateways.add(gn);
    });
    return gateways;
}

From source file:org.dcache.xrootd.core.XrootdRequestHandler.java

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof XrootdRequest) {
        requestReceived(ctx, (XrootdRequest) msg);
    } else if (msg instanceof HAProxyMessage) {
        HAProxyMessage proxyMessage = (HAProxyMessage) msg;
        switch (proxyMessage.command()) {
        case LOCAL:
            _isHealthCheck = true;//from  w  w  w.  j a v  a2  s . c om
            break;
        case PROXY:
            String sourceAddress = proxyMessage.sourceAddress();
            String destinationAddress = proxyMessage.destinationAddress();
            InetSocketAddress localAddress = (InetSocketAddress) ctx.channel().localAddress();
            if (proxyMessage.proxiedProtocol() == HAProxyProxiedProtocol.TCP4
                    || proxyMessage.proxiedProtocol() == HAProxyProxiedProtocol.TCP6) {
                if (Objects.equals(destinationAddress, localAddress.getAddress().getHostAddress())) {
                    /* Workaround for what looks like a bug in HAProxy - health checks should
                     * generate a LOCAL command, but it appears they do actually use PROXY.
                     */
                    _isHealthCheck = true;
                } else {
                    _destinationAddress = new InetSocketAddress(InetAddresses.forString(destinationAddress),
                            proxyMessage.destinationPort());
                    _sourceAddress = new InetSocketAddress(InetAddresses.forString(sourceAddress),
                            proxyMessage.sourcePort());
                }
            }
            break;
        }
        ctx.fireChannelRead(msg);
    } else {
        ctx.fireChannelRead(msg);
    }
}

From source file:nl.sidn.pcap.ip.AbstractNetworkCheck.java

public boolean isMatch(String address) {
    Boolean cacheHit = matchCache.get(address);
    if (cacheHit != null) {
        return cacheHit.booleanValue();
    }//from   w  ww.  j  a  v a2 s  .c om
    InetAddress ipAddress = InetAddresses.forString(address);
    boolean match = bitCompare(ipAddress);

    //create cache with hashmap for matches for perf
    matchCache.put(address, match);

    return match;
}

From source file:org.opendaylight.controller.config.yang.pcep.topology.provider.PCEPTopologyProviderModule.java

private InetAddress listenAddress() {
    final IpAddress a = getListenAddress();
    Preconditions.checkArgument(a.getIpv4Address() != null || a.getIpv6Address() != null,
            "Address %s not supported", a);
    if (a.getIpv4Address() != null) {
        return InetAddresses.forString(a.getIpv4Address().getValue());
    }//from w ww .  j  a v a  2 s.c  o m
    return InetAddresses.forString(a.getIpv6Address().getValue());
}

From source file:google.registry.whois.WhoisReader.java

/**
 * Given a WHOIS command string, parse it into its command type and target string. See class level
 * comments for a full description of the command syntax accepted.
 *//*from  w  ww .java 2 s. c om*/
private WhoisCommand parseCommand(String command) throws WhoisException {
    // Split the string into tokens based on whitespace.
    List<String> tokens = filterEmptyStrings(command.split("\\s"));

    if (tokens.isEmpty()) {
        throw new WhoisException(now, SC_BAD_REQUEST, "No WHOIS command specified.");
    }

    final String arg1 = tokens.get(0);

    // Check if the first token is equal to the domain lookup command.
    if (arg1.equalsIgnoreCase(DOMAIN_LOOKUP_COMMAND)) {
        if (tokens.size() != 2) {
            throw new WhoisException(now, SC_BAD_REQUEST,
                    String.format("Wrong number of arguments to '%s' command.", DOMAIN_LOOKUP_COMMAND));
        }

        // Try to parse the argument as a domain name.
        try {
            return new DomainLookupCommand(InternetDomainName.from(canonicalizeDomainName(tokens.get(1))));
        } catch (IllegalArgumentException iae) {
            // If we can't interpret the argument as a host name, then return an error.
            throw new WhoisException(now, SC_BAD_REQUEST,
                    String.format("Could not parse argument to '%s' command", DOMAIN_LOOKUP_COMMAND));
        }
    }

    // Check if the first token is equal to the nameserver lookup command.
    if (arg1.equalsIgnoreCase(NAMESERVER_LOOKUP_COMMAND)) {
        if (tokens.size() != 2) {
            throw new WhoisException(now, SC_BAD_REQUEST,
                    String.format("Wrong number of arguments to '%s' command.", NAMESERVER_LOOKUP_COMMAND));
        }

        // Try to parse the argument as an IP address.
        try {
            return new NameserverLookupByIpCommand(InetAddresses.forString(tokens.get(1)));
        } catch (IllegalArgumentException iae) {
            // Silently ignore this exception.
        }

        // Try to parse the argument as a host name.
        try {
            return new NameserverLookupByHostCommand(
                    InternetDomainName.from(canonicalizeDomainName(tokens.get(1))));
        } catch (IllegalArgumentException iae) {
            // Silently ignore this exception.
        }

        // If we can't interpret the argument as either a host name or IP address, return an error.
        throw new WhoisException(now, SC_BAD_REQUEST,
                String.format("Could not parse argument to '%s' command", NAMESERVER_LOOKUP_COMMAND));
    }

    // Check if the first token is equal to the registrar lookup command.
    if (arg1.equalsIgnoreCase(REGISTRAR_LOOKUP_COMMAND)) {
        if (tokens.size() == 1) {
            throw new WhoisException(now, SC_BAD_REQUEST,
                    String.format("Too few arguments to '%s' command.", REGISTRAR_LOOKUP_COMMAND));
        }
        return new RegistrarLookupCommand(Joiner.on(' ').join(tokens.subList(1, tokens.size())));
    }

    // If we have a single token, then try to interpret that in various ways.
    if (tokens.size() == 1) {
        // Try to parse it as an IP address. If successful, then this is a lookup on a nameserver.
        try {
            return new NameserverLookupByIpCommand(InetAddresses.forString(arg1));
        } catch (IllegalArgumentException iae) {
            // Silently ignore this exception.
        }

        // Try to parse it as a domain name or host name.
        try {
            final InternetDomainName targetName = InternetDomainName.from(canonicalizeDomainName(arg1));

            // We don't know at this point whether we have a domain name or a host name. We have to
            // search through our configured TLDs to see if there's one that prefixes the name.
            Optional<InternetDomainName> tld = findTldForName(targetName);
            if (!tld.isPresent()) {
                // This target is not under any configured TLD, so just try it as a registrar name.
                return new RegistrarLookupCommand(arg1);
            }

            // If the target is exactly one level above the TLD, then this is an second level domain
            // (SLD) and we should do a domain lookup on it.
            if (targetName.parent().equals(tld.get())) {
                return new DomainLookupCommand(targetName, tld.get());
            }

            // The target is more than one level above the TLD, so we'll assume it's a nameserver.
            return new NameserverLookupByHostCommand(targetName, tld.get());
        } catch (IllegalArgumentException e) {
            // Silently ignore this exception.
        }

        // Purposefully fall through to code below.
    }

    // The only case left is that there are multiple tokens with no particular command given. We'll
    // assume this is a registrar lookup, since there's really nothing else it could be.
    return new RegistrarLookupCommand(Joiner.on(' ').join(tokens));
}

From source file:org.opendaylight.netconf.impl.NetconfServerSession.java

@Override
public Session toManagementSession() {
    SessionBuilder builder = new SessionBuilder();

    builder.setSessionId(getSessionId());
    IpAddress address;/*from  ww w  . j  a  va 2  s .co m*/
    InetAddress address1 = InetAddresses.forString(header.getAddress());
    if (address1 instanceof Inet4Address) {
        address = new IpAddress(new Ipv4Address(header.getAddress()));
    } else {
        address = new IpAddress(new Ipv6Address(header.getAddress()));
    }
    builder.setSourceHost(new Host(address));

    Preconditions.checkState(DateAndTime.PATTERN_CONSTANTS.size() == 1);
    String formattedDateTime = dateFormatter.format(loginTime);

    Matcher matcher = dateTimePattern.matcher(formattedDateTime);
    Preconditions.checkState(matcher.matches(), "Formatted datetime %s does not match pattern %s",
            formattedDateTime, dateTimePattern);
    builder.setLoginTime(new DateAndTime(formattedDateTime));

    builder.setInBadRpcs(new ZeroBasedCounter32(inRpcFail));
    builder.setInRpcs(new ZeroBasedCounter32(inRpcSuccess));
    builder.setOutRpcErrors(new ZeroBasedCounter32(outRpcError));

    builder.setUsername(header.getUserName());
    builder.setTransport(getTransportForString(header.getTransport()));

    builder.setOutNotifications(new ZeroBasedCounter32(outNotification));

    builder.setKey(new SessionKey(getSessionId()));

    Session1Builder builder1 = new Session1Builder();
    builder1.setSessionIdentifier(header.getSessionIdentifier());
    builder.addAugmentation(Session1.class, builder1.build());

    return builder.build();
}

From source file:com.lambdaworks.redis.resource.DirContextDnsResolver.java

/**
 * Perform hostname to address resolution.
 * //  w  ww  . j a v a  2  s.co m
 * @param host the hostname, must not be empty or {@literal null}.
 * @return array of one or more {@link InetAddress adresses}
 * @throws UnknownHostException
 */
@Override
public InetAddress[] resolve(String host) throws UnknownHostException {

    if (InetAddresses.isInetAddress(host)) {
        return new InetAddress[] { InetAddresses.forString(host) };
    }

    List<InetAddress> inetAddresses = new ArrayList<>();
    try {
        resolve(host, inetAddresses);
    } catch (NamingException e) {
        throw new UnknownHostException(String.format("Cannot resolve %s to a hostname because of %s", host, e));
    }

    if (inetAddresses.isEmpty()) {
        throw new UnknownHostException(String.format("Cannot resolve %s to a hostname", host));
    }

    return inetAddresses.toArray(new InetAddress[inetAddresses.size()]);
}

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

static InetAddress toInetAddress(Name name) {
    return InetAddresses.forString(PATTERN.matcher(name.toString()).replaceAll(DNS_TO_IP_REGEX));
}

From source file:org.opendaylight.sxp.util.inet.NodeIdConv.java

/**
 * Converts NodeId into Byte Array/*from   w w  w.j a va  2 s  .  c om*/
 *
 * @param nodeId NodeId that will be converted
 * @return ByteArray representing specified NodeId
 */
public static byte[] toBytes(NodeId nodeId) {
    String _prefix = nodeId.getValue();
    if (_prefix.startsWith("/")) {
        _prefix = _prefix.substring(1);
    }
    int i = _prefix.lastIndexOf("/");
    if (i != -1) {
        _prefix = _prefix.substring(0, i);
    }
    return InetAddresses.forString(_prefix).getAddress();
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.loc.AnonymousIp.java

@SuppressWarnings({ "PMD.CyclomaticComplexity", "PMD.NPathComplexity" })
public static boolean enforce(final TrafficRouter trafficRouter, final String dsvcId, final String url,
        final String ip) {

    final InetAddress address = InetAddresses.forString(ip);

    if (inWhitelist(ip)) {
        return false;
    }// w w  w  .ja  v  a  2s .c o m

    final AnonymousIpResponse response = trafficRouter.getAnonymousIpDatabaseService().lookupIp(address);

    if (response == null) {
        return false;
    }

    // Check if the ip should be blocked by checking if the ip falls into a
    // specific policy
    if (AnonymousIp.getCurrentConfig().blockAnonymousIp && response.isAnonymousVpn()) {
        return true;
    }

    if (AnonymousIp.getCurrentConfig().blockHostingProvider && response.isHostingProvider()) {
        return true;
    }

    if (AnonymousIp.getCurrentConfig().blockPublicProxy && response.isPublicProxy()) {
        return true;
    }

    if (AnonymousIp.getCurrentConfig().blockTorExitNode && response.isTorExitNode()) {
        return true;
    }

    return false;
}