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:org.jahia.tools.maven.plugins.LegalArtifactAggregator.java

private void processJarFile(InputStream inputStream, String jarFilePath, JarMetadata contextJarMetadata,
        boolean processMavenPom, int level, boolean lookForNotice, boolean lookForLicense,
        boolean processingSources) throws IOException {
    // if we don't need to find either a license or notice, don't process the jar at all
    if (!lookForLicense && !lookForNotice) {
        return;/* w w w .  j  a v a 2  s .  c o  m*/
    }

    final String indent = getIndent(level);
    output(indent, "Processing JAR " + jarFilePath + "...", false, true);

    // JarFile realJarFile = new JarFile(jarFile);
    JarInputStream jarInputStream = new JarInputStream(inputStream);
    String bundleLicense = null;
    Manifest manifest = jarInputStream.getManifest();
    if (manifest != null && manifest.getMainAttributes() != null) {
        bundleLicense = manifest.getMainAttributes().getValue("Bundle-License");
        if (bundleLicense != null) {
            output(indent, "Found Bundle-License attribute with value:" + bundleLicense);
            KnownLicense knownLicense = getKnowLicenseByName(bundleLicense);
            // this data is not reliable, especially on the ServiceMix repackaged bundles
        }
    }
    String pomFilePath = null;
    byte[] pomByteArray = null;

    final String jarFileName = getJarFileName(jarFilePath);
    if (contextJarMetadata == null) {
        contextJarMetadata = jarDatabase.get(jarFileName);
        if (contextJarMetadata == null) {
            // compute project name
            contextJarMetadata = new JarMetadata(jarFilePath, jarFileName);
        }
        jarDatabase.put(jarFileName, contextJarMetadata);
    }

    Notice notice;
    JarEntry curJarEntry = null;
    while ((curJarEntry = jarInputStream.getNextJarEntry()) != null) {

        if (!curJarEntry.isDirectory()) {
            final String fileName = curJarEntry.getName();
            if (lookForNotice && isNotice(fileName, jarFilePath)) {

                output(indent, "Processing notice found in " + curJarEntry + "...");

                InputStream noticeInputStream = jarInputStream;
                List<String> noticeLines = IOUtils.readLines(noticeInputStream);
                notice = new Notice(noticeLines);

                Map<String, Notice> notices = contextJarMetadata.getNoticeFiles();
                if (notices == null) {
                    notices = new TreeMap<>();
                    notices.put(fileName, notice);
                    output(indent, "Found first notice " + curJarEntry);
                } else if (!notices.containsValue(notice)) {
                    output(indent, "Found additional notice " + curJarEntry);
                    notices.put(fileName, notice);
                } else {
                    output(indent, "Duplicated notice in " + curJarEntry);
                    notices.put(fileName, notice);
                    duplicatedNotices.add(jarFilePath);
                }

                // IOUtils.closeQuietly(noticeInputStream);
            } else if (processMavenPom && fileName.endsWith("pom.xml")) {
                // remember pom file path in case we need it
                pomFilePath = curJarEntry.getName();
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                IOUtils.copy(jarInputStream, byteArrayOutputStream);
                pomByteArray = byteArrayOutputStream.toByteArray();

            } else if (lookForLicense && isLicense(fileName, jarFilePath)) {

                output(indent, "Processing license found in " + curJarEntry + "...");
                InputStream licenseInputStream = jarInputStream;
                List<String> licenseLines = IOUtils.readLines(licenseInputStream);

                LicenseFile licenseFile = new LicenseFile(jarFilePath, fileName, jarFilePath, licenseLines);

                resolveKnownLicensesByText(licenseFile);

                if (StringUtils.isNotBlank(licenseFile.getAdditionalLicenseText())
                        && StringUtils.isNotBlank(licenseFile.getAdditionalLicenseText().trim())) {
                    KnownLicense knownLicense = new KnownLicense();
                    knownLicense.setId(FilenameUtils.getBaseName(jarFilePath) + "-additional-terms");
                    knownLicense
                            .setName("Additional license terms from " + FilenameUtils.getBaseName(jarFilePath));
                    List<TextVariant> textVariants = new ArrayList<>();
                    TextVariant textVariant = new TextVariant();
                    textVariant.setId("default");
                    textVariant.setDefaultVariant(true);
                    textVariant.setText(Pattern.quote(licenseFile.getAdditionalLicenseText()));
                    textVariants.add(textVariant);
                    knownLicense.setTextVariants(textVariants);
                    knownLicense.setTextToUse(licenseFile.getAdditionalLicenseText());
                    knownLicense.setViral(licenseFile.getText().toLowerCase().contains("gpl"));
                    knownLicenses.getLicenses().put(knownLicense.getId(), knownLicense);
                    licenseFile.getKnownLicenses().add(knownLicense);
                    licenseFile.getKnownLicenseKeys().add(knownLicense.getId());
                }

                for (KnownLicense knownLicense : licenseFile.getKnownLicenses()) {
                    SortedSet<LicenseFile> licenseFiles = knownLicensesFound.get(knownLicense);
                    if (licenseFiles != null) {
                        if (!licenseFiles.contains(licenseFile)) {
                            licenseFiles.add(licenseFile);
                        }
                        knownLicensesFound.put(knownLicense, licenseFiles);
                    } else {
                        licenseFiles = new TreeSet<>();
                        licenseFiles.add(licenseFile);
                        knownLicensesFound.put(knownLicense, licenseFiles);
                    }
                }

                Map<String, LicenseFile> licenseFiles = contextJarMetadata.getLicenseFiles();
                if (licenseFiles == null) {
                    licenseFiles = new TreeMap<>();
                }
                if (licenseFiles.containsKey(fileName)) {
                    // warning we already have a license file here, what should we do ?
                    output(indent, "License file already exists for " + jarFilePath + " will override it !",
                            true, false);
                    licenseFiles.remove(fileName);
                }
                licenseFiles.put(fileName, licenseFile);

                // IOUtils.closeQuietly(licenseInputStream);

            } else if (fileName.endsWith(".jar")) {
                InputStream embeddedJarInputStream = jarInputStream;
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                IOUtils.copy(embeddedJarInputStream, byteArrayOutputStream);
                final JarMetadata embeddedJarMetadata = new JarMetadata(jarFilePath, getJarFileName(fileName));

                if (embeddedJarMetadata != null) {
                    embeddedJarMetadata.setJarContents(byteArrayOutputStream.toByteArray());
                    contextJarMetadata.getEmbeddedJars().add(embeddedJarMetadata);
                }
            } else if (fileName.endsWith(".class")) {
                String className = fileName.substring(0, fileName.length() - ".class".length()).replaceAll("/",
                        ".");
                int lastPoint = className.lastIndexOf(".");
                String packageName = null;
                if (lastPoint > 0) {
                    packageName = className.substring(0, lastPoint);
                    SortedSet<String> currentJarPackages = jarDatabase
                            .get(FilenameUtils.getBaseName(jarFilePath)).getPackages();
                    if (currentJarPackages == null) {
                        currentJarPackages = new TreeSet<>();
                    }
                    currentJarPackages.add(packageName);
                }
            }

        }
        jarInputStream.closeEntry();
    }

    jarInputStream.close();
    jarInputStream = null;

    if (!contextJarMetadata.getEmbeddedJars().isEmpty()) {
        for (JarMetadata embeddedJarMetadata : contextJarMetadata.getEmbeddedJars()) {
            if (embeddedJarMetadata.getJarContents() != null) {
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
                        embeddedJarMetadata.getJarContents());
                processJarFile(byteArrayInputStream, contextJarMetadata.toString(), null, true, level, true,
                        true, processingSources);
            } else {
                output(indent, "Couldn't find dependency for embedded JAR " + contextJarMetadata, true, false);
            }
        }
    }

    if (processMavenPom) {
        if (pomFilePath == null) {
            output(indent, "No POM found in " + jarFilePath);
        } else {
            output(indent, "Processing POM found at " + pomFilePath + " in " + jarFilePath + "...");
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(pomByteArray);
            processJarPOM(byteArrayInputStream, pomFilePath, jarFilePath, contextJarMetadata, lookForNotice,
                    lookForLicense, contextJarMetadata.getEmbeddedJars(), level + 1, processingSources);
        }
    }

    if (lookForLicense || lookForNotice) {
        if (lookForLicense) {
            output(indent, "No license found in " + jarFilePath);
        }
        if (lookForNotice) {
            output(indent, "No notice found in " + jarFilePath);
        }

        if (pomFilePath == null && lookForLicense && lookForNotice) {
            if (StringUtils.isBlank(contextJarMetadata.getVersion())) {
                output(indent, "Couldn't resolve version for JAR " + contextJarMetadata
                        + ", can't query Maven Central repository without version !");
            } else {
                List<Artifact> mavenCentralArtifacts = findArtifactInMavenCentral(contextJarMetadata.getName(),
                        contextJarMetadata.getVersion(), contextJarMetadata.getClassifier());
                if (mavenCentralArtifacts != null && mavenCentralArtifacts.size() == 1) {
                    Artifact mavenCentralArtifact = mavenCentralArtifacts.get(0);
                    Artifact resolvedArtifact = resolveArtifact(mavenCentralArtifact, level);
                    if (resolvedArtifact != null) {
                        // we have a copy of the local artifact, let's request the sources for it.
                        if (!processingSources && !"sources".equals(contextJarMetadata.getClassifier())) {
                            final Artifact artifact = new DefaultArtifact(resolvedArtifact.getGroupId(),
                                    resolvedArtifact.getArtifactId(), "sources", "jar",
                                    resolvedArtifact.getVersion());
                            File sourceJar = getArtifactFile(artifact, level);
                            if (sourceJar != null && sourceJar.exists()) {
                                FileInputStream sourceJarInputStream = new FileInputStream(sourceJar);
                                processJarFile(sourceJarInputStream, sourceJar.getPath(), contextJarMetadata,
                                        false, level + 1, lookForNotice, lookForLicense, true);
                                IOUtils.closeQuietly(sourceJarInputStream);
                            }
                        } else {
                            // we are already processing a sources artifact, we need to load the pom artifact to extract information from there
                            final Artifact artifact = new DefaultArtifact(resolvedArtifact.getGroupId(),
                                    resolvedArtifact.getArtifactId(), null, "pom",
                                    resolvedArtifact.getVersion());
                            File artifactPom = getArtifactFile(artifact, level);
                            if (artifactPom != null && artifactPom.exists()) {
                                output(indent, "Processing POM for " + artifact + "...");
                                processPOM(lookForNotice, lookForLicense, jarFilePath, contextJarMetadata,
                                        contextJarMetadata.getEmbeddedJars(), level + 1,
                                        new FileInputStream(artifactPom), processingSources);
                            }
                        }
                    } else {
                        output(indent, "===>  Couldn't resolve artifact " + mavenCentralArtifact
                                + " in Maven Central. Please resolve license and notice files manually!", false,
                                true);
                    }
                } else {
                    output(indent, "===>  Couldn't find nor POM, license or notice. Please check manually!",
                            false, true);
                }
            }
        }
    }

    output(indent, "Done processing JAR " + jarFilePath + ".", false, true);

}

