List of usage examples for java.util.regex Pattern quote
public static String quote(String s)
From source file:com.adobe.ags.curly.controller.ActionRunner.java
private void applyVariablesToMap(Map<String, String> variables, Map<String, String> target) { Set<String> variableTokens = ActionUtils.getVariableNames(action); Set removeSet = new HashSet<>(); Map<String, String> newValues = new HashMap<>(); target.forEach((paramName, paramValue) -> { StringProperty paramNameProperty = new SimpleStringProperty(paramName); variableTokens.forEach((String originalName) -> { String[] variableNameParts = originalName.split("\\|"); String variableName = variableNameParts[0]; String variableNameMatchPattern = Pattern.quote("${" + originalName + "}"); String val = variables.get(variableName); if (val == null) { val = ""; }// ww w .j a v a2 s. co m String variableValue = Matcher.quoteReplacement(val); //---- String newParamValue = newValues.containsKey(paramNameProperty.get()) ? newValues.get(paramNameProperty.get()) : paramValue; String newParamName = paramNameProperty.get().replaceAll(variableNameMatchPattern, variableValue); paramNameProperty.set(newParamName); newParamValue = newParamValue.replaceAll(variableNameMatchPattern, variableValue); if (!newParamName.equals(paramName) || !newParamValue.equals(paramValue)) { removeSet.add(paramNameProperty.get()); removeSet.add(paramName); newValues.put(newParamName, newParamValue); } }); }); target.keySet().removeAll(removeSet); target.putAll(newValues); }
From source file:com.thoughtworks.go.config.materials.git.GitMaterialUpdaterTest.java
@Test public void shouldBombForFetchAndResetWhenSubmoduleUpdateFails() throws Exception { GitSubmoduleRepos submoduleRepos = new GitSubmoduleRepos(); File submoduleFolder = submoduleRepos.addSubmodule(SUBMODULE, "sub1"); GitMaterial material = new GitMaterial(submoduleRepos.projectRepositoryUrl(), true); FileUtils.deleteDirectory(submoduleFolder); assertThat(submoduleFolder.exists(), Matchers.is(false)); updateTo(material, new RevisionContext(new StringRevision("origin/HEAD")), JobResult.Failed); assertThat(console.output(),// ww w .j a va 2 s . c om // different versions of git use different messages // git on windows prints full submodule paths new RegexMatcher(String.format("[Cc]lone of '%s' into submodule path '((.*)[\\/])?sub1' failed", Pattern.quote(submoduleFolder.getAbsolutePath())))); }
From source file:de.tbuchloh.kiskis.persistence.PersistenceManager.java
private static void deleteOldBackups(final File file) { final File[] files = file.getParentFile().listFiles(new BackupFilter(file)); LOG.debug("found " + files.length + " backup files"); final List<File> sorted = new ArrayList<File>(Arrays.asList(files)); Collections.sort(sorted, FILE_BY_DATE); int toDelete = files.length - maxBackups + 1; for (int i = 0; i < sorted.size() && toDelete > 0; i++, toDelete--) { final File documentFile = sorted.get(i); LOG.debug("deleting document backup file " + documentFile.getName()); final String extension = getBackupExtension(documentFile); final String backupExtensionFilter = "(.*)" + Pattern.quote(extension); LOG.debug("backupExtensionFilter is " + backupExtensionFilter); for (final File f : listFiles(documentFile.getParentFile(), backupExtensionFilter)) { LOG.debug("Deleting backup file " + f); f.delete();//w w w . ja v a 2s.c om } } }
From source file:de.tarent.maven.plugins.pkg.AbstractMvnPkgPluginTestCase.java
protected boolean debRevisionIs(String s) throws MojoExecutionException, IOException { final Pattern p = Pattern.compile("Version:.*-" + Pattern.quote(s)); return debContains(p, "--info"); }
From source file:com.addthis.hydra.data.tree.prop.DataReservoir.java
private ValueObject generateValueObject(String key, String separator) { long targetEpoch = -1; int numObservations = -1; double sigma = Double.POSITIVE_INFINITY; double percentile = 0; boolean doubleToLongBits = false; int minMeasurement = Integer.MIN_VALUE; boolean raw = false; String mode = "sigma"; if (key == null) { return null; }//w w w. j av a2s .co m String[] kvpairs = key.split(Pattern.quote("~")); for (String kvpair : kvpairs) { String[] kv = kvpair.split(Pattern.quote(separator)); if (kv.length == 2) { String kvkey = kv[0]; String kvvalue = kv[1]; switch (kvkey) { case "double": doubleToLongBits = Boolean.parseBoolean(kvvalue); break; case "epoch": targetEpoch = Long.parseLong(kvvalue); break; case "sigma": sigma = Double.parseDouble(kvvalue); break; case "min": minMeasurement = Integer.parseInt(kvvalue); break; case "obs": numObservations = Integer.parseInt(kvvalue); break; case "raw": raw = Boolean.parseBoolean(kvvalue); break; case "percentile": percentile = Double.parseDouble(kvvalue); break; case "mode": mode = kvvalue; break; default: throw new RuntimeException("Unknown key " + kvkey); } } } if (mode.equals("get")) { long count = retrieveCount(targetEpoch); if (count < 0) { return ValueFactory.create(0L); } else { return ValueFactory.create(count); } } else { DataReservoirValue.Builder builder = new DataReservoirValue.Builder(); builder.setTargetEpoch(targetEpoch); builder.setNumObservations(numObservations); builder.setDoubleToLongBits(doubleToLongBits); builder.setRaw(raw); builder.setSigma(sigma); builder.setMinMeasurement(minMeasurement); builder.setPercentile(percentile); builder.setMode(mode); DataReservoirValue value = builder.build(this); return value; } }
From source file:edu.brown.workload.Workload.java
/** * //from w w w . j a v a 2s . co m * @param input_path * @param catalog_db * @param limit * @throws Exception */ public Workload load(File input_path, Database catalog_db, Filter filter) throws Exception { if (debug.val) LOG.debug("Reading workload trace from file '" + input_path + "'"); this.input_path = input_path; long start = System.currentTimeMillis(); // HACK: Throw out traces unless they have the procedures that we're looking for Pattern temp_pattern = null; if (filter != null) { List<ProcedureNameFilter> procname_filters = filter.getFilters(ProcedureNameFilter.class); if (procname_filters.isEmpty() == false) { Set<String> names = new HashSet<String>(); for (ProcedureNameFilter f : procname_filters) { for (String name : f.getProcedureNames()) { names.add(Pattern.quote(name)); } // FOR } // FOR if (names.isEmpty() == false) { temp_pattern = Pattern.compile( String.format("\"NAME\":[\\s]*\"(%s)\"", StringUtil.join("|", names)), Pattern.CASE_INSENSITIVE); if (debug.val) { LOG.debug(String.format("Fast filter for %d procedure names", names.size())); LOG.debug("PATTERN: " + temp_pattern.pattern()); } } } } final Pattern pattern = temp_pattern; final AtomicInteger counters[] = new AtomicInteger[] { new AtomicInteger(0), // ELEMENT COUNTER new AtomicInteger(0), // TXN COUNTER new AtomicInteger(0), // QUERY COUNTER new AtomicInteger(0), // WEIGHTED TXN COUNTER new AtomicInteger(0), // WEIGHTED QUERY COUNTER }; List<Runnable> all_runnables = new ArrayList<Runnable>(); int num_threads = ThreadUtil.getMaxGlobalThreads(); // Create the reader thread first WorkloadUtil.ReadThread rt = new WorkloadUtil.ReadThread(this.input_path, pattern, num_threads); all_runnables.add(rt); // Then create all of our processing threads for (int i = 0; i < num_threads; i++) { WorkloadUtil.ProcessingThread lt = new WorkloadUtil.ProcessingThread(this, this.input_path, rt, catalog_db, filter, counters); rt.processingThreads.add(lt); all_runnables.add(lt); } // FOR if (debug.val) LOG.debug(String.format("Loading workload trace using %d ProcessThreads", rt.processingThreads.size())); ThreadUtil.runNewPool(all_runnables, all_runnables.size()); VerifyWorkload.verify(catalog_db, this); long stop = System.currentTimeMillis(); LOG.info(String.format("Loaded %d txns / %d queries from '%s' in %.1f seconds using %d threads", this.txn_traces.size(), counters[2].get(), this.input_path.getName(), (stop - start) / 1000d, num_threads)); if (counters[1].get() != counters[3].get() || counters[2].get() != counters[4].get()) { LOG.info( String.format("Weighted Workload: %d txns / %d queries", counters[3].get(), counters[4].get())); } return (this); }
From source file:de.da_sense.moses.client.abstraction.apks.ExternalApplication.java
/** * Builds this {@link ExternalApplication} instance from consumed String. * @param s the String containing a serialized {@link ExternalApplication} instance. *///from w ww . j a v a2 s .c o m protected void initializeFromString(String s) { Log.d(LOG_TAG, "fromOnelineString : " + s); String[] split = s.split(Pattern.quote(SEPARATOR)); String ID = null; String name = null; String description = null; String newestVersion = null; String startDate = null; String endDate = null; String apkVersion = null; String questionnaireString = null; for (int i = 0; i < split.length; i++) { if (i == 0) { Log.d(LOG_TAG, "ID set to " + split[i].toString()); ID = split[i]; } else { if (split[i].startsWith(TAG_DESCRIPTION)) { description = fromLinebreakSubst(split[i].substring(TAG_DESCRIPTION.length())); } if (split[i].startsWith(TAG_NAME)) { name = fromLinebreakSubst(split[i].substring(TAG_NAME.length())); } if (split[i].startsWith(TAG_NEWESTVERSION)) { newestVersion = split[i].substring(TAG_NEWESTVERSION.length()); } if (split[i].startsWith(TAG_STARTDATE)) { startDate = split[i].substring(TAG_STARTDATE.length()); } if (split[i].startsWith(TAG_ENDDATE)) { endDate = split[i].substring(TAG_ENDDATE.length()); } if (split[i].startsWith(TAG_APKVERSION)) { apkVersion = split[i].substring(TAG_APKVERSION.length()); } if (split[i].startsWith(TAG_QUESTIONNAIRE)) { questionnaireString = split[i].substring(TAG_QUESTIONNAIRE.length()); } } } this.setID(ID); this.setName(name); this.setDescription(description); this.setNewestVersion(newestVersion); this.setStartDate(startDate); this.setEndDate(endDate); this.setApkVersion(apkVersion); Log.d(LOG_TAG, "questionnaire = " + questionnaireString); if (questionnaireString != null) if (questionnaireString.length() > 0) { Log.d(LOG_TAG, "has Local questionnaire " + questionnaireString); this.setQuestionnaire(questionnaireString); apkHasSurveyLocally = true; } else { apkHasSurveyLocally = false; } }
From source file:edu.stolaf.cs.wmrserver.TransformProcessor.java
private void copyLibraryFiles(SubnodeConfiguration languageConf, File jobTransformDir) throws IOException { // Get the library directory, returning if not specified File libDir = getLibraryDirectory(languageConf); if (libDir == null) return;/*from w w w . j ava 2s . c o m*/ // Get the file extension appropriate for the language String scriptExtension = languageConf.getString("extension", ""); if (!scriptExtension.isEmpty()) scriptExtension = "." + scriptExtension; // Create a file filter to exclude prefix/suffix files String pattern = "^(mapper|reducer)-(prefix|suffix)" + Pattern.quote(scriptExtension) + "$"; FileFilter libFilter = new NotFileFilter(new RegexFileFilter(pattern)); // Copy filtered contents of library directory FileUtils.copyDirectory(libDir, jobTransformDir, libFilter); }
From source file:com.replaymod.replaystudio.launcher.Launcher.java
public void parseConfig(Studio studio, String line, String[] args) { String ios = line.substring(1, line.indexOf(')')); String instructions = line.substring(line.indexOf(')') + 2, line.length() - 1); int arg = 0;// w ww .j a v a 2 s. c o m try { for (String ioi : ios.split(",")) { String io = ioi.substring(1); if (ioi.charAt(0) == '<') { inputs.put(io, args[arg++]); } else if (ioi.charAt(0) == '>') { outputs.put(io, args[arg++]); } else if (ioi.charAt(0) == '-') { pipes.add(io); } else { throw new IllegalArgumentException("Config input/output is invalid: " + ioi); } } } catch (IndexOutOfBoundsException e) { System.out.println("Insufficient input/output files. Need at least " + arg); throw new CriticalException(7); } for (String instructionStr : instructions.split(Pattern.quote(")("))) { String ins = instructionStr; List<String> inputs = new ArrayList<>(); List<String> outputs = new ArrayList<>(); // Read inputs OUTER: while (true) { for (int i = 0; i < ins.length(); i++) { char c = ins.charAt(i); if (!Character.isAlphabetic(c)) { inputs.add(ins.substring(0, i)); if (c == ',') { ins = ins.substring(i + 1); continue OUTER; } else { ins = ins.substring(i); break OUTER; } } } throw new IllegalArgumentException("Config input/output is invalid: " + instructionStr); } // Read outputs OUTER: while (true) { for (int i = ins.length() - 1; i >= 0; i--) { char c = ins.charAt(i); if (!Character.isAlphabetic(c)) { outputs.add(ins.substring(i + 1)); if (c == ',') { ins = ins.substring(0, i); continue OUTER; } else { ins = ins.substring(0, i + 1); break OUTER; } } } throw new IllegalArgumentException("Config instruction input/output is invalid: " + instructionStr); } Collections.reverse(outputs); String options = ins.length() > 1 ? ins.substring(1, ins.length() - 1) : ""; Instruction instruction; switch (ins.charAt(0)) { case '|': // split Collection<Long> splitAt = Collections2.transform(Arrays.asList(options.split(",")), this::timeStampToMillis); instruction = new SplitInstruction(Longs.toArray(splitAt)); break; case '&': // append instruction = new AppendInstruction(); break; case '[': // squash instruction = new SquashInstruction(studio); break; case ':': // copy instruction = new CopyInstruction(); break; case '>': // filter String filterName; JsonObject filterOptions; if (options.contains(",")) { String[] parts = options.split(",", 2); filterName = parts[0]; filterOptions = new JsonParser().parse(parts[1]).getAsJsonObject(); } else { filterName = options; filterOptions = new JsonObject(); } Filter filter = studio.loadFilter(filterName); if (filter == null) { throw new IllegalStateException("Filter not found: " + filterName); } instruction = new FilterInstruction(studio, filter, filterOptions); break; default: throw new IllegalArgumentException("Config instruction is unknown: " + instructionStr); } instruction.getInputs().addAll(inputs); instruction.getOutputs().addAll(outputs); this.instructions.add(instruction); } }
From source file:io.fabric8.tooling.archetype.generator.ArchetypeHelper.java
protected String replaceVariable(String text, String name, String value) { if (value.contains("}")) { System.out.println("Ignoring dodgy value '" + value + "'"); return text; } else {//from w ww . j a v a 2s . co m // System.out.println("Replacing '" + name + "' with '" + value + "'"); return text.replaceAll(Pattern.quote("${" + name + "}"), value); } }