List of usage examples for java.util.regex Matcher end
public int end()
From source file:com.nuxeo.intranet.jenkins.web.JenkinsJobsActions.java
/** * Converts a job comment to HTML and parses JIRA issues to turn them into * links./*from w ww. j av a2s . co m*/ * * @param jiraUrl TODO */ public String getConvertedJobComment(String toConvert, String jiraURL, String[] jiraProjects) { if (toConvert == null) { return null; } if (StringUtils.isBlank(jiraURL) || jiraProjects == null || jiraProjects.length == 0) { toConvert = toConvert.replace("\n", "<br />\n"); return toConvert; } String res = ""; String regexp = "\\b(" + StringUtils.join(jiraProjects, "|") + ")-\\d+\\b"; Pattern pattern = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE); Matcher m = pattern.matcher(toConvert); int lastIndex = 0; boolean done = false; while (m.find()) { String jiraIssue = m.group(0); res += toConvert.substring(lastIndex, m.start()) + getJiraUrlTag(jiraURL, jiraIssue); lastIndex = m.end(); done = true; } if (done) { res += toConvert.substring(lastIndex); } else { res = toConvert; } res = res.replace("\n", "<br />\n"); return res; }
From source file:org.ops4j.pax.web.itest.tomcat.WarJSFTCIntegrationTest.java
@Test public void testJSF() throws Exception { LOG.debug("Testing JSF workflow!"); String response = testClient.testWebPath("http://127.0.0.1:8282/war-jsf-sample", "Please enter your name"); LOG.debug("Found JSF starting page: {}", response); int indexOf = response.indexOf("id=\"javax.faces.ViewState\" value="); String substring = response.substring(indexOf + 34); indexOf = substring.indexOf("\""); substring = substring.substring(0, indexOf); Pattern pattern = Pattern.compile("(input id=\"mainForm:j_id_\\w*)"); Matcher matcher = pattern.matcher(response); if (!matcher.find()) fail("Didn't find required input id!"); String inputID = response.substring(matcher.start(), matcher.end()); inputID = inputID.substring(inputID.indexOf('"') + 1); LOG.debug("Found ID: {}", inputID); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("mainForm:name", "Dummy-User")); nameValuePairs.add(new BasicNameValuePair("javax.faces.ViewState", substring.trim())); nameValuePairs.add(new BasicNameValuePair(inputID, "Press me")); nameValuePairs.add(new BasicNameValuePair("mainForm_SUBMIT", "1")); LOG.debug("Will send the following NameValuePairs: {}", nameValuePairs); testClient.testPost("http://127.0.0.1:8282/war-jsf-sample/faces/helloWorld.jsp", nameValuePairs, "Hello Dummy-User. We hope you enjoy Apache MyFaces", 200); }
From source file:com.norconex.importer.handler.transformer.impl.StripAfterTransformer.java
@Override protected void transformStringContent(String reference, StringBuilder content, ImporterMetadata metadata, boolean parsed, boolean partialContent) { if (stripAfterRegex == null) { LOG.error("No regular expression provided."); return;//from w ww. ja v a 2 s .co m } int flags = Pattern.DOTALL | Pattern.UNICODE_CASE; if (!caseSensitive) { flags = flags | Pattern.CASE_INSENSITIVE; } Pattern pattern = Pattern.compile(stripAfterRegex, flags); Matcher match = pattern.matcher(content); if (match.find()) { if (inclusive) { content.delete(match.start(), content.length()); } else { content.delete(match.end(), content.length()); } } }
From source file:com.conwet.xjsp.session.Negotiator.java
/** * Consume available data and returns a new state when a transition is * reached.//w w w . ja va 2 s. co m * * TODO: violates the least-surprise principle * * @param buffer * @return State to transit to or null * @throws ConnectionException */ private NegotiationPhase consumeData(StringBuilder buffer) throws ConnectionException { Matcher m; switch (phase) { case start: m = START_PATTERN.matcher(buffer); if (m.find()) { buffer.replace(0, m.end(), ""); return NegotiationPhase.header; } return null; case header: try { String header = JSONUtil.extractStanza(buffer); if (header == null) { return null; } JSONObject jsonHeader = (JSONObject) parser.parse(header); validateHeader(jsonHeader); extractFeaturePrefixes(jsonHeader); return NegotiationPhase.messages; } catch (ParseException ex) { throw new ConnectionException(ConnError.ProtocolSyntaxError, "Invalid header: " + ex.getMessage()); } case messages: m = MESSAGE_PATTERN.matcher(buffer); if (m.find()) { buffer.replace(0, m.end(), ""); return NegotiationPhase.finished; } return null; case finished: return null; default: // should never reach this point throw new IllegalStateException("Unexpected exception"); } }
From source file:com.flexive.war.filter.BrowserDetect.java
/** * Return the browser version, if available. * * @return the browser version, if available. * @since 3.1//from w ww. j a va 2 s. c o m */ public double getBrowserVersion() { if (browserVersion < 0) { final String versionString; final Browser browser = getBrowser(); if (BROWSER_VERSION_OVERRIDES.containsKey(browser)) { versionString = BROWSER_VERSION_OVERRIDES.get(browser); } else { versionString = BROWSER_IDS.get(browser); } final int pos = ua.indexOf(versionString); browserVersion = DEFAULT_VERSION; if (pos != -1) { final Matcher matcher = P_VERSION.matcher(ua); if (matcher.find(pos + versionString.length())) { try { browserVersion = Double.parseDouble(ua.substring(matcher.start(), matcher.end())); } catch (NumberFormatException e) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to extract browser version from user agent: '" + ua + "'"); } browserVersion = DEFAULT_VERSION; } } } } return browserVersion; }
From source file:disko.flow.analyzers.RegexpAnalyzer.java
private void processText(AnalysisContext<TextDocument> context, Ports ports, String docText, int offset) { String cleanText = cleanText(docText); for (Map.Entry<String, Pattern> e : patterns.entrySet()) { String tag = e.getKey();/* www .j a v a2s .c o m*/ Pattern p = e.getValue(); Matcher m = p.matcher(cleanText.replaceAll("[\\n\\r]", " ")); log.debug("Looking for " + tag); while (m.find()) { final String found = m.group(); final int start = m.start() + offset; final int end = m.end() + offset; DocumentAnn ann = new DocumentAnn(start, end, tag); log.debug("Found " + ann + ": " + found); if (saveAnnotations) { context.add(ann); } } } }
From source file:info.novatec.testit.livingdoc.html.HtmlDocumentBuilder.java
/** * Most regex implementations today do not build a DFA / NFA -- especially * those that offer backreferences (which are not "regular" at all). * // w ww .ja va 2 s . c o m * And because they do NOT build DFAs and NFAs, it's very simple to * construct pathological cases - e.g., "((a*)(a*))+b" can take * exponentially long to decide that aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac is * not in the language using the matching techniques commonly in use. * * Ori Berger * * @param text The text to check * @return boolean true, if the text matches pathological case, else false */ private boolean pathologicalCase(String text) { String tag = toRegex(CollectionUtil.first(tags)); String regex = String.format("(?is)(<\\s*(%s)\\s*.*?>)", tag); Matcher match = compile(regex).matcher(text); if (match.find()) { regex = String.format("(?is)(.*?)(<\\s*/\\s*(%s)\\s*.*?>)", tag); return !compile(regex).matcher(text).find(match.end()); } return true; }
From source file:org.jutge.joc.porra.service.EmailService.java
/** * Mighty delicate a process it is to send an email through the Raco webmail frontend. Let me break it down: * You need to log in as you'd normally do in the Raco. After a couple of redirects to the CAS server, you should be inside. * Then you issue a GET for the mail compose form. The response contains a form token to be used in the actual multipart POST that should send the mail. * The minute they change the login system or the webmail styles, this'll probably break down LOL: Let's hope they keep it this way til the Joc d'EDA is over * @param userAccount user to send the mail to * @param message the message body/*from w w w . jav a 2 s. c om*/ * @throws Exception should anything crash */ private void sendMail(final Account userAccount, final String message) throws Exception { // Enviar mail pel Raco // Authenticate final List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("service", "https://raco.fib.upc.edu/oauth/gestio-api/api.jsp")); params.add(new BasicNameValuePair("loginDirecte", "true")); params.add(new BasicNameValuePair("username", "XXXXXXXX")); params.add(new BasicNameValuePair("password", "XXXXXXXX")); HttpPost post = new HttpPost("https://raco.fib.upc.edu/cas/login"); post.setEntity(new UrlEncodedFormEntity(params)); final DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.setRedirectStrategy(new DefaultRedirectStrategy() { public boolean isRedirected(final HttpRequest request, final HttpResponse response, final HttpContext context) { boolean isRedirect = false; try { isRedirect = super.isRedirected(request, response, context); } catch (ProtocolException e) { EmailService.this.logger.error(e.getMessage()); } if (!isRedirect) { final int responseCode = response.getStatusLine().getStatusCode(); isRedirect = responseCode == 301 || responseCode == 302; } return isRedirect; } }); HttpResponse response = httpClient.execute(post); HttpEntity entity = response.getEntity(); EntityUtils.consumeQuietly(entity); // get form page final HttpGet get = new HttpGet("https://webmail.fib.upc.es/horde/imp/compose.php?thismailbox=INBOX&uniq=" + System.currentTimeMillis()); response = httpClient.execute(get); entity = response.getEntity(); String responseBody = EntityUtils.toString(entity); // Find form action with uniq parameter Pattern pattern = Pattern.compile(RacoUtils.RACO_MAIL_ACTION_PATTERN); Matcher matcher = pattern.matcher(responseBody); matcher.find(); final String action = matcher.group(); // formtoken responseBody = responseBody.substring(matcher.end(), responseBody.length()); pattern = Pattern.compile(RacoUtils.RACO_FORMTOKEN_PATTERN); matcher = pattern.matcher(responseBody); matcher.find(); String formToken = matcher.group(); formToken = formToken.substring(28, formToken.length()); // to final String email = userAccount.getEmail(); // Send mail - it's a multipart post final MultipartEntity multipart = new MultipartEntity(); multipart.addPart("MAX_FILE_SIZE", new StringBody("1038090240")); multipart.addPart("actionID", new StringBody("send_message")); multipart.addPart("__formToken_compose", new StringBody(formToken)); multipart.addPart("messageCache", new StringBody("")); multipart.addPart("spellcheck", new StringBody("")); multipart.addPart("page", new StringBody("")); multipart.addPart("start", new StringBody("")); multipart.addPart("thismailbox", new StringBody("INBOX")); multipart.addPart("attachmentAction", new StringBody("")); multipart.addPart("reloaded", new StringBody("1")); multipart.addPart("oldrtemode", new StringBody("")); multipart.addPart("rtemode", new StringBody("1")); multipart.addPart("last_identity", new StringBody("0")); multipart.addPart("from", new StringBody("porra-joc-eda@est.fib.upc.edu")); multipart.addPart("to", new StringBody(email)); multipart.addPart("cc", new StringBody("")); multipart.addPart("bcc", new StringBody("")); multipart.addPart("subject", new StringBody("Activacio Porra Joc EDA")); multipart.addPart("charset", new StringBody("UTF-8")); multipart.addPart("save_sent_mail", new StringBody("on")); multipart.addPart("message", new StringBody(message)); multipart.addPart("upload_1", new StringBody("")); multipart.addPart("upload_disposition_1", new StringBody("attachment")); multipart.addPart("save_attachments_select", new StringBody("0")); multipart.addPart("link_attachments", new StringBody("0")); post = new HttpPost("https://webmail.fib.upc.es/horde/imp/" + action); post.setEntity(multipart); response = httpClient.execute(post); EntityUtils.consumeQuietly(entity); this.logger.info("EmailService.sendMail done"); }
From source file:com.thoughtworks.go.domain.DefaultCommentRenderer.java
public String render(String text) { if (StringUtils.isBlank(text)) { return ""; }//from w w w . j a v a 2 s .c om if (regex.isEmpty() || link.isEmpty()) { Comment comment = new Comment(); comment.escapeAndAdd(text); return comment.render(); } try { Matcher matcher = Pattern.compile(regex).matcher(text); int start = 0; Comment comment = new Comment(); while (hasMatch(matcher)) { comment.escapeAndAdd(text.substring(start, matcher.start())); comment.add(dynamicLink(matcher)); start = matcher.end(); } comment.escapeAndAdd(text.substring(start)); return comment.render(); } catch (PatternSyntaxException e) { LOGGER.warn("Illegal regular expression: {} - {}", regex, e.getMessage()); } return text; }
From source file:com.asakusafw.workflow.executor.TaskExecutors.java
/** * Resolves a path string using the current context. * @param context the current task execution context * @param path the target path expression * @return the resolved path//from w ww . ja v a2 s .co m */ public static String resolvePath(TaskExecutionContext context, String path) { Matcher matcher = PATTERN_VARIABLE.matcher(path); int start = 0; StringBuilder buf = new StringBuilder(); while (matcher.find(start)) { buf.append(path, start, matcher.start()); switch (matcher.group(1)) { case VAR_USER: buf.append(getUserName(context)); break; case VAR_BATCH_ID: buf.append(context.getBatchId()); break; case VAR_FLOW_ID: buf.append(context.getFlowId()); break; case VAR_EXECUTION_ID: buf.append(context.getExecutionId()); break; default: throw new IllegalArgumentException( MessageFormat.format("unknown variable \"{1}\": {0}", path, matcher.group())); } start = matcher.end(); } buf.append(path, start, path.length()); return buf.toString(); }