Example usage for java.util.regex Pattern quote

List of usage examples for java.util.regex Pattern quote

Introduction

In this page you can find the example usage for java.util.regex Pattern quote.

Prototype

public static String quote(String s) 

Source Link

Document

Returns a literal pattern String for the specified String .

Usage

From source file:com.hp.alm.ali.idea.entity.tree.EntityNode.java

private String wildcardToRegex(String mask) {
    String[] tokens = mask.split("\\*", -1);
    for (int i = 0; i < tokens.length; i++) {
        tokens[i] = Pattern.quote(tokens[i]);
    }//from   w  w w. j  a  v a2s  .  c  o m
    return StringUtils.join(tokens, ".*");
}

From source file:org.bremersee.common.spring.autoconfigure.LdaptiveInMemoryDirectoryServerProperties.java

public String[] getSchemaLocationsAsArray() {
    if (StringUtils.hasText(schemaLocations)) {
        String[] values = schemaLocations.split(Pattern.quote(","));
        return Arrays.stream(values).map(String::trim).toArray(size -> new String[size]);
    }/*from   ww w .  j a va2 s. c o m*/
    return new String[0];
}

From source file:unalcol.termites.boxplots.ECALMessages.java

/**
 * Creates a sample dataset./* w ww .  jav  a2s. c om*/
 *
 * @return A sample dataset.
 */
private BoxAndWhiskerCategoryDataset createSampleDataset(ArrayList<Double> Pf, BoxAndWhiskerRenderer renderer) {

    final int seriesCount = 5;
    final int categoryCount = 4;
    final int entityCount = 22;
    String sDirectorio = ".\\experiments\\ECAL CR";
    File f = new File(sDirectorio);
    String extension;
    File[] files = f.listFiles();
    Hashtable<String, String> Pop = new Hashtable<>();
    PrintWriter escribir;
    Scanner sc = null;
    ArrayList<Integer> aPops = new ArrayList<>();
    ArrayList<Double> aPf = new ArrayList<>();
    ArrayList<String> aTech = new ArrayList<>();

    final DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();

    for (File file : files) {
        extension = "";
        int i = file.getName().lastIndexOf('.');
        int p = Math.max(file.getName().lastIndexOf('/'), file.getName().lastIndexOf('\\'));
        if (i > p) {
            extension = file.getName().substring(i + 1);
        }

        // System.out.println(file.getName() + "extension" + extension);
        if (file.isFile() && extension.equals("csv") && file.getName().startsWith("experiment")) {
            System.out.println(file.getName());
            System.out.println("get: " + file.getName());
            String[] filenamep = file.getName().split(Pattern.quote("+"));

            System.out.println("file" + filenamep[8]);

            int popsize = Integer.valueOf(filenamep[2]);
            double pf = Double.valueOf(filenamep[4]);
            String mode = filenamep[6];

            int maxIter = -1;
            //if (!filenamep[8].isEmpty()) {
            maxIter = Integer.valueOf(filenamep[8]);
            //}

            System.out.println("psize:" + popsize);
            System.out.println("pf:" + pf);
            System.out.println("mode:" + mode);
            System.out.println("maxIter:" + maxIter);

            String[] aMode = { "random", "levywalk", "sandc" };
            //String[] aMode = {"lwphclwevap", "lwsandc2", "lwsandc", "lwphevap2", "lwphevap"};

            if (/*Pf == pf && */isInMode(aMode, mode)) {
                final List list = new ArrayList();
                try {
                    sc = new Scanner(file);

                } catch (FileNotFoundException ex) {
                    Logger.getLogger(DataCollectedLatexConsolidatorSASOMessagesSend1.class.getName())
                            .log(Level.SEVERE, null, ex);
                }
                int agentsCorrect = 0;
                int worldSize = 0;
                double averageExplored = 0.0;
                int bestRoundNumber = 0;
                double avgSend = 0;
                double avgRecv = 0;
                double avgdataExplInd = 0;
                ArrayList<Double> acSt = new ArrayList<>();
                ArrayList<Double> avgExp = new ArrayList<>();
                ArrayList<Double> bestR = new ArrayList<>();
                ArrayList<Double> avSnd = new ArrayList<>();
                ArrayList<Double> avRecv = new ArrayList<>();
                ArrayList<Double> avIndExpl = new ArrayList<>();

                String[] data = null;
                while (sc.hasNext()) {
                    String line = sc.nextLine();
                    //System.out.println("line:" + line);
                    data = line.split(",");
                    agentsCorrect = Integer.valueOf(data[0]);
                    //agentsIncorrect = Integer.valueOf(data[1]); // not used
                    worldSize = Integer.valueOf(data[3]);
                    averageExplored = Double.valueOf(data[4]);
                    // data[3] stdavgExplored - not used
                    bestRoundNumber = Integer.valueOf(data[6]);
                    avgSend = Double.valueOf(data[7]);
                    avgRecv = Double.valueOf(data[8]);
                    avgdataExplInd = Double.valueOf(data[11]);

                    //Add Data and generate statistics 
                    acSt.add((double) agentsCorrect);
                    avgExp.add(averageExplored);

                    avSnd.add(avgSend);
                    avRecv.add(avgRecv);
                    avIndExpl.add(avgdataExplInd);

                    list.add(new Double(avgSend));

                }
                LOGGER.debug("Adding series " + i);
                LOGGER.debug(list.toString());

                if (Pf.contains(pf)) {
                    /*pf == 1.0E-4 || pf == 3.0E-4*/
                    if (Pf.size() == 1) {
                        dataset.add(list, popsize, getTechniqueName(mode));
                    } else {
                        dataset.add(list, String.valueOf(popsize) + "-" + pf + "\n", getTechniqueName(mode));
                    }
                }
            }
        }

    }

    /*for (int i = 0; i < seriesCount; i++) {
     for (int j = 0; j < categoryCount; j++) {
     final List list = new ArrayList();
     // add some values...
     for (int k = 0; k < entityCount; k++) {
     final double value1 = 10.0 + Math.random() * 3;
     list.add(new Double(value1));
     final double value2 = 11.25 + Math.random(); // concentrate values in the middle
     list.add(new Double(value2));
     }
     LOGGER.debug("Adding series " + i);
     LOGGER.debug(list.toString());
     dataset.add(list, "Series " + i, " Type " + j);
     }
            
     }*/
    return dataset;
}

