Example usage for org.apache.commons.validator.routines InetAddressValidator getInstance

List of usage examples for org.apache.commons.validator.routines InetAddressValidator getInstance

Introduction

In this page you can find the example usage for org.apache.commons.validator.routines InetAddressValidator getInstance.

Prototype

public static InetAddressValidator getInstance() 

Source Link

Document

Returns the singleton instance of this validator.

Usage

From source file:info.sugoiapps.xoserver.XOverServer.java

/**
 * Check if supplied string is a valid IPv4 address.
 * @param s the string to check//from  www  .j a  va  2  s .c  om
 * @return true - if the string represents a valid IPv4 address
 */
private boolean isValidAddress(String s) {
    return InetAddressValidator.getInstance().isValidInet4Address(s);
}

From source file:info.sugoiapps.xoclient.XOverClient.java

/**
 * Check the validity of the supplied IP address.
 * @param s the string to check/*from  w ww .  j ava 2  s .c  om*/
 * @return true if the supplied address is a valid IPv4 address
 */
public boolean validAddress(String s) {
    if (s != null) {
        if (InetAddressValidator.getInstance().isValidInet4Address(s))
            return true;
    }
    return false;
}

From source file:edu.harvard.iq.dvn.core.web.admin.EditLockssConfigPage.java

private static boolean doValidate(Object value) {
    boolean valid = false;
    String address = value.toString();
    // first, assume it's a domain name
    if (address.startsWith("*.")) {
        StringBuffer sb = new StringBuffer(address);
        sb.setCharAt(0, 'a');
        address = sb.toString();//from   w  ww  .j a va2s .c om
    }
    valid = validateDomainName(address);

    if (!valid) {
        // Try to validate it as an ip address
        String ipAddress = value.toString();

        // for the purposes of validation, if the string ends in ".*",
        // replace it with dummy data for the validator.
        if (ipAddress.endsWith(".*")) {
            StringBuffer sb = new StringBuffer(ipAddress);
            sb.setCharAt(ipAddress.length() - 1, '1');
            ipAddress = sb.toString();
            // if necessary, add dummy values to the end of the string,
            // so it will pass validation.
            String[] splitStrings = ipAddress.split("\\.");
            if (splitStrings.length == 2) {
                ipAddress += ".1.1";
            } else if (splitStrings.length == 3) {
                ipAddress += ".1";
            }
        }
        InetAddressValidator val = InetAddressValidator.getInstance();

        valid = val.isValid(ipAddress);
    }
    return valid;
}

From source file:io.appium.java_client.service.local.AppiumServiceBuilder.java

@Override
protected ImmutableList<String> createArgs() {
    List<String> argList = new ArrayList<>();
    checkAppiumJS();//from   w w  w .  j ava 2s  .co m
    argList.add(appiumJS.getAbsolutePath());
    argList.add("--port");
    argList.add(String.valueOf(getPort()));

    if (StringUtils.isBlank(ipAddress))
        ipAddress = DEFAULT_LOCAL_IP_ADDRESS;
    else {
        InetAddressValidator validator = InetAddressValidator.getInstance();
        if (!validator.isValid(ipAddress) && !validator.isValidInet4Address(ipAddress)
                && !validator.isValidInet6Address(ipAddress))
            throw new IllegalArgumentException("The invalid IP address " + ipAddress + " is defined");
    }
    argList.add("--address");
    argList.add(ipAddress);

    File log = getLogFile();
    if (log != null) {
        argList.add("--log");
        argList.add(log.getAbsolutePath());
    }

    Set<Map.Entry<String, String>> entries = serverArguments.entrySet();
    Iterator<Map.Entry<String, String>> iterator = entries.iterator();
    while (iterator.hasNext()) {
        Map.Entry<String, String> entry = iterator.next();
        String argument = entry.getKey();
        String value = entry.getValue();
        if (StringUtils.isBlank(argument) || value == null)
            continue;

        argList.add(argument);
        if (!StringUtils.isBlank(value))
            argList.add(value);
    }

    ImmutableList<String> result = new ImmutableList.Builder<String>().addAll(argList).build();
    return result;
}

From source file:com.vmware.photon.controller.model.resources.ComputeService.java

