Example usage for java.util.regex Pattern pattern

List of usage examples for java.util.regex Pattern pattern

Introduction

In this page you can find the example usage for java.util.regex Pattern pattern.

Prototype

pattern

Source Link

Usage

From source file:org.kuali.rice.kns.service.impl.DictionaryValidationServiceImpl.java

/**
 * The attributeDataType parameter should be one of the data types specified by the SearchableAttribute
 * interface; will default to DATA_TYPE_STRING if a data type other than the ones from SearchableAttribute
 * is specified.//from w w  w .j  av a 2  s  .c  o  m
 *
 * @deprecated since 1.1
 */
@Override
@Deprecated
public void validateAttributeFormat(String objectClassName, String attributeName, String attributeInValue,
        String attributeDataType, String errorKey) {
    boolean checkDateBounds = false; // this is used so we can check date bounds
    Class<?> formatterClass = null;

    if (LOG.isDebugEnabled()) {
        LOG.debug("(bo, attributeName, attributeValue) = (" + objectClassName + "," + attributeName + ","
                + attributeInValue + ")");
    }

    /*
    *  This will return a list of searchable attributes. so if the value is
    *  12/07/09 .. 12/08/09 it will return [12/07/09,12/08/09]
    */

    final List<String> attributeValues = SQLUtils.getCleanedSearchableValues(attributeInValue,
            attributeDataType);

    if (attributeValues == null || attributeValues.isEmpty()) {
        return;
    }

    for (String attributeValue : attributeValues) {

        // FIXME: JLR : Replacing this logic with KS-style validation is trickier, since KS validation requires a DataProvider object that can
        // look back and find other attribute values aside from the one we're working on.
        // Also - the date stuff below is implemented very differently.
        //validator.validateAttributeField(businessObject, fieldName);

        if (StringUtils.isNotBlank(attributeValue)) {
            Integer minLength = getDataDictionaryService().getAttributeMinLength(objectClassName,
                    attributeName);
            if ((minLength != null) && (minLength.intValue() > attributeValue.length())) {
                String errorLabel = getDataDictionaryService().getAttributeErrorLabel(objectClassName,
                        attributeName);
                GlobalVariables.getMessageMap().putError(errorKey, RiceKeyConstants.ERROR_MIN_LENGTH,
                        new String[] { errorLabel, minLength.toString() });
                return;
            }
            Integer maxLength = getDataDictionaryService().getAttributeMaxLength(objectClassName,
                    attributeName);
            if ((maxLength != null) && (maxLength.intValue() < attributeValue.length())) {
                String errorLabel = getDataDictionaryService().getAttributeErrorLabel(objectClassName,
                        attributeName);
                GlobalVariables.getMessageMap().putError(errorKey, RiceKeyConstants.ERROR_MAX_LENGTH,
                        new String[] { errorLabel, maxLength.toString() });
                return;
            }
            Pattern validationExpression = getDataDictionaryService()
                    .getAttributeValidatingExpression(objectClassName, attributeName);
            if (validationExpression != null && !validationExpression.pattern().equals(".*")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("(bo, attributeName, validationExpression) = (" + objectClassName + ","
                            + attributeName + "," + validationExpression + ")");
                }

                if (!validationExpression.matcher(attributeValue).matches()) {
                    // Retrieving formatter class
                    if (formatterClass == null) {
                        // this is just a cache check... all dates ranges get called twice
                        formatterClass = getDataDictionaryService().getAttributeFormatter(objectClassName,
                                attributeName);
                    }

                    if (formatterClass != null) {
                        boolean valuesAreValid = true;
                        boolean isError = true;
                        String errorKeyPrefix = "";
                        try {

                            // this is a special case for date ranges in order to set the proper error message
                            if (DateFormatter.class.isAssignableFrom(formatterClass)) {
                                String[] values = attributeInValue.split("\\.\\."); // is it a range
                                if (values.length == 2 && attributeValues.size() == 2) { // make sure it's not like a .. b | c
                                    checkDateBounds = true; // now we need to check that a <= b
                                    if (attributeValues.indexOf(attributeValue) == 0) { // only care about lower bound
                                        errorKeyPrefix = KRADConstants.LOOKUP_RANGE_LOWER_BOUND_PROPERTY_PREFIX;
                                    }
                                }
                            }

                            Method validatorMethod = formatterClass.getDeclaredMethod(VALIDATE_METHOD,
                                    new Class<?>[] { String.class });
                            Object o = validatorMethod.invoke(formatterClass.newInstance(), attributeValue);
                            if (o instanceof Boolean) {
                                isError = !((Boolean) o).booleanValue();
                            }
                            valuesAreValid &= !isError;
                        } catch (Exception e) {
                            if (LOG.isDebugEnabled()) {
                                LOG.debug(e.getMessage(), e);
                            }
                            isError = true;
                            valuesAreValid = false;
                        }
                        if (isError) {
                            checkDateBounds = false; // it's already invalid, no need to check date bounds
                            String errorMessageKey = getDataDictionaryService()
                                    .getAttributeValidatingErrorMessageKey(objectClassName, attributeName);
                            String[] errorMessageParameters = getDataDictionaryService()
                                    .getAttributeValidatingErrorMessageParameters(objectClassName,
                                            attributeName);
                            GlobalVariables.getMessageMap().putError(errorKeyPrefix + errorKey, errorMessageKey,
                                    errorMessageParameters);
                        }
                    } else {
                        // if it fails the default validation and has no formatter class then it's still a std failure.
                        String errorMessageKey = getDataDictionaryService()
                                .getAttributeValidatingErrorMessageKey(objectClassName, attributeName);
                        String[] errorMessageParameters = getDataDictionaryService()
                                .getAttributeValidatingErrorMessageParameters(objectClassName, attributeName);
                        GlobalVariables.getMessageMap().putError(errorKey, errorMessageKey,
                                errorMessageParameters);
                    }
                }
            }
            /*BigDecimal*/
            String exclusiveMin = getDataDictionaryService().getAttributeExclusiveMin(objectClassName,
                    attributeName);
            if (exclusiveMin != null) {
                try {
                    BigDecimal exclusiveMinBigDecimal = new BigDecimal(exclusiveMin);
                    if (exclusiveMinBigDecimal.compareTo(new BigDecimal(attributeValue)) >= 0) {
                        String errorLabel = getDataDictionaryService().getAttributeErrorLabel(objectClassName,
                                attributeName);
                        GlobalVariables.getMessageMap().putError(errorKey, RiceKeyConstants.ERROR_EXCLUSIVE_MIN,
                                // todo: Formatter for currency?
                                new String[] { errorLabel, exclusiveMin.toString() });
                        return;
                    }
                } catch (NumberFormatException e) {
                    // quash; this indicates that the DD contained a min for a non-numeric attribute
                }
            }
            /*BigDecimal*/
            String inclusiveMax = getDataDictionaryService().getAttributeInclusiveMax(objectClassName,
                    attributeName);
            if (inclusiveMax != null) {
                try {
                    BigDecimal inclusiveMaxBigDecimal = new BigDecimal(inclusiveMax);
                    if (inclusiveMaxBigDecimal.compareTo(new BigDecimal(attributeValue)) < 0) {
                        String errorLabel = getDataDictionaryService().getAttributeErrorLabel(objectClassName,
                                attributeName);
                        GlobalVariables.getMessageMap().putError(errorKey, RiceKeyConstants.ERROR_INCLUSIVE_MAX,
                                // todo: Formatter for currency?
                                new String[] { errorLabel, inclusiveMax.toString() });
                        return;
                    }
                } catch (NumberFormatException e) {
                    // quash; this indicates that the DD contained a max for a non-numeric attribute
                }
            }
        }
    }

    if (checkDateBounds) {
        // this means that we only have 2 values and it's a date range.
        java.sql.Timestamp lVal = null;
        java.sql.Timestamp uVal = null;
        try {
            lVal = CoreApiServiceLocator.getDateTimeService().convertToSqlTimestamp(attributeValues.get(0));
            uVal = CoreApiServiceLocator.getDateTimeService().convertToSqlTimestamp(attributeValues.get(1));
        } catch (Exception ex) {
            // this shouldn't happen because the tests passed above.
            String errorMessageKey = getDataDictionaryService()
                    .getAttributeValidatingErrorMessageKey(objectClassName, attributeName);
            String[] errorMessageParameters = getDataDictionaryService()
                    .getAttributeValidatingErrorMessageParameters(objectClassName, attributeName);
            GlobalVariables.getMessageMap().putError(
                    KRADConstants.LOOKUP_RANGE_LOWER_BOUND_PROPERTY_PREFIX + errorKey, errorMessageKey,
                    errorMessageParameters);
        }

        if (lVal != null && lVal.compareTo(uVal) > 0) { // check the bounds
            String errorMessageKey = getDataDictionaryService()
                    .getAttributeValidatingErrorMessageKey(objectClassName, attributeName);
            String[] errorMessageParameters = getDataDictionaryService()
                    .getAttributeValidatingErrorMessageParameters(objectClassName, attributeName);
            GlobalVariables.getMessageMap().putError(
                    KRADConstants.LOOKUP_RANGE_LOWER_BOUND_PROPERTY_PREFIX + errorKey,
                    errorMessageKey + ".range", errorMessageParameters);
        }
    }
}

