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:org.owasp.webscarab.plugin.sessionid.swing.SessionIDPanel.java

private void fetchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fetchButtonActionPerformed
    try {/*  ww w.ja v a 2s  .  c  om*/
        Request request = _requestPanel.getRequest();
        if (request == null) {
            _logger.warning("Request was null in fetch request");
            return;
        }
        String name = nameTextField.getText();
        String regex = regexTextField.getText();
        int count = ((Integer) sampleSpinner.getValue()).intValue();
        try {
            _sa.fetch(request, name, regex, count);
        } catch (PatternSyntaxException pse) {
            JOptionPane.showMessageDialog(this, pse.getMessage(), "Pattern Syntax Exception",
                    JOptionPane.WARNING_MESSAGE);
        }
    } catch (MalformedURLException mue) {
        JOptionPane.showMessageDialog(this, new String[] { "The URL requested is malformed", mue.getMessage() },
                "Malformed URL", JOptionPane.ERROR_MESSAGE);
    } catch (ParseException pe) {
        JOptionPane.showMessageDialog(this, new String[] { "The request is malformed", pe.getMessage() },
                "Malformed Request", JOptionPane.ERROR_MESSAGE);
    }

}

From source file:com.tunyk.mvn.plugins.htmlcompressor.HtmlCompressorMojo.java

