Example usage for java.util.regex Pattern toString

List of usage examples for java.util.regex Pattern toString

Introduction

In this page you can find the example usage for java.util.regex Pattern toString.

Prototype

public String toString() 

Source Link

Document

Returns the string representation of this pattern.

Usage

From source file:com.microsoft.tfs.client.eclipse.tpignore.TPIgnoreCache.java

/**
 * Tests whether the given resource matches any exclusion pattern in this
 * cache.//from   w w w  .  j  a  v a2s  .  c o  m
 *
 * @param resource
 *        the resource to test whether it matches (not null).
 * @return true if the the given resource matches the exclusions set for the
 *         resource's project, false if it does not.
 */
public boolean matchesAnyPattern(final IResource resource) {
    Check.notNull(resource, "resource"); //$NON-NLS-1$

    if (canMatch(resource)) {
        final Pattern[] patterns = getExclusionPatterns(resource.getProject());

        if (patterns == null || patterns.length == 0) {
            return false;
        }

        final String matchPath = createResourceMatchString(resource);

        for (final Pattern pattern : patterns) {
            if (pattern.matcher(matchPath).matches()) {
                log.debug(MessageFormat.format("item ''{0}'' matched exclusion pattern ''{1}''", //$NON-NLS-1$
                        matchPath, pattern.toString()));

                return true;
            }
        }
    }

    return false;
}

From source file:com.microsoft.tfs.client.eclipse.tpignore.TPIgnoreCache.java

/**
 * Gets the unique (as computed by {@link TPIgnorePatternComparator})
 * patterns in this cache which match the given resource.
 *
 * @param resource/*from www .  java2s  .  c o  m*/
 *        the resource to find matching patterns for (must not be
 *        <code>null</code>)
 * @return the {@link Pattern}s which match, {@link #NO_MATCH_PATTERN_ARRAY}
 *         if none match
 */
public Pattern[] getMatchingPatterns(final IResource resource) {
    Check.notNull(resource, "resource"); //$NON-NLS-1$

    if (canMatch(resource)) {
        final Pattern[] patterns = getExclusionPatterns(resource.getProject());

        if (patterns == null || patterns.length == 0) {
            return NO_MATCH_PATTERN_ARRAY;
        }

        final String matchPath = createResourceMatchString(resource);

        final Set<Pattern> matches = new TreeSet<Pattern>(new TPIgnorePatternComparator());

        for (final Pattern pattern : patterns) {
            if (pattern.matcher(matchPath).matches()) {
                log.debug(MessageFormat.format("item ''{0}'' matched exclusion pattern ''{1}''", //$NON-NLS-1$
                        matchPath, pattern.toString()));

                matches.add(pattern);
            }
        }

        if (matches.size() > 0) {
            return matches.toArray(new Pattern[matches.size()]);
        }
    }

    return NO_MATCH_PATTERN_ARRAY;
}

From source file:org.mobicents.servlet.restcomm.provisioning.number.vi.VoIPInnovationsNumberProvisioningManager.java

@Override
public List<PhoneNumber> searchForNumbers(String country, PhoneNumberSearchFilters listFilters) {
    if (logger.isDebugEnabled()) {
        logger.debug("searchPattern " + listFilters.getFilterPattern());
    }//  w  w w  . j a va  2  s .com
    String areaCode = listFilters.getAreaCode();
    Pattern filterPattern = listFilters.getFilterPattern();
    String searchPattern = null;
    if (filterPattern != null) {
        searchPattern = filterPattern.toString();
    }
    if ((areaCode == null || !areaCode.isEmpty() || areaCode.length() < 3) && (searchPattern != null
            && !searchPattern.toString().isEmpty() && searchPattern.toString().length() >= 5)) {
        areaCode = searchPattern.toString().substring(2, 5);
        if (logger.isDebugEnabled()) {
            logger.debug("areaCode derived from searchPattern " + searchPattern);
        }
    }
    if (areaCode != null && !areaCode.isEmpty() && (areaCode.length() == 3)) {
        final StringBuilder buffer = new StringBuilder();
        buffer.append("<request id=\"" + generateId() + "\">");
        buffer.append(header);
        buffer.append("<body>");
        buffer.append("<requesttype>").append("getDIDs").append("</requesttype>");
        buffer.append("<item>");
        buffer.append("<npa>").append(areaCode).append("</npa>");
        buffer.append("</item>");
        buffer.append("</body>");
        buffer.append("</request>");
        final String body = buffer.toString();
        final HttpPost post = new HttpPost(uri);

        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("apidata", body));
        try {
            post.setEntity(new UrlEncodedFormEntity(parameters));

            final DefaultHttpClient client = new DefaultHttpClient();
            if (telestaxProxyEnabled) {
                addTelestaxProxyHeaders(post, ProvisionProvider.REQUEST_TYPE.GETDIDS.name());
            }
            final HttpResponse response = client.execute(post);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                final String content = StringUtils.toString(response.getEntity().getContent());
                final VoipInnovationsResponse result = (VoipInnovationsResponse) xstream.fromXML(content);
                final GetDIDListResponse dids = (GetDIDListResponse) result.body().content();
                if (dids.code() == 100) {
                    final List<PhoneNumber> numbers = toAvailablePhoneNumbers(dids, listFilters);
                    return numbers;
                }
            } else {
                logger.warn("Couldn't reach uri for getting DIDs. Response status was: "
                        + response.getStatusLine().getStatusCode());
            }
        } catch (final Exception e) {
            logger.warn("Couldn't reach uri for getting DIDs " + uri, e);
        }
    }
    return new ArrayList<PhoneNumber>();
}

