Search in sources :

Example 21 with Pattern

use of java.util.regex.Pattern in project watson by totemo.

the class BlockEditSet method load.

// --------------------------------------------------------------------------
/**
   * Load additional entries from the specified file.
   *
   * @param file the file to load.
   * @return the number of edits loaded.
   */
public synchronized int load(File file) throws Exception {
    BufferedReader reader = new BufferedReader(new FileReader(file));
    try {
        Pattern editPattern = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})\\|(\\d{2}):(\\d{2}):(\\d{2})\\|(\\w+)\\|([cd])\\|(\\d+)\\|(\\d+)\\|(-?\\d+)\\|(\\d+)\\|(-?\\d+)");
        Pattern annoPattern = Pattern.compile("#(-?\\d+)\\|(\\d+)\\|(-?\\d+)\\|(.*)");
        Calendar time = Calendar.getInstance();
        String line;
        int edits = 0;
        BlockEdit blockEdit = null;
        while ((line = reader.readLine()) != null) {
            Matcher edit = editPattern.matcher(line);
            if (edit.matches()) {
                int year = Integer.parseInt(edit.group(1));
                int month = Integer.parseInt(edit.group(2)) - 1;
                int day = Integer.parseInt(edit.group(3));
                int hour = Integer.parseInt(edit.group(4));
                int minute = Integer.parseInt(edit.group(5));
                int second = Integer.parseInt(edit.group(6));
                time.set(year, month, day, hour, minute, second);
                String player = edit.group(7);
                boolean created = edit.group(8).equals("c");
                int id = Integer.parseInt(edit.group(9));
                int data = Integer.parseInt(edit.group(10));
                int x = Integer.parseInt(edit.group(11));
                int y = Integer.parseInt(edit.group(12));
                int z = Integer.parseInt(edit.group(13));
                BlockType type = BlockTypeRegistry.instance.getBlockTypeByIdData(id, data);
                blockEdit = new BlockEdit(time.getTimeInMillis(), player, created, x, y, z, type);
                addBlockEdit(blockEdit);
                ++edits;
            } else // if
            {
                // Is the line an annotation?
                Matcher anno = annoPattern.matcher(line);
                if (anno.matches()) {
                    int x = Integer.parseInt(anno.group(1));
                    int y = Integer.parseInt(anno.group(2));
                    int z = Integer.parseInt(anno.group(3));
                    String text = anno.group(4);
                    _annotations.add(new Annotation(x, y, z, text));
                }
            }
        }
        // If there was at least one BlockEdit, select it.
        if (blockEdit != null) {
            Controller.instance.selectBlockEdit(blockEdit);
        }
        return edits;
    } finally {
        reader.close();
    }
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) Calendar(java.util.Calendar) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader)

Example 22 with Pattern

use of java.util.regex.Pattern in project jvm-tools by aragozin.

the class ClassDumpSegment method getJavaClassesByRegExp.

Collection<JavaClass> getJavaClassesByRegExp(String regexp) {
    Iterator<JavaClass> classIt = createClassCollection().iterator();
    Collection<JavaClass> result = new ArrayList<JavaClass>(256);
    Pattern pattern = Pattern.compile(regexp);
    while (classIt.hasNext()) {
        ClassDump cls = (ClassDump) classIt.next();
        if (pattern.matcher(cls.getName()).matches()) {
            result.add(cls);
        }
    }
    return result;
}
Also used : Pattern(java.util.regex.Pattern) ArrayList(java.util.ArrayList)

Example 23 with Pattern

use of java.util.regex.Pattern in project bazel by bazelbuild.

the class ResourceUsageAnalyzer method keepPossiblyReferencedResources.

