Example usage for org.apache.http.conn.util InetAddressUtils isIPv6Address

List of usage examples for org.apache.http.conn.util InetAddressUtils isIPv6Address

Introduction

In this page you can find the example usage for org.apache.http.conn.util InetAddressUtils isIPv6Address.

Prototype

public static boolean isIPv6Address(final String input) 

Source Link

Document

Checks whether the parameter is a valid IPv6 address (including compressed).

Usage

From source file:fr.cnes.sitools.security.filter.SecurityFilter.java

/**
 * Transform an address from string to long
 * //from ww  w . j a  v  a2 s .c om
 * @param ip
 *          the String representing an ip address
 * @return the long representation of the given ip address
 */
private long getAddress(String ip) {
    boolean isIPv4 = InetAddressUtils.isIPv4Address(ip);
    if (isIPv4) {
        StringTokenizer st = new StringTokenizer(ip, ".");

        long a1 = Integer.parseInt(st.nextToken());
        long a2 = Integer.parseInt(st.nextToken());
        long a3 = Integer.parseInt(st.nextToken());
        long a4 = Integer.parseInt(st.nextToken());

        return a1 << 24 | a2 << 16 | a3 << 8 | a4;
    }

    boolean isIPv6 = InetAddressUtils.isIPv6Address(ip);
    if (isIPv6) {
        getContext().getLogger().warning("SecurityFilter: IPV6 Address cannot match IPV4 mask");
        return 0;
    }
    getContext().getLogger().warning("SecurityFilter: Not a valid IP Address");
    return 0;
}

From source file:org.getlantern.firetweet.util.net.FiretweetHostAddressResolver.java

private static boolean isValidIpAddress(final String address) {
    if (isEmpty(address))
        return false;
    return InetAddressUtils.isIPv4Address(address) || InetAddressUtils.isIPv6Address(address);
}

From source file:ch.cyberduck.core.HostParser.java

private static boolean isv6Address(final String address) {
    if (IPV6_STD_PATTERN.matcher(address).matches()) {
        return true;
    }/*w ww.j  a  v a  2 s .c o  m*/
    return InetAddressUtils.isIPv6Address(address);
}

From source file:org.jivesoftware.smack.ConnectionConfiguration.java

/**
 * Returns the host to use when establishing the connection. The host and port to use
 * might have been resolved by a DNS lookup as specified by the XMPP spec (and therefore
 * may not match the {@link #getServiceName service name}.
 *
 * @return the host to use when establishing the connection.
 *//*from   w w  w. j  a va 2 s  . c  o  m*/
public String getHost() {
    // ?IP???IP?
    if (!InetAddressUtils.isIPv4Address(host) && !InetAddressUtils.isIPv6Address(host)) {
        try {
            InetAddress address = InetAddress.getByName(host);
            host = address.getHostAddress();
            Log.d(LOG_TAG, "transform host name to host address:" + host);
        } catch (UnknownHostException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        }
    }
    return host;
}

From source file:org.opennms.netmgt.provision.service.vmware.VmwareRequisitionUrlConnection.java

/**
 * Creates a requisition node for the given managed entity and type.
 *
 * @param ipAddresses   the set of Ip addresses
 * @param managedEntity the managed entity
 * @return the generated requisition node
 *///  w w  w . j a va2 s .c  o  m