From source file:org.tinymediamanager.core.tvshow.TvShowEpisodeAndSeasonParser.java

/**
 * Does all the season/episode detection
 * /* w ww .j  a  v a2 s  .  c  o m*/
 * @param name
 *          the RELATIVE filename (like /dir2/seas1/fname.ext) from the TvShowRoot
 * @param showname
 *          the show name
 * @return result the calculated result
 */
public static EpisodeMatchingResult detectEpisodeFromFilenameAlternative(String name, String showname) {
    LOGGER.debug("parsing '" + name + "'");
    EpisodeMatchingResult result = new EpisodeMatchingResult();
    Pattern regex;
    Matcher m;

    // remove problematic strings from name
    String filename = FilenameUtils.getName(name);
    String extension = FilenameUtils.getExtension(name);

    // check for disc files and remove!!
    if (filename.toLowerCase(Locale.ROOT).matches("(video_ts|vts_\\d\\d_\\d)\\.(vob|bup|ifo)") || // dvd
            filename.toLowerCase(Locale.ROOT).matches("(index\\.bdmv|movieobject\\.bdmv|\\d{5}\\.m2ts)")) { // bluray
        name = FilenameUtils.getPath(name);
    }

    String basename = ParserUtils.removeStopwordsAndBadwordsFromTvEpisodeName(name);
    String foldername = "";

    // parse foldername
    regex = Pattern.compile("(.*[\\/\\\\])");
    m = regex.matcher(basename);
    if (m.find()) {
        foldername = m.group(1);
        basename = basename.replaceAll(regex.pattern(), "");
    }

    if (showname != null && !showname.isEmpty()) {
        // remove string like tvshow name (440, 24, ...)
        basename = basename.replaceAll("(?i)^" + Pattern.quote(showname) + "", "");
        basename = basename.replaceAll("(?i) " + Pattern.quote(showname) + " ", "");
    }
    basename = basename.replaceFirst("\\.\\w{1,4}$", ""); // remove extension if 1-4 chars
    basename = basename.replaceFirst("[\\(\\[]\\d{4}[\\)\\]]", ""); // remove (xxxx) or [xxxx] as year

    basename = basename + " ";

    result.stackingMarkerFound = !Utils.getStackingMarker(filename).isEmpty() ? true : false;
    result.name = basename.trim();

    // season detection
    if (result.season == -1) {
        regex = seasonPattern;
        m = regex.matcher(foldername + basename);
        if (m.find()) {
            int s = result.season;
            try {
                s = Integer.parseInt(m.group(2));
            } catch (NumberFormatException nfe) {
                // can not happen from regex since we only come here with max 2 numeric chars
            }
            result.season = s;
            LOGGER.trace("add found season " + s);
        }
    }

    String numbers = basename.replaceAll("[^0-9]", "");
    // try to parse YXX numbers first, and exit (need to do that per length)
    if (numbers.length() == 3) { // eg 102
        regex = numbers3Pattern;
        m = regex.matcher(basename);
        if (m.find()) {
            // Filename contains only 3 subsequent numbers; parse this as SEE
            int s = Integer.parseInt(m.group(1));
            int ep = Integer.parseInt(m.group(2));
            if (ep > 0 && !result.episodes.contains(ep)) {
                result.episodes.add(ep);
                LOGGER.trace("add found EP " + ep);
            }
            LOGGER.trace("add found season " + s);
            result.season = s;
            return result;
        } else {
            // check if we have at least 2 subsequent numbers - parse this as episode
            regex = numbers2Pattern;
            m = regex.matcher(basename);
            if (m.find()) {
                // Filename contains only 2 subsequent numbers; parse this as EE
                int ep = Integer.parseInt(m.group(1));
                if (ep > 0 && !result.episodes.contains(ep)) {
                    result.episodes.add(ep);
                    LOGGER.trace("add found EP " + ep);
                }
                // return result; // do NOT return here, although we have 3 numbers (2 subsequent) we might parse the correct season later
            }
        }
    } // FIXME: what if we have
    else if (numbers.length() == 2) { // eg 01
        regex = numbers2Pattern;
        m = regex.matcher(basename);
        if (m.find()) {
            // Filename contains only 2 subsequent numbers; parse this as EE
            int ep = Integer.parseInt(m.group(1));
            if (ep > 0 && !result.episodes.contains(ep)) {
                result.episodes.add(ep);
                LOGGER.trace("add found EP " + ep);
            }
            return result;
        }
    } else if (numbers.length() == 1) { // eg 1
        int ep = Integer.parseInt(numbers); // just one :P
        if (ep > 0 && !result.episodes.contains(ep)) {
            result.episodes.add(ep);
            LOGGER.trace("add found EP " + ep);
        }
        return result;
    }

    // parse SxxEPyy 1-N
    regex = seasonMultiEP;
    m = regex.matcher(foldername + basename);
    int lastFoundEpisode = 0;
    while (m.find()) {
        int s = -1;
        try {
            s = Integer.parseInt(m.group(1));
            String eps = m.group(2); // name.s01"ep02-02-04".ext
            // now we have a string of 1-N episodes - parse them
            Pattern regex2 = episodePattern; // episode fixed to 1-2 chars
            Matcher m2 = regex2.matcher(eps);
            while (m2.find()) {
                int ep = 0;
                try {
                    ep = Integer.parseInt(m2.group(1));
                } catch (NumberFormatException nfe) {
                    // can not happen from regex since we only come here with max 2 numeric chars
                }
                // check if the found episode is greater zero, not already in the list and if multi episode
                // it has to be the next number than the previous found one
                if (ep > 0 && !result.episodes.contains(ep)
                        && (lastFoundEpisode == 0 || lastFoundEpisode + 1 == ep)) {
                    lastFoundEpisode = ep;
                    result.episodes.add(ep);
                    LOGGER.trace("add found EP " + ep);
                }
            }
        } catch (NumberFormatException nfe) {
            // can not happen from regex since we only come here with max 2 numeric chars
        }
        if (s >= 0) {
            result.season = s;
            LOGGER.trace("add found season " + s);
        }
    }

    // parse XYY or XX_YY 1-N
    regex = seasonMultiEP2;
    m = regex.matcher(foldername + basename);
    while (m.find()) {
        int s = -1;
        try {
            // for the case of name.1x02x03.ext
            if (m.group(2) != null && result.season == -1) {
                s = Integer.parseInt(m.group(1));
            }
            String eps = m.group(2); // name.s01"ep02-02-04".ext
            // now we have a string of 1-N episodes - parse them
            Pattern regex2 = episodePattern; // episode fixed to 1-2 chars
            Matcher m2 = regex2.matcher(eps);
            while (m2.find()) {
                int ep = 0;
                try {
                    ep = Integer.parseInt(m2.group(1));
                } catch (NumberFormatException nfe) {
                    // can not happen from regex since we only come here with max 2 numeric chars
                }
                if (ep > 0 && !result.episodes.contains(ep)) {
                    result.episodes.add(ep);
                    LOGGER.trace("add found EP " + ep);
                }
            }
        } catch (NumberFormatException nfe) {
            // can not happen from regex since we only come here with max 2 numeric chars
        }
        if (s >= 0) {
            result.season = s;
            LOGGER.trace("add found season " + s);
        }
    }

    // Episode-only parsing, when previous styles didn't find anything!
    if (result.episodes.isEmpty()) {
        regex = episodePattern2;
        m = regex.matcher(basename);
        while (m.find()) {
            int ep = 0;
            try {
                ep = Integer.parseInt(m.group(1));
            } catch (NumberFormatException nfe) {
                // can not happen from regex since we only come here with max 2 numeric chars
            }
            if (ep > 0 && !result.episodes.contains(ep)) {
                result.episodes.add(ep);
                LOGGER.trace("add found EP " + ep);
            }
        }
    }

    // Episode-only parsing, when previous styles didn't find anything!
    // this is a VERY generic pattern!!!
    if (result.episodes.isEmpty()) {
        regex = episodePattern;
        m = regex.matcher(basename);
        while (m.find()) {
            int ep = 0;
            try {
                ep = Integer.parseInt(m.group(1));
            } catch (NumberFormatException nfe) {
                // can not happen from regex since we only come here with max 2 numeric chars
            }
            if (ep > 0 && !result.episodes.contains(ep)) {
                result.episodes.add(ep);
                LOGGER.trace("add found EP " + ep);
            }
        }
    }

    // parse Roman only when not found anything else!!
    if (result.episodes.isEmpty()) {
        regex = romanPattern;
        m = regex.matcher(basename);
        while (m.find()) {
            int ep = 0;
            ep = decodeRoman(m.group(2));
            if (ep > 0 && !result.episodes.contains(ep)) {
                result.episodes.add(ep);
                LOGGER.trace("add found EP " + ep);
            }
        }
    }

    if (result.season == -1) {
        // Date1 pattern yyyy-mm-dd
        m = date1.matcher(basename);
        if (m.find()) {
            int s = result.season;
            try {
                s = Integer.parseInt(m.group(1));
                result.date = new SimpleDateFormat("yyyy-MM-dd")
                        .parse(m.group(1) + "-" + m.group(2) + "-" + m.group(3));
            } catch (NumberFormatException | ParseException nfe) {
                // can not happen from regex since we only come here with max 2 numeric chars
            }
            result.season = s;
            LOGGER.trace("add found year as season " + s);
        }
    }

    if (result.season == -1) {
        // Date2 pattern dd-mm-yyyy
        m = date2.matcher(basename);
        if (m.find()) {
            int s = result.season;
            try {
                s = Integer.parseInt(m.group(3));
                result.date = new SimpleDateFormat("dd-MM-yyyy")
                        .parse(m.group(1) + "-" + m.group(2) + "-" + m.group(3));
            } catch (NumberFormatException | ParseException nfe) {
                // can not happen from regex since we only come here with max 2 numeric chars
            }
            result.season = s;
            LOGGER.trace("add found year as season " + s);
        }
    }

    Collections.sort(result.episodes);
    LOGGER.debug("returning result " + result);
    return result;
}

