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:org.opendaylight.genius.mdsalutil.MDSALUtil.java

public static BigInteger getBigIntIpFromIpAddress(IpAddress ipAddr) {
    String ipString = ipAddr.getIpv4Address().getValue();
    int ipInt = InetAddresses.coerceToInteger(InetAddresses.forString(ipString));
    return BigInteger.valueOf(ipInt & 0xffffffffL);
}

From source file:diskCacheV111.srm.SrmHandler.java

public Object handleRequest(String requestName, Object request) throws RemoteException {
    long startTimeStamp = System.currentTimeMillis();
    // requestName values all start "srm".  This is redundant, so may
    // be removed when creating the session id.  The initial character is
    // converted to lowercase, so "srmPrepareToPut" becomes "prepareToPut".
    String session = "srm2:" + Character.toLowerCase(requestName.charAt(3)) + requestName.substring(4);
    try (JDC ignored = JDC.createSession(session)) {
        for (RequestLogger logger : loggers) {
            logger.request(requestName, request);
        }//from   www  . ja va2 s  .c o m

        Subject user = null;
        Object response;
        if (requestName.equals("srmPing")) {
            // Ping is special as it isn't authenticated and unable to return a failure
            response = new SrmPingResponse("v2.2", pingExtraInfo);
        } else {
            try {
                LoginReply login = login();
                user = login.getSubject();
                X509Credential credential = Axis.getDelegatedCredential().orElse(null);
                String remoteIP = Axis.getRemoteAddress();
                String remoteHost = isClientDNSLookup ? InetAddresses.forString(remoteIP).getCanonicalHostName()
                        : remoteIP;

                response = dispatch(login, credential, remoteHost, requestName, request);
            } catch (SRMInternalErrorException e) {
                LOGGER.error(e.getMessage());
                response = getFailedResponse(requestName, e.getStatusCode(),
                        "Authentication failed (server log contains additional information).");
            } catch (SRMAuthorizationException e) {
                LOGGER.info(e.getMessage());
                response = getFailedResponse(requestName, e.getStatusCode(), "Permission denied.");
            } catch (SRMAuthenticationException e) {
                LOGGER.warn(e.getMessage());
                response = getFailedResponse(requestName, e.getStatusCode(),
                        "Authentication failed (server log contains additional information).");
            } catch (SRMException e) {
                response = getFailedResponse(requestName, e.getStatusCode(), e.getMessage());
            } catch (PermissionDeniedCacheException e) {
                response = getFailedResponse(requestName, TStatusCode.SRM_AUTHORIZATION_FAILURE,
                        e.getMessage());
            } catch (CacheException e) {
                response = getFailedResponse(requestName, TStatusCode.SRM_INTERNAL_ERROR, e.getMessage());
            } catch (InterruptedException e) {
                response = getFailedResponse(requestName, TStatusCode.SRM_FATAL_INTERNAL_ERROR,
                        "Server shutdown.");
            } catch (NoRouteToCellException e) {
                LOGGER.error(e.getMessage());
                response = getFailedResponse(requestName, TStatusCode.SRM_INTERNAL_ERROR,
                        "SRM backend serving this request is currently offline.");
            }
        }
        long time = System.currentTimeMillis() - startTimeStamp;
        for (RequestLogger logger : loggers) {
            logger.response(requestName, request, response, user, time);
        }
        return response;
    }
}

From source file:org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.IpConversionUtil.java

/**
 * Convert Ipv6Prefix object to a valid Canonical v6 prefix in byte format
 *
 * @param ipv6Prefix - v6 prefix object//from  w  w w.ja  v a2 s.  c o  m
 * @return - byte array of size 16 + 1. Last byte contains netmask
 */
