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:de.tarent.maven.plugins.pkg.AbstractMvnPkgPluginTestCase.java

protected boolean debContainsFile(String name) throws MojoExecutionException, IOException {
    final Pattern p = Pattern.compile(".*" + Pattern.quote(name) + ".*");
    return debContains(p, "-c");
}

From source file:de.tudarmstadt.ukp.clarin.webanno.tsv.WebannoTsv3Reader.java

/**
 * Importing span annotations including slot annotations
 * /* www . ja v a  2 s. com*/
 * @param aJCas
 * @param aAnnosPerTypePerUnit
 */

private void addAnnotations(JCas aJCas,
        Map<Type, Map<AnnotationUnit, List<AnnotationFS>>> aAnnosPerTypePerUnit) {

    for (Type type : annotationsPerPostion.keySet()) {
        Map<AnnotationUnit, Map<Integer, AnnotationFS>> multiTokUnits = new HashMap<>();
        int ref = 1;
        for (AnnotationUnit unit : annotationsPerPostion.get(type).keySet()) {
            int end = unit.end;
            List<AnnotationFS> annos = aAnnosPerTypePerUnit.get(type).get(unit);
            int j = 0;
            Feature linkeF = null;
            Map<AnnotationFS, List<FeatureStructure>> linkFSesPerSlotAnno = new HashMap<>();

            if (allLayers.get(type).size() == 0) {
                ref = addAnnotationWithNoFeature(aJCas, type, unit, annos, multiTokUnits, end, ref);
                continue;
            }

            for (Feature feat : allLayers.get(type)) {
                String anno = annotationsPerPostion.get(type).get(unit).get(j);
                if (!anno.equals("_")) {
                    int i = 0;
                    // if it is a slot annotation (multiple slots per
                    // single annotation
                    // (Target1<--role1--Base--role2-->Target2)
                    int slot = 0;
                    boolean targetAdd = false;
                    String stackedAnnoRegex = "(?<!\\\\)" + Pattern.quote("|");
                    for (String mAnnos : anno.split(stackedAnnoRegex)) {
                        String multipleSlotAnno = "(?<!\\\\)" + Pattern.quote(";");
                        for (String mAnno : mAnnos.split(multipleSlotAnno)) {
                            String depRef = "";
                            String multSpliter = "(?<!\\\\)" + Pattern.quote("[");
                            // is this slot target ambiguous?
                            boolean ambigTarget = false;
                            if (mAnno.split(multSpliter).length > 1) {
                                ambigTarget = true;
                                depRef = mAnno.substring(mAnno.indexOf("[") + 1, mAnno.length() - 1);
                                ref = depRef.contains("_") ? ref
                                        : Integer.valueOf(
                                                mAnno.substring(mAnno.indexOf("[") + 1, mAnno.length() - 1));
                                mAnno = mAnno.substring(0, mAnno.indexOf("["));
                            }
                            if (mAnno.equals("*")) {
                                mAnno = null;
                            }
                            boolean isMultitoken = false;
                            AnnotationFS multiAnnoFs = null;

                            if (!multiTokUnits.isEmpty())
                                for (AnnotationUnit u : multiTokUnits.keySet()) {
                                    for (Integer r : multiTokUnits.get(u).keySet()) {
                                        if (ref == r) {
                                            isMultitoken = true;
                                            multiAnnoFs = multiTokUnits.get(u).get(r);
                                            break;
                                        }
                                    }
                                }
                            if (isMultitoken) {
                                Feature endF = type.getFeatureByBaseName(CAS.FEATURE_BASE_NAME_END);
                                multiAnnoFs.setIntValue(endF, end);
                                mAnno = getEscapeChars(mAnno);
                                multiAnnoFs.setFeatureValueFromString(feat, mAnno);
                                if (feat.getShortName().equals(REF_LINK)) {
                                    // since REF_REL do not start with BIO,
                                    // update it it...
                                    annos.set(i, multiAnnoFs);
                                }
                                setAnnoRefPerUnit(unit, type, ref, multiAnnoFs);

                            } else {
                                if (roleLinks.containsKey(feat)) {
                                    linkeF = feat;
                                    FeatureStructure link = aJCas.getCas().createFS(slotLinkTypes.get(feat));
                                    Feature roleFeat = link.getType().getFeatureByBaseName("role");

                                    mAnno = getEscapeChars(mAnno);

                                    link.setStringValue(roleFeat, mAnno);
                                    linkFSesPerSlotAnno.putIfAbsent(annos.get(i), new ArrayList<>());
                                    linkFSesPerSlotAnno.get(annos.get(i)).add(link);

                                } else if (roleTargets.containsKey(feat)) {

                                    FeatureStructure link = linkFSesPerSlotAnno.get(annos.get(i)).get(slot);
                                    int customTypeNumber = 0;
                                    if (mAnno.split("-").length > 2) {
                                        customTypeNumber = Integer
                                                .valueOf(mAnno.substring(mAnno.lastIndexOf("-") + 1));
                                        mAnno = mAnno.substring(0, mAnno.lastIndexOf("-"));
                                    }

                                    AnnotationUnit targetUnit = token2Units.get(mAnno);
                                    Type tType = null;
                                    if (customTypeNumber == 0) {
                                        tType = roleTargets.get(feat);
                                    } else {
                                        tType = layerMaps.get(customTypeNumber);
                                    }
                                    AnnotationFS targetFs;

                                    if (ambigTarget) {
                                        targetFs = annosPerRef.get(tType).get(targetUnit).get(ref);
                                    } else {
                                        targetFs = annosPerRef.get(tType).get(targetUnit).entrySet().iterator()
                                                .next().getValue();
                                    }

                                    link.setFeatureValue(feat, targetFs);
                                    addSlotAnnotations(linkFSesPerSlotAnno, linkeF);
                                    targetAdd = true;
                                    slot++;

                                } else if (feat.getShortName().equals(REF_REL)) {

                                    int chainNo = Integer.valueOf(mAnno.split("->")[1].split("-")[0]);
                                    int LinkNo = Integer.valueOf(mAnno.split("->")[1].split("-")[1]);
                                    chainAnnosPerTyep.putIfAbsent(type, new TreeMap<>());
                                    if (chainAnnosPerTyep.get(type).get(chainNo) != null
                                            && chainAnnosPerTyep.get(type).get(chainNo).get(LinkNo) != null) {
                                        continue;
                                    }
                                    String refRel = mAnno.split("->")[0];

                                    refRel = getEscapeChars(refRel);
                                    if (refRel.equals("*")) {
                                        refRel = null;
                                    }

                                    annos.get(i).setFeatureValueFromString(feat, refRel);
                                    chainAnnosPerTyep.putIfAbsent(type, new TreeMap<>());
                                    chainAnnosPerTyep.get(type).putIfAbsent(chainNo, new TreeMap<>());
                                    chainAnnosPerTyep.get(type).get(chainNo).put(LinkNo, annos.get(i));

                                } else if (feat.getShortName().equals(REF_LINK)) {

                                    mAnno = getEscapeChars(mAnno);

                                    annos.get(i).setFeatureValueFromString(feat, mAnno);
                                    aJCas.addFsToIndexes(annos.get(i));

                                }

                                else if (depFeatures.get(type) != null && depFeatures.get(type).equals(feat)) {

                                    int g = depRef.isEmpty() ? 0 : Integer.valueOf(depRef.split("_")[0]);
                                    int d = depRef.isEmpty() ? 0 : Integer.valueOf(depRef.split("_")[1]);
                                    Type depType = depTypess.get(type);
                                    AnnotationUnit govUnit = token2Units.get(mAnno);
                                    int l = annotationsPerPostion.get(type).get(unit).size();
                                    String thisUnit = annotationsPerPostion.get(type).get(unit).get(l - 1);
                                    AnnotationUnit depUnit = token2Units.get(thisUnit);
                                    AnnotationFS govFs;
                                    AnnotationFS depFs;

                                    if (depType.getName().equals(POS.class.getName())) {
                                        depType = aJCas.getCas().getTypeSystem().getType(Token.class.getName());
                                        govFs = units2Tokens.get(govUnit);
                                        depFs = units2Tokens.get(unit);

                                    }
                                    // to pass the test case, which have relation on Token which not the case
                                    // in WebAnno world :)(!
                                    else if (depType.getName().equals(Token.class.getName())) {
                                        govFs = units2Tokens.get(govUnit);
                                        depFs = units2Tokens.get(unit);
                                    } else if (g == 0 && d == 0) {
                                        govFs = annosPerRef.get(depType).get(govUnit).entrySet().iterator()
                                                .next().getValue();
                                        depFs = annosPerRef.get(depType).get(depUnit).entrySet().iterator()
                                                .next().getValue();
                                    } else if (g == 0) {
                                        govFs = annosPerRef.get(depType).get(govUnit).entrySet().iterator()
                                                .next().getValue();
                                        depFs = annosPerRef.get(depType).get(depUnit).get(d);
                                    } else {
                                        govFs = annosPerRef.get(depType).get(govUnit).get(g);
                                        depFs = annosPerRef.get(depType).get(depUnit).entrySet().iterator()
                                                .next().getValue();
                                    }

                                    annos.get(i).setFeatureValue(feat, depFs);
                                    annos.get(i).setFeatureValue(type.getFeatureByBaseName(GOVERNOR), govFs);
                                    if (depFs.getBegin() <= annos.get(i).getBegin()) {
                                        Feature beginF = type.getFeatureByBaseName(CAS.FEATURE_BASE_NAME_BEGIN);
                                        annos.get(i).setIntValue(beginF, depFs.getBegin());
                                    } else {
                                        Feature endF = type.getFeatureByBaseName(CAS.FEATURE_BASE_NAME_END);
                                        annos.get(i).setIntValue(endF, depFs.getEnd());
                                    }
                                    aJCas.addFsToIndexes(annos.get(i));

                                } else {
                                    mAnno = getEscapeChars(mAnno);
                                    multiTokUnits.putIfAbsent(unit, new HashMap<>());
                                    multiTokUnits.get(unit).put(ref, annos.get(i));
                                    annos.get(i).setFeatureValueFromString(feat, mAnno);
                                    aJCas.addFsToIndexes(annos.get(i));
                                    setAnnoRefPerUnit(unit, type, ref, annos.get(i));
                                }

                            }
                            ref++;
                        }
                        if (type.getName().equals(POS.class.getName())) {
                            units2Tokens.get(unit).setPos((POS) annos.get(i));
                        }
                        if (type.getName().equals(Lemma.class.getName())) {
                            units2Tokens.get(unit).setLemma((Lemma) annos.get(i));
                        }
                        i++;
                    }

                    if (targetAdd) {
                        linkFSesPerSlotAnno = new HashMap<>();
                    }
                }
                j++;
            }
        }
        annosPerRef.put(type, multiTokUnits);
    }

}