From source file:net.dv8tion.jda.core.entities.impl.MessageImpl.java

@Override
public synchronized String getStrippedContent() {
    if (strippedContent == null) {
        String tmp = getContent();
        //all the formatting keys to keep track of
        String[] keys = new String[] { "*", "_", "`", "~~" };

        //find all tokens (formatting strings described above)
        TreeSet<FormatToken> tokens = new TreeSet<>((t1, t2) -> Integer.compare(t1.start, t2.start));
        for (String key : keys) {
            Matcher matcher = Pattern.compile(Pattern.quote(key)).matcher(tmp);
            while (matcher.find()) {
                tokens.add(new FormatToken(key, matcher.start()));
            }//from www  . j  a v a  2s. c o  m
        }

        //iterate over all tokens, find all matching pairs, and add them to the list toRemove
        Stack<FormatToken> stack = new Stack<>();
        List<FormatToken> toRemove = new ArrayList<>();
        boolean inBlock = false;
        for (FormatToken token : tokens) {
            if (stack.empty() || !stack.peek().format.equals(token.format)
                    || stack.peek().start + token.format.length() == token.start) {
                //we are at opening tag
                if (!inBlock) {
                    //we are outside of block -> handle normally
                    if (token.format.equals("`")) {
                        //block start... invalidate all previous tags
                        stack.clear();
                        inBlock = true;
                    }
                    stack.push(token);
                } else if (token.format.equals("`")) {
                    //we are inside of a block -> handle only block tag
                    stack.push(token);
                }
            } else if (!stack.empty()) {
                //we found a matching close-tag
                toRemove.add(stack.pop());
                toRemove.add(token);
                if (token.format.equals("`") && stack.empty()) {
                    //close tag closed the block
                    inBlock = false;
                }
            }
        }

        //sort tags to remove by their start-index and iteratively build the remaining string
        Collections.sort(toRemove, (t1, t2) -> Integer.compare(t1.start, t2.start));
        StringBuilder out = new StringBuilder();
        int currIndex = 0;
        for (FormatToken formatToken : toRemove) {
            if (currIndex < formatToken.start) {
                out.append(tmp.substring(currIndex, formatToken.start));
            }
            currIndex = formatToken.start + formatToken.format.length();
        }
        if (currIndex < tmp.length()) {
            out.append(tmp.substring(currIndex));
        }
        //return the stripped text, escape all remaining formatting characters (did not have matching open/close before or were left/right of block
        strippedContent = out.toString().replace("*", "\\*").replace("_", "\\_").replace("~", "\\~");
    }
    return strippedContent;
}

