private String addDataRights(String content, String classification, Artifact artifact) { String toReturn = content; PageOrientation orientation = WordRendererUtil.getPageOrientation(artifact); DataRightInput request = new DataRightInput(); request.addData(artifact.getGuid(), classification, orientation, 0); DataRightProvider provider = new DataRightProviderImpl(); DataRightResult dataRights = provider.getDataRights(request); String footer = dataRights.getContent(artifact.getGuid(), orientation); Matcher startFtr = START_PATTERN.matcher(footer); Matcher endFtr = END_PATTERN.matcher(footer); if (startFtr.find() && endFtr.find()) { ChangeSet ftrCs = new ChangeSet(footer); ftrCs.delete(0, startFtr.end()); ftrCs.delete(endFtr.start(), footer.length()); footer = ftrCs.applyChangesToSelf().toString(); } startFtr.reset(content); endFtr.reset(content); ChangeSet cs = new ChangeSet(content); while (startFtr.find()) { if (endFtr.find()) { cs.replace(startFtr.end(), endFtr.start(), footer); } } toReturn = cs.applyChangesToSelf().toString(); return toReturn; }
@Override public void visitMatchingTerms(IndexReader reader, String fieldName, MatchingTermVisitor mtv) throws IOException { boolean expanded = false; int prefixLength = prefix.length(); TermEnum enumerator = reader.terms(new Term(fieldName, prefix)); Matcher matcher = pattern.matcher(""); try { do { Term term = enumerator.term(); if (term != null) { String text = term.text(); if ((!text.startsWith(prefix)) || (!term.field().equals(fieldName))) { break; } else { matcher.reset(text.substring(prefixLength)); if (matcher.matches()) { mtv.visitMatchingTerm(term); expanded = true; } } } } while (enumerator.next()); } finally { enumerator.close(); matcher.reset(); } if (!expanded) { System.out.println("No terms in " + fieldName + " field for: " + toString()); } }
/** * Include row if each matcher succeeds in at least one column. In other words all the * conditions are combined with "and" * * @param value * @return */ @Override public boolean include(Entry value) { for (Pair<String, Matcher> entry : matchers) { String column = entry.getFirst(); Matcher matcher = entry.getSecond(); // Search for a match in at least one column. The first column is the checkbox. boolean found = false; // Pessimistic int nColumns = table.getColumnCount(); for (int index = 1; index < nColumns; index++) { // Include column headings in search. This is to prevent premature filtering when // entering a // specific column condition (e.g. cataType=ChipSeq) matcher.reset(table.getColumnName(index).toLowerCase()); if (matcher.find()) { found = true; break; } boolean wildcard = column.equals("*"); if (wildcard || column.equalsIgnoreCase(table.getColumnName(index))) { matcher.reset(value.getStringValue(index)); if (matcher.find()) { found = true; break; } } } if (!found) return false; } return true; // If we get here we matched them all }
boolean isSelected(String className, ProtectionDomain protectionDomain) { CodeSource codeSource = protectionDomain.getCodeSource(); if (codeSource == null || className.charAt(0) == '[' || className.startsWith("mockit.") || className.startsWith("org.junit.") || className.startsWith("junit.") || className.startsWith("org.testng.")) { return false; } if (classesToExclude != null && classesToExclude.reset(className).matches()) { return false; } else if (classesToInclude != null && classesToInclude.reset(className).matches()) { return true; } else if (testCode != null && testCode.reset(className).matches()) { return false; } String location = codeSource.getLocation().getPath(); return !location.endsWith(".jar") && !location.endsWith("/.cp/") && (testCode == null || !location.endsWith("/test-classes/") && !location.endsWith("/jmockit/main/classes/")); }
/** * Creates a new {@code UriPathTemplate} from the given {@code uriPattern}. * * @param uriPattern The pattern to be used by the template */ public UriPathTemplate(String uriPattern) { String s = "^" + uriPattern; Matcher m = NAME_SPLAT_PATTERN.matcher(s); while (m.find()) { for (int i = 1; i <= m.groupCount(); i++) { String name = m.group(i); pathVariables.add(name); s = m.replaceFirst(NAME_SPLAT_REPLACEMENT.replaceAll("%NAME%", name)); m.reset(s); } } m = NAME_PATTERN.matcher(s); while (m.find()) { for (int i = 1; i <= m.groupCount(); i++) { String name = m.group(i); pathVariables.add(name); s = m.replaceFirst(NAME_REPLACEMENT.replaceAll("%NAME%", name)); m.reset(s); } } m = FULL_SPLAT_PATTERN.matcher(s); while (m.find()) { s = m.replaceAll(FULL_SPLAT_REPLACEMENT); m.reset(s); } this.uriPattern = Pattern.compile(s + "$"); }
public static void main(String[] args) { String inputStr = null; BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { while ((inputStr = reader.readLine()) != null) { inputStr = inputStr.trim(); if (DEST_MATCHER.reset(inputStr).matches()) { System.out.println("Destination field!\n"); } else if (SOURCE_MATCHER.reset(inputStr).matches()) { System.out.println("Source field!\n"); } else if (STRING_MATCHER.reset(inputStr).matches()) { System.out.println("String literal!\n"); } else if (VAR_MATCHER.reset(inputStr).matches()) { System.out.println("Variable!\n"); } else if (NUM_MATCHER.reset(inputStr).matches()) { System.out.println("Number!\n"); } else { System.out.println("Huh???\n"); } } } catch (Exception ioe) { System.out.println("Exception: " + ioe.toString()); ioe.printStackTrace(); } }
/** * Returns true if any of the options in {@code options} matches both of the regular expressions * provided: its name matches the option's name and its value matches the option's value. */ public boolean optionMatches(String namePattern, String valuePattern) { Matcher nameMatcher = Pattern.compile(namePattern).matcher(""); Matcher valueMatcher = Pattern.compile(valuePattern).matcher(""); for (Map.Entry<ProtoMember, Object> entry : map.entrySet()) { if (nameMatcher.reset(entry.getKey().member()).matches() && valueMatcher.reset(String.valueOf(entry.getValue())).matches()) { return true; } } return false; }
public void test_resetLjava_lang_String() { String testPattern = "(abb)"; String testString1 = "babbabbcccabbabbabbabbabb"; String testString2 = "cddcddcddcddcddbbbb"; Pattern pat = Pattern.compile(testPattern); Matcher mat = pat.matcher(testString1); while (mat.find()) ; assertEquals("Reset should return itself 1", mat, mat.reset(testString2)); assertFalse("After reset matcher should not find pattern in given input", mat.find()); assertEquals("Reset should return itself 2", mat, mat.reset(testString1)); assertTrue("After reset matcher should find pattern in given input", mat.find()); }
protected int matchEachElementPos(Matcher matcher, Tuple input) { int pos = 0; for (Object value : input) { if (value == null) value = ""; matcher.reset(value.toString()); boolean matchFound = matcher.find(); if (LOG.isDebugEnabled()) LOG.debug( "pattern: " + getPatternString() + ", matches: " + matchFound + ", element: '" + value + "'"); if (matchFound == negateMatch) return pos; pos++; } return -1; }
public static Cookie getKeyValues(String url) { if (url == null) return new Cookie(); int indexOfSemi = url.indexOf(";"); int indexOfQuestion = url.indexOf(";"); int queryIndex = -1; int maxQueryIndex = Math.max(indexOfSemi, indexOfQuestion); int minQueryIndex = Math.min(indexOfSemi, indexOfQuestion); if (minQueryIndex != -1) { queryIndex = minQueryIndex; } else { queryIndex = maxQueryIndex; } if (queryIndex == -1) { return null; } Cookie keyValues = new Cookie(); String queryString = url.substring(queryIndex + 1); keyValueMatcher.reset(queryString); while (keyValueMatcher.find()) { String key = keyValueMatcher.group(1); String value = keyValueMatcher.group(2); keyValues.addProperty(key, value); } return keyValues; }
@Override public void visit(NodeTraversal t, Node n, Node parent) { if (n.isString() && !parent.isGetProp() && !parent.isRegExp()) { String s = n.getString(); for (blacklist.reset(s); blacklist.find(); ) { if (parent.isTemplateLit()) { if (parent.getChildCount() > 1) { // Ignore template string with substitutions continue; } else { n = parent; } } if (insideGetCssNameCall(n)) { continue; } if (insideGetUniqueIdCall(n)) { continue; } if (insideAssignmentToIdConstant(n)) { continue; } compiler.report(t.makeError(n, level, MISSING_GETCSSNAME, blacklist.group())); } } }
protected final String substitute(Configuration conf, String expr, int depth) { Matcher match = varPat.matcher(""); String eval = expr; StringBuilder builder = new StringBuilder(); int s = 0; for (; s <= depth; s++) { match.reset(eval); builder.setLength(0); int prev = 0; boolean found = false; while (match.find(prev)) { String group = match.group(); String var = group.substring(2, group.length() - 1); // remove ${ .. } String substitute = getSubstitute(conf, var); if (substitute == null) { substitute = group; // append as-is } else { found = true; } builder.append(eval.substring(prev, match.start())).append(substitute); prev = match.end(); } if (!found) { return eval; } builder.append(eval.substring(prev)); eval = builder.toString(); } if (s > depth) { throw new IllegalStateException( "Variable substitution depth is deeper than " + depth + " for expression " + expr); } return eval; }
/** * Save the model into the file * * @param root the root of the model to save * @param file the file to save * @throws JAXBException on error */ public void save(Model root, File file) throws JAXBException { try { final StringWriter strw = new StringWriter(); marshaller.marshal(unmerge(root), strw); /* * Customize the file to be handled by the xml2modelica tool */ final StringBuffer buffer = strw.getBuffer(); final String newline = System.getProperty("line.separator"); Pattern pat = Pattern.compile("(/\\w*>)(<[\\w/])"); Matcher m = pat.matcher(buffer); while (m.find()) { final int index = m.end(1); buffer.insert(index, newline); m.reset(); } buffer.append(newline); new FileOutputStream(file).write(strw.toString().getBytes()); } catch (FactoryConfigurationError e) { Logger.getLogger(Modelica.class.getName()).severe(e.toString()); } catch (IOException e) { Logger.getLogger(Modelica.class.getName()).severe(e.toString()); } }
private static String processHtml(final String source, StringBuilder errorMessages) { if (M_evilTags == null) init(); // normalize all variants of the "<br>" HTML tag to be "<br />\n" // TODO call a method to do this in each process routine String Html = M_patternTagBr.matcher(source).replaceAll("<br />"); // process text and tags StringBuilder buf = new StringBuilder(); if (Html != null) { try { int start = 0; Matcher m = M_patternTag.matcher(Html); // if there are no tags, return as is if (!m.find()) return Html; m.reset(Html); // if there are tags, make sure they are safe while (m.find()) { // append text that isn't part of a tag if (m.start() > start) buf.append(Html.substring(start, m.start())); start = m.end(); buf.append(checkTag(m.group(), errorMessages)); } // tail if (Html.length() > start) buf.append(Html.substring((start))); } catch (Exception e) { M_log.warn("FormattedText.processEscapedHtml M_patternTag.matcher(Html):", e); } } return new String(buf.toString()); }
@Override public void reset(Reader input) throws IOException { super.reset(input); str = IOUtils.toString(input); matcher.reset(str); index = 0; }
/** * : Availability of properties indexes for org-units. * * @throws Exception If anything fails. */ @Test public void testSBOUSR29() throws Exception { Pattern orgUnitIdPattern = Pattern.compile("(.*)\\$\\{ORGUNIT(.*?)\\}(.*)"); Matcher orgUnitIdMatcher = orgUnitIdPattern.matcher(""); HashMap<String, String> parameters = new HashMap<String, String>(); for (String indexName : SearchTestConstants.ORG_UNIT_INDEX_PROPERTIES_SEARCHES.keySet()) { HashMap<String, String> info = SearchTestConstants.ORG_UNIT_INDEX_PROPERTIES_SEARCHES.get(indexName); orgUnitIdMatcher.reset(info.get("searchString")); String searchString = info.get("searchString"); if (orgUnitIdMatcher.matches()) { int indexNum = new Integer(orgUnitIdMatcher.group(2)); searchString = orgUnitIdMatcher.replaceAll("$1" + orgUnitIds[indexNum] + "$3"); } String expectedHits = info.get("expectedHits"); parameters.put(FILTER_PARAMETER_QUERY, searchString); String response = search(parameters, INDEX_NAME); assertXmlValidSrwResponse(response); assertEquals( "expected " + expectedHits + " for " + indexName + " but was " + getNumberOfHits(response), expectedHits, getNumberOfHits(response)); } }
/** Returns the regular or irregular plural form of <code>noun</code>. */ public String pluralize(String noun) { boolean dbug = false; wordMatcher.reset(noun); if (!wordMatcher.matches()) return noun; if (MODALS.contains(noun)) return noun; String result = null; for (int i = 0; i < PLURAL_RULES.length; i++) { RegexRule currentRule = PLURAL_RULES[i]; if (currentRule.applies(noun)) { if (dbug) System.out.print("applying rule " + i + " -> "); result = currentRule.fire(noun); if (dbug) System.out.println(result); break; } } if ((result == null) && (defaultRule != null)) { result = defaultRule.fire(noun); if (dbug) System.out.println("applying default: -> " + result); } return result; }
/* * Returns TTL value of ElasticSearch index in milliseconds when TTL * specifier is "ms" / "s" / "m" / "h" / "d" / "w". In case of unknown * specifier TTL is not set. When specifier is not provided it defaults to * days in milliseconds where the number of days is parsed integer from TTL * string provided by user. <p> Elasticsearch supports ttl values being * provided in the format: 1d / 1w / 1ms / 1s / 1h / 1m specify a time unit * like d (days), m (minutes), h (hours), ms (milliseconds) or w (weeks), * milliseconds is used as default unit. * http://www.elasticsearch.org/guide/reference/mapping/ttl-field/. * * @param ttl TTL value provided by user in flume configuration file for the * sink * * @return the ttl value in milliseconds */ private long parseTTL(String ttl) { matcher = matcher.reset(ttl); while (matcher.find()) { if (matcher.group(2).equals("ms")) { return Long.parseLong(matcher.group(1)); } else if (matcher.group(2).equals("s")) { return TimeUnit.SECONDS.toMillis(Integer.parseInt(matcher.group(1))); } else if (matcher.group(2).equals("m")) { return TimeUnit.MINUTES.toMillis(Integer.parseInt(matcher.group(1))); } else if (matcher.group(2).equals("h")) { return TimeUnit.HOURS.toMillis(Integer.parseInt(matcher.group(1))); } else if (matcher.group(2).equals("d")) { return TimeUnit.DAYS.toMillis(Integer.parseInt(matcher.group(1))); } else if (matcher.group(2).equals("w")) { return TimeUnit.DAYS.toMillis(7 * Integer.parseInt(matcher.group(1))); } else if (matcher.group(2).equals("")) { logger.info("TTL qualifier is empty. Defaulting to day qualifier."); return TimeUnit.DAYS.toMillis(Integer.parseInt(matcher.group(1))); } else { logger.debug("Unknown TTL qualifier provided. Setting TTL to 0."); return 0; } } logger.info("TTL not provided. Skipping the TTL config by returning 0."); return 0; }
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (m != null) m.reset(root.relativize(dir).toString()); return m == null || m.matches() || m.hitEnd() ? FileVisitResult.CONTINUE : FileVisitResult.SKIP_SUBTREE; }
/** Strips out the scheme and authority. */ private String getPathPart(Path path) { pathMatcher.reset(path.toString()); pathMatcher.matches(); return pathMatcher.group(5); }
private String substituteVars(String expr) { if (expr == null) { return null; } Matcher match = varPat.matcher(""); String eval = expr; for (int s = 0; s < MAX_SUBST; s++) { match.reset(eval); if (!match.find()) { return eval; } String var = match.group(); var = var.substring(2, var.length() - 1); // remove ${ .. } String val = getRaw(var); if (val == null) { val = System.getProperty(var); } if (val == null) { return eval; // return literal ${var}: var is unbound } // substitute eval = eval.substring(0, match.start()) + val + eval.substring(match.end()); } throw new IllegalStateException( "Variable substitution depth too large: " + MAX_SUBST + " " + expr); }
/** Parses a line of javascript, extracting goog.provide and goog.require information. */ @Override protected boolean parseLine(String line) throws ParseException { boolean hasProvidesOrRequires = false; // Quick sanity check that will catch most cases. This is a performance // win for people with a lot of JS. if (line.indexOf("provide") != -1 || line.indexOf("require") != -1) { // Iterate over the provides/requires. googMatcher.reset(line); while (googMatcher.find()) { hasProvidesOrRequires = true; // See if it's a require or provide. boolean isRequire = googMatcher.group(1).charAt(0) == 'r'; // Parse the param. String arg = parseJsString(googMatcher.group(2)); // Add the dependency. if (isRequire) { // goog is always implicit. // TODO(nicksantos): I'm pretty sure we don't need this anymore. // Remove this later. if (!"goog".equals(arg)) { requires.add(arg); } } else { provides.add(arg); } } } return !shortcutMode || hasProvidesOrRequires || CharMatcher.WHITESPACE.matchesAllOf(line); }
private void searchForwards() throws IOException { String input = readLine('/'); int lineNo = topLineNo; if (input.length() <= 1) { if (regex == null) { setPrompt(str_no_prev); return; } lineNo++; } else { try { regex = Pattern.compile(input.substring(1)); } catch (PatternSyntaxException ex) { setPrompt(str_inv_regex); return; } matcher = regex.matcher(""); } while (true) { String line = lineStore.getLine(lineNo); if (line == null) { gotoLastPage(); setPrompt(str_not_found); return; } matcher.reset(line); if (matcher.find()) { prepare(lineNo, 0).output(); return; } lineNo++; } }
@Test public void testStandardUrlSegmentPattern() { MetaPattern pattern = new MetaPattern(AbstractURLSegment.SEGMENT_PARAMETER); Matcher matcher = pattern.matcher(""); assertFalse(matcher.matches()); matcher = pattern.matcher("seg&ment"); assertFalse(matcher.matches()); matcher = pattern.matcher("segment:"); assertFalse(matcher.matches()); matcher = pattern.matcher("{*}"); assertFalse(matcher.matches()); matcher = pattern.matcher("{segment}"); assertTrue(matcher.matches()); matcher = pattern.matcher("{segment0} a segment {segment1} another segment {segment2}"); assertTrue(matcher.find()); matcher.reset(); assertFalse(matcher.matches()); matcher = pattern.matcher("{117}"); assertFalse(matcher.matches()); pattern = new MetaPattern(AbstractURLSegment.REGEXP_BODY); matcher = pattern.matcher("[0-9]*:abba"); assertTrue(matcher.matches()); matcher = pattern.matcher("^\\(?\\d{3}\\)?[ -]?\\d{3}[ -]?\\d{4}$anotherseg"); assertTrue(matcher.matches()); }
private void insertRecord(String line) throws FormatException { String[] fields = line.split(","); if (fields.length < 9) throw new FormatException( "Too few columns in sample sheet. Expecing at least 9 but found " + fields.length + ". Line: " + line); // Format is CSV with these columns: // "FCID","Lane","SampleID","SampleRef","Index","Description","Control","Recipe","Operator" // All text fields are quoted (all except Lane) // remove external quotes and whitespace from all string fields (even spaces within the quotes) for (int i = 0; i < fields.length; ++i) { quoteMatcher.reset(fields[i]); fields[i] = quoteMatcher.replaceAll("").trim(); } Entry entry; try { entry = Entry.createEntry(fields); } catch (IllegalArgumentException e) { throw new FormatException(e.getMessage() + ". Line: " + line); } table.add(entry); }
public static String parseDiagnosedRanges(String text, List<DiagnosedRange> result) { Matcher matcher = RANGE_START_OR_END_PATTERN.matcher(text); Stack<DiagnosedRange> opened = new Stack<DiagnosedRange>(); int offsetCompensation = 0; while (matcher.find()) { int effectiveOffset = matcher.start() - offsetCompensation; String matchedText = matcher.group(); if ("<!>".equals(matchedText)) { opened.pop().setEnd(effectiveOffset); } else { Matcher diagnosticTypeMatcher = INDIVIDUAL_DIAGNOSTIC_PATTERN.matcher(matchedText); DiagnosedRange range = new DiagnosedRange(effectiveOffset); while (diagnosticTypeMatcher.find()) { range.addDiagnostic(diagnosticTypeMatcher.group()); } opened.push(range); result.add(range); } offsetCompensation += matchedText.length(); } assert opened.isEmpty() : "Stack is not empty"; matcher.reset(); return matcher.replaceAll(""); }
/** * Leave only the value for RCS keywords. * * <p>For example, <code>$Revision: 1.1 $</code> becomes <code>1.0</code>. */ public String replaceRcsKeywords(String text) { if (matcher == null) { matcher = Pattern.compile( "\\$(Author|Date|Header|Id|Locker|Log|Name|RCSFile|Revision|Source|State): (.+?) \\$") .matcher(text); } else { matcher.reset(text); } StringBuffer buffer = new StringBuffer(); while (matcher.find()) { String string = matcher.group(2); // For the Date: keyword, have a shot at reformatting string if ("Date".equals(matcher.group(1))) { try { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = dateFormat.parse(string); string = date.toString(); } catch (ParseException e) { } // if we can't parse, return unchanged } matcher.appendReplacement(buffer, string); } matcher.appendTail(buffer); return buffer.toString(); }
@Override public void check(String value) throws T2DBException { if (value == null || value.length() == 0 || value.length() > MAX_NAME_LENGTH) throw T2DBMsg.exception(D.D10105, value, 0, MAX_NAME_LENGTH); validNameMatcher.reset(value); if (!validNameMatcher.matches()) throw T2DBMsg.exception(D.D10104, value, NAME_PATTERN); }
/** * Analyze configuration to get meter names * * @return set of String of meter names */ private Set<String> getNames(Dictionary<String, ?> config) { Set<String> set = new HashSet<String>(); Enumeration<String> keys = config.keys(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); // the config-key enumeration contains additional keys that we // don't want to process here ... if ("service.pid".equals(key) || "refresh".equals(key)) { continue; } Matcher meterMatcher = METER_CONFIG_PATTERN.matcher(key); if (!meterMatcher.matches()) { logger.debug( "given config key '" + key + "' does not follow the expected pattern '<meterName>.<serialPort|baudRateChangeDelay|echoHandling>'"); continue; } meterMatcher.reset(); meterMatcher.find(); set.add(meterMatcher.group(1)); } return set; }
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (attrs.isRegularFile()) { if (m != null) m.reset(root.relativize(file).toString()); if (m == null || m.matches()) futures.add(exec.submit(new FileLoader(root, file, blocSize))); } return FileVisitResult.CONTINUE; }