@SuppressLint("WorldReadableFiles")
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
      // NOTE: this function is *always* called from a background thread, and
      // not the UI thread.

      ArrayList<ApplicationInfo> items = new ArrayList<ApplicationInfo>();
      synchronized (this) {
        items.addAll(appList);
      }

      SharedPreferences prefs = getSharedPreferences(Common.PREFS, Context.MODE_WORLD_READABLE);

      FilterResults result = new FilterResults();
      if (constraint != null && constraint.length() > 0) {
        Pattern regexp =
            Pattern.compile(constraint.toString(), Pattern.LITERAL | Pattern.CASE_INSENSITIVE);
        for (Iterator<ApplicationInfo> i = items.iterator(); i.hasNext(); ) {
          ApplicationInfo app = i.next();
          if (!regexp.matcher(app.name == null ? "" : app.name).find()
              && !regexp.matcher(app.packageName).find()) {
            i.remove();
          }
        }
      }
      for (Iterator<ApplicationInfo> i = items.iterator(); i.hasNext(); ) {
        ApplicationInfo app = i.next();
        if (filteredOut(prefs, app)) i.remove();
      }

      result.values = items;
      result.count = items.size();

      return result;
    }
Esempio n. 2
0
  boolean isManaged(File file) {
    log("isManaged() " + file);

    if (file == null) {
      return false;
    }
    String path = file.getAbsolutePath();
    if (metadataPattern.matcher(path).matches()) {
      return false;
    }

    if (lhTmpFilePattern.matcher(path).matches()) {
      return false;
    }

    if (includeFiles != null) {
      return includeFiles.matcher(path).matches();
    }

    if (excludeFiles != null) {
      return !excludeFiles.matcher(path).matches();
    }

    return true;
  }
