Example usage for java.util.regex PatternSyntaxException getMessage

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

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns a multi-line string containing the description of the syntax error and its index, the erroneous regular-expression pattern, and a visual indication of the error index within the pattern.

Usage

From source file:net.triptech.metahive.CalculationParser.java

/**
 * Marks up the calculation.//  w ww .j a va2 s .  c o  m
 *
 * @param calculation the calculation
 * @return the string
 */
public static String maredUpCalculation(String calculation) {

    String markedUpCalculation = "";

    logger.debug("Calculation: " + calculation);

    if (StringUtils.isNotBlank(calculation)) {
        try {
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(calculation);
            StringBuffer sb = new StringBuffer();
            logger.debug("Regular expression: " + regEx);
            while (m.find()) {
                logger.info("Variable instance found: " + m.group());
                try {
                    String text = "<span class=\"variable\">" + m.group().toUpperCase() + "</span>";

                    m.appendReplacement(sb, Matcher.quoteReplacement(text));

                } catch (NumberFormatException nfe) {
                    logger.error("Error parsing variable id");
                }
            }
            m.appendTail(sb);

            markedUpCalculation = sb.toString();
            logger.info("Marked up calculation: " + markedUpCalculation);

        } catch (PatternSyntaxException pe) {
            logger.error("Regex syntax error ('" + pe.getPattern() + "') " + pe.getMessage());
        }
    }
    return markedUpCalculation;
}

From source file:net.triptech.metahive.CalculationParser.java

/**
 * Parses the calculation to identify what variables are referenced in it.
 *
 * @param calculation the calculation/*from w  w  w .  j a va 2s  . c  o  m*/
 * @return the list
 */
public static Set<Long> parseVariableIds(final String calculation) {

    Set<Long> variableIds = new TreeSet<Long>();

    logger.debug("Calculation: " + calculation);

    if (StringUtils.isNotBlank(calculation)) {
        try {
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(calculation);
            logger.debug("Regular expression: " + regEx);
            while (m.find()) {
                logger.info("Variable instance found: " + m.group());
                try {
                    Long id = Long.parseLong(StringUtils.substring(m.group(), 1));
                    logger.debug("Variable id: " + id);
                    variableIds.add(id);
                } catch (NumberFormatException nfe) {
                    logger.error("Error parsing variable id");
                }
            }
        } catch (PatternSyntaxException pe) {
            logger.error("Regex syntax error ('" + pe.getPattern() + "') " + pe.getMessage());
        }
    }

    logger.info(variableIds.size() + " ids found");

    return variableIds;
}

From source file:nl.toolforge.karma.core.cmd.impl.CreateModuleCommand.java

/**
 * Physical creation of a module in a version control system.
 *//*  www. j av  a2 s. co  m*/
public void execute() throws CommandException {

    CommandLine commandLine = getCommandLine();

    String locationAlias = commandLine.getOptionValue("l");
    String moduleName = commandLine.getOptionValue("m");
    String comment = commandLine.getOptionValue("c");

    // Part 1 of the transaction is the creation of a Module instance.
    //

    // todo this bit sucks. Since renamed to ModuleDigester, it doesn't make sense anymore.
    ModuleDigester digester = null;
    try {
        digester = new ModuleDigester(moduleName, locationAlias);
    } catch (PatternSyntaxException e) {
        throw new CommandException(CommandException.INVALID_ARGUMENT,
                new Object[] { moduleName, e.getMessage() });
    }

    Module.Type moduleType = new Module.Type();
    try {
        moduleType.setType(commandLine.getOptionValue("t"));
    } catch (IllegalArgumentException e1) {
        throw new CommandException(CommandException.INVALID_ARGUMENT);
    }

    Module module = null;
    try {
        ModuleFactory factory = new ModuleFactory(getWorkingContext());
        module = factory.create(digester, moduleType);
    } catch (LocationException e) {
        throw new CommandException(e.getErrorCode(), e.getMessageArguments());
    }

    SimpleMessage message = new SimpleMessage(getFrontendMessages().getString("message.CREATE_MODULE_STARTED"),
            new Object[] { moduleName, locationAlias });
    commandResponse.addEvent(new MessageEvent(this, message));

    try {

        AuthenticatorKey key = new AuthenticatorKey(getWorkingContext().getName(),
                module.getLocation().getId());
        module.createRemote(Authenticators.getAuthenticator(key), comment);

        // Ensure that only this message is passed back to the client
        //
        message = new SimpleMessage(getFrontendMessages().getString("message.CREATE_MODULE_SUCCESSFULL"),
                new Object[] { moduleName, locationAlias });
        commandResponse.addEvent(new MessageEvent(this, message));

    } catch (VersionControlException e) {
        logger.error(e);
        throw new CommandException(e.getErrorCode(), e.getMessageArguments());
    } catch (AuthenticationException e) {
        logger.error(e);
        throw new CommandException(e.getErrorCode(), e.getMessageArguments());
    }
}

