Example usage for org.apache.commons.lang StringUtils containsAny

List of usage examples for org.apache.commons.lang StringUtils containsAny

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils containsAny.

Prototype

public static boolean containsAny(String str, String searchChars) 

Source Link

Document

Checks if the String contains any character in the given set of characters.

Usage

From source file:de.tudarmstadt.ukp.dkpro.tc.features.wordDifficulty.FrequencyOfWordAndContextUFE.java

private void addToFeatureList(String featureName, Double prob, String phrase) {
    if (prob.isNaN() || prob.isInfinite()) {
        prob = 0.0;/* w  ww  . j ava 2  s  . c  om*/
        logger.log(Level.INFO, "No prob for: " + phrase);
    }
    // the frequency calculation of ngrams with - or ' does not work properly
    // weka replaces the missing value with the mean of the feature for most classifiers

    if (prob == 0.0 && StringUtils.containsAny(phrase, "-'")) {
        featList.addAll(
                Arrays.asList(new Feature(featureName, new MissingValue(MissingValueNonNominalType.NUMERIC))));
    }
    featList.addAll(Arrays.asList(new Feature(PROBABILITY, prob)));

}

From source file:info.magnolia.cms.filters.AggregatorFilter.java

/**
 * Check if the path *may be* a valid path before calling getItem, in order to avoid annoying logs.
 * @param handle node handle/*w ww  .  j  a v  a 2 s  . c o m*/
 * @return true if the path is invalid
 */
private boolean isJcrPathValid(String handle) {
    if (StringUtils.isBlank(handle) || StringUtils.equals(handle, "/")) {
        // empty path not allowed
        return false;
    }
    if (StringUtils.containsAny(handle, new char[] { ':', '*', '\n' })) {
        // not allowed chars
        return false;
    }
    if (StringUtils.contains(handle, " /")) {
        // trailing slash not allowed
        return false;
    }
    return true;
}

From source file:mitm.djigzo.web.grid.CertStoreCertificateGridDataSource.java

private String getFilter() {
    String filter = filterSettings.getFilter();

    if (filter == null) {
        /*// ww  w. jav a2  s.  c o  m
         * If search is empty search for all everything
         */
        filter = "%%";
    } else {
        /*
         * Treat searching for # as a special character to indicate that searching for null
         * field should be done.
         */
        if (filter.equals("#")) {
            filter = null;
        } else {
            /*
             * If the filter string does not contain a LIKE special symbol ('%' or '_') the search
             * string will be embedded in %%.
             */
            if (!StringUtils.containsAny(filter, "%_")) {
                filter = "%" + filter + "%";
            }
        }
    }

    return filter;
}

From source file:com.alibaba.otter.shared.common.model.config.ConfigHelper.java

private static boolean isWildCard(String value) {
    return StringUtils.containsAny(value,
            new char[] { '*', '?', '+', '|', '(', ')', '{', '}', '[', ']', '\\', '$', '^', '.' });
}

From source file:net.bible.service.common.CommonUtils.java

/**
 * StringUtils methods only compare with a single char and hence create lots
 * of temporary Strings This method compares with all chars and just creates
 * one new string for each original string. This is to minimise memory
 * overhead & gc.//from   w  w  w. j a v a2s  .co  m
 * 
 * @param str
 * @param removeChars
 * @return
 */
public static String remove(String str, char[] removeChars) {
    if (StringUtils.isEmpty(str) || !StringUtils.containsAny(str, removeChars)) {
        return str;
    }

    StringBuilder r = new StringBuilder(str.length());
    // for all chars in string
    for (int i = 0; i < str.length(); i++) {
        char strCur = str.charAt(i);

        // compare with all chars to be removed
        boolean matched = false;
        for (int j = 0; j < removeChars.length && !matched; j++) {
            if (removeChars[j] == strCur) {
                matched = true;
            }
        }
        // if current char does not match any in the list then add it to the
        if (!matched) {
            r.append(strCur);
        }
    }
    return r.toString();
}

From source file:com.microsoft.alm.plugin.external.commands.Command.java

protected boolean isFilePath(final String line) {
    if (StringUtils.endsWith(line, ":")) {
        // File paths are different on different OSes
        if (StringUtils.containsAny(line, "\\/")) {
            return true;
        }//w  w w  . java 2s.  c o m
    }
    return false;
}

From source file:com.impetus.kundera.query.KunderaQuery.java

/**
 * Inits the entity class./*from   w  w w.  j a  va  2s  .co  m*/
 */