From source file:org.tinymediamanager.core.Utils.java

/**
 * replaces a string with placeholder ({}) with the string from the replacement array the strings in the replacement array have to be in the same
 * order as the placeholder in the source string
 * //w  w w .  j a  v a 2  s.c  o m
 * @param source
 *          string
 * @param replacements
 *          array
 * @return replaced string
 */
public static String replacePlaceholders(String source, String[] replacements) {
    String result = source;
    int index = 0;

    Pattern pattern = Pattern.compile("\\{\\}");
    while (true) {
        Matcher matcher = pattern.matcher(result);
        if (matcher.find()) {
            try {
                // int index = Integer.parseInt(matcher.group(1));
                if (replacements.length > index) {
                    result = result.replaceFirst(pattern.pattern(),
                            StringEscapeUtils.escapeJava(replacements[index]));
                } else {
                    result = result.replaceFirst(pattern.pattern(), "");
                }
            } catch (Exception e) {
                result = result.replaceFirst(pattern.pattern(), "");
            }
            index++;
        } else {
            break;
        }
    }
    return StrgUtils.removeDuplicateWhitespace(result);
}

From source file:de.undercouch.bson4jackson.BsonGenerator.java

/**
 * Write a BSON regex//from  www. ja v a2  s. c o  m
 *
 * @param pattern The regex to write
 * @throws IOException If an error occurred in the stream while writing
 */