Esempio n. 3
0
 private String cleanXSS(String paramString) {
   if (paramString == null) {
     return "";
   }
   String str = paramString.toLowerCase();
   str = str.replaceAll("", "");
   Pattern localPattern = Pattern.compile("<script>(.*?)</script>", 2);
   str = localPattern.matcher(str).replaceAll("");
   localPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\'(.*?)\\'", 42);
   str = localPattern.matcher(str).replaceAll("");
   localPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", 42);
   str = localPattern.matcher(str).replaceAll("");
   localPattern = Pattern.compile("</script>", 2);
   str = localPattern.matcher(str).replaceAll("");
   localPattern = Pattern.compile("<script(.*?)>", 42);
   str = localPattern.matcher(str).replaceAll("");
   localPattern = Pattern.compile("eval\\((.*?)\\)", 42);
   str = localPattern.matcher(str).replaceAll("");
   localPattern = Pattern.compile("expression\\((.*?)\\)", 42);
   str = localPattern.matcher(str).replaceAll("");
   localPattern = Pattern.compile("javascript:", 2);
   str = localPattern.matcher(str).replaceAll("");
   localPattern = Pattern.compile("vbscript:", 2);
   str = localPattern.matcher(str).replaceAll("");
   localPattern = Pattern.compile("onload(.*?)=", 42);
   str = localPattern.matcher(str).replaceAll("");
   str = str.replaceAll("\\(", "&#40;").replaceAll("\\)", "&#41;");
   str = str.replaceAll("'", this.apostrophe);
   str = str.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
   return str;
 }
  private List<String> findRelativeURLs(StringBuffer buf) {
    List<String> uris = new ArrayList<String>();

    if (buf.indexOf("<wsdl:") < 0) { // $NON-NLS-1$
      Pattern pattern = Pattern.compile("(<import)(.*)( schemaLocation=\")([^\"]+)"); // $NON-NLS-1$
      Matcher matcher = pattern.matcher(buf);
      while (matcher.find()) {
        String relativeURLString = matcher.group(4);
        uris.add(relativeURLString);
      }

      pattern = Pattern.compile("(<import schemaLocation=\")([^\"]+)"); // $NON-NLS-1$
      matcher = pattern.matcher(buf);
      while (matcher.find()) {
        String relativeURLString = matcher.group(2);
        uris.add(relativeURLString);
      }
    } else {
      Pattern pattern =
          Pattern.compile("(<xsd:import)(.*)( schemaLocation=\")([^\"]+)"); // $NON-NLS-1$
      Matcher matcher = pattern.matcher(buf);
      while (matcher.find()) {
        String relativeURLString = matcher.group(4);
        uris.add(relativeURLString);
      }
      pattern = Pattern.compile("(<xsd:import schemaLocation=\")([^\"]+)"); // $NON-NLS-1$
      matcher = pattern.matcher(buf);
      while (matcher.find()) {
        String relativeURLString = matcher.group(2);
        uris.add(relativeURLString);
      }
    }
    return uris;
  }
  private boolean isValidPort(String text) {
    if (StringUtils.isBlank(text)) return false;
    String[] ports = text.trim().split(",");
    boolean ok = false;
    // linux (and OSX?)
    if (SystemUtils.IS_OS_LINUX || SystemUtils.IS_OS_MAC_OSX) {
      // each will be /dev/tty* or /dev/cu*
      for (String port : ports) {
        if (StringUtils.isBlank(port)) continue;
        if (portNamesRegexLinux.matcher(port.trim()).matches()) {
          // must be at least one good
          ok = true;
        } else {
          // doesnt match, its bad so outa here.
          return false;
        }
      }
    }

    // windows
    if (SystemUtils.IS_OS_WINDOWS) {
      // each will be COM*
      for (String port : ports) {
        if (StringUtils.isBlank(port)) continue;
        if (portNamesRegexWindows.matcher(port.trim()).matches()) {
          // must be at least one good
          ok = true;
        } else {
          // doesnt match, its bad so outa here.
          return false;
        }
      }
    }
    return ok;
  }
  /**
   * Returns the browser given by the specified browser string
   *
   * @param browser a browser string like "*firefox"
   * @param sessionId the sessionId to launch
   * @param queue
   * @return the BrowserLauncher ready to launch
   */
  public BrowserLauncher getBrowserLauncher(String browser, String sessionId, SeleneseQueue queue) {
    if (browser == null) throw new IllegalArgumentException("browser may not be null");

    for (Iterator iterator = supportedBrowsers.entrySet().iterator(); iterator.hasNext(); ) {
      Map.Entry entry = (Map.Entry) iterator.next();
      String name = (String) entry.getKey();
      Class c = (Class) entry.getValue();
      Pattern pat = Pattern.compile("^\\*" + name + "( .*)?$");
      Matcher mat = pat.matcher(browser);
      if (mat.find()) {
        String browserStartCommand;
        if (browser.equals("*" + name)) {
          browserStartCommand = null;
        } else {
          browserStartCommand = mat.group(1).substring(1);
        }
        return createBrowserLauncher(c, browserStartCommand, sessionId, queue);
      }
    }
    Matcher CustomMatcher = CUSTOM_PATTERN.matcher(browser);
    if (CustomMatcher.find()) {
      String browserStartCommand = CustomMatcher.group(1).substring(1);
      return new DestroyableRuntimeExecutingBrowserLauncher(browserStartCommand, sessionId);
    }
    throw browserNotSupported(browser);
  }
Esempio n. 7
0
  /**
   * 把参数名转换为字段名,把中文转换为拼音,特殊字符转换为下划线
   *
   * @param string
   * @return
   */
  public static String pinyin(String string) {
    Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5]");
    Pattern pattern2 = Pattern.compile("^\\w+$");
    char ch[] = string.toCharArray();
    StringBuffer sb = new StringBuffer();

    for (int i = 0; i < ch.length; i++) {
      String t = String.valueOf(ch[i]);
      Matcher matcher = pattern.matcher(t);
      Matcher matcher2 = pattern2.matcher(t);
      if (matcher.find()) { // 匹配中文
        String pinyin =
            PinyinHelper.toHanyuPinyinStringArray(matcher.group().toCharArray()[0])[0]
                .replaceAll("\\d+", "")
                .replace("u:", "v");
        sb.append(pinyin);
      } else {
        if (matcher2.find()) { // 匹配字母数字下划线

        } else {
          t = "_";
        }
        sb.append(t);
      }
    }

    return sb.toString();
  }
