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.ichi2.libanki.Decks.java

/**
 * Rename deck prefix to NAME if not exists. Updates children.
 *//*ww  w.ja  v a 2  s  . c o  m*/
public void rename(JSONObject g, String newName) throws DeckRenameException {
    // make sure target node doesn't already exist
    if (allNames().contains(newName)) {
        throw new DeckRenameException(DeckRenameException.ALREADY_EXISTS);
    }
    try {
        // ensure we have parents
        newName = _ensureParents(newName);
        // make sure we're not nesting under a filtered deck
        if (newName.contains("::")) {
            List<String> parts = Arrays.asList(newName.split("::", -1));
            String newParent = TextUtils.join("::", parts.subList(0, parts.size() - 1));
            if (byName(newParent).getInt("dyn") != 0) {
                throw new DeckRenameException(DeckRenameException.FILTERED_NOSUBDEKCS);
            }
        }
        // rename children
        String oldName = g.getString("name");
        for (JSONObject grp : all()) {
            if (grp.getString("name").startsWith(oldName + "::")) {
                // In Java, String.replaceFirst consumes a regex so we need to quote the pattern to be safe
                grp.put("name",
                        grp.getString("name").replaceFirst(Pattern.quote(oldName + "::"), newName + "::"));
                save(grp);
            }
        }
        // adjust name
        g.put("name", newName);
        // ensure we have parents again, as we may have renamed parent->child
        newName = _ensureParents(newName);
        save(g);
        // renaming may have altered active did order
        maybeAddToActive();
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.mediaworx.opencms.moduleutils.manifestgenerator.OpenCmsModuleManifestGenerator.java

/**
 * Generates the manifest.xml for OpenCms modules from meta files (manifest_stub.xml and separate meta files for all
 * files and folders in the VFS)./*from   w ww.ja  va  2  s. co m*/
 * @param manifestRoot  file representing the root folder of the manifest meta data (including manifest_stub.xml)
 *
 * @throws OpenCmsMetaXmlParseException     if the XmlHelper can not be initialized or the manifest stub file or any
 *                                          meta file can not be read or parsed
 * @throws OpenCmsMetaXmlFileWriteException if the resulting manifest file can not be written
 */
public void generateManifest(File manifestRoot)
        throws OpenCmsMetaXmlParseException, OpenCmsMetaXmlFileWriteException {

    manifestRootPath = manifestRoot.getPath();

    handledSiblingResourceIds = new HashSet<String>();

    String manifestStubPath = manifestRoot.getPath() + File.separator + FILENAME_MANIFEST_STUB;
    String manifestPath = manifestRoot.getPath() + File.separator + FILENAME_MANIFEST;
    LOG.info("manifestStubPath: {}", manifestStubPath);

    Node filesNode;
    Document manifest;
    try {
        xmlHelper = new XmlHelper();
        Map<String, String> replacements = null;
        if (replaceMetaVariables) {
            replacements = new HashMap<String, String>();
            replacements.put(META_VAR_CREATEDATE, formatDate((new Date()).getTime()));
        }
        manifest = xmlHelper.parseFile(manifestStubPath, replacements);
        filesNode = xmlHelper.getSingleNodeForXPath(manifest, FILES_NODE_XPATH);
    } catch (ParserConfigurationException e) {
        throw new OpenCmsMetaXmlParseException("The XmlHelper could not be initialized", e);
    } catch (IOException e) {
        throw new OpenCmsMetaXmlParseException("The manifest stub file could not be read", e);
    } catch (SAXException e) {
        throw new OpenCmsMetaXmlParseException("The manifest stub xml could not be parsed (parse error)", e);
    } catch (XPathExpressionException e) {
        throw new OpenCmsMetaXmlParseException("The manifest stub xml could not be parsed (xpath error)", e);
    }

    // Regular Expression matching anything but Strings ending with the VFS folder meta file suffix (".ocmsfolder.xml")
    String excludeFolderMetaRegex = "^(?:(?!" + Pattern.quote(FOLDER_META_SUFFIX) + "$).)*$";

    // FileFilter filtering all VFS folder meta files (so only VFS file meta files and folders are included)
    IOFileFilter excludeFolderMetaFilter = new RegexFileFilter(excludeFolderMetaRegex);

    // read all files and folders excluding VFS folder meta files
    Collection<File> files = FileUtils.listFilesAndDirs(manifestRoot, excludeFolderMetaFilter,
            TrueFileFilter.INSTANCE);

    for (File file : files) {
        if (file.isDirectory()) {
            // exclude the manifest root
            if (file.getPath().equals(manifestRoot.getPath())) {
                continue;
            }
            addFolderToFilesNode(filesNode, file);
        } else {
            // exclude the manifest stub file and the manifest file
            if (file.getPath().equals(manifestPath) || file.getPath().equals(manifestStubPath)) {
                continue;
            }
            addFileToFilesNode(filesNode, file);
        }
    }

    // render the xml string
    String manifestString = xmlHelper.getXmlStringFromDocument(manifest, CDATA_NODES);

    // if a specific version is provided, replace the original version
    if (StringUtils.isNotBlank(moduleVersion)) {
        manifestString = manifestString.replaceFirst("<version>[^<]*</version>",
                "<version>" + Matcher.quoteReplacement(moduleVersion) + "</version>");
    }

    // write the manifest to the disk
    try {
        writeManifest(manifestPath, manifestString);
    } catch (IOException e) {
        throw new OpenCmsMetaXmlFileWriteException("manifest.xml could not be written", e);
    }
}

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

private BoxAndWhiskerCategoryDataset addDataSet(Hashtable<String, List> info) {
    DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();
    for (String key : info.keySet()) {
        System.out.println(key + ":" + info.get(key).size());
        String[] keyData = key.split(Pattern.quote("+"));
        dataset.add(info.get(key), keyData[1], getTechniqueName(keyData[0]));
    }/*w w w.  j ava2s .  c  o  m*/
    //System.out.println("dataset" + dataset);
    return dataset;
}

From source file:com.adobe.ags.curly.controller.ActionRunner.java

private void applyMultiVariablesToMap(Map<String, String> variables, Map<String, List<String>> target) {
    Set<String> variableTokens = ActionUtils.getVariableNames(action);

    Map<String, List<String>> newValues = new HashMap<>();
    Set removeSet = new HashSet<>();

    target.forEach((paramName, paramValues) -> {
        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 = "";
            }//from  w  w w . j ava  2  s. co m
            String variableValue = Matcher.quoteReplacement(val);
            String newParamName = paramNameProperty.get().replaceAll(variableNameMatchPattern, variableValue);
            removeSet.add(paramNameProperty.get());
            removeSet.add(paramName);
            if (newValues.get(paramNameProperty.get()) == null) {
                newValues.put(paramNameProperty.get(), new ArrayList<>(paramValues.size()));
            }
            if (newValues.get(newParamName) == null) {
                newValues.put(newParamName, new ArrayList<>(paramValues.size()));
            }
            List<String> newParamValues = newValues.get(paramNameProperty.get());
            for (int i = 0; i < paramValues.size(); i++) {
                String newParamValue = newParamValues != null && newParamValues.size() > i
                        && newParamValues.get(i) != null ? newParamValues.get(i) : paramValues.get(i);

                // fix for removing JCR values (setting them to an empty
                // string deletes them from the JCR)
                if (null == newParamValue) {
                    newParamValue = "";
                }

                newParamValue = newParamValue.replaceAll(variableNameMatchPattern, variableValue);
                if (newParamName.contains("/") && newParamValue.equals("@" + newParamName)) {
                    // The upload name should actually be the file name, not the full path of the file.
                    removeSet.add(newParamName);
                    newValues.remove(newParamName);
                    newParamName = newParamName.substring(newParamName.lastIndexOf("/") + 1);
                    newValues.put(newParamName, newParamValues);
                }
                if (newValues.get(newParamName).size() == i) {
                    newValues.get(newParamName).add(newParamValue);
                } else {
                    newValues.get(newParamName).set(i, newParamValue);
                }
            }
            if (!paramNameProperty.get().equals(newParamName)) {
                newValues.remove(paramNameProperty.get());
            }
            paramNameProperty.set(newParamName);
        });
    });
    target.keySet().removeAll(removeSet);
    target.putAll(newValues);
}