From source file:com.hp.mqm.clt.RestClient.java

private String resolveTemplate(String template, Map<String, ?> params) {
    String result = template;/*from  w w w .j  a  va  2  s  .c o m*/
    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:com.thoughtworks.go.domain.materials.git.GitCommandTest.java

@Test
void shouldBombForResetWorkingDirWhenSubmoduleUpdateFails() throws Exception {
    GitRepoContainingSubmodule submoduleRepos = new GitRepoContainingSubmodule(temporaryFolder);
    File submoduleFolder = submoduleRepos.addSubmodule(SUBMODULE, "sub1");
    GitCommand gitWithSubmodule = new GitCommand(null, createTempWorkingDirectory(),
            GitMaterialConfig.DEFAULT_BRANCH, false, null);
    gitWithSubmodule.clone(inMemoryConsumer(), submoduleRepos.mainRepo().getUrl());
    FileUtils.deleteDirectory(submoduleFolder);

    assertThat(submoduleFolder.exists()).isFalse();
    try {//from w  w  w . j  a  v a 2s . c o  m
        gitWithSubmodule.resetWorkingDir(new SysOutStreamConsumer(), new StringRevision("HEAD"), false);
        fail("should have failed for non 0 return code");
    } catch (Exception e) {
        assertThat(e.getMessage())
                .containsPattern(String.format("[Cc]lone of '%s' into submodule path '((.*)[\\/])?sub1' failed",
                        Pattern.quote(FileUtil.toFileURI(submoduleFolder.getAbsolutePath()) + "/")));
    }
}

From source file:de.tarent.maven.plugins.pkg.AbstractMvnPkgPluginTestCase.java

protected boolean rpmContainsMainArtifact() throws MojoExecutionException, IOException {
    final Pattern p = Pattern
            .compile(".*" + Pattern.quote(packagingPlugin.project.getArtifact().getFile().getName()) + ".*");
    return rpmContains(p, "--dump");
}

From source file:de.tor.tribes.ui.components.GroupSelectionList.java

private List<Village> getVillagesByEquation() {
    StringBuilder b = new StringBuilder();
    boolean isFirst = true;
    List<Tag> relevantTags = new LinkedList<>();
    for (int i = 1; i < getModel().getSize(); i++) {
        ListItem item = getItemAt(i);//from  ww  w. j  a  v a 2  s. com
        boolean ignore = false;
        if (!isFirst) {
            switch (item.getState()) {
            case NOT:
                b.append(" && !");
                break;
            case AND:
                b.append(" && ");
                break;
            case OR:
                b.append(" || ");
                break;
            default:
                ignore = true;
            }
        } else {
            if (item.getState() == ListItem.RELATION_TYPE.DISABLED) {//ignore
                ignore = true;
            } else if (item.getState() == ListItem.RELATION_TYPE.NOT) {//NOT Tag 1
                b.append("!");
                isFirst = false;
            } else {
                isFirst = false;
            }
        }

        if (!ignore) {
            b.append(item.getTag().toString()).append(" ");
            relevantTags.add(item.getTag());
        }
    }

    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    String baseEquation = b.toString();

    List<Village> result = new LinkedList<>();
    try {
        if (relevantVillages == null) {
            relevantVillages = GlobalOptions.getSelectedProfile().getTribe().getVillageList();
        }
        for (Village v : relevantVillages) {
            String evaluationEquation = baseEquation;
            for (Tag tag : relevantTags) {
                evaluationEquation = evaluationEquation.replaceFirst(Pattern.quote(tag.toString()),
                        Boolean.toString(tag.tagsVillage(v.getId())));
            }
            engine.eval("var b = eval(\"" + evaluationEquation + "\")");
            if ((Boolean) engine.get("b")) {
                result.add(v);
            }
        }
    } catch (Exception e) {
        //no result
    }
    return result;
}

From source file:com.github.maven.plugin.client.impl.GithubClientImpl.java

/**
 * Removes the github url part from the given repository url.
 *
 * @param repositoryUrl The repository url.
 *
 * @return The repoditory url without the github part or {@code null} if it's not a valid github repository url.
 */// w  w w. j  av  a 2 s.c om
private String removeGithubUrlPart(String repositoryUrl) {
    Pattern pattern = Pattern.compile(Pattern.quote(GITHUB_REPOSITORY_URL_PREFIX) + "(.*)?");
    Matcher matcher = pattern.matcher(repositoryUrl);
    if (matcher.find()) {
        return matcher.group(1);
    }
    return null;
}

From source file:com.nuvolect.securesuite.webserver.connector.CmdUpload.java

/**
 * Collect chunk data until last chuck is received, then assemble the uploaded file.
 *
 * EXAMPLE, 60.3MB file://from   ww w. j  ava  2 s  .com
 * "cmd" -> "upload"
 * "mtime[]" -> "1489684754"
 * "cid" -> "697767115"
 * "upload_path[]" -> "l0_L3Rlc3QvdG1w"
 * "range" -> "0,10485760,60323475"
 x "post_uploads" -> "[{"file_path":"\/data\/user\/0\/com.nuvolect.securesuite.debug\/cache\/NanoHTTPD-340250228","file_name":"blob"}]"
 * "dropWith" -> "0"
 * "chunk" -> "kepler_7_weeks.mp4.0_5.part"
 x "target" -> "l0_L3Rlc3QvdG1w"
 * "unique_id" -> "1489174097708"
 * "upload[]" -> "blob"
 * "queryParameterStrings" -> "cmd=ls&target=l0_L3Rlc3QvdG1w&intersect%5B%5D=kepler_7_weeks.mp4&_=1489697705506"
 * "uri" -> "/connector"
 */
private InputStream chunksUpload(@NonNull Map<String, String> params, OmniFile targetDirectory) {
    String url = params.get("url");
    String targetVolumeId = targetDirectory.getVolumeId();

    JsonObject wrapper = new JsonObject();
    String chunk = params.get("chunk");
    String[] parts = chunk.split(Pattern.quote("."));
    String[] twoNumbers = parts[parts.length - 2].split("_");
    int chunkMax = Integer.valueOf(twoNumbers[1]);
    String targetFilename = parts[0] + "." + parts[1];
    JsonObject fileChunks = new JsonObject(); // Chunks for the target file

    /**
     * Parse the uploads array and collect specific of the current chunk.
     * Metadata for each chunk is saved in a JSONObject using the chunk filename as the key.
     * Move each chunk from the app:/cache folder to app:/chunk.
     * When all chunks are uploaded, the target is assembled and chunks deleted.
     */
    JsonParser parser = new JsonParser();
    JsonArray postUploads = parser.parse(params.get("post_uploads")).getAsJsonArray();

    for (int i = 0; i < postUploads.size(); i++) {
        JsonObject postUpload = postUploads.get(i).getAsJsonObject();
        //app: /cache/xxx
        String cachePath = postUpload.get(CConst.FILE_PATH).getAsString();
        File cacheFile = new File(cachePath);

        String chunkPath = chunkDirPath + FilenameUtils.getName(cachePath);
        File chunkFile = new File(chunkPath);

        /**
         * Move the chunk, otherwise Nanohttpd will delete it.
         */
        cacheFile.renameTo(chunkFile);

        JsonObject chunkObj = new JsonObject();
        chunkObj.addProperty("filepath", chunkPath);
        chunkObj.addProperty("range", params.get("range"));

        if (fileUploads.has(targetFilename)) {
            fileChunks = fileUploads.get(targetFilename).getAsJsonObject();
        } else {
            fileChunks = new JsonObject();
        }
        fileChunks.add(chunk, chunkObj);
        fileUploads.add(targetFilename, fileChunks);
    }

    /**
     * If not complete, return with intermediate results
     */
    if (fileChunks.size() <= chunkMax) {
        wrapper.add("added", new JsonArray());

        return getInputStream(wrapper);
    }

    try {
        int totalSize = 0;
        /**
         * All chunks are uploaded.  Iterate over the chunk meta data and assemble the file.
         * Open the target file.
         */
        OmniFile destFile = new OmniFile(targetVolumeId,
                targetDirectory.getPath() + File.separator + targetFilename);
        OutputStream destOutputStream = destFile.getOutputStream();
        String error = null;

        for (int i = 0; i <= chunkMax; i++) {
            String chunkKey = targetFilename + "." + i + "_" + chunkMax + ".part";

            if (!fileChunks.has(chunk)) {
                error = "Missing chunk: " + chunkKey;
                break;
            }

            JsonObject chunkObj = fileChunks.get(chunkKey).getAsJsonObject();
            String chunkPath = chunkObj.get("filepath").getAsString();
            File sourceFile = new File(chunkPath);
            if (sourceFile.exists()) {
                LogUtil.log(LogUtil.LogType.CMD_UPLOAD, "File exists: " + sourceFile.getPath());
            } else {
                LogUtil.log(LogUtil.LogType.CMD_UPLOAD, "File NOT exists: " + sourceFile.getPath());
                break;
            }

            FileInputStream fis = new FileInputStream(sourceFile);

            //TODO error check range of bytes from each chunk and compare with chunk bytes copied

            /**
             * Append next chunk to the destination file.
             */
            int bytesCopied = OmniFiles.copyFileLeaveOutOpen(fis, destOutputStream);

            totalSize += bytesCopied;

            LogUtil.log(LogUtil.LogType.CMD_UPLOAD, "Bytes copied, total: " + bytesCopied + ", " + totalSize);

            // Delete temp file
            if (!sourceFile.delete()) {
                error = "Delete temp file failed : " + sourceFile.getPath();
                LogUtil.log(LogUtil.LogType.CMD_UPLOAD, error);
                break;
            } else {
                LogUtil.log(LogUtil.LogType.CMD_UPLOAD, "Removed " + sourceFile.getName());
            }
        }
        destOutputStream.flush();
        destOutputStream.close();

        // Done with this file, clean up.
        fileUploads.remove(targetFilename);

        JsonArray added = new JsonArray();
        if (error == null) {
            JsonObject fileObj = FileObj.makeObj(targetVolumeId, destFile, url);
            added.add(fileObj);
            wrapper.add("added", added);
            LogUtil.log(LogUtil.LogType.CMD_UPLOAD, "File upload success: " + destFile.getPath());
        } else {
            JsonArray warning = new JsonArray();
            warning.add(error);
            wrapper.add("warning", warning);
        }

        return getInputStream(wrapper);

    } catch (IOException e) {
        logException(CmdUpload.class, e);
        clearChunkFiles();
    }
    return null;
}

From source file:de.tarent.maven.plugins.pkg.AbstractMvnPkgPluginTestCase.java

protected boolean ipkContainsMainArtifact() throws MojoExecutionException, IOException {
    final Pattern p = Pattern
            .compile(".*" + Pattern.quote(packagingPlugin.project.getArtifact().getFile().getName()) + ".*");
    return ipkContains(p, "-c");
}

From source file:com.csipsimple.wizards.impl.OneWorld.java

private Filter getFilterRemoveReplaceLeading(String prefix, String replace) {

    Filter f = new Filter();
    f.action = Filter.ACTION_REPLACE;
    f.matchPattern = "^" + Pattern.quote(prefix) + "(.*)$";
    f.replacePattern = replace + "$1";
    f.matchType = Filter.MATCHER_STARTS;

    return f;//  w w  w . j a v  a2s.c  o m
}