From source file:dk.netarkivet.harvester.indexserver.RawMetadataCache.java

/** Create a new RawMetadataCache.  For a given job ID, this will fetch
 * and cache selected content from metadata files
 * (&lt;ID&gt;-metadata-[0-9]+.arc).  Any entry in a metadata file that
 * matches both patterns will be returned.  The returned data does not
 * directly indicate which file they were from, though parts intrinsic to
 * the particular format might./* w  w w .  ja  va  2s  .co m*/
 *
 * @param prefix A prefix that will be used to distinguish this cache's
 * files from other caches'.  It will be used for creating a directory,
 * so it must not contain characters not legal in directory names.
 * @param urlMatcher A pattern for matching URLs of the desired entries.
 * If null, a .* pattern will be used.
 * @param mimeMatcher A pattern for matching mime-types of the desired
 * entries.  If null, a .* pattern will be used.
 */
public RawMetadataCache(String prefix, Pattern urlMatcher, Pattern mimeMatcher) {
    super(prefix);
    this.prefix = prefix;
    Pattern urlMatcher1;
    if (urlMatcher != null) {
        urlMatcher1 = urlMatcher;
    } else {
        urlMatcher1 = MATCH_ALL_PATTERN;
    }
    Pattern mimeMatcher1;
    if (mimeMatcher != null) {
        mimeMatcher1 = mimeMatcher;
    } else {
        mimeMatcher1 = MATCH_ALL_PATTERN;
    }
    log.info("Metadata cache for '" + prefix + "' is fetching" + " metadata with urls matching '"
            + urlMatcher1.toString() + "' and mimetype matching '" + mimeMatcher1 + "'");
    job = new GetMetadataArchiveBatchJob(urlMatcher1, mimeMatcher1);
}

From source file:org.mobicents.servlet.restcomm.provisioning.number.nexmo.NexmoPhoneNumberProvisioningManager.java