@Override
public void handlePatch(Operation patch) {
    ComputeState currentState = getState(patch);
    ComputeState patchBody = patch.getBody(ComputeState.class);

    boolean isChanged = false;

    if (patchBody.id != null && !patchBody.id.equals(currentState.id)) {
        currentState.id = patchBody.id;/*from  ww w . j  ava2s. c  o m*/
        isChanged = true;
    }

    if (patchBody.address != null && !patchBody.address.equals(currentState.address)) {
        InetAddressValidator.getInstance().isValidInet4Address(patchBody.address);
        currentState.address = patchBody.address;
        isChanged = true;
    }

    if (patchBody.powerState != null && patchBody.powerState != PowerState.UNKNOWN
            && patchBody.powerState != currentState.powerState) {
        currentState.powerState = patchBody.powerState;
        isChanged = true;
    }

    if (patchBody.primaryMAC != null && !patchBody.primaryMAC.equals(currentState.primaryMAC)) {
        currentState.primaryMAC = patchBody.primaryMAC;
        isChanged = true;
    }

    if (patchBody.diskLinks != null) {
        if (currentState.diskLinks == null) {
            currentState.diskLinks = patchBody.diskLinks;
            isChanged = true;
        } else {
            for (String link : patchBody.diskLinks) {
                if (!currentState.diskLinks.contains(link)) {
                    currentState.diskLinks.add(link);
                    isChanged = true;
                }
            }
        }
    }

    if (patchBody.networkLinks != null) {
        if (currentState.networkLinks == null) {
            currentState.networkLinks = patchBody.networkLinks;
            isChanged = true;
        } else {
            for (String link : patchBody.networkLinks) {
                if (!currentState.networkLinks.contains(link)) {
                    currentState.networkLinks.add(link);
                    isChanged = true;
                }
            }
        }
    }

    if (patchBody.resourcePoolLink != null
            && !patchBody.resourcePoolLink.equals(currentState.resourcePoolLink)) {
        currentState.resourcePoolLink = patchBody.resourcePoolLink;
        isChanged = true;
    }

    if (patchBody.adapterManagementReference != null
            && !patchBody.adapterManagementReference.equals(currentState.adapterManagementReference)) {
        currentState.adapterManagementReference = patchBody.adapterManagementReference;
        isChanged = true;
    }

    if (patchBody.descriptionLink != null && !patchBody.descriptionLink.equals(currentState.descriptionLink)) {
        currentState.descriptionLink = patchBody.descriptionLink;
        isChanged = true;
    }

    if (patchBody.customProperties != null && !patchBody.customProperties.isEmpty()) {
        if (currentState.customProperties == null || currentState.customProperties.isEmpty()) {
            currentState.customProperties = patchBody.customProperties;
        } else {
            for (Map.Entry<String, String> e : patchBody.customProperties.entrySet()) {
                currentState.customProperties.put(e.getKey(), e.getValue());
            }
        }
        isChanged = true;
    }

    if (!isChanged) {
        patch.setStatusCode(Operation.STATUS_CODE_NOT_MODIFIED);
    }
    patch.complete();
}

From source file:com.vmware.photon.controller.api.frontend.backends.clients.ClusterManagerClient.java

private ClusterService.State assembleCommonClusterEntity(ClusterType clusterType, String projectId,
        ClusterCreateSpec spec, ClusterConfigurationService.State clusterConfiguration)
        throws SpecInvalidException {

    String dns = spec.getExtendedProperties().get(ClusterManagerConstants.EXTENDED_PROPERTY_DNS);
    String gateway = spec.getExtendedProperties().get(ClusterManagerConstants.EXTENDED_PROPERTY_GATEWAY);
    String netmask = spec.getExtendedProperties().get(ClusterManagerConstants.EXTENDED_PROPERTY_NETMASK);

    // Verify the cluster entity
    if (dns == null) {
        throw new SpecInvalidException("Missing extended property: dns");
    } else if (!InetAddressValidator.getInstance().isValidInet4Address(dns)) {
        throw new SpecInvalidException("Invalid extended property: dns: " + dns);
    }//from  w ww  .j a va 2 s .  c o m

    if (gateway == null) {
        throw new SpecInvalidException("Missing extended property: gateway");
    } else if (!InetAddressValidator.getInstance().isValidInet4Address(gateway)) {
        throw new SpecInvalidException("Invalid extended property: gateway: " + gateway);
    }

    if (netmask == null) {
        throw new SpecInvalidException("Missing extended property: netmask");
    } else if (!InetAddressValidator.getInstance().isValidInet4Address(netmask)) {
        throw new SpecInvalidException("Invalid extended property: netmask: " + netmask);
    }

    ClusterService.State cluster = new ClusterService.State();
    cluster.clusterState = ClusterState.CREATING;
    cluster.clusterName = spec.getName();
    cluster.clusterType = clusterType;
    cluster.imageId = clusterConfiguration.imageId;
    cluster.projectId = projectId;
    cluster.diskFlavorName = spec.getDiskFlavor() == null || spec.getDiskFlavor().isEmpty()
            ? ClusterManagerConstants.VM_DISK_FLAVOR
            : spec.getDiskFlavor();
    cluster.masterVmFlavorName = spec.getVmFlavor() == null || spec.getVmFlavor().isEmpty()
            ? ClusterManagerConstants.MASTER_VM_FLAVOR
            : spec.getVmFlavor();
    cluster.otherVmFlavorName = spec.getVmFlavor() == null || spec.getVmFlavor().isEmpty()
            ? ClusterManagerConstants.OTHER_VM_FLAVOR
            : spec.getVmFlavor();
    cluster.vmNetworkId = spec.getVmNetworkId();
    cluster.slaveCount = spec.getSlaveCount();
    cluster.extendedProperties = new HashMap<>();
    cluster.documentSelfLink = UUID.randomUUID().toString();
    cluster.extendedProperties = new HashMap<>();
    cluster.extendedProperties.put(ClusterManagerConstants.EXTENDED_PROPERTY_DNS, dns);
    cluster.extendedProperties.put(ClusterManagerConstants.EXTENDED_PROPERTY_GATEWAY, gateway);
    cluster.extendedProperties.put(ClusterManagerConstants.EXTENDED_PROPERTY_NETMASK, netmask);

    return cluster;
}

