List of usage examples for java.util.regex Pattern pattern
pattern
From source file:org.pentaho.platform.plugin.services.importexport.PentahoMetadataFileInfo.java
public PentahoMetadataFileInfo(final String path) { this.path = path; this.fileType = UNKNOWN; final String internalPath = RepositoryFilenameUtils.normalize(path, true); if (!StringUtils.isEmpty(internalPath)) { final String fileExtension = RepositoryFilenameUtils.getExtension(path); if (StringUtils.equals(fileExtension, "xmi")) { for (final Pattern xmiPattern : xmiPatterns) { final Matcher xmiMatcher = xmiPattern.matcher(internalPath); if (xmiMatcher.matches()) { log.trace("MATCH: [" + internalPath + "] by [" + xmiPattern.pattern() + "] - group(s)=[" + xmiMatcher.group(1) + "]"); initialize(FileType.XMI, xmiMatcher.group(1), null); break; }//from ww w . ja va 2s .co m } } else if (StringUtils.equals(fileExtension, "properties")) { for (final Pattern propertyBundlePattern : propertyBundlePatternsNoPostfix) { final Matcher propertyBundleMatcher = propertyBundlePattern.matcher(internalPath); if (propertyBundleMatcher.matches()) { log.trace("MATCH: [" + internalPath + "] by [" + propertyBundleMatcher.pattern() + "] - group(s)=[" + propertyBundleMatcher.group(1) + " : " + propertyBundleMatcher.group(2) + "]"); initialize(FileType.PROPERTIES, propertyBundleMatcher.group(1), propertyBundleMatcher.group(2)); break; } } for (final Pattern propertyBundlePattern : propertyBundlePatternsWithPostfix) { final Matcher propertyBundleMatcher = propertyBundlePattern.matcher(internalPath); if (propertyBundleMatcher.matches()) { log.trace("MATCH: [" + internalPath + "] by [" + propertyBundleMatcher.pattern() + "] - group(s)=[" + propertyBundleMatcher.group(1) + " : " + propertyBundleMatcher.group(2) + "]"); initialize(FileType.PROPERTIES, propertyBundleMatcher.group(1) + PROPERTY_BUNDLE_DOMAIN_POSTFIX, propertyBundleMatcher.group(2)); break; } } } } }
From source file:org.jboss.windup.interrogator.util.KnownArchiveProfiler.java
public boolean isExclusivelyKnownArchive(ZipMetadata archive) { String extension = archive.getFilePointer().getAbsolutePath(); extension = StringUtils.substringAfterLast(extension, "."); if (!StringUtils.equalsIgnoreCase(extension, "jar")) { return false; }// w w w. j av a 2s . c o m VendorResult vr = null; // this should only be true if: // 1) the package does not contain *any* customer packages. // 2) the package contains "known" vendor packages. boolean exclusivelyKnown = false; Enumeration<?> e = archive.getZipFile().entries(); // go through all entries... ZipEntry entry; while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); String entryName = getClassNameFromFile(entry.getName()); // if the package isn't current "known", try to match against known packages for this entry. if (!exclusivelyKnown) { for (Pattern cbl : knownPackages.keySet()) { if (cbl.matcher(entryName).find()) { if (LOG.isDebugEnabled()) { LOG.debug("Found known package: " + entry.getName() + " matching: " + cbl.pattern()); } String vendor = knownPackages.get(cbl); LOG.debug("Known Package: " + archive.getName() + "; Vendor: " + vendor); exclusivelyKnown = true; vr = new VendorResult(); vr.setDescription(vendor); // no reason to check other patterns. break; } } } // check each entry to see if it is a customer package. if (customerPackageResolver.isCustomerPkg(entryName)) { // if it is a customer package, then we want to basically say, this is not exclusively a known package. // we can stop all other processing. return false; } } if (exclusivelyKnown && vr != null) { archive.getDecorations().add(vr); } // otherwise, return the evaluated exclusively known value. return exclusivelyKnown; }
From source file:edu.vt.middleware.servlet.filter.RequestMethodFilter.java
/** * This verifies that the supplied result matches the expected result for the * supplied method name. This method returns true if result is null; * * @param name of invoked method//w w w .j a va 2s. co m * @param result of method invocation * * @return whether the supplied result is valid */ private boolean verifyResult(final String name, final String result) { boolean success = false; if (result != null) { final Pattern pattern = this.patterns.get(name); if (!pattern.matcher(result).matches()) { if (LOG.isDebugEnabled()) { LOG.debug(result + " does not match " + pattern.pattern()); } } else { if (LOG.isDebugEnabled()) { LOG.debug(result + " matches " + pattern.pattern()); } success = true; } } else { success = true; } return success; }
From source file:org.kuali.kra.proposaldevelopment.rules.ProposalBudgetDataOverrideRule.java
/** * //w w w .jav a 2s. co m * This method is to validate the format/length of custom attribute * @param customAttribute * @param errorKey * @return */ private boolean validateAttributeFormat(BudgetChangedData budgetOverriddenData, DataDictionaryService dataDictionaryService) { ProposalDevelopmentService proposalDevelopmentService = KraServiceLocator .getService(ProposalDevelopmentService.class); DateTimeService dateTimeService = CoreApiServiceLocator.getDateTimeService(); String overriddenValue = budgetOverriddenData.getChangedValue(); String changedValueLabel = dataDictionaryService.getAttributeLabel(BudgetChangedData.class, "changedValue"); String dataType = null; Integer maxLength = -1; if (budgetOverriddenData.getEditableColumn() != null) { dataType = budgetOverriddenData.getEditableColumn().getDataType(); maxLength = budgetOverriddenData.getEditableColumn().getDataLength(); } ValidationPattern validationPattern = null; if (DATE.equalsIgnoreCase(dataType)) { try { dateTimeService.convertToDate(overriddenValue); } catch (ParseException e) { GlobalVariables.getMessageMap().putError(Constants.BUDGETDATA_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 Budget 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.BUDGETDATA_CHANGED_VAL_KEY, RiceKeyConstants.ERROR_INVALID_FORMAT, new String[] { changedValueLabel, overriddenValue }); return false; } } } } BusinessObjectService boService = KraServiceLocator.getService(BusinessObjectService.class); Map<String, String> documentMap = new HashMap<String, String>(); documentMap.put("proposalNumber", budgetOverriddenData.getProposalNumber()); DevelopmentProposal developmentProposal = boService.findByPrimaryKey(DevelopmentProposal.class, documentMap); Map budgetMap = new HashMap(); budgetMap.put("parentDocumentKey", developmentProposal.getProposalDocument().getDocumentNumber()); BudgetDocument budgetDocument = null; Collection<BudgetDocument> budgetDocuments = boService.findMatching(BudgetDocument.class, budgetMap); for (BudgetDocument document : budgetDocuments) { if (document.getBudget().getFinalVersionFlag()) { budgetDocument = document; break; } } Object currentValue = proposalDevelopmentService.getBudgetFieldValueFromDBColumnName( budgetDocument.getDocumentNumber(), budgetOverriddenData.getColumnName()); if (currentValue instanceof BudgetDecimal) { try { Double overriddenValueToInt = Double.parseDouble(overriddenValue); } catch (Exception e) { GlobalVariables.getMessageMap().putError(Constants.BUDGETDATA_CHANGED_VAL_KEY, RiceKeyConstants.ERROR_NUMBER, new String[] { changedValueLabel, overriddenValue }); return false; } } if ((maxLength != null) && (maxLength.intValue() < overriddenValue.length())) { if (!(currentValue instanceof Boolean)) { GlobalVariables.getMessageMap().putError(Constants.BUDGETDATA_CHANGED_VAL_KEY, RiceKeyConstants.ERROR_MAX_LENGTH, new String[] { changedValueLabel, maxLength.toString() }); return false; } } String currentValueStr = (currentValue != null) ? currentValue.toString() : ""; if (DATE.equalsIgnoreCase(budgetOverriddenData.getEditableColumn().getDataType()) && currentValue != null) { currentValueStr = dateTimeService.toString((Date) currentValue, "MM/dd/yyyy"); } if (StringUtils.isNotEmpty(currentValueStr) && currentValueStr.equalsIgnoreCase(overriddenValue)) { if (!(currentValue instanceof Boolean)) { GlobalVariables.getMessageMap().putError(Constants.BUDGETDATA_CHANGED_VAL_KEY, KeyConstants.BUDGET_DATA_OVERRIDE_SAME_VALUE, new String[] { budgetOverriddenData.getEditableColumn().getColumnLabel(), (budgetOverriddenData.getDisplayValue() != null) ? budgetOverriddenData.getDisplayValue() : overriddenValue }); return false; } } return true; }
From source file:org.apereo.services.persondir.support.RegexGatewayPersonAttributeDao.java
/** * @return the patterns//www. j a v a 2s . c o m */ public Map<String, String> getPatterns() { if (this.patterns == null) { return null; } final Map<String, String> toReturn = new LinkedHashMap<>(this.patterns.size()); for (final Map.Entry<String, Pattern> patternEntry : this.patterns.entrySet()) { final String attribute = patternEntry.getKey(); final Pattern pattern = patternEntry.getValue(); toReturn.put(attribute, pattern.pattern()); } return toReturn; }
From source file:org.kuali.coeus.propdev.impl.budget.editable.ProposalBudgetDataOverrideRule.java
/** * /*from w w w . j a v a 2 s .c o m*/ * This method is to validate the format/length of custom attribute * @param budgetOverriddenData * @param dataDictionaryService * @return */ private boolean validateAttributeFormat(BudgetChangedData budgetOverriddenData, DataDictionaryService dataDictionaryService) { ProposalDevelopmentService proposalDevelopmentService = getProposalDevelopmentService(); DateTimeService dateTimeService = getDateTimeService(); String overriddenValue = budgetOverriddenData.getChangedValue(); String changedValueLabel = dataDictionaryService.getAttributeLabel(BudgetChangedData.class, "changedValue"); String dataType = null; Integer maxLength = -1; if (budgetOverriddenData.getEditableColumn() != null) { dataType = budgetOverriddenData.getEditableColumn().getDataType(); maxLength = budgetOverriddenData.getEditableColumn().getDataLength(); } ValidationPattern validationPattern = null; if (DATE.equalsIgnoreCase(dataType)) { try { dateTimeService.convertToDate(overriddenValue); } catch (ParseException e) { GlobalVariables.getMessageMap().putError(Constants.BUDGETDATA_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 Budget 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.BUDGETDATA_CHANGED_VAL_KEY, RiceKeyConstants.ERROR_INVALID_FORMAT, new String[] { changedValueLabel, overriddenValue }); return false; } } } } DevelopmentProposal developmentProposal = getDataObjectService().find(DevelopmentProposal.class, budgetOverriddenData.getProposalNumber()); Budget finalBudget = developmentProposal.getFinalBudget(); Object currentValue = proposalDevelopmentService.getBudgetFieldValueFromDBColumnName( finalBudget.getParentDocumentKey(), budgetOverriddenData.getColumnName()); if (currentValue instanceof ScaleTwoDecimal) { try { Double overriddenValueToInt = Double.parseDouble(overriddenValue); } catch (Exception e) { GlobalVariables.getMessageMap().putError(Constants.BUDGETDATA_CHANGED_VAL_KEY, RiceKeyConstants.ERROR_NUMBER, new String[] { changedValueLabel, overriddenValue }); return false; } } if ((maxLength != null) && (maxLength.intValue() < overriddenValue.length())) { if (!(currentValue instanceof Boolean)) { GlobalVariables.getMessageMap().putError(Constants.BUDGETDATA_CHANGED_VAL_KEY, RiceKeyConstants.ERROR_MAX_LENGTH, new String[] { changedValueLabel, maxLength.toString() }); return false; } } String currentValueStr = (currentValue != null) ? currentValue.toString() : ""; if (DATE.equalsIgnoreCase(budgetOverriddenData.getEditableColumn().getDataType()) && currentValue != null) { currentValueStr = dateTimeService.toString((Date) currentValue, "MM/dd/yyyy"); } if (StringUtils.isNotEmpty(currentValueStr) && currentValueStr.equalsIgnoreCase(overriddenValue)) { if (!(currentValue instanceof Boolean)) { GlobalVariables.getMessageMap().putError(Constants.BUDGETDATA_CHANGED_VAL_KEY, KeyConstants.BUDGET_DATA_OVERRIDE_SAME_VALUE, new String[] { budgetOverriddenData.getEditableColumn().getColumnLabel(), (budgetOverriddenData.getDisplayValue() != null) ? budgetOverriddenData.getDisplayValue() : overriddenValue }); return false; } } return true; }
From source file:org.tangram.components.MetaLinkHandler.java
public ViewContext handleRequest(HttpServletRequest request, HttpServletResponse response) throws Throwable { String url = request.getRequestURI().substring(linkFactoryAggregator.getPrefix(request).length()); LOG.info("handleRequest() {}", url); Utils.setPrimaryBrowserLanguageForJstl(request); for (Map.Entry<Pattern, Method> entry : methods.entrySet()) { Pattern p = entry.getKey(); LOG.debug("handleRequest() url pattern {}", p.pattern()); Matcher matcher = p.matcher(url); if (matcher.matches()) { LOG.debug("handleRequest() match {}", matcher.groupCount()); Object target = atHandlers.get(entry.getKey()); TargetDescriptor descriptor = new TargetDescriptor(target, null, null); TargetDescriptor resultDescriptor = callAction(request, response, matcher, entry.getValue(), descriptor, target); return (resultDescriptor != TargetDescriptor.DONE) ? handleResultDescriptor(resultDescriptor, request, response) : null;//from w w w. java2s .co m } // if } // for for (String className : handlers.keySet()) { LinkHandler linkHandler = handlers.get(className); TargetDescriptor descriptor = linkHandler.parseLink(url, response); if (descriptor != null) { LOG.info("handleRequest() {} hit for {}", linkHandler.getClass().getName(), url); LOG.debug("handleRequest() found bean {}", descriptor.bean); // Map<String, Object> model = createModel(descriptor, request, response); TargetDescriptor resultDescriptor = descriptor; if (descriptor.action != null) { LOG.debug("handleRequest() trying to call action {}", descriptor.action); Method method = linkFactoryAggregator.findMethod(linkHandler, descriptor.action); resultDescriptor = callAction(request, response, null, method, descriptor, linkHandler); if (resultDescriptor == null) { for (Object value : createModel(descriptor, request, response).values()) { // This has to be checked because of special null values in context like $null // if the link is already set don't try to call other methods if ((value != null) && (resultDescriptor == null)) { method = linkFactoryAggregator.findMethod(value, descriptor.action); resultDescriptor = callAction(request, response, null, method, descriptor, value); } // if } // for } // if } // if return handleResultDescriptor(resultDescriptor, request, response); } // if } // for response.sendError(HttpServletResponse.SC_NOT_FOUND); return null; }
From source file:com.joliciel.talismane.tokeniser.patterns.TokenPatternImpl.java
/** * Does this particular token match this particular pattern. * @param pattern//from ww w .java 2 s . c o m * @param token * @return */ boolean checkTokenForMatch(Pattern pattern, Token token) { String regex = pattern.pattern(); if (regex.contains(".+") || regex.contains("\\D")) { // this pattern is only allowed for non-separators if (!token.isSeparator()) return pattern.matcher(token.getText()).matches(); else return false; } else if (!this.separatorPattern.matcher(regex).find()) { // no separators, we simply check for string equality return (regex.equals(token.getText())); } else if (regex.startsWith("\\") && !(regex.startsWith("\\d")) && !(regex.startsWith("\\s")) && !(regex.startsWith("\\p")) && !(regex.startsWith("\\b"))) { // an escaped separator return (regex.substring(1).equals(token.getText())); } else if (regex.length() == 1) { // an unescaped separator return (regex.equals(token.getText())); } else if (regex.equals("\\b")) { // \b matches whitespace, sentence start and sentence end return (whitespacePattern.matcher(token.getText()).matches()); } else { // a true pattern return (pattern.matcher(token.getText()).matches()); } }
From source file:com.ryantenney.metrics.spring.reporter.AbstractReporterFactoryBean.java
protected MetricFilter metricFilterPattern(String pattern) { final Pattern filter = Pattern.compile(pattern); return new MetricFilter() { @Override/*www. j a v a 2s . c om*/ public boolean matches(String name, Metric metric) { return filter.matcher(name).matches(); } @Override public String toString() { return "[MetricFilter regex=" + filter.pattern() + "]"; } }; }
From source file:org.rhq.core.util.file.FileUtilTest.java
private Pattern assertPatternsRegex(String expectedPattern, PathFilter... filters) { Pattern regex = FileUtil.generateRegex(asList(filters)); assert regex != null : "The regex was not able to be produced - it was null"; assert expectedPattern.equals(regex.pattern()) : "The expected pattern [" + expectedPattern + "] did not match the actual pattern [" + regex.pattern() + "]"; return regex; }