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:hudson.plugins.sonar.utils.MaskPasswordsOutputStream.java

public MaskPasswordsOutputStream(OutputStream logger, Charset charset, Collection<String> passwords) {

    this.logger = logger;
    this.charset = charset;

    if (passwords != null && !passwords.isEmpty()) {

        // passwords are aggregated into a regex which is compiled as a pattern
        // for efficiency
        StringBuilder regex = new StringBuilder().append('(');

        int nbMaskedPasswords = 0;
        for (String password : passwords) {
            // we must not handle empty passwords
            if (StringUtils.isNotEmpty(password)) {
                regex.append(Pattern.quote(password));
                regex.append('|');
                nbMaskedPasswords++;/*from w  ww .  j av a2 s  .  co m*/
            }
        }
        // is there at least one password to mask?
        if (nbMaskedPasswords >= 1) {
            // removes the last unuseful pipe
            regex.deleteCharAt(regex.length() - 1);
            regex.append(')');
            passwordsAsPattern = Pattern.compile(regex.toString());
        } else {
            // no passwords to hide
            passwordsAsPattern = null;
        }
    } else {
        // no passwords to hide
        passwordsAsPattern = null;
    }
}

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

public static boolean isValidHostNameTemplateForVMs(String hostName, ServiceTemplateComponent component) {
    // must not be empty and must contain a number pattern for VMs
    if (StringUtils.isBlank(hostName) || !(hostName.contains(NUM_PATTERN))) {
        return false;
    }//from  w  ww .j a v a 2  s.c o  m

    // replace known patterns
    hostName = hostName.replaceAll(Pattern.quote(NUM_PATTERN), "123");

    return isValidHostName(hostName, component);
}

From source file:com.bodybuilding.turbine.servlet.ClusterListServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from  w w  w  .  j a v a 2 s .  com
        response.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        boolean preferPrivateAddress = request.getParameter("preferPrivateAddress") != null;
        String servletPathRegex = Pattern.quote(request.getServletPath());
        Set<String> clusterNames = ClusterListUtil.getClusterNames();
        Optional<String> dashboardUrl = getDashboardUrl(getServletContext(), request);
        String turbinePath = getTurbineMapping(getServletContext());
        String turbineBaseUrl;
        if (preferPrivateAddress && getPrivateAddress().isPresent()) {
            String requestURL = request.getRequestURL().toString();
            requestURL = requestURL.replace(request.getServerName(), getPrivateAddress().get());
            turbineBaseUrl = requestURL.replaceFirst(servletPathRegex, turbinePath + "?cluster=");
        } else {
            turbineBaseUrl = request.getRequestURL().toString().replaceFirst(servletPathRegex,
                    turbinePath + "?cluster=");
        }
        log.debug("Using turbine URL: {}", turbineBaseUrl);
        log.debug("Using dashboard URL: {}", dashboardUrl);
        ClusterMonitorFactory<?> clusterMonitorFactory = PluginsFactory.getClusterMonitorFactory();
        List<ClusterInfo> clusters = clusterNames.stream().filter(c -> {
            ClusterMonitor<? extends TurbineData> m = clusterMonitorFactory.getClusterMonitor(c);
            if (m == null) {
                log.debug("Cluster {} does not have a ClusterMonitor", c);
            }
            return m != null;
        }).map(c -> {
            String turbineUrl = turbineBaseUrl + encodeUrl(c);
            if (dashboardUrl.isPresent()) {
                String link = dashboardUrl.get() + encodeUrl(turbineBaseUrl + c) + "&title=" + encodeUrl(c);
                return new ClusterInfo(c, turbineUrl, link);
            } else {
                return new ClusterInfo(c, turbineUrl);
            }
        }).collect(Collectors.toList());

        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        OBJECT_MAPPER.writeValue(response.getOutputStream(), clusters);
        response.getOutputStream().flush();
    } catch (Exception e) {
        log.error("Error returning list of clusters", e);
    }
}

From source file:io.cloudslang.lang.runtime.bindings.AbstractBinding.java

protected Iterable<Value> getIterableFromEvalResult(Value loopCollection) {
    Serializable loopCollectionContent = loopCollection.get();
    if (loopCollectionContent instanceof Iterable) {
        @SuppressWarnings("unchecked")
        Iterable<? extends Serializable> loopCollectionContentSerializable = (Iterable<? extends Serializable>) loopCollectionContent;
        return convert(loopCollectionContentSerializable, loopCollection.isSensitive());
    } else if (loopCollectionContent instanceof String) {
        String[] strings = ((String) loopCollectionContent).split(Pattern.quote(","));
        return convert(Arrays.asList(strings), loopCollection.isSensitive());
    } else if (loopCollectionContent instanceof PyObject) {
        PyObject pyObject = (PyObject) loopCollectionContent;
        return convert(pyObject.asIterable(), loopCollection.isSensitive());
    } else {//from www .j  a  va  2 s  .  c om
        return null;
    }
}

From source file:de.uzk.hki.da.cb.ShortenFileNamesAction.java

