Search in sources :

Example 11 with PatternSyntaxException

use of java.util.regex.PatternSyntaxException in project jersey by jersey.

the class ServletContainer method init.

// Filter
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
    this.filterConfig = filterConfig;
    init(new WebFilterConfig(filterConfig));
    final String regex = (String) getConfiguration().getProperty(ServletProperties.FILTER_STATIC_CONTENT_REGEX);
    if (regex != null && !regex.isEmpty()) {
        try {
            staticContentPattern = Pattern.compile(regex);
        } catch (final PatternSyntaxException ex) {
            throw new ContainerException(LocalizationMessages.INIT_PARAM_REGEX_SYNTAX_INVALID(regex, ServletProperties.FILTER_STATIC_CONTENT_REGEX), ex);
        }
    }
    this.filterContextPath = filterConfig.getInitParameter(ServletProperties.FILTER_CONTEXT_PATH);
    if (filterContextPath != null) {
        if (filterContextPath.isEmpty()) {
            filterContextPath = null;
        } else {
            if (!filterContextPath.startsWith("/")) {
                filterContextPath = '/' + filterContextPath;
            }
            if (filterContextPath.endsWith("/")) {
                filterContextPath = filterContextPath.substring(0, filterContextPath.length() - 1);
            }
        }
    }
    // get the url-pattern defined (e.g.) in the filter-mapping section of web.xml
    final FilterUrlMappingsProvider filterUrlMappingsProvider = getFilterUrlMappingsProvider();
    if (filterUrlMappingsProvider != null) {
        filterUrlMappings = filterUrlMappingsProvider.getFilterUrlMappings(filterConfig);
    }
    // not work (won't be accessible)
    if (filterUrlMappings == null && filterContextPath == null) {
        LOGGER.warning(LocalizationMessages.FILTER_CONTEXT_PATH_MISSING());
    }
}
Also used : ContainerException(org.glassfish.jersey.server.ContainerException) FilterUrlMappingsProvider(org.glassfish.jersey.servlet.spi.FilterUrlMappingsProvider) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 12 with PatternSyntaxException

use of java.util.regex.PatternSyntaxException in project intellij-community by JetBrains.

the class PatternValidator method checkExpression.