From source file:com.dtolabs.rundeck.plugin.resources.gcp.InstanceToNodeMapper.java

/**
 * Return the result of the selector applied to the instance, otherwise return the defaultValue. The selector can be
 * a comma-separated list of selectors./*from  w  ww . ja  va 2 s.c  o  m*/
 * @param inst the instance
 * @param selector the selector string
 * @param defaultValue a default value to return if there is no result from the selector
 * @param tagMerge if true, allow | separator to merge multiple values
 */

public static String applySelector(final Instance inst, final String selector, final String defaultValue,
        final boolean tagMerge) throws GeneratorException {

    if (null != selector) {
        for (final String selPart : selector.split(",")) {
            if (tagMerge) {
                final StringBuilder sb = new StringBuilder();
                for (final String subPart : selPart.split(Pattern.quote("|"))) {
                    final String val = applySingleSelector(inst, subPart);
                    if (null != val) {
                        if (sb.length() > 0) {
                            sb.append(",");
                        }
                        sb.append(val);
                    }
                }
                if (sb.length() > 0) {
                    return sb.toString();
                }
            } else {
                final String val = applySingleSelector(inst, selPart);
                if (null != val) {
                    return val;
                }
            }
        }
    }
    return defaultValue;
}

From source file:com.ngdata.hbaseindexer.cli.AddOrUpdateIndexerCli.java