private void keepPossiblyReferencedResources() {
    if ((!foundGetIdentifier && !foundWebContent) || strings == null) {
        // to worry about string references to resources
        return;
    }
    if (!model.isSafeMode()) {
        // explicitly mark them as kept if necessary instead
        return;
    }
    List<String> sortedStrings = new ArrayList<String>(strings);
    Collections.sort(sortedStrings);
    logger.fine("android.content.res.Resources#getIdentifier present: " + foundGetIdentifier);
    logger.fine("Web content present: " + foundWebContent);
    logger.fine("Referenced Strings:");
    for (String string : sortedStrings) {
        string = string.trim().replace("\n", "\\n");
        if (string.length() > 40) {
            string = string.substring(0, 37) + "...";
        } else if (string.isEmpty()) {
            continue;
        }
        logger.fine("  " + string);
    }
    int shortest = Integer.MAX_VALUE;
    Set<String> names = Sets.newHashSetWithExpectedSize(50);
    for (Resource resource : model.getResources()) {
        String name = resource.name;
        names.add(name);
        int length = name.length();
        if (length < shortest) {
            shortest = length;
        }
    }
    for (String string : strings) {
        if (string.length() < shortest) {
            continue;
        }
        //  (4) If foundWebContent is true, look for android_res/ URL strings as well
        if (foundWebContent) {
            Resource resource = model.getResourceFromFilePath(string);
            if (resource != null) {
                ResourceUsageModel.markReachable(resource);
                continue;
            } else {
                int start = 0;
                int slash = string.lastIndexOf('/');
                if (slash != -1) {
                    start = slash + 1;
                }
                int dot = string.indexOf('.', start);
                String name = string.substring(start, dot != -1 ? dot : string.length());
                if (names.contains(name)) {
                    for (Map<String, Resource> map : model.getResourceMaps()) {
                        resource = map.get(name);
                        if (resource != null) {
                            logger.fine(String.format("Marking %s used because it matches string pool constant %s", resource, string));
                        }
                        ResourceUsageModel.markReachable(resource);
                    }
                }
            }
        }
        // Look for normal getIdentifier resource URLs
        int n = string.length();
        boolean justName = true;
        boolean formatting = false;
        boolean haveSlash = false;
        for (int i = 0; i < n; i++) {
            char c = string.charAt(i);
            if (c == '/') {
                haveSlash = true;
                justName = false;
            } else if (c == '.' || c == ':' || c == '%') {
                justName = false;
                if (c == '%') {
                    formatting = true;
                }
            } else if (!Character.isJavaIdentifierPart(c)) {
                // the {@link #referencedString} method
                assert false : string;
                break;
            }
        }
        String name;
        if (justName) {
            // Check name (below)
            name = string;
            // getResources().getIdentifier("ic_video_codec_" + codecName, "drawable", ...)
            for (Resource resource : model.getResources()) {
                if (resource.name.startsWith(name)) {
                    logger.fine(String.format("Marking %s used because its prefix matches string pool constant %s", resource, string));
                    ResourceUsageModel.markReachable(resource);
                }
            }
        } else if (!haveSlash) {
            if (formatting) {
                //   int res = getContext().getResources().getIdentifier(name, "drawable", ...)
                try {
                    Pattern pattern = Pattern.compile(convertFormatStringToRegexp(string));
                    for (Resource resource : model.getResources()) {
                        if (pattern.matcher(resource.name).matches()) {
                            logger.fine(String.format("Marking %s used because it format-string matches string pool constant %s", resource, string));
                            ResourceUsageModel.markReachable(resource);
                        }
                    }
                } catch (PatternSyntaxException ignored) {
                // Might not have been a formatting string after all!
                }
            }
            //noinspection UnnecessaryContinue
            continue;
        } else {
            // Try to pick out the resource name pieces; if we can find the
            // resource type unambiguously; if not, just match on names
            int slash = string.indexOf('/');
            // checked with haveSlash above
            assert slash != -1;
            name = string.substring(slash + 1);
            if (name.isEmpty() || !names.contains(name)) {
                continue;
            }
            // See if have a known specific resource type
            if (slash > 0) {
                int colon = string.indexOf(':');
                String typeName = string.substring(colon != -1 ? colon + 1 : 0, slash);
                ResourceType type = ResourceType.getEnum(typeName);
                if (type == null) {
                    continue;
                }
                Resource resource = model.getResource(type, name);
                if (resource != null) {
                    logger.fine(String.format("Marking %s used because it matches string pool constant %s", resource, string));
                }
                ResourceUsageModel.markReachable(resource);
                continue;
            }
        // fall through and check the name
        }
        if (names.contains(name)) {
            for (Map<String, Resource> map : model.getResourceMaps()) {
                Resource resource = map.get(name);
                if (resource != null) {
                    logger.fine(String.format("Marking %s used because it matches string pool constant %s", resource, string));
                }
                ResourceUsageModel.markReachable(resource);
            }
        } else if (Character.isDigit(name.charAt(0))) {
            // "android.resource://com.android.alarmclock/2130837524".
            try {
                int id = Integer.parseInt(name);
                if (id != 0) {
                    ResourceUsageModel.markReachable(model.getResource(id));
                }
            } catch (NumberFormatException e) {
            // pass
            }
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) ArrayList(java.util.ArrayList) Resource(com.android.tools.lint.checks.ResourceUsageModel.Resource) ResourceType(com.android.resources.ResourceType) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 24 with Pattern

use of java.util.regex.Pattern in project solo by b3log.

the class PermalinkQueryService method matchDefaultArticlePermalinkFormat.

/**
     * Checks whether the specified article permalink matches the system generated format 
     * pattern ("/articles/yyyy/MM/dd/${articleId}.html").
     * 
     * @param permalink the specified permalink
     * @return {@code true} if matches, returns {@code false} otherwise
     */
public static boolean matchDefaultArticlePermalinkFormat(final String permalink) {
    final Pattern pattern = Pattern.compile("/articles/\\d{4}/\\d{2}/\\d{2}/\\d+\\.html");
    final Matcher matcher = pattern.matcher(permalink);
    return matcher.matches();
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher)

Example 25 with Pattern

use of java.util.regex.Pattern in project Japid by branaway.

the class JapidAbstractCompilerTest method testOpentForPattern.

@Test
public void testOpentForPattern() {
    String forPattern = JapidAbstractCompiler.OPEN_FOR_PATTERN_STRING;
    Pattern p = JapidAbstractCompiler.OPEN_FOR_PATTERN;
    assertTrue("for String a:aaa ".matches(forPattern));
    assertFalse(" for String a : aaa".matches(forPattern));
    assertTrue("for String a : foo()".matches(forPattern));
    String string = "for String a : new foo.bar(){}";
    assertTrue(string.matches(forPattern));
    Matcher matcher = p.matcher(string);
    assertTrue(matcher.matches());
    assertEquals("String a", matcher.group(1).trim());
    assertEquals("new foo.bar(){}", matcher.group(2));
    assertFalse("for String a:aaa {".matches(forPattern));
    assertFalse("for(String a: aaa)  ".matches(forPattern));
    assertFalse("for(String a: aaa) { ".matches(forPattern));
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) Test(org.junit.Test)

Aggregations

Pattern (java.util.regex.Pattern)3181 Matcher (java.util.regex.Matcher)2116 ArrayList (java.util.ArrayList)387 IOException (java.io.IOException)247 Test (org.junit.Test)238 File (java.io.File)193 HashMap (java.util.HashMap)163 BufferedReader (java.io.BufferedReader)127 Field (java.lang.reflect.Field)119 PatternSyntaxException (java.util.regex.PatternSyntaxException)119 Map (java.util.Map)110 List (java.util.List)93 HashSet (java.util.HashSet)79 InputStreamReader (java.io.InputStreamReader)67 InputStream (java.io.InputStream)43 FileReader (java.io.FileReader)41 FileInputStream (java.io.FileInputStream)40 URL (java.net.URL)35 SmallTest (android.test.suitebuilder.annotation.SmallTest)31 LinkedHashMap (java.util.LinkedHashMap)31