From source file:com.mengge.service.local.AppiumServiceBuilder.java

@Override
protected ImmutableList<String> createArgs() {
    List<String> argList = new ArrayList<>();
    checkAppiumJS();//from ww  w  . j  a  va 2  s  .  co m
    argList.add(appiumJS.getAbsolutePath());
    argList.add("--port");
    argList.add(String.valueOf(getPort()));

    if (StringUtils.isBlank(ipAddress)) {
        ipAddress = DEFAULT_LOCAL_IP_ADDRESS;
    } else {
        InetAddressValidator validator = InetAddressValidator.getInstance();
        if (!validator.isValid(ipAddress) && !validator.isValidInet4Address(ipAddress)
                && !validator.isValidInet6Address(ipAddress)) {
            throw new IllegalArgumentException("The invalid IP address " + ipAddress + " is defined");
        }
    }
    argList.add("--address");
    argList.add(ipAddress);

    File log = getLogFile();
    if (log != null) {
        argList.add("--log");
        argList.add(log.getAbsolutePath());
    }

    Set<Map.Entry<String, String>> entries = serverArguments.entrySet();
    for (Map.Entry<String, String> entry : entries) {
        String argument = entry.getKey();
        String value = entry.getValue();
        if (StringUtils.isBlank(argument) || value == null) {
            continue;
        }

        argList.add(argument);
        if (!StringUtils.isBlank(value)) {
            argList.add(value);
        }
    }

    if (capabilities != null) {
        argList.add("--default-capabilities");
        argList.add(parseCapabilities());
    }

    return new ImmutableList.Builder<String>().addAll(argList).build();
}

From source file:com.netease.backend.collector.rss.common.util.UrlValidator.java

/**
 * Returns true if the authority is properly formatted.  An authority is the combination
 * of hostname and port.  A <code>null</code> authority value is considered invalid.
 * @param authority Authority value to validate.
 * @return true if authority (hostname and port) is valid.
 *///from ww  w .ja  va  2s .c  om
protected boolean isValidAuthority(String authority) {
    if (authority == null) {
        return false;
    }

    // check manual authority validation if specified
    if (authorityValidator != null) {
        if (authorityValidator.isValid(authority)) {
            return true;
        }
    }

    Matcher authorityMatcher = AUTHORITY_PATTERN.matcher(authority);
    if (!authorityMatcher.matches()) {
        return false;
    }

    String hostLocation = authorityMatcher.group(PARSE_AUTHORITY_HOST_IP);
    // check if authority is hostname or IP address:
    // try a hostname first since that's much more likely
    DomainValidator domainValidator = DomainValidator.getInstance(isOn(ALLOW_LOCAL_URLS));
    if (!domainValidator.isValid(hostLocation)) {
        // try an IP address
        InetAddressValidator inetAddressValidator = InetAddressValidator.getInstance();
        if (!inetAddressValidator.isValid(hostLocation)) {
            // isn't either one, so the URL is invalid
            return false;
        }
    }

    String port = authorityMatcher.group(PARSE_AUTHORITY_PORT);
    if (port != null) {
        if (!PORT_PATTERN.matcher(port).matches()) {
            return false;
        }
    }

    String extra = authorityMatcher.group(PARSE_AUTHORITY_EXTRA);
    if (extra != null && extra.trim().length() > 0) {
        return false;
    }

    return true;
}

