List of usage examples for java.util.regex Pattern pattern
pattern
From source file:de.undercouch.bson4jackson.BsonParserTest.java
@Test public void parseComplex() throws Exception { BSONObject o = new BasicBSONObject(); o.put("Timestamp", new BSONTimestamp(0xAABB, 0xCCDD)); o.put("Symbol", new Symbol("Test")); o.put("ObjectId", new org.bson.types.ObjectId(Integer.MAX_VALUE, -2, Integer.MIN_VALUE)); Pattern p = Pattern.compile(".*", Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE | Pattern.UNICODE_CASE); o.put("Regex", p); Map<?, ?> data = parseBsonObject(o); assertEquals(new Timestamp(0xAABB, 0xCCDD), data.get("Timestamp")); assertEquals(new de.undercouch.bson4jackson.types.Symbol("Test"), data.get("Symbol")); ObjectId oid = (ObjectId) data.get("ObjectId"); assertEquals(Integer.MAX_VALUE, oid.getTime()); assertEquals(-2, oid.getMachine());/* ww w .j a v a 2 s. com*/ assertEquals(Integer.MIN_VALUE, oid.getInc()); Pattern p2 = (Pattern) data.get("Regex"); assertEquals(p.flags(), p2.flags()); assertEquals(p.pattern(), p2.pattern()); }
From source file:org.apache.hadoop.conf.TestConfiguration.java
public void testPattern() throws IOException { out = new BufferedWriter(new FileWriter(CONFIG)); startConfig();// w w w . jav a 2 s . c o m appendProperty("test.pattern1", ""); appendProperty("test.pattern2", "("); appendProperty("test.pattern3", "a+b"); endConfig(); Path fileResource = new Path(CONFIG); conf.addResource(fileResource); Pattern defaultPattern = Pattern.compile("x+"); // Return default if missing assertEquals(defaultPattern.pattern(), conf.getPattern("xxxxx", defaultPattern).pattern()); // Return null if empty and default is null assertNull(conf.getPattern("test.pattern1", null)); // Return default for empty assertEquals(defaultPattern.pattern(), conf.getPattern("test.pattern1", defaultPattern).pattern()); // Return default for malformed assertEquals(defaultPattern.pattern(), conf.getPattern("test.pattern2", defaultPattern).pattern()); // Works for correct patterns assertEquals("a+b", conf.getPattern("test.pattern3", defaultPattern).pattern()); }
From source file:org.jets3t.service.utils.FileComparer.java
/** * If a <code>.jets3t-ignore</code> file is present in the given directory, the file is read * and all the paths contained in it are coverted to regular expression Pattern objects. * If the parent directory's list of patterns is provided, any relevant patterns are also * added to the ignore listing. Relevant parent patterns are those with a directory prefix * that matches the current directory, or with the wildcard depth pattern (*.*./). * * @param directory/*from w w w . ja va2 s . c o m*/ * a directory that may contain a <code>.jets3t-ignore</code> file. If this parameter is null * or is actually a file and not a directory, an empty list will be returned. * @param parentIgnorePatternList * a list of Patterns that were applied to the parent directory of the given directory. If this * parameter is null, no parent ignore patterns are applied. * * @return * a list of Pattern objects representing the paths in the ignore file. If there is no ignore * file, or if it has no contents, the list returned will be empty. */ protected List<Pattern> buildIgnoreRegexpList(File directory, List<Pattern> parentIgnorePatternList) { List<Pattern> ignorePatternList = new ArrayList<Pattern>(); // Add any applicable ignore patterns found in ancestor directories if (parentIgnorePatternList != null) { Iterator<Pattern> parentIgnorePatternIter = parentIgnorePatternList.iterator(); while (parentIgnorePatternIter.hasNext()) { Pattern parentPattern = parentIgnorePatternIter.next(); String parentIgnorePatternString = parentPattern.pattern(); // If parent ignore pattern contains a slash, it is eligible for inclusion. int slashOffset = parentIgnorePatternString.indexOf(Constants.FILE_PATH_DELIM); if (slashOffset >= 0 && parentIgnorePatternString.length() > (slashOffset + 1)) { // Ensure there is at least 1 char after slash // Chop pattern into header and tail around first slash character. String patternHeader = parentIgnorePatternString.substring(0, slashOffset); String patternTail = parentIgnorePatternString.substring(slashOffset + 1); if (".*.*".equals(patternHeader)) { // ** patterns are special and apply to any directory depth, so add both the // pattern's tail to match in this directory, and the original pattern to match // again in descendent directories. ignorePatternList.add(Pattern.compile(patternTail)); ignorePatternList.add(parentPattern); } else if (Pattern.compile(patternHeader).matcher(directory.getName()).matches()) { // Adds pattern's tail section to ignore list for this directory, provided // the pre-slash pattern matches the current directory's name. ignorePatternList.add(Pattern.compile(patternTail)); } } } } if (directory == null || !directory.isDirectory()) { return ignorePatternList; } File jets3tIgnoreFile = new File(directory, Constants.JETS3T_IGNORE_FILENAME); if (jets3tIgnoreFile.exists() && jets3tIgnoreFile.canRead()) { if (log.isDebugEnabled()) { log.debug("Found ignore file: " + jets3tIgnoreFile.getPath()); } try { String ignorePaths = ServiceUtils.readInputStreamToString(new FileInputStream(jets3tIgnoreFile), null); StringTokenizer st = new StringTokenizer(ignorePaths.trim(), "\n"); while (st.hasMoreTokens()) { String ignorePath = st.nextToken(); // Convert path to RegExp. String ignoreRegexp = ignorePath; ignoreRegexp = ignoreRegexp.replaceAll("\\.", "\\\\."); ignoreRegexp = ignoreRegexp.replaceAll("\\*", ".*"); ignoreRegexp = ignoreRegexp.replaceAll("\\?", "."); Pattern pattern = Pattern.compile(ignoreRegexp); if (log.isDebugEnabled()) { log.debug("Ignore path '" + ignorePath + "' has become the regexp: " + pattern.pattern()); } ignorePatternList.add(pattern); if (pattern.pattern().startsWith(".*.*/") && pattern.pattern().length() > 5) { // **/ patterns are special and apply to any directory depth, including the current // directory. So add the pattern's after-slash tail to match in this directory as well. ignorePatternList.add(Pattern.compile(pattern.pattern().substring(5))); } } } catch (IOException e) { if (log.isErrorEnabled()) { log.error("Failed to read contents of ignore file '" + jets3tIgnoreFile.getPath() + "'", e); } } } if (isSkipMd5FileUpload()) { Pattern pattern = Pattern.compile(".*\\.md5"); if (log.isDebugEnabled()) { log.debug("Skipping upload of pre-computed MD5 files with path '*.md5' using the regexp: " + pattern.pattern()); } ignorePatternList.add(pattern); } return ignorePatternList; }
From source file:org.canova.api.conf.Configuration.java
/** * Set the given property to <code>Pattern</code>. * If the pattern is passed as null, sets the empty pattern which results in * further calls to getPattern(...) returning the default value. * * @param name property name//from w ww .ja va 2 s. c o m * @param pattern new value */ public void setPattern(String name, Pattern pattern) { if (null == pattern) { set(name, null); } else { set(name, pattern.pattern()); } }
From source file:org.opencms.configuration.CmsImportExportConfiguration.java
/** * @see org.opencms.configuration.I_CmsXmlConfiguration#generateXml(org.dom4j.Element) *///from w w w.ja va 2 s .com public Element generateXml(Element parent) { // generate import/export node and subnodes Element importexportElement = parent.addElement(N_IMPORTEXPORT); Element resourceloadersElement = importexportElement.addElement(N_IMPORTEXPORTHANDLERS); List<I_CmsImportExportHandler> handlers = m_importExportManager.getImportExportHandlers(); Iterator<I_CmsImportExportHandler> handlerIt = handlers.iterator(); while (handlerIt.hasNext()) { I_CmsImportExportHandler handler = handlerIt.next(); // add the handler node Element loaderNode = resourceloadersElement.addElement(N_IMPORTEXPORTHANDLER); loaderNode.addAttribute(A_CLASS, handler.getClass().getName()); } Element importElement = importexportElement.addElement(N_IMPORT); // <overwrite> node importElement.addElement(N_OVERWRITE) .setText(String.valueOf(m_importExportManager.overwriteCollidingResources())); // <convert> node importElement.addElement(N_CONVERT).setText(String.valueOf(m_importExportManager.convertToXmlPage())); // <oldwebappurl> node if (m_importExportManager.getOldWebAppUrl() != null) { importElement.addElement(N_OLDWEBAPPURL).setText(m_importExportManager.getOldWebAppUrl()); } // <importversions> node Element resourcetypesElement = importElement.addElement(N_IMPORTVERSIONS); Iterator<I_CmsImport> importVersions = m_importExportManager.getImportVersionClasses().iterator(); while (importVersions.hasNext()) { resourcetypesElement.addElement(N_IMPORTVERSION).addAttribute(A_CLASS, importVersions.next().getClass().getName()); } // <immutables> node Element immutablesElement = importElement.addElement(N_IMMUTABLES); Iterator<String> immutables = m_importExportManager.getImmutableResources().iterator(); while (immutables.hasNext()) { String uri = immutables.next(); immutablesElement.addElement(N_RESOURCE).addAttribute(A_URI, uri); } // <principaltranslations> node Element principalsElement = importElement.addElement(N_PRINCIPALTRANSLATIONS); Iterator<String> userTranslationKeys = m_importExportManager.getImportUserTranslations().keySet() .iterator(); while (userTranslationKeys.hasNext()) { String from = userTranslationKeys.next(); String to = m_importExportManager.getImportUserTranslations().get(from); principalsElement.addElement(N_PRINCIPALTRANSLATION).addAttribute(A_TYPE, I_CmsPrincipal.PRINCIPAL_USER) .addAttribute(A_FROM, from).addAttribute(A_TO, to); } Iterator<String> groupTranslationKeys = m_importExportManager.getImportGroupTranslations().keySet() .iterator(); while (groupTranslationKeys.hasNext()) { String from = groupTranslationKeys.next(); String to = m_importExportManager.getImportGroupTranslations().get(from); principalsElement.addElement(N_PRINCIPALTRANSLATION) .addAttribute(A_TYPE, I_CmsPrincipal.PRINCIPAL_GROUP).addAttribute(A_FROM, from) .addAttribute(A_TO, to); } // <ignoredproperties> node Element propertiesElement = importElement.addElement(N_IGNOREDPROPERTIES); Iterator<String> ignoredProperties = m_importExportManager.getIgnoredProperties().iterator(); while (ignoredProperties.hasNext()) { String property = ignoredProperties.next(); propertiesElement.addElement(N_PROPERTY).addAttribute(A_NAME, property); } // <staticexport> node Element staticexportElement = parent.addElement(N_STATICEXPORT); staticexportElement.addAttribute(A_ENABLED, m_staticExportManager.getExportEnabled()); // <staticexporthandler> node staticexportElement.addElement(N_STATICEXPORT_HANDLER) .addText(m_staticExportManager.getHandler().getClass().getName()); // <linksubstitutionhandler> node staticexportElement.addElement(N_LINKSUBSTITUTION_HANDLER) .addText(m_staticExportManager.getLinkSubstitutionHandler().getClass().getName()); // <exportpath> node String exportPathUnmodified = m_staticExportManager.getExportPathForConfiguration(); // cut path seperator if (exportPathUnmodified.endsWith(File.separator)) { exportPathUnmodified = exportPathUnmodified.substring(0, exportPathUnmodified.length() - 1); } staticexportElement.addElement(N_STATICEXPORT_EXPORTPATH).addText(exportPathUnmodified); // <exportworkpath> node String exportWorkPathUnmodified = m_staticExportManager.getExportWorkPathForConfiguration(); if (exportWorkPathUnmodified != null) { // cut path seperator if (exportWorkPathUnmodified.endsWith(File.separator)) { exportWorkPathUnmodified = exportWorkPathUnmodified.substring(0, exportWorkPathUnmodified.length() - 1); } staticexportElement.addElement(N_STATICEXPORT_EXPORTWORKPATH).addText(exportWorkPathUnmodified); } // <exportbackups> node if (m_staticExportManager.getExportBackups() != null) { String exportBackupsUnmodified = String.valueOf(m_staticExportManager.getExportBackups()); staticexportElement.addElement(N_STATICEXPORT_EXPORTBACKUPS).addText(exportBackupsUnmodified); } // <defaultpropertyvalue> node staticexportElement.addElement(N_STATICEXPORT_DEFAULT).addText(m_staticExportManager.getDefault()); // <defaultsuffixes> node and its <suffix> sub nodes Element defaultsuffixesElement = staticexportElement.addElement(N_STATICEXPORT_DEFAULTSUFFIXES); Iterator<String> exportSuffixes = m_staticExportManager.getExportSuffixes().iterator(); while (exportSuffixes.hasNext()) { String suffix = exportSuffixes.next(); Element suffixElement = defaultsuffixesElement.addElement(N_STATICEXPORT_SUFFIX); suffixElement.addAttribute(A_KEY, suffix); } // <exportheaders> node and its <header> sub nodes Iterator<String> exportHandlers = m_staticExportManager.getExportHeaders().iterator(); if (exportHandlers.hasNext()) { Element exportheadersElement = staticexportElement.addElement(N_STATICEXPORT_EXPORTHEADERS); while (exportHandlers.hasNext()) { String header = exportHandlers.next(); exportheadersElement.addElement(N_STATICEXPORT_HEADER).addText(header); } } // <requestheaders> node and the <acceptlanguage> and <acceptcharset> node String acceptlanguage = m_staticExportManager.getAcceptLanguageHeader(); String acceptcharset = m_staticExportManager.getAcceptCharsetHeader(); String remoteaddr = m_staticExportManager.getRemoteAddr(); if ((acceptlanguage != null) || (acceptcharset != null) || (remoteaddr != null)) { Element requestheadersElement = staticexportElement.addElement(N_STATICEXPORT_REQUESTHEADERS); if (acceptlanguage != null) { requestheadersElement.addElement(N_STATICEXPORT_ACCEPTLANGUAGE).addText(acceptlanguage); } if (acceptcharset != null) { requestheadersElement.addElement(N_STATICEXPORT_ACCEPTCHARSET).addText(acceptcharset); } if (remoteaddr != null) { requestheadersElement.addElement(N_STATICEXPORT_REMOTEADDR).addText(remoteaddr); } } // <rendersettings> node Element rendersettingsElement = staticexportElement.addElement(N_STATICEXPORT_RENDERSETTINGS); // <rfsPrefix> node rendersettingsElement.addElement(N_STATICEXPORT_RFS_PREFIX) .addText(m_staticExportManager.getRfsPrefixForConfiguration()); // <vfsPrefix> node rendersettingsElement.addElement(N_STATICEXPORT_VFS_PREFIX) .addText(m_staticExportManager.getVfsPrefixForConfiguration()); // <userelativelinks> node rendersettingsElement.addElement(N_STATICEXPORT_RELATIVELINKS) .addText(m_staticExportManager.getRelativeLinks()); // <exporturl> node rendersettingsElement.addElement(N_STATICEXPORT_EXPORTURL) .addText(m_staticExportManager.getExportUrlForConfiguration()); // <plainoptimization> node rendersettingsElement.addElement(N_STATICEXPORT_PLAINOPTIMIZATION) .addText(m_staticExportManager.getPlainExportOptimization()); // <testresource> node Element testresourceElement = rendersettingsElement.addElement(N_STATICEXPORT_TESTRESOURCE); testresourceElement.addAttribute(A_URI, m_staticExportManager.getTestResource()); // <resourcestorender> node and <regx> subnodes Element resourcetorenderElement = rendersettingsElement.addElement(N_STATICEXPORT_RESOURCESTORENDER); Iterator<String> exportFolderPatterns = m_staticExportManager.getExportFolderPatterns().iterator(); while (exportFolderPatterns.hasNext()) { String pattern = exportFolderPatterns.next(); resourcetorenderElement.addElement(N_STATICEXPORT_REGEX).addText(pattern); } if (!m_staticExportManager.getExportRules().isEmpty()) { // <export-rules> node Element exportRulesElement = resourcetorenderElement.addElement(N_STATICEXPORT_EXPORTRULES); Iterator<CmsStaticExportExportRule> exportRules = m_staticExportManager.getExportRules().iterator(); while (exportRules.hasNext()) { CmsStaticExportExportRule rule = exportRules.next(); // <export-rule> node Element exportRuleElement = exportRulesElement.addElement(N_STATICEXPORT_EXPORTRULE); exportRuleElement.addElement(N_STATICEXPORT_NAME).addText(rule.getName()); exportRuleElement.addElement(N_STATICEXPORT_DESCRIPTION).addText(rule.getDescription()); // <modified-resources> node and <regex> subnodes Element modifiedElement = exportRuleElement.addElement(N_STATICEXPORT_MODIFIED); Iterator<Pattern> itMods = rule.getModifiedResources().iterator(); while (itMods.hasNext()) { Pattern regex = itMods.next(); modifiedElement.addElement(N_STATICEXPORT_REGEX).addText(regex.pattern()); } // <export-resources> node and <uri> subnodes Element exportElement = exportRuleElement.addElement(N_STATICEXPORT_EXPORT); Iterator<String> itExps = rule.getExportResourcePatterns().iterator(); while (itExps.hasNext()) { String uri = itExps.next(); exportElement.addElement(N_STATICEXPORT_URI).addText(uri); } } } if (!m_staticExportManager.getRfsRules().isEmpty()) { // <rfs-rules> node Element rfsRulesElement = rendersettingsElement.addElement(N_STATICEXPORT_RFS_RULES); Iterator<CmsStaticExportRfsRule> rfsRules = m_staticExportManager.getRfsRules().iterator(); while (rfsRules.hasNext()) { CmsStaticExportRfsRule rule = rfsRules.next(); // <rfs-rule> node and subnodes Element rfsRuleElement = rfsRulesElement.addElement(N_STATICEXPORT_RFS_RULE); rfsRuleElement.addElement(N_STATICEXPORT_NAME).addText(rule.getName()); rfsRuleElement.addElement(N_STATICEXPORT_DESCRIPTION).addText(rule.getDescription()); rfsRuleElement.addElement(N_STATICEXPORT_SOURCE).addText(rule.getSource().pattern()); rfsRuleElement.addElement(N_STATICEXPORT_RFS_PREFIX).addText(rule.getRfsPrefixConfigured()); rfsRuleElement.addElement(N_STATICEXPORT_EXPORTPATH).addText(rule.getExportPathConfigured()); if (rule.getExportWorkPathConfigured() != null) { rfsRuleElement.addElement(N_STATICEXPORT_EXPORTWORKPATH) .addText(rule.getExportWorkPathConfigured()); } if (rule.getExportBackups() != null) { rfsRuleElement.addElement(N_STATICEXPORT_EXPORTBACKUPS) .addText(String.valueOf(rule.getExportBackups())); } if (rule.getUseRelativeLinks() != null) { rfsRuleElement.addElement(N_STATICEXPORT_RELATIVELINKS) .addText(rule.getUseRelativeLinks().toString()); } Element relatedSystemRes = rfsRuleElement.addElement(N_STATICEXPORT_RELATED_SYSTEM_RES); Iterator<Pattern> itSystemRes = rule.getRelatedSystemResources().iterator(); while (itSystemRes.hasNext()) { Pattern sysRes = itSystemRes.next(); relatedSystemRes.addElement(N_STATICEXPORT_REGEX).addText(sysRes.pattern()); } } } if (m_importExportManager.getUserExportSettings() != null) { // <usercsvexport> Element userExportElement = parent.addElement(N_USERCSVEXPORT); userExportElement.addElement(N_SEPARATOR) .setText(m_importExportManager.getUserExportSettings().getSeparator()); Element exportColumns = userExportElement.addElement(N_COLUMNS); List<String> exportColumnList = m_importExportManager.getUserExportSettings().getColumns(); Iterator<String> itExportColumnList = exportColumnList.iterator(); while (itExportColumnList.hasNext()) { exportColumns.addElement(N_COLUMN).setText(itExportColumnList.next()); } // </usercsvexport> } if (m_repositoryManager.isConfigured()) { List<A_CmsRepository> repositories = m_repositoryManager.getRepositories(); if (repositories != null) { // <repositories> node Element repositoriesElement = parent.addElement(N_REPOSITORIES); Iterator<A_CmsRepository> repositoriesIt = repositories.iterator(); while (repositoriesIt.hasNext()) { // <repository> node A_CmsRepository repository = repositoriesIt.next(); Element repositoryElement = repositoriesElement.addElement(N_REPOSITORY); repositoryElement.addAttribute(A_NAME, repository.getName()); repositoryElement.addAttribute(A_CLASS, repository.getClass().getName()); // <params> node CmsParameterConfiguration config = repository.getConfiguration(); if ((config != null) && (config.size() > 0)) { Element paramsElement = repositoryElement.addElement(N_PARAMS); config.appendToXml(paramsElement); } // <filter> node CmsRepositoryFilter filter = repository.getFilter(); if (filter != null) { List<Pattern> rules = filter.getFilterRules(); if (rules.size() > 0) { Element filterElement = repositoryElement.addElement(N_FILTER); filterElement.addAttribute(A_TYPE, filter.getType()); // <regex> nodes Iterator<Pattern> it = rules.iterator(); while (it.hasNext()) { Pattern rule = it.next(); filterElement.addElement(N_REGEX).addText(rule.pattern()); } } } } } } CmsExtendedHtmlImportDefault htmlimport = m_importExportManager.getExtendedHtmlImportDefault(true); if (htmlimport != null) { // <extendedhtmlimport> Element htmlImportElement = parent.addElement(N_EXTHTMLIMPORT); // <destination> node if (!CmsStringUtil.isEmptyOrWhitespaceOnly(htmlimport.getDestinationDir())) { htmlImportElement.addElement(N_EXTHTMLIMPORT_DESTINATION).setText(htmlimport.getDestinationDir()); } // <input> node if (!CmsStringUtil.isEmptyOrWhitespaceOnly(htmlimport.getInputDir())) { htmlImportElement.addElement(N_EXTHTMLIMPORT_INPUT).setText(htmlimport.getInputDir()); } // <galleries> node Element galleryElement = htmlImportElement.addElement(N_EXTHTMLIMPORT_GALLERIES); // <download> node if (!CmsStringUtil.isEmptyOrWhitespaceOnly(htmlimport.getDownloadGallery())) { galleryElement.addElement(N_EXTHTMLIMPORT_DOWNLOAD).setText(htmlimport.getDownloadGallery()); } // <image> node if (!CmsStringUtil.isEmptyOrWhitespaceOnly(htmlimport.getImageGallery())) { galleryElement.addElement(N_EXTHTMLIMPORT_IMAGE).setText(htmlimport.getImageGallery()); } // <externallink> node if (!CmsStringUtil.isEmptyOrWhitespaceOnly(htmlimport.getLinkGallery())) { galleryElement.addElement(N_EXTHTMLIMPORT_EXTERNALLINK).setText(htmlimport.getLinkGallery()); } // <settings> node Element settingElement = htmlImportElement.addElement(N_EXTHTMLIMPORT_SETTINGS); // <template> node settingElement.addElement(N_EXTHTMLIMPORT_TEMPLATE).setText(htmlimport.getTemplate()); // <element> node settingElement.addElement(N_EXTHTMLIMPORT_ELEMENT).setText(htmlimport.getElement()); // <locale> node settingElement.addElement(N_EXTHTMLIMPORT_LOCALE).setText(htmlimport.getLocale()); // <encoding> node settingElement.addElement(N_EXTHTMLIMPORT_ENCODING).setText(htmlimport.getEncoding()); // <pattern> node Element patternElement = settingElement.addElement(N_EXTHTMLIMPORT_PATTERN); // <start> node if (!CmsStringUtil.isEmptyOrWhitespaceOnly(htmlimport.getStartPattern())) { patternElement.addElement(N_EXTHTMLIMPORT_PATTERN_START).setText(htmlimport.getStartPattern()); } // <end> node if (!CmsStringUtil.isEmptyOrWhitespaceOnly(htmlimport.getEndPattern())) { patternElement.addElement(N_EXTHTMLIMPORT_PATTERN_END).setText(htmlimport.getEndPattern()); } // <overwrite> node settingElement.addElement(N_EXTHTMLIMPORT_OVERWRITE).setText(htmlimport.getOverwrite()); // <keepbrokenlinks> node settingElement.addElement(N_EXTHTMLIMPORT_KEEPBROKENLINKS).setText(htmlimport.getKeepBrokenLinks()); // </extendedhtmlimport> } // return the configured node return importexportElement; }
From source file:gtu._work.ui.JSFMakerUI.java
void resetPasteClipboardHtmlToJtable() { String content = ClipboardUtil.getInstance().getContents(); Pattern tdStartPattern = Pattern.compile("<[tT][dDhH][^>]*>"); Pattern tdEndPattern = Pattern.compile("</[tT][dDhH]>"); Pattern innerPattern_HasTag = Pattern.compile("<[\\w:]+\\s[^>]*value=\"([^\"]*)\"[^>]*>", Pattern.MULTILINE);//from w w w . j a v a 2s .c o m Matcher innerMatcher = null; Scanner scan = new Scanner(content); Scanner tdScan = null; String currentContent = null; String tdContent = null; StringBuilder sb = new StringBuilder(); scan.useDelimiter("<tr>"); for (; scan.hasNext();) { boolean anyMatcher = false; tdScan = new Scanner(scan.next()); tdScan.useDelimiter(tdStartPattern); while (tdScan.hasNext()) { tdScan.useDelimiter(tdEndPattern); if (tdScan.hasNext()) { tdContent = tdScan.next().replaceAll(tdStartPattern.pattern(), ""); { innerMatcher = innerPattern_HasTag.matcher(tdContent.toString()); if (innerMatcher.find()) { currentContent = StringUtils.defaultIfEmpty(innerMatcher.group(1), " "); // System.out.format("1[%s]\n", currentContent); sb.append(currentContent + "\t"); continue; } currentContent = tdContent.toString().replaceAll("<[\\w:=,.#;/'?\"\\s\\{\\}\\(\\)\\[\\]]+>", ""); currentContent = currentContent.replaceAll("[\\s\t\n]", ""); currentContent = StringUtils.defaultIfEmpty(currentContent, " "); // System.out.format("2[%s]\n", currentContent); sb.append(currentContent + "\t"); anyMatcher = true; } } tdScan.useDelimiter(tdStartPattern); } if (anyMatcher) { sb.append("\n"); } } scan.close(); ClipboardUtil.getInstance().setContents(sb); System.out.println("####################################"); System.out.println(sb); System.out.println("####################################"); }
From source file:org.jets3t.service.utils.FileComparer.java
/** * Determines whether a file should be ignored when building a file map. A file may be ignored * in two situations: 1) if it matches a regular expression pattern in the given list of * ignore patterns, or 2) if it is a symlink/alias and the JetS3tProperties setting * "filecomparer.skip-symlinks" is true. * * @param ignorePatternList/* w w w. jav a2 s . c o m*/ * a list of Pattern objects representing the file names to ignore. * @param file * a file that will either be ignored or not, depending on whether it matches an ignore Pattern * or is a symlink/alias. * * @return * true if the file should be ignored, false otherwise. */ protected boolean isIgnored(List<Pattern> ignorePatternList, File file) { if (isSkipSymlinks()) { /* * Check whether this file is actually a symlink/alias, and skip it if so. * Since Java IO libraries do not provide an official way to determine whether * a file is a symlink, we rely on a property of symlinks where the absolute * path to the symlink differs from the canonical path. This is hacky, but * mostly seems to work... */ try { if (!file.getAbsolutePath().equals(file.getCanonicalPath())) { if (log.isDebugEnabled()) { log.debug("Ignoring symlink " + (file.isDirectory() ? "directory" : "file") + ": " + file.getPath()); } // Skip symlink. return true; } } catch (IOException e) { log.warn("Unable to determine whether " + (file.isDirectory() ? "directory" : "file") + " '" + file.getAbsolutePath() + "' is a symlink", e); } } // Skip 'special' files that are neither files nor directories if (!file.isFile() && !file.isDirectory()) { if (log.isDebugEnabled()) { log.debug("Ignoring special file: " + file.getPath()); } return true; } Iterator<Pattern> patternIter = ignorePatternList.iterator(); while (patternIter.hasNext()) { Pattern pattern = patternIter.next(); if (pattern.matcher(file.getName()).matches()) { if (log.isDebugEnabled()) { log.debug("Ignoring " + (file.isDirectory() ? "directory" : "file") + " matching pattern '" + pattern.pattern() + "': " + file.getPath()); } return true; } } return false; }
From source file:org.jahia.modules.gateway.mail.MailToJSONImpl.java
@Handler public void handleExchange(Exchange exchange) { assert exchange.getIn() instanceof MailMessage; long timer = System.currentTimeMillis(); final Message mailMessage = ((MailMessage) exchange.getIn()).getMessage(); try {/*from w w w . j a v a 2 s.co m*/ String subject = mailMessage.getSubject(); Address[] from = mailMessage.getFrom(); Address sender = from != null && from.length > 0 ? from[0] : null; if (logger.isDebugEnabled()) { logger.debug("Got message from {} with the subject: {}", sender, subject); } // Parse content and multipart MailContent mailContent = new MailContent(); parseMailMessage(mailMessage, mailContent); if (logger.isTraceEnabled()) { logger.trace("Parsed message body:\n{} \n\nFiles:\n{}", mailContent.getBody(), mailContent.getFiles()); } Pattern matchingPattern = null; MailDecoder decoder = decoders.get("<default>"); // get the default decoder if any decodersLoop: for (MailDecoder examinee : decoders.values()) { List<Pattern> patterns = examinee.getPatterns(); if (patterns != null) { for (Pattern regexp : patterns) { if (matches(mailContent, regexp)) { decoder = examinee; matchingPattern = regexp; break decodersLoop; } } } } if (decoder != null) { if (logger.isDebugEnabled()) { if (matchingPattern == null) { logger.debug("Using default decoder '{}' ({}) for the e-mail", new String[] { decoder.getKey(), decoder.getClass().getName() }); } else { logger.debug("Using decoder '{}' ({}) for the e-mail matching pattern \"{}\"", new String[] { decoder.getKey(), decoder.getClass().getName(), matchingPattern.pattern() }); } } boolean deleteFiles = false; String jsonOutput = null; try { jsonOutput = decoder.decode(matchingPattern, mailContent, mailMessage); } catch (Exception e) { logger.error("Error processing e-mail message with subject \"" + subject + "\" using decoder " + decoder.getKey() + " from " + sender + ", Cause: " + e.getMessage(), e); deleteFiles = true; } if (StringUtils.isNotBlank(jsonOutput)) { if (logger.isTraceEnabled()) { logger.trace("Decoder output is:\n{}", jsonOutput); } DefaultMessage in = new DefaultMessage(); in.setBody(jsonOutput); exchange.setOut(in); } else { deleteFiles = true; } if (deleteFiles && !mailContent.getFiles().isEmpty()) { for (FileItem file : mailContent.getFiles()) { FileUtils.deleteQuietly(file.getFile()); } } } else { if (logger.isDebugEnabled()) { logger.debug("Skipping e-mail as no decoder configured to match subject: {}\n", subject); } } if (logger.isDebugEnabled()) { logger.debug("Message from {} with the subject '{}' processed in {} ms", new Object[] { sender, subject, System.currentTimeMillis() - timer }); } } catch (Exception e) { logger.error(e.getMessage(), e); } }
From source file:com.palantir.opensource.sysmon.linux.LinuxDiskspaceJMXWrapper.java
/** * Here's where the sausage gets made - run df in separate process and read its output into * {@link DfData} structures./*from w w w . j a v a2s . co m*/ * * @param cmd * @param headerPattern * @param dataPattern * @return parsed output of the df command * @throws LinuxMonitoringException */ private Map<String, DfData> readDfData(String[] cmd, Pattern headerPattern, Pattern dataPattern) throws LinuxMonitoringException { Map<String, DfData> result = new HashMap<String, DfData>(); BufferedReader stdout = null; InputStream stderr = null; OutputStream stdin = null; try { synchronized (this) { process = Runtime.getRuntime().exec(cmd); // (authorized) stdout = new BufferedReader(new InputStreamReader(process.getInputStream())); stderr = process.getErrorStream(); stdin = process.getOutputStream(); } String line = stdout.readLine(); if (line == null) { throw new LinuxMonitoringException("No data read from df process!"); } // Check header. Matcher m = headerPattern.matcher(line); if (!m.matches()) { throw new LinuxMonitoringException("Unexpected header from df process: " + line + ". " + "Did not mach with regex: " + headerPattern.pattern()); } // Read data. do { line = stdout.readLine(); if (line != null) { m = dataPattern.matcher(line); if (m.matches()) { DfData dfData = new DfData(m.group(1), // device name m.group(6), // mount point parseLongIgnoreAlpha(m.group(2)), // total parseLongIgnoreAlpha(m.group(3)), // used parseLongIgnoreAlpha(m.group(4)), // available parseByteIgnorePcnt(m.group(5))); // percentage used result.put(dfData.getDeviceName(), dfData); } else { String msg = "Df data line did not match: " + line + ". Pattern: " + dataPattern.pattern(); log.warn(msg); } } } while (line != null); } catch (IOException e) { throw new LinuxMonitoringException("Error while reading data from df process", e); } finally { IOUtils.closeQuietly(stdout); IOUtils.closeQuietly(stderr); IOUtils.closeQuietly(stdin); kill(); } return result; }
From source file:de.tudarmstadt.ukp.dkpro.core.textnormalizer.frequency.ExpressiveLengtheningNormalizer.java
public String getBestReplacement(String token) throws IOException { Pattern pattern = Pattern.compile("([a-zA-Z])\\1{1,}"); Matcher matcher = pattern.matcher(token); // In case there are no abnormalities if (!matcher.find()) return token; // Collecting the start points of all abnormal parts List<Integer> abnormalities = new ArrayList<Integer>(); matcher.reset();/* w w w . j a va 2 s . c o m*/ while (matcher.find()) { abnormalities.add(matcher.start()); } // splitting in parts starting with first character abnormalities List<String> parts = new ArrayList<String>(); for (int i = 0; i < abnormalities.size(); i++) { // in case the token has only one abnormality if (abnormalities.size() == 1) { parts.add(token); break; } // first abnormality if (i == 0) { parts.add(token.substring(0, abnormalities.get(i + 1))); continue; } // last abnormality if (i == abnormalities.size() - 1) { parts.add(token.substring(abnormalities.get(i))); continue; } if (i < abnormalities.size() - 1) { parts.add(token.substring(abnormalities.get(i), abnormalities.get(i + 1))); continue; } } // Fills big list of arrays with all parts and their versions List<String[]> bigList = new ArrayList<String[]>(); for (String part : parts) { String v1 = part.replaceFirst(pattern.pattern(), "$1"); String v2 = part.replaceFirst(pattern.pattern(), "$1$1"); String v3 = part.replaceFirst(pattern.pattern(), "$1$1$1"); bigList.add(new String[] { v1, v2, v3 }); } List<String> candidates = permute(bigList, 0, new ArrayList<String>(), ""); return getMostFrequentCandidate(candidates); }