@Override
public void execute() throws MojoExecutionException {
    if (!enabled) {
        getLog().info("HTML compression was turned off.");
        return;//w w  w .  j  ava 2s .co m
    }

    if (!new File(srcFolder).exists()) {
        getLog().warn("Compressor folder does not exist, skipping compression of " + srcFolder);
        return;
    }

    getLog().info("Compressing " + srcFolder);
    HtmlCompressor htmlCompressor = new HtmlCompressor(srcFolder, targetFolder);

    htmlCompressor.setFileExt(fileExt);
    htmlCompressor.setFileEncoding(encoding);
    htmlCompressor.setCreateJsonFile(javascriptHtmlSprite);
    htmlCompressor.setJsonIntegrationFilePath(javascriptHtmlSpriteIntegrationFile);
    htmlCompressor.setTargetJsonFilePath(javascriptHtmlSpriteTargetFile);

    com.googlecode.htmlcompressor.compressor.HtmlCompressor htmlCompressorHandler = new com.googlecode.htmlcompressor.compressor.HtmlCompressor();
    htmlCompressorHandler.setEnabled(enabled);
    htmlCompressorHandler.setRemoveComments(removeComments);
    htmlCompressorHandler.setRemoveMultiSpaces(removeMultiSpaces);
    htmlCompressorHandler.setRemoveIntertagSpaces(removeIntertagSpaces);
    htmlCompressorHandler.setRemoveQuotes(removeQuotes);
    htmlCompressorHandler.setSimpleDoctype(simpleDoctype);
    htmlCompressorHandler.setRemoveScriptAttributes(removeScriptAttributes);
    htmlCompressorHandler.setRemoveStyleAttributes(removeStyleAttributes);
    htmlCompressorHandler.setRemoveLinkAttributes(removeLinkAttributes);
    htmlCompressorHandler.setRemoveFormAttributes(removeFormAttributes);
    htmlCompressorHandler.setRemoveInputAttributes(removeInputAttributes);
    htmlCompressorHandler.setSimpleBooleanAttributes(simpleBooleanAttributes);
    htmlCompressorHandler.setRemoveJavaScriptProtocol(removeJavaScriptProtocol);
    htmlCompressorHandler.setRemoveHttpProtocol(removeHttpProtocol);
    htmlCompressorHandler.setRemoveHttpsProtocol(removeHttpsProtocol);
    htmlCompressorHandler.setCompressCss(compressCss);
    htmlCompressorHandler.setPreserveLineBreaks(preserveLineBreaks);
    htmlCompressorHandler.setYuiCssLineBreak(yuiCssLineBreak);
    htmlCompressorHandler.setCompressJavaScript(compressJavaScript);
    htmlCompressorHandler.setYuiJsNoMunge(yuiJsNoMunge);
    htmlCompressorHandler.setYuiJsPreserveAllSemiColons(yuiJsPreserveAllSemiColons);
    htmlCompressorHandler.setYuiJsLineBreak(yuiJsLineBreak);
    htmlCompressorHandler.setYuiJsDisableOptimizations(yuiJsDisableOptimizations);
    htmlCompressorHandler.setGenerateStatistics(generateStatistics);

    if (jsCompressor.equalsIgnoreCase("closure")) {
        ClosureJavaScriptCompressor closureCompressor = new ClosureJavaScriptCompressor();
        if (closureOptLevel != null
                && closureOptLevel.equalsIgnoreCase(ClosureJavaScriptCompressor.COMPILATION_LEVEL_ADVANCED)) {
            closureCompressor.setCompilationLevel(CompilationLevel.ADVANCED_OPTIMIZATIONS);
            closureCompressor.setCustomExternsOnly(closureCustomExternsOnly != null);
            if (closureExterns.length > 0) {
                List<SourceFile> externs = new ArrayList<SourceFile>();
                for (String externFile : closureExterns) {
                    externs.add(SourceFile.fromFile(externFile));
                }
                closureCompressor.setExterns(externs);
            }
        } else if (closureOptLevel != null
                && closureOptLevel.equalsIgnoreCase(ClosureJavaScriptCompressor.COMPILATION_LEVEL_WHITESPACE)) {
            closureCompressor.setCompilationLevel(CompilationLevel.WHITESPACE_ONLY);
        } else {
            closureCompressor.setCompilationLevel(CompilationLevel.SIMPLE_OPTIMIZATIONS);
        }

        htmlCompressorHandler.setJavaScriptCompressor(closureCompressor);
    }

    List<Pattern> preservePatternList = new ArrayList<Pattern>();
    boolean phpTagPatternAdded = false;
    boolean serverScriptTagPatternAdded = false;
    if (predefinedPreservePatterns != null) {
        for (String pattern : predefinedPreservePatterns) {
            if (!phpTagPatternAdded && pattern.equalsIgnoreCase("PHP_TAG_PATTERN")) {
                preservePatternList
                        .add(com.googlecode.htmlcompressor.compressor.HtmlCompressor.PHP_TAG_PATTERN);
                phpTagPatternAdded = true;
            } else if (!serverScriptTagPatternAdded && pattern.equalsIgnoreCase("SERVER_SCRIPT_TAG_PATTERN")) {
                preservePatternList
                        .add(com.googlecode.htmlcompressor.compressor.HtmlCompressor.SERVER_SCRIPT_TAG_PATTERN);
                serverScriptTagPatternAdded = true;
            }
        }
    }
    if (preservePatterns != null) {
        for (String preservePatternString : preservePatterns) {
            if (!preservePatternString.isEmpty()) {
                try {
                    preservePatternList.add(Pattern.compile(preservePatternString));
                } catch (PatternSyntaxException e) {
                    throw new MojoExecutionException(e.getMessage());
                }
            }
        }
    }
    if (preservePatternFiles != null) {
        for (File file : preservePatternFiles) {
            try {
                List<String> fileLines = Files.readAllLines(file.toPath(), Charset.forName(encoding));
                for (String line : fileLines) {
                    if (!line.isEmpty()) {
                        preservePatternList.add(Pattern.compile(line));
                    }
                }
            } catch (PatternSyntaxException e) {
                throw new MojoExecutionException(e.getMessage());
            } catch (IOException e) {
                throw new MojoExecutionException(e.getMessage());
            }
        }
    }
    htmlCompressorHandler.setPreservePatterns(preservePatternList);
    htmlCompressor.setHtmlCompressor(htmlCompressorHandler);

    try {
        htmlCompressor.compress();
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage());
    }

    boolean si = true;

    // TODO: if no files matched pattern (*.htm or *.html) then this gives NullPointerException
    int origFilesizeBytes = htmlCompressor.getHtmlCompressor().getStatistics().getOriginalMetrics()
            .getFilesize();
    String origFilesize = FileTool.humanReadableByteCount(origFilesizeBytes, si);
    String origEmptyChars = String
            .valueOf(htmlCompressor.getHtmlCompressor().getStatistics().getOriginalMetrics().getEmptyChars());
    String origInlineEventSize = FileTool.humanReadableByteCount(
            htmlCompressor.getHtmlCompressor().getStatistics().getOriginalMetrics().getInlineEventSize(), si);
    String origInlineScriptSize = FileTool.humanReadableByteCount(
            htmlCompressor.getHtmlCompressor().getStatistics().getOriginalMetrics().getInlineScriptSize(), si);
    String origInlineStyleSize = FileTool.humanReadableByteCount(
            htmlCompressor.getHtmlCompressor().getStatistics().getOriginalMetrics().getInlineStyleSize(), si);

    int compFilesizeBytes = htmlCompressor.getHtmlCompressor().getStatistics().getCompressedMetrics()
            .getFilesize();
    String compFilesize = FileTool.humanReadableByteCount(compFilesizeBytes, si);
    String compEmptyChars = String
            .valueOf(htmlCompressor.getHtmlCompressor().getStatistics().getCompressedMetrics().getEmptyChars());
    String compInlineEventSize = FileTool.humanReadableByteCount(
            htmlCompressor.getHtmlCompressor().getStatistics().getCompressedMetrics().getInlineEventSize(), si);
    String compInlineScriptSize = FileTool.humanReadableByteCount(
            htmlCompressor.getHtmlCompressor().getStatistics().getCompressedMetrics().getInlineScriptSize(),
            si);
    String compInlineStyleSize = FileTool.humanReadableByteCount(
            htmlCompressor.getHtmlCompressor().getStatistics().getCompressedMetrics().getInlineStyleSize(), si);

    String elapsedTime = FileTool
            .getElapsedHMSTime(htmlCompressor.getHtmlCompressor().getStatistics().getTime());
    String preservedSize = FileTool
            .humanReadableByteCount(htmlCompressor.getHtmlCompressor().getStatistics().getPreservedSize(), si);
    Float compressionRatio = Float.valueOf(compFilesizeBytes) / Float.valueOf(origFilesizeBytes);
    Float spaceSavings = Float.valueOf(1) - compressionRatio;

    String format = "%-30s%-30s%-30s%-2s";
    NumberFormat formatter = new DecimalFormat("#0.00");
    String eol = "\n";
    String hr = "+-----------------------------+-----------------------------+-----------------------------+";
    StringBuilder sb = new StringBuilder("HTML compression statistics:").append(eol);
    sb.append(hr).append(eol);
    sb.append(String.format(format, "| Category", "| Original", "| Compressed", "|")).append(eol);
    sb.append(hr).append(eol);
    sb.append(String.format(format, "| Filesize", "| " + origFilesize, "| " + compFilesize, "|")).append(eol);
    sb.append(String.format(format, "| Empty Chars", "| " + origEmptyChars, "| " + compEmptyChars, "|"))
            .append(eol);
    sb.append(String.format(format, "| Script Size", "| " + origInlineScriptSize, "| " + compInlineScriptSize,
            "|")).append(eol);
    sb.append(
            String.format(format, "| Style Size", "| " + origInlineStyleSize, "| " + compInlineStyleSize, "|"))
            .append(eol);
    sb.append(String.format(format, "| Event Handler Size", "| " + origInlineEventSize,
            "| " + compInlineEventSize, "|")).append(eol);
    sb.append(hr).append(eol);
    sb.append(String.format("%-90s%-2s",
            String.format("| Time: %s, Preserved: %s, Compression Ratio: %s, Savings: %s%%", elapsedTime,
                    preservedSize, formatter.format(compressionRatio), formatter.format(spaceSavings * 100)),
            "|")).append(eol);
    sb.append(hr).append(eol);

    String statistics = sb.toString();
    getLog().info(statistics);
    try {
        FileUtils.writeStringToFile(new File(htmlCompressionStatistics), statistics, encoding);
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage());
    }

    getLog().info("HTML compression completed.");
}

