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:cn.dockerfoundry.ide.eclipse.dockerfile.validator.DockerfileDelegatingValidator.java

@SuppressWarnings("unchecked")
public Map<DockerfileValidationLevel, List<DockerfileValidationResult>> validate() {
    Map<DockerfileValidationLevel, List<DockerfileValidationResult>> result = new HashMap<DockerfileValidationLevel, List<DockerfileValidationResult>>();
    if (this.dockerfileInputStream == null)
        return result;

    ValidatorUtils validatorUtils = new ValidatorUtils();
    boolean fromCheck = false;
    int currentLine = 0;
    List<DockerfileValidationResult> errors = new ArrayList<DockerfileValidationResult>();
    List<DockerfileValidationResult> warnings = new ArrayList<DockerfileValidationResult>();
    List<DockerfileValidationResult> infos = new ArrayList<DockerfileValidationResult>();

    Map<String, Object> ruleObject = validatorUtils
            .getRules(DockerfileDelegatingValidator.class.getResourceAsStream("default.yaml"));
    List<Map<String, Object>> requiredInstructions = validatorUtils.createReqInstructionHash(ruleObject);
    Map<String, Object> general = (Map<String, Object>) ruleObject.get("general");
    List<String> valid_instructions = (List<String>) general.get("valid_instructions");
    Pattern validInstructionsRegex = validatorUtils.createValidCommandRegex(valid_instructions);
    Pattern continuationRegex = null;
    //      Pattern ignoreRegex = null;
    Object multiline_regex = general.get("multiline_regex");
    if (multiline_regex != null && multiline_regex.toString().length() > 2) {
        String _multiline_regex = multiline_regex.toString().substring(1,
                multiline_regex.toString().length() - 1);
        continuationRegex = Pattern.compile(_multiline_regex, Pattern.CASE_INSENSITIVE);
    }//  ww w.j  a  v  a2  s.c  o m
    Object ignore_regex = general.get("ignore_regex");
    if (ignore_regex != null && ignore_regex.toString().length() > 2) {
        String _ignore_regex = ignore_regex.toString().substring(1, ignore_regex.toString().length() - 1);
        Pattern ignoreRegex = Pattern.compile(_ignore_regex, Pattern.CASE_INSENSITIVE);
        System.out.println("ignore_regex is not used for now: " + ignoreRegex.pattern());
    }

    try {
        String dockerfile = IOUtils.toString(dockerfileInputStream);
        String[] linesArr = dockerfile.split("(\\r|\\n)");
        if (linesArr != null && linesArr.length > 0) {
            for (int i = 0; i < linesArr.length; i++) {
                currentLine++;
                String line = linesArr[i];
                int lineOffSet = 0;
                if (line == null || line.length() == 0 || line.charAt(0) == '#') {
                    continue;
                }

                while (validatorUtils.isPartialLine(line, continuationRegex)) {
                    line = continuationRegex.matcher(line).replaceAll(" ");
                    if (linesArr[currentLine + lineOffSet].charAt(0) == '#') {
                        linesArr[currentLine + lineOffSet] = null;
                        line = line + "\\";
                    } else {
                        line = line + linesArr[currentLine + lineOffSet];
                        linesArr[currentLine + lineOffSet] = null;
                    }
                    lineOffSet++;
                }

                // First instruction must be FROM
                if (!fromCheck) {
                    fromCheck = true;
                    if (line.toUpperCase().indexOf("FROM") != 0) {
                        DockerfileValidationResult error = new DockerfileValidationResult();
                        error.setLine(currentLine);
                        error.setLevel(DockerfileValidationLevel.ERROR);
                        error.setMessage("Missing or misplaced FROM");
                        error.setLineContent(line);
                        errors.add(error);
                    }
                } // end for FROM

                Matcher matcher = validInstructionsRegex.matcher(line);
                if (!matcher.find()) {
                    DockerfileValidationResult error = new DockerfileValidationResult();
                    error.setLine(currentLine);
                    error.setLevel(DockerfileValidationLevel.ERROR);
                    error.setMessage("Invalid instruction");
                    error.setLineContent(line);
                    errors.add(error);
                } else {
                    String instruction = line.substring(matcher.start(), matcher.end()).trim();
                    String params = matcher.replaceAll("");
                    validatorUtils.checkLineRules(ruleObject, instruction, params, line, currentLine, errors,
                            warnings, infos);
                    requiredInstructions.remove(instruction);
                } // end for valid instructions checking
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    validatorUtils.checkRequiredInstructions(requiredInstructions, errors, warnings, infos);

    result.put(DockerfileValidationLevel.ERROR, errors);
    result.put(DockerfileValidationLevel.WARNING, warnings);
    result.put(DockerfileValidationLevel.INFO, infos);
    return result;
}

From source file:org.kuali.kra.questionnaire.answer.SaveQuestionnaireAnswerRule.java

private boolean validateAttributeFormat(Answer answer, String errorKey, int questionIndex) {
    boolean valid = true;

    ValidationPattern validationPattern = VALIDATION_CLASSES
            .get(answer.getQuestion().getQuestionTypeId().toString());

    // if there is no data type matched, then set error ?
    Pattern validationExpression = validationPattern.getRegexPattern();

    String validFormat = getValidFormat(answer.getQuestion().getQuestionTypeId().toString());

    if (validationExpression != null && !".*".equals(validationExpression.pattern())) {
        if (answer.getQuestion().getQuestionTypeId().toString().equals(QUESTION_TYPE_DATE)) {
            if (!answer.getAnswer().matches(DATE_REGEX)) {
                GlobalVariables.getMessageMap().putError(errorKey, RiceKeyConstants.ERROR_INVALID_FORMAT,
                        ANSWER + (questionIndex + 1), answer.getAnswer(), validFormat);
                valid = false;/*from w ww. ja  v  a 2s .  c om*/
            }
        } else if (!validationExpression.matcher(answer.getAnswer()).matches()) {
            GlobalVariables.getMessageMap().putError(errorKey, KeyConstants.ERROR_INVALID_FORMAT_WITH_FORMAT,
                    new String[] { ANSWER + (questionIndex + 1), answer.getAnswer(), validFormat });
            valid = false;
        }
    }
    return valid;
}

From source file:org.kuali.kra.proposaldevelopment.rules.ProposalDevelopmentDataOverrideRule.java

/**
 * //from w  w  w  .  j  av a2 s  . co m
 * This method is to validate the format/length of custom attribute
 * @param customAttribute
 * @param errorKey
 * @return
 */
private boolean validateAttributeFormat(ProposalChangedData proposalOverriddenData,
        DataDictionaryService dataDictionaryService) {
    ProposalDevelopmentService proposalDevelopmentService = KraServiceLocator
            .getService(ProposalDevelopmentService.class);
    DateTimeService dateTimeService = KNSServiceLocator.getDateTimeService();

    String overriddenValue = proposalOverriddenData.getChangedValue();
    String changedValueLabel = dataDictionaryService.getAttributeLabel(ProposalChangedData.class,
            "changedValue");

    String dataType = null;
    Integer maxLength = -1;

    if (proposalOverriddenData.getEditableColumn() != null) {
        dataType = proposalOverriddenData.getEditableColumn().getDataType();
        maxLength = proposalOverriddenData.getEditableColumn().getDataLength();
    }

    ValidationPattern validationPattern = null;

    if (DATE.equalsIgnoreCase(dataType)) {
        try {
            dateTimeService.convertToDate(overriddenValue);
        } catch (ParseException e) {
            GlobalVariables.getErrorMap().putError(Constants.PROPOSALDATA_CHANGED_VAL_KEY,
                    RiceKeyConstants.ERROR_INVALID_FORMAT, new String[] { changedValueLabel, overriddenValue });
            return false;
        }
    } else {
        String validationClassName = validationClasses.get(dataType);
        if (StringUtils.isNotEmpty(validationClassName)) {
            try {
                validationPattern = (ValidationPattern) Class.forName(validationClasses.get(dataType))
                        .newInstance();
                if (dataType.equalsIgnoreCase("STRING")) {
                    ((org.kuali.rice.kns.datadictionary.validation.charlevel.AnyCharacterValidationPattern) validationPattern)
                            .setAllowWhitespace(true);
                }
            } catch (Exception e) {
                throw new RuntimeException(
                        "Error in instantiating a ValidationPatternClass for Proposal Data Overriding", e);
            }
        } else {
            //throw error
        }

        if (validationPattern != null) {
            Pattern validationExpression = validationPattern.getRegexPattern();
            if (validationExpression != null && !validationExpression.pattern().equals(".*")) {
                if (!validationExpression.matcher(overriddenValue).matches()) {
                    GlobalVariables.getErrorMap().putError(Constants.PROPOSALDATA_CHANGED_VAL_KEY,
                            RiceKeyConstants.ERROR_INVALID_FORMAT,
                            new String[] { changedValueLabel, overriddenValue });
                    return false;
                }
            }
        }
    }

    if ((maxLength != null) && (maxLength.intValue() < overriddenValue.length())) {
        GlobalVariables.getErrorMap().putError(Constants.PROPOSALDATA_CHANGED_VAL_KEY,
                RiceKeyConstants.ERROR_MAX_LENGTH, new String[] { changedValueLabel, maxLength.toString() });
        return false;
    }

    Object currentValue = proposalDevelopmentService.getProposalFieldValueFromDBColumnName(
            proposalOverriddenData.getProposalNumber(), proposalOverriddenData.getColumnName());
    String currentValueStr = (currentValue != null) ? currentValue.toString() : "";
    if (DATE.equalsIgnoreCase(proposalOverriddenData.getEditableColumn().getDataType())
            && currentValue != null) {
        currentValueStr = dateTimeService.toString((Date) currentValue, "MM/dd/yyyy");
    }

    if (StringUtils.isNotEmpty(currentValueStr) && currentValueStr.equalsIgnoreCase(overriddenValue)) {
        GlobalVariables.getErrorMap().putError(Constants.PROPOSALDATA_CHANGED_VAL_KEY,
                KeyConstants.PROPOSAL_DATA_OVERRIDE_SAME_VALUE,
                new String[] { proposalOverriddenData.getEditableColumn().getColumnLabel(),
                        (proposalOverriddenData.getDisplayValue() != null)
                                ? proposalOverriddenData.getDisplayValue()
                                : overriddenValue });
        return false;
    }

    return true;
}

From source file:com.edgenius.wiki.render.RenderUtil.java

/**
 * @param input/*from   www. j  a v a 2 s . c  o m*/
 * @param key
 * @param regions
 * @param newlineKey 
 * @return
 */
public static CharSequence createRegion(CharSequence input, String key, Collection<Region> regions,
        String newlineKey) {
    if (regions == null || regions.size() == 0)
        return input;

    //first, web split whole text by special border tag string some think like "key_regionKey_S|E"
    input = createRegionBorder(input, key, regions, newlineKey);

    //then we split them one by one. The split is dependent on the RegionComparator(), which ensure the split 
    //from end to start, and from inside to outside. And this makes easier on below replacement process.
    Set<Region> sortRegions = new TreeSet<Region>(new RegionComparator());
    sortRegions.addAll(regions);

    StringBuilder buf = new StringBuilder(input);
    StringBuilder regKey = new StringBuilder(key);
    int ks = key.length();
    for (Region region : sortRegions) {
        //See our issue http://bug.edgenius.com/issues/34
        //and SUN Java bug: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6337993
        Pattern pat = Pattern.compile(new StringBuilder(key).append(region.getKey()).append("S(.*?)")
                .append(key).append(region.getKey()).append("E").toString(), Pattern.DOTALL);
        try {
            Matcher matcher = pat.matcher(buf);
            if (matcher.find()) {
                region.setBody(matcher.group(1));
                buf.delete(matcher.start(), matcher.end());
                regKey.delete(ks, regKey.length());
                buf.insert(matcher.start(), regKey.append(region.getKey()).append(Region.REGION_SUFFIX));
            }
        } catch (StackOverflowError e) {
            AuditLogger.error("StackOverflow Error in RenderUtil.createRegion. Input[" + buf + "]  Pattern ["
                    + pat.pattern() + "]");
        } catch (Throwable e) {
            AuditLogger.error("Unexpected error in RenderUtil.createRegion. Input[" + buf + "]  Pattern ["
                    + pat.pattern() + "]", e);
        }
    }

    return buf;
}

From source file:org.sakaiproject.webservices.interceptor.RemoteHostMatcher.java

/**
 * Is this HTTP request allowed based on the remote host and the configured allows/denied properties.
 * @param request The HTTP request./*  w w  w  . j  a  v a2 s .  c  o m*/
 * @return <code>true</code> if we should allow access.
 */
public boolean isAllowed(HttpServletRequest request) {

    String host = request.getRemoteHost();
    String addr = request.getRemoteAddr();

    // Check requests that are always allowed ...
    String uri = request.getRequestURI();
    for (String allowedUri : allowRequests) {
        if (StringUtils.startsWith(uri, allowedUri)) {
            if (logAllowed)
                log.info("Access granted for request ({}): {}/{}", uri, host, addr);
            return true;
        }
    }

    // Check if explicit denied ...
    for (Pattern pattern : denyPattern) {
        if (pattern.matcher(host).matches() || pattern.matcher(addr).matches()) {
            if (logDenied)
                log.info("Access denied ({}): {}/{}", pattern.pattern(), host, addr);
            return false;
        }
    }

    // Check if explicitly allowed ...
    for (Pattern pattern : allowPattern) {
        if (pattern.matcher(host).matches() || pattern.matcher(addr).matches()) {
            if (logAllowed)
                log.info("Access granted ({}): {}/{}", pattern.pattern(), host, addr);
            return true;
        }
    }

    // Allow if allows is null, but denied is not
    if ((!denyPattern.isEmpty()) && (allowPattern.isEmpty())) {
        if (logAllowed)
            log.info("Access granted (implicit): {}/{}", host, addr);
        return true;
    }

    // Deny this request
    if (logDenied)
        log.info("Access denied (implicit): {}/{}", host, addr);
    return false;
}

From source file:com.github.javarch.support.SlugGenerator.java

public String encode(String str) {
    Pattern p = Pattern.compile("\\p{InCombiningDiacriticalMarks}+", Pattern.UNICODE_CASE);
    Pattern p2 = Pattern.compile("\\p{Punct}+", Pattern.UNICODE_CASE);
    Pattern p3 = Pattern.compile("\\s+", Pattern.UNICODE_CASE);

    // Decompose any funny characters.
    String link = Normalizer.normalize(str, Normalizer.Form.NFD).replaceAll(p.pattern(), "") // remove all the diacritic marks
            .replaceAll(p2.pattern(), " ").trim() // transform the punctuation into spaces first, so that we can trim some ending or beginning punctuation
            .replaceAll(p3.pattern(), "-") // and replace all the whitespace with a dash.
            .toLowerCase();/*w ww. jav  a2 s . c o  m*/

    return link;
}

From source file:org.nuxeo.ecm.core.opencmis.impl.client.sso.CasPortal.java

protected String extractText(Pattern pattern, String content) {
    Matcher matcher = pattern.matcher(content);
    if (matcher.matches() == false) {
        throw new Error(String.format("Cannot extract '%s' from '%s'", pattern.pattern(), content));
    }/*from   www . java 2s.com*/
    return matcher.group(1);
}

From source file:org.kuali.coeus.propdev.impl.editable.ProposalDevelopmentDataOverrideRule.java

/**
 * //from w w w  . j  a  va 2s.  co m
 * This method is to validate the format/length of custom attribute
 * @param proposalOverriddenData
 * @param dataDictionaryService
 * @return boolean
 */
private boolean validateAttributeFormat(ProposalChangedData proposalOverriddenData,
        DevelopmentProposal developmentProposal, DataDictionaryService dataDictionaryService) {
    ProposalDevelopmentService proposalDevelopmentService = KcServiceLocator
            .getService(ProposalDevelopmentService.class);
    DateTimeService dateTimeService = CoreApiServiceLocator.getDateTimeService();

    String overriddenValue = proposalOverriddenData.getChangedValue();
    String changedValueLabel = dataDictionaryService.getAttributeLabel(ProposalChangedData.class,
            "changedValue");

    String dataType = null;
    Integer maxLength = -1;

    if (proposalOverriddenData.getEditableColumn() != null) {
        dataType = proposalOverriddenData.getEditableColumn().getDataType();
        maxLength = proposalOverriddenData.getEditableColumn().getDataLength();
    }

    ValidationPattern validationPattern = null;

    if (DATE.equalsIgnoreCase(dataType)) {
        try {
            dateTimeService.convertToDate(overriddenValue);
        } catch (ParseException e) {
            GlobalVariables.getMessageMap().putError(Constants.PROPOSALDATA_CHANGED_VAL_KEY,
                    RiceKeyConstants.ERROR_INVALID_FORMAT, new String[] { changedValueLabel, overriddenValue });
            return false;
        }
    } else {
        String validationClassName = validationClasses.get(dataType);
        if (StringUtils.isNotEmpty(validationClassName)) {
            try {
                validationPattern = (ValidationPattern) Class.forName(validationClasses.get(dataType))
                        .newInstance();
                if (dataType.equalsIgnoreCase("STRING")) {
                    ((org.kuali.rice.kns.datadictionary.validation.charlevel.AnyCharacterValidationPattern) validationPattern)
                            .setAllowWhitespace(true);
                }
            } catch (Exception e) {
                throw new RuntimeException(
                        "Error in instantiating a ValidationPatternClass for Proposal Data Overriding", e);
            }
        } else {
            //throw error
        }

        if (validationPattern != null) {
            Pattern validationExpression = validationPattern.getRegexPattern();
            if (validationExpression != null && !validationExpression.pattern().equals(".*")) {
                if (!validationExpression.matcher(overriddenValue).matches()) {
                    GlobalVariables.getMessageMap().putError(Constants.PROPOSALDATA_CHANGED_VAL_KEY,
                            RiceKeyConstants.ERROR_INVALID_FORMAT,
                            new String[] { changedValueLabel, overriddenValue });
                    return false;
                }
            }
        }
    }

    if ((maxLength != null) && (maxLength.intValue() < overriddenValue.length())) {
        GlobalVariables.getMessageMap().putError(Constants.PROPOSALDATA_CHANGED_VAL_KEY,
                RiceKeyConstants.ERROR_MAX_LENGTH, new String[] { changedValueLabel, maxLength.toString() });
        return false;
    }

    try {
        Object currentValue = PropertyUtils.getNestedProperty(developmentProposal,
                proposalOverriddenData.getAttributeName());
        String currentValueStr = (currentValue != null) ? currentValue.toString() : "";
        if (DATE.equalsIgnoreCase(proposalOverriddenData.getEditableColumn().getDataType())
                && currentValue != null) {
            currentValueStr = dateTimeService.toString((Date) currentValue, "MM/dd/yyyy");
        }

        if (StringUtils.isNotEmpty(currentValueStr) && currentValueStr.equalsIgnoreCase(overriddenValue)) {
            GlobalVariables.getMessageMap().putError(Constants.PROPOSALDATA_CHANGED_VAL_KEY,
                    KeyConstants.PROPOSAL_DATA_OVERRIDE_SAME_VALUE,
                    new String[] { proposalOverriddenData.getEditableColumn().getColumnLabel(),
                            (proposalOverriddenData.getDisplayValue() != null)
                                    ? proposalOverriddenData.getDisplayValue()
                                    : overriddenValue });
            return false;
        }
    } catch (Exception e) {
        throw new RuntimeException(
                "Error retrieving " + proposalOverriddenData.getAttributeName() + " from the proposal", e);
    }

    return true;
}

From source file:guru.qas.martini.DefaultMixologistTest.java

@SuppressWarnings("Guava")
@Test//from  w w  w.ja  v  a 2 s  .  c o m
public void testGetParameterizedMartini() throws NoSuchMethodException {
    String id = "Parameterized_Method_Calls:A_Parameterized_Case:25";
    Martini martini = getMartini(id);
    checkState(null != martini, "no Martini found matching ID [%s]", id);

    Map<Step, StepImplementation> stepIndex = martini.getStepIndex();
    Collection<StepImplementation> implementations = stepIndex.values();
    ImmutableList<StepImplementation> filtered = FluentIterable.from(implementations).filter(notNull())
            .filter(Predicates.not(Predicates.instanceOf(UnimplementedStep.class))).toList();
    assertFalse(filtered.isEmpty(), "expected at least one implementation");
    StepImplementation givenImplementation = filtered.get(0);

    Pattern pattern = givenImplementation.getPattern();
    assertNotNull(pattern, "expected implementation to have a Pattern");

    String regex = pattern.pattern();
    assertEquals(regex, "^a pre-existing condition known as \"(.+)\"$", "Pattern contains wrong regex");

    Method method = givenImplementation.getMethod();
    Method expected = ParameterizedTestSteps.class.getDeclaredMethod("aPreExistingConditionKnownAs",
            String.class);
    assertEquals(method, expected, "implementation contains wrong Method");
}

From source file:org.apache.sling.nosql.couchbase.resourceprovider.impl.CouchbaseNoSqlAdapter.java

@Override
public boolean deleteRecursive(String path) {
    Bucket bucket = couchbaseClient.getBucket();
    // fetch all descendants and self for deletion
    Pattern descendantsAndSelf = Pattern.compile("^" + path + "(/.+)?$");
    N1qlQuery query = N1qlQuery.simple(select("*").from(couchbaseClient.getBucketName())
            .where("REGEXP_LIKE(`" + PN_PATH + "`, '" + descendantsAndSelf.pattern() + "')"), N1QL_PARAMS);
    N1qlQueryResult queryResult = bucket.query(query);
    handleQueryError(queryResult);// w  w  w  .j a v a2s  .  co  m
    final Iterator<N1qlQueryRow> results = queryResult.iterator();
    boolean deletedAny = false;
    while (results.hasNext()) {
        JsonObject item = results.next().value();
        JsonObject envelope = item.getObject(couchbaseClient.getBucketName());
        String itemPath = envelope.getString(PN_PATH);
        String itemCacheKey = CouchbaseKey.build(itemPath, cacheKeyPrefix);
        bucket.remove(itemCacheKey);
        deletedAny = true;
    }
    return deletedAny;
}