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.helpers.ServiceLocationsHelper.java

public static void addLocationToOpportunity(String opportunityID, String locationID)
        throws ConnectionException {
    System.out.println("addLocationToOpportunity\t" + opportunityID + "\t" + locationID);

    String tempArr[] = locationID.split(Pattern.quote("***"));
    String addLocations = tempArr[0];
    String deleteLocations = tempArr.length > 1 ? tempArr[1] : null;

    StringTokenizer st = new StringTokenizer(addLocations, ",");

    List<Pricesenz__ServLocOppJn__c> locations = getLocationsForOpportunity(opportunityID);

    ArrayList<Pricesenz__ServLocOppJn__c> addList = new ArrayList<>();
    ArrayList<Pricesenz__ServLocOppJn__c> deleteList = new ArrayList<>();

    Pricesenz__ServLocOppJn__c tempJnObj;

    while (st.hasMoreTokens()) {
        boolean flag = true;
        String tempID = st.nextToken();
        for (Pricesenz__ServLocOppJn__c l : locations) {
            if (l.getId().equals(tempID)) {
                //                    System.out.println(tempID);
                flag = false;//from   ww w .  ja  v a  2  s. c  o  m
                break;
            }
        }
        if (flag) {
            tempJnObj = new Pricesenz__ServLocOppJn__c();
            tempJnObj.setPricesenz__Service_Location__c(tempID);
            tempJnObj.setPricesenz__Opportunity__c(opportunityID);
            addList.add(tempJnObj);
        }
    }
}

From source file:AIR.ResourceBundler.Xml.FileSetInput.java

public String getRelative(String basePath, String targetPath) {

    targetPath = targetPath.replace('\\', '/');
    basePath = basePath.replace('\\', '/');

    String pathSeparator = "/";
    // Normalize the paths
    String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath);
    String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath);

    // Undo the changes to the separators made by normalization
    normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath);
    normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath);

    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.
    StringBuffer common = new StringBuffer();

    int commonIndex = 0;
    while (commonIndex < target.length && commonIndex < base.length
            && target[commonIndex].equals(base[commonIndex])) {
        common.append(target[commonIndex] + pathSeparator);
        commonIndex++;/*from w  ww.ja  v a2  s .  co  m*/
    }

    if (commonIndex == 0) {
        // No single common path element. This most
        // likely indicates differing drive letters, like C: and D:.
        // These paths cannot be relativized.
        try {
            throw new Exception("No common path element found for '" + normalizedTargetPath + "' and '"
                    + normalizedBasePath + "'");
        } catch (Exception e) {

        }
    }

    // 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;
    }

    StringBuffer relative = new StringBuffer();

    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:it.eng.spagobi.engines.chart.bo.charttypes.utils.MyCategoryUrlGenerator.java

public String generateURL(CategoryDataset dataset, int series, int category) {
    logger.debug("IN");
    URL = new String();
    URL = super.generateURL(dataset, series, category);

    // URL contains the URL generated by the JFreeChart Library

    // take the serieUrlLabel, default is "series"
    if (serieUrlLabel == null || serieUrlLabel.equals("")) {
        serieUrlLabel = "series";
    }/*from   ww w.j a  v  a 2  s  .c  o  m*/
    String serieToMove = replaceAndGetParameter("series=", serieUrlLabel, true);

    // take the categoryUrlLabel, default is "category"
    if (categoryUrlLabel == null || categoryUrlLabel.equals("")) {
        categoryUrlLabel = "category";
    }
    String categoryToMove = replaceAndGetParameter("category=", categoryUrlLabel, false);

    // this is the string to move inside PARAMETERS=
    String toMove = serieToMove + categoryToMove;

    // workaround (work-around): since JFreeChart converts white space into '+', this ruins the cross navigation url
    // therefore we substitute '+' with white space
    // TODO check what happens when the chart's template does not specify any categoryUrlName and seriesUrlName
    toMove = toMove.replaceAll(Pattern.quote("+"), " ");

    // insert into PARAMETERS=
    /*if(!document_composition){
    String parameters=ObjectsTreeConstants.PARAMETERS;
    URL=URL.replaceAll(parameters+"=", parameters+"="+toMove);
    URL=URL+"');";
    }
    else{*/
    URL = URL + toMove;
    if (drillDocTitle != null && target != null && target.equalsIgnoreCase("tab")) {
        URL += "','','" + drillDocTitle + "','tab";
    } else if (drillDocTitle != null) {
        URL += "','','" + drillDocTitle;
    }
    URL = URL + "');";
    logger.debug("Linked URL:" + URL);
    //}

    logger.debug("OUT");
    return URL;
}

From source file:py.una.pol.karaku.menu.client.MenuHelper.java

private String replace(String src, String toReplace, String replacement) {

    return src.replaceAll(Pattern.quote(toReplace), Matcher.quoteReplacement(replacement));
}

From source file:cz.muni.fi.mir.tools.Tools.java

/**
 * Method normalizes input string. Simply said it removes diacritics and other nonascii characters.
 * @param input to be normalized/*from ww  w .  j a v  a  2s .c om*/
 * @return normalized input, an input without unicode symbols
 * @throws IllegalArgumentException if input contains unsupported encoding
 */