public void writeRegex(Pattern pattern) throws IOException {
    _writeArrayFieldNameIfNeeded();
    _verifyValueWrite("write regex");
    _buffer.putByte(_typeMarker, BsonConstants.TYPE_REGEX);
    _writeCString(pattern.pattern());
    _writeCString(flagsToRegexOptions(pattern.flags()));
    flushBuffer();
}

From source file:org.kuali.rice.kns.datadictionary.validation.AttributeValidatingTypeServiceBase.java

/**
 * <p>Validates the format of the value for the given attribute field.</p>
 * <p>This implementation checks if the attribute value is not blank, in which case it checks (as applicable) the
 * max length, min length, min value, max value, and format (using the {@link Pattern} returned by
 * {@link #getAttributeValidatingExpression(org.kuali.rice.core.api.uif.RemotableAttributeField)}).  If that doesn't
 * match, it will use the Formatter returned by
 * {@link #getAttributeFormatter(org.kuali.rice.core.api.uif.RemotableAttributeField)} to format the value and try
 * matching against it again.  For each format error that is found,
 * {@link #createErrorString(String, String...)} is called to prepare the text for the
 * {@link RemotableAttributeError} that is generated.
 *
 * @param field the field for the attribute whose value we are validating
 * @param objectClassName the name of the class to which the attribute belongs
 * @param attributeName the name of the attribute
 * @param attributeValue the String value whose format we are validating
 * @param errorKey the name of the property on the object class that this attribute maps to
 * @return a List containing any errors ({@link RemotableAttributeError}s) that are detected.
 *///from ww w  .  j a v a 2  s  .  c o m