private void checkExpression(PsiExpression expression, final PsiAnnotation[] annotations, ProblemsHolder holder) {
    if (annotations.length == 0)
        return;
    final PsiAnnotation psiAnnotation = annotations[0];
    // cache compiled pattern with annotation
    CachedValue<Pattern> p = psiAnnotation.getUserData(COMPLIED_PATTERN);
    if (p == null) {
        final CachedValueProvider<Pattern> provider = () -> {
            final String pattern = AnnotationUtilEx.calcAnnotationValue(psiAnnotation, "value");
            Pattern p1 = null;
            if (pattern != null) {
                try {
                    p1 = Pattern.compile(pattern);
                } catch (PatternSyntaxException e) {
                // pattern stays null
                }
            }
            return CachedValueProvider.Result.create(p1, (Object[]) annotations);
        };
        p = CachedValuesManager.getManager(expression.getProject()).createCachedValue(provider, false);
        psiAnnotation.putUserData(COMPLIED_PATTERN, p);
    }
    final Pattern pattern = p.getValue();
    if (pattern == null)
        return;
    List<PsiExpression> nonConstantElements = new SmartList<>();
    final Object result = new SubstitutedExpressionEvaluationHelper(expression.getProject()).computeExpression(expression, myConfiguration.getAdvancedConfiguration().getDfaOption(), false, nonConstantElements);
    final String o = result == null ? null : String.valueOf(result);
    if (o != null) {
        if (!pattern.matcher(o).matches()) {
            if (annotations.length > 1) {
                // the last element contains the element's actual annotation
                final String fqn = annotations[annotations.length - 1].getQualifiedName();
                assert fqn != null;
                final String name = StringUtil.getShortName(fqn);
                holder.registerProblem(expression, MessageFormat.format("Expression ''{0}'' doesn''t match ''{1}'' pattern: {2}", o, name, pattern.pattern()));
            } else {
                holder.registerProblem(expression, MessageFormat.format("Expression ''{0}'' doesn''t match pattern: {1}", o, pattern.pattern()));
            }
        }
    } else if (CHECK_NON_CONSTANT_VALUES) {
        for (PsiExpression expr : nonConstantElements) {
            final PsiElement e;
            if (expr instanceof PsiReferenceExpression) {
                e = ((PsiReferenceExpression) expr).resolve();
            } else if (expr instanceof PsiMethodCallExpression) {
                e = ((PsiMethodCallExpression) expr).getMethodExpression().resolve();
            } else {
                e = expr;
            }
            final PsiModifierListOwner owner = e instanceof PsiModifierListOwner ? (PsiModifierListOwner) e : null;
            LocalQuickFix quickFix;
            if (owner != null && PsiUtilEx.isLanguageAnnotationTarget(owner)) {
                PsiAnnotation[] resolvedAnnos = AnnotationUtilEx.getAnnotationFrom(owner, myConfiguration.getAdvancedConfiguration().getPatternAnnotationPair(), true);
                if (resolvedAnnos.length == 2 && annotations.length == 2 && Comparing.strEqual(resolvedAnnos[1].getQualifiedName(), annotations[1].getQualifiedName())) {
                    // both target and source annotated indirectly with the same anno
                    return;
                }
                final String classname = myConfiguration.getAdvancedConfiguration().getSubstAnnotationPair().first;
                quickFix = AnnotateFix.canApplyOn(owner) ? new AnnotateFix(classname) : new IntroduceVariableFix();
            } else {
                quickFix = new IntroduceVariableFix();
            }
            holder.registerProblem(expr, "Unsubstituted expression", quickFix);
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) LocalQuickFix(com.intellij.codeInspection.LocalQuickFix) SubstitutedExpressionEvaluationHelper(org.intellij.plugins.intelliLang.util.SubstitutedExpressionEvaluationHelper) SmartList(com.intellij.util.SmartList) AnnotateFix(org.intellij.plugins.intelliLang.util.AnnotateFix) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 13 with PatternSyntaxException

use of java.util.regex.PatternSyntaxException in project intellij-community by JetBrains.

the class ImportClassFixBase method doFix.

public Result doFix(@NotNull final Editor editor, boolean allowPopup, final boolean allowCaretNearRef) {
    List<PsiClass> classesToImport = getClassesToImport();
    if (classesToImport.isEmpty())
        return Result.POPUP_NOT_SHOWN;
    try {
        String name = getQualifiedName(myElement);
        if (name != null) {
            Pattern pattern = Pattern.compile(DaemonCodeAnalyzerSettings.getInstance().NO_AUTO_IMPORT_PATTERN);
            Matcher matcher = pattern.matcher(name);
            if (matcher.matches()) {
                return Result.POPUP_NOT_SHOWN;
            }
        }
    } catch (PatternSyntaxException e) {
    //ignore
    }
    final PsiFile psiFile = myElement.getContainingFile();
    if (classesToImport.size() > 1) {
        reduceSuggestedClassesBasedOnDependencyRuleViolation(psiFile, classesToImport);
    }
    PsiClass[] classes = classesToImport.toArray(new PsiClass[classesToImport.size()]);
    final Project project = myElement.getProject();
    CodeInsightUtil.sortIdenticalShortNamedMembers(classes, myRef);
    final QuestionAction action = createAddImportAction(classes, project, editor);
    boolean canImportHere = true;
    boolean isInModlessContext = Registry.is("ide.perProjectModality") ? !LaterInvocator.isInModalContextForProject(editor.getProject()) : !LaterInvocator.isInModalContext();
    if (classes.length == 1 && (canImportHere = canImportHere(allowCaretNearRef, editor, psiFile, classes[0].getName())) && isAddUnambiguousImportsOnTheFlyEnabled(psiFile) && (ApplicationManager.getApplication().isUnitTestMode() || DaemonListeners.canChangeFileSilently(psiFile)) && isInModlessContext && !autoImportWillInsertUnexpectedCharacters(classes[0])) {
        CommandProcessor.getInstance().runUndoTransparentAction(() -> action.execute());
        return Result.CLASS_AUTO_IMPORTED;
    }
    if (allowPopup && canImportHere) {
        String hintText = ShowAutoImportPass.getMessage(classes.length > 1, classes[0].getQualifiedName());
        if (!ApplicationManager.getApplication().isUnitTestMode() && !HintManager.getInstance().hasShownHintsThatWillHideByOtherHint(true)) {
            HintManager.getInstance().showQuestionHint(editor, hintText, getStartOffset(myElement, myRef), getEndOffset(myElement, myRef), action);
        }
        return Result.POPUP_SHOWN;
    }
    return Result.POPUP_NOT_SHOWN;
}
Also used : Pattern(java.util.regex.Pattern) Project(com.intellij.openapi.project.Project) QuestionAction(com.intellij.codeInsight.hint.QuestionAction) Matcher(java.util.regex.Matcher) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 14 with PatternSyntaxException

use of java.util.regex.PatternSyntaxException in project lucene-solr by apache.

the class TestUtil method randomPattern.

/**
   * Returns a valid (compiling) Pattern instance with random stuff inside. Be careful
   * when applying random patterns to longer strings as certain types of patterns
   * may explode into exponential times in backtracking implementations (such as Java's).
   */
public static Pattern randomPattern(Random random) {
    final String nonBmpString = "AB𠀀C";
    while (true) {
        try {
            Pattern p = Pattern.compile(TestUtil.randomRegexpishString(random));
            String replacement = null;
            // ignore bugs in Sun's regex impl
            try {
                replacement = p.matcher(nonBmpString).replaceAll("_");
            } catch (StringIndexOutOfBoundsException jdkBug) {
                System.out.println("WARNING: your jdk is buggy!");
                System.out.println("Pattern.compile(\"" + p.pattern() + "\").matcher(\"AB\\uD840\\uDC00C\").replaceAll(\"_\"); should not throw IndexOutOfBounds!");
            }
            // unicode characters is a valid utf16 string. See LUCENE-4078 for discussion.
            if (replacement != null && UnicodeUtil.validUTF16String(replacement)) {
                return p;
            }
        } catch (PatternSyntaxException ignored) {
        // Loop trying until we hit something that compiles.
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 15 with PatternSyntaxException

use of java.util.regex.PatternSyntaxException in project maven-plugins by apache.

the class JavadocUtil method parseJavadocVersion.

/**
     * Parse the output for 'javadoc -J-version' and return the javadoc version recognized.
     * <br/>
     * 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 complète 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).*?[^a-zA-Z]([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).*?[^a-zA-Z]([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);
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Aggregations

PatternSyntaxException (java.util.regex.PatternSyntaxException)355 Pattern (java.util.regex.Pattern)190 Matcher (java.util.regex.Matcher)115 ArrayList (java.util.ArrayList)46 IOException (java.io.IOException)25 List (java.util.List)19 File (java.io.File)14 Map (java.util.Map)12 HashMap (java.util.HashMap)9 URL (java.net.URL)7 HashSet (java.util.HashSet)7 Iterator (java.util.Iterator)7 InvalidSettingsException (org.knime.core.node.InvalidSettingsException)7 BufferedReader (java.io.BufferedReader)6 Collection (java.util.Collection)6 LinkedList (java.util.LinkedList)5 Test (org.junit.Test)5 InputStreamReader (java.io.InputStreamReader)4 SQLException (java.sql.SQLException)4 LinkedHashMap (java.util.LinkedHashMap)4