public String normalizeString(String input) throws IllegalArgumentException {
    StringBuilder sb = new StringBuilder();

    String s1 = Normalizer.normalize(input, Normalizer.Form.NFKD);
    String regex = Pattern.quote("[\\p{InCombiningDiacriticalMarks}+");

    String s2 = null;
    try {
        s2 = new String(s1.replaceAll(regex, "").getBytes("ascii"), "ascii");
    } catch (UnsupportedEncodingException uee) {
        throw new IllegalArgumentException(uee);
    }

    char[] data = s2.toCharArray();

    for (char c : data) {
        if (c != '?') {
            sb.append(c);
        }
    }

    return sb.toString();
}

From source file:me.childintime.childintime.util.file.PathUtils.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 '\'.
 *
 * @param targetPath targetPath is calculated to this file
 * @param basePath basePath is calculated from this file
 * @param pathSeparator directory separator. The platform default is not assumed so that we can test Unix behaviour when running on Windows (for example)
 *
 * @return The relative path./*from   ww w . j a  v  a 2s .co  m*/
 */
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
    switch (pathSeparator) {
    case "/":
        normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath);
        break;

    case "\\":
        normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath);
        normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath);
        break;

    default:
        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]).append(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("..").append(pathSeparator);
    }

    relative.append(normalizedTargetPath.substring(common.length()));
    return relative.toString();
}

From source file:dollar.api.types.DollarString.java

@NotNull
@Override//www  . j  a  va 2  s . com
public Value $divide(@NotNull Value rhs) {
    Value rhsFix = rhs.$fixDeep();
    if (rhsFix.string() && !rhsFix.toString().isEmpty()) {
        try {
            //                final Pattern pattern = Pattern.compile(rhsFix.toString(),Pattern.LITERAL);
            final String quote = Pattern.quote(rhsFix.toString());
            final String[] split = value.split(quote);
            if (split.length == 1) {
                return this;
            }

            return DollarFactory.fromValue(Arrays.asList(split));
        } catch (PatternSyntaxException pse) {
            return failure(BAD_REGEX, pse, false);
        }
    } else if (rhsFix.number()) {
        if (rhsFix.toDouble() == 0.0) {
            return DollarFactory.infinity(true);
        }
        if ((rhsFix.toDouble() > 0.0) && (rhsFix.toDouble() < 1.0)) {
            return $multiply(DollarFactory.fromValue(1.0 / rhsFix.toDouble()));
        }
        if (rhsFix.toDouble() < 0) {
            return this;
        }
        return DollarFactory
                .fromStringValue(value.substring(0, (int) ((double) value.length() / rhsFix.toDouble())));
    } else {
        return this;
    }

}

From source file:com.predic8.membrane.core.interceptor.authentication.session.StaticUserDataProvider.java

@Override
public Map<String, String> verify(Map<String, String> postData) {
    String username = postData.get("username");
    if (username == null)
        throw new NoSuchElementException();
    if (username.equals("error"))
        throw new RuntimeException();
    User userAttributes;/*  w w w  . jav  a2s .  c o  m*/
    userAttributes = getUsersByName().get(username);
    if (userAttributes == null)
        throw new NoSuchElementException();
    String pw = null;
    String postDataPassword = postData.get("password");
    if (isHashedPassword(userAttributes.getPassword())) {
        String userHash = userAttributes.getPassword();
        if (userHash == null)
            throw new NoSuchElementException();
        String[] userHashSplit = userHash.split(Pattern.quote("$"));
        String algo = userHashSplit[1];
        String salt = userHashSplit[2];
        try {
            pw = createPasswdCompatibleHash(algo, postDataPassword, salt);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e.getMessage());
        }
    } else
        pw = postDataPassword;
    String pw2;
    pw2 = userAttributes.getPassword();
    if (pw2 == null || !pw2.equals(pw))
        throw new NoSuchElementException();
    return userAttributes.getAttributes();
}

From source file:com.thero.framework.util.AntPathStringMatcher.java

private String quote(String s, int start, int end) {
    if (start == end) {
        return "";
    }//from   www.  j a v a2s.  c o  m
    return Pattern.quote(s.substring(start, end));
}

From source file:de.fau.cs.osr.utils.FileCompare.java

private void checkReferenceFile(File expectedFile, String actual) throws IOException {
    if (!expectedFile.exists()) {
        File create;/*from   w  w w  .j a  va 2s  .c  om*/
        if (putInitialRefFilesIntoRefFileDir) {
            String dir = expectedFile.getParentFile().getAbsolutePath();

            // We always operate with UNIX separator '/':
            FileUtils.fileSeparatorToUnix(dir);

            if (inputPathToRefPathSearch == null)
                inputPathToRefPathSearch = Pattern.compile("(.*?)" + Pattern.quote("/target/test-classes/"));

            if (!inputPathToRefPathSearch.matcher(dir).find())
                Assert.fail("Reference file did not exist! " + "FAILED TO WRITE REFERENCE FILE!");

            if (inputPathToRefPathReplaceWith == null)
                inputPathToRefPathReplaceWith = "$1" + Pattern.quote("/src/test/resources/");

            dir = inputPathToRefPathSearch.matcher(dir).replaceAll(inputPathToRefPathReplaceWith);
            create = new File(dir);
        } else {
            create = new File("").getAbsoluteFile();
        }

        if (randomRefName) {
            create = File.createTempFile(expectedFile.getName() + "-", "", create);
        } else {
            create = new File(create, expectedFile.getName());
        }

        org.apache.commons.io.FileUtils.writeStringToFile(create, actual);
        Assert.fail("Reference file did not exist! " + "Wrote initial reference file to: "
                + create.getAbsolutePath());
    }
}