protected List<RemotableAttributeError> validateAttributeFormat(RemotableAttributeField field,
        String objectClassName, String attributeName, String attributeValue, String errorKey) {
    List<RemotableAttributeError> errors = new ArrayList<RemotableAttributeError>();

    String errorLabel = getAttributeErrorLabel(field);

    if (LOG.isDebugEnabled()) {
        LOG.debug("(bo, attributeName, attributeValue) = (" + objectClassName + "," + attributeName + ","
                + attributeValue + ")");
    }

    if (StringUtils.isNotBlank(attributeValue)) {
        Integer maxLength = field.getMaxLength();
        if ((maxLength != null) && (maxLength.intValue() < attributeValue.length())) {
            errors.add(RemotableAttributeError.Builder.create(errorKey,
                    createErrorString(RiceKeyConstants.ERROR_MAX_LENGTH, errorLabel, maxLength.toString()))
                    .build());
            return errors;
        }
        Integer minLength = field.getMinLength();
        if ((minLength != null) && (minLength.intValue() > attributeValue.length())) {
            errors.add(RemotableAttributeError.Builder.create(errorKey,
                    createErrorString(RiceKeyConstants.ERROR_MIN_LENGTH, errorLabel, minLength.toString()))
                    .build());
            return errors;
        }
        Pattern validationExpression = getAttributeValidatingExpression(field);
        if (!ANY_CHAR_PATTERN_S.equals(validationExpression.pattern())) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("(bo, attributeName, validationExpression) = (" + objectClassName + ","
                        + attributeName + "," + validationExpression + ")");
            }

            if (!validationExpression.matcher(attributeValue).matches()) {
                boolean isError = true;
                final Formatter formatter = getAttributeFormatter(field);
                if (formatter != null) {
                    Object o = formatter.format(attributeValue);
                    isError = !validationExpression.matcher(String.valueOf(o)).matches();
                }
                if (isError) {
                    errors.add(RemotableAttributeError.Builder
                            .create(errorKey, createErrorString(field.getRegexContraintMsg(), errorLabel))
                            .build());
                }
                return errors;
            }
        }
        Double min = field.getMinValue();
        if (min != null) {
            try {
                if (Double.parseDouble(attributeValue) < min) {
                    errors.add(RemotableAttributeError.Builder.create(errorKey,
                            createErrorString(RiceKeyConstants.ERROR_INCLUSIVE_MIN, errorLabel, min.toString()))
                            .build());
                    return errors;
                }
            } catch (NumberFormatException e) {
                // quash; this indicates that the DD contained a min for a non-numeric attribute
            }
        }
        Double max = field.getMaxValue();
        if (max != null) {
            try {

                if (Double.parseDouble(attributeValue) > max) {
                    errors.add(RemotableAttributeError.Builder.create(errorKey,
                            createErrorString(RiceKeyConstants.ERROR_INCLUSIVE_MAX, errorLabel, max.toString()))
                            .build());
                    return errors;
                }
            } catch (NumberFormatException e) {
                // quash; this indicates that the DD contained a max for a non-numeric attribute
            }
        }
    }
    return errors;
}