From source file:io.syndesis.jsondb.impl.JsonRecordSupport.java

static int fromLexSortableStringToInt(String value, char marker) {
    // Trim the initial markers.
    String remaining = value.replaceFirst("^" + Pattern.quote(String.valueOf(marker)) + "+", "");

    int rc = 1;/*from  w  ww.  j  a va2 s  .com*/
    while (!remaining.isEmpty()) {
        String x = remaining.substring(0, rc);
        remaining = remaining.substring(rc);
        rc = Integer.parseInt(x);
    }

    return rc;
}

From source file:lu.lippmann.cdb.graph.GraphUtil.java

/**
 * Method to remove undefined variables.
 *//*from w  w w . j  a va2 s .  c  om*/
public static String cleanVariables(final String expression) {
    String res = expression;
    Matcher m;
    while ((m = CLEAN_VARIABLES_PATTERN.matcher(res)).find()) {
        final String var = Pattern.quote(m.group(0));
        res = res.replaceAll(var, "" + m.group(1).hashCode());
    }
    return res;
}

From source file:unalcol.termites.boxplots.MessagesSent2.java

/**
 * Creates a sample dataset./*from  w  w  w.  ja v a2 s  .c  om*/
 *
 * @return A sample dataset.
 */
private BoxAndWhiskerCategoryDataset createSampleDataset(ArrayList<Double> Pf, BoxAndWhiskerRenderer renderer) {

    final int seriesCount = 5;
    final int categoryCount = 4;
    final int entityCount = 22;
    String sDirectorio = ".\\experiments\\2015-10-14-Maze\\results";
    File f = new File(sDirectorio);
    String extension;
    File[] files = f.listFiles();
    Hashtable<String, String> Pop = new Hashtable<>();
    PrintWriter escribir;
    Scanner sc = null;
    ArrayList<Integer> aPops = new ArrayList<>();
    ArrayList<Double> aPf = new ArrayList<>();
    ArrayList<String> aTech = new ArrayList<>();

    final DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();

    for (File file : files) {
        extension = "";
        int i = file.getName().lastIndexOf('.');
        int p = Math.max(file.getName().lastIndexOf('/'), file.getName().lastIndexOf('\\'));
        if (i > p) {
            extension = file.getName().substring(i + 1);
        }

        // System.out.println(file.getName() + "extension" + extension);
        if (file.isFile() && extension.equals("csv") && file.getName().startsWith("experiment")) {
            System.out.println(file.getName());
            System.out.println("get: " + file.getName());
            String[] filenamep = file.getName().split(Pattern.quote("+"));

            System.out.println("file" + filenamep[8]);

            int popsize = Integer.valueOf(filenamep[2]);
            double pf = Double.valueOf(filenamep[4]);
            String mode = filenamep[6];

            int maxIter = -1;
            //if (!filenamep[8].isEmpty()) {
            maxIter = Integer.valueOf(filenamep[8]);
            //}

            System.out.println("psize:" + popsize);
            System.out.println("pf:" + pf);
            System.out.println("mode:" + mode);
            System.out.println("maxIter:" + maxIter);

            String[] aMode = { "levywalk", "lwphevap", "hybrid" };
            //String[] aMode = {"sandclw", "lwsandc2", "lwsandc", "lwphevap2", "lwphevap"};
            //String[] aMode = {"lwphclwevap", "lwsandc2", "lwsandc", "lwphevap2", "lwphevap"};

            if (/*Pf == pf && */isInMode(aMode, mode)) {
                final List list = new ArrayList();
                try {
                    sc = new Scanner(file);

                } catch (FileNotFoundException ex) {
                    Logger.getLogger(DataCollectedLatexConsolidatorSASOMessagesSend1.class.getName())
                            .log(Level.SEVERE, null, ex);
                }
                int agentsCorrect = 0;
                int worldSize = 0;
                double averageExplored = 0.0;
                int bestRoundNumber = 0;
                double avgSend = 0;
                double avgRecv = 0;
                double avgdataExplInd = 0;
                ArrayList<Double> acSt = new ArrayList<>();
                ArrayList<Double> avgExp = new ArrayList<>();
                ArrayList<Double> bestR = new ArrayList<>();
                ArrayList<Double> avSnd = new ArrayList<>();
                ArrayList<Double> avRecv = new ArrayList<>();
                ArrayList<Double> avIndExpl = new ArrayList<>();

                String[] data = null;
                while (sc.hasNext()) {
                    String line = sc.nextLine();
                    //System.out.println("line:" + line);
                    data = line.split(",");
                    agentsCorrect = Integer.valueOf(data[0]);
                    //agentsIncorrect = Integer.valueOf(data[1]); // not used
                    worldSize = Integer.valueOf(data[3]);
                    averageExplored = Double.valueOf(data[4]);
                    // data[3] stdavgExplored - not used
                    bestRoundNumber = Integer.valueOf(data[6]);
                    avgSend = Double.valueOf(data[7]);
                    avgRecv = Double.valueOf(data[8]);
                    avgdataExplInd = Double.valueOf(data[11]);

                    //Add Data and generate statistics 
                    acSt.add((double) agentsCorrect);
                    avgExp.add(averageExplored);

                    avSnd.add(avgSend);
                    avRecv.add(avgRecv);
                    avIndExpl.add(avgdataExplInd);

                    list.add(new Double(avgSend));

                }
                LOGGER.debug("Adding series " + i);
                LOGGER.debug(list.toString());

                if (Pf.contains(pf)) {
                    /*pf == 1.0E-4 || pf == 3.0E-4*/
                    if (Pf.size() == 1) {
                        dataset.add(list, popsize, getTechniqueName(mode));
                    } else {
                        dataset.add(list, String.valueOf(popsize) + "-" + pf + "\n", getTechniqueName(mode));
                    }
                }
            }
        }

    }

    /*for (int i = 0; i < seriesCount; i++) {
     for (int j = 0; j < categoryCount; j++) {
     final List list = new ArrayList();
     // add some values...
     for (int k = 0; k < entityCount; k++) {
     final double value1 = 10.0 + Math.random() * 3;
     list.add(new Double(value1));
     final double value2 = 11.25 + Math.random(); // concentrate values in the middle
     list.add(new Double(value2));
     }
     LOGGER.debug("Adding series " + i);
     LOGGER.debug(list.toString());
     dataset.add(list, "Series " + i, " Type " + j);
     }
            
     }*/
    return dataset;
}