From source file:com.cdd.bao.importer.KeywordMapping.java

private String regexOrName(String regex, String name) {
    if (Util.notBlank(name))
        return Pattern.quote(name);
    return regex;
}

From source file:net.bashtech.geobot.Channel.java

public void addAutoReply(String trigger, String response) {
    trigger = trigger.replaceAll(",,", "");
    response.replaceAll(",,", "");

    if (!trigger.startsWith("REGEX:")) {
        String[] parts = trigger.replaceFirst("^\\*", "").replaceFirst("\\*$", "").split("\\*");

        // Only apply leading & trailing any if an one was requested
        boolean trailingAny = trigger.endsWith("*");
        if (trigger.startsWith("*"))
            trigger = ".*";
        else//from   ww w.  j av a2 s  . c o m
            trigger = "";

        for (int i = 0; i < parts.length; i++) {
            if (parts[i].length() < 1)
                continue;

            trigger += Pattern.quote(parts[i]);
            if (i != parts.length - 1)
                trigger += ".*";
        }

        if (trailingAny)
            trigger += ".*";

    } else {
        trigger = trigger.replaceAll("REGEX:", "");
    }

    System.out.println("Final: " + trigger);
    autoReplyTrigger.add(Pattern.compile(trigger, Pattern.CASE_INSENSITIVE));
    autoReplyResponse.add(response);

    saveAutoReply();
}