From source file:AndroidUninstallStock.java

private static LinkedHashMap<String, String> _getListFromPattern(LinkedHashMap<String, String> apkorliblist,
        HashMap<String, String> pattern, AusInfo info, String status, boolean library) {
    LinkedHashMap<String, String> res = new LinkedHashMap<String, String>();
    if (library && !pattern.get("in").equalsIgnoreCase("library")) {
        return res;
    }/*w  w  w  .  j  a v  a 2 s . com*/
    int flags = getBoolean(pattern.get("case-insensitive")) ? Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE
            : 0;
    try {
        Pattern pat = Pattern.compile(getBoolean(pattern.get("regexp")) ? pattern.get("pattern")
                : Pattern.quote(pattern.get("pattern")), flags);
        for (Map.Entry<String, String> apk : apkorliblist.entrySet()) {
            String need = "";
            switch (pattern.get("in")) {
            case "library": // TODO well as to specify the pattern package...
            case "path":
                need = apk.getKey();
                break;
            case "path+package":
                need = apk.getKey() + apk.getValue();
                break;
            case "apk":
                need = apk.getKey().substring(apk.getKey().lastIndexOf('/') + 1);
                break;
            case "package":
            default:
                need = apk.getValue();
                break;
            }
            if (pat.matcher(need).find()) {
                res.put(apk.getKey(), apk.getValue());
                System.out.println(status + need + " - " + pat.pattern());
            }
        }
    } catch (PatternSyntaxException e) {
        System.out.println("Warring in: " + info + " pattern: " + e);
    }
    return res;
}

From source file:org.yamj.filescanner.ScannerManagementImpl.java

/**
 * Scan a directory (and recursively any other directories contained
 *
 * @param library//from w  w w  . ja v  a 2 s . c om
 * @param parentDto
 * @param directory
 */