From source file:org.owasp.webscarab.plugin.sessionid.swing.SessionIDPanel.java

private void testButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_testButtonActionPerformed
    try {//w  w  w .j  av  a  2  s  .c o  m
        final Request request = _requestPanel.getRequest();
        if (request == null) {
            return;
        }
        testButton.setEnabled(false);
        final Component parent = this;
        new SwingWorker() {
            public Object construct() {
                try {
                    _sa.setRequest(request);
                    _sa.fetchResponse();
                    return _sa.getResponse();
                } catch (IOException ioe) {
                    return ioe;
                }
            }

            //Runs on the event-dispatching thread.
            public void finished() {
                Object obj = getValue();
                if (obj instanceof Response) {
                    Response response = (Response) getValue();
                    if (response != null) {
                        _responsePanel.setResponse(response);
                        String name = nameTextField.getText();
                        String regex = regexTextField.getText();
                        try {
                            Map<String, SessionID> ids = _sa.getIDsFromResponse(response, name, regex);
                            String[] keys = ids.keySet().toArray(new String[0]);
                            for (int i = 0; i < keys.length; i++) {
                                SessionID id = ids.get(keys[i]);
                                keys[i] = keys[i] + " = " + id.getValue();
                            }
                            if (keys.length == 0)
                                keys = new String[] { "No session identifiers found!" };
                            JOptionPane.showMessageDialog(parent, keys, "Extracted Sessionids",
                                    JOptionPane.INFORMATION_MESSAGE);
                        } catch (PatternSyntaxException pse) {
                            JOptionPane.showMessageDialog(parent, pse.getMessage(), "Patter Syntax Exception",
                                    JOptionPane.WARNING_MESSAGE);
                        }
                    }
                } else if (obj instanceof Exception) {
                    JOptionPane.showMessageDialog(null,
                            new String[] { "Error fetching response: ", obj.toString() }, "Error",
                            JOptionPane.ERROR_MESSAGE);
                    _logger.severe("Exception fetching response: " + obj);
                }
                testButton.setEnabled(true);
            }
        }.start();
    } catch (MalformedURLException mue) {
        JOptionPane.showMessageDialog(this, new String[] { "The URL requested is malformed", mue.getMessage() },
                "Malformed URL", JOptionPane.ERROR_MESSAGE);
    } catch (ParseException pe) {
        JOptionPane.showMessageDialog(this, new String[] { "The request is malformed", pe.getMessage() },
                "Malformed Request", JOptionPane.ERROR_MESSAGE);
    }

}