@Override
public List<PhoneNumber> searchForNumbers(String country, PhoneNumberSearchFilters listFilters) {
    if (logger.isDebugEnabled()) {
        logger.debug("searchPattern " + listFilters.getFilterPattern());
    }/*from  www.  j a v  a  2s . co  m*/
    Pattern filterPattern = listFilters.getFilterPattern();
    String filterPatternString = null;
    if (filterPattern != null) {
        filterPatternString = filterPattern.toString().replaceAll("[^\\d]", "");
    }
    if (logger.isDebugEnabled()) {
        logger.debug("searchPattern simplified for nexmo " + filterPatternString);
    }

    String queryUri = searchURI + country;
    boolean queryParamAdded = false;
    if (("US".equalsIgnoreCase(country) || "CA".equalsIgnoreCase(country))
            && listFilters.getAreaCode() != null) {
        // https://github.com/Mobicents/RestComm/issues/551 fixing the search pattern for US when Area Code is selected
        // https://github.com/Mobicents/RestComm/issues/602 fixing the search pattern for CA when Area Code is selected
        queryUri = queryUri + "?pattern=1" + listFilters.getAreaCode() + "&search_pattern=0";
        queryParamAdded = true;
    } else if (filterPatternString != null) {
        queryUri = queryUri + "?pattern=" + filterPatternString + "&search_pattern=1";
        queryParamAdded = true;
    }
    if (listFilters.getSmsEnabled() != null || listFilters.getVoiceEnabled() != null) {
        if (!queryParamAdded) {
            queryUri = queryUri + "?";
            queryParamAdded = true;
        } else {
            queryUri = queryUri + "&";
        }
        if (listFilters.getSmsEnabled() != null && listFilters.getVoiceEnabled() != null) {
            queryUri = queryUri + "features=SMS,VOICE";
        } else if (listFilters.getSmsEnabled() != null) {
            queryUri = queryUri + "features=SMS";
        } else {
            queryUri = queryUri + "features=VOICE";
        }
    }
    if (listFilters.getRangeIndex() != -1) {
        if (!queryParamAdded) {
            queryUri = queryUri + "?";
            queryParamAdded = true;
        } else {
            queryUri = queryUri + "&";
        }
        queryUri = queryUri + "index=" + listFilters.getRangeIndex();
    }
    if (listFilters.getRangeSize() != -1) {
        if (!queryParamAdded) {
            queryUri = queryUri + "?";
            queryParamAdded = true;
        } else {
            queryUri = queryUri + "&";
        }
        queryUri = queryUri + "size=" + listFilters.getRangeSize();
    }
    final HttpGet get = new HttpGet(queryUri);
    try {

        final DefaultHttpClient client = new DefaultHttpClient();
        //                if (telestaxProxyEnabled) {
        //                    // This will work as a flag for LB that this request will need to be modified and proxied to VI
        //                    get.addHeader("TelestaxProxy", String.valueOf(telestaxProxyEnabled));
        //                    // This will tell LB that this request is a getAvailablePhoneNumberByAreaCode request
        //                    get.addHeader("RequestType", "GetAvailablePhoneNumbersByAreaCode");
        //                    //This will let LB match the DID to a node based on the node host+port
        //                    for (SipURI uri: containerConfiguration.getOutboundInterfaces()) {
        //                        get.addHeader("OutboundIntf", uri.getHost()+":"+uri.getPort()+":"+uri.getTransportParam());
        //                    }
        //                }
        if (logger.isDebugEnabled()) {
            logger.debug("Nexmo query " + queryUri);
        }
        final HttpResponse response = client.execute(get);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            final String content = StringUtils.toString(response.getEntity().getContent());
            JsonParser parser = new JsonParser();
            JsonObject jsonResponse = parser.parse(content).getAsJsonObject();
            if (logger.isDebugEnabled()) {
                logger.debug("Nexmo response " + jsonResponse.toString());
            }
            JsonPrimitive countPrimitive = jsonResponse.getAsJsonPrimitive("count");
            if (countPrimitive == null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("No numbers found");
                }
                return new ArrayList<PhoneNumber>();
            }
            long count = countPrimitive.getAsLong();
            if (logger.isDebugEnabled()) {
                logger.debug("Number of numbers found : " + count);
            }
            JsonArray nexmoNumbers = jsonResponse.getAsJsonArray("numbers");
            final List<PhoneNumber> numbers = toAvailablePhoneNumbers(nexmoNumbers, listFilters);
            return numbers;
        } else {
            logger.warn("Couldn't reach uri for getting Phone Numbers. Response status was: "
                    + response.getStatusLine().getStatusCode());
        }
    } catch (final Exception e) {
        logger.warn("Couldn't reach uri for getting Phone Numbers" + uri, e);
    }

    return new ArrayList<PhoneNumber>();
}

From source file:com.ibm.jaggr.core.impl.modulebuilder.css.CSSModuleBuilderTest.java