private void initEntityClass() {
    if (from == null) {
        throw new JPQLParseException("Bad query format FROM clause is mandatory for SELECT queries");
    }
    String fromArray[] = from.split(" ");

    if (!this.isDeleteUpdate) {
        if (fromArray.length == 3 && fromArray[1].equalsIgnoreCase("as")) {
            fromArray = new String[] { fromArray[0], fromArray[2] };
        }

        if (fromArray.length != 2) {
            throw new JPQLParseException("Bad query format: " + from
                    + ". Identification variable is mandatory in FROM clause for SELECT queries");
        }

        // TODO
        StringTokenizer tokenizer = new StringTokenizer(result[0], ",");
        while (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();
            if (!StringUtils.containsAny(fromArray[1] + ".", token)) {
                throw new QueryHandlerException("bad query format with invalid alias:" + token);
            }
        }
    }

    this.entityName = fromArray[0];
    if (fromArray.length == 2)
        this.entityAlias = fromArray[1];

    persistenceUnit = kunderaMetadata.getApplicationMetadata().getMappedPersistenceUnit(entityName);

    // Get specific metamodel.
    MetamodelImpl model = getMetamodel(persistenceUnit);

    if (model != null) {
        entityClass = model.getEntityClass(entityName);
    }

    if (null == entityClass) {
        logger.error(
                "No entity {} found, please verify it is properly annotated with @Entity and not a mapped Super class",
                entityName);
        throw new QueryHandlerException("No entity found by the name: " + entityName);
    }

    EntityMetadata metadata = model.getEntityMetadata(entityClass);

    if (metadata != null && !metadata.isIndexable()) {
        throw new QueryHandlerException(entityClass + " is not indexed. Not possible to run a query on it."
                + " Check whether it was properly annotated for indexing.");
    }
}

From source file:com.cloud.hypervisor.vmware.mo.HypervisorHostHelper.java

/**
 * @param ethPortProfileName//from w w  w  .  ja v  a  2 s .co m
 * @param namePrefix
 * @param hostMo
 * @param vlanId
 * @param networkRateMbps
 * @param networkRateMulticastMbps
 * @param timeOutMs
 * @param vSwitchType
 * @param numPorts
 * @param details
 * @return
 * @throws Exception
 */

