Example usage for java.util.regex PatternSyntaxException getDescription

List of usage examples for java.util.regex PatternSyntaxException getDescription

Introduction

In this page you can find the example usage for java.util.regex PatternSyntaxException getDescription.

Prototype

public String getDescription() 

Source Link

Document

Retrieves the description of the error.

Usage

From source file:Main.java

public static void main(String[] args) {
    Pattern pattern = null;//from w w  w  . ja  va2 s.co m
    Matcher matcher = null;

    Console console = System.console();
    while (true) {
        try {
            pattern = Pattern.compile(console.readLine("%nEnter your regex: "));

            matcher = pattern.matcher(console.readLine("Enter input string to search: "));
        } catch (PatternSyntaxException pse) {
            console.format("There is a problem with the regular expression!%n");
            console.format("The pattern in question is: %s%n", pse.getPattern());
            console.format("The description is: %s%n", pse.getDescription());
            console.format("The message is: %s%n", pse.getMessage());
            console.format("The index is: %s%n", pse.getIndex());
            System.exit(0);
        }
        boolean found = false;
        while (matcher.find()) {
            console.format("I found the text \"%s\" starting at " + "index %d and ending at index %d.%n",
                    matcher.group(), matcher.start(), matcher.end());
            found = true;
        }
        if (!found) {
            console.format("No match found.%n");
        }
    }
}

From source file:Correct.java

public static void execute(String One, String Two) {

    Two = Two.replaceAll("\\\\n", "\n");
    try {//w  w  w  .ja  v a 2  s .  com
        System.out.println("Regex = " + One);
        System.out.println("Input = " + Two);

        Pattern pattern = Pattern.compile(One);
        Matcher match = pattern.matcher(Two);

        while (match.find()) {
            System.out.println("Found [" + match.group() + "]\nStarting at " + match.start() + " , \nEnding at "
                    + (match.end() - 1));
        }
    } catch (PatternSyntaxException pse) {

        System.err.println("Bad regex: " + pse.getMessage());
        System.err.println("Description: " + pse.getDescription());
        System.err.println("Index: " + pse.getIndex());
        System.err.println("Incorrect pattern: " + pse.getPattern());
    }
}

From source file:RegexTestHarness2.java

private static void initResources() {
    try {//from w w w  .  j av a2  s. c o  m
        br = new BufferedReader(new FileReader("regex.txt"));
    } catch (FileNotFoundException fnfe) {
        System.out.println("Cannot locate input file! " + fnfe.getMessage());
        System.exit(0);
    }
    try {
        REGEX = br.readLine();
        INPUT = br.readLine();
    } catch (IOException ioe) {
    }

    try {
        pattern = Pattern.compile(REGEX);
        matcher = pattern.matcher(INPUT);
    } catch (PatternSyntaxException pse) {
        System.out.println("There is a problem with the regular expression!");
        System.out.println("The pattern in question is: " + pse.getPattern());
        System.out.println("The description is: " + pse.getDescription());
        System.out.println("The message is: " + pse.getMessage());
        System.out.println("The index is: " + pse.getIndex());
        System.exit(0);
    }

    System.out.println("Current REGEX is: " + REGEX);
    System.out.println("Current INPUT is: " + INPUT);
}

From source file:hudson.plugins.validating_string_parameter.ValidatingStringParameterValidator.java

/**
* Check the regular expression entered by the user
* 
*   * @param value//from w w  w.  j av  a2 s. c  om
*            the regex
* @return false when regex is malformed, true otherwise
*/
public FormValidation doCheckRegex(final String value) {
    FormValidation validation = FormValidation.ok();
    if (StringUtils.isNotBlank(value)) {
        try {
            Pattern.compile(value);
        } catch (PatternSyntaxException pse) {
            validation = FormValidation.error("Invalid regular expression: " + pse.getDescription());
            //FormValidation.error(e, e.getLocalizedMessage());
        }
    }

    return validation;
}

From source file:hudson.plugins.validating_string_parameter.ValidatingStringParameterValidator.java

/**
 * Called to validate the passed user entered value against the configured regular expression.
 *//*  w  w  w .j av a  2  s.c  o  m*/
public FormValidation doValidate(String regex, final String failedValidationMessage, final String value) {

    FormValidation validation = FormValidation.ok();

    if (StringUtils.isNotBlank(value)) {
        if (value.contains("$")) {
            // since this is used to disable projects, be conservative
            //            LOGGER.fine("Location could be expanded on build '" + build
            //                  + "' parameters values:");
        } else {
            if (!Pattern.matches(regex, value)) {
                try {
                    return failedValidationMessage == null || "".equals(failedValidationMessage)
                            ? FormValidation.error("Value entered does not match regular expression: " + regex)
                            : FormValidation.error(failedValidationMessage);

                } catch (PatternSyntaxException pse) {
                    validation = FormValidation
                            .error("Invalid regular expression [" + regex + "]: " + pse.getDescription());
                }
            }
            //   validation = FormValidation.error(Messages
            //      .SiteMonitor_Error_PrefixOfURL());

        }
    }

    return validation;
}