From source file:contestTabulation.Main.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) {
    final long startTimeMillis = System.currentTimeMillis();
    final Map<Test, Pair<Integer, Integer>> testsGraded = new HashMap<Test, Pair<Integer, Integer>>();
    final List<Test> tiesBroken = new ArrayList<Test>();

    final Entity contestInfo;
    final Map<String, Integer> awardCriteria;

    final Map<Level, Set<Student>> students = new HashMap<Level, Set<Student>>();
    final Map<Level, Map<String, School>> schools = new HashMap<Level, Map<String, School>>();
    final Map<Level, Map<Test, List<Student>>> categoryWinners = new HashMap<Level, Map<Test, List<Student>>>();
    final Map<Level, Map<Subject, List<School>>> categorySweepstakesWinners = new HashMap<Level, Map<Subject, List<School>>>();
    final Map<Level, List<School>> sweepstakesWinners = new HashMap<Level, List<School>>();

    final StringBuilder errorLog = new StringBuilder();

    memCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(java.util.logging.Level.INFO));
    memCache.put("tabulationTaskStatus", ("Running/Init_" + System.currentTimeMillis()).getBytes());

    try {// w w w  .  ja v a2  s  .c o m
        // Retrieve contest information from Datastore
        contestInfo = Retrieve.contestInfo();

        // Get award criteria from Datastore
        awardCriteria = Retrieve.awardCriteria(contestInfo);

        // Initialize data structures
        for (Level level : Level.values()) {
            students.put(level, new HashSet<Student>());
            schools.put(level, new HashMap<String, School>());
            categoryWinners.put(level, new HashMap<Test, List<Student>>());
            categorySweepstakesWinners.put(level, new HashMap<Subject, List<School>>());
            sweepstakesWinners.put(level, new ArrayList<School>());
        }

        // Authenticate to Google Documents Service using OAuth 2.0 Authentication Token from Datastore
        Map<String, String[]> params = req.getParameterMap();
        SpreadsheetService service = new SpreadsheetService("contestTabulation");
        authService(service, contestInfo);

        // Retrieve enabled levels from Datastore
        String[] stringLevels = ((String) contestInfo.getProperty("levels")).split(Pattern.quote("+"));
        Level[] levels = new Level[stringLevels.length];
        for (int i = 0; i < stringLevels.length; i++) {
            levels[i] = Level.fromString(stringLevels[i]);
        }

        for (Level level : levels) {
            memCache.put("tabulationTaskStatus",
                    ("Running/" + level.getName() + "_" + System.currentTimeMillis()).getBytes());
            Map<String, School> lSchools = schools.get(level);
            List<School> lsweepstakesWinners = sweepstakesWinners.get(level);
            Map<Test, List<Student>> lCategoryWinners = categoryWinners.get(level);
            Map<Subject, List<School>> lCategorySweepstakesWinners = categorySweepstakesWinners.get(level);

            // Populate base data structures by traversing Google Documents Spreadsheets
            SpreadsheetEntry spreadsheet = getSpreadSheet(params.get("doc" + level.getName())[0], service);
            Map<String, String> schoolGroups = getSchoolGroups(level, contestInfo);
            updateDatabase(level, spreadsheet, students.get(level), lSchools, schoolGroups, testsGraded,
                    service, errorLog);

            // Populate category winners lists with top scorers (as defined by award criteria)
            tabulateCategoryWinners(level, students.get(level), lCategoryWinners, testsGraded, tiesBroken,
                    awardCriteria, errorLog);

            // Calculate school sweepstakes scores and number of tests fields
            for (School school : lSchools.values()) {
                school.calculateScores();
                school.calculateTestNums();
            }

            // Populate category sweepstakes winners maps and sweepstakes winners lists with top scorers
            tabulateCategorySweepstakesWinners(lSchools, lCategorySweepstakesWinners);
            tabulateSweepstakesWinners(lSchools, lsweepstakesWinners);

            // Persist JDOs in Datastore
            persistData(level, lSchools.values(), lCategoryWinners, lCategorySweepstakesWinners,
                    lsweepstakesWinners);

            // Update Datastore by modifying registrations to include actual number of tests taken
            updateRegistrations(level, lSchools);
        }

        // Update Datastore by modifying contest information entity to include tests graded, last updated timestamp and error logs
        updateContestInfo(testsGraded, tiesBroken, contestInfo, errorLog);

        long elapsedSeconds = TimeUnit.SECONDS.convert(System.currentTimeMillis() - startTimeMillis,
                TimeUnit.MILLISECONDS);
        memCache.put("tabulationTaskStatus", ("Success/" + elapsedSeconds + " second"
                + (elapsedSeconds == 1 ? "" : "s") + "_" + System.currentTimeMillis()).getBytes());
    } catch (Exception e) {
        e.printStackTrace();
        memCache.put("tabulationTaskStatus",
                ("Failed/" + e.getClass().getName() + "_" + System.currentTimeMillis()).getBytes());
    }
}