public static Pair<ManagedObjectReference, String> prepareNetwork(String physicalNetwork, String namePrefix,
        HostMO hostMo, String vlanId, String secondaryvlanId, Integer networkRateMbps,
        Integer networkRateMulticastMbps, long timeOutMs, VirtualSwitchType vSwitchType, int numPorts,
        String gateway, boolean configureVServiceInNexus, BroadcastDomainType broadcastDomainType,
        Map<String, String> vsmCredentials, Map<NetworkOffering.Detail, String> details) throws Exception {
    ManagedObjectReference morNetwork = null;
    VmwareContext context = hostMo.getContext();
    ManagedObjectReference dcMor = hostMo.getHyperHostDatacenter();
    DatacenterMO dataCenterMo = new DatacenterMO(context, dcMor);
    DistributedVirtualSwitchMO dvSwitchMo = null;
    ManagedObjectReference morEthernetPortProfile = null;
    String ethPortProfileName = null;
    ManagedObjectReference morDvSwitch = null;
    String dvSwitchName = null;
    boolean bWaitPortGroupReady = false;
    boolean createGCTag = false;
    String vcApiVersion;
    String minVcApiVersionSupportingAutoExpand;
    boolean autoExpandSupported;
    String networkName;
    Integer vid = null;
    Integer spvlanid = null; // secondary pvlan id

    /** This is the list of BroadcastDomainTypes we can actually
     * prepare networks for in this function.
     */
    BroadcastDomainType[] supportedBroadcastTypes = new BroadcastDomainType[] { BroadcastDomainType.Lswitch,
            BroadcastDomainType.LinkLocal, BroadcastDomainType.Native, BroadcastDomainType.Pvlan,
            BroadcastDomainType.Storage, BroadcastDomainType.UnDecided, BroadcastDomainType.Vlan,
            BroadcastDomainType.Vsp };

    if (!Arrays.asList(supportedBroadcastTypes).contains(broadcastDomainType)) {
        throw new InvalidParameterException("BroadcastDomainType " + broadcastDomainType
                + " it not supported on a VMWare hypervisor at this time.");
    }

    if (broadcastDomainType == BroadcastDomainType.Lswitch) {
        if (vSwitchType == VirtualSwitchType.NexusDistributedVirtualSwitch) {
            throw new InvalidParameterException(
                    "Nexus Distributed Virtualswitch is not supported with BroadcastDomainType "
                            + broadcastDomainType);
        }
        /**
         * Nicira NVP requires all vms to be connected to a single port-group.
         * A unique vlan needs to be set per port. This vlan is specific to
         * this implementation and has no reference to other vlans in CS
         */
        networkName = "br-int"; // FIXME Should be set via a configuration item in CS
        // No doubt about this, depending on vid=null to avoid lots of code below
        vid = null;
    } else {
        if (vlanId != null) {
            vlanId = vlanId.replace("vlan://", "");
        }
        networkName = composeCloudNetworkName(namePrefix, vlanId, secondaryvlanId, networkRateMbps,
                physicalNetwork);

        if (vlanId != null && !UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId)
                && !StringUtils.containsAny(vlanId, ",-")) {
            createGCTag = true;
            vid = Integer.parseInt(vlanId);
        }
        if (vlanId != null && StringUtils.containsAny(vlanId, ",-")) {
            createGCTag = true;
        }
        if (secondaryvlanId != null) {
            spvlanid = Integer.parseInt(secondaryvlanId);
        }
    }

    if (vSwitchType == VirtualSwitchType.VMwareDistributedVirtualSwitch) {
        DVSTrafficShapingPolicy shapingPolicy;
        DVSSecurityPolicy secPolicy;
        vcApiVersion = getVcenterApiVersion(context);
        minVcApiVersionSupportingAutoExpand = "5.0";
        autoExpandSupported = isFeatureSupportedInVcenterApiVersion(vcApiVersion,
                minVcApiVersionSupportingAutoExpand);

        dvSwitchName = physicalNetwork;
        // TODO(sateesh): Remove this after ensuring proper default value for vSwitchName throughout traffic types
        // and switch types.
        if (dvSwitchName == null) {
            s_logger.warn("Detected null dvSwitch. Defaulting to dvSwitch0");
            dvSwitchName = "dvSwitch0";
        }
        morDvSwitch = dataCenterMo.getDvSwitchMor(dvSwitchName);
        if (morDvSwitch == null) {
            String msg = "Unable to find distributed vSwitch " + dvSwitchName;
            s_logger.error(msg);
            throw new Exception(msg);
        } else {
            s_logger.debug("Found distributed vSwitch " + dvSwitchName);
        }

        if (broadcastDomainType == BroadcastDomainType.Lswitch) {
            if (!dataCenterMo.hasDvPortGroup(networkName)) {
                throw new InvalidParameterException("NVP integration port-group " + networkName
                        + " does not exist on the DVS " + dvSwitchName);
            }
            bWaitPortGroupReady = false;
        } else {
            dvSwitchMo = new DistributedVirtualSwitchMO(context, morDvSwitch);

            shapingPolicy = getDVSShapingPolicy(networkRateMbps);
            secPolicy = createDVSSecurityPolicy(details);

            // First, if both vlan id and pvlan id are provided, we need to
            // reconfigure the DVSwitch to have a tuple <vlan id, pvlan id> of
            // type isolated.
            if (vid != null && spvlanid != null) {
                setupPVlanPair(dvSwitchMo, morDvSwitch, vid, spvlanid);
            }

            VMwareDVSPortgroupPolicy portGroupPolicy = null;
            if (broadcastDomainType == BroadcastDomainType.Vsp) {
                //If the broadcastDomainType is Vsp, then set the VMwareDVSPortgroupPolicy
                portGroupPolicy = new VMwareDVSPortgroupPolicy();
                portGroupPolicy.setVlanOverrideAllowed(true);
                portGroupPolicy.setBlockOverrideAllowed(true);
                portGroupPolicy.setPortConfigResetAtDisconnect(true);
            }
            // Next, create the port group. For this, we need to create a VLAN spec.
            createPortGroup(physicalNetwork, networkName, vlanId, vid, spvlanid, dataCenterMo, shapingPolicy,
                    secPolicy, portGroupPolicy, dvSwitchMo, numPorts, autoExpandSupported);
            bWaitPortGroupReady = true;
        }
    } else if (vSwitchType == VirtualSwitchType.NexusDistributedVirtualSwitch) {

        ethPortProfileName = physicalNetwork;
        // TODO(sateesh): Remove this after ensuring proper default value for vSwitchName throughout traffic types
        // and switch types.
        if (ethPortProfileName == null) {
            s_logger.warn("Detected null ethrenet port profile. Defaulting to epp0.");
            ethPortProfileName = "epp0";
        }
        morEthernetPortProfile = dataCenterMo.getDvPortGroupMor(ethPortProfileName);
        if (morEthernetPortProfile == null) {
            String msg = "Unable to find Ethernet port profile " + ethPortProfileName;
            s_logger.error(msg);
            throw new Exception(msg);
        } else {
            s_logger.info("Found Ethernet port profile " + ethPortProfileName);
        }
        long averageBandwidth = 0L;
        if (networkRateMbps != null && networkRateMbps.intValue() > 0) {
            averageBandwidth = networkRateMbps.intValue() * 1024L * 1024L;
        }
        // We chose 50% higher allocation than average bandwidth.
        // TODO(sateesh): Optionally let user specify the peak coefficient
        long peakBandwidth = (long) (averageBandwidth * 1.5);
        // TODO(sateesh): Optionally let user specify the burst coefficient
        long burstSize = 5 * averageBandwidth / 8;
        if (vsmCredentials != null) {
            s_logger.info("Stocking credentials of Nexus VSM");
            context.registerStockObject("vsmcredentials", vsmCredentials);
        }

        if (!dataCenterMo.hasDvPortGroup(networkName)) {
            s_logger.info("Port profile " + networkName + " not found.");
            createPortProfile(context, physicalNetwork, networkName, vid, networkRateMbps, peakBandwidth,
                    burstSize, gateway, configureVServiceInNexus);
            bWaitPortGroupReady = true;
        } else {
            s_logger.info("Port profile " + networkName + " found.");
            updatePortProfile(context, physicalNetwork, networkName, vid, networkRateMbps, peakBandwidth,
                    burstSize);
        }
    }
    // Wait for dvPortGroup on vCenter
    if (bWaitPortGroupReady)
        morNetwork = waitForDvPortGroupReady(dataCenterMo, networkName, timeOutMs);
    else
        morNetwork = dataCenterMo.getDvPortGroupMor(networkName);
    if (morNetwork == null) {
        String msg = "Failed to create guest network " + networkName;
        s_logger.error(msg);
        throw new Exception(msg);
    }

    if (createGCTag) {
        NetworkMO networkMo = new NetworkMO(hostMo.getContext(), morNetwork);
        networkMo.setCustomFieldValue(CustomFieldConstants.CLOUD_GC_DVP, "true");
        s_logger.debug("Added custom field : " + CustomFieldConstants.CLOUD_GC_DVP);
    }

    return new Pair<ManagedObjectReference, String>(morNetwork, networkName);
}