private StageDirectoryDTO scanDir(Library library, File directory) {
    DirectoryType dirType = DirectoryEnding.check(directory);
    StageDirectoryDTO stageDir;

    LOG.info("Scanning directory '{}', detected type - {}", library.getRelativeDir(directory), dirType);

    if (dirType == DirectoryType.BLURAY || dirType == DirectoryType.DVD) {
        // Don't scan BLURAY or DVD structures
        LOG.info("Skipping directory '{}' as its a {} type", directory.getAbsolutePath(), dirType);
        library.getStatistics().increment(dirType == DirectoryType.BLURAY ? StatType.BLURAY : StatType.DVD);
        stageDir = null;
    } else if (DIR_EXCLUSIONS.containsKey(directory.getName().toLowerCase())) {
        LOG.info("Skipping directory '{}' as its in the exclusion list.", directory.getAbsolutePath());
        stageDir = null;
    } else {
        try {
            if (FileUtils.directoryContains(directory, new File(directory, FILE_MJBIGNORE))) {
                LOG.debug("Exclusion file '{}' found, skipping scanning of directory {}.", FILE_MJBIGNORE,
                        directory.getName());
                return null;
            }
        } catch (IOException ex) {
            LOG.trace("Failed to seach for '{}' in the directory {}", FILE_MJBIGNORE, directory.getName());
        }

        stageDir = new StageDirectoryDTO();
        stageDir.setPath(directory.getAbsolutePath());
        stageDir.setDate(directory.lastModified());

        library.getStatistics().increment(StatType.DIRECTORY);

        List<File> currentFileList = Arrays.asList(directory.listFiles());
        FileTypeComparator comp = new FileTypeComparator(Boolean.FALSE);
        Collections.sort(currentFileList, comp);

        /*
         * We need to scan the directory and look for any of the exclusion filenames.
         *
         * We then build a list of those excluded extensions, so that when we scan the filename list we can exclude the unwanted files.
         */
        List<String> exclusions = new ArrayList<String>();
        for (File file : currentFileList) {
            if (file.isFile()) {
                String lcFilename = file.getName().toLowerCase();
                if (DIR_EXCLUSIONS.containsKey(lcFilename)) {
                    if (CollectionUtils.isEmpty(DIR_EXCLUSIONS.get(lcFilename))) {
                        // Because the value is null or empty we exclude the whole directory, so quit now.
                        LOG.debug("Exclusion file '{}' found, skipping scanning of directory {}.", lcFilename,
                                file.getParent());
                        // All files to be excluded, so quit
                        return null;
                    } else {
                        // We found a match, so add it to our local copy
                        LOG.debug("Exclusion file '{}' found, will exclude all {} file types", lcFilename,
                                DIR_EXCLUSIONS.get(lcFilename).toString());
                        exclusions.addAll(DIR_EXCLUSIONS.get(lcFilename));
                        // Skip to the next file, theres no need of further processing
                        continue;
                    }
                }
            } else {
                // First directory we find, we can stop (because we sorted the files first)
                break;
            }
        }

        // Create a precompiled Matcher for use later (Doesn't matter what the values are)
        Matcher matcher = Pattern.compile(FILE_MJBIGNORE).matcher(FILE_MJBIGNORE);

        // Scan the directory properly
        for (File file : currentFileList) {
            boolean excluded = Boolean.FALSE;
            if (file.isFile()) {
                String lcFilename = file.getName().toLowerCase();
                if (exclusions.contains(FilenameUtils.getExtension(lcFilename))
                        || DIR_EXCLUSIONS.containsKey(lcFilename)) {
                    LOG.debug(
                            "File name '{}' excluded because it's listed in the exlusion list for this directory",
                            file.getName());
                    continue;
                }

                // Process the DIR_IGNORE_FILES
                for (Pattern pattern : DIR_IGNORE_FILES) {
                    matcher.reset(lcFilename).usePattern(pattern);
                    if (matcher.matches()) {
                        // Found the file pattern, so skip the file
                        LOG.debug("File name '{}' excluded because it matches exlusion pattern '{}'",
                                file.getName(), pattern.pattern());
                        excluded = Boolean.TRUE;
                        break;
                    }
                }

                if (!excluded) {
                    stageDir.addStageFile(scanFile(file));
                    library.getStatistics().increment(StatType.FILE);
                }
            } else {
                // First directory we find, we can stop (because we sorted the files first)
                break;
            }
        }

        library.addDirectory(stageDir);
        queueForSending(library, stageDir);

        // Resort the files with directories first
        comp.setDirectoriesFirst(Boolean.TRUE);
        Collections.sort(currentFileList, comp);

        // Now scan the directories
        for (File scanDir : currentFileList) {
            if (scanDir.isDirectory()) {
                if (scanDir(library, scanDir) == null) {
                    LOG.info("Not adding directory '{}', no files found or all excluded",
                            scanDir.getAbsolutePath());
                }
            } else {
                // First file we find, we can stop (because we are sorted directories first)
                break;
            }
        }
    }
    return stageDir;
}