From source file:com.marvelution.hudson.plugins.apiv2.APIv2Plugin.java

/**
 * Web Method to validate a given {@link Pattern}
 * //ww w. j  a  va2 s  .  c  om
 * @param value the {@link Pattern} to validate
 * @return validation result
 * @throws IOException in case of errors
 * @throws ServletException in case of errors
 */
public FormValidation doCheckPattern(@QueryParameter final String value) throws IOException, ServletException {
    if (!Hudson.getInstance().hasPermission(Hudson.ADMINISTER) || StringUtils.isBlank(value)) {
        return FormValidation.ok();
    }
    try {
        Pattern.compile(value);
        return FormValidation.ok();
    } catch (PatternSyntaxException e) {
        StringBuilder builder = new StringBuilder(e.getDescription());
        if (e.getIndex() >= 0) {
            builder.append(" near index ").append(e.getIndex());
        }
        builder.append("<pre>");
        builder.append(e.getPattern()).append(System.getProperty("line.separator"));
        if (e.getIndex() >= 0) {
            for (int i = 0; i < e.getIndex(); ++i) {
                builder.append(' ');
            }
            builder.append('^');
        }
        builder.append("</pre>");
        return FormValidation.errorWithMarkup(builder.toString());
    }
}

From source file:net.sourceforge.vulcan.core.support.AbstractProjectDomBuilder.java

private void linkifyCommitMessage(Element changeSet, ChangeSetDto changes, String projectName) {
    final CommitLogParser commitLogParser = new CommitLogParser();

    try {/*from w  ww .  j av a 2 s  .c  o  m*/
        final ProjectConfigDto projectConfig = projectManager.getProjectConfig(projectName);

        commitLogParser.setKeywordPattern(projectConfig.getBugtraqLogRegex1());
        commitLogParser.setIdPattern(projectConfig.getBugtraqLogRegex2());
    } catch (NoSuchProjectException ignore) {
    }

    try {
        commitLogParser.parse(changes.getMessage());

        changeSet.addContent(commitLogParser.getMessageNode());
    } catch (PatternSyntaxException e) {
        eventHandler.reportEvent(new ErrorEvent(this, "errors.bugtraq.regex",
                new Object[] { e.getPattern(), e.getDescription(), e.getIndex() }, e));

        final Element message = new Element("message");
        message.setText(changes.getMessage());
        changeSet.addContent(message);
    }
}

From source file:net.sourceforge.vulcan.web.struts.forms.ProjectConfigForm.java

private void validateRegex(ActionErrors errors, String regex, String propertyName) {
    if (isNotBlank(regex)) {
        try {/*from  w  w w .  j  a  v  a 2 s .c o m*/
            Pattern.compile(regex);
        } catch (PatternSyntaxException e) {
            errors.add(propertyName, new ActionMessage("errors.regex", e.getDescription(), e.getIndex()));
        }
    }

}

From source file:org.apache.jmeter.report.dashboard.HtmlTemplateExporter.java