From source file:adalid.commons.util.StrUtils.java

public static String escapeMeta(String string) {
    final char[] meta = { '\\', '^', '$', '.', '*', '+', '?', '|', '-', '&', '{', '}', '[', ']', '(', ')', '<',
            '>' };
    if (StringUtils.containsAny(string, meta)) {
        String s;/* www  .java  2  s  .c  o  m*/
        for (char c : meta) {
            s = String.valueOf(c);
            if (string.contains(s)) {
                string = string.replace(s, "\\" + s);
            }
        }
    }
    return string;
}

From source file:com.thinkaurelius.titan.diskstorage.solr.Solr5Index.java

@Override
public String mapKey2Field(String key, KeyInformation keyInfo) {
    Preconditions.checkArgument(!StringUtils.containsAny(key, new char[] { ' ' }),
            "Invalid key name provided: %s", key);
    if (!dynFields)
        return key;
    if (ParameterType.MAPPED_NAME.hasParameter(keyInfo.getParameters()))
        return key;
    String postfix;//ww w .j av a 2s  .  c o m
    Class datatype = keyInfo.getDataType();
    if (AttributeUtil.isString(datatype)) {
        Mapping map = getStringMapping(keyInfo);
        switch (map) {
        case TEXT:
            postfix = "_t";
            break;
        case STRING:
            postfix = "_s";
            break;
        default:
            throw new IllegalArgumentException("Unsupported string mapping: " + map);
        }
    } else if (AttributeUtil.isWholeNumber(datatype)) {
        if (datatype.equals(Long.class))
            postfix = "_l";
        else
            postfix = "_i";
    } else if (AttributeUtil.isDecimal(datatype)) {
        if (datatype.equals(Float.class))
            postfix = "_f";
        else
            postfix = "_d";
    } else if (datatype.equals(Geoshape.class)) {
        postfix = "_g";
    } else if (datatype.equals(Date.class)) {
        postfix = "_dt";
    } else if (datatype.equals(Boolean.class)) {
        postfix = "_b";
    } else if (datatype.equals(UUID.class)) {
        postfix = "_uuid";
    } else
        throw new IllegalArgumentException("Unsupported data type [" + datatype + "] for field: " + key);
    return key + postfix;
}