From source file:com.sciaps.view.SpectrumShotPanel.java

private void filterTable() {
    try {//from w w  w  .  j  a va  2 s .c  o m
        RowFilter<ShotListTableModel, Object> rowFilter = RowFilter
                .regexFilter("(?i)" + txtFilterText_.getText(), 1);
        sorter_.setRowFilter(rowFilter);
    } catch (java.util.regex.PatternSyntaxException ex) {
        logger_.error(ex.getMessage());
    }
}

From source file:com.moviejukebox.MovieJukebox.java

/**
 * Clean up the jukebox folder of any extra files that are not needed.
 *
 * If the jukeboxClean parameter is not set, just report on the files that would be cleaned.
 *//*from   w  w  w. j a v a  2 s. c  om*/
private static void cleanJukeboxFolder() {
    boolean cleanReport = PropertiesUtil.getBooleanProperty("mjb.jukeboxCleanReport", Boolean.FALSE);

    if (jukeboxClean) {
        if (ScanningLimit.isLimitReached()) {
            LOG.info("Jukebox cleaning skipped as movie limit was reached");
            return;
        }
        LOG.info("Cleaning up the jukebox directory...");
    } else if (cleanReport) {
        LOG.info("Jukebox cleaning skipped, the following files are orphaned (not used anymore):");
    } else {
        LOG.info("Jukebox cleaning skipped.");
        return;
    }

    Collection<String> generatedFileNames = FileTools.getJukeboxFiles();

    File[] cleanList = jukebox.getJukeboxRootLocationDetailsFile().listFiles();
    int cleanDeletedTotal = 0;
    boolean skip;

    String skipPattStr = getProperty("mjb.clean.skip");
    Pattern skipPatt;

    if (StringTools.isValidString(skipPattStr)) {
        // Try and convert the string into a pattern
        try {
            skipPatt = Pattern.compile(skipPattStr, Pattern.CASE_INSENSITIVE);
        } catch (PatternSyntaxException ex) {
            LOG.warn("Error converting mjb.clean.skip '{}'", skipPattStr);
            LOG.warn(ex.getMessage());
            skipPatt = null;
        }
    } else {
        skipPatt = null;
    }
    for (File cleanList1 : cleanList) {
        // Scan each file in here
        if (cleanList1.isFile() && !generatedFileNames.contains(cleanList1.getName())) {
            skip = Boolean.FALSE;
            // If the file is in the skin's exclusion regex, skip it
            if (skipPatt != null) {
                skip = skipPatt.matcher(cleanList1.getName()).matches();
            }
            // If the file isn't skipped and it's not part of the library, delete it
            if (!skip) {
                if (jukeboxClean) {
                    LOG.debug("Deleted: {} from library", cleanList1.getName());
                    cleanList1.delete();
                } else {
                    LOG.debug("Unused: {}", cleanList1.getName());
                }
                cleanDeletedTotal++;
            }
        }
    }

    LOG.info("{} files in the jukebox directory", cleanList.length);
    if (cleanDeletedTotal > 0) {
        if (jukeboxClean) {
            LOG.info("Deleted {} unused file{} from the jukebox directory", cleanDeletedTotal,
                    cleanDeletedTotal == 1 ? "" : "s");
        } else {
            LOG.info("There {} {} orphaned file{} in the jukebox directory",
                    cleanDeletedTotal == 1 ? "is" : "are", cleanDeletedTotal,
                    cleanDeletedTotal == 1 ? "" : "s");
        }
    }
}

