Example usage for java.util.regex Pattern pattern

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

Introduction

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

Prototype

pattern

Source Link

Usage

From source file:com.medallia.spider.api.StRenderer.java

/** @return the template name based on the name of the given class */
protected String getTemplateNameFromClass(Class<?> c) {
    String tn = c.getName();/*w  w  w.  j  ava2s .  c o  m*/

    Pattern p = getClassNamePrefixPattern();
    Matcher m = p.matcher(tn);
    if (!m.matches())
        throw new AssertionError(
                "Default template name expects class name [" + tn + "] to match regex " + p.pattern());

    tn = m.group(1);
    tn = tn.substring(0, 1).toLowerCase() + tn.substring(1);
    return tn;
}

From source file:org.jodconverter.process.AbstractProcessManager.java

@Override
public long findPid(final ProcessQuery query) throws IOException {

    final Pattern commandPattern = Pattern
            .compile(Pattern.quote(query.getCommand()) + ".*" + Pattern.quote(query.getArgument()));
    final Pattern processLinePattern = getRunningProcessLinePattern();
    final String[] currentProcessesCommand = getRunningProcessesCommand(query.getCommand());

    LOGGER.trace(//from w  w w  .  j a v a  2s.  c o  m
            "Finding PID using\n" + "Command to get current running processes: {}\n"
                    + "Regex used to match current running process lines: {}\n"
                    + "Regex used to match running office process we are looking for: {}",
            currentProcessesCommand, processLinePattern.pattern(), // NOSONAR
            commandPattern.pattern());

    final List<String> lines = execute(currentProcessesCommand);
    for (final String line : lines) {
        if (StringUtils.isBlank(line)) {
            // Skip this one
            continue;
        }
        LOGGER.trace("Checking if process line matches the process line regex\nProcess line: {}", line);
        final Matcher lineMatcher = processLinePattern.matcher(line);
        if (lineMatcher.matches()) {
            final String pid = lineMatcher.group("Pid");
            final String commandLine = lineMatcher.group("CommanLine");
            LOGGER.trace(
                    "Line matches!\n" + "pid: {}; Command line: {}\n"
                            + "Checking if this command line matches the office command line regex",
                    pid, commandLine);
            final Matcher commandMatcher = commandPattern.matcher(commandLine);
            if (commandMatcher.find()) {
                LOGGER.debug("Command line matches! Returning pid: {}", pid);
                return Long.parseLong(pid);
            }
        }
    }
    return PID_NOT_FOUND;
}

From source file:net.sf.logsaw.dialect.pattern.APatternDialect.java

@Override
public <T> void validate(IConfigOption<T> option, T value) throws CoreException {
    option.visit(new IConfigOptionVisitor() {
        /* (non-Javadoc)
         * @see net.sf.logsaw.core.config.IConfigOptionVisitor#visit(net.sf.logsaw.core.config.StringConfigOption, java.lang.String)
         *///from   ww w . j a  v  a2 s.  c o  m
        @Override
        public void visit(StringConfigOption opt, String value) throws CoreException {
            if (OPTION_PATTERN.equals(opt)) {
                Assert.isNotNull(value, "externalPattern"); //$NON-NLS-1$
                getLogger().info("Validating conversion pattern " + value); //$NON-NLS-1$

                // Create pattern translator
                IConversionPatternTranslator translator = doCreatePatternTranslator();
                Assert.isNotNull(translator, "patternTranslator"); //$NON-NLS-1$

                // Extract rules from external pattern
                value = translator.prepare(value);
                Assert.isNotNull(value, "externalPattern"); //$NON-NLS-1$
                List<ConversionRule> rules = translator.extractRules(value);
                Assert.isNotNull(rules, "rules"); //$NON-NLS-1$
                if (rules.isEmpty()) {
                    throw new CoreException(new Status(IStatus.ERROR, PatternDialectPlugin.PLUGIN_ID,
                            Messages.APatternDialect_error_invalidPattern));
                }
                for (ConversionRule rule : rules) {
                    // Apply default modifiers
                    translator.applyDefaults(rule, APatternDialect.this);
                    // Rewrite rules
                    translator.rewrite(rule, APatternDialect.this);
                }
                fillFollowedByQuotedString(value, rules);

                // Convert rules to Regex (internal) pattern
                try {
                    Pattern internalPatternFirstLine = Pattern
                            .compile(toRegexPattern(value, translator, rules, true));
                    getLogger().debug("Internal Pattern (first line): " + internalPatternFirstLine.pattern()); //$NON-NLS-1$
                    Pattern internalPatternFull = Pattern
                            .compile(toRegexPattern(value, translator, rules, false));
                    getLogger().debug("Internal Pattern (full): " + internalPatternFull.pattern()); //$NON-NLS-1$
                } catch (PatternSyntaxException e) {
                    throw new CoreException(new Status(IStatus.ERROR, PatternDialectPlugin.PLUGIN_ID,
                            NLS.bind(Messages.APatternDialect_error_failedToTranslateToRegex, value)));
                }
            }
        }
    }, value);
    super.validate(option, value);
}