From source file:org.adeptnet.atlassian.common.Common.java

private void initSkip401(final Map<String, String> params) {
    if (!params.containsKey(KRB5_SKIP401)) {
        return;//ww  w.j av  a  2s .  c om
    }
    final String[] skips = params.get(KRB5_SKIP401).split("\n");
    for (final String _skip : skips) {
        final String skip = _skip.trim();
        if (skip.isEmpty()) {
            continue;
        }
        try {
            final Pattern pattern = Pattern.compile(skip);
            patterns.add(pattern);
        } catch (PatternSyntaxException ex) {
            LOG.error(String.format("skip401: %s - %s", skip, ex.getMessage()), ex);
        }
    }
}

From source file:org.ajax4jsf.webapp.ConfigurableXMLFilter.java

/**
 * @param servletContext/*from   ww w  .ja v a2 s. c o  m*/
 * @param parsersParameter
 * @throws ServletException
 */
public void configureParsers(ServletContext servletContext, String parsersParameter) throws ServletException {
    String[] parsersNames = parsersParameter.split("\\s*,\\s*");
    for (int i = parsersNames.length - 1; i >= 0; i--) {
        String parserName = parsersNames[i];
        ParserConfig parserConfig;
        if (TIDY.equals(parserName)) {
            parserConfig = new TidyParserConfig();
        } else if (NEKO.equals(parserName)) {
            parserConfig = new NekoParserConfig();
        } else if (NONE.equals(parserName)) {
            parserConfig = new PassParserConfig();
        } else {
            throw new ServletException("Unknown XML parser type in config parameter " + parserName);
        }
        parserConfig.setNext(parsers);
        if (null != servletContext) {
            try {
                String parserViewPattern = servletContext
                        .getInitParameter(VIEW_ID_PATTERN_PARAMETER + parserName);
                parserConfig.setPatterns(parserViewPattern);

            } catch (PatternSyntaxException e) {
                throw new ServletException(
                        "Invalid pattern for a parser " + parserName + " :" + e.getMessage());
            }
        }
        parsers = parserConfig;
    }
}

From source file:org.alfresco.web.bean.wcm.FormWorkflowDialog.java

/**
 * @see org.alfresco.web.bean.dialog.BaseDialogBean#finishImpl(javax.faces.context.FacesContext, java.lang.String)
 *//*from w  ww .ja v a 2s .c  om*/
@Override
protected String finishImpl(FacesContext context, String outcome) throws Exception {
    if (this.workflowNode != null) {
        // push serialized params back into workflow object
        WorkflowConfiguration wf = getActionWorkflow();
        Map<QName, Serializable> taskParams = WorkflowUtil.prepareTaskParams(this.workflowNode);
        if (wf.getParams() == null) {
            wf.setParams(taskParams);
        } else {
            // merge existing with params - as only new items are returned from the editor
            Map<QName, Serializable> params = wf.getParams();
            for (QName qname : taskParams.keySet()) {
                Serializable value = taskParams.get(qname);
                if (params.get(qname) == null || (value instanceof List == false)) {
                    params.put(qname, value);
                } else {
                    List current = (List) params.get(qname);
                    if (qname.equals(WorkflowModel.ASSOC_ASSIGNEES)) {
                        current.clear();
                    }
                    current.addAll((List) value);
                }
            }
            // remove any deleted associations
            Map<String, Map<String, AssociationRef>> assocs = this.workflowNode.getRemovedAssociations();
            for (String assocName : assocs.keySet()) {
                QName assocQName = Repository.resolveToQName(assocName);

                // get the associations removed and create list of targets
                if (params.containsKey(assocQName)) {
                    List current = (List) params.get(assocQName);
                    if (current != null) {
                        Map<String, AssociationRef> removedAssocs = assocs.get(assocName);
                        for (AssociationRef assoc : removedAssocs.values()) {
                            current.remove(assoc.getTargetRef());
                        }
                    }
                }
            }
            wf.setParams(params);
        }
        wf.setType(this.workflowNode.getType());

        if (this.filenamePattern != null && this.filenamePattern.length() != 0) {
            // check the filename pattern compiles and display an error if a problem occurs
            try {
                Pattern.compile(this.filenamePattern);
            } catch (PatternSyntaxException pax) {
                throw new AlfrescoRuntimeException(MessageFormat.format(
                        Application.getMessage(FacesContext.getCurrentInstance(), MSG_ERROR_FILENAME_PATTERN),
                        pax.getMessage()), pax);
            }
            wf.setFilenamePattern(this.filenamePattern);
        }
    }
    return outcome;
}

