Example usage for java.util.regex Pattern matches

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

Introduction

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

Prototype

public static boolean matches(String regex, CharSequence input) 

Source Link

Document

Compiles the given regular expression and attempts to match the given input against it.

Usage

From source file:com.seajas.search.contender.replication.ModifierCache.java

/**
 * Determine whether the given modifier matches the URL.
 * //from   w  ww.j a  v a 2s  . c  om
 * @param modifier
 * @param url
 * @return boolean
 */
private static boolean modifierMatchesUrl(final Modifier modifier, final String url) {
    if (logger.isDebugEnabled())
        logger.debug("Attempting to match modifier expression '" + modifier.getUrlExpression()
                + "' against URL '" + url + "'");

    return Pattern.matches(modifier.getUrlExpression(), url);
}

From source file:com.frostwire.gui.components.slides.MultimediaSlideshowPanel.java

private boolean isMessageEligibleForMyVersion(String versions) {
    if (versions == null || versions.equals("*")) {
        return true;
    }/*from   ww  w.  j  a  va  2 s  .co m*/

    String frostWireVersion = FrostWireUtils.getFrostWireVersion();
    for (String pattern : versions.split(",")) {
        if (Pattern.matches(pattern, frostWireVersion)) {
            return true; // for-loop-break?
        }
    }

    return false;
}

From source file:com.seajas.search.contender.service.modifier.FeedModifierService.java

/**
 * Test a given feed modifier chain by its (feed) modifier ID.
 * //from  w  ww  .j ava2 s  . c o  m
 * @param id
 * @param uri
 * @param encodingOverride
 * @param userAgent
 * @throws Exception
 * @return List<String, Boolean>
 */