From source file:com.twinsoft.convertigo.engine.localbuild.BuildLocally.java

/***
 * /*from ww w  .j av  a2  s.c o m*/
 * @param paths
 * @param command
 * @return
 * @throws IOException
 */
private static String getFullPath(String paths, String command) throws IOException {
    for (String path : paths.split(Pattern.quote(File.pathSeparator))) {
        File candidate = new File(path, command);
        if (candidate.exists()) {
            return candidate.getCanonicalPath();
        }
    }
    return null;
}

From source file:com.android.ddmuilib.log.event.EventDisplay.java

/**
 * Loads a new {@link EventDisplay} from a storage string. The string must have been created
 * with {@link #getStorageString()}.//from   w ww.  j  a  v  a2 s  . c o  m
 *
 * @param storageString the storage string
 * @return a new {@link EventDisplay} or null if the load failed.
 */
static EventDisplay load(String storageString) {
    if (storageString.length() > 0) {
        // the storage string is separated by ':'
        String[] values = storageString.split(Pattern.quote(DISPLAY_DATA_STORAGE_SEPARATOR));

        try {
            int index = 0;

            String name = values[index++];
            int displayType = Integer.parseInt(values[index++]);
            boolean pidFiltering = Boolean.parseBoolean(values[index++]);

            EventDisplay ed = eventDisplayFactory(displayType, name);
            ed.setPidFiltering(pidFiltering);

            // because empty sections are removed by String.split(), we have to check
            // the index for those.
            if (index < values.length) {
                ed.loadPidFilters(values[index++]);
            }

            if (index < values.length) {
                ed.loadValueDescriptors(values[index++]);
            }

            if (index < values.length) {
                ed.loadOccurrenceDescriptors(values[index++]);
            }

            ed.updateValueDescriptorCheck();

            if (index < values.length) {
                ed.mMaximumChartItemAge = Long.parseLong(values[index++]);
            }

            if (index < values.length) {
                ed.mHistWidth = Long.parseLong(values[index++]);
            }

            return ed;
        } catch (RuntimeException re) {
            // we'll return null below.
            Log.e("ddms", re);
        }
    }

    return null;
}