Esempio n. 8
0
  public static Boolean evaluate(String string, String regex, int flags, Navigator navigator) {

    ThreadLocalCache<Map<String, Pattern>> threadLocalPatterns =
        ThreadLocalCacheManager.getThreadLocalCache(
            Lifecycle.ETERNAL, MatchesFunction.class.getName());

    Map<String, Pattern> patterns = threadLocalPatterns.get(_THREAD_LOCAL_PATTERNS_KEY);

    if (patterns == null) {
      patterns = new HashMap<String, Pattern>();
    }

    Pattern pattern = patterns.get(regex);

    if (pattern != null) {
      Matcher matcher = pattern.matcher(string);

      return matcher.find();
    }

    pattern = Pattern.compile(regex, flags);

    patterns.put(regex, pattern);

    threadLocalPatterns.put(_THREAD_LOCAL_PATTERNS_KEY, patterns);

    Matcher matcher = pattern.matcher(string);

    return matcher.find();
  }
Esempio n. 9
0
 private String normalizeCountList(String str) {
   ArrayList<String> chunkedtokens = new ArrayList<String>(Arrays.asList(str.split("\\s+")));
   String countp = "one|two|three|four|five|six|seven|eight|nine|ten|more|fewer";
   Pattern p = Pattern.compile("(\\b(?:" + countp + ") (?:or|to) (?:" + countp + ")\\b)");
   Matcher m = p.matcher(str);
   while (m.find()) {
     int start = m.start(1);
     int end = m.end(1);
     String count = m.group(1);
     String rcount = "{count~list~" + count.replaceAll(" ", "~") + "}";
     // synchronise this.chunkedtokens
     // split by single space to get an accurate count to elements that would be in chunkedtokens
     int index =
         (str.substring(0, start).trim() + " a").trim().split("\\s").length
             - 1; // number of tokens before the count pattern
     chunkedtokens.set(index, rcount);
     int num = count.split("\\s+").length;
     for (int i = index + 1; i < index + num; i++) {
       chunkedtokens.set(i, "");
     }
     // resemble the str from chunkedtokens, counting all empty elements, so the str and
     // chunkedtokens are in synch.
     str = "";
     for (String t : chunkedtokens) {
       str += t + " ";
     }
     m = p.matcher(str);
   }
   return str.replaceAll("\\s+", " ").trim();
 }
  /**
   * Handles DROP TABLE. Drop table suppresses comments so we instead add a fake table with the
   * comment in the following form:
   *
   * <pre><code>
   *    DROP TABLE, TUNGSTEN_INFO.`comment text`, othertable1, othertable2,...
   * </code></pre>
   *
   * This requires special handling to ensure we deal with multiple tables, comments in the DROP
   * TABLE command, and extra syntax like IF EXISTS.
   *
   * @param statement DROP TABLE statement that requires a comment to be inserted.
   * @param comment Comment string to be added.
   */
  private String processDropTable(String statement, String comment) {
    // Ensure we don't edit in the values twice. Look for the edit
    // values and skip out if they are already there.
    if (statement.contains(" TUNGSTEN_INFO.`")) return statement;

    // Now process the edit, since it has not been done before.
    Matcher m = ifExistsPattern.matcher(statement);
    boolean foundIfExists = m.find();
    if (foundIfExists) {
      // This is the easy case. Split the DROP table and put our
      // comment in between.
      String before = m.group(1);
      String after = m.group(2);
      String newStatement = before + " TUNGSTEN_INFO.`" + comment + "`, " + after;
      return newStatement;
    } else {
      // This is trickier. We need to split the statement before the
      // first table name and add our comment preceded by IF EXISTS.
      // Another regex to the rescue. This regex much split properly even
      // there are comments embedded in the DROP TABLE or multiple
      // tables.
      Matcher m2 = dropTable.matcher(statement);
      if (m2.find()) {
        String before = m2.group(1);
        String after = m2.group(2);
        String newStatement = before + " IF EXISTS TUNGSTEN_INFO.`" + comment + "`, " + after;
        return newStatement;
      }
    }

    // We didn't succeed in matching. We'll hand back the original statement
    // and hope for the best.
    return statement;
  }
  public static Map<String, Long> decodeVersioningMap(String in) {
    // Cleaning up
    Map<String, Long> out = new HashMap<String, Long>();
    if (in == null || in.isEmpty()) {
      return null;
    }
    String inMod = in.trim();
    inMod = leftTrimP.matcher(inMod).replaceFirst("");
    inMod = rightTrimP.matcher(inMod).replaceFirst("");

    // The value should look like this: <proj>=<ver>;<proj>=ver;...
    for (String entry : inMod.split(";")) {
      Matcher m = keyValP.matcher(entry);
      while (m.find()) {
        String key = m.group(1);
        if (key == null || key.isEmpty()) {
          continue;
        }
        String value = m.group(2);
        if (value == null || value.isEmpty()) {
          continue;
        }
        try {
          Long lv = Long.parseLong(value);
          // Trying to add this to the version map
          out.put(key, lv);
        } catch (NumberFormatException ex) {
          continue;
        }
      }
    }
    return out;
  }
 /**
  * Applies the exclude and include filters to the found annotations.
  *
  * @param allAnnotations all annotations
  * @return the filtered annotations if there is a filter defined
  */
 private List<FileAnnotation> applyFilters(final List<FileAnnotation> allAnnotations) {
   List<FileAnnotation> includedAnnotations;
   if (includePatterns.isEmpty()) {
     includedAnnotations = allAnnotations;
   } else {
     includedAnnotations = new ArrayList<FileAnnotation>();
     for (FileAnnotation annotation : allAnnotations) {
       for (Pattern include : includePatterns) {
         if (include.matcher(annotation.getFileName()).matches()) {
           includedAnnotations.add(annotation);
         }
       }
     }
   }
   if (excludePatterns.isEmpty()) {
     return includedAnnotations;
   } else {
     List<FileAnnotation> excludedAnnotations = new ArrayList<FileAnnotation>(includedAnnotations);
     for (FileAnnotation annotation : includedAnnotations) {
       for (Pattern exclude : excludePatterns) {
         if (exclude.matcher(annotation.getFileName()).matches()) {
           excludedAnnotations.remove(annotation);
         }
       }
     }
     return excludedAnnotations;
   }
 }
  /**
   * This method is used to help in converting a complex object's data into a JSON string
   *
   * @param data The submitted data as a string
   * @return The JSON equivalent of the submitted string
   */
  private String applyRegEx(String data) {
    // regular expresion for getting property names
    String elementPart = "([\\w]*:)";

    // regular expression for getting the values
    String elValuePart = "(:)([\\w]*)";

    // apply regular expressions to patterns
    Pattern elPattern = Pattern.compile(elementPart);
    Pattern valPattern = Pattern.compile(elValuePart);

    // get matchers to use patterns to match the data/String
    Matcher elMatcher = elPattern.matcher(data);
    Matcher vMatcher = valPattern.matcher(data);
    while (elMatcher.find()) // handles value part
    {
      String element = elMatcher.group();
      data = StringUtils.replaceOnce(data, element, "\"" + element.replace(":", "\":"));
    }
    while (vMatcher.find()) // handles the value part
    {
      String value = vMatcher.group();
      value = StringUtils.remove(value, ":");
      if (!StringUtils.isNumeric(value)
          && // not a number
          !StringUtils.equals(value, "true")
          && // not a boolean value
          !StringUtils.equals(value, "false")) // not a boolean value
      {
        if (StringUtils.isEmpty(value)) data = data.replace(":,", ":null,");
        else data = StringUtils.replaceOnce(data, value, "\"" + value + "\"");
      }
    }
    return data;
  }
 private Multiplier multiplier(String expression, int offset) {
   Matcher matcher = MULTIPLIER_PREFIX_PATTERN.matcher(expression);
   if (!matcher.find()) {
     return null;
   }
   if (matcher.start() > 0) {
     fail(offset + matcher.start(), "illegal multiplier position");
   }
   Matcher digitMatcher = DIGIT_PATTERN.matcher(expression);
   if (!digitMatcher.find()) {
     return null;
   }
   String digitStr = expression.substring(0, digitMatcher.end());
   int number = 0;
   try {
     number = Integer.parseInt(digitStr);
   } catch (NumberFormatException e) {
     fail(offset, e);
   }
   if (number <= 0) {
     fail(offset, "illegal 0 multiplier");
   }
   String subexpression = expression.substring(matcher.end(), expression.length() - 1);
   return new Multiplier(number, subexpression, matcher.end());
 }
