List of usage examples for java.util.regex Pattern quote
public static String quote(String s)
From source file:com.predic8.membrane.core.interceptor.authentication.session.StaticUserDataProvider.java
private boolean isHashedPassword(String postDataPassword) { // TODO do a better check here String[] split = postDataPassword.split(Pattern.quote("$")); if (split.length != 4) return false; if (!split[0].isEmpty()) return false; if (split[3].length() < 20) return false; return true;//www . j a v a2 s. c o m }
From source file:org.apache.nifi.minifi.c2.provider.nifi.rest.NiFiRestConfigurationProvider.java
@Override public Configuration getConfiguration(String contentType, Integer version, Map<String, List<String>> parameters) throws ConfigurationProviderException { if (!CONTENT_TYPE.equals(contentType)) { throw new ConfigurationProviderException( "Unsupported content type: " + contentType + " supported value is " + CONTENT_TYPE); }//www . j a v a 2 s . c o m String filename = templateNamePattern; for (Map.Entry<String, List<String>> entry : parameters.entrySet()) { if (entry.getValue().size() != 1) { throw new InvalidParameterException( "Multiple values for same parameter not supported in this provider."); } filename = filename.replaceAll(Pattern.quote("${" + entry.getKey() + "}"), entry.getValue().get(0)); } int index = filename.indexOf("${"); while (index != -1) { int endIndex = filename.indexOf("}", index); if (endIndex == -1) { break; } String variable = filename.substring(index + 2, endIndex); if (!"version".equals(variable)) { throw new InvalidParameterException("Found unsubstituted parameter " + variable); } index = endIndex + 1; } String id = null; if (version == null) { String filenamePattern = Arrays.stream(filename.split(Pattern.quote("${version}"), -1)) .map(Pattern::quote).collect(Collectors.joining("([0-9+])")); Pair<String, Integer> maxIdAndVersion = getMaxIdAndVersion(filenamePattern); id = maxIdAndVersion.getFirst(); version = maxIdAndVersion.getSecond(); } filename = filename.replaceAll(Pattern.quote("${version}"), Integer.toString(version)); WriteableConfiguration configuration = configurationCache.getCacheFileInfo(contentType, parameters) .getConfiguration(version); if (configuration.exists()) { if (logger.isDebugEnabled()) { logger.debug( "Configuration " + configuration + " exists and can be served from configurationCache."); } } else { if (logger.isDebugEnabled()) { logger.debug("Configuration " + configuration + " doesn't exist, will need to download and convert template."); } if (id == null) { try { String tmpFilename = templateNamePattern; for (Map.Entry<String, List<String>> entry : parameters.entrySet()) { if (entry.getValue().size() != 1) { throw new InvalidParameterException( "Multiple values for same parameter not supported in this provider."); } tmpFilename = tmpFilename.replaceAll(Pattern.quote("${" + entry.getKey() + "}"), entry.getValue().get(0)); } Pair<Stream<Pair<String, String>>, Closeable> streamCloseablePair = getIdAndFilenameStream(); try { String finalFilename = filename; id = streamCloseablePair.getFirst().filter(p -> finalFilename.equals(p.getSecond())) .map(Pair::getFirst).findFirst().orElseThrow(() -> new InvalidParameterException( "Unable to find template named " + finalFilename)); } finally { streamCloseablePair.getSecond().close(); } } catch (IOException | TemplatesIteratorException e) { throw new ConfigurationProviderException("Unable to retrieve template list", e); } } HttpURLConnection urlConnection = httpConnector.get("/templates/" + id + "/download"); try (InputStream inputStream = urlConnection.getInputStream()) { ConfigSchema configSchema = ConfigMain.transformTemplateToSchema(inputStream); SchemaSaver.saveConfigSchema(configSchema, configuration.getOutputStream()); } catch (IOException e) { throw new ConfigurationProviderException( "Unable to download template from url " + urlConnection.getURL(), e); } catch (JAXBException e) { throw new ConfigurationProviderException("Unable to convert template to yaml", e); } finally { urlConnection.disconnect(); } } return configuration; }
From source file:dmh.kuebiko.view.NoteTable.java
/** * Apply a filter to the table's, hiding all rows that don't match. * @param filterString The string to use as a filter. *///from w w w . j av a 2 s . co m void filter(String filterString) { // Short-circuit if we're clearing the filter. if (StringUtils.isBlank(filterString)) { sorter.setRowFilter(null); return; } final RowFilter<NoteTableModel, Integer> rowFilter; try { rowFilter = RowFilter.regexFilter(String.format(".*?%s.*", Pattern.quote(filterString)), Column.TITLE.ordinal()); } catch (PatternSyntaxException e) { throw new IllegalArgumentException("Invalid filter string", e); } sorter.setRowFilter(rowFilter); }
From source file:com.c4om.autoconf.ulysses.configanalyzer.guilauncher.ChromeAppEditorGUILauncher.java
/** * @see com.c4om.autoconf.ulysses.interfaces.configanalyzer.core.GUILauncher#launchGUI(com.c4om.autoconf.ulysses.interfaces.configanalyzer.core.datastructures.ConfigurationAnalysisContext, com.c4om.autoconf.ulysses.interfaces.Target) */// w ww . j a v a 2 s .c om @SuppressWarnings("resource") @Override public void launchGUI(ConfigurationAnalysisContext context, Target target) throws GUILaunchException { try { List<File> temporaryFolders = this.getTemporaryStoredChangesetsAndConfigs(context, target); for (File temporaryFolder : temporaryFolders) { //The temporary folder where one subfolder per analyzer execution will be stored (and removed). File temporaryFolderRoot = temporaryFolder.getParentFile().getParentFile(); System.out.println("Writing launch properties."); //Now, we build the properties file Properties launchProperties = new Properties(); String relativeTemporaryFolder = temporaryFolder.getAbsolutePath() .replaceAll("^" + Pattern.quote(temporaryFolderRoot.getAbsolutePath()), "") .replaceAll("^" + Pattern.quote(File.separator), "") .replaceAll(Pattern.quote(File.separator) + "$", "") .replaceAll(Pattern.quote(File.separator) + "+", "/"); // launchProperties.put(KEY_LOAD_RECOMMENDATIONS_FILE, relativeTemporaryFolder+CHANGESET_TO_APPLY); launchProperties.put(KEY_CATALOG, relativeTemporaryFolder + CATALOG_FILE_PATH); Writer writer = new OutputStreamWriter( new FileOutputStream(new File(temporaryFolderRoot, LAUNCH_PROPERTIES_FILE_NAME)), Charsets.UTF_8); launchProperties.store(writer, ""); writer.close(); System.out.println("Launch properties written!!!!"); System.out.println("Launching XML editor Chrome app"); Properties configurationAnalyzerProperties = context.getConfigurationAnalyzerSettings(); String chromeLocation = configurationAnalyzerProperties.getProperty(PROPERTIES_KEY_CHROME_LOCATION); String editorChromeAppLocation = configurationAnalyzerProperties .getProperty(PROPERTIES_KEY_EDITOR_CHROME_APP_LOCATION); ProcessBuilder chromeEditorPB = new ProcessBuilder( ImmutableList.of(chromeLocation, "--load-and-launch-app=" + editorChromeAppLocation)); chromeEditorPB.directory(new File(editorChromeAppLocation)); chromeEditorPB.start(); System.out.println("Editor started!!!"); System.out.println("Now, make all your changes and press ENTER when finished..."); new Scanner(System.in).nextLine(); FileUtils.forceDeleteOnExit(temporaryFolder.getParentFile()); } } catch (IOException e) { throw new GUILaunchException(e); } }
From source file:de.hybris.platform.atddimpex.keywords.ImpexKeywordLibrary.java
private OutputStream getImpExLogOutputStream(final String resourceName) throws IOException { if (impExLogOutputStream == null) { final RobotTest robotTest = robotTestContext.getCurrentRobotTest(); if (robotTest == null) { throw new IllegalStateException( "KeywordMethods must only be called within a valid RobotTestContext"); } else {//from w w w. j ava 2 s .com final String testSuiteName = robotTest.getTestSuite().getName().replaceAll(Pattern.quote(" "), "_"); final String impExLogPath = String.format("%s/%s/%s-data.impex", robotTestContext.getProjectName(), testSuiteName, robotTest.getName()); final File impExLogFile = new File(Config.getParameter(PROP_REPORT_PATH), impExLogPath); impExLogOutputStream = FileUtils.openOutputStream(impExLogFile); } } else { IOUtils.write(IMPEX_LOG_LINE_SEPERATOR, impExLogOutputStream, DEFAULT_ENCODING); } IOUtils.write(IMPEX_LOG_RESOURCE_BANNER, impExLogOutputStream, DEFAULT_ENCODING); IOUtils.write(String.format("# Import from %s %s", resourceName, IMPEX_LOG_LINE_SEPERATOR), impExLogOutputStream, DEFAULT_ENCODING); IOUtils.write(IMPEX_LOG_RESOURCE_BANNER, impExLogOutputStream, DEFAULT_ENCODING); impExLogOutputStream.flush(); return impExLogOutputStream; }
From source file:com.ngdata.hbaseindexer.cli.BaseCli.java
protected void printHelpFooter() throws IOException { String className = getClass().getName(); String helpHeaderPath = className.replaceAll(Pattern.quote("."), "/") + "_help_footer.txt"; InputStream is = getClass().getClassLoader().getResourceAsStream(helpHeaderPath); if (is != null) { System.out.println();/*from w ww . ja va2 s. c o m*/ IOUtils.copy(is, System.out); System.out.println(); } }
From source file:com.sap.prd.mobile.ios.mios.FileUtils.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 * '\'./*from w w w .j a v a2 s . co m*/ * * Copied from http://stackoverflow.com/a/3054692/933106. * * @param target * targetPath is calculated to this file * @param base * basePath is calculated from this file * @param separator * 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:uk.ac.kcl.at.ElasticGazetteerAcceptanceTest.java
@Test public void deidentificationPerformanceTest() { dbmsTestUtils.createBasicInputTable(); dbmsTestUtils.createBasicOutputTable(); dbmsTestUtils.createDeIdInputTable(); List<Mutant> mutants = testUtils.insertTestDataForDeidentification(env.getProperty("tblIdentifiers"), env.getProperty("tblInputDocs"), mutatortype, true); int totalTruePositives = 0; int totalFalsePositives = 0; int totalFalseNegatives = 0; for (Mutant mutant : mutants) { Set<Pattern> mutatedPatterns = new HashSet<>(); mutant.setDeidentifiedString(elasticGazetteerService.deIdentifyString(mutant.getFinalText(), String.valueOf(mutant.getDocumentid()))); Set<String> set = new HashSet<>(mutant.getOutputTokens()); mutatedPatterns.addAll(//from w w w . j a v a 2s . com set.stream().map(string -> Pattern.compile(Pattern.quote(string), Pattern.CASE_INSENSITIVE)) .collect(Collectors.toSet())); List<MatchResult> results = new ArrayList<>(); for (Pattern pattern : mutatedPatterns) { Matcher matcher = pattern.matcher(mutant.getFinalText()); while (matcher.find()) { results.add(matcher.toMatchResult()); } } int truePositives = getTruePositiveTokenCount(mutant); int falsePositives = getFalsePositiveTokenCount(mutant); int falseNegatives = getFalseNegativeTokenCount(mutant); System.out.println("Doc ID " + mutant.getDocumentid() + " has " + falseNegatives + " unmasked identifiers from a total of " + (falseNegatives + truePositives)); System.out.println("Doc ID " + mutant.getDocumentid() + " has " + falsePositives + " inaccurately masked tokens from a total of " + (falsePositives + truePositives)); System.out.println("TP: " + truePositives + " FP: " + falsePositives + " FN: " + falseNegatives); System.out.println("Doc ID precision " + calcPrecision(falsePositives, truePositives)); System.out.println("Doc ID recall " + calcRecall(falseNegatives, truePositives)); System.out.println(mutant.getDeidentifiedString()); System.out.println(mutant.getFinalText()); System.out.println(mutant.getInputTokens()); System.out.println(mutant.getOutputTokens()); System.out.println(); if (env.getProperty("elasticgazetteerTestOutput") != null) { try { try (BufferedWriter bw = new BufferedWriter( new FileWriter(new File(env.getProperty("elasticgazetteerTestOutput") + File.separator + mutant.getDocumentid())))) { bw.write("Doc ID " + mutant.getDocumentid() + " has " + falseNegatives + " unmasked identifiers from a total of " + (falseNegatives + truePositives)); bw.newLine(); bw.write("Doc ID " + mutant.getDocumentid() + " has " + falsePositives + " inaccurately masked tokens from a total of " + (falsePositives + truePositives)); bw.newLine(); bw.write("TP: " + truePositives + " FP: " + falsePositives + " FN: " + falseNegatives); bw.newLine(); bw.write("Doc ID precision " + calcPrecision(falsePositives, truePositives)); bw.newLine(); bw.write("Doc ID recall " + calcRecall(falseNegatives, truePositives)); bw.newLine(); bw.write(mutant.getDeidentifiedString()); bw.newLine(); bw.write(mutant.getFinalText()); bw.newLine(); bw.write(mutant.getInputTokens().toString()); bw.newLine(); bw.write(mutant.getOutputTokens().toString()); } } catch (IOException e) { e.printStackTrace(); } } totalTruePositives += truePositives; totalFalsePositives += falsePositives; totalFalseNegatives += falseNegatives; } DecimalFormat df = new DecimalFormat("#.#"); df.setRoundingMode(RoundingMode.CEILING); System.out.println(); System.out.println(); System.out.println("THIS RUN TP: " + totalTruePositives + " FP: " + totalFalsePositives + " FN: " + totalFalseNegatives); System.out.println("Doc ID precision " + calcPrecision(totalFalsePositives, totalTruePositives)); System.out.println("Doc ID recall " + calcRecall(totalFalseNegatives, totalTruePositives)); System.out.println(totalTruePositives + " & " + totalFalsePositives + " & " + totalFalseNegatives + " & " + df.format(calcPrecision(totalFalsePositives, totalTruePositives)) + " & " + df.format(calcRecall(totalFalseNegatives, totalTruePositives)) + " \\\\"); if (env.getProperty("elasticgazetteerTestOutput") != null) { try { try (BufferedWriter bw = new BufferedWriter(new FileWriter( new File(env.getProperty("elasticgazetteerTestOutput") + File.separator + "summary")))) { bw.write("THIS RUN TP: " + totalTruePositives + " FP: " + totalFalsePositives + " FN: " + totalFalseNegatives); bw.newLine(); bw.write("Doc ID precision " + calcPrecision(totalFalsePositives, totalTruePositives)); bw.newLine(); bw.write("Doc ID recall " + calcRecall(totalFalseNegatives, totalTruePositives)); } } catch (IOException e) { e.printStackTrace(); } } }
From source file:com.bluexml.side.Framework.alfresco.propertiesUpdater.PatternPropertiesUpdater.java
protected void extractCurrentPropertyValue(String currentKey, String template, Pattern p, String expressionProperty) { String oldPropertyValue = getOldValue(currentKey); if (logger.isDebugEnabled()) { logger.debug("[getNewValue] oldProperty Value :" + oldPropertyValue); }/* ww w. j a v a 2s . c o m*/ String currentPropertyValue = getNewValue(currentKey); if (logger.isDebugEnabled()) { logger.debug("[getNewValue] Property Value :" + currentPropertyValue); } if (currentPropertyValue != null && currentPropertyValue.equals(oldPropertyValue)) { if (logger.isDebugEnabled()) { logger.debug("[getNewValue] currentValue not changed, need to compute the real propertyValue"); } Matcher matcher = p.matcher(template); // need to extract from name value the matching value from template // before compute new value // compute regexp (replace in template by old value except for the // property to update) String newValue = template; while (matcher.find()) { String key = matcher.group(1); if (!key.equals(currentKey)) { String oldValue = getOldValue(key); newValue = newValue.replaceAll(Pattern.quote(matcher.group()), oldValue); } } // create the regExp used to identify the original value String currentValueMAtchedRegExp = ""; String[] split = newValue.split(Pattern.quote(expressionProperty)); for (int i = 0; i < split.length; i++) { String string = split[i]; currentValueMAtchedRegExp += Pattern.quote(string); if (i < split.length - 1) { currentValueMAtchedRegExp += "(.*)"; } } if (logger.isDebugEnabled()) { logger.debug("*** matched old currentKeyvalueRegExp :" + currentValueMAtchedRegExp); } Pattern compile = Pattern.compile(currentValueMAtchedRegExp); if (logger.isDebugEnabled()) { logger.debug("*** oldValue to match, search currentKeyvalue :" + oldPropertyValue); } Matcher matcher2 = compile.matcher(oldPropertyValue); matcher2.find(); String currentValueMAtched = matcher2.group(1); if (logger.isDebugEnabled()) { logger.debug("*** identified value (pattern matching) :" + currentValueMAtched); } // change the newValue to be able to apply template newValues.put(currentKey, currentValueMAtched); } }
From source file:ddf.catalog.pubsub.predicate.ContextualPredicate.java
/** * Normalizes a search phrase for a Lucene query * * @param inputPhrase the input phrase/*from w w w. j a va 2 s . c o m*/ * @param isFuzzy true indicates the criteria is fuzzy * @return a search phrase aligned to Lucene syntax */ public static String normalizePhrase(String inputPhrase, boolean isFuzzy) { String phrase = ""; if (inputPhrase != null && !inputPhrase.equals("")) { phrase = inputPhrase.trim(); String parts[] = phrase.split("\""); LOGGER.debug("phrase = [{}] parts.length = {}", phrase, parts.length); // if multiple parts found, then exact (quoted) phrases are present if (parts.length > 1) { // Odd parts are in quotes, i.e., exact (quoted) phrases, so skip them // Even parts are individual words or operators for (int i = 0; i < parts.length; i++) { LOGGER.debug("parts[{}] = {}", i, parts[i]); if (i % 2 == 0) { if (!parts[i].isEmpty()) { parts[i] = normalizeBooleanOperators(parts[i]); parts[i] = escapeSpecialCharacters(parts[i]); if (isFuzzy && !isBooleanOperator(parts[i])) { parts[i] = parts[i] + "~"; parts[i] = parts[i].replace("~~", "~"); LOGGER.debug("Fuzzy Search adding a tilde: {}", parts[i]); } } else { LOGGER.debug("part[{}] was empty", i); } } else { parts[i] = escapeSpecialCharacters(parts[i]); } } StringBuilder phraseBuilder = new StringBuilder(""); for (int i = 0; i < parts.length; i++) { phraseBuilder.append(parts[i]); if (i < (parts.length - 1)) { phraseBuilder.append("\""); } } phrase = phraseBuilder.toString(); } else { LOGGER.debug("parts.length <= 1: phrase = {}", phrase); phrase = normalizeBooleanOperators(phrase); phrase = escapeSpecialCharacters(phrase); if (isFuzzy) { String[] words = phrase.trim().split("[ ]+"); for (int i = 0; i < words.length; i++) { String[] subParts = words[i].split("[\\(\\)]+"); for (String subPart : subParts) { if (!subPart.isEmpty() && !isBooleanOperator(subPart)) { String fuzzySubPart = subPart + "~"; phrase = phrase.replaceFirst(Pattern.quote(subPart), fuzzySubPart); LOGGER.debug("2. Fuzzy Search adding a tilde: {}", subPart); LOGGER.debug("phrase = {}", phrase); } } phrase = phrase.replace("~~", "~"); } LOGGER.debug("2. Fuzzy-fied phrase: {}", phrase); } } // Pass thru the last literal double quote if (inputPhrase.lastIndexOf("\"") == inputPhrase.length() - 1) { phrase = phrase + "\""; } } else { phrase = ""; } LOGGER.debug("Normalization complete. \nBefore: {}\nAfter: {}", inputPhrase, phrase); return phrase; }