private boolean isValidConnectionParam(String param) {
    List<String> fixed = Lists.newArrayList(SolrConnectionParams.COLLECTION, SolrConnectionParams.MODE,
            SolrConnectionParams.SHARDER_TYPE, SolrConnectionParams.ZOOKEEPER,
            SolrConnectionParams.MAX_CONNECTIONS, SolrConnectionParams.MAX_CONNECTIONS_PER_HOST);
    if (fixed.contains(param)) {
        return true;
    }/*from w w w. j a v  a2 s  .c om*/
    if (param.matches(Pattern.quote(SolrConnectionParams.SOLR_SHARD_PREFIX) + "\\d+")) {
        return true;
    }

    return false;
}

From source file:com.fujitsu.dc.test.jersey.box.odatacol.batch.UserDataBatchLinkTest.java

private String retrieveQueryOperationResErrorBody(int statusCode, String code, String message) {
    // TODO ?URI??
    return "Content-Type: application/http\n\n"
            + "HTTP/1.1 " + Integer.toString(statusCode) + " \n"
            + "Content-Type: application/json\n\n"
            + "\\{\"code\":\"" + code + "\",\"message\":\\{\"lang\":\"en\",\"value\":\"" + Pattern.quote(message)
            + ".*\n\n";
}

From source file:io.hawt.osgi.jmx.RBACDecorator.java

/**
 * <p>see: <code>org.apache.karaf.management.KarafMBeanServerGuard#getGeneralPid(java.util.List, java.lang.String)</code></p>
 *
 * <p>Given a list of all available configadmin PIDs that define RBAC information, return a real PID that'll be
 * used to fetch information about particular, non wildcard <code>pid</code>.</p>
 *
 * <p>Here, the PID returned may use wildcards ("_"), which means that general PID will be used to check particular
 * <code>pid</code> (one of possible PIDs derived from {@link ObjectName})</p>
 * @param allJmxAclPids//  w  w  w . j  a v  a  2s.  com
 * @param pid one of the PIDs returned from {@link #iterateDownPids(List)}
 * @return
 */
private static String getGeneralPid(List<String> allJmxAclPids, String pid) {
    String[] pidStrArray = pid.split(Pattern.quote("."));
    Set<String[]> rets = new TreeSet<>(WILDCARD_PID_COMPARATOR);
    for (String id : allJmxAclPids) {
        String[] idStrArray = id.split(Pattern.quote("."));
        if (idStrArray.length == pidStrArray.length) {
            boolean match = true;
            for (int i = 0; i < idStrArray.length; i++) {
                if (!(idStrArray[i].equals(JMX_OBJECTNAME_PROPERTY_WILDCARD)
                        || idStrArray[i].equals(pidStrArray[i]))) {
                    match = false;
                    break;
                }
            }
            if (match) {
                rets.add(idStrArray);
            }
        }
    }

    Iterator<String[]> it = rets.iterator();
    if (!it.hasNext()) {
        return "";
    } else {
        StringBuilder buffer = new StringBuilder();
        for (String segment : it.next()) {
            if (buffer.length() > 0) {
                buffer.append(".");
            }
            buffer.append(segment);
        }
        return buffer.toString();
    }
}

From source file:com.hp.mqm.client.AbstractMqmRestClient.java

/**
 * Resolves all placeholders in template according to their order in params. All parameters are URI encoded before
 * they are used for template resolving.
 * This method works properly only if method {@link #encodeParam(String)} encodes parameters correctly (replace '{' and '}' by some other character(s)).
 *
 * @param template URI template/* w w  w .j  a va2 s .  com*/
 * @param params   URI parameters
 * @return resolved URI template
 */
private String resolveTemplate(String template, Map<String, ?> params) {
    String result = template;
    for (String param : params.keySet()) {
        Object value = params.get(param);
        result = result.replaceAll(Pattern.quote("{" + param + "}"),
                encodeParam(value == null ? "" : value.toString()));
    }
    return result;
}

From source file:info.varden.anatychia.Main.java

public static String jsonDecode(String json) {
    String p1 = json.replace("\\\"", "\"").replace("\\/", "/").replace("\\b", "\b").replace("\\f", "\f")
            .replace("\\n", "\n").replace("\\t", "\t");
    Pattern p = Pattern.compile("\\\\u[0-9A-Fa-f]{4}");
    Matcher m = p.matcher(p1);//  w  ww . j  a  v  a 2 s.  c  om
    while (m.find()) {
        char c = (char) Integer.parseInt(m.group().substring(2), 16);
        p1 = p1.replaceFirst(Pattern.quote(m.group()), String.valueOf(c));
    }
    p1 = p1.replace("\\\\", "\\");
    return p1;
}