From source file:org.apache.cayenne.access.loader.NamePatternMatcher.java

/**
 * Returns an array of Patterns. Takes a comma-separated list of patterns, attempting
 * to convert them to the java.util.regex.Pattern syntax. E.g.
 * <p>/*from   w  w  w  .  jav  a  2s . c om*/
 * <code>"billing_*,user?"</code> will become an array of two expressions:
 * <p>
 * <code>^billing_.*$</code><br>
 * <code>^user.?$</code><br>
 */
public static Pattern[] createPatterns(Log logger, String patternString) {
    if (patternString == null) {
        return new Pattern[0];
    }
    String[] patternStrings = tokenizePattern(patternString);
    List<Pattern> patterns = new ArrayList<Pattern>(patternStrings.length);

    for (String patternString1 : patternStrings) {

        // test the pattern
        try {
            patterns.add(Pattern.compile(patternString1));
        } catch (PatternSyntaxException e) {

            if (logger != null) {
                logger.warn("Ignoring invalid pattern [" + patternString1 + "], reason: " + e.getMessage());
            }
        }
    }

    return patterns.toArray(new Pattern[patterns.size()]);
}

From source file:org.apache.cayenne.dbsync.filter.NamePatternMatcher.java

/**
 * Returns an array of Patterns. Takes a comma-separated list of patterns, attempting
 * to convert them to the java.util.regex.Pattern syntax. E.g.
 * <p>/*from   w  ww .  j  a  v  a2s .com*/
 * <code>"billing_*,user?"</code> will become an array of two expressions:
 * <p>
 * <code>^billing_.*$</code><br>
 * <code>^user.?$</code><br>
 */
public static Pattern[] createPatterns(Log logger, String patternString) {
    if (patternString == null) {
        return new Pattern[0];
    }
    String[] patternStrings = tokenizePattern(patternString);
    List<Pattern> patterns = new ArrayList<>(patternStrings.length);

    for (String patternString1 : patternStrings) {

        // test the pattern
        try {
            patterns.add(Pattern.compile(patternString1));
        } catch (PatternSyntaxException e) {

            if (logger != null) {
                logger.warn("Ignoring invalid pattern [" + patternString1 + "], reason: " + e.getMessage());
            }
        }
    }

    return patterns.toArray(new Pattern[patterns.size()]);
}

From source file:org.apache.cayenne.tools.NamePatternMatcher.java

/**
 * Returns an array of Patterns. Takes a comma-separated list of patterns, attempting
 * to convert them to the java.util.regex.Pattern syntax. E.g.
 * <p>/*  www .  j a  v a  2  s.  c  o  m*/
 * <code>"billing_*,user?"</code> will become an array of two expressions:
 * <p>
 * <code>^billing_.*$</code><br>
 * <code>^user.?$</code><br>
 */
public Pattern[] createPatterns(String patternString) {
    String[] patternStrings = tokenizePattern(patternString);
    List<Pattern> patterns = new ArrayList<Pattern>(patternStrings.length);

    for (int i = 0; i < patternStrings.length; i++) {

        // test the pattern
        try {
            patterns.add(Pattern.compile(patternStrings[i]));
        } catch (PatternSyntaxException e) {

            if (logger != null) {
                logger.warn("Ignoring invalid pattern [" + patternStrings[i] + "], reason: " + e.getMessage());
            }
        }
    }

    return patterns.toArray(new Pattern[patterns.size()]);
}

From source file:org.apache.hadoop.hive.ql.parse.SemanticAnalyzer.java