From source file:org.apache.manifoldcf.crawler.connectors.rss.RSSConnector.java

/** Compile all regexp entries in the passed in list, and add them to the output
* list./*from ww w . j a v a 2  s  .c  o  m*/
*/
protected static void compileList(List<Pattern> output, List<String> input) throws ManifoldCFException {
    for (String inputString : input) {
        try {
            output.add(Pattern.compile(inputString));
        } catch (PatternSyntaxException e) {
            throw new ManifoldCFException(
                    "Mapping regular expression '" + inputString + "' is illegal: " + e.getMessage(), e);
        }
    }
}

From source file:org.apache.manifoldcf.crawler.connectors.webcrawler.WebcrawlerConnector.java

/** Compile all regexp entries in the passed in list, and add them to the output
* list./*from   w ww  . ja v  a 2  s .  c  o  m*/
*/
protected static void compileList(List<Pattern> output, List<String> input) throws ManifoldCFException {
    int i = 0;
    while (i < input.size()) {
        String inputString = input.get(i++);
        try {
            output.add(Pattern.compile(inputString));
        } catch (PatternSyntaxException e) {
            throw new ManifoldCFException(
                    "Mapping regular expression '" + inputString + "' is illegal: " + e.getMessage(), e);
        }
    }
}

From source file:com.zimbra.cs.account.ldap.LdapProvisioning.java

/**
 * called to check password strength. Should pass in either an Account, or Cos/Attributes (during creation).
 *
 * @param password//from ww w .  j av a2 s.c o m
 * @param acct
 * @param cos
 * @param attrs
 * @throws ServiceException
 */