From source file:net.sf.logsaw.dialect.pattern.APatternDialect.java

@Override
public <T> void configure(IConfigOption<T> option, T value) throws CoreException {
    option.visit(new IConfigOptionVisitor() {
        /* (non-Javadoc)
         * @see net.sf.logsaw.core.config.IConfigOptionVisitor#visit(net.sf.logsaw.core.config.StringConfigOption, java.lang.String)
         *//*  w  ww  .j a  va  2s.c om*/
        @Override
        public void visit(StringConfigOption opt, String value) throws CoreException {
            if (OPTION_TIMESTAMP_PATTERN.equals(opt)) {
                Assert.isNotNull(value, "timestampPattern"); //$NON-NLS-1$
                timestampPattern = value;
            } else if (OPTION_PATTERN.equals(opt)) {
                Assert.isNotNull(value, "externalPattern"); //$NON-NLS-1$
                getLogger().info("Configuring conversion pattern " + value); //$NON-NLS-1$

                // Create pattern translator
                IConversionPatternTranslator translator = doCreatePatternTranslator();
                Assert.isNotNull(translator, "patternTranslator"); //$NON-NLS-1$
                setPatternTranslator(translator);

                // Extract rules from external pattern
                value = translator.prepare(value);
                Assert.isNotNull(value, "externalPattern"); //$NON-NLS-1$
                List<ConversionRule> rules = translator.extractRules(value);
                Assert.isNotNull(rules, "rules"); //$NON-NLS-1$
                if (rules.isEmpty()) {
                    throw new CoreException(new Status(IStatus.ERROR, PatternDialectPlugin.PLUGIN_ID,
                            Messages.APatternDialect_error_invalidPattern));
                }
                for (ConversionRule rule : rules) {
                    // Apply default modifiers
                    translator.applyDefaults(rule, APatternDialect.this);
                    // Rewrite rules
                    translator.rewrite(rule, APatternDialect.this);
                }
                fillFollowedByQuotedString(value, rules);
                setRules(rules);

                // Convert rules to Regex (internal) pattern
                try {
                    Pattern internalPatternFirstLine = Pattern
                            .compile(toRegexPattern(value, translator, rules, true));
                    getLogger().debug("Internal Pattern (first line): " + internalPatternFirstLine.pattern()); //$NON-NLS-1$
                    setInternalPatternFirstLine(internalPatternFirstLine);
                    Pattern internalPatternFull = Pattern
                            .compile(toRegexPattern(value, translator, rules, false));
                    getLogger().debug("Internal Pattern (full): " + internalPatternFull.pattern()); //$NON-NLS-1$
                    setInternalPatternFull(internalPatternFull);
                } catch (PatternSyntaxException e) {
                    throw new CoreException(new Status(IStatus.ERROR, PatternDialectPlugin.PLUGIN_ID,
                            NLS.bind(Messages.APatternDialect_error_failedToTranslateToRegex, value)));
                }

                // Setup field provider
                List<ALogEntryField<?, ?>> fields = extractFields(rules);
                ILogFieldProvider innerProvider = doCreateFieldProvider();
                Assert.isNotNull(innerProvider, "fieldProvider"); //$NON-NLS-1$
                setFieldProvider(new FilteringFieldProvider(innerProvider, fields));
            }
        }
    }, value);
    super.configure(option, value);
}

From source file:rapture.plugin.install.PluginSandbox.java