From source file:org.codehaus.mojo.license.DefaultDependenciesTool.java

protected boolean isIncludable(Artifact project, Pattern includedGroupPattern,
        Pattern includedArtifactPattern) {

    Logger log = getLogger();//  ww w  .ja v a 2s.c  o  m

    // check if the groupId of the project should be included
    if (includedGroupPattern != null) {
        // we have some defined license filters
        try {
            Matcher matchGroupId = includedGroupPattern.matcher(project.getGroupId());
            if (matchGroupId.find()) {
                if (log.isDebugEnabled()) {
                    log.debug("Include " + project.getGroupId());
                }
                return true;
            }
        } catch (PatternSyntaxException e) {
            log.warn(String.format(INVALID_PATTERN_MESSAGE, includedGroupPattern.pattern()));
        }
    }

    // check if the artifactId of the project should be included
    if (includedArtifactPattern != null) {
        // we have some defined license filters
        try {
            Matcher matchGroupId = includedArtifactPattern.matcher(project.getArtifactId());
            if (matchGroupId.find()) {
                if (log.isDebugEnabled()) {
                    log.debug("Include " + project.getArtifactId());
                }
                return true;
            }
        } catch (PatternSyntaxException e) {
            log.warn(String.format(INVALID_PATTERN_MESSAGE, includedArtifactPattern.pattern()));
        }
    }

    return false;
}

From source file:org.codehaus.mojo.license.DefaultDependenciesTool.java

protected boolean isExcludable(Artifact project, Pattern excludedGroupPattern,
        Pattern excludedArtifactPattern) {

    Logger log = getLogger();/*  www  .  ja v  a2 s  . c  o  m*/

    // check if the groupId of the project should be included
    if (excludedGroupPattern != null) {
        // we have some defined license filters
        try {
            Matcher matchGroupId = excludedGroupPattern.matcher(project.getGroupId());
            if (matchGroupId.find()) {
                if (log.isDebugEnabled()) {
                    log.debug("Exclude " + project.getGroupId());
                }
                return true;
            }
        } catch (PatternSyntaxException e) {
            log.warn(String.format(INVALID_PATTERN_MESSAGE, excludedGroupPattern.pattern()));
        }
    }

    // check if the artifactId of the project should be included
    if (excludedArtifactPattern != null) {
        // we have some defined license filters
        try {
            Matcher matchGroupId = excludedArtifactPattern.matcher(project.getArtifactId());
            if (matchGroupId.find()) {
                if (log.isDebugEnabled()) {
                    log.debug("Exclude " + project.getArtifactId());
                }
                return true;
            }
        } catch (PatternSyntaxException e) {
            log.warn(String.format(INVALID_PATTERN_MESSAGE, excludedArtifactPattern.pattern()));
        }
    }

    return false;
}

From source file:org.codehaus.mojo.license.api.DefaultDependenciesTool.java

/**
 * Tests if the given project is includeable against a groupdId pattern and a artifact pattern.
 *
 * @param project                 the project to test
 * @param includedGroupPattern    the include group pattern
 * @param includedArtifactPattern the include artifact pattenr
 * @return {@code true} if the project is includavble, {@code false} otherwise
 *//*from w  w w  .jav  a 2  s . co m*/
protected boolean isIncludable(Artifact project, Pattern includedGroupPattern,
        Pattern includedArtifactPattern) {

    Logger log = getLogger();

    // check if the groupId of the project should be included
    if (includedGroupPattern != null) {
        // we have some defined license filters
        try {
            Matcher matchGroupId = includedGroupPattern.matcher(project.getGroupId());
            if (matchGroupId.find()) {
                if (log.isDebugEnabled()) {
                    log.debug("Include " + project.getGroupId());
                }
                return true;
            }
        } catch (PatternSyntaxException e) {
            log.warn(String.format(INVALID_PATTERN_MESSAGE, includedGroupPattern.pattern()));
        }
    }

    // check if the artifactId of the project should be included
    if (includedArtifactPattern != null) {
        // we have some defined license filters
        try {
            Matcher matchGroupId = includedArtifactPattern.matcher(project.getArtifactId());
            if (matchGroupId.find()) {
                if (log.isDebugEnabled()) {
                    log.debug("Include " + project.getArtifactId());
                }
                return true;
            }
        } catch (PatternSyntaxException e) {
            log.warn(String.format(INVALID_PATTERN_MESSAGE, includedArtifactPattern.pattern()));
        }
    }
    return false;
}