@Override
public void export(SampleContext context, File file, ReportGeneratorConfiguration configuration)
        throws ExportException {
    Validate.notNull(context, MUST_NOT_BE_NULL, "context");
    Validate.notNull(file, MUST_NOT_BE_NULL, "file");
    Validate.notNull(configuration, MUST_NOT_BE_NULL, "configuration");

    LOG.debug("Start template processing");

    // Create data context and populate it
    DataContext dataContext = new DataContext();

    // Get the configuration of the current exporter
    final ExporterConfiguration exportCfg = configuration.getExportConfigurations().get(getName());

    // Get template directory property value
    File templateDirectory = getPropertyFromConfig(exportCfg, TEMPLATE_DIR,
            new File(JMeterUtils.getJMeterBinDir(), TEMPLATE_DIR_NAME_DEFAULT), File.class);
    if (!templateDirectory.isDirectory()) {
        String message = String.format(INVALID_TEMPLATE_DIRECTORY_FMT, templateDirectory.getAbsolutePath());
        LOG.error(message);/*  ww w  . j  av a 2s.c om*/
        throw new ExportException(message);
    }

    // Get output directory property value
    File outputDir = getPropertyFromConfig(exportCfg, OUTPUT_DIR,
            new File(JMeterUtils.getJMeterBinDir(), OUTPUT_DIR_NAME_DEFAULT), File.class);
    String globallyDefinedOutputDir = JMeterUtils.getProperty(JMeter.JMETER_REPORT_OUTPUT_DIR_PROPERTY);
    if (!StringUtils.isEmpty(globallyDefinedOutputDir)) {
        outputDir = new File(globallyDefinedOutputDir);
    }

    JOrphanUtils.canSafelyWriteToFolder(outputDir);

    LOG.info("Will generate dashboard in folder:" + outputDir.getAbsolutePath());

    // Add the flag defining whether only sample series are filtered to the
    // context
    final boolean filtersOnlySampleSeries = exportCfg.filtersOnlySampleSeries();
    addToContext(DATA_CTX_FILTERS_ONLY_SAMPLE_SERIES, Boolean.valueOf(filtersOnlySampleSeries), dataContext);

    // Add the series filter to the context
    final String seriesFilter = exportCfg.getSeriesFilter();
    Pattern filterPattern = null;
    if (StringUtils.isNotBlank(seriesFilter)) {
        try {
            filterPattern = Pattern.compile(seriesFilter);
        } catch (PatternSyntaxException ex) {
            LOG.error(String.format("Invalid series filter: \"%s\", %s", seriesFilter, ex.getDescription()));
        }
    }
    addToContext(DATA_CTX_SERIES_FILTER, seriesFilter, dataContext);

    // Add the flag defining whether only controller series are displayed
    final boolean showControllerSeriesOnly = exportCfg.showControllerSeriesOnly();
    addToContext(DATA_CTX_SHOW_CONTROLLERS_ONLY, Boolean.valueOf(showControllerSeriesOnly), dataContext);

    JsonizerVisitor jsonizer = new JsonizerVisitor();
    Map<String, Object> storedData = context.getData();

    // Add begin date consumer result to the data context
    addResultToContext(ReportGenerator.BEGIN_DATE_CONSUMER_NAME, storedData, dataContext, jsonizer);

    // Add end date summary consumer result to the data context
    addResultToContext(ReportGenerator.END_DATE_CONSUMER_NAME, storedData, dataContext, jsonizer);

    // Add Apdex summary consumer result to the data context
    addResultToContext(ReportGenerator.APDEX_SUMMARY_CONSUMER_NAME, storedData, dataContext, jsonizer);

    // Add errors summary consumer result to the data context
    addResultToContext(ReportGenerator.ERRORS_SUMMARY_CONSUMER_NAME, storedData, dataContext, jsonizer);

    // Add requests summary consumer result to the data context
    addResultToContext(ReportGenerator.REQUESTS_SUMMARY_CONSUMER_NAME, storedData, dataContext, jsonizer);

    // Add statistics summary consumer result to the data context
    addResultToContext(ReportGenerator.STATISTICS_SUMMARY_CONSUMER_NAME, storedData, dataContext, jsonizer);

    // Collect graph results from sample context and transform them into
    // Json strings to inject in the data context
    ExtraOptionsResultCustomizer customizer = new ExtraOptionsResultCustomizer();
    EmptyGraphChecker checker = new EmptyGraphChecker(filtersOnlySampleSeries, showControllerSeriesOnly,
            filterPattern);
    for (Map.Entry<String, GraphConfiguration> graphEntry : configuration.getGraphConfigurations().entrySet()) {
        final String graphId = graphEntry.getKey();
        final GraphConfiguration graphConfiguration = graphEntry.getValue();
        final SubConfiguration extraOptions = exportCfg.getGraphExtraConfigurations().get(graphId);

        // Initialize customizer and checker
        customizer.setExtraOptions(extraOptions);
        checker.setExcludesControllers(graphConfiguration.excludesControllers());
        checker.setGraphId(graphId);

        // Export graph data
        addResultToContext(graphId, storedData, dataContext, jsonizer, customizer, checker);
    }

    // Replace the begin date with its formatted string and store the old
    // timestamp
    long oldTimestamp = formatTimestamp(ReportGenerator.BEGIN_DATE_CONSUMER_NAME, dataContext);

    // Replace the end date with its formatted string
    formatTimestamp(ReportGenerator.END_DATE_CONSUMER_NAME, dataContext);

    // Add time zone offset (that matches the begin date) to the context
    TimeZone timezone = TimeZone.getDefault();
    addToContext(DATA_CTX_TIMEZONE_OFFSET, Integer.valueOf(timezone.getOffset(oldTimestamp)), dataContext);

    // Add report title to the context
    if (!StringUtils.isEmpty(configuration.getReportTitle())) {
        dataContext.put(DATA_CTX_REPORT_TITLE, StringEscapeUtils.escapeHtml4(configuration.getReportTitle()));
    }

    // Add the test file name to the context
    addToContext(DATA_CTX_TESTFILE, file.getName(), dataContext);

    // Add the overall filter property to the context
    addToContext(DATA_CTX_OVERALL_FILTER, configuration.getSampleFilter(), dataContext);

    // Walk template directory to copy files and process templated ones
    Configuration templateCfg = new Configuration(Configuration.getVersion());
    try {
        templateCfg.setDirectoryForTemplateLoading(templateDirectory);
        templateCfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        LOG.info("Report will be generated in:" + outputDir.getAbsolutePath() + ", creating folder structure");
        FileUtils.forceMkdir(outputDir);
        TemplateVisitor visitor = new TemplateVisitor(templateDirectory.toPath(), outputDir.toPath(),
                templateCfg, dataContext);
        Files.walkFileTree(templateDirectory.toPath(), visitor);
    } catch (IOException ex) {
        throw new ExportException("Unable to process template files.", ex);
    }

    LOG.debug("End of template processing");

}

From source file:org.bitbucket.mlopatkin.android.logviewer.search.SearchStrategyFactory.java

public static String describeError(String request) {
    try {//from   w  ww  .j  a  va 2s  .com
        isSearchRequestValid(request, false);
        return "OK";
    } catch (PatternSyntaxException e) {
        return e.getDescription();
    }
}