List of usage examples for java.util.regex Matcher groupCount
public int groupCount()
From source file:com.xwiki.authentication.trustedldap.TrustedLDAPAuthServiceImpl.java
protected Map<String, String> parseRemoteUser(String ssoRemoteUser, XWikiContext context) { Map<String, String> ldapConfiguration = new HashMap<String, String>(); ldapConfiguration.put("login", ssoRemoteUser); Pattern remoteUserParser = getConfig().getRemoteUserParser(context); LOG.debug("remoteUserParser: " + remoteUserParser); if (remoteUserParser != null) { Matcher marcher = remoteUserParser.matcher(ssoRemoteUser); if (marcher.find()) { int groupCount = marcher.groupCount(); if (groupCount == 0) { ldapConfiguration.put("login", marcher.group()); } else { for (int g = 1; g <= groupCount; ++g) { String groupValue = marcher.group(g); List<String> remoteUserMapping = getConfig().getRemoteUserMapping(g, context); for (String configName : remoteUserMapping) { ldapConfiguration.put(configName, convertRemoteUserMapping(configName, groupValue, context)); }//from w w w . j a va 2 s. c om } } } } return ldapConfiguration; }
From source file:amp.lib.io.db.SQLFactory.java
/** * Simplifies an every complex SQL error message. * @param message the message/* w ww .ja v a 2 s.c om*/ * @return the simplified message */ public String simplifyErrorMessage(String message) { Pattern p = Pattern.compile("MESSAGE: *(.*\\n)", Pattern.MULTILINE); Matcher m = p.matcher(message); if (m.find() && m.groupCount() > 0) { message = m.group(1); } return message; }
From source file:org.ala.documentmapper.XMLDocumentMapper.java
/** * Map properties using a regular expression. * // w w w . j ava 2s .c o m * @param document * @param parsedDoc * @param isDublinCore * @param mapping */ private void performRegexMapping(Document document, ParsedDocument parsedDoc, boolean isDublinCore, Mapping mapping) { // regex handler DOMBuilder builder = new DOMBuilder(); XMLOutputter xml = new XMLOutputter(); String docString = new String(); try { docString = xml.outputString(builder.build(document)); } catch (Exception e) { } String value = new String(); Pattern p = Pattern.compile(mapping.getQueryString()); Matcher m = p.matcher(docString); int searchIdx = 0; while (m.find(searchIdx)) { int endIdx = m.end(); for (int i = 1; i <= m.groupCount(); i++) { value += " " + m.group(i); } createTriples(parsedDoc, isDublinCore, mapping, value); searchIdx = endIdx; } }
From source file:org.apache.camel.language.simple.SimpleLanguageSupport.java
private void dumpMatcher(Matcher matcher) { if (log.isTraceEnabled()) { log.trace("Matcher start: " + matcher.start()); log.trace("Matcher end: " + matcher.end()); log.trace("Matcher group: " + matcher.group()); log.trace("Matcher group count: " + matcher.groupCount()); for (int i = 0; i < matcher.groupCount() + 1; i++) { String group = matcher.group(i); log.trace("Matcher group #" + i + ": " + group); }// w w w. jav a 2 s . com } }
From source file:fr.fastconnect.cargo.container.openspaces.deployable.ProcessingUnitDeployable.java
public Properties getParsedContextProperties() { final Properties properties = new Properties(); if (this.contextPropertiesFile != null) { try {/*from w w w .j a v a2 s . c om*/ properties.load(new FileInputStream(new File(this.contextPropertiesFile))); } catch (FileNotFoundException e) { LOGGER.error("Unable to load properties from file.", e); } catch (IOException e) { LOGGER.error("Unable to load properties from file.", e); } } if (this.contextProperties != null) { final String[] keyValues = this.contextProperties .split(ProcessingUnitDeployable.CONTEXT_PROPERTY_SEPARATOR); for (final String keyValue : keyValues) { final Matcher matcher = Pattern.compile(ProcessingUnitDeployable.VALUE_KEY_SEPARATOR) .matcher(keyValue); if (matcher.matches() && matcher.groupCount() == 2) { final String key = matcher.group(1); final String value = matcher.group(2); properties.put(key, value.toString()); } else { throw new IllegalArgumentException("Cannot parse <" + keyValue + ">; key/value must be separated by " + ProcessingUnitDeployable.VALUE_KEY_SEPARATOR); } } } return properties; }
From source file:com.osrdata.etltoolbox.fileloader.FileSpecification.java
/** * Loads specified file into target targetTable. This operation transactional and will rollback any database operations if * there are any errors processing the data. * * @param sourceFile source file to be loaded * @throws IOException on error reading file * @throws ParseException on error parsing fields from file *//*from ww w . j a v a 2s . c o m*/ public void load(final File sourceFile) throws IOException, ParseException { this.sourceFile = sourceFile; Matcher matcher = sourcePattern.matcher(sourceFile.getName()); etlDate = new Date(); etlType = "I"; if (matcher.find()) { if (dateGroup != null && dateGroup.intValue() <= matcher.groupCount()) { etlDate = new SimpleDateFormat(dateFormat).parse(matcher.group(dateGroup.intValue())); } if (typeGroup != null && typeGroup.intValue() <= matcher.groupCount()) { etlType = matcher.group(typeGroup.intValue()).substring(0, 1).toUpperCase(); } } recordId = new BigDecimal(new SimpleDateFormat("yyyyMMdd").format(etlDate) + "0000000000"); DataSourceTransactionManager txManager = new DataSourceTransactionManager(targetDs); TransactionTemplate txTemplate = new TransactionTemplate(txManager); targetTemplate = new JdbcTemplate(targetDs); log.info("Processing source file " + sourceFile.getName()); numRecords = 0l; try { txTemplate.execute(new TransactionCallbackWithoutResult() { public void doInTransactionWithoutResult(TransactionStatus status) { try { boolean loadFlag = false; Integer fileId = selectAuditFile(); if (fileId != null && replaceExisting) { deleteExisting(fileId); updateAuditFile(fileId); loadFlag = true; } else if (fileId == null) { fileId = insertAuditFile(); loadFlag = true; } if (loadFlag) { CSVReader reader = new CSVReader(new FileReader(sourceFile), parserSeparator, parserQuotechar, parserEscape, parserLine, parserStrictQuotes, parserIgnoreLeadingWhiteSpace); String[] values; startTime = System.currentTimeMillis(); while ((values = reader.readNext()) != null) { add(values, fileId); numRecords++; if (trace > 0l && numRecords % trace == 0l) { log.info("\tProcessed " + getCount(numRecords) + " records in " + getDuration() + " (" + getRecordsPerSecond() + " rps)"); } } reader.close(); insertTarget(); } else { log.info("\tSkipping previously loaded file" + sourceFile.getName()); } } catch (RuntimeException e) { throw e; } catch (Throwable e) { log.error("\tError at record " + numRecords + " in " + sourceFile.getName()); throw new RuntimeException(e); } } }); } catch (RuntimeException e) { log.error("\tAn exception occurred while processing record " + numRecords + " in " + sourceFile.getName() + ". All transactions for this file have been rolled back.", e); } log.info("\tCompleted processing of " + getCount(numRecords) + " records in " + getDuration() + " (" + getRecordsPerSecond() + " rps)"); }
From source file:com.joliciel.talismane.posTagger.PosTagRegexBasedCorpusReaderImpl.java
@Override public boolean hasNextPosTagSequence() { if (maxSentenceCount > 0 && sentenceCount >= maxSentenceCount) { // we've reached the end, do nothing } else {/*from www .j av a2 s .co m*/ while (posTagSequence == null) { PretokenisedSequence tokenSequence = null; List<PosTag> posTags = null; boolean hasLine = false; if (!scanner.hasNextLine()) break; while (scanner.hasNextLine() && posTagSequence == null) { String line = scanner.nextLine().replace("\r", ""); lineNumber++; if (line.length() == 0) { if (!hasLine) continue; // end of sentence sentenceCount++; LOG.debug("sentenceCount: " + sentenceCount); // check cross-validation if (crossValidationSize > 0) { boolean includeMe = true; if (includeIndex >= 0) { if (sentenceCount % crossValidationSize != includeIndex) { includeMe = false; } } else if (excludeIndex >= 0) { if (sentenceCount % crossValidationSize == excludeIndex) { includeMe = false; } } if (!includeMe) { hasLine = false; tokenSequence = null; posTags = null; continue; } } tokenSequence.cleanSlate(); for (TokenSequenceFilter tokenFilter : this.tokenFilters) { tokenFilter.apply(tokenSequence); } posTagSequence = posTaggerServiceInternal.getPosTagSequence(tokenSequence, tokenSequence.size()); int i = 0; PosTagSet posTagSet = TalismaneSession.getPosTagSet(); for (PosTag posTag : posTags) { Token token = tokenSequence.get(i++); if (tokenSequence.getTokensAdded().contains(token)) { Decision<PosTag> nullDecision = posTagSet .createDefaultDecision(PosTag.NULL_POS_TAG); PosTaggedToken emptyToken = posTaggerServiceInternal.getPosTaggedToken(token, nullDecision); posTagSequence.addPosTaggedToken(emptyToken); token = tokenSequence.get(i++); } Decision<PosTag> corpusDecision = posTagSet.createDefaultDecision(posTag); PosTaggedToken posTaggedToken = posTaggerServiceInternal.getPosTaggedToken(token, corpusDecision); posTagSequence.addPosTaggedToken(posTaggedToken); } for (PosTagSequenceFilter posTagSequenceFilter : this.posTagSequenceFilters) { posTagSequenceFilter.apply(posTagSequence); } } else { hasLine = true; if (tokenSequence == null) { tokenSequence = tokeniserService.getEmptyPretokenisedSequence(); posTags = new ArrayList<PosTag>(); } Matcher matcher = this.getPattern().matcher(line); if (!matcher.matches()) throw new TalismaneException("Didn't match pattern on line " + lineNumber); if (matcher.groupCount() != placeholderIndexMap.size()) { throw new TalismaneException("Expected " + placeholderIndexMap.size() + " matches (but found " + matcher.groupCount() + ") on line " + lineNumber); } String word = matcher.group(placeholderIndexMap.get(TOKEN_PLACEHOLDER)); word = CoNLLFormatter.fromCoNLL(word); Token token = tokenSequence.addToken(word); String posTagCode = matcher.group(placeholderIndexMap.get(POSTAG_PLACEHOLDER)); if (placeholderIndexMap.containsKey(FILENAME_PLACEHOLDER)) token.setFileName(matcher.group(placeholderIndexMap.get(FILENAME_PLACEHOLDER))); if (placeholderIndexMap.containsKey(ROW_PLACEHOLDER)) token.setLineNumber( Integer.parseInt(matcher.group(placeholderIndexMap.get(ROW_PLACEHOLDER)))); if (placeholderIndexMap.containsKey(COLUMN_PLACEHOLDER)) token.setColumnNumber( Integer.parseInt(matcher.group(placeholderIndexMap.get(COLUMN_PLACEHOLDER)))); PosTagSet posTagSet = TalismaneSession.getPosTagSet(); PosTag posTag = null; try { posTag = posTagSet.getPosTag(posTagCode); } catch (UnknownPosTagException upte) { throw new TalismaneException( "Unknown posTag on line " + lineNumber + ": " + posTagCode); } posTags.add(posTag); } } } } return (posTagSequence != null); }
From source file:gtu._work.ui.RegexCatchReplacer.java
/** * @param fromPattern//w ww . j a v a2s.c o m * ???pattern * @param toFormat * ??pattern * @param replaceText * ?? */ void replacer(String fromPattern, String toFormat, String replaceText) { try { Pattern pattern = Pattern.compile(fromPattern); Matcher matcher = pattern.matcher(replaceText); Map<String, Integer> tmap = new LinkedHashMap<String, Integer>(); String tempStr = null; for (; matcher.find();) { tempStr = toFormat.toString(); for (int ii = 0; ii <= matcher.groupCount(); ii++) { System.out.println(ii + " -- " + matcher.group(ii)); tempStr = tempStr.replaceAll("#" + ii + "#", Matcher.quoteReplacement(matcher.group(ii))); if (!tmap.containsKey(tempStr)) { tmap.put(tempStr, 0); } tmap.put(tempStr, tmap.get(tempStr) + 1); } } DefaultTableModel model = JTableUtil.createModel(true, "match", "count"); for (String str : tmap.keySet()) { model.addRow(new Object[] { str, tmap.get(str) }); } setTitle("total : " + model.getRowCount()); resultArea.setModel(model); } catch (Exception ex) { JOptionPaneUtil.newInstance().iconErrorMessage().showMessageDialog(ex.getMessage(), getTitle()); ex.printStackTrace(); } }
From source file:com.hotfey.flume.extra.interceptor.RegexExtractorInterceptor.java
@Override public Event intercept(Event event) { /**//ww w . j a va 2 s. c o m * <pre> * ===================================================================== * ===================================================================== * Matcher matcher = regex.matcher(new String(event.getBody(), Charsets.UTF_8)); * Map<String, String> headers = event.getHeaders(); * ===================================================================== * ===================================================================== * </pre> */ /** * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> */ Map<String, String> mapHeaders = event.getHeaders(); StringBuffer stringBufferHeaders = new StringBuffer(); for (String key : mapHeaders.keySet()) { stringBufferHeaders.append(key).append(":").append(mapHeaders.get(key)); } Matcher matcher = regex.matcher(stringBufferHeaders.toString()); /** * <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< * <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< */ Map<String, String> headers = event.getHeaders(); if (matcher.find()) { for (int group = 0, count = matcher.groupCount(); group < count; group++) { int groupIndex = group + 1; if (groupIndex > serializers.size()) { if (logger.isDebugEnabled()) { logger.debug("Skipping group {} to {} due to missing serializer", group, count); } break; } NameAndSerializer serializer = serializers.get(group); if (logger.isDebugEnabled()) { logger.debug("Serializing {} using {}", serializer.headerName, serializer.serializer); } headers.put(serializer.headerName, serializer.serializer.serialize(matcher.group(groupIndex))); } } return event; }
From source file:org.hyperic.hq.plugin.netservices.HTTPCollector.java
private boolean matchResponse(HttpResponse response) { String body;/*from w ww .j av a 2 s . co m*/ try { body = EntityUtils.toString(response.getEntity(), "UTF-8"); body = body == null ? "" : body; if (log.isDebugEnabled()) { log.debug("attempting to match pattern=" + pattern.get() + " against response body=" + body); } } catch (ParseException e) { setErrorMessage("Exception parsing response: " + e, e); return false; } catch (IOException e) { setErrorMessage("Exception reading response stream: " + e, e); return false; } Matcher matcher = this.pattern.get().matcher(body); boolean matches = false; while (matcher.find()) { matches = true; int count = matcher.groupCount(); // skip group(0): // "Group zero denotes the entire pattern by convention" for (int i = 1; i <= count; i++) { this.matches.add(matcher.group(i)); } } if (matches) { if (log.isDebugEnabled()) { log.debug("pattern='" + pattern.get() + "' matches"); } return true; } else { if (log.isDebugEnabled()) { log.debug("pattern='" + pattern.get() + "' does not match"); } setWarningMessage("Response (length=" + body.length() + ") does not match " + pattern.get()); return false; } }