public static byte[] canonicalBinaryV6Prefix(final Ipv6Prefix ipv6Prefix) {
    /*
     * Do not modify this routine to take direct strings input!!!
     * Key checks have been removed based on the assumption that
     * the input is validated via regexps in Ipv6Prefix()
     */

    int mask = 128;

    String[] address = null;

    boolean valid = true;

    address = (ipv6Prefix.getValue()).split("/");
    try {
        mask = Integer.parseInt(address[1]);
        if (mask > 128) {
            valid = false;
        }
    } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
        valid = false;
    }

    Preconditions.checkArgument(valid, "Supplied netmask in %s is invalid", ipv6Prefix.getValue());

    int colonp;
    char ch;
    boolean saw_xdigit;

    /* Isn't it fun - the above variable names are the same in BSD and Sun sources */

    int val;

    char[] src = address[0].toCharArray();

    byte[] dst = new byte[INADDR6SZ + 1];

    int m = mask;

    int src_length = src.length;

    colonp = -1;
    int i = 0, j = 0;

    /* Leading :: requires some special handling. */

    /* Isn't it fun - the above comment is again the same in BSD and Sun sources,
     * We will derive our code from BSD. Shakespear always sounds better
     * in original Clingon. So does Dilbert.
     */

    if (src[i] == ':') {
        Preconditions.checkArgument(src[++i] == ':', "Invalid v6 address");
    }

    int curtok = i;
    saw_xdigit = false;

    val = 0;
    while (i < src_length) {
        ch = src[i++];
        int chval = Character.digit(ch, 16);

        /* Business as usual - ipv6 address digit.
         * We can remove all checks from the original BSD code because
         * the regexp has already verified that we are not being fed
         * anything bigger than 0xffff between the separators.
         */

        if (chval != -1) {
            val <<= 4;
            val |= chval;
            saw_xdigit = true;
            continue;
        }

        /* v6 separator */

        if (ch == ':') {
            curtok = i;
            if (!saw_xdigit) {
                /* no need to check separator position validity - regexp does that */
                colonp = j;
                continue;
            }

            /* removed overrun check - the regexp checks for valid data */

            saw_xdigit = false;

            if (m < 0) {
                /* stop parsing if we are past the mask */
                break;
            }

            dst[j] = (byte) ((val >> 8) & nextNibble(m));
            j++;
            m = m - 8;

            if (m < 0) {
                /* stop parsing if we are past the mask */
                break;
            }

            dst[j] = (byte) (val & nextNibble(m));
            j++;
            m = m - 8;

            val = 0;
            continue;
        }

        /* frankenstein - v4 attached to v6, mixed notation */

        if (ch == '.' && ((j + INADDR4SZ) <= INADDR6SZ)) {

            /* this has passed the regexp so it is fairly safe to parse it
             * straight away. As v4 addresses do not suffer from the same
             * defficiencies as the java v6 implementation we can invoke it
             * straight away and be done with it
             */

            Preconditions.checkArgument(j != (INADDR6SZ - INADDR4SZ - 1), "Invalid v4 in v6 mapping");

            InetAddress _inet_form = InetAddresses.forString(address[0].substring(curtok, src_length));

            Preconditions.checkArgument(_inet_form instanceof Inet4Address);
            System.arraycopy(_inet_form.getAddress(), 0, dst, j, INADDR4SZ);
            j += INADDR4SZ;

            saw_xdigit = false;
            break;
        }
        /* removed parser exit on ivalid char - no need to do it, regexp checks it */
    }
    if (saw_xdigit) {
        Preconditions.checkArgument(j + INT16SZ <= INADDR6SZ, "Overrun in v6 parsing, should not occur");
        dst[j] = (byte) ((val >> 8) & nextNibble(m));
        j++;
        m = m - 8;
        dst[j] = (byte) (val & nextNibble(m));
        j++;
        m = m - 8;
    }

    if ((j < INADDR6SZ) && (m < 0)) {
        /* past the mask */
        for (i = j; i < INADDR6SZ; i++) {
            dst[i] = 0;
        }
    } else {
        /* normal parsing */
        if (colonp != -1) {
            int n = j - colonp;

            Preconditions.checkArgument(j != INADDR6SZ, "Overrun in v6 parsing, should not occur");
            for (i = 1; i <= n; i++) {
                dst[INADDR6SZ - i] = dst[colonp + n - i];
                dst[colonp + n - i] = 0;
            }
            j = INADDR6SZ;
        }
        Preconditions.checkArgument(j == INADDR6SZ, "Overrun in v6 parsing, should not occur");
    }

    dst[INADDR6SZ] = (byte) mask;
    return dst;
}

From source file:net.shibboleth.idp.test.flows.saml2.SAML2TestResponseValidator.java