private RequisitionNode createRequisitionNode(Set<String> ipAddresses, ManagedEntity managedEntity,
        int apiVersion, VmwareViJavaAccess vmwareViJavaAccess) {
    RequisitionNode requisitionNode = new RequisitionNode();

    // Setting the node label
    requisitionNode.setNodeLabel(managedEntity.getName());

    // Foreign Id consisting of managed entity Id
    requisitionNode.setForeignId(managedEntity.getMOR().getVal());

    /*
     * Original version:
     *
     * Foreign Id consisting of VMware management server's hostname and managed entity id
     *
     * requisitionNode.setForeignId(m_hostname + "/" + managedEntity.getMOR().getVal());
     */

    if (managedEntity instanceof VirtualMachine) {
        boolean firstInterface = true;

        // add all given interfaces
        for (String ipAddress : ipAddresses) {

            try {
                if ((m_persistIPv4 && InetAddressUtils.isIPv4Address(ipAddress))
                        || (m_persistIPv6 && InetAddressUtils.isIPv6Address(ipAddress))) {
                    InetAddress inetAddress = InetAddress.getByName(ipAddress);

                    if (!inetAddress.isLoopbackAddress()) {
                        RequisitionInterface requisitionInterface = new RequisitionInterface();
                        requisitionInterface.setIpAddr(ipAddress);

                        //  the first one will be primary
                        if (firstInterface) {
                            requisitionInterface.setSnmpPrimary(PrimaryType.PRIMARY);
                            for (String service : m_virtualMachineServices) {
                                requisitionInterface.insertMonitoredService(
                                        new RequisitionMonitoredService(service.trim()));
                            }
                            firstInterface = false;
                        } else {
                            requisitionInterface.setSnmpPrimary(PrimaryType.SECONDARY);
                        }

                        requisitionInterface.setManaged(Boolean.TRUE);
                        requisitionInterface.setStatus(Integer.valueOf(1));
                        requisitionNode.putInterface(requisitionInterface);
                    }
                }
            } catch (UnknownHostException unknownHostException) {
                logger.warn("Invalid IP address '{}'", unknownHostException.getMessage());
            }
        }
    } else {
        if (managedEntity instanceof HostSystem) {
            boolean reachableInterfaceFound = false, firstInterface = true;
            List<RequisitionInterface> requisitionInterfaceList = new ArrayList<RequisitionInterface>();
            RequisitionInterface primaryInterfaceCandidate = null;

            // add all given interfaces
            for (String ipAddress : ipAddresses) {

                try {
                    if ((m_persistIPv4 && InetAddressUtils.isIPv4Address(ipAddress))
                            || (m_persistIPv6 && InetAddressUtils.isIPv6Address(ipAddress))) {
                        InetAddress inetAddress = InetAddress.getByName(ipAddress);

                        if (!inetAddress.isLoopbackAddress()) {
                            RequisitionInterface requisitionInterface = new RequisitionInterface();
                            requisitionInterface.setIpAddr(ipAddress);

                            if (firstInterface) {
                                primaryInterfaceCandidate = requisitionInterface;
                                firstInterface = false;
                            }

                            if (!reachableInterfaceFound && reachableCimService(vmwareViJavaAccess,
                                    (HostSystem) managedEntity, ipAddress)) {
                                primaryInterfaceCandidate = requisitionInterface;
                                reachableInterfaceFound = true;
                            }

                            requisitionInterface.setManaged(Boolean.TRUE);
                            requisitionInterface.setStatus(Integer.valueOf(1));
                            requisitionInterface.setSnmpPrimary(PrimaryType.SECONDARY);
                            requisitionInterfaceList.add(requisitionInterface);
                        }
                    }

                } catch (UnknownHostException unknownHostException) {
                    logger.warn("Invalid IP address '{}'", unknownHostException.getMessage());
                }
            }

            if (primaryInterfaceCandidate != null) {
                if (reachableInterfaceFound) {
                    logger.warn("Found reachable primary interface '{}'",
                            primaryInterfaceCandidate.getIpAddr());
                } else {
                    logger.warn(
                            "Only non-reachable interfaces found, using first one for primary interface '{}'",
                            primaryInterfaceCandidate.getIpAddr());
                }
                primaryInterfaceCandidate.setSnmpPrimary(PrimaryType.PRIMARY);

                for (String service : m_hostSystemServices) {
                    if (reachableInterfaceFound || !"VMwareCim-HostSystem".equals(service)) {
                        primaryInterfaceCandidate
                                .insertMonitoredService(new RequisitionMonitoredService(service.trim()));
                    }
                }
            } else {
                logger.warn("No primary interface found");
            }

            for (RequisitionInterface requisitionInterface : requisitionInterfaceList) {
                requisitionNode.putInterface(requisitionInterface);
            }

        } else {
            logger.error("Undefined type of managedEntity '{}'", managedEntity.getMOR().getType());
            return null;
        }
    }

    /*
     * For now we use displaycategory, notifycategory and pollercategory for storing
     * the vcenter Ip address, the username and the password
     */

    String powerState = "unknown";
    StringBuffer vmwareTopologyInfo = new StringBuffer();

    // putting parents to topology information
    ManagedEntity parentEntity = managedEntity.getParent();

    do {
        if (vmwareTopologyInfo.length() > 0) {
            vmwareTopologyInfo.append(", ");
        }
        try {
            if (parentEntity != null && parentEntity.getMOR() != null) {
                vmwareTopologyInfo.append(parentEntity.getMOR().getVal() + "/"
                        + URLEncoder.encode(parentEntity.getName(), "UTF-8"));
            } else {
                logger.warn(
                        "Can't add topologyInformation because either the parentEntity or the MOR is null for "
                                + managedEntity.getName());
            }
        } catch (UnsupportedEncodingException e) {
            logger.warn("Unsupported encoding '{}'", e.getMessage());
        }
        parentEntity = parentEntity == null ? null : parentEntity.getParent();
    } while (parentEntity != null);

    if (managedEntity instanceof HostSystem) {

        HostSystem hostSystem = (HostSystem) managedEntity;

        HostRuntimeInfo hostRuntimeInfo = hostSystem.getRuntime();

        if (hostRuntimeInfo == null) {
            logger.debug("hostRuntimeInfo=null");
        } else {
            HostSystemPowerState hostSystemPowerState = hostRuntimeInfo.getPowerState();
            if (hostSystemPowerState == null) {
                logger.debug("hostSystemPowerState=null");
            } else {
                powerState = hostSystemPowerState.toString();
            }
        }

        try {
            if (m_topologyDatastores) {
                for (Datastore datastore : hostSystem.getDatastores()) {
                    if (vmwareTopologyInfo.length() > 0) {
                        vmwareTopologyInfo.append(", ");
                    }
                    try {
                        vmwareTopologyInfo.append(datastore.getMOR().getVal() + "/"
                                + URLEncoder.encode(datastore.getSummary().getName(), "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        logger.warn("Unsupported encoding '{}'", e.getMessage());
                    }
                }
            }
        } catch (RemoteException e) {
            logger.warn("Cannot retrieve datastores for managedEntity '{}': '{}'",
                    managedEntity.getMOR().getVal(), e.getMessage());
        }

        try {
            if (m_topologyNetworks) {
                for (Network network : hostSystem.getNetworks()) {
                    if (vmwareTopologyInfo.length() > 0) {
                        vmwareTopologyInfo.append(", ");
                    }
                    try {
                        if (network instanceof DistributedVirtualPortgroup ? m_topologyPortGroups : true) {
                            vmwareTopologyInfo.append(network.getMOR().getVal() + "/"
                                    + URLEncoder.encode(network.getSummary().getName(), "UTF-8"));
                        }
                    } catch (UnsupportedEncodingException e) {
                        logger.warn("Unsupported encoding '{}'", e.getMessage());
                    }
                }
            }
        } catch (RemoteException e) {
            logger.warn("Cannot retrieve networks for managedEntity '{}': '{}'",
                    managedEntity.getMOR().getVal(), e.getMessage());
        }
    } else {

        if (managedEntity instanceof VirtualMachine) {
            VirtualMachine virtualMachine = (VirtualMachine) managedEntity;

            VirtualMachineRuntimeInfo virtualMachineRuntimeInfo = virtualMachine.getRuntime();

            if (virtualMachineRuntimeInfo == null) {
                logger.debug("virtualMachineRuntimeInfo=null");
            } else {
                VirtualMachinePowerState virtualMachinePowerState = virtualMachineRuntimeInfo.getPowerState();
                if (virtualMachinePowerState == null) {
                    logger.debug("virtualMachinePowerState=null");
                } else {
                    powerState = virtualMachinePowerState.toString();
                }
            }

            try {
                if (m_topologyDatastores) {
                    for (Datastore datastore : virtualMachine.getDatastores()) {
                        if (vmwareTopologyInfo.length() > 0) {
                            vmwareTopologyInfo.append(", ");
                        }
                        try {
                            vmwareTopologyInfo.append(datastore.getMOR().getVal() + "/"
                                    + URLEncoder.encode(datastore.getSummary().getName(), "UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            logger.warn("Unsupported encoding '{}'", e.getMessage());
                        }
                    }
                }
            } catch (RemoteException e) {
                logger.warn("Cannot retrieve datastores for managedEntity '{}': '{}'",
                        managedEntity.getMOR().getVal(), e.getMessage());
            }
            try {
                if (m_topologyNetworks) {
                    for (Network network : virtualMachine.getNetworks()) {
                        if (vmwareTopologyInfo.length() > 0) {
                            vmwareTopologyInfo.append(", ");
                        }
                        try {
                            if (network instanceof DistributedVirtualPortgroup ? m_topologyPortGroups : true) {
                                vmwareTopologyInfo.append(network.getMOR().getVal() + "/"
                                        + URLEncoder.encode(network.getSummary().getName(), "UTF-8"));
                            }
                        } catch (UnsupportedEncodingException e) {
                            logger.warn("Unsupported encoding '{}'", e.getMessage());
                        }
                    }
                }
            } catch (RemoteException e) {
                logger.warn("Cannot retrieve networks for managedEntity '{}': '{}'",
                        managedEntity.getMOR().getVal(), e.getMessage());
            }

            if (vmwareTopologyInfo.length() > 0) {
                vmwareTopologyInfo.append(", ");
            }

            try {
                vmwareTopologyInfo.append(virtualMachine.getRuntime().getHost().getVal() + "/" + URLEncoder
                        .encode(m_hostSystemMap.get(virtualMachine.getRuntime().getHost().getVal()), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                logger.warn("Unsupported encoding '{}'", e.getMessage());
            }
        } else {
            logger.error("Undefined type of managedEntity '{}'", managedEntity.getMOR().getType());

            return null;
        }
    }

    RequisitionAsset requisitionAssetHostname = new RequisitionAsset("vmwareManagementServer", m_hostname);
    requisitionNode.putAsset(requisitionAssetHostname);

    RequisitionAsset requisitionAssetType = new RequisitionAsset("vmwareManagedEntityType",
            (managedEntity instanceof HostSystem ? "HostSystem" : "VirtualMachine"));
    requisitionNode.putAsset(requisitionAssetType);

    RequisitionAsset requisitionAssetId = new RequisitionAsset("vmwareManagedObjectId",
            managedEntity.getMOR().getVal());
    requisitionNode.putAsset(requisitionAssetId);

    RequisitionAsset requisitionAssetTopologyInfo = new RequisitionAsset("vmwareTopologyInfo",
            vmwareTopologyInfo.toString());
    requisitionNode.putAsset(requisitionAssetTopologyInfo);

    RequisitionAsset requisitionAssetState = new RequisitionAsset("vmwareState", powerState);
    requisitionNode.putAsset(requisitionAssetState);

    requisitionNode.putCategory(new RequisitionCategory("VMware" + apiVersion));

    return requisitionNode;
}

From source file:org.apache.http.conn.ssl.AbstractVerifier.java

private static boolean isIPAddress(final String hostname) {
    return hostname != null
            && (InetAddressUtils.isIPv4Address(hostname) || InetAddressUtils.isIPv6Address(hostname));
}

From source file:org.apache.http.conn.ssl.AbstractVerifier.java

private String normaliseIPv6Address(final String hostname) {
    if (hostname == null || !InetAddressUtils.isIPv6Address(hostname)) {
        return hostname;
    }/*from   w w w .  j  ava2s  .  c o m*/
    try {
        final InetAddress inetAddress = InetAddress.getByName(hostname);
        return inetAddress.getHostAddress();
    } catch (final UnknownHostException uhe) { // Should not happen, because we check for IPv6 address above
        log.error("Unexpected error converting " + hostname, uhe);
        return hostname;
    }
}

From source file:org.apache.http.conn.ssl.DefaultHostnameVerifier.java

public final void verify(final String host, final X509Certificate cert) throws SSLException {
    final boolean ipv4 = InetAddressUtils.isIPv4Address(host);
    final boolean ipv6 = InetAddressUtils.isIPv6Address(host);
    final int subjectType = ipv4 || ipv6 ? IP_ADDRESS_TYPE : DNS_NAME_TYPE;
    final List<String> subjectAlts = extractSubjectAlts(cert, subjectType);
    if (subjectAlts != null && !subjectAlts.isEmpty()) {
        if (ipv4) {
            matchIPAddress(host, subjectAlts);
        } else if (ipv6) {
            matchIPv6Address(host, subjectAlts);
        } else {//from w w w.  java 2s.c  o  m
            matchDNSName(host, subjectAlts, this.publicSuffixMatcher);
        }
    } else {
        // CN matching has been deprecated by rfc2818 and can be used
        // as fallback only when no subjectAlts are available
        final X500Principal subjectPrincipal = cert.getSubjectX500Principal();
        final String cn = extractCN(subjectPrincipal.getName(X500Principal.RFC2253));
        if (cn == null) {
            throw new SSLException("Certificate subject for <" + host + "> doesn't contain "
                    + "a common name and does not have alternative names");
        }
        matchCN(host, cn, this.publicSuffixMatcher);
    }
}