List of usage examples for java.util.regex Pattern CASE_INSENSITIVE
int CASE_INSENSITIVE
To view the source code for java.util.regex Pattern CASE_INSENSITIVE.
Click Source Link
From source file:com.logsniffer.event.publisher.MailPublisherTest.java
@Test public void testMailPublishing() throws PublishException { final Event event = new Event(); event.setId("3"); event.setLogPath("path.log"); event.setLogSourceId(7);/*from w ww .j a v a 2 s . c o m*/ event.setSnifferId(5); final Map<String, Serializable> data = new HashMap<String, Serializable>(); data.put("key1", "abc"); data.put("key3", "def"); event.putAll(data); final List<LogEntry> entries = new ArrayList<LogEntry>(); final LogEntry e1 = new LogEntry(); e1.setRawContent("e1"); final LogEntry e2 = new LogEntry(); e2.setRawContent("e2"); entries.add(e1); entries.add(e2); event.setEntries(entries); mailPublisher.setSubject("Subject: $event.lf_entries[0].lf_raw"); mailPublisher.setFrom("fromme $event"); mailPublisher.setTo("tome$event,toyou"); final MailPublisher clonePublisher = configManager.createBeanFromJSON(MailPublisher.class, configManager.saveBeanToJSON(mailPublisher)); clonePublisher.publish(event); Mockito.verify(mailSender).send(Mockito.argThat(new BaseMatcher<SimpleMailMessage>() { @Override public boolean matches(final Object arg0) { final SimpleMailMessage mail = (SimpleMailMessage) arg0; if (!mail.getSubject().equals("Subject: " + e1.getRawContent())) { return false; } final Pattern textPattern = Pattern.compile( "[^\n]+/c/sniffers/5/events/#/3\n\n" + "Log entries:\n" + "\\s*e1\n" + "\\s*e2\n\\s*", Pattern.CASE_INSENSITIVE + Pattern.DOTALL + Pattern.MULTILINE); if (!textPattern.matcher(mail.getText()).matches()) { return false; } return mail.getFrom().equals("fromme $event") && mail.getTo().length == 2 && mail.getTo()[0].equals("tome$event") && mail.getTo()[1].equals("toyou"); } @Override public void describeTo(final Description arg0) { } })); }
From source file:com.seer.datacruncher.validation.MacroRulesValidation.java
/** * Apply validation macro rules.//from ww w . j av a2 s. c o m * @param datastreamDTO * @return ResultStepValidation */ protected ResultStepValidation doValidation(DatastreamDTO datastreamDTO) { long schemaId = datastreamDTO.getIdSchema(); List<MacroEntity> list = new ArrayList<MacroEntity>(); DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder .parse(new ByteArrayInputStream(schemasXSDDao.find(schemaId).getSchemaXSD().getBytes())); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile("//annotation/appinfo/text()"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { String val = nodes.item(i).getNodeValue(); if (val.startsWith("@RuleCheck")) { String[] arr = val.split(";\n"); for (String s : arr) { list.add(macrosDao.getMacroEntityByName(s.trim().substring(11))); } break; } } } catch (ParserConfigurationException e) { log.error("ParserConfigurationException", e); } catch (SAXException e) { log.error("SAXException", e); } catch (IOException e) { log.error("IOException", e); } catch (XPathExpressionException e) { log.error("XPathExpressionException", e); } ResultStepValidation resultStepValidation = new ResultStepValidation(); resultStepValidation.setValid(true); resultStepValidation.setMessageResult(I18n.getMessage("success.validationOK")); List<Element> xmlTextNodes = null; try { xmlTextNodes = StreamsUtils.parseStreamXml(datastreamDTO.getOutput()); } catch (DocumentException e) { log.error("Stream parse exception", e); } JexlEngine jexl = JexlEngineFactory.getInstance(); boolean isSuccess = true; Pattern pattern = Pattern.compile(MACRO_SQL_VALIDATOR_PATTERN, Pattern.CASE_INSENSITIVE); for (MacroEntity ent : list) { if (!isSuccess) continue; String rule = ent.getRule(); List<Map<String, String>> varsList = parseVars(ent.getVars()); combineVariableLists(varsList, schemaId); Matcher matcher = pattern.matcher(rule); while (matcher.find()) { String varName = matcher.group(4); String sqlRes = "false"; for (Map<String, String> m : varsList) { if (m.get("uniqueName").equals(varName)) { for (Element el : xmlTextNodes) { int t = datastreamDTO.getIdStreamType(); String fieldPath = (t == StreamType.XML || t == StreamType.XMLEXI ? "" : "ROOT/") + m.get("nodePath"); if (fieldPath.equals(StreamsUtils.formatPathForXmlNode(el.getPath()))) { String prepSql = matcher.group().replaceAll(matcher.group(4), "\"" + el.getText() + "\""); String signum = matcher.group(3); if (signum.equals("<")) { prepSql = prepSql.replaceAll(signum, ">="); } else if (signum.equals(">")) { prepSql = prepSql.replaceAll(signum, "<="); } else if (signum.equals("!=")) { prepSql = prepSql.replaceAll(signum, "="); } Query q = entityManager.createNativeQuery(prepSql); @SuppressWarnings("rawtypes") List resList = q.getResultList(); if ((signum.equals("=") && resList.size() > 0) || (signum.equals("!=") && resList.size() == 0) || (signum.equals(">") && resList.size() == 0) || (signum.equals("<") && resList.size() == 0)) { sqlRes = "true"; } break; } } } } rule = rule.replaceAll(matcher.group(), sqlRes); } Expression e = jexl.createExpression(rule); JexlContext context = new MapContext(); for (Map<String, String> m : varsList) { for (Element el : xmlTextNodes) { int t = datastreamDTO.getIdStreamType(); String fieldPath = (t == StreamType.XML || t == StreamType.XMLEXI ? "" : "ROOT/") + m.get("nodePath"); if (fieldPath.equals(StreamsUtils.formatPathForXmlNode(el.getPath()))) { context.set(m.get("uniqueName"), JEXLFieldFactory.getField(m.get("fieldType"), el.getText()).getValue()); break; } } } Object res = e.evaluate(context); if (res != null) { isSuccess = false; resultStepValidation.setValid(false); if (ent.getErrorType() == StreamStatus.Warning.getCode()) { resultStepValidation.setWarning(true); } resultStepValidation .setMessageResult(I18n.getMessage("error.validationMacro") + ": " + res.toString()); } } return resultStepValidation; }
From source file:infrascructure.data.vocabulary.SimpleVocabularyBuider.java
protected Collection<Word> retrieveWords(ResourceMetaData resource) { String wordPattern = WORD_PATTERN; Pattern pattern = Pattern.compile(wordPattern, Pattern.CASE_INSENSITIVE); String source = resource.getData(); Matcher matcher = pattern.matcher(source); HashMap<String, Word> wordsMap = new LinkedHashMap<>(200); while (matcher.find()) { String word = matcher.group().toLowerCase(); int indexOfAp = word.indexOf("'"); if (indexOfAp != -1) { String[] ww = word.split("'"); word = ww[0];/*from www .j a v a 2s . co m*/ } if (!stopWords.contains(word)) { String stemmedWord = stemmer.getCanonicalForm(word); if (!stopWords.contains(stemmedWord) && word.length() > 2) { Set<String> originalWords = wordsMap.containsKey(stemmedWord) ? wordsMap.get(stemmedWord).getOriginalWords() : new HashSet<>(); originalWords.add(word); if (!wordsMap.containsKey(stemmedWord)) { wordsMap.put(stemmedWord, new Word(stemmedWord, 1, originalWords)); } else { Word existedToken = wordsMap.get(stemmedWord); wordsMap.put(stemmedWord, new Word(stemmedWord, existedToken.getCount() + 1, originalWords)); } } } } return wordsMap.values(); }
From source file:edu.harvard.hms.dbmi.bd2k.irct.cl.filter.SessionFilter.java
private String validateAuthorizationHeader(HttpServletRequest req) { String authorizationHeader = ((HttpServletRequest) req).getHeader("Authorization"); if (authorizationHeader != null) { try {//from w w w . j a va 2 s . c om String[] parts = authorizationHeader.split(" "); if (parts.length != 2) { return null; } String scheme = parts[0]; String credentials = parts[1]; String token = ""; Pattern pattern = Pattern.compile("^Bearer$", Pattern.CASE_INSENSITIVE); if (pattern.matcher(scheme).matches()) { token = credentials; } byte[] secret = Base64.decodeBase64(this.clientSecret); Map<String, Object> decodedPayload = new JWTVerifier(secret, this.clientId).verify(token); return (String) decodedPayload.get(this.userField); } catch (InvalidKeyException | NoSuchAlgorithmException | IllegalStateException | SignatureException | IOException | JWTVerifyException e) { System.out.println("TOKEN VALIDATION FAILED: " + e.getMessage()); } } return null; }
From source file:de.yaio.commons.data.DataUtils.java
/** * extract url from string (defaults if not set scheme:http host:localhost port:80) * @param value string to extract url from * @return the extracted url * @throws MalformedURLException possible invalid URL *//*from w w w . j a v a2 s . c o m*/ public static URL extractWebUrl(final String value) throws MalformedURLException { if (StringUtils.isEmpty(value)) { LOGGER.warn("cant parse url from empty value"); return null; } // define url-pattern String urlPattern = "(https?://)?([-a-zA-Z\\.]+)(:[0-9]+)?(\\?.*)?$"; Pattern pattern = Pattern.compile(urlPattern, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(value); URL url = null; // extract url-parts if matches if (matcher.matches()) { int matcherindex = 1; String protocol = "http"; if (LOGGER.isDebugEnabled()) { LOGGER.debug("Pattern: " + pattern + " " + matcherindex + ":" + matcher.group(matcherindex)); } if (matcher.group(matcherindex) != null) { protocol = matcher.group(matcherindex).toLowerCase().trim(); } matcherindex = 2; String host = "localhost"; if (LOGGER.isDebugEnabled()) { LOGGER.debug("Pattern: " + pattern + " " + matcherindex + ":" + matcher.group(matcherindex)); } if (matcher.group(matcherindex) != null) { host = matcher.group(matcherindex).toLowerCase().trim(); } matcherindex = 3; int port = 80; if (LOGGER.isDebugEnabled()) { LOGGER.debug("Pattern: " + pattern + " " + matcherindex + ":" + matcher.group(matcherindex)); } if (matcher.group(matcherindex) != null) { port = Integer.parseInt(matcher.group(matcherindex).trim()); } matcherindex = 4; String context = ""; if (LOGGER.isDebugEnabled()) { LOGGER.debug("Pattern: " + pattern + " " + matcherindex + ":" + matcher.group(matcherindex)); } if (matcher.group(matcherindex) != null) { context = matcher.group(matcherindex).trim(); } url = new URL(protocol, host, port, context); LOGGER.debug("parsed url:" + url + " from value:" + value); return url; } // return not found LOGGER.warn("cant parse url from value:" + value); return null; }
From source file:br.com.blackhubos.eventozero.util.Framework.java
/** * Sistema eficiente para pegar umb oolean por uma String ou nmero. * * @param string A string a ser processada. Se comear com t, y, s ou 1 considerado true. * @return retorna se true ou false o valor processado. *//* w w w . ja v a 2 s . co m*/ public static boolean getBoolean(final String string) { final Pattern p = Pattern.compile("(t.*|y.*|1|allow|allows|can)", Pattern.CASE_INSENSITIVE); if (p.matcher(string.replaceAll("\\s", "")).matches()) { return true; } else { return false; } }
From source file:de.uniwue.info6.misc.StringTools.java
/** * * * @return/*from w w w . j a va 2 s. com*/ */ public static String stripHtmlTagsForQuestion(String text) { if (text != null) { text = text.replaceAll("(?i)<script.*?</script>", ""); text = text.replaceAll("(?i)<javascript.*?</javascript>", ""); text = text.replaceAll("(?i)<style.*?</style>", ""); String REGEX_FIELD = "<[^>]*>"; Matcher matcher = Pattern.compile(REGEX_FIELD, Pattern.CASE_INSENSITIVE).matcher(text); while (matcher.find()) { String snippet = matcher.group(); String snippetNoSpaces = snippet.replaceAll("[\\s\"\'0-9]", ""); if (!snippetNoSpaces.equals("<br>") && !snippetNoSpaces.equals("<br/>") && !snippetNoSpaces.equals("</span>") && !snippetNoSpaces.equals("<span>")) { if (snippetNoSpaces.startsWith("<span")) { if (!snippetNoSpaces.equals("<spanstyle=font-style:italic;>") && !snippetNoSpaces.equals("<spanstyle=text-decoration:underline;>") && !snippetNoSpaces.equals("<spanstyle=text-decoration:line-through;>") && !snippetNoSpaces.equals("<spanstyle=color:rgb(,,);>")) { text = text.replace(snippet, "<span>"); } } else { text = text.replaceFirst(snippet, ""); } } } } return text; }
From source file:fr.dudie.acrachilisync.tools.upgrade.IssueDescriptionReaderV1.java
/** * Extracts the list of bug occurrences from the description. * //from ww w . j a v a 2 s . co m * @param pDescription * the issue description * @param pStacktraceMD5 * the stacktrace MD5 hash the issue is related to * @return the ACRA bug occurrences listed in the description * @throws IssueParseException * malformed issue description */ private Map<String, Date> parseAcraOccurrencesTable(final String pDescription, final String pStacktraceMD5) throws IssueParseException { final Map<String, Date> occur = new HashMap<String, Date>(); // escape braces { and } to use strings in regexp final String header = IssueDescriptionUtilsV1.getOccurrencesTableHeader(); final String escHeader = Pattern.quote(header); // regexp to find occurrences tables final Pattern p = Pattern.compile(escHeader + IssueDescriptionUtilsV1.EOL + "(?:" + OCCURR_LINE_PATTERN + IssueDescriptionUtilsV1.EOL + "+)+", Pattern.DOTALL | Pattern.CASE_INSENSITIVE); final Matcher m = p.matcher(pDescription); if (m.find()) { // regexp to find occurrences lines final Pattern pLine = Pattern.compile(OCCURR_LINE_PATTERN); final Matcher mLine = pLine.matcher(m.group()); while (mLine.find()) { final StringTokenizer line = new StringTokenizer(mLine.group(), "|"); final String acraReportId = line.nextToken(); final String acraUserCrashDate = line.nextToken(); try { occur.put(acraReportId, IssueDescriptionUtilsV1.parseDate(acraUserCrashDate)); } catch (final ParseException e) { throw new IssueParseException("Unable to parse user crash date of ACRA report " + acraReportId, e); } } } else { throw new IssueParseException("No crash occurrence table found in the description"); } if (m.find()) { throw new IssueParseException("More than 1 occurrence table found in the description"); } if (MapUtils.isEmpty(occur)) { throw new IssueParseException("0 user crash occurrence found in the description"); } return occur; }
From source file:wuit.common.crawler.search.Crawler.java
public static String match(String content, String filter) { String val = ""; try {// ww w . ja v a2 s . com Matcher m = Pattern.compile(filter, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE).matcher(content); while (m.find()) { val = m.group(); break; } } catch (Exception e) { System.out.println("Composite Parse match " + e.getMessage()); } return val; }
From source file:net.riezebos.thoth.configuration.persistence.dbs.DDLExecuter.java
protected String applyDialect(String command) { String timestampRe = "\\{fn CURRENT_TIMESTAMP\\}"; command = command.replaceAll(timestampRe, databaseIdiom.getCurrentTimeDDL()); // Only translate create/alter statements boolean createOrAlter = command.toLowerCase().startsWith("create") || command.toLowerCase().startsWith("alter") || command.toLowerCase().startsWith("rename") || command.toLowerCase().startsWith("drop"); if (!createOrAlter) return command; for (TranslationPair wa : translations) { if (!wa.exclude(command)) { command = ThothUtil.replaceWord(command + " ", wa.getFrom(), wa.getTo(), SEPARATORS).trim(); }//from w w w . j a va2s . c om } for (TranslationPair wa : workarounds) { Pattern pattern = Pattern.compile(wa.getFrom(), Pattern.CASE_INSENSITIVE | Pattern.DOTALL); command = pattern.matcher(command).replaceAll(wa.getTo()); } command = databaseIdiom.applyDialect(command); return command; }