@Override
public boolean implementation() throws FileNotFoundException, IOException {

    String metadataFile = o.getMetadata_file();

    // rename results of conversions
    for (Event e : o.getLatestPackage().getEvents()) {

        logger.debug("checking if event is CONVERT for {}", e);

        if (!"CONVERT".equals(e.getType()))
            continue;

        logger.debug("event is CONVERT: {}", e);

        DAFile daFile = e.getTarget_file();
        if (!daFile.getRep_name().startsWith(WorkArea.TMP_PIPS))
            continue;

        final File file = wa.toFile(daFile);
        final String filePath = daFile.getRelative_path();
        logger.debug("filePath: " + filePath);
        String extension = FilenameUtils.getExtension(filePath);
        logger.debug("extension: " + extension);

        String newFilePath;/*from  w  w w  . jav a 2 s .co  m*/
        if (filePath.equals(metadataFile)) {
            logger.warn("Metadata file should not be subject to a conversion!");
            continue;
        } else {
            final String hash = DigestUtils.md5Hex(filePath);
            logger.debug("hash: " + hash);
            newFilePath = "_" + hash + "." + extension;
        }

        logger.debug("newFilePath: " + newFilePath);
        File newFile = new File(file.getAbsolutePath().replaceAll(Pattern.quote(filePath) + "$", newFilePath));
        logger.debug("newFile: " + newFile.getAbsolutePath());

        daFile.setRelative_path(newFilePath);
        FileUtils.moveFile(file, newFile);
        map.put(newFilePath, filePath);

        deleteEmptyDirsRecursively(file.getAbsolutePath());

    }

    return true;

}

From source file:cf.adriantodt.utils.HTML2Discord.java

public static String toPlainText(String discordFormatMessage) {
    String strippedContent;/*www .  j  av  a 2 s.  c o  m*/
    //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(discordFormatMessage);
        while (matcher.find()) {
            tokens.add(new FormatToken(key, matcher.start()));
        }
    }

    //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(discordFormatMessage.substring(currIndex, formatToken.start));
        }
        currIndex = formatToken.start + formatToken.format.length();
    }
    if (currIndex < discordFormatMessage.length()) {
        out.append(discordFormatMessage.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:lucee.commons.io.res.type.smb.SMBResourceProvider.java

public static String unencryptUserInfo(String userInfo) {
    if (!isEncryptedUserInfo(userInfo))
        return userInfo;
    String encrypted = userInfo.replaceAll(Pattern.quote(ENCRYPTED_PREFIX), "");
    byte[] unencryptedBytes = Base32DecEnc.decode(encrypted.toUpperCase());
    return new String(unencryptedBytes, UTF8);

}

From source file:com.ogaclejapan.dotapk.manager.ApkFileManager.java

@Override
public File getByName(final String apk) throws WebApiException {
    if (!apkDir.exists()) {
        throw WebApiException.asInternalServerError("does not exist: " + apkDir.getAbsolutePath());
    }//  w  w w  . j  av a2  s .c  om

    File[] files = apkDir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.matches(Pattern.quote(apk));
        }
    });

    if (files == null || files.length == 0) {
        throw WebApiException.asNotFound("does not exist: " + apk);
    }

    return files[0];
}

From source file:com.genentech.chemistry.openEye.apps.SDFRingSystemExtractor.java

private void run(String inFile) {
    oemolithread ifs = new oemolithread(inFile);
    long start = System.currentTimeMillis();
    int iCounter = 0; //Structures in the SD file.

    OEMolBase mol = new OEGraphMol();
    RingSystemExtractor rsExtractor = new RingSystemExtractor();
    while (oechem.OEReadMolecule(ifs, mol)) {
        iCounter++;//w  ww.  j a v a 2  s .co  m
        rsExtractor.extract(mol);
        if (rsExtractor.hasLargestRingSystem()) {
            oechem.OESetSDData(mol, "largestRingSystem", rsExtractor.getLargestRingSystemSMILES());
        }
        if (rsExtractor.getBasicRingSystemCount() > 0) {
            oechem.OESetSDData(mol, "basicRingSystems", rsExtractor.getBasicRingSystemsSMILES());
        }
        oechem.OEWriteMolecule(outputOEThread, 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.Clear();
    }
    ifs.close();
    inFile = inFile.replaceAll(".*" + Pattern.quote(File.separator), "");
    System.err.printf("SDFRingSystemExtractor: Read %d structures from %s. %d sec\n", iCounter, inFile,
            (System.currentTimeMillis() - start) / 1000);
}

From source file:com.genentech.chemistry.openEye.apps.SDFMolSeparator.java

private void run(String inFile) {
    oemolithread ifs = new oemolithread(inFile);
    long start = System.currentTimeMillis();
    int iCounter = 0; //Structures in the input SD file
    int oCounter = 0; //Structure in the output SD file

    OEMolBase inMol = new OEGraphMol();
    while (oechem.OEReadMolecule(ifs, inMol)) {
        iCounter++;/*from w ww  .j a v  a 2s  . c om*/
        int nComponents = molSeparator.separate(inMol);
        for (int i = 0; i < nComponents; i++) {
            OEMolBase mol = molSeparator.getMol(i);
            oechem.OEWriteMolecule(outputOEThread, mol);
            oCounter++;
        }
        molSeparator.clear();

        //Output "." to show that the program is running.
        if (iCounter % 100 == 0)
            System.err.print(".");
        if (iCounter % 6000 == 0) {
            System.err.printf(" %d %dsec\n", iCounter, (System.currentTimeMillis() - start) / 1000);
        }
    }

    inMol.delete();
    ifs.close();
    ifs.delete();
    inFile = inFile.replaceAll(".*" + Pattern.quote(File.separator), "");
    System.err.printf("%s: Read %d molecules from %s and output %d molecules. %d sec\n", MY_NAME, iCounter,
            inFile, oCounter, (System.currentTimeMillis() - start) / 1000);
}