From source file:com.dell.asm.asmcore.asmmanager.util.deployment.HostnameUtil.java

public String generateHostname(String hostnameTemplate, ServiceTemplateComponent component,
        DeviceInventoryEntity server, Set<String> allHostnames) {
    if (server != null) {
        if (hostnameTemplate.contains(TAG_PATTERN)) {
            hostnameTemplate = hostnameTemplate.replaceAll(Pattern.quote(TAG_PATTERN),
                    safeName(server.getServiceTag()));
        }//from  ww w .ja v  a  2s  . c  o  m

        if (hostnameTemplate.contains(MODEL_PATTERN)) {
            hostnameTemplate = hostnameTemplate.replaceAll(Pattern.quote(MODEL_PATTERN),
                    safeName(server.getModel()));
        }

        if (hostnameTemplate.contains(VENDOR_PATTERN)) {
            hostnameTemplate = hostnameTemplate.replaceAll(Pattern.quote(VENDOR_PATTERN),
                    safeName(server.getVendor()));
        }
    }
    if (hostnameTemplate.contains(DNS_PATTERN)) {
        hostnameTemplate = replaceDnsPattern(hostnameTemplate, component);
    }

    hostnameTemplate = hostnameTemplate.toLowerCase();

    if (hostnameTemplate.contains(NUM_PATTERN)) {
        hostnameTemplate = replaceNumPattern(hostnameTemplate, allHostnames);
    }

    return hostnameTemplate;
}