From source file:com.microfocus.application.automation.tools.octane.configuration.JobConfigurationProxy.java

@JavaScriptMethod
public JSONObject searchListItems(String logicalListName, String term, String instanceId, long workspaceId,
        boolean multiValue, boolean extensible) {
    int defaultSize = 10;
    JSONObject ret = new JSONObject();
    OctaneClient octaneClient = OctaneSDK.getClientByInstanceId(instanceId);
    try {/* w w  w  .j  av  a  2 s.c o m*/
        ResponseEntityList listItemPagedList = queryListItems(octaneClient, logicalListName, term, workspaceId,
                defaultSize);
        List<Entity> listItems = listItemPagedList.getData();
        boolean moreResults = listItemPagedList.getTotalCount() > listItems.size();

        JSONArray retArray = new JSONArray();
        if (moreResults) {
            retArray.add(createMoreResultsJson());
        }

        if (!multiValue) {
            String quotedTerm = Pattern.quote(term.toLowerCase());
            if (Pattern.matches(".*" + quotedTerm + ".*", NOT_SPECIFIED.toLowerCase())) {
                JSONObject notSpecifiedItemJson = new JSONObject();
                notSpecifiedItemJson.put("id", -1);
                notSpecifiedItemJson.put("text", NOT_SPECIFIED);
                retArray.add(notSpecifiedItemJson);
            }
        }

        for (Entity item : listItems) {
            if (!toBeFiltered(item)) {
                JSONObject itemJson = new JSONObject();
                itemJson.put("id", item.getId());
                itemJson.put("text", item.getName());
                retArray.add(itemJson);
            }

        }
        // we shall use "if (extensible){}" on following line, but we do not have UI ready for the case: multiValue = true & extensible = true
        if (extensible && !multiValue) {
            //if exactly one item matches, we do not want to bother user with "new value" item
            if ((listItems.size() != 1)
                    || (!listItems.get(0).getName().toLowerCase().equals(term.toLowerCase()))) {
                retArray.add(createNewValueJson("0"));
            }
        }

        ret.put("results", retArray);
    } catch (Exception e) {
        logger.warn("Failed to retrieve list items", e);
        return error("Unable to retrieve job configuration");
    }

    return ret;
}