private boolean shouldInclude(RaptureURI uri) {
    if (!ignorePatterns.isEmpty()) {
        for (Pattern pattern : ignorePatterns) {
            if (pattern.matcher(uri.toString()).matches()) {
                warn("Ignoring " + uri.toString() + " because it matches pattern " + pattern.pattern());
                return false;
            }/*from w  w w.  ja  va2s  . co  m*/
        }
    }
    return true;
}

From source file:de.undercouch.bson4jackson.BsonGeneratorTest.java

@Test
public void patterns() throws Exception {
    Pattern pattern = Pattern.compile("a.*a", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    Map<String, Object> data = new LinkedHashMap<String, Object>();
    data.put("pattern", pattern);

    BSONObject obj = generateAndParse(data);

    Pattern result = (Pattern) obj.get("pattern");
    assertNotNull(result);//from   w ww .j  ava 2s.c o  m
    assertEquals(pattern.pattern(), result.pattern());
    assertEquals(pattern.flags(), result.flags());
}

From source file:com.adobe.acs.commons.workflow.bulk.removal.impl.WorkflowInstanceRemoverImpl.java

/**
 * {@inheritDoc}//from   w w  w. ja  v  a2 s  .c  o m
 */
@SuppressWarnings({ "squid:S3776", "squid:S1141" })
public int removeWorkflowInstances(final ResourceResolver resourceResolver, final Collection<String> modelIds,
        final Collection<String> statuses, final Collection<Pattern> payloads, final Calendar olderThan,
        final int batchSize, final int maxDurationInMins) throws PersistenceException, WorkflowRemovalException,
        InterruptedException, WorkflowRemovalForceQuitException {

    final long start = System.currentTimeMillis();
    long end = -1;

    int count = 0;
    int checkedCount = 0;
    int workflowRemovedCount = 0;

    if (maxDurationInMins > 0) {
        // Max duration has been requested (greater than 0)

        // Convert minutes to milliseconds
        long maxDurationInMs = maxDurationInMins * MS_IN_ONE_MINUTE;

        // Compute the end time
        end = start + maxDurationInMs;
    }

    try {
        this.start(resourceResolver);

        final List<Resource> containerFolders = this.getWorkflowInstanceFolders(resourceResolver);

        for (Resource containerFolder : containerFolders) {
            log.debug("Checking [ {} ] for workflow instances to remove", containerFolder.getPath());

            final Collection<Resource> sortedFolders = this.getSortedAndFilteredFolders(containerFolder);

            for (final Resource folder : sortedFolders) {

                int remaining = 0;

                for (final Resource instance : folder.getChildren()) {

                    if (this.forceQuit.get()) {
                        throw new WorkflowRemovalForceQuitException();
                    } else if (end > 0 && System.currentTimeMillis() >= end) {
                        throw new WorkflowRemovalMaxDurationExceededException();
                    }

                    final ValueMap properties = instance.getValueMap();

                    if (!StringUtils.equals(NT_CQ_WORKFLOW,
                            properties.get(JcrConstants.JCR_PRIMARYTYPE, String.class))) {

                        // Only process cq:Workflow's
                        remaining++;
                        continue;
                    }

                    checkedCount++;

                    final String instanceStatus = getStatus(instance);
                    final String model = properties.get(PN_MODEL_ID, String.class);
                    final Calendar startTime = properties.get(PN_STARTED_AT, Calendar.class);
                    final String payload = properties.get(PAYLOAD_PATH, String.class);

                    if (StringUtils.isBlank(payload)) {
                        log.warn("Unable to find payload for Workflow instance [ {} ]", instance.getPath());
                        remaining++;
                        continue;
                    } else if (CollectionUtils.isNotEmpty(statuses) && !statuses.contains(instanceStatus)) {
                        log.trace("Workflow instance [ {} ] has non-matching status of [ {} ]",
                                instance.getPath(), instanceStatus);
                        remaining++;
                        continue;
                    } else if (CollectionUtils.isNotEmpty(modelIds) && !modelIds.contains(model)) {
                        log.trace("Workflow instance [ {} ] has non-matching model of [ {} ]",
                                instance.getPath(), model);
                        remaining++;
                        continue;
                    } else if (olderThan != null && startTime != null && startTime.before(olderThan)) {
                        log.trace("Workflow instance [ {} ] has non-matching start time of [ {} ]",
                                instance.getPath(), startTime);
                        remaining++;
                        continue;
                    } else {

                        if (CollectionUtils.isNotEmpty(payloads)) {
                            // Only evaluate payload patterns if they are provided

                            boolean match = false;

                            if (StringUtils.isNotEmpty(payload)) {
                                for (final Pattern pattern : payloads) {
                                    if (payload.matches(pattern.pattern())) {
                                        // payload matches a pattern
                                        match = true;
                                        break;
                                    }
                                }

                                if (!match) {
                                    // Not a match; skip to next workflow instance
                                    log.trace("Workflow instance [ {} ] has non-matching payload path [ {} ]",
                                            instance.getPath(), payload);
                                    remaining++;
                                    continue;
                                }
                            }
                        }

                        // Only remove matching

                        try {
                            instance.adaptTo(Node.class).remove();
                            log.debug("Removed workflow instance at [ {} ]", instance.getPath());

                            workflowRemovedCount++;
                            count++;
                        } catch (RepositoryException e) {
                            log.error("Could not remove workflow instance at [ {} ]. Continuing...",
                                    instance.getPath(), e);
                        }

                        if (count % batchSize == 0) {
                            this.batchComplete(resourceResolver, checkedCount, workflowRemovedCount);

                            log.info("Removed a running total of [ {} ] workflow instances", count);
                        }
                    }
                }

                if (remaining == 0 && isWorkflowDatedFolder(folder) && !StringUtils.startsWith(folder.getName(),
                        new SimpleDateFormat(WORKFLOW_FOLDER_FORMAT).format(new Date()))) {
                    // Dont remove folders w items and dont remove any of "today's" folders
                    // MUST match the YYYY-MM-DD(.*) pattern; do not try to remove root folders
                    try {
                        folder.adaptTo(Node.class).remove();
                        log.debug("Removed empty workflow folder node [ {} ]", folder.getPath());
                        // Incrementing only count to trigger batch save and not total since is not a WF
                        count++;
                    } catch (RepositoryException e) {
                        log.error("Could not remove workflow folder at [ {} ]", folder.getPath(), e);
                    }
                }
            }

            // Save final batch if needed, and update tracking nodes
            this.complete(resourceResolver, checkedCount, workflowRemovedCount);
        }

    } catch (PersistenceException e) {
        this.forceQuit.set(false);
        log.error("Error persisting changes with Workflow Removal", e);
        this.error();
        throw e;
    } catch (WorkflowRemovalException e) {
        this.forceQuit.set(false);
        log.error("Error with Workflow Removal", e);
        this.error();
        throw e;
    } catch (InterruptedException e) {
        this.forceQuit.set(false);
        log.error("Errors in persistence retries during Workflow Removal", e);
        this.error();
        throw e;
    } catch (WorkflowRemovalForceQuitException e) {
        this.forceQuit.set(false);
        // Uncommon instance of using Exception to control flow; Force quitting is an extreme condition.
        log.warn("Workflow removal was force quit. The removal state is unknown.");
        this.internalForceQuit();
        throw e;
    } catch (WorkflowRemovalMaxDurationExceededException e) {
        // Uncommon instance of using Exception to control flow; Exceeding max duration extreme condition.
        log.warn("Workflow removal exceeded max duration of [ {} ] minutes. Final removal commit initiating...",
                maxDurationInMins);
        this.complete(resourceResolver, checkedCount, count);
    }

    if (log.isInfoEnabled()) {
        log.info(
                "Workflow Removal Process Finished! "
                        + "Removed a total of [ {} ] workflow instances in [ {} ] ms",
                count, System.currentTimeMillis() - start);
    }

    return count;
}

From source file:synapticloop.copyrightr.Parser.java

private void parseFile(File file) throws CopyrightrException {
    statistics.incrementNumFiles();//from w  w  w  .j  a  va 2  s . c o m

    boolean fileMatch = false;
    logger.info(String.format("Searching for copyright notice in file '%s'", file.getPath()));
    try {
        List<String> readLines = FileUtils.readLines(file);
        int i = 0;
        for (String line : readLines) {
            for (Pattern pattern : compiledPatterns) {
                // if we have found a line in the file and we already only want to 
                // replace the first one, then break here
                if (onlyReplaceFirst && fileMatch) {
                    break;
                }
                Matcher matcher = pattern.matcher(line);

                if (matcher.matches()) {
                    logger.debug(String.format("Found a match with pattern '%s' for line '%s'",
                            pattern.pattern(), line));

                    fileMatch = true;
                    int groupCount = matcher.groupCount();

                    String group = matcher.group(groupCount);
                    int regionStart = matcher.start(groupCount);
                    int regionEnd = matcher.end(groupCount);

                    boolean overwrite = false;
                    switch (groupCount) {
                    case 2:
                        // we have a date with a '-' in it, we will replace the last group
                        overwrite = true;
                        break;
                    case 1:
                        // we have a date with no '-' in it - we are going to add one in...
                    default:
                        break;
                    }

                    readLines.set(i, getReplacementLine(line, group, regionStart, regionEnd, overwrite));
                    statistics.incrementNumFound();
                    break;
                }
            }
            i++;
        }

        if (fileMatch) {
            if (!dryRun) {
                FileUtils.writeLines(file, readLines, false);
            }
        } else {
            statistics.incrementNumMissing();
            logger.warn(String.format("Could not find copyright in file '%s'.", file.getName()));
        }

    } catch (IOException ex) {
        throw new CopyrightrException(
                String.format("Could not update copyright for file '%s', message was '%s'", file.getPath(),
                        ex.getMessage()),
                ex);
    }
}

From source file:br.com.blackhubos.eventozero.util.Framework.java

public static String fixSpaces(String literal) {
    literal = literal.trim();// www . ja v a2s  . co  m
    final Pattern pattern = Pattern.compile("\\s{2}");
    final Matcher matcher = pattern.matcher(literal);
    while (matcher.find()) {
        literal = literal.replaceAll(pattern.pattern(), " ");
    }

    return literal;
}

From source file:org.apache.maven.plugin.javadoc.JavadocUtil.java

/**
 * Parse the output for 'javadoc -J-version' and return the javadoc version recognized.
 * <br/>//from  www.  j a  v  a 2  s  .c  om
 * Here are some output for 'javadoc -J-version' depending the JDK used:
 * <table>
 * <tr>
 *   <th>JDK</th>
 *   <th>Output for 'javadoc -J-version'</th>
 * </tr>
 * <tr>
 *   <td>Sun 1.4</td>
 *   <td>java full version "1.4.2_12-b03"</td>
 * </tr>
 * <tr>
 *   <td>Sun 1.5</td>
 *   <td>java full version "1.5.0_07-164"</td>
 * </tr>
 * <tr>
 *   <td>IBM 1.4</td>
 *   <td>javadoc full version "J2RE 1.4.2 IBM Windows 32 build cn1420-20040626"</td>
 * </tr>
 * <tr>
 *   <td>IBM 1.5 (French JVM)</td>
 *   <td>javadoc version complte de "J2RE 1.5.0 IBM Windows 32 build pwi32pdev-20070426a"</td>
 * </tr>
 * <tr>
 *   <td>FreeBSD 1.5</td>
 *   <td>java full version "diablo-1.5.0-b01"</td>
 * </tr>
 * <tr>
 *   <td>BEA jrockit 1.5</td>
 *   <td>java full version "1.5.0_11-b03"</td>
 * </tr>
 * </table>
 *
 * @param output for 'javadoc -J-version'
 * @return the version of the javadoc for the output.
 * @throws PatternSyntaxException if the output doesn't match with the output pattern
 * <tt>(?s).*?([0-9]+\\.[0-9]+)(\\.([0-9]+))?.*</tt>.
 * @throws IllegalArgumentException if the output is null
 */
protected static float parseJavadocVersion(String output) throws IllegalArgumentException {
    if (StringUtils.isEmpty(output)) {
        throw new IllegalArgumentException("The output could not be null.");
    }

    Pattern pattern = Pattern.compile("(?s).*?([0-9]+\\.[0-9]+)(\\.([0-9]+))?.*");

    Matcher matcher = pattern.matcher(output);
    if (!matcher.matches()) {
        throw new PatternSyntaxException("Unrecognized version of Javadoc: '" + output + "'", pattern.pattern(),
                pattern.toString().length() - 1);
    }

    String version = matcher.group(3);
    if (version == null) {
        version = matcher.group(1);
    } else {
        version = matcher.group(1) + version;
    }

    return Float.parseFloat(version);
}