private void checkPasswordStrength(String password, Account acct, Cos cos, ZMutableEntry entry)
        throws ServiceException {
    int minLength = getInt(acct, cos, entry, Provisioning.A_zimbraPasswordMinLength, 0);
    if (minLength > 0 && password.length() < minLength) {
        throw AccountServiceException.INVALID_PASSWORD("too short",
                new Argument(Provisioning.A_zimbraPasswordMinLength, minLength, Argument.Type.NUM));
    }

    int maxLength = getInt(acct, cos, entry, Provisioning.A_zimbraPasswordMaxLength, 0);
    if (maxLength > 0 && password.length() > maxLength) {
        throw AccountServiceException.INVALID_PASSWORD("too long",
                new Argument(Provisioning.A_zimbraPasswordMaxLength, maxLength, Argument.Type.NUM));
    }

    int minUpperCase = getInt(acct, cos, entry, Provisioning.A_zimbraPasswordMinUpperCaseChars, 0);
    int minLowerCase = getInt(acct, cos, entry, Provisioning.A_zimbraPasswordMinLowerCaseChars, 0);
    int minNumeric = getInt(acct, cos, entry, Provisioning.A_zimbraPasswordMinNumericChars, 0);
    int minPunctuation = getInt(acct, cos, entry, Provisioning.A_zimbraPasswordMinPunctuationChars, 0);
    int minAlpha = getInt(acct, cos, entry, Provisioning.A_zimbraPasswordMinAlphaChars, 0);
    int minNumOrPunc = getInt(acct, cos, entry, Provisioning.A_zimbraPasswordMinDigitsOrPuncs, 0);

    String allowedChars = getString(acct, cos, entry, Provisioning.A_zimbraPasswordAllowedChars);
    Pattern allowedCharsPattern = null;
    if (allowedChars != null) {
        try {
            allowedCharsPattern = Pattern.compile(allowedChars);
        } catch (PatternSyntaxException e) {
            throw AccountServiceException.INVALID_PASSWORD(
                    Provisioning.A_zimbraPasswordAllowedChars + " is not valid regex: " + e.getMessage());
        }
    }
    String allowedPuncChars = getString(acct, cos, entry, Provisioning.A_zimbraPasswordAllowedPunctuationChars);
    Pattern allowedPuncCharsPattern = null;
    if (allowedPuncChars != null) {
        try {
            allowedPuncCharsPattern = Pattern.compile(allowedPuncChars);
        } catch (PatternSyntaxException e) {
            throw AccountServiceException.INVALID_PASSWORD(Provisioning.A_zimbraPasswordAllowedPunctuationChars
                    + " is not valid regex: " + e.getMessage());
        }
    }

    boolean hasPolicies = minUpperCase > 0 || minLowerCase > 0 || minNumeric > 0 || minPunctuation > 0
            || minAlpha > 0 || minNumOrPunc > 0 || allowedCharsPattern != null
            || allowedPuncCharsPattern != null;

    if (!hasPolicies) {
        return;
    }

    int upper = 0;
    int lower = 0;
    int numeric = 0;
    int punctuation = 0;
    int alpha = 0;

    for (int i = 0; i < password.length(); i++) {
        char ch = password.charAt(i);

        if (allowedCharsPattern != null) {
            if (!allowedCharsPattern.matcher(Character.toString(ch)).matches()) {
                throw AccountServiceException.INVALID_PASSWORD(ch + " is not an allowed character",
                        new Argument(Provisioning.A_zimbraPasswordAllowedChars, allowedChars,
                                Argument.Type.STR));
            }
        }

        boolean isAlpha = true;
        if (Character.isUpperCase(ch)) {
            upper++;
        } else if (Character.isLowerCase(ch)) {
            lower++;
        } else if (Character.isDigit(ch)) {
            numeric++;
            isAlpha = false;
        } else if (allowedPuncCharsPattern != null) {
            if (allowedPuncCharsPattern.matcher(Character.toString(ch)).matches()) {
                punctuation++;
                isAlpha = false;
            }
        } else if (isAsciiPunc(ch)) {
            punctuation++;
            isAlpha = false;
        }
        if (isAlpha) {
            alpha++;
        }
    }

    if (upper < minUpperCase) {
        throw AccountServiceException.INVALID_PASSWORD("not enough upper case characters",
                new Argument(Provisioning.A_zimbraPasswordMinUpperCaseChars, minUpperCase, Argument.Type.NUM));
    }
    if (lower < minLowerCase) {
        throw AccountServiceException.INVALID_PASSWORD("not enough lower case characters",
                new Argument(Provisioning.A_zimbraPasswordMinLowerCaseChars, minLowerCase, Argument.Type.NUM));
    }
    if (numeric < minNumeric) {
        throw AccountServiceException.INVALID_PASSWORD("not enough numeric characters",
                new Argument(Provisioning.A_zimbraPasswordMinNumericChars, minNumeric, Argument.Type.NUM));
    }
    if (punctuation < minPunctuation) {
        throw AccountServiceException.INVALID_PASSWORD("not enough punctuation characters", new Argument(
                Provisioning.A_zimbraPasswordMinPunctuationChars, minPunctuation, Argument.Type.NUM));
    }
    if (alpha < minAlpha) {
        throw AccountServiceException.INVALID_PASSWORD("not enough alpha characters",
                new Argument(Provisioning.A_zimbraPasswordMinAlphaChars, minAlpha, Argument.Type.NUM));
    }
    if (numeric + punctuation < minNumOrPunc) {
        throw AccountServiceException.INVALID_PASSWORD("not enough numeric or punctuation characters",
                new Argument(Provisioning.A_zimbraPasswordMinDigitsOrPuncs, minNumOrPunc, Argument.Type.NUM));
    }
}

From source file:com.jhh.hdb.sqlparser.MySemanticAnalyzer.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;/*  www . j  ava  2 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.
    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 (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()) {
                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());
    }
    return pos;
}

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

/**
 * Builds the calculation./*from   www  .j av a 2 s  . co  m*/
 *
 * @param calculation the calculation
 * @param values the values
 * @return the string
 */
public static String buildCalculation(String calculation, Map<Long, Double> values) {

    String parsedCalculation = "";

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

    if (StringUtils.isNotBlank(calculation) && values != null) {
        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 = m.group();
                    Long id = Long.parseLong(StringUtils.substring(text, 1));
                    logger.info("Variable id: " + id);

                    if (values.containsKey(id)) {
                        logger.debug("Contains variable " + id);
                        double value = values.get(id);
                        logger.debug("Value: " + value);
                        text = String.valueOf(value);
                    }
                    logger.debug("Replacement text: " + text);
                    m.appendReplacement(sb, Matcher.quoteReplacement(text));

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

            parsedCalculation = sb.toString();
            logger.info("Parsed calculation: " + parsedCalculation);

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