/**
 * Assert that :/* ww  w.  j  a va2  s  .co  m*/
 * <ul>
 * <li>the subject confirmation data address is in the expected range</li>
 * <li>the subject confirmation data NotOnOrAfter is not null</li>
 * <li>the subject confirmation data recipient is not null nor empty</li>
 * </ul>
 * 
 * @param subjectConfirmationData the subject confirmation data
 */
public void assertSubjectConfirmationData(@Nullable final SubjectConfirmationData subjectConfirmationData) {
    final InetAddress address = InetAddresses.forString(subjectConfirmationData.getAddress());
    Assert.assertTrue(subjectConfirmationDataAddressRange.contains(address));
    // TODO only in some cases ? Assert.assertNotNull(subjectConfirmationData.getNotBefore());
    Assert.assertNotNull(subjectConfirmationData.getNotOnOrAfter());
    Assert.assertNotNull(subjectConfirmationData.getRecipient());
    Assert.assertFalse(subjectConfirmationData.getRecipient().isEmpty());
}

From source file:org.graylog2.plugin.Message.java

public InetAddress getInetAddress() {
    if (!fields.containsKey("gl2_remote_ip")) {
        return null;
    }/*from  w  w w . j a v  a 2  s  .com*/
    final String ipAddr = (String) fields.get("gl2_remote_ip");
    try {
        return InetAddresses.forString(ipAddr);
    } catch (IllegalArgumentException ignored) {
        return null;
    }
}

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

public void updateHostIntf(Uuid portId, List<FixedIps> fixedIpsList) {
    LOG.debug("updateHostIntf portId {}, fixedIpsList {} ", portId, fixedIpsList);
    Boolean portIncludesV6Address = Boolean.FALSE;

    VirtualPort intf = vintfs.get(portId);
    if (intf == null) {
        LOG.warn("Update Host interface failed. Could not get Host interface details {}", portId);
        return;/*  www . j a va  2  s  .c  o m*/
    }

    intf.clearSubnetInfo();
    for (FixedIps fip : fixedIpsList) {
        IpAddress fixedIp = fip.getIpAddress();
        if (fixedIp.getIpv4Address() != null) {
            continue;
        }
        portIncludesV6Address = Boolean.TRUE;
        //Save the interface ipv6 address in its fully expanded format
        Ipv6Address addr = new Ipv6Address(
                InetAddresses.forString(fixedIp.getIpv6Address().getValue()).getHostAddress());
        fixedIp = new IpAddress(addr);

        intf.setSubnetInfo(fip.getSubnetId(), fixedIp);

        VirtualSubnet snet = vsubnets.get(fip.getSubnetId());

        if (snet != null) {
            intf.setSubnet(fip.getSubnetId(), snet);
        } else {
            addUnprocessed(unprocessedSubnetIntfs, fip.getSubnetId(), intf);
        }
    }

    /* If the VMPort initially included an IPv6 address (along with IPv4 address) and IPv6 address
     was removed, we will have to unbind the service on the VM port. Similarly we do a ServiceBind
     if required.
      */
    if (portIncludesV6Address) {
        if (intf.getServiceBindingStatus() == Boolean.FALSE) {
            Long elanTag = getNetworkElanTag(intf.getNetworkID());
            ipv6ServiceUtils.bindIpv6Service(dataBroker, portId.getValue(), elanTag, NwConstants.IPV6_TABLE);
            intf.setServiceBindingStatus(Boolean.TRUE);
        }
    } else {
        ipv6ServiceUtils.unbindIpv6Service(dataBroker, portId.getValue());
        intf.setServiceBindingStatus(Boolean.FALSE);
    }
    return;
}

From source file:org.apache.hadoop.hdfs.server.datanode.DWRRDataXceiver.java

/**
 * Returns InetAddress from peer//from   ww  w .  j  a  v  a 2  s.com
 * The getRemoteAddressString is the form  /ip-address:port
 * The ip-address is extracted from peer and InetAddress is formed
 * @param peer
 * @return
 * @throws UnknownHostException
 */
private static InetAddress getClientAddress(Peer peer) {
    return InetAddresses.forString(peer.getRemoteAddressString().split(":")[0].substring(1));
}

From source file:org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.common.IpConversionUtil.java

/**
 * Convert Ipv6Prefix object to a valid Canonical v6 prefix in byte format
 *
 * @param ipv6Prefix - v6 prefix object//www. j a  v  a  2s.  com
 * @return - byte array of size 16 + 1. Last byte contains netmask
 */