@SuppressWarnings("nls")
// TODO: make aliases unique, otherwise needless rewriting takes place
Integer genColListRegex(String colRegex, String tabAlias, ASTNode sel, ArrayList<ExprNodeDesc> col_list,
        HashSet<ColumnInfo> excludeCols, RowResolver input, RowResolver colSrcRR, Integer pos,
        RowResolver output, List<String> aliases, boolean ensureUniqueCols) throws SemanticException {

    if (colSrcRR == null) {
        colSrcRR = input;//w w  w.  j a va2 s  . c om
    }
    // The table alias should exist
    if (tabAlias != null && !colSrcRR.hasTableAlias(tabAlias)) {
        throw new SemanticException(ErrorMsg.INVALID_TABLE_ALIAS.getMsg(sel));
    }

    // TODO: Have to put in the support for AS clause
    Pattern regex = null;
    try {
        regex = Pattern.compile(colRegex, Pattern.CASE_INSENSITIVE);
    } catch (PatternSyntaxException e) {
        throw new SemanticException(ErrorMsg.INVALID_COLUMN.getMsg(sel, e.getMessage()));
    }

    StringBuilder replacementText = new StringBuilder();
    int matched = 0;
    // add empty string to the list of aliases. Some operators (ex. GroupBy) add
    // ColumnInfos for table alias "".
    if (!aliases.contains("")) {
        aliases.add("");
    }
    /*
     * track the input ColumnInfos that are added to the output.
     * if a columnInfo has multiple mappings; then add the column only once,
     * but carry the mappings forward.
     */
    Map<ColumnInfo, ColumnInfo> inputColsProcessed = new HashMap<ColumnInfo, ColumnInfo>();
    // For expr "*", aliases should be iterated in the order they are specified
    // in the query.

    if (colSrcRR.getNamedJoinInfo() != null) {
        // We got using() clause in previous join. Need to generate select list as
        // per standard. For * we will have joining columns first non-repeated
        // followed by other columns.
        HashMap<String, ColumnInfo> leftMap = colSrcRR
                .getFieldMap(colSrcRR.getNamedJoinInfo().getAliases().get(0));
        HashMap<String, ColumnInfo> rightMap = colSrcRR
                .getFieldMap(colSrcRR.getNamedJoinInfo().getAliases().get(1));
        HashMap<String, ColumnInfo> chosenMap = null;
        if (colSrcRR.getNamedJoinInfo().getHiveJoinType() != JoinType.RIGHTOUTER) {
            chosenMap = leftMap;
        } else {
            chosenMap = rightMap;
        }
        // first get the columns in named columns
        for (String columnName : colSrcRR.getNamedJoinInfo().getNamedColumns()) {
            for (Map.Entry<String, ColumnInfo> entry : chosenMap.entrySet()) {
                ColumnInfo colInfo = entry.getValue();
                if (!columnName.equals(colInfo.getAlias())) {
                    continue;
                }
                String name = colInfo.getInternalName();
                String[] tmp = colSrcRR.reverseLookup(name);

                // Skip the colinfos which are not for this particular alias
                if (tabAlias != null && !tmp[0].equalsIgnoreCase(tabAlias)) {
                    continue;
                }

                if (colInfo.getIsVirtualCol() && colInfo.isHiddenVirtualCol()) {
                    continue;
                }
                ColumnInfo oColInfo = inputColsProcessed.get(colInfo);
                if (oColInfo == null) {
                    ExprNodeColumnDesc expr = new ExprNodeColumnDesc(colInfo.getType(), name,
                            colInfo.getTabAlias(), colInfo.getIsVirtualCol(), colInfo.isSkewedCol());
                    col_list.add(expr);
                    oColInfo = new ColumnInfo(getColumnInternalName(pos), colInfo.getType(),
                            colInfo.getTabAlias(), colInfo.getIsVirtualCol(), colInfo.isHiddenVirtualCol());
                    inputColsProcessed.put(colInfo, oColInfo);
                }
                if (ensureUniqueCols) {
                    if (!output.putWithCheck(tmp[0], tmp[1], null, oColInfo)) {
                        throw new CalciteSemanticException(
                                "Cannot add column to RR: " + tmp[0] + "." + tmp[1] + " => " + oColInfo
                                        + " due to duplication, see previous warnings",
                                UnsupportedFeature.Duplicates_in_RR);
                    }
                } else {
                    output.put(tmp[0], tmp[1], oColInfo);
                }
                pos = Integer.valueOf(pos.intValue() + 1);
                matched++;

                if (unparseTranslator.isEnabled() || tableMask.isEnabled()) {
                    if (replacementText.length() > 0) {
                        replacementText.append(", ");
                    }
                    replacementText.append(HiveUtils.unparseIdentifier(tmp[0], conf));
                    replacementText.append(".");
                    replacementText.append(HiveUtils.unparseIdentifier(tmp[1], conf));
                }
            }
        }
    }
    for (String alias : aliases) {
        HashMap<String, ColumnInfo> fMap = colSrcRR.getFieldMap(alias);
        if (fMap == null) {
            continue;
        }
        // For the tab.* case, add all the columns to the fieldList
        // from the input schema
        for (Map.Entry<String, ColumnInfo> entry : fMap.entrySet()) {
            ColumnInfo colInfo = entry.getValue();
            if (colSrcRR.getNamedJoinInfo() != null
                    && colSrcRR.getNamedJoinInfo().getNamedColumns().contains(colInfo.getAlias())) {
                // we already added this column in select list.
                continue;
            }
            if (excludeCols != null && excludeCols.contains(colInfo)) {
                continue; // This was added during plan generation.
            }
            // First, look up the column from the source against which * is to be
            // resolved.
            // We'd later translated this into the column from proper input, if
            // it's valid.
            // TODO: excludeCols may be possible to remove using the same
            // technique.
            String name = colInfo.getInternalName();
            String[] tmp = colSrcRR.reverseLookup(name);

            // Skip the colinfos which are not for this particular alias
            if (tabAlias != null && !tmp[0].equalsIgnoreCase(tabAlias)) {
                continue;
            }

            if (colInfo.getIsVirtualCol() && colInfo.isHiddenVirtualCol()) {
                continue;
            }

            // Not matching the regex?
            if (!regex.matcher(tmp[1]).matches()) {
                continue;
            }

            // If input (GBY) is different than the source of columns, find the
            // same column in input.
            // TODO: This is fraught with peril.
            if (input != colSrcRR) {
                colInfo = input.get(tabAlias, tmp[1]);
                if (colInfo == null) {
                    LOG.error("Cannot find colInfo for " + tabAlias + "." + tmp[1] + ", derived from ["
                            + colSrcRR + "], in [" + input + "]");
                    throw new SemanticException(ErrorMsg.NON_KEY_EXPR_IN_GROUPBY, tmp[1]);
                }
                String oldCol = null;
                if (LOG.isDebugEnabled()) {
                    oldCol = name + " => " + (tmp == null ? "null" : (tmp[0] + "." + tmp[1]));
                }
                name = colInfo.getInternalName();
                tmp = input.reverseLookup(name);
                if (LOG.isDebugEnabled()) {
                    String newCol = name + " => " + (tmp == null ? "null" : (tmp[0] + "." + tmp[1]));
                    LOG.debug("Translated [" + oldCol + "] to [" + newCol + "]");
                }
            }

            ColumnInfo oColInfo = inputColsProcessed.get(colInfo);
            if (oColInfo == null) {
                ExprNodeColumnDesc expr = new ExprNodeColumnDesc(colInfo.getType(), name, colInfo.getTabAlias(),
                        colInfo.getIsVirtualCol(), colInfo.isSkewedCol());
                col_list.add(expr);
                oColInfo = new ColumnInfo(getColumnInternalName(pos), colInfo.getType(), colInfo.getTabAlias(),
                        colInfo.getIsVirtualCol(), colInfo.isHiddenVirtualCol());
                inputColsProcessed.put(colInfo, oColInfo);
            }
            if (ensureUniqueCols) {
                if (!output.putWithCheck(tmp[0], tmp[1], null, oColInfo)) {
                    throw new CalciteSemanticException(
                            "Cannot add column to RR: " + tmp[0] + "." + tmp[1] + " => " + oColInfo
                                    + " due to duplication, see previous warnings",
                            UnsupportedFeature.Duplicates_in_RR);
                }
            } else {
                output.put(tmp[0], tmp[1], oColInfo);
            }
            pos = Integer.valueOf(pos.intValue() + 1);
            matched++;

            if (unparseTranslator.isEnabled() || tableMask.isEnabled()) {
                if (replacementText.length() > 0) {
                    replacementText.append(", ");
                }
                replacementText.append(HiveUtils.unparseIdentifier(tmp[0], conf));
                replacementText.append(".");
                replacementText.append(HiveUtils.unparseIdentifier(tmp[1], conf));
            }
        }
    }

    if (matched == 0) {
        throw new SemanticException(ErrorMsg.INVALID_COLUMN.getMsg(sel));
    }

    if (unparseTranslator.isEnabled()) {
        unparseTranslator.addTranslation(sel, replacementText.toString());
    } else if (tableMask.isEnabled()) {
        tableMask.addTranslation(sel, replacementText.toString());
    }
    return pos;
}