From source file:languages.TabFile.java

/**
 * Optimizes the dictionary of the app. As The dictionaries are a resource
 * of the app, this method is currently only intended to run in a dev
 * environment.<br>/*ww  w  . ja  va  2  s  . c o  m*/
 * <br>
 * Optimization means in this case that words are split up at spaces and
 * punctuation is deleted.
 *
 * @param origin                The original {@code TabFile} that is to be optimized.
 * @param originWordColumnIndex The column index with the words to be optimized.
 * @param preserveColumnIndex   If {@code true}, the words are written to the same column
 *                              index as in the origin-file and the values of all other
 *                              columns are preserved, if {@code false}, the optimized word
 *                              list will be written into the first column (index: 0) and all
 *                              other columns will be deleted.
 * @return A {@code TabFile} with the optimized word list.
 */
public static TabFile optimizeDictionaries(TabFile origin, int originWordColumnIndex,
        boolean preserveColumnIndex) {
    // Create new TabFile with one column
    String[] colHeads;

    if (preserveColumnIndex) {
        colHeads = origin.getColumnHeaders();
    } else {
        colHeads = new String[] { "words" };
    }
    TabFile res = new TabFile(colHeads);

    for (int lineIndex = 0; lineIndex < origin.getRowCount(); lineIndex++) {
        ArrayListWithSortableKey<String> line = origin.values.get(lineIndex);
        // Split at spaces
        String[] words;

        try {
            words = line.get(originWordColumnIndex).split(" ");
        } catch (ArrayIndexOutOfBoundsException e) {
            words = "".split(" ");
        }

        for (String word : words) {
            // Remove punctuation
            word = word.replaceAll("(" + Pattern.quote(".") + "|,)", "");

            // Add word to result
            if (preserveColumnIndex) {
                String[] tempValues = new String[origin.getColumnCount()];

                for (int i = 0; i < origin.getColumnCount(); i++) {
                    if (i != originWordColumnIndex) {
                        tempValues[i] = origin.getValueAt(lineIndex, i);
                    } else {
                        tempValues[i] = word;
                    }
                }

                res.addRow(tempValues);
            } else {
                res.addRow(new String[] { word });
            }
        }
    }

    return res;
}