public static byte[] canonicalBinaryV6Prefix(final Ipv6Prefix ipv6Prefix) {
    /*
     * Do not modify this routine to take direct strings input!!!
     * Key checks have been removed based on the assumption that
     * the input is validated via regexps in Ipv6Prefix()
     */

    int mask = 128;

    Iterable<String> splittedV6Prefix = Splitter.on("/").trimResults().omitEmptyStrings()
            .split(ipv6Prefix.getValue());
    List<String> partsV6Prefix = Lists.newArrayList(splittedV6Prefix.iterator());

    boolean valid = true;

    try {
        mask = Integer.parseInt(partsV6Prefix.get(1));
        if (mask > 128) {
            valid = false;
        }
    } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
        valid = false;
    }

    Preconditions.checkArgument(valid, "Supplied netmask in %s is invalid", ipv6Prefix.getValue());

    int colonp;
    char ch;
    boolean saw_xdigit;

    /* Isn't it fun - the above variable names are the same in BSD and Sun sources */

    int val;

    char[] src = partsV6Prefix.get(0).toCharArray();

    byte[] dst = new byte[INADDR6SZ + 1];

    int m = mask;

    int src_length = src.length;

    colonp = -1;
    int i = 0, j = 0;

    /* Leading :: requires some special handling. */

    /* Isn't it fun - the above comment is again the same in BSD and Sun sources,
     * We will derive our code from BSD. Shakespear always sounds better
     * in original Clingon. So does Dilbert.
     */

    if (src[i] == ':') {
        Preconditions.checkArgument(src[++i] == ':', "Invalid v6 address");
    }

    int curtok = i;
    saw_xdigit = false;

    val = 0;
    while (i < src_length) {
        ch = src[i++];
        int chval = Character.digit(ch, 16);

        /* Business as usual - ipv6 address digit.
         * We can remove all checks from the original BSD code because
         * the regexp has already verified that we are not being fed
         * anything bigger than 0xffff between the separators.
         */

        if (chval != -1) {
            val <<= 4;
            val |= chval;
            saw_xdigit = true;
            continue;
        }

        /* v6 separator */

        if (ch == ':') {
            curtok = i;
            if (!saw_xdigit) {
                /* no need to check separator position validity - regexp does that */
                colonp = j;
                continue;
            }

            /* removed overrun check - the regexp checks for valid data */

            saw_xdigit = false;

            if (m < 0) {
                /* stop parsing if we are past the mask */
                break;
            }

            dst[j] = (byte) ((val >> 8) & nextNibble(m));
            j++;
            m = m - 8;

            if (m < 0) {
                /* stop parsing if we are past the mask */
                break;
            }

            dst[j] = (byte) (val & nextNibble(m));
            j++;
            m = m - 8;

            val = 0;
            continue;
        }

        /* frankenstein - v4 attached to v6, mixed notation */

        if (ch == '.' && ((j + INADDR4SZ) <= INADDR6SZ)) {

            /* this has passed the regexp so it is fairly safe to parse it
             * straight away. As v4 addresses do not suffer from the same
             * defficiencies as the java v6 implementation we can invoke it
             * straight away and be done with it
             */

            Preconditions.checkArgument(j != (INADDR6SZ - INADDR4SZ - 1), "Invalid v4 in v6 mapping");

            InetAddress _inet_form = InetAddresses
                    .forString(partsV6Prefix.get(0).substring(curtok, src_length));

            Preconditions.checkArgument(_inet_form instanceof Inet4Address);
            System.arraycopy(_inet_form.getAddress(), 0, dst, j, INADDR4SZ);
            j += INADDR4SZ;

            saw_xdigit = false;
            break;
        }
        /* removed parser exit on ivalid char - no need to do it, regexp checks it */
    }
    if (saw_xdigit) {
        Preconditions.checkArgument(j + INT16SZ <= INADDR6SZ, "Overrun in v6 parsing, should not occur");
        dst[j] = (byte) ((val >> 8) & nextNibble(m));
        j++;
        m = m - 8;
        dst[j] = (byte) (val & nextNibble(m));
        j++;
        m = m - 8;
    }

    if ((j < INADDR6SZ) && (m < 0)) {
        /* past the mask */
        for (i = j; i < INADDR6SZ; i++) {
            dst[i] = 0;
        }
    } else {
        /* normal parsing */
        if (colonp != -1) {
            int n = j - colonp;

            Preconditions.checkArgument(j != INADDR6SZ, "Overrun in v6 parsing, should not occur");
            for (i = 1; i <= n; i++) {
                dst[INADDR6SZ - i] = dst[colonp + n - i];
                dst[colonp + n - i] = 0;
            }
            j = INADDR6SZ;
        }
        Preconditions.checkArgument(j == INADDR6SZ, "Overrun in v6 parsing, should not occur");
    }

    dst[INADDR6SZ] = (byte) mask;
    return dst;
}

