List of usage examples for java.util.regex Pattern quote
public static String quote(String s)
From source file:org.springframework.core.util.AntPathStringMatcher.java
private String quote(final String s, final int start, final int end) { if (start == end) { return ""; }/* w w w . j a v a2 s. c o m*/ return Pattern.quote(s.substring(start, end)); }
From source file:hudson.plugins.copyartifact.CopyArtifactPermissionProperty.java
/** * package scope for testing purpose./* w ww .ja va 2 s . c om*/ * * @param name * @param pattern * @return whether name matches pattern. */ /*package*/ static boolean isNameMatch(String name, String pattern) { if (pattern == null || name == null) { return false; } if (!pattern.contains("*")) { // if no wild card, simply complete match. return pattern.equals(name); } List<String> literals = Arrays.asList(pattern.split("\\*", -1)); String regex = StringUtils.join(Lists.transform(literals, new Function<String, String>() { public String apply(String input) { return (input != null) ? Pattern.quote(input) : ""; } }), ".*"); return name.matches(regex); }
From source file:edu.kit.dama.staging.adapters.DefaultStorageVirtualizationAdapter.java
@Override public boolean configure(Configuration pConfig) throws ConfigurationException { pathPattern = pConfig.getString("pathPattern"); String archiveUrlProperty = pConfig.getString("archiveUrl"); if (archiveUrlProperty == null) { throw new ConfigurationException("Property 'archiveUrl' is missing"); }/*from w w w. j a v a 2s.co m*/ //replace TMP_DIR_PATTERN in target URL LOGGER.debug("Looking for replacements in archive location"); String tmp = System.getProperty("java.io.tmpdir"); if (!tmp.startsWith("/")) { tmp = "/" + tmp; } archiveUrlProperty = archiveUrlProperty.replaceAll(Pattern.quote(TMP_DIR_PATTERN), Matcher.quoteReplacement(tmp)); LOGGER.debug("Using archive Url {}", archiveUrlProperty); //set baseDestinationURL property try { archiveUrl = new URL(archiveUrlProperty); } catch (MalformedURLException mue) { throw new ConfigurationException("archiveUrl property (" + archiveUrlProperty + ") is not a valid URL", mue); } AbstractFile destination = new AbstractFile(archiveUrl); //if caching location is local, check accessibility if (destination.isLocal()) { LOGGER.debug("Archive URL is local. Checking accessibility."); URI uri = null; try { uri = destination.getUrl().toURI(); } catch (IllegalArgumentException ex) { //provided archive URL is no URI (e.g. file://folder/ -> third slash is missing after file:) throw new StagingIntitializationException( "Archive location " + destination.getUrl().toString() + " has an invalid URI syntax", ex); } catch (URISyntaxException ex) { LOGGER.warn("Failed to check local archive URL. URL " + destination.getUrl() + " seems not to be a valid URI.", ex); } File localFile = null; try { localFile = new File(uri); } catch (IllegalArgumentException ex) { throw new ConfigurationException("Archive URI " + uri + " seems not to be a supported file URI. This storage virtualization implementation only supports URLs in the format file:///<path>/", ex); } if (!FileUtils.isAccessible(localFile)) { throw new StagingIntitializationException( "Archive location seems to be offline: '" + destination.getUrl().toString() + "'"); } } try { if (!destination.exists()) { LOGGER.debug("Archive location does not exists, trying to create it..."); destination = AbstractFile.createDirectory(destination); LOGGER.debug("Archive location successfully created "); } else { LOGGER.debug("Archive location already exists"); } //clear cached values, e.g. for isReadable() and isWriteable() destination.clearCachedValues(); //check access if (destination.isReadable() && destination.isWriteable()) { LOGGER.debug("Archive location '{}' is valid", destination.getUrl()); } else { throw new StagingIntitializationException( "Archive location '" + destination.getUrl().toString() + "' is not accessible"); } } catch (AdalapiException ae) { throw new StagingIntitializationException( "Failed to setup archive location '" + destination.getUrl().toString() + "'", ae); } return true; }
From source file:hudson.plugins.project_inheritance.util.PathMapping.java
/** * Get the relative path from one file to another, specifying the directory separator. * If one of the provided resources does not exist, it is assumed to be a file unless it ends with '/' or * '\'./*w ww. j a va 2 s. com*/ * * @param targetPath targetPath is calculated to this file * @param basePath basePath is calculated from this file * @param pathSeparator directory separator. The platform default is not assumed so that we can test Unix behaviour when running on Windows (for example) * @return */ public static String getRelativePath(String targetPath, String basePath, String pathSeparator) { // Normalize the paths String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath); String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath); // Undo the changes to the separators made by normalization if (pathSeparator.equals("/")) { normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath); normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath); } else if (pathSeparator.equals("\\")) { normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath); normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath); } else { throw new IllegalArgumentException("Unrecognised dir separator '" + pathSeparator + "'"); } String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator)); String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator)); // First get all the common elements. Store them as a string, // and also count how many of them there are. StringBuilder common = new StringBuilder(); int commonIndex = 0; while (commonIndex < target.length && commonIndex < base.length && target[commonIndex].equals(base[commonIndex])) { common.append(target[commonIndex] + pathSeparator); commonIndex++; } if (commonIndex == 0) { // No single common path element. This most // likely indicates differing drive letters, like C: and D:. // These paths cannot be relativized. throw new PathResolutionException("No common path element found for '" + normalizedTargetPath + "' and '" + normalizedBasePath + "'"); } // The number of directories we have to backtrack depends on whether the base is a file or a dir // For example, the relative path from // // /foo/bar/baz/gg/ff to /foo/bar/baz // // ".." if ff is a file // "../.." if ff is a directory // // The following is a heuristic to figure out if the base refers to a file or dir. It's not perfect, because // the resource referred to by this path may not actually exist, but it's the best I can do boolean baseIsFile = true; File baseResource = new File(normalizedBasePath); if (baseResource.exists()) { baseIsFile = baseResource.isFile(); } else if (basePath.endsWith(pathSeparator)) { baseIsFile = false; } StringBuilder relative = new StringBuilder(); if (base.length != commonIndex) { int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex; for (int i = 0; i < numDirsUp; i++) { relative.append(".." + pathSeparator); } } relative.append(normalizedTargetPath.substring(common.length())); return relative.toString(); }
From source file:com.genentech.chemistry.openEye.apps.SDFMDLSSSMatcher.java
void run(String inFile) throws InterruptedException { long start = System.currentTimeMillis(); ifs = new oemolithread(inFile); // start nCpu instances of MDLSSSFind and submit them to the completionService for (int i = 0; i < nCpu; i++) { finder[i] = new MDLSSSFind(); completionService.submit(finder[i]); }//from w w w.j a va2 s . c o m int iCount = 0; int lastICount = 0; int nRunning = nCpu; // poll the running threads and output progress until all are done while (nRunning > 0) { if (completionService.poll(2, TimeUnit.SECONDS) != null) { nRunning--; } // print status report to stderr iCount = 0; for (int i = 0; i < nCpu; i++) iCount += finder[i].count; if (iCount == lastICount) continue; if (iCount / (4000 * nCpu) > lastICount / (4000 * nCpu)) { System.err.printf(" %d %dsec\n", iCount, (System.currentTimeMillis() - start) / 1000); } else { for (int i = lastICount; i < iCount - (100 * nCpu); i += (100 * nCpu)) System.err.print("."); } lastICount = iCount; } ifs.close(); ifs.delete(); ifs = null; int nMatches = 0; for (int i = 0; i < nCpu; i++) nMatches += finder[i].nMatches; inFile = inFile.replaceAll(".*" + Pattern.quote(File.separator), ""); System.err.printf("\nSDFMDLSSSMatcher: Read %d structures from %s, found %d matches. nCpu=%d %d sec\n", iCount, inFile, nMatches, nCpu, (System.currentTimeMillis() - start) / 1000); }
From source file:com.genentech.chemistry.openEye.apps.SDFCatsIndexer.java
private void printDescriptors(String inFile, String outFile) throws FileNotFoundException { oemolithread ifs = new oemolithread(inFile); PrintStream out;// w w w . ja v a 2 s . co m if (".tab".equals(outFile)) out = System.out; else out = new PrintStream(new BufferedOutputStream(new FileOutputStream(outFile))); long start = System.currentTimeMillis(); int iCounter = 0; //Structures in the SD file. indexer.printDescriptorHeader(out); OEMolBase mol = new OEGraphMol(); while (oechem.OEReadMolecule(ifs, mol)) { iCounter++; indexer.printDistanceDescriptors(out, mol); //Output "." to show that the program is running. if (iCounter % 100 == 0) System.err.print("."); if (iCounter % 4000 == 0) { System.err.printf(" %d %dsec\n", iCounter, (System.currentTimeMillis() - start) / 1000); } } mol.delete(); out.close(); ifs.close(); ifs.delete(); inFile = inFile.replaceAll(".*" + Pattern.quote(File.separator), ""); System.err.printf("%s: Read %d structures from %s. in %d sec\n", MY_NAME, iCounter, inFile, (System.currentTimeMillis() - start) / 1000); }
From source file:com.ngdata.hbaseindexer.cli.BaseCli.java
protected void printHelpHeader() throws IOException { String className = getClass().getName(); String helpHeaderPath = className.replaceAll(Pattern.quote("."), "/") + "_help_header.txt"; InputStream is = getClass().getClassLoader().getResourceAsStream(helpHeaderPath); if (is != null) { IOUtils.copy(is, System.out); System.out.println();//from w ww. j a v a2 s. c o m System.out.println(); } }
From source file:com.googlecode.noweco.webmail.lotus.LotusWebmailConnection.java
@SuppressWarnings("unchecked") public LotusWebmailConnection(final HttpClient httpclient, final HttpHost host, final String prefix) throws IOException { this.prefix = prefix; HttpGet httpGet;//from w w w . j a v a 2s .co m HttpResponse rsp; HttpEntity entity; String baseName = getClass().getPackage().getName().replace('.', '/') + "/lotus"; ResourceBundle bundleBrowser = null; for (Header header : (Collection<Header>) httpclient.getParams() .getParameter(ClientPNames.DEFAULT_HEADERS)) { if (header.getName().equals("Accept-Language")) { Matcher matcher = LANGUAGE_PATTERN.matcher(header.getValue()); if (matcher.find()) { String region = matcher.group(2); if (region != null && region.length() != 0) { bundleBrowser = ResourceBundle.getBundle(baseName, new Locale(matcher.group(1), region)); } else { bundleBrowser = ResourceBundle.getBundle(baseName, new Locale(matcher.group(1))); } } } } ResourceBundle bundleEnglish = ResourceBundle.getBundle(baseName, new Locale("en")); String deletePattern = "(?:" + Pattern.quote(bundleEnglish.getString("Delete")); if (bundleBrowser != null) { deletePattern = deletePattern + "|" + Pattern.quote(bundleBrowser.getString("Delete")) + ")"; } String emptyTrashPattern = "(?:" + Pattern.quote(bundleEnglish.getString("EmptyTrash")); if (bundleBrowser != null) { emptyTrashPattern = emptyTrashPattern + "|" + Pattern.quote(bundleBrowser.getString("EmptyTrash")) + ")"; } deleteDeletePattern = Pattern.compile( "_doClick\\('([^/]*/\\$V\\d+ACTIONS/[^']*)'[^>]*>" + deletePattern + "\\\\" + deletePattern); deleteEmptyTrashPattern = Pattern.compile( "_doClick\\('([^/]*/\\$V\\d+ACTIONS/[^']*)'[^>]*>" + deletePattern + "\\\\" + emptyTrashPattern); httpGet = new HttpGet(prefix + "/($Inbox)?OpenView"); rsp = httpclient.execute(host, httpGet); entity = rsp.getEntity(); String string = EntityUtils.toString(entity); if (entity != null) { LOGGER.trace("inbox content : {}", string); EntityUtils.consume(entity); } Matcher matcher = MAIN_PAGE_PATTERN.matcher(string); if (!matcher.find()) { throw new IOException("Unable to parse main page"); } pagePrefix = matcher.group(1); this.httpclient = httpclient; this.host = host; }
From source file:org.hawkular.listener.cache.InventoryHelper.java
/** * Get the list of metrics for given tenant, feed and metric type *///from w ww . j av a 2 s . co m static Observable<Metric.Blueprint> listMetricsForType(MetricsService metricsService, String tenantId, String feedId, MetricType.Blueprint metricType, long currentTime) { String escapedForRegex = Pattern.quote("|" + metricType.getId() + "|"); String tags = "module:inventory,feed:" + feedId + ",type:r,mtypes:.*" + escapedForRegex + ".*"; return metricsService.findMetricsWithFilters(tenantId, org.hawkular.metrics.model.MetricType.STRING, tags) .flatMap(metric -> { return metricsService.findStringData(metric.getMetricId(), 0, currentTime, false, 0, Order.DESC) .toList().map(dataPoints -> { try { return rebuildFromChunks(dataPoints); } catch (InvalidInventoryChunksException e) { e.addContext("metricType", metricType.getId()); e.addContext("metricId", metric.getId()); throw Throwables.propagate(e); } }).map(inv -> extractMetricsForType(inv, metricType.getId())).flatMap(Observable::from); }); }
From source file:com.github.shynixn.blockball.bukkit.logic.persistence.context.SqlDbContextImpl.java
private void connectInternal(Plugin plugin) { if (!plugin.getConfig().getBoolean("sql.enabled")) { try {//from ww w .ja v a 2 s. c o m if (!plugin.getDataFolder().exists()) plugin.getDataFolder().mkdir(); final File file = new File(plugin.getDataFolder(), "BlockBall.db"); if (!file.exists()) file.createNewFile(); this.enableData(SqlDbContextImpl.SQLITE_DRIVER, "jdbc:sqlite:" + file.getAbsolutePath(), null, null, this.retriever); try (final Connection connection = this.getConnection()) { this.execute("PRAGMA foreign_keys=ON", connection); } } catch (final SQLException e) { Bukkit.getLogger().log(Level.WARNING, "Cannot execute statement.", e); } catch (final IOException e) { Bukkit.getLogger().log(Level.WARNING, "Cannot read file.", e); } try (final Connection connection = this.getConnection()) { for (final String data : this.getStringFromFile("create-sqlite").split(Pattern.quote(";"))) { this.executeUpdate(data, connection); } } catch (final Exception e) { Bukkit.getLogger().log(Level.WARNING, "Cannot execute creation.", e); } } else { final FileConfiguration c = plugin.getConfig(); try { this.enableData(SqlDbContextImpl.MYSQL_DRIVER, "jdbc:mysql://", c.getString("sql.host"), c.getInt("sql.port"), c.getString("sql.database"), c.getString("sql.username"), c.getString("sql.password"), this.retriever); } catch (final IOException e) { Bukkit.getLogger().log(Level.WARNING, "Cannot connect to MySQL database!", e); Bukkit.getLogger().log(Level.WARNING, "Trying to connect to SQLite database....", e); plugin.getConfig().set("sql.enabled", false); this.connectInternal(plugin); return; } try (final Connection connection = this.getConnection()) { for (final String data : this.getStringFromFile("create-mysql").split(Pattern.quote(";"))) { this.executeUpdate(data, connection); } } catch (final Exception e) { Bukkit.getLogger().log(Level.WARNING, "Cannot execute creation.", e); Bukkit.getLogger().log(Level.WARNING, "Trying to connect to SQLite database....", e); plugin.getConfig().set("sql.enabled", false); this.connectInternal(plugin); } } }