Search in sources :

Example 41 with PatternSyntaxException

use of java.util.regex.PatternSyntaxException in project twicalico by moko256.

the class GlobalApplication method onCreate.

@Override
public void onCreate() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel("crash_log", getString(R.string.crash_log), NotificationManager.IMPORTANCE_DEFAULT);
        channel.setDescription(getString(R.string.crash_log_channel_description));
        channel.setLightColor(Color.RED);
        channel.enableLights(true);
        channel.setShowBadge(false);
        channel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (manager != null) {
            manager.createNotificationChannel(channel);
        }
    }
    final Thread.UncaughtExceptionHandler defaultUnCaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
        try {
            new ExceptionNotification().create(e, getApplicationContext());
        } catch (Throwable fe) {
            fe.printStackTrace();
        } finally {
            defaultUnCaughtExceptionHandler.uncaughtException(t, e);
        }
    });
    SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    configuration = new AppConfiguration();
    configuration.isPatternTweetMuteEnabled = defaultSharedPreferences.getBoolean("patternTweetMuteEnabled", false);
    if (configuration.isPatternTweetMuteEnabled) {
        try {
            configuration.tweetMutePattern = Pattern.compile(defaultSharedPreferences.getString("tweetMutePattern", ""));
        } catch (PatternSyntaxException e) {
            e.printStackTrace();
            configuration.isPatternTweetMuteEnabled = false;
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    configuration.isPatternTweetMuteShowOnlyImageEnabled = defaultSharedPreferences.getBoolean("patternTweetMuteShowOnlyImageEnabled", false);
    if (configuration.isPatternTweetMuteShowOnlyImageEnabled) {
        try {
            configuration.tweetMuteShowOnlyImagePattern = Pattern.compile(defaultSharedPreferences.getString("tweetMuteShowOnlyImagePattern", ""));
        } catch (PatternSyntaxException e) {
            e.printStackTrace();
            configuration.isPatternTweetMuteShowOnlyImageEnabled = false;
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    configuration.isPatternUserScreenNameMuteEnabled = defaultSharedPreferences.getBoolean("patternUserScreenNameMuteEnabled", false);
    if (configuration.isPatternUserScreenNameMuteEnabled) {
        try {
            configuration.userScreenNameMutePattern = Pattern.compile(defaultSharedPreferences.getString("userScreenNameMutePattern", ""));
        } catch (PatternSyntaxException e) {
            e.printStackTrace();
            configuration.isPatternUserScreenNameMuteEnabled = false;
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    configuration.isPatternUserNameMuteEnabled = defaultSharedPreferences.getBoolean("patternUserNameMuteEnabled", false);
    if (configuration.isPatternUserNameMuteEnabled) {
        try {
            configuration.userNameMutePattern = Pattern.compile(defaultSharedPreferences.getString("userNameMutePattern", ""));
        } catch (PatternSyntaxException e) {
            e.printStackTrace();
            configuration.isPatternUserNameMuteEnabled = false;
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    configuration.isPatternTweetSourceMuteEnabled = defaultSharedPreferences.getBoolean("patternTweetSourceMuteEnabled", false);
    if (configuration.isPatternTweetSourceMuteEnabled) {
        try {
            configuration.tweetSourceMutePattern = Pattern.compile(defaultSharedPreferences.getString("tweetSourceMutePattern", ""));
        } catch (PatternSyntaxException e) {
            e.printStackTrace();
            configuration.isPatternTweetSourceMuteEnabled = false;
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    configuration.isTimelineImageLoad = Boolean.valueOf(defaultSharedPreferences.getString("isTimelineImageLoad", "true"));
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    @AppCompatDelegate.NightMode int mode = AppCompatDelegate.MODE_NIGHT_NO;
    switch(defaultSharedPreferences.getString("nightModeType", "mode_night_no_value")) {
        case "mode_night_no":
            mode = AppCompatDelegate.MODE_NIGHT_NO;
            break;
        case "mode_night_auto":
            mode = AppCompatDelegate.MODE_NIGHT_AUTO;
            break;
        case "mode_night_follow_system":
            mode = AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM;
            break;
        case "mode_night_yes":
            mode = AppCompatDelegate.MODE_NIGHT_YES;
            break;
    }
    AppCompatDelegate.setDefaultNightMode(mode);
    String accountKey = defaultSharedPreferences.getString("AccountKey", "-1");
    if (accountKey.equals("-1"))
        return;
    TokenSQLiteOpenHelper tokenOpenHelper = new TokenSQLiteOpenHelper(this);
    AccessToken accessToken = tokenOpenHelper.getAccessToken(accountKey);
    tokenOpenHelper.close();
    if (accessToken == null)
        return;
    initTwitter(accessToken);
    super.onCreate();
}
Also used : NotificationManager(android.app.NotificationManager) SharedPreferences(android.content.SharedPreferences) NotificationChannel(android.app.NotificationChannel) AccessToken(com.github.moko256.twicalico.entity.AccessToken) ExceptionNotification(com.github.moko256.twicalico.notification.ExceptionNotification) AppConfiguration(com.github.moko256.twicalico.config.AppConfiguration) TokenSQLiteOpenHelper(com.github.moko256.twicalico.database.TokenSQLiteOpenHelper) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 42 with PatternSyntaxException

use of java.util.regex.PatternSyntaxException in project eclipse.platform.text by eclipse.

the class FindReplaceDocumentAdapterTest method testRegexFindLinebreakIllegal.

@Test
public void testRegexFindLinebreakIllegal() throws Exception {
    FindReplaceDocumentAdapter adapter = new FindReplaceDocumentAdapter(fDocument);
    fDocument.set("\n");
    IRegion region = null;
    try {
        region = adapter.find(0, "[\\R]", true, false, false, true);
    } catch (PatternSyntaxException e) {
    // expected
    }
    assertNull(region);
    try {
        region = adapter.find(0, "[\\s&&[^\\R]]", true, false, false, true);
    } catch (PatternSyntaxException e) {
    // expected
    }
    assertNull(region);
    try {
        region = adapter.find(0, "\\p{\\R}", true, false, false, true);
    } catch (PatternSyntaxException e) {
    // expected
    }
    assertNull(region);
}
Also used : FindReplaceDocumentAdapter(org.eclipse.jface.text.FindReplaceDocumentAdapter) IRegion(org.eclipse.jface.text.IRegion) PatternSyntaxException(java.util.regex.PatternSyntaxException) Test(org.junit.Test)

Example 43 with PatternSyntaxException

use of java.util.regex.PatternSyntaxException in project eclipse.platform.text by eclipse.

the class FindReplaceDocumentAdapterTest method testRegexFindStackOverflow_fail.

@Test
public void testRegexFindStackOverflow_fail() throws Exception {
    if (BUG_392594 && System.getProperty("os.name").indexOf("Mac") != -1)
        // VM crash on the Mac, see https://bugs.eclipse.org/392594
        return;
    FindReplaceDocumentAdapter adapter = new FindReplaceDocumentAdapter(fDocument);
    int len = 100000;
    char[] chars = new char[len];
    Arrays.fill(chars, '\n');
    chars[0] = '{';
    chars[len - 1] = '}';
    fDocument.set(new String(chars));
    try {
        adapter.find(0, "\\{(.|[\\r\\n])*\\}", true, false, false, true);
    } catch (PatternSyntaxException ex) {
        return;
    }
    fail();
}
Also used : FindReplaceDocumentAdapter(org.eclipse.jface.text.FindReplaceDocumentAdapter) PatternSyntaxException(java.util.regex.PatternSyntaxException) Test(org.junit.Test)

Example 44 with PatternSyntaxException

use of java.util.regex.PatternSyntaxException in project eclipse.platform.text by eclipse.

the class FindReplaceDocumentAdapter method interpretReplaceEscape.

/**
 * Interprets the escaped character <code>ch</code> at offset <code>i</code>
 * of the <code>replaceText</code> and appends the interpretation to <code>buf</code>.
 *
 * @param ch the escaped character
 * @param i the offset
 * @param buf the output buffer
 * @param replaceText the original replace pattern
 * @param foundText the found pattern to be replaced
 * @return the new offset
 * @since 3.4
 */
private int interpretReplaceEscape(final char ch, int i, StringBuilder buf, String replaceText, String foundText) {
    int length = replaceText.length();
    switch(ch) {
        case 'r':
            buf.append('\r');
            break;
        case 'n':
            buf.append('\n');
            break;
        case 't':
            buf.append('\t');
            break;
        case 'f':
            buf.append('\f');
            break;
        case 'a':
            buf.append('\u0007');
            break;
        case 'e':
            buf.append('\u001B');
            break;
        case // see http://www.unicode.org/unicode/reports/tr18/#Line_Boundaries
        'R':
            buf.append(TextUtilities.getDefaultLineDelimiter(fDocument));
            break;
        /*
			 * \0 for octal is not supported in replace string, since it
			 * would conflict with capturing group \0, etc.
			 */
        case '0':
            buf.append('$').append(ch);
            /*
				 * See explanation in "Feature in java.util.regex.Matcher#replaceFirst(String)"
				 * in interpretReplaceEscape(String) above.
				 */
            if (i + 1 < length) {
                char ch1 = replaceText.charAt(i + 1);
                if ('0' <= ch1 && ch1 <= '9') {
                    buf.append('\\');
                }
            }
            break;
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':
            buf.append('$').append(ch);
            break;
        case 'c':
            if (i + 1 < length) {
                char ch1 = replaceText.charAt(i + 1);
                interpretRetainCase(buf, (char) (ch1 ^ 64));
                i++;
            } else {
                // $NON-NLS-1$ //$NON-NLS-2$
                String msg = TextMessages.getFormattedString("FindReplaceDocumentAdapter.illegalControlEscape", "\\c");
                throw new PatternSyntaxException(msg, replaceText, i);
            }
            break;
        case 'x':
            if (i + 2 < length) {
                int parsedInt;
                try {
                    parsedInt = Integer.parseInt(replaceText.substring(i + 1, i + 3), 16);
                    if (parsedInt < 0)
                        throw new NumberFormatException();
                } catch (NumberFormatException e) {
                    // $NON-NLS-1$
                    String msg = TextMessages.getFormattedString("FindReplaceDocumentAdapter.illegalHexEscape", replaceText.substring(i - 1, i + 3));
                    throw new PatternSyntaxException(msg, replaceText, i);
                }
                interpretRetainCase(buf, (char) parsedInt);
                i += 2;
            } else {
                // $NON-NLS-1$
                String msg = TextMessages.getFormattedString("FindReplaceDocumentAdapter.illegalHexEscape", replaceText.substring(i - 1, length));
                throw new PatternSyntaxException(msg, replaceText, i);
            }
            break;
        case 'u':
            if (i + 4 < length) {
                int parsedInt;
                try {
                    parsedInt = Integer.parseInt(replaceText.substring(i + 1, i + 5), 16);
                    if (parsedInt < 0)
                        throw new NumberFormatException();
                } catch (NumberFormatException e) {
                    // $NON-NLS-1$
                    String msg = TextMessages.getFormattedString("FindReplaceDocumentAdapter.illegalUnicodeEscape", replaceText.substring(i - 1, i + 5));
                    throw new PatternSyntaxException(msg, replaceText, i);
                }
                interpretRetainCase(buf, (char) parsedInt);
                i += 4;
            } else {
                // $NON-NLS-1$
                String msg = TextMessages.getFormattedString("FindReplaceDocumentAdapter.illegalUnicodeEscape", replaceText.substring(i - 1, length));
                throw new PatternSyntaxException(msg, replaceText, i);
            }
            break;
        case 'C':
            if (// is whole match upper-case?
            foundText.toUpperCase().equals(foundText))
                fRetainCaseMode = RC_UPPER;
            else if (// is whole match lower-case?
            foundText.toLowerCase().equals(foundText))
                fRetainCaseMode = RC_LOWER;
            else if (// is first character upper-case?
            Character.isUpperCase(foundText.charAt(0)))
                fRetainCaseMode = RC_FIRSTUPPER;
            else
                fRetainCaseMode = RC_MIXED;
            break;
        default:
            // unknown escape k: append uninterpreted \k
            buf.append('\\').append(ch);
            break;
    }
    return i;
}
Also used : PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 45 with PatternSyntaxException

use of java.util.regex.PatternSyntaxException in project eclipse.platform.text by eclipse.

the class FindReplaceDocumentAdapter method findReplace.

/**
 * Stateful findReplace executes a FIND, REPLACE, REPLACE_FIND or FIND_FIRST operation.
 * In case of REPLACE and REPLACE_FIND it sends a <code>DocumentEvent</code> to all
 * registered <code>IDocumentListener</code>.
 *
 * @param startOffset document offset at which search starts
 * 			this value is only used in the FIND_FIRST operation and otherwise ignored
 * @param findString the string to find
 * 			this value is only used in the FIND_FIRST operation and otherwise ignored
 * @param replaceText the string to replace the current match
 * 			this value is only used in the REPLACE and REPLACE_FIND operations and otherwise ignored
 * @param forwardSearch the search direction
 * @param caseSensitive indicates whether lower and upper case should be distinguished
 * @param wholeWord indicates whether the findString should be limited by white spaces as
 * 			defined by Character.isWhiteSpace. Must not be used in combination with <code>regExSearch</code>.
 * @param regExSearch if <code>true</code> this operation represents a regular expression
 * 			Must not be used in combination with <code>wholeWord</code>.
 * @param operationCode specifies what kind of operation is executed
 * @return the find or replace region or <code>null</code> if there was no match
 * @throws BadLocationException if startOffset is an invalid document offset
 * @throws IllegalStateException if a REPLACE or REPLACE_FIND operation is not preceded by a successful FIND operation
 * @throws PatternSyntaxException if a regular expression has invalid syntax
 */
private IRegion findReplace(final FindReplaceOperationCode operationCode, int startOffset, String findString, String replaceText, boolean forwardSearch, boolean caseSensitive, boolean wholeWord, boolean regExSearch) throws BadLocationException {
    // Validate option combinations
    Assert.isTrue(!(regExSearch && wholeWord));
    // Validate state
    if ((operationCode == REPLACE || operationCode == REPLACE_FIND_NEXT) && (fFindReplaceState != FIND_FIRST && fFindReplaceState != FIND_NEXT))
        // $NON-NLS-1$
        throw new IllegalStateException("illegal findReplace state: cannot replace without preceding find");
    if (operationCode == FIND_FIRST) {
        if (findString == null || findString.length() == 0)
            return null;
        // Validate start offset
        if (startOffset < 0 || startOffset > length())
            throw new BadLocationException();
        int patternFlags = 0;
        if (regExSearch) {
            patternFlags |= Pattern.MULTILINE;
            findString = substituteLinebreak(findString);
        }
        if (!caseSensitive)
            patternFlags |= Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE;
        if (!regExSearch)
            findString = asRegPattern(findString);
        if (wholeWord)
            // $NON-NLS-1$ //$NON-NLS-2$
            findString = "\\b" + findString + "\\b";
        fFindReplaceMatchOffset = startOffset;
        if (fFindReplaceMatcher != null && fFindReplaceMatcher.pattern().pattern().equals(findString) && fFindReplaceMatcher.pattern().flags() == patternFlags) {
        /*
				 * Commented out for optimization:
				 * The call is not needed since FIND_FIRST uses find(int) which resets the matcher
				 */
        // fFindReplaceMatcher.reset();
        } else {
            Pattern pattern = Pattern.compile(findString, patternFlags);
            fFindReplaceMatcher = pattern.matcher(this);
        }
    }
    // Set state
    fFindReplaceState = operationCode;
    if (operationCode == REPLACE || operationCode == REPLACE_FIND_NEXT) {
        if (regExSearch) {
            Pattern pattern = fFindReplaceMatcher.pattern();
            String prevMatch = fFindReplaceMatcher.group();
            try {
                replaceText = interpretReplaceEscapes(replaceText, prevMatch);
                Matcher replaceTextMatcher = pattern.matcher(this);
                replaceTextMatcher.find(fFindReplaceMatcher.start());
                StringBuffer sb = new StringBuffer();
                replaceTextMatcher.appendReplacement(sb, replaceText);
                replaceText = sb.substring(fFindReplaceMatcher.start());
            } catch (IndexOutOfBoundsException ex) {
                throw new PatternSyntaxException(ex.getLocalizedMessage(), replaceText, -1);
            }
        }
        int offset = fFindReplaceMatcher.start();
        int length = fFindReplaceMatcher.group().length();
        if (fDocument instanceof IRepairableDocumentExtension && ((IRepairableDocumentExtension) fDocument).isLineInformationRepairNeeded(offset, length, replaceText)) {
            // $NON-NLS-1$
            String message = TextMessages.getString("FindReplaceDocumentAdapter.incompatibleLineDelimiter");
            throw new PatternSyntaxException(message, replaceText, offset);
        }
        fDocument.replace(offset, length, replaceText);
        if (operationCode == REPLACE) {
            return new Region(offset, replaceText.length());
        }
    }
    if (operationCode != REPLACE) {
        try {
            if (forwardSearch) {
                boolean found = false;
                if (operationCode == FIND_FIRST)
                    found = fFindReplaceMatcher.find(startOffset);
                else
                    found = fFindReplaceMatcher.find();
                if (operationCode == REPLACE_FIND_NEXT)
                    fFindReplaceState = FIND_NEXT;
                if (found && fFindReplaceMatcher.group().length() > 0)
                    return new Region(fFindReplaceMatcher.start(), fFindReplaceMatcher.group().length());
                return null;
            }
            // backward search
            boolean found = fFindReplaceMatcher.find(0);
            int index = -1;
            int length = -1;
            while (found && fFindReplaceMatcher.start() + fFindReplaceMatcher.group().length() <= fFindReplaceMatchOffset + 1) {
                index = fFindReplaceMatcher.start();
                length = fFindReplaceMatcher.group().length();
                found = fFindReplaceMatcher.find(index + 1);
            }
            fFindReplaceMatchOffset = index;
            if (index > -1) {
                // must set matcher to correct position
                fFindReplaceMatcher.find(index);
                return new Region(index, length);
            }
            return null;
        } catch (StackOverflowError e) {
            // $NON-NLS-1$
            String message = TextMessages.getString("FindReplaceDocumentAdapter.patternTooComplex");
            throw new PatternSyntaxException(message, findString, -1);
        }
    }
    return null;
}
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