From source file:diskCacheV111.srm.SrmHandler.java

private LoginReply login() throws SRMAuthenticationException, CacheException, SRMInternalErrorException {
    try {//from   ww w. ja  v a  2  s  .  co m
        Subject subject = new Subject();
        X509Certificate[] chain = Axis.getCertificateChain().orElseThrow(
                () -> new SRMAuthenticationException("Client's certificate chain is missing from request"));
        subject.getPublicCredentials().add(cf.generateCertPath(asList(chain)));
        subject.getPrincipals().add(new Origin(InetAddresses.forString(Axis.getRemoteAddress())));
        return loginStrategy.login(subject);
    } catch (CertificateException e) {
        throw new SRMInternalErrorException("Failed to process certificate chain.", e);
    }
}

From source file:com.gemini.provision.network.openstack.NetworkProviderOpenStackImpl.java

/**
 * getAllSubnets. Lists all the subnets in the cloud - function may not have
 * practical use in OpenStack. Use getSubnets and provide a network to get
 * subnets specific to a network./*  ww w.jav  a 2 s  .c o  m*/
 *
 * @param tenant - the tenant
 * @param env - the environment with the subnets
 * @return
 */
@Override
public List<GeminiSubnet> getAllSubnets(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();
    if (os == null) {
        Logger.error("Failed to authenticate Tenant: {}",
                ToStringBuilder.reflectionToString(tenant, ToStringStyle.MULTI_LINE_STYLE));
        return null;
    }

    //get all the subnets
    List<? extends Subnet> subnets = os.networking().subnet().list();
    if (subnets.isEmpty()) {
        return null;
    }
    List<GeminiSubnet> gemSubnets = new ArrayList();

    //map the list of network gateways and their subnets to gemini equivalents
    subnets.stream().forEach(s -> {
        GeminiSubnet gn = new GeminiSubnet();
        //the basic elements
        gn.setName(s.getName());
        gn.setCloudID(s.getId());
        gn.setCidr(s.getCidr());
        gn.setGateway(InetAddresses.forString(s.getGateway()));

        //connect with the parent network
        try {
            //match the parent network to one in the application
            gn.setParent(
                    env.getApplications().stream().map(GeminiApplication::getNetworks).flatMap(List::stream)
                            .filter(g -> g.getCloudID().equals(s.getNetworkId())).findAny().get());
        } catch (NoSuchElementException | NullPointerException ex) {
            try {
                //could not find a parent network in the applications, now look in the orphaned networks
                gn.setParent(env.getOrphanNetworks().stream()
                        .filter(g -> g.getCloudID().equals(s.getNetworkId())).findAny().get());
            } catch (NoSuchElementException | NullPointerException e) {
                gn.setParent(null); //VERY BAD SITUATION - GEMINI MODEL IS COMPLETELY OUT OF SYNC
                Logger.error(
                        "Subnet {} has a network that isn't in Applications or orphaned networks. subnet {} parent network {}",
                        gn.getName(), s.getNetworkId());
            }
        }
        gn.setEnableDHCP(s.isDHCPEnabled());
        gn.setNetworkType(s.getIpVersion() == IPVersionType.V6 ? IPAddressType.IPv6 : IPAddressType.IPv4);
        s.getHostRoutes();
        s.getAllocationPools().stream().forEach(ap -> {
            GeminiSubnetAllocationPool gsap = new GeminiSubnetAllocationPool(
                    InetAddresses.forString(ap.getStart()), InetAddresses.forString(ap.getEnd()));
            gn.addAllocationPool(gsap);
        });
        gemSubnets.add(gn);
    });
    return gemSubnets;
}