From source file:com.vmware.photon.controller.model.tasks.ProvisionComputeTaskService.java

private void doSubStageValidateComputeHostState(ProvisionComputeTaskState updatedState) {
    // we need to make sure the boot/power services not only properly patched
    // our sub tasks but also patched the compute host with the IP address and other
    // runtime data

    sendRequest(Operation.createGet(this, updatedState.computeLink).setTargetReplicated(true)
            .setCompletion((o, e) -> {
                if (e != null) {
                    // the compute host is co-located so it is unexpected that it failed the GET
                    logWarning("GET to %s failed:", o.getUri(), Utils.toString(e));
                    failTask(e);/*w  w w.  j  a v  a  2  s  . c om*/
                    return;
                }
                ComputeService.ComputeState chs = o.getBody(ComputeService.ComputeState.class);
                try {
                    if (!updatedState.isMockRequest) {
                        InetAddressValidator.getInstance().isValidInet4Address(chs.address);
                    }
                    sendSelfPatch(TaskStage.FINISHED, ProvisionComputeTaskState.SubStage.DONE, null);
                } catch (Throwable ex) {
                    failTask(ex);
                }
            }));
}

From source file:com.vmware.photon.controller.apife.backends.clients.ClusterManagerClient.java

private String createKubernetesClusterEntity(String projectId, ClusterCreateSpec spec,
        ClusterConfigurationService.State clusterConfiguration) throws SpecInvalidException {

    List<String> etcdIps = new ArrayList<>();
    for (String property : Arrays.asList(EXTENDED_PROPERTY_ETCD_IP1, EXTENDED_PROPERTY_ETCD_IP2,
            EXTENDED_PROPERTY_ETCD_IP3)) {
        String etcdIp = spec.getExtendedProperties().get(property);
        if (etcdIp != null) {
            etcdIps.add(etcdIp);//w ww. j  av  a2  s.  co m
        }
    }
    String masterIp = spec.getExtendedProperties().get(ClusterManagerConstants.EXTENDED_PROPERTY_MASTER_IP);
    String containerNetwork = spec.getExtendedProperties()
            .get(ClusterManagerConstants.EXTENDED_PROPERTY_CONTAINER_NETWORK);

    if (etcdIps.size() == 0) {
        throw new SpecInvalidException("Missing extended property: etcd ips");
    }

    for (String etcdIp : etcdIps) {
        if (etcdIp != null && !InetAddressValidator.getInstance().isValidInet4Address(etcdIp)) {
            throw new SpecInvalidException("Invalid extended property: etcd ip: " + etcdIp);
        }
    }

    if (masterIp == null) {
        throw new SpecInvalidException("Missing extended property: master ip");
    } else if (!InetAddressValidator.getInstance().isValidInet4Address(masterIp)) {
        throw new SpecInvalidException("Invalid extended property: master ip: " + masterIp);
    }

    if (containerNetwork == null) {
        throw new SpecInvalidException(
                "Missing extended property: " + ClusterManagerConstants.EXTENDED_PROPERTY_CONTAINER_NETWORK);
    } else {
        String[] segments = containerNetwork.split("/");
        SpecInvalidException error = new SpecInvalidException("Invalid extended property: "
                + ClusterManagerConstants.EXTENDED_PROPERTY_CONTAINER_NETWORK + ": " + containerNetwork);

        // Check that container network is of CIDR format.
        if (segments.length != 2) {
            throw error;
        }

        // Check the first segment of the container network is a valid address.
        if (!InetAddressValidator.getInstance().isValidInet4Address(segments[0])) {
            throw error;
        }

        // Check the second segment of the container network is a valid netmask.
        try {
            int cidr = Integer.parseInt(segments[1]);
            if (cidr < 0 || cidr > 32) {
                throw error;
            }
        } catch (NumberFormatException e) {
            throw error;
        }
    }

    // Assemble the cluster entity
    ClusterService.State cluster = assembleCommonClusterEntity(ClusterType.KUBERNETES, projectId, spec,
            clusterConfiguration);
    cluster.extendedProperties.put(ClusterManagerConstants.EXTENDED_PROPERTY_CONTAINER_NETWORK,
            containerNetwork);
    cluster.extendedProperties.put(ClusterManagerConstants.EXTENDED_PROPERTY_ETCD_IPS,
            serializeIpAddresses(etcdIps));
    cluster.extendedProperties.put(ClusterManagerConstants.EXTENDED_PROPERTY_MASTER_IP, masterIp);

    // Create the cluster entity
    apiFeDcpClient.post(ClusterServiceFactory.SELF_LINK, cluster);

    return cluster.documentSelfLink;
}