@Test
public void testToRegexp() {
    CSSModuleBuilder builder = new CSSModuleBuilder() {
        @Override/* w ww  .j  a va  2  s  .  c o m*/
        public Pattern toRegexp(String filespec) {
            return super.toRegexp(filespec);
        }
    };
    Pattern regexp = builder.toRegexp("test?.*");
    Assert.assertEquals("(^|/)test[^/]\\.[^/]*?$", regexp.toString());
    Assert.assertTrue(regexp.matcher("test1.abc").find());
    Assert.assertFalse(regexp.matcher("test11.abc").find());
    Assert.assertTrue(regexp.matcher("/test1.abc").find());
    Assert.assertTrue(regexp.matcher("/some/path/test1.abc").find());
    regexp = builder.toRegexp("test/*/hello@$!.???");
    Assert.assertEquals("(^|/)test/[^/]*?/hello@\\$!\\.[^/][^/][^/]$", regexp.toString());
    Assert.assertTrue(regexp.matcher("test/abc/hello@$!.foo").find());
    Assert.assertTrue(regexp.matcher("/test/xyz/hello@$!.123").find());
    Assert.assertTrue(regexp.matcher("somepath/test/xyz/hello@$!.123").find());
    Assert.assertFalse(regexp.matcher("/test/xyz/hello@$!.ab").find());
    Assert.assertFalse(regexp.matcher("/test/hello@$!.123").find());
    regexp = builder.toRegexp("/a?c");
    Assert.assertEquals("/a[^/]c$", regexp.toString());
}

From source file:org.apache.eagle.jpm.mr.history.parser.JHFEventReaderBase.java

private boolean included(String key) {
    if (filter.getJobConfKeyInclusionPatterns() == null) {
        return true;
    }/*www  . j  a  v  a2s  .  com*/
    for (Pattern p : filter.getJobConfKeyInclusionPatterns()) {
        Matcher m = p.matcher(key);
        if (m.matches()) {
            LOG.info("include key: " + p.toString());
            return true;
        }
    }
    return false;
}

From source file:org.apache.kylin.common.KylinConfigBase.java

private static String getFileName(String homePath, Pattern pattern) {
    File home = new File(homePath);
    SortedSet<String> files = Sets.newTreeSet();
    if (home.exists() && home.isDirectory()) {
        File[] listFiles = home.listFiles();
        if (listFiles != null) {
            for (File file : listFiles) {
                final Matcher matcher = pattern.matcher(file.getName());
                if (matcher.matches()) {
                    files.add(file.getAbsolutePath());
                }/* w  w  w  .  ja  va2s  . co m*/
            }
        }
    }
    if (files.isEmpty()) {
        throw new RuntimeException("cannot find " + pattern.toString() + " in " + homePath);
    } else {
        return files.last();
    }
}

From source file:com.blackducksoftware.integration.hub.rest.RestConnection.java

/**
 * The proxy settings get set as System properties. I.E. https.proxyHost,
 * https.proxyPort, http.proxyHost, http.proxyPort, http.nonProxyHosts
 *
 *//* w  w w  .  j  a v  a2 s  .  com*/
public void setProxyProperties(final String proxyHost, final int proxyPort, final List<Pattern> noProxyHosts,
        final String proxyUsername, final String proxyPassword) {

    HubCredentials proxyCredentials = null;
    try {
        proxyCredentials = new HubCredentials(proxyUsername, proxyPassword);
    } catch (final IllegalArgumentException e) {
        if (logger != null) {
            logger.error(e);
        }
    } catch (final EncryptionException e) {
        if (logger != null) {
            logger.error(e);
        }
    }
    String noProxyHostsString = null;
    if (noProxyHosts != null && !noProxyHosts.isEmpty()) {
        for (final Pattern pattern : noProxyHosts) {
            if (noProxyHostsString == null) {
                noProxyHostsString = pattern.toString();
            } else {
                noProxyHostsString = noProxyHostsString + "|" + pattern.toString();
            }
        }
    }

    final HubProxyInfo proxyInfo = new HubProxyInfo(proxyHost, proxyPort, proxyCredentials, noProxyHostsString);
    setProxyProperties(proxyInfo);

}

From source file:com.blackducksoftware.integration.hub.ScanExecutor.java

public Result setupAndRunScan(final String scanExec, final String oneJarPath, final String javaExec)
        throws HubIntegrationException {
    if (isConfiguredCorrectly(scanExec, oneJarPath, javaExec)) {

        try {/*from  w w w .j a v a2  s . c  om*/

            final URL url = new URL(getHubUrl());
            final List<String> cmd = new ArrayList<>();

            final String javaPath = javaExec;

            getLogger().debug("Using this java installation : " + javaPath);

            cmd.add(javaPath);
            cmd.add("-Done-jar.silent=true");
            cmd.add("-Done-jar.jar.path=" + oneJarPath);

            if (StringUtils.isNotBlank(getProxyHost()) && getProxyPort() != null) {
                cmd.add("-Dhttp.proxyHost=" + getProxyHost());
                cmd.add("-Dhttp.proxyPort=" + getProxyPort());

                if (getNoProxyHosts() != null) {
                    final StringBuilder noProxyHosts = new StringBuilder();

                    for (final Pattern pattern : getNoProxyHosts()) {
                        if (noProxyHosts.length() > 0) {
                            noProxyHosts.append("|");
                        }
                        noProxyHosts.append(pattern.toString());
                    }
                    cmd.add("-Dhttp.nonProxyHosts=" + noProxyHosts.toString());
                }
                if (StringUtils.isNotBlank(getProxyUsername()) && StringUtils.isNotBlank(getProxyPassword())) {
                    cmd.add("-Dhttp.proxyUser=" + getProxyUsername());
                    cmd.add("-Dhttp.proxyPassword=" + getProxyPassword());
                }
            }

            cmd.add("-Xmx" + scanMemory + "m");

            cmd.add("-jar");
            cmd.add(scanExec);
            cmd.add("--scheme");
            cmd.add(url.getProtocol());
            cmd.add("--host");
            cmd.add(url.getHost());
            getLogger().debug("Using this Hub hostname : '" + url.getHost() + "'");
            cmd.add("--username");
            cmd.add(getHubUsername());
            if (!supportHelper.hasCapability(HubCapabilitiesEnum.CLI_PASSWORD_ENVIRONMENT_VARIABLE)) {
                cmd.add("--password");
                cmd.add(getHubPassword());
            }

            if (url.getPort() != -1) {
                cmd.add("--port");
                cmd.add(Integer.toString(url.getPort()));
            } else {
                if (url.getDefaultPort() != -1) {
                    cmd.add("--port");
                    cmd.add(Integer.toString(url.getDefaultPort()));
                } else {
                    getLogger().warn("Could not find a port to use for the Server.");
                }

            }

            if (isVerboseRun()) {
                cmd.add("-v");
            }

            final String logDirectoryPath = getLogDirectoryPath();
            cmd.add("--logDir");

            cmd.add(logDirectoryPath);

            if (isDryRun()) {
                // The dryRunWriteDir is the same as the log directory path
                // The CLI will create a subdirectory for the json files
                cmd.add("--dryRunWriteDir");
                cmd.add(getLogDirectoryPath());
            }

            if (supportHelper.hasCapability(HubCapabilitiesEnum.CLI_STATUS_DIRECTORY_OPTION)) {
                // Only add the statusWriteDir option if the Hub supports
                // the statusWriteDir option

                // The scanStatusDirectoryPath is the same as the log
                // directory path
                // The CLI will create a subdirectory for the status files
                final String scanStatusDirectoryPath = getLogDirectoryPath();

                cmd.add("--statusWriteDir");

                cmd.add(scanStatusDirectoryPath);
            }

            if (StringUtils.isNotBlank(getProject()) && StringUtils.isNotBlank(getVersion())) {
                cmd.add("--project");

                cmd.add(getProject());

                cmd.add("--release");

                cmd.add(getVersion());
            }

            for (final String target : scanTargets) {
                cmd.add(target);
            }

            return executeScan(cmd, logDirectoryPath);

        } catch (final MalformedURLException e) {
            throw new HubIntegrationException("The server URL provided was not a valid", e);
        } catch (final IOException e) {
            throw new HubIntegrationException(e.getMessage(), e);
        } catch (final InterruptedException e) {
            throw new HubIntegrationException(e.getMessage(), e);
        }
    } else {
        return Result.FAILURE;
    }
}