From source file:com.hichinaschool.flashcards.libanki.Finder.java

private String _findField(String field, String val) {
    val = val.replace("*", "%");
    // find models that have that field
    Map<Long, Object[]> mods = new HashMap<Long, Object[]>();
    try {//w w  w  . jav  a2 s  .c  o m
        for (JSONObject m : mCol.getModels().all()) {
            JSONArray flds = m.getJSONArray("flds");
            for (int fi = 0; fi < flds.length(); ++fi) {
                JSONObject f = flds.getJSONObject(fi);
                if (f.getString("name").equalsIgnoreCase(field)) {
                    mods.put(m.getLong("id"), new Object[] { m, f.getInt("ord") });
                }

            }

        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    if (mods.isEmpty()) {
        // nothing has that field
        return "";
    }
    // gather nids
    // Pattern.quote escapes the meta characters with \Q \E
    String regex = Pattern.quote(val).replace("\\Q_\\E", ".").replace("\\Q%\\E", ".*");
    LinkedList<Long> nids = new LinkedList<Long>();
    Cursor cur = null;
    try {
        cur = mCol.getDb().getDatabase()
                .rawQuery("select id, mid, flds from notes where mid in "
                        + Utils.ids2str(new LinkedList<Long>(mods.keySet())) + " and flds like ? escape '\\'",
                        new String[] { "%" + val + "%" });
        while (cur.moveToNext()) {
            String[] flds = Utils.splitFields(cur.getString(2));
            int ord = (Integer) mods.get(cur.getLong(1))[1];
            String strg = flds[ord];
            if (Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(strg).matches()) {
                nids.add(cur.getLong(0));
            }
        }
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    if (nids.isEmpty()) {
        return "";
    }
    return "n.id in " + Utils.ids2str(nids);
}

From source file:microsoft.exchange.webservices.data.core.EwsUtilities.java

/**
 * Parses an enum value list.//from   w  w  w.  jav a 2  s. c o  m
 *
 * @param <T>        the generic type
 * @param c          the c
 * @param list       the list
 * @param value      the value
 * @param separators the separators
 */
public static <T extends Enum<?>> void parseEnumValueList(Class<T> c, List<T> list, String value,
        char... separators) {
    EwsUtilities.ewsAssert(c.isEnum(), "EwsUtilities.ParseEnumValueList", "T is not an enum type.");

    StringBuilder regexp = new StringBuilder();
    regexp.append("[");
    for (char s : separators) {
        regexp.append("[");
        regexp.append(Pattern.quote(s + ""));
        regexp.append("]");
    }
    regexp.append("]");

    String[] enumValues = value.split(regexp.toString());

    for (String enumValue : enumValues) {
        for (T o : c.getEnumConstants()) {
            if (o.toString().equals(enumValue)) {
                list.add(o);
            }
        }
    }
}

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

private int addAnnotationWithNoFeature(JCas aJCas, Type aType, AnnotationUnit aUnit, List<AnnotationFS> aAnnos,
        Map<AnnotationUnit, Map<Integer, AnnotationFS>> aMultiTokUnits, int aEnd, int aRef) {
    String anno = annotationsPerPostion.get(aType).get(aUnit).get(0);
    if (!anno.equals("_")) {
        int i = 0;
        String stackedAnnoRegex = "(?<!\\\\)" + Pattern.quote("|");
        for (String mAnnos : anno.split(stackedAnnoRegex)) {
            String multipleSlotAnno = "(?<!\\\\)" + Pattern.quote(";");
            for (String mAnno : mAnnos.split(multipleSlotAnno)) {
                String depRef = "";
                if (mAnno.endsWith("]")) {
                    depRef = mAnno.substring(mAnno.indexOf("[") + 1, mAnno.length() - 1);
                    aRef = depRef.contains("_") ? 0
                            : Integer.valueOf(mAnno.substring(mAnno.indexOf("[") + 1, mAnno.length() - 1));
                    mAnno = mAnno.substring(0, mAnno.indexOf("["));
                }/*  ww w  .  j a va 2  s  . c o  m*/

                boolean isMultitoken = false;
                AnnotationFS multiAnnoFs = null;

                if (!aMultiTokUnits.isEmpty())
                    for (AnnotationUnit u : aMultiTokUnits.keySet()) {
                        for (Integer r : aMultiTokUnits.get(u).keySet()) {
                            if (aRef == r) {
                                isMultitoken = true;
                                multiAnnoFs = aMultiTokUnits.get(u).get(r);
                                break;
                            }
                        }
                    }

                if (isMultitoken) {

                    Feature endF = aType.getFeatureByBaseName(CAS.FEATURE_BASE_NAME_END);
                    multiAnnoFs.setIntValue(endF, aEnd);
                    setAnnoRefPerUnit(aUnit, aType, aRef, multiAnnoFs);

                } else {

                    aMultiTokUnits.putIfAbsent(aUnit, new HashMap<>());
                    aMultiTokUnits.get(aUnit).put(aRef, aAnnos.get(i));
                    aJCas.addFsToIndexes(aAnnos.get(i));
                    setAnnoRefPerUnit(aUnit, aType, aRef, aAnnos.get(i));
                }
                aRef++;
            }
            i++;
        }
    }
    return aRef;
}

From source file:com.hp.application.automation.tools.octane.configuration.JobConfigurationProxy.java

@JavaScriptMethod
public JSONObject searchReleases(String term, long workspaceId) {
    int defaultSize = 5;
    JSONObject ret = new JSONObject();

    MqmRestClient client;/*from ww  w.ja v a2s.c o m*/
    try {
        client = createClient();
    } catch (ClientException e) {
        logger.warn(PRODUCT_NAME + " connection failed", e);
        return error(e.getMessage(), e.getLink());
    }
    try {
        PagedList<Release> releasePagedList = client.queryReleases(term, workspaceId, 0, defaultSize);
        List<Release> releases = releasePagedList.getItems();
        boolean moreResults = releasePagedList.getTotalCount() > releases.size();

        JSONArray retArray = new JSONArray();
        if (moreResults) {
            retArray.add(createMoreResultsJson());
        }

        String quotedTerm = Pattern.quote(term.toLowerCase());
        if (Pattern.matches(".*" + quotedTerm + ".*", NOT_SPECIFIED.toLowerCase())) {
            JSONObject notSpecifiedItemJson = new JSONObject();
            notSpecifiedItemJson.put("id", -1);
            notSpecifiedItemJson.put("text", NOT_SPECIFIED);
            retArray.add(notSpecifiedItemJson);
        }

        for (Release release : releases) {
            JSONObject relJson = new JSONObject();
            relJson.put("id", release.getId());
            relJson.put("text", release.getName());
            retArray.add(relJson);
        }
        ret.put("results", retArray);

    } catch (RequestException e) {
        logger.warn("Failed to retrieve releases", e);
        return error("Unable to retrieve releases");
    }

    return ret;
}