Esempio n. 15
0
  /**
   * Analyze ping results. Compare number of tolerated lost packets to actual lost packets. Note
   * that the analyzer does not use the expected number packets for analysis but for reporting only.
   */
  public void analyze() {

    String text = (String) testAgainst;

    status = true;
    if (text == null) {
      title = "null testAgainst";
      status = false;
      return;
    }
    message = text;

    // First check if the ping results are in Windows format
    Pattern p =
        Pattern.compile(
            "Sent\\s*=\\s*(\\d+),\\s*Received\\s*=\\s*(\\d+),\\s*Lost\\s*=\\s*\\d+\\s*\\((\\d+)%.*Minimum\\s*=\\s*(\\d+).*Maximum\\s*=\\s*(\\d+).*Average\\s*=\\s*(\\d+)",
            Pattern.DOTALL);
    Matcher m = p.matcher(text);
    if (!m.find()) {
      // If not, check if the ping results are in Windows format
      p =
          Pattern.compile(
              "---\\s*\\n(\\d*)\\s*packets transmitted,\\s*(\\d*)\\s*received,\\s*(\\d*)%");
      m = p.matcher(text);
      if (!m.find()) {
        // If not Windows, nor Linux, give up
        title = "Unknown ping output format";
        status = false;
        return;
      }
    }

    // Retrieve raw data from ping results
    sent = Integer.parseInt(m.group(1));
    received = Integer.parseInt(m.group(2));
    lost = Integer.parseInt(m.group(3));
    min = Integer.parseInt(m.group(4));
    max = Integer.parseInt(m.group(5));
    average = Integer.parseInt(m.group(6));

    /*
     * Compare number of tolerated lost packets to actual lost packets.
     */
    if (lost > expected) {
      status = false;
    }

    title =
        "Packets: Expected "
            + expected
            + "% lost. Sent = "
            + sent
            + ", Received = "
            + received
            + ", Lost = "
            + lost
            + "%"
            + ", Average = "
            + average;
  }
    public boolean matches(String extension) {
        switch (matchType) {
        case IS:
            for (Pattern o : this.list) {
                try {
                    if (o.matcher(extension).matches()) return true;
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
            return false;
        case IS_NOT:
            for (Pattern o : this.list) {
                try {
                    if (o.matcher(extension).matches()) return false;
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
            return true;

        }

        return false;
    }
Esempio n. 17
0
    private void extractUsedProperties(String text) {
      Pattern p1 = Pattern.compile("\\$\\{([^@$}]*)\\}");
      Matcher m1 = p1.matcher(text);
      log(text, Project.MSG_DEBUG);
      while (m1.find()) {
        String group = m1.group(1);
        if (!propertyList.contains(group)) {
          propertyList.add(group);
        }
        log("property matches: " + group, Project.MSG_DEBUG);
      }

      Pattern p2 = Pattern.compile("\\$\\{([^\n]*\\})\\}");
      Matcher m2 = p2.matcher(text);
      log(text, Project.MSG_DEBUG);
      while (m2.find()) {
        String group = m2.group(1);
        if (!propertyList.contains(group)) {
          propertyList.add(group);
        }
        log("property matches: " + group, Project.MSG_DEBUG);
      }

      Pattern p3 = Pattern.compile("\\$\\{(\\@\\{[^\n]*)\\}");
      Matcher m3 = p3.matcher(text);
      log(text, Project.MSG_DEBUG);
      while (m3.find()) {
        String group = m3.group(1);
        if (!propertyList.contains(group)) {
          propertyList.add(group);
        }
        log("property matches: " + group, Project.MSG_DEBUG);
      }
    }
 private String replaceEscapedLiterals(String resolvedMessage) {
   resolvedMessage = LEFT_BRACE.matcher(resolvedMessage).replaceAll("{");
   resolvedMessage = RIGHT_BRACE.matcher(resolvedMessage).replaceAll("}");
   resolvedMessage = SLASH.matcher(resolvedMessage).replaceAll(Matcher.quoteReplacement("\\"));
   resolvedMessage = DOLLAR.matcher(resolvedMessage).replaceAll(Matcher.quoteReplacement("$"));
   return resolvedMessage;
 }
  protected Map<String, String> getAttributes() {
    if (attributes != null) {
      return attributes;
    }

    attributes = new HashMap<String, String>();

    matcher = ADDITIONAL_ATTRIBUTES_PATTERN.matcher(firstLine);
    if (matcher.find()) {
      String s;
      Matcher attributeMatcher;

      s = matcher.group(2);
      attributeMatcher = ADDITIONAL_ATTRIBUTE_PATTERN.matcher(s);
      while (attributeMatcher.find()) {
        String key;
        String value;

        key = attributeMatcher.group(1);
        value = attributeMatcher.group(2);
        attributes.put(key.toLowerCase(Locale.ENGLISH), value);
      }
    }
    return attributes;
  }
Esempio n. 20
0
 @Override
 public TestCaseResult test(Project project, boolean autoGrade)
     throws NotAutomatableException, NotGradableException {
   RunningProject noInfo = RunningProjectUtils.runProject(project, 10, "ba");
   String noInfoOutput = noInfo.await();
   boolean hasMessage = false;
   boolean askAgain = false;
   if (noInfoOutput.toLowerCase().contains("not enough information")) hasMessage = true;
   String[] splittedNoInfoOutput = noInfoOutput.split("\n");
   int length = splittedNoInfoOutput.length;
   Pattern genecrap = Pattern.compile(".*gene|seq|anoth.*");
   if (genecrap.matcher(splittedNoInfoOutput[length - 1]).find()
       || genecrap.matcher(splittedNoInfoOutput[length - 2]).find()) askAgain = true;
   if (askAgain && hasMessage) return pass();
   if (!askAgain && !hasMessage)
     return fail("did not print out notification correctly nor asked for gene input");
   int numwrong = 0;
   String graderMessage = "";
   if (!hasMessage) {
     graderMessage += "Did not print out the notification exactly as prompt states.";
     numwrong++;
   }
   if (!askAgain) {
     graderMessage += "Does not ask for another gene input";
     numwrong++;
   }
   return partialPass(0.5, graderMessage);
 }
Esempio n. 21
0
    @Override
    public void output(int id, String line) {
      // general check if line contains file
      if (line.contains(fileName)) {

        // try to match line exactly
        try {
          Matcher permissionMatcher = permissionPattern.matcher(line);
          if (permissionMatcher.find()) {
            permissions = convertPermissions(permissionMatcher.group(1));

            Log.d(RootCommands.TAG, "Found permissions: " + permissions);
          } else {
            Log.d(RootCommands.TAG, "Permissions were not found in ls command!");
          }

          // try to parse for symlink
          Matcher symlinkMatcher = symlinkPattern.matcher(line);
          if (symlinkMatcher.find()) {
            /*
             * TODO: If symlink points to a file in the same directory the path is not
             * absolute!!!
             */
            symlink = symlinkMatcher.group(1);
            Log.d(RootCommands.TAG, "Symlink found: " + symlink);
          } else {
            Log.d(RootCommands.TAG, "No symlink found!");
          }
        } catch (Exception e) {
          Log.e(RootCommands.TAG, "Error with regex!", e);
        }
      }
    }
Esempio n. 22
0
 /** @desc 初始化 */
 public void initMethods() {
   getMethods = new Hashtable<String, Method>();
   setMethods = new Hashtable<String, Method>();
   cls = obj.getClass();
   Method[] methods = cls.getMethods();
   // 定义正则表达式,从方法中过滤出getter / setter 函数.
   String gs = "get(\\w+)";
   Pattern getM = Pattern.compile(gs);
   String ss = "set(\\w+)";
   Pattern setM = Pattern.compile(ss);
   // 把方法中的"set" 或者 "get" 去掉
   String rapl = "$1";
   String param;
   for (int i = 0; i < methods.length; ++i) {
     Method m = methods[i];
     String methodName = m.getName();
     if (Pattern.matches(gs, methodName)) {
       param = getM.matcher(methodName).replaceAll(rapl).toLowerCase();
       getMethods.put(param, m);
     } else if (Pattern.matches(ss, methodName)) {
       param = setM.matcher(methodName).replaceAll(rapl).toLowerCase();
       setMethods.put(param, m);
     } else {
       // System.out.println(methodName + " 不是getter,setter方法!");
     }
   }
 }
Esempio n. 23
0
 private String getTextNodeText(TextNode tn, boolean normalText) {
   String input = normalText ? tn.text() : tn.getWholeText();
   Node prev = tn.previousSibling();
   Node next = tn.nextSibling();
   boolean parentIsBlock = isBlock(tn.parent());
   if (isBlock(prev)) {
     input = ltrim(input);
   } else if (prev == null && parentIsBlock) {
     input = ltrim(input);
   } else if (normalText && prev instanceof TextNode) {
     TextNode tprev = (TextNode) prev;
     if (EMPTY_MATCHER.matcher(tprev.text()).matches()) {
       input = ltrim(input);
     }
   }
   if (input.length() > 0) {
     if (isBlock(next)) {
       input = rtrim(input);
     } else if (next == null && parentIsBlock) {
       input = rtrim(input);
     } else if (normalText && next instanceof TextNode) {
       TextNode tnext = (TextNode) next;
       if (EMPTY_MATCHER.matcher(tnext.text()).matches()) {
         input = rtrim(input);
       }
     }
   }
   return input;
 }
 public Set<Integer> parseRanges(Collection<String> ranges) {
   Set<Integer> result = new TreeSet<>();
   for (String range : ranges) {
     range = range.trim();
     if (range.isEmpty()) {
       continue;
     }
     Matcher matcher;
     if (SINGLE_YEAR_PATTERN.matcher(range).matches()) {
       result.add(Integer.parseInt(range));
     } else if ((matcher = FULL_RANGE_YEAR_PATTERN.matcher(range)).matches()) {
       result.addAll(
           range(Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2))));
     } else if ((matcher = SHORTEN_RANGE_YEAR_PATTERN.matcher(range)).matches()) {
       int start = Integer.parseInt(matcher.group(1));
       int end = Integer.parseInt(matcher.group(1).substring(0, 2) + matcher.group(2));
       result.addAll(range(start, end));
     } else if ((matcher = LIST_YEAR_PATTERN.matcher(range)).matches()) { // 1989,1990,1991
       String[] years = matcher.group(0).split(",");
       for (String year : years) {
         result.add(Integer.parseInt(year));
       }
     } else if ((matcher = FOUR_DIGIT_YEAR_PATTERN.matcher(range)).find()) {
       int year = Integer.parseInt(matcher.group(0));
       if (year == 9999) year = MAX_YEAR;
       result.add(year);
     } else {
       //				logger.warn("Range '{}' not matched", range);
     }
   }
   return result;
 }
Esempio n. 25
0
  @Override
  public List<String> getCphNameList(boolean toLowerCase) {
    Pattern pattern = Pattern.compile("ui:insert\\s*name=[\"'](.*?)[\"']");
    Set<String> matches = new HashSet<String>();

    Matcher m = pattern.matcher(head);
    while (m.find()) {
      String match = m.group(1);
      if (!match.startsWith("_")) {
        matches.add(m.group(1));
      }
    }

    m = pattern.matcher(body);
    while (m.find()) {
      String match = m.group(1);
      if (!match.startsWith("_")) {
        matches.add(m.group(1));
      }
    }
    List<String> cphNameList = new ArrayList<String>(matches);
    if (toLowerCase) {
      for (int i = 0, n = cphNameList.size(); i < n; i++) {
        cphNameList.set(i, cphNameList.get(i).toLowerCase());
      }
    }
    return cphNameList;
  }
Esempio n. 26
0
    public boolean compare(BibtexEntry entry) {
      // specification of fields to search is done in the search expression itself
      String[] searchKeys = entry.getAllFields().toArray(new String[entry.getAllFields().size()]);

      boolean noSuchField = true;
      // this loop iterates over all regular keys, then over pseudo keys like "type"
      for (int i = 0; i < searchKeys.length + 1; i++) {
        String content;
        if (i - searchKeys.length == 0) {
          // PSEUDOFIELD_TYPE
          if (!fieldPattern.matcher("entrytype").matches()) continue;
          content = entry.getType().getName();
        } else {
          String searchKey = searchKeys[i];
          if (!fieldPattern.matcher(searchKey).matches()) continue;
          content = entry.getField(searchKey);
        }
        noSuchField = false;
        if (content == null) continue; // paranoia

        if (matchInField(content)) {
          return true;
        }
      }

      return noSuchField && operator == ComparisonOperator.DOES_NOT_CONTAIN;
    }
Esempio n. 27
0
  private String decodeEntities(String s) {
    StringBuffer buf = new StringBuffer();

    Matcher m = P_ENTITY.matcher(s);
    while (m.find()) {
      final String match = m.group(1);
      final int decimal = Integer.decode(match).intValue();
      m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
    }
    m.appendTail(buf);
    s = buf.toString();

    buf = new StringBuffer();
    m = P_ENTITY_UNICODE.matcher(s);
    while (m.find()) {
      final String match = m.group(1);
      final int decimal = Integer.valueOf(match, 16).intValue();
      m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
    }
    m.appendTail(buf);
    s = buf.toString();

    buf = new StringBuffer();
    m = P_ENCODE.matcher(s);
    while (m.find()) {
      final String match = m.group(1);
      final int decimal = Integer.valueOf(match, 16).intValue();
      m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
    }
    m.appendTail(buf);
    s = buf.toString();

    s = validateEntities(s);
    return s;
  }
  /**
   * Converts an identifier to upper-underscore format. The identifier must start with a letter or
   * underscore and must only contain letters, digits, and underscores (i.e. it must match the
   * regular expression {@code [A-Za-z_][A-Za-z_0-9]*}).
   *
   * @param ident The identifer to convert.
   * @return The identifier in upper-underscore format.
   */
  public static String convertToUpperUnderscore(String ident) {

    ident = LEADING_OR_TRAILING_UNDERSCORE_PATTERN.matcher(ident).replaceAll("");
    ident = WORD_BOUNDARY_IN_IDENT_PATTERN.matcher(ident).replaceAll("_");
    ident = CONSECUTIVE_UNDERSCORES_PATTERN.matcher(ident).replaceAll("_");
    return ident.toUpperCase();
  }
Esempio n. 29
0
 private void checkLoadedModForPermissionClass(File modFile) {
   try {
     Pattern p = Pattern.compile("permission", Pattern.CASE_INSENSITIVE);
     if (modFile.isDirectory()) {
       for (File file : modFile.listFiles()) {
         checkLoadedModForPermissionClass(file);
       }
     } else if ((modFile.getName().endsWith(".zip")) || (modFile.getName().endsWith(".jar"))) {
       ZipFile zip = new ZipFile(modFile);
       Enumeration entries = zip.entries();
       while (entries.hasMoreElements()) {
         ZipEntry zipentry = (ZipEntry) entries.nextElement();
         if (zipentry != null
             && zipentry.getName().endsWith(".class")
             && p.matcher(zipentry.getName()).find()) {
           checkLoadedClass(zip.getInputStream(zipentry));
         }
       }
       zip.close();
     } else if (modFile.getName().endsWith(".class") && p.matcher(modFile.getName()).find()) {
       checkLoadedClass(new FileInputStream(modFile));
     }
   } catch (IOException e) {
   }
 }
  @Override
  protected String calculateId(String tokenName, int tokenType) {
    if (PUNCTUATION.matcher(tokenName).matches()) {
      return DefaultHighlightingConfiguration.DEFAULT_ID;
    }

    if ("'requirements'".equals(tokenName)
        || "'allEnvironments'".equals(tokenName)
        || "'source'".equals(tokenName)
        || "'configurePhase'".equals(tokenName)) {
      return TargetPlatformHighlightingConfiguration.OPTION_ID;
    }

    if ("'version'".equals(tokenName) || "'='".equals(tokenName) || "';'".equals(tokenName)) {
      return DefaultHighlightingConfiguration.DEFAULT_ID;
    }

    if (QUOTED.matcher(tokenName).matches()) {
      return DefaultHighlightingConfiguration.KEYWORD_ID;
    }
    if ("RULE_STRING".equals(tokenName)) {
      return DefaultHighlightingConfiguration.STRING_ID;
    }
    if ("RULE_ML_COMMENT".equals(tokenName) || "RULE_SL_COMMENT".equals(tokenName)) {
      return DefaultHighlightingConfiguration.COMMENT_ID;
    }
    return DefaultHighlightingConfiguration.DEFAULT_ID;
  }