public Map<String, Boolean> testModifier(Integer id, URI uri, String encodingOverride, String userAgent)
        throws Exception {
    WebResolverSettings settings = new WebResolverSettings();
    settings.setMaximumContentLength(maximumContentLength);
    settings.setUserAgent(userAgent);

    Map<String, Boolean> result = new HashMap<String, Boolean>();

    logger.info("Testing feed modifier with ID " + id + " and URI " + uri);

    try {
        Modifier modifier = modifierCache.getFeedModifierById(id);

        if (!Pattern.matches(modifier.getUrlExpression(), uri.toString()))
            throw new Exception("The given testing feed URI is not covered by the modifier expression");

        Reader reader = getContent(uri, encodingOverride, userAgent, null);

        if (reader != null) {
            // Run it through the modifier

            for (ModifierFilter filter : modifier.getFilters()) {
                StringBuffer current = new StringBuffer(), updated = new StringBuffer();

                reader = readerToBuffer(current, reader, false);
                reader = modifierFilterProcessor.process(filter, reader);
                reader = readerToBuffer(updated, reader, false);

                result.put("Filter_" + filter.getId(), !current.toString().equals(updated.toString()));

                reader.close();
            }

            for (ModifierScript script : modifier.getScripts()) {
                StringBuffer current = new StringBuffer(), updated = new StringBuffer();

                reader = readerToBuffer(current, reader, false);
                reader = modifierScriptProcessor.process(script, extractAndClose(reader), uri, settings, false);
                reader = readerToBuffer(updated, reader, false);

                result.put("Script_" + script.getId(), !current.toString().equals(updated.toString()));

                reader.close();
            }
        } else
            throw new Exception("Could not retrieve the result feed content");
    } catch (ScriptException e) {
        throw new Exception("Could not test the given feed: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new Exception("Could not test the given feed: " + e.getMessage(), e);
    }

    return result;
}

From source file:com.turn.griffin.GriffinLibCacheUtil.java

public Map<String, FileInfo> findFilesToDownload() {

    Map<String, FileInfo> filesToDownload = new HashMap<>();

    Map<String, FileInfo> localFiles = getLatestLocalFileInfo().get();
    Map<String, FileInfo> globalFiles = getLatestGlobalFileInfo().get();

    /*//from   w ww  . j a va  2  s.co m
    List<String> watchedFiles = Lists.transform(SyncManagerWatcher.getInstance().getWatchers(),
        new Function<Watcher, String>() {
            @Override
            public String apply(Watcher w) {
                return w.getResource() + "-" + w.getSchemaVersion();
            }
        }
    );
    */

    for (FileInfo globalFile : globalFiles.values()) {

        /* If this server is not in the list of destinations, ignore the file */
        boolean destMatch = false;
        for (String dest : globalFile.getDest().replaceAll("\\s+", "").split(",")) {
            destMatch = destMatch || Pattern.matches(dest, this.myServerId);
        }

        String globalFilename = globalFile.getFilename();
        //destMatch = destMatch || watchedFiles.contains(globalFilename);

        if (!destMatch) {
            continue;
        }

        Optional<FileInfo> localFile = Optional.fromNullable(localFiles.get(globalFilename));
        if (!localFile.isPresent()) {
            filesToDownload.put(globalFilename, globalFile);
            continue;
        }

        if (localFile.get().getVersion() < globalFile.getVersion()) {
            filesToDownload.put(globalFilename, globalFile);
        }
    }

    return filesToDownload;
}

From source file:fr.msch.wissl.server.Library.java

private Library() {
    this.songs = new ConcurrentLinkedQueue<Song>();
    this.toRead = new ConcurrentHashMap<String, File>();
    this.files = new ConcurrentLinkedQueue<File>();
    this.toInsert = new ConcurrentLinkedQueue<Song>();
    this.hashes = new HashSet<String>();
    this.artworks = new HashMap<String, Map<String, String>>();

    this.artworkFallback = new FileFilter() {
        @Override//from  w  w w  . j  av a2  s.c om
        public boolean accept(File pathname) {
            return Pattern.matches(".*[.](jpeg|jpg|png|bmp|gif)$", pathname.getName().toLowerCase());
        }
    };

    Runnable timer = new Runnable() {

        @Override
        public void run() {
            while (!kill) {
                final long t1 = System.currentTimeMillis();

                final List<File> music = new ArrayList<File>();
                for (String path : Config.getMusicPath()) {
                    music.add(new File(path));
                }

                addSongCount = 0;
                skipSongCount = 0;
                failedSongCount = 0;
                fileSearchTime = 0;
                dbCheckTime = 0;
                fileReadTime = 0;
                dbInsertTime = 0;
                resizeTime = 0;
                songs.clear();
                toRead.clear();
                files.clear();
                hashes.clear();
                toInsert.clear();
                artworks.clear();

                songsTodo = 0;
                songsDone = 0;
                working = true;
                stop = false;
                percentDone = 0.0f;
                secondsLeft = -1;

                artworkRegex = Pattern.compile(Config.getArtworkRegex());
                artworkFilter = new FileFilter() {
                    @Override
                    public boolean accept(File pathname) {
                        return (artworkRegex.matcher(pathname.getName().toLowerCase()).matches());
                    }
                };

                // walks filesystem and indexes files that look like music
                fileSearchDone = false;
                Thread fileSearch = new Thread(new Runnable() {
                    public void run() {
                        long f1 = System.currentTimeMillis();
                        for (File f : music) {
                            try {
                                listFiles(f, files);
                            } catch (IOException e) {
                                Logger.error("Failed to add directory to library: " + f.getAbsolutePath(), e);
                            } catch (InterruptedException e) {
                                return;
                            }
                        }
                        fileSearchDone = true;
                        fileSearchTime = (System.currentTimeMillis() - f1);
                    }
                });
                fileSearch.start();

                // exclude files that are already in DB
                dbCheckDone = false;
                Thread dbCheck = new Thread(new Runnable() {
                    public void run() {
                        while (!stop && !dbCheckDone) {
                            long f1 = System.currentTimeMillis();
                            while (!files.isEmpty()) {
                                File f = files.remove();
                                String hash = new String(md5.digest(f.getAbsolutePath().getBytes()));

                                boolean hasSong = false;

                                try {
                                    hasSong = DB.get().hasSong(hash);
                                } catch (SQLException e) {
                                    Logger.error("Failed to query DB for file " + f.getAbsolutePath(), e);
                                }
                                if (!hasSong) {
                                    toRead.put(hash, f);
                                } else {
                                    skipSongCount++;
                                }
                                hashes.add(hash);
                            }

                            dbCheckTime += (System.currentTimeMillis() - f1);
                            if (fileSearchDone && files.isEmpty()) {
                                dbCheckDone = true;
                                return;
                            }
                        }
                    }
                });
                dbCheck.start();

                // read file metadata
                fileReadDone = false;
                Thread fileRead = new Thread(new Runnable() {
                    public void run() {
                        while (!stop && !fileReadDone) {
                            long f1 = System.currentTimeMillis();

                            Iterator<Entry<String, File>> it = toRead.entrySet().iterator();
                            while (it.hasNext()) {
                                Entry<String, File> f = it.next();
                                it.remove();
                                try {
                                    Song s = getSong(f.getValue(), f.getKey());
                                    songs.add(s);
                                    addSongCount++;
                                } catch (IOException e) {
                                    Logger.warn("Failed to read music file " + f.getValue(), e);
                                    failedSongCount++;
                                }
                            }

                            fileReadTime += (System.currentTimeMillis() - f1);
                            if (dbCheckDone && toRead.isEmpty()) {
                                fileReadDone = true;
                                return;
                            }
                        }
                    }
                });
                fileRead.start();

                // resize images
                resizeDone = false;
                Thread resize = new Thread(new Runnable() {
                    public void run() {
                        while (!stop && !resizeDone) {
                            long f1 = System.currentTimeMillis();
                            while (!songs.isEmpty()) {
                                Song s = songs.remove();
                                String path = null;
                                Map<String, String> m = artworks.get(s.artist.name);
                                if (m != null && m.containsKey(s.album.name)) {
                                    path = m.get(s.album.name);
                                }
                                if (path != null) {
                                    if (new File(path + "_SCALED.jpg").exists()) {
                                        path = path + "_SCALED.jpg";
                                    } else {
                                        try {
                                            path = resizeArtwork(path);
                                        } catch (IOException e) {
                                            Logger.warn("Failed to resize image", e);
                                        }
                                    }
                                    s.album.artwork_path = path;
                                    s.album.artwork_id = "" + System.currentTimeMillis();
                                }
                                toInsert.add(s);
                            }
                            resizeTime += (System.currentTimeMillis() - f1);

                            if (fileReadDone && songs.isEmpty()) {
                                resizeDone = true;
                                return;
                            }
                        }
                    }
                });
                resize.start();

                // insert Songs in DB
                Thread dbInsert = new Thread(new Runnable() {
                    public void run() {
                        while (!stop) {
                            long f1 = System.currentTimeMillis();
                            while (!toInsert.isEmpty()) {
                                Song s = toInsert.remove();
                                try {
                                    DB.get().addSong(s);
                                } catch (SQLException e) {
                                    Logger.warn("Failed to insert in DB " + s.filepath, e);
                                    failedSongCount++;
                                }
                                songsDone++;
                                percentDone = songsDone / ((float) songsTodo);

                                float songsPerSec = songsDone / ((System.currentTimeMillis() - t1) / 1000f);
                                secondsLeft = (long) ((songsTodo - songsDone) / songsPerSec);
                            }
                            dbInsertTime += (System.currentTimeMillis() - f1);

                            if (resizeDone && toInsert.isEmpty()) {
                                return;
                            }
                        }
                    }
                });
                dbInsert.start();
                try {
                    dbInsert.join();
                } catch (InterruptedException e3) {
                    Logger.warn("Library indexer interrupted", e3);
                    fileSearch.interrupt();
                    dbCheck.interrupt();
                    fileRead.interrupt();
                    resize.interrupt();
                    dbInsert.interrupt();
                }

                if (Thread.interrupted()) {
                    Logger.warn("Library indexer has been interrupted");
                    continue;
                }

                // remove files from DB that were not found
                int removed = 0;
                long r1 = System.currentTimeMillis();
                try {
                    removed = DB.get().removeSongs(hashes);
                } catch (SQLException e3) {
                    Logger.error("Failed to remove songs", e3);
                }
                long dbRemoveTime = (System.currentTimeMillis() - r1);

                // update statistics
                long u1 = System.currentTimeMillis();
                try {
                    DB.get().updateSongCount();
                } catch (SQLException e1) {
                    Logger.error("Failed to update song count", e1);
                }
                long dbUpdateTime = (System.currentTimeMillis() - u1);

                try {
                    RuntimeStats.get().updateFromDB();
                } catch (SQLException e) {
                    Logger.error("Failed to update runtime statistics", e);
                }

                working = false;

                long t2 = (System.currentTimeMillis() - t1);
                Logger.info("Processed " + songsDone + " files " //
                        + "(add:" + addSongCount + "," //
                        + "skip:" + skipSongCount + "," //
                        + "fail:" + failedSongCount + "," //
                        + "rem:" + removed + ")");
                Logger.info("Indexer took " + t2 + " (" + ((float) songsDone / ((float) t2 / 1000)) + " /s) (" //
                        + "search:" + fileSearchTime + "," //
                        + "check:" + dbCheckTime + ","//
                        + "read:" + fileReadTime + "," //
                        + "resize:" + resizeTime + "," //
                        + "insert:" + dbInsertTime + "," //
                        + "remove:" + dbRemoveTime + "," //
                        + "update:" + dbUpdateTime + ")");

                int seconds = Config.getMusicRefreshRate();
                try {
                    Thread.sleep(seconds * 1000);
                } catch (InterruptedException e) {
                    Logger.warn("Library indexer interrupted", e);
                }
            }
        }

    };
    this.thread = new Thread(timer, "MusicIndexer");
}

From source file:br.com.nordestefomento.jrimum.vallia.AbstractCPRFValidator.java

/**
 * <p>//from  ww w .ja  v a  2 s . c o  m
 * Faz a pr-validao e se correto identifica o tipo de cadastro.
 * </p>
 * 
 * @param codigoDoCadastro
 * @return
 * @throws IllegalArgumentException
 * 
 * @since 0.2
 */
private static TipoDeCPRF selectTipoDeCadastro(String codigoDoCadastro) throws IllegalArgumentException {

    TipoDeCPRF tipo = null;

    switch_Tipo: {

        if (StringUtils.isNotBlank(codigoDoCadastro)) {

            /*
             * FILTRO
             */

            if (Pattern.matches(REGEX_CPF, codigoDoCadastro)) {

                tipo = TipoDeCPRF.CPF;

                break switch_Tipo;
            }

            if (Pattern.matches(REGEX_CNPJ, codigoDoCadastro)) {

                tipo = TipoDeCPRF.CNPJ;

                break switch_Tipo;
            }

        }

        throw new IllegalArgumentException(
                "O cdigo de cadastro [ " + codigoDoCadastro + " ] no est em um formatador vlido !");
    }

    return tipo;
}

From source file:com.adobe.acs.commons.util.impl.UrlFilter.java

private boolean check(String value, String allowedArrayPropertyName, String allowedPatternPropertyName,
        ValueMap properties) {//  w w w  .j  a v a2s.c  o m
    if (value == null) {
        // no value is always allowed
        return true;
    }
    String[] allowedValues = properties.get(allowedArrayPropertyName, String[].class);
    if (allowedValues != null) {
        if (allowedValues.length == 0) {
            log.debug("{} was empty, therefore not allowing any value.", allowedArrayPropertyName);
            return false;
        } else if (!ArrayUtils.contains(allowedValues, value)) {
            log.debug("{} did not contain our string {}. checking the pattern.", allowedArrayPropertyName,
                    value);
            String allowedPattern = properties.get(allowedPatternPropertyName, String.class);
            if (allowedPattern == null || !Pattern.matches(allowedPattern, value)) {
                log.debug("allowedPattern ({}) did not match our string {}", allowedPattern, value);
                return false;
            } else {
                log.debug("allowedPattern ({}) did match our string {}", allowedPattern, value);
                return true;
            }
        } else {
            return true;
        }
    } else {
        String allowedPattern = properties.get(allowedPatternPropertyName, String.class);
        if (allowedPattern != null && !Pattern.matches(allowedPattern, value)) {
            log.debug("allowedPattern ({}) did not match our string {}", allowedPattern, value);
            return false;
        } else {
            return true;
        }
    }
}

From source file:com.microsoft.azure.management.resources.ResourceGroupOperationsImpl.java

/**
* Begin deleting resource group.To determine whether the operation has
* finished processing the request, call GetLongRunningOperationStatus.
*
* @param resourceGroupName Required. The name of the resource group to be
* deleted. The name is case insensitive.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations./* www.  ja  v a 2s . c  o  m*/
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response for long running operations.
*/
@Override
public LongRunningOperationResponse beginDeleting(String resourceGroupName)
        throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (resourceGroupName != null && resourceGroupName.length() > 1000) {
        throw new IllegalArgumentException("resourceGroupName");
    }
    if (Pattern.matches("^[-\\w\\._]+$", resourceGroupName) == false) {
        throw new IllegalArgumentException("resourceGroupName");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("resourceGroupName", resourceGroupName);
        CloudTracing.enter(invocationId, this, "beginDeletingAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/resourcegroups/";
    url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2014-04-01-preview");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    CustomHttpDelete httpRequest = new CustomHttpDelete(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_ACCEPTED) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        LongRunningOperationResponse result = null;
        // Deserialize Response
        result = new LongRunningOperationResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("Location").length > 0) {
            result.setOperationStatusLink(httpResponse.getFirstHeader("Location").getValue());
        }
        if (httpResponse.getHeaders("Retry-After").length > 0) {
            result.setRetryAfter(
                    DatatypeConverter.parseInt(httpResponse.getFirstHeader("Retry-After").getValue()));
        }
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }
        if (statusCode == HttpStatus.SC_CONFLICT) {
            result.setStatus(OperationStatus.Failed);
        }
        if (statusCode == HttpStatus.SC_OK) {
            result.setStatus(OperationStatus.Succeeded);
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:cx.fbn.nevernote.sql.REnSearch.java

private boolean matchTagsAny(List<String> tagNames, List<String> list) {
    if (list.size() == 0)
        return true;

    boolean negative = false;

    for (int j = 0; j < list.size(); j++) {
        negative = false;//from w  w w  .  j  a v  a 2s  .  co  m
        if (list.get(j).startsWith("-"))
            negative = true;
        int pos = list.get(j).indexOf(":");
        String filterName = cleanupWord(list.get(j).substring(pos + 1));
        filterName = filterName.replace("*", ".*"); // setup for regular expression pattern match

        if (tagNames.size() == 0 && !negative)
            return false;

        for (int i = 0; i < tagNames.size(); i++) {
            boolean matches = Pattern.matches(filterName.toLowerCase(), tagNames.get(i).toLowerCase());
            if (!matches && !negative)
                return false;
        }
    }
    return true;
}

From source file:net.sf.jailer.Configuration.java

/**
 * Gets DBMS specific configuration.//from   w  ww.j  a va  2s. co m
 * 
 * @param session connected to the DBMS
 * @return configuration for the DBMS to which the {@link Session} is connected to
 */
@SuppressWarnings("unchecked")
public static synchronized Configuration forDbms(Session session) {
    if (session == null) {
        return defaultConfiguration;
    }
    if (perUrl.containsKey(session.dbUrl)) {
        return perUrl.get(session.dbUrl);
    }
    if (getContext().containsBean("dbms-configuration")) {
        List<Configuration> cs = (List<Configuration>) getContext().getBean("dbms-configuration");
        for (Configuration c : cs) {
            if (Pattern.matches(c.urlPattern, session.dbUrl)) {
                perUrl.put(session.dbUrl, c);
                return c;
            }
        }
    }
    perUrl.put(session.dbUrl, defaultConfiguration);
    return defaultConfiguration;
}