List of usage examples for java.util.regex Matcher end
public int end()
From source file:com.novartis.opensource.yada.plugin.Gatekeeper.java
/** * Modifies the original query by appending a dynamic predicate * <p>Recall the {@link Service#engagePreprocess} method * will recall {@link QueryManager#endowQuery} to * reconform the code after this {@link Preprocess} * disengages.//from www. j a va 2 s .co m * * * @throws YADASecurityException when token retrieval fails */ @Override public void applyContentPolicy() throws YADASecurityException { // TODO make it impossible to reset args and preargs dynamically if pl class implements SecurityPolicy // this will close an attack vector String SPACE = " "; StringBuilder contentPolicy = new StringBuilder(); Pattern rxInjection = Pattern.compile(RX_COL_INJECTION); String rawPolicy = getArgumentValue(CONTENT_POLICY_PREDICATE); Matcher m1 = rxInjection.matcher(rawPolicy); int start = 0; // field = getToken // field = getCookie(string) // field = getHeader(string) // field = getUser() // field = getRandom(string) if (!m1.find()) { String msg = "Unathorized. Injected method invocation failed."; throw new YADASecurityException(msg); } m1.reset(); while (m1.find()) { int rxStart = m1.start(); int rxEnd = m1.end(); contentPolicy.append(rawPolicy.substring(start, rxStart)); String frag = rawPolicy.substring(rxStart, rxEnd); String method = frag.substring(0, frag.indexOf('(')); String arg = frag.substring(frag.indexOf('(') + 1, frag.indexOf(')')); Object val = null; try { if (arg.equals("")) val = getClass().getMethod(method).invoke(this, new Object[] {}); else val = getClass().getMethod(method, new Class[] { java.lang.String.class }).invoke(this, new Object[] { arg }); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { String msg = "Unathorized. Injected method invocation failed."; throw new YADASecurityException(msg, e); } contentPolicy.append((String) val + SPACE); start = rxEnd; } Expression parsedContentPolicy; try { parsedContentPolicy = CCJSqlParserUtil.parseCondExpression(contentPolicy.toString()); } catch (JSQLParserException e) { String msg = "Unauthorized. Content policy is not valid."; throw new YADASecurityException(msg, e); } PlainSelect sql = (PlainSelect) ((Select) getYADAQuery().getStatement()).getSelectBody(); Expression where = sql.getWhere(); if (where != null) { AndExpression and = new AndExpression(where, parsedContentPolicy); sql.setWhere(and); } else { sql.setWhere(parsedContentPolicy); } try { CCJSqlParserManager parserManager = new CCJSqlParserManager(); sql = (PlainSelect) ((Select) parserManager.parse(new StringReader(sql.toString()))).getSelectBody(); } catch (JSQLParserException e) { String msg = "Unauthorized. Content policy is not valid."; throw new YADASecurityException(msg, e); } getYADAQuery().setCoreCode(sql.toString()); this.clearSecurityPolicy(); }
From source file:net.antoinecomte.regex.RegExTesterApplication.java
private void showResult(String regexValue, String textValue) { Matcher matcher; try {/* w ww. j a va 2s . c om*/ result.setVisible(!"".equals(regexValue)); Label match = new Label("no match"); match.addStyleName("h3 color"); result.removeAllComponents(); result.addComponent(match); matcher = Pattern.compile(regexValue).matcher(textValue); if (matcher.matches()) { if (matcher.groupCount() > 0) for (int i = 1; i <= matcher.groupCount(); i++) { Label g = new Label("group " + i + " = " + matcher.group(i)); g.addStyleName("h3 color"); g.setSizeUndefined(); result.addComponent(g); } match.setValue("match"); } matcher.reset(); if (matcher.find()) { Label findresult = new Label("find=true, start = " + matcher.start() + " end = " + matcher.end()); findresult.addStyleName("h3 color"); result.addComponent(findresult); } Label javaString = new Label("java string : \"" + StringEscapeUtils.escapeJava(regexValue) + "\""); javaString.addStyleName("small color"); result.addComponent(javaString); } catch (Exception e) { result.removeAllComponents(); Label error = new Label(e.getMessage()); error.addStyleName("error"); result.addComponent(error); } }
From source file:org.openmrs.module.rheashradapter.util.RHEA_ORU_R01Handler.java
private Location getLocation(MSH msh, OBR obr) throws HL7Exception { String hl7Location = msh.getSendingFacility().getNamespaceID().toString(); Location location = null;/*w w w . j ava2 s. c o m*/ List<Location> locationsList = Context.getLocationService().getAllLocations(); for (Location l : locationsList) { String fosaid = l.getDescription(); String elid = null; if (fosaid != null) { final Matcher matcher = Pattern.compile(":").matcher(fosaid); if (matcher.find()) { elid = fosaid.substring(matcher.end()).trim(); if (elid.equals(hl7Location)) { location = l; } } } } if (location == null) { String locationName = obr.getFillerField2().getValue(); if (locationName != null) { location = Context.getLocationService().getLocation(locationName); if (location != null) { location.setDescription("OpenMRS ELID:" + hl7Location); Context.getLocationService().saveLocation(location); } else { location = new Location(); location.setName(obr.getFillerField2().getValue()); location.setDescription("OpenMRS ELID:" + hl7Location); Context.getLocationService().saveLocation(location); } } else { location = new Location(); location.setName(obr.getFillerField2().getValue()); location.setDescription("OpenMRS ELID:" + hl7Location); Context.getLocationService().saveLocation(location); } } return location; }
From source file:com.healthmarketscience.jackcess.ImportUtil.java
/** * Splits the given line using the given delimiter pattern and quote * character. May read additional lines for quotes spanning newlines. *///from www . j a v a2 s . c o m private static Object[] splitLine(String line, Pattern delim, char quote, BufferedReader in, int numColumns) throws IOException { List<String> tokens = new ArrayList<String>(); StringBuilder sb = new StringBuilder(); Matcher m = delim.matcher(line); int idx = 0; while (idx < line.length()) { if (line.charAt(idx) == quote) { // find quoted value sb.setLength(0); ++idx; while (true) { int endIdx = line.indexOf(quote, idx); if (endIdx >= 0) { sb.append(line, idx, endIdx); ++endIdx; if ((endIdx < line.length()) && (line.charAt(endIdx) == quote)) { // embedded quote sb.append(quote); // keep searching idx = endIdx + 1; } else { // done idx = endIdx; break; } } else { // line wrap sb.append(line, idx, line.length()); sb.append(LINE_SEPARATOR); idx = 0; line = in.readLine(); if (line == null) { throw new EOFException("Missing end of quoted value " + sb); } } } tokens.add(sb.toString()); // skip next delim idx = (m.find(idx) ? m.end() : line.length()); } else if (m.find(idx)) { // next unquoted value tokens.add(line.substring(idx, m.start())); idx = m.end(); } else { // trailing token tokens.add(line.substring(idx)); idx = line.length(); } } return tokens.toArray(new Object[Math.max(tokens.size(), numColumns)]); }
From source file:tr.edu.gsu.nerwip.recognition.internal.modelless.subee.Subee.java
/** * Handles the name of the person described in the processed article. For this matter, * we consider the article title and name, as well as the first sentence, which generally * starts with the full name of the person. * /*from w ww . jav a 2 s. c o m*/ * @param article * Article to process. * @return * List of possible entities based on the analysis of the article title and name. * * @throws ClientProtocolException * Problem while accessing Freebase. * @throws ParseException * Problem while accessing Freebase. * @throws IOException * Problem while accessing Freebase. * @throws org.json.simple.parser.ParseException * Problem while accessing Freebase. */ private List<AbstractEntity<?>> processMainName(Article article) throws ClientProtocolException, ParseException, IOException, org.json.simple.parser.ParseException { logger.increaseOffset(); List<AbstractEntity<?>> result = new ArrayList<AbstractEntity<?>>(); String rawText = article.getRawText(); // init candidate strings with article name and title Set<String> candidateStrings = new TreeSet<String>(); String articleTitle = article.getTitle(); //debug //if(articleTitle.equals("Alfred Lothar Wegener")) // System.out.print(""); logger.log("Article title: " + articleTitle); candidateStrings.add(articleTitle); String articleName = article.getName(); logger.log("Article name: " + articleName); articleName = articleName.replace('_', ' ').trim(); candidateStrings.add(articleName); // process the beginning of the first sentence // we look for the string before the first parenthesis (usually containing birth info) // if there's none, we just ignore this potential information source Pattern p = Pattern.compile("^[^\\.]+?\\("); Matcher m = p.matcher(rawText); if (m.find()) { int startPos = m.start(); if (startPos == 0) { int endPos = m.end(); String persName = rawText.substring(0, endPos - 1); persName = persName.trim(); int wordCount = persName.length() - persName.replaceAll(" ", "").length(); if (wordCount > 6) logger.log( "Not able to extract person name from first sentence (too many words before the parenthesis): \"" + rawText.substring(0, 75) + "\""); else { logger.log("Person name: " + persName); candidateStrings.add(persName); } } } else logger.log("Not able to extract person name from first sentence (can't find the parenthesis): \"" + rawText.substring(0, 75) + "\""); // possibly remove double quotes (especially for the nicknames) List<String> nickFull = new ArrayList<String>(); Set<String> copy = new TreeSet<String>(candidateStrings); candidateStrings.clear(); for (String candidateString : copy) { if (candidateString.contains("\"")) { nickFull.add(candidateString); candidateString = candidateString.replaceAll("\"", ""); } candidateStrings.add(candidateString); } // possibly remove an indication in parenthesis at the end (especially for the titles) copy = new TreeSet<String>(candidateStrings); candidateStrings.clear(); for (String candidateString : copy) { if (candidateString.endsWith(")")) { String temp[] = candidateString.split("\\("); candidateString = temp[0].trim(); } candidateStrings.add(candidateString); } // add the lastname alone; only with the preceeding word; only with the 2 preeceding words, etc. copy = new TreeSet<String>(candidateStrings); for (String candidateString : copy) { String split[] = candidateString.split(" "); for (int i = split.length - 1; i >= 0; i--) { String temp = ""; for (int j = i; j < split.length; j++) temp = temp + split[j] + " "; temp = temp.trim(); candidateStrings.add(temp); } } // add very first and very last names (for more than 2 words) copy = new TreeSet<String>(candidateStrings); for (String candidateString : copy) { String split[] = candidateString.split(" "); if (split.length > 2) { String temp = split[0] + " " + split[split.length - 1]; candidateStrings.add(temp); } } // add variants with initials instead of firstnames copy = new TreeSet<String>(candidateStrings); for (String candidateString : copy) { String split[] = candidateString.split(" "); if (split.length > 1) { String initials1 = ""; String initials2 = ""; for (int i = 0; i < split.length - 1; i++) { initials1 = initials1 + split[i].substring(0, 1).toUpperCase(Locale.ENGLISH) + ". "; initials2 = initials2 + split[i].substring(0, 1).toUpperCase(Locale.ENGLISH) + "."; } initials1 = initials1 + split[split.length - 1]; initials2 = initials2 + " " + split[split.length - 1]; candidateStrings.add(initials1); candidateStrings.add(initials2); } } // add the original version of the nicknames candidateStrings.addAll(nickFull); // look for similar strings in the text for (String expr : candidateStrings) { String escapedStr = Pattern.quote(expr); p = Pattern.compile("\\b" + escapedStr + "\\b"); m = p.matcher(rawText); while (m.find()) { int startPos = m.start(); int endPos = m.end(); String valueStr = m.group(); AbstractEntity<?> ent = AbstractEntity.build(EntityType.PERSON, startPos, endPos, RecognizerName.SUBEE, valueStr); result.add(ent); } } if (result.isEmpty()) logger.log("WARNING: title not found at all in the text, which is unusual"); logger.decreaseOffset(); return result; }
From source file:com.manydesigns.portofino.pageactions.text.TextAction.java
protected String processAttachmentUrls(String content) { String baseUrl = StringEscapeUtils.escapeHtml(generateViewAttachmentUrl("").replace("?", "\\?")); String patternString = "([^\\s\"]+)\\s*=\\s*\"\\s*" + baseUrl + "([^\"]+)\""; Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(content); int lastEnd = 0; StringBuilder sb = new StringBuilder(); while (matcher.find()) { String hrefAttribute = matcher.group(1); String attachmentId = matcher.group(2); sb.append(content.substring(lastEnd, matcher.start())); sb.append("portofino:attachment=\"").append(attachmentId).append("\" "); sb.append("portofino:hrefAttribute=\"").append(hrefAttribute).append("\""); lastEnd = matcher.end(); }/*from ww w.ja v a 2s .c o m*/ sb.append(content.substring(lastEnd)); return sb.toString(); }
From source file:org.mobisocial.corral.ContentCorral.java
private static void scrapePage(File storageDir, Uri baseUri, String relativePath) throws IOException { File sourceFile = new File(storageDir, relativePath); String page = IOUtils.toString(new FileInputStream(sourceFile)); Matcher matcher = sScriptRegex.matcher(page); int offset = 0; while (matcher.find(offset)) { try {/*from w w w . j a v a 2 s . c om*/ String tag = matcher.group(); Matcher srcMatcher = sSrcRegex.matcher(tag); if (!srcMatcher.find()) continue; String srcPath = srcMatcher.group(1); srcPath = srcPath.substring(1, srcPath.length() - 1); srcPath = StringEscapeUtils.unescapeHtml4(srcPath); //srcPath = absoluteToRelative(baseUri, srcPath); if (!srcPath.contains("://")) { Uri absolutePath = getAbsoluteUri(baseUri, relativePath, srcPath); downloadFile(storageDir, absolutePath, absolutePath.getPath()); } } finally { offset = matcher.end(); } } }
From source file:net.sf.logsaw.dialect.log4j.pattern.Log4JConversionPatternTranslator.java
@Override public List<ConversionRule> extractRules(String externalPattern) throws CoreException { // Find supported conversion characters Matcher m = EXTRACTION_PATTERN.matcher(externalPattern); List<ConversionRule> ret = new ArrayList<ConversionRule>(); while (m.find()) { String minWidthModifier = m.group(2); String maxWidthModifier = m.group(4); String conversionName = m.group(5); String conversionModifier = m.group(7); int minWidth = -1; // not specified if ((minWidthModifier != null) && (minWidthModifier.length() > 0)) { minWidth = Integer.parseInt(minWidthModifier); }// ww w . j a v a 2 s .c o m int maxWidth = -1; // not specified if ((maxWidthModifier != null) && (maxWidthModifier.length() > 0)) { maxWidth = Integer.parseInt(maxWidthModifier); } ConversionRule rule = new ConversionRule(); rule.setBeginIndex(m.start()); rule.setLength(m.end() - m.start()); rule.setMaxWidth(maxWidth); rule.setMinWidth(minWidth); rule.setPlaceholderName(conversionName); rule.setModifier(conversionModifier); if (conversionName.equals("n")) { rule.setLineBreak(true); } ret.add(rule); } return ret; }
From source file:org.springframework.core.util.AntPathStringMatcher.java
private Pattern createPattern(final String pattern) { StringBuilder patternBuilder = new StringBuilder(); Matcher m = GLOB_PATTERN.matcher(pattern); int end = 0;// ww w . java2 s . c om while (m.find()) { patternBuilder.append(quote(pattern, end, m.start())); String match = m.group(); if ("?".equals(match)) { patternBuilder.append('.'); } else if ("*".equals(match)) { patternBuilder.append(".*"); } else if (match.startsWith("{") && match.endsWith("}")) { int colonIdx = match.indexOf(':'); if (colonIdx == -1) { patternBuilder.append(DEFAULT_VARIABLE_PATTERN); variableNames.add(m.group(1)); } else { String variablePattern = match.substring(colonIdx + 1, match.length() - 1); patternBuilder.append('('); patternBuilder.append(variablePattern); patternBuilder.append(')'); String variableName = match.substring(1, colonIdx); variableNames.add(variableName); } } end = m.end(); } patternBuilder.append(quote(pattern, end, pattern.length())); return Pattern.compile(patternBuilder.toString()); }
From source file:com.twosigma.beaker.r.utils.RServerEvaluator.java
protected String fixSvgResults(String xml) { Pattern pat = Pattern.compile("<use xlink:href=\"#([^\"]+)\" x=\"([^\"]+)\" y=\"([^\"]+)\"/>"); xml = xml.replace("d=\"\"", ""); xml = xml.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", ""); while (true) { Matcher matcher = pat.matcher(xml); if (!matcher.find()) { break; }//from w w w . j a va 2 s .com String expansion = "<g transform=\"translate(" + matcher.group(2) + "," + matcher.group(3) + ")\">\n"; String glyph = matcher.group(1); int gi = xml.indexOf(glyph); int pathStart = xml.indexOf("<path", gi); int pathStop = xml.indexOf("/>", pathStart); String path = xml.substring(pathStart, pathStop + 2); expansion = expansion + path + "</g>\n"; xml = xml.substring(0, matcher.start()) + expansion + xml.substring(matcher.end()); } int defsStart = xml.indexOf("<defs>"); if (defsStart >= 0) { int defsStop = xml.indexOf("</defs>"); xml = xml.substring(0, defsStart) + xml.substring(defsStop + 7); } return xml; }