Esempio n. 1
0
  public static enum OutputType {
    /** Normal JSON, with all its quotes. */
    json,
    /** Like JSON, but names are only quoted if necessary. */
    javascript,
    /** Like JSON, but names and values are only quoted if necessary. */
    minimal;

    private static Pattern javascriptPattern = Pattern.compile("[a-zA-Z_$][a-zA-Z_$0-9]*");
    private static Pattern minimalPattern = Pattern.compile("[a-zA-Z_$][^:}\\], ]*");

    public String quoteValue(String value) {
      value = value.replace("\\", "\\\\");
      if (this == OutputType.minimal
          && !value.equals("true")
          && !value.equals("false")
          && !value.equals("null")
          && minimalPattern.matcher(value).matches()) return value;
      return '"' + value + '"';
    }

    public String quoteName(String value) {
      value = value.replace("\\", "\\\\");
      switch (this) {
        case minimal:
          if (minimalPattern.matcher(value).matches()) return value;
          return '"' + value + '"';
        case javascript:
          if (javascriptPattern.matcher(value).matches()) return value;
          return '"' + value + '"';
        default:
          return '"' + value + '"';
      }
    }
  }
Esempio n. 2
0
/** Utilities for reading the encoding of a file. */
public class Encoding {
  private static final Pattern COMMENT_OR_EMPTY_LINE_PATTERN = Pattern.compile("^\\s*#|^\\s*$");
  private static final Pattern ENCODING_PATTERN =
      Pattern.compile("^\\s*#\\s*encoding\\s*:\\s*([0-9a-zA-Z\\-]+)", Pattern.CASE_INSENSITIVE);
  public static final String DEFAULT_ENCODING = "UTF-8";

  public String readFile(String path) throws FileNotFoundException, UnsupportedEncodingException {
    String source =
        FixJava.readReader(new InputStreamReader(new FileInputStream(path), DEFAULT_ENCODING));
    String enc = encoding(source);
    if (!enc.equals(DEFAULT_ENCODING)) {
      source = FixJava.readReader(new InputStreamReader(new FileInputStream(path), enc));
    }
    return source;
  }

  public String encoding(String source) {
    String encoding = DEFAULT_ENCODING;
    for (String line : source.split("\\n")) {
      if (!COMMENT_OR_EMPTY_LINE_PATTERN.matcher(line).find()) {
        break;
      }
      Matcher matcher = ENCODING_PATTERN.matcher(line);
      if (matcher.find()) {
        encoding = matcher.group(1);
        break;
      }
    }
    return encoding.toUpperCase();
  }
}
  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;
  }
Esempio n. 4
0
 static {
   Map<Pattern, String> m = new IdentityHashMap<>();
   m.put(Pattern.compile(".*lucene-core-.*\\.jar$"), "es.security.jar.lucene.core");
   m.put(Pattern.compile(".*jsr166e-.*\\.jar$"), "es.security.jar.twitter.jsr166e");
   m.put(Pattern.compile(".*securemock-.*\\.jar$"), "es.security.jar.elasticsearch.securemock");
   SPECIAL_JARS = Collections.unmodifiableMap(m);
 }
Esempio n. 5
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. 6
0
  /**
   * Attempts to generate legal variable name. Does not take into account key words.
   *
   * @param setName
   * @return
   * @throws Exception
   */
  public static String getLegalVarName(String setName, final Collection<String> names)
      throws Exception {

    if (setName.endsWith("/")) setName = setName.substring(0, setName.length() - 1);
    if (setName.indexOf('/') > -1) setName = setName.substring(setName.lastIndexOf('/'));

    setName = setName.replaceAll(" ", "_");
    setName = setName.replaceAll("[^a-zA-Z0-9_]", "");
    final Matcher matcher = Pattern.compile("(\\d+)(.+)").matcher(setName);
    if (matcher.matches()) {
      setName = matcher.group(2);
    }

    if (Pattern.compile("(\\d+)").matcher(setName).matches()) {
      throw new Exception("Variable name of numbers only not possible!");
    }

    if (names != null)
      if (names.contains(setName)) {
        int i = 1;
        while (names.contains(setName + i)) i++;
        setName = setName + i;
      }

    return setName;
  }
Esempio n. 7
0
 private static Condition parse(Element element, LogHeaderDefinition definition) {
   String name = element.getTagName();
   if ("message".equals(name))
     try {
       return new MessageCondition(Pattern.compile(element.getTextContent()));
     } catch (PatternSyntaxException ex) {
       throw new RuntimeException(
           "[LogFilter] invalid regex " + element.getTextContent() + " in message element", ex);
     }
   else if ("field".equals(name)) {
     Attr attr = element.getAttributeNode("name");
     if (attr == null)
       throw new IllegalArgumentException("[LogFilter] name attribute missing in field element");
     int index = Arrays.asList(definition.groupNames).indexOf(attr.getNodeValue());
     try {
       Pattern pattern = Pattern.compile(element.getTextContent());
       return new FieldCondition(pattern, index);
     } catch (PatternSyntaxException ex) {
       throw new RuntimeException(
           "[LogFilter] invalid regex " + element.getTextContent() + " in field element", ex);
     }
   } else if ("and".equals(name)) return new AndCondition(getChildConditions(element, definition));
   else if ("or".equals(name)) return new OrCondition(getChildConditions(element, definition));
   else if ("not".equals(name)) {
     return new NotCondition(getChildConditions(element, definition)[0]);
   } else if ("index".equals(name)) {
     return new IndexCondition(Integer.parseInt(element.getTextContent()));
   } else if ("following".equals(name)) {
     boolean includeSelf = Boolean.parseBoolean(element.getAttribute("includeSelf"));
     return new FollowingCondition(getChildConditions(element, definition)[0], includeSelf);
   } else if ("preceding".equals(name)) {
     boolean includeSelf = Boolean.parseBoolean(element.getAttribute("includeSelf"));
     return new PrecedingCondition(getChildConditions(element, definition)[0], includeSelf);
   } else throw new RuntimeException("[LogFilter] invalid element " + name);
 }
Esempio n. 8
0
 public static Class discoverRegistryKeyType(String key) {
   if (!doesRegistryValueExist(key)) {
     return null;
   }
   RegKeyValue r = new RegKeyValue(key);
   String output = runRegQuery(key);
   Pattern pat;
   if (isRegExeVersion1()) {
     pat = Pattern.compile("\\s*(REG_\\S+)");
   } else {
     pat = Pattern.compile("\\Q" + r.value + "\\E\\s+(REG_\\S+)\\s+(.*)");
   }
   Matcher m = pat.matcher(output);
   if (!m.find()) {
     throw new WindowsRegistryException("Output didn't look right: " + output);
   }
   String type = m.group(1);
   if ("REG_SZ".equals(type) || "REG_EXPAND_SZ".equals(type)) {
     return String.class;
   } else if ("REG_DWORD".equals(type)) {
     return int.class;
   } else {
     throw new WindowsRegistryException("Unknown type: " + type);
   }
 }
Esempio n. 9
0
  public static int readIntRegistryValue(String key) {
    RegKeyValue r = new RegKeyValue(key);
    String output = runRegQuery(key);
    Pattern pat;
    if (isRegExeVersion1()) {
      pat = Pattern.compile("\\s*(REG_\\S+)\\s+\\Q" + r.value + "\\E\\s+(.*)");
    } else {
      pat = Pattern.compile("\\Q" + r.value + "\\E\\s+(REG_\\S+)\\s+0x(.*)");
    }

    Matcher m = pat.matcher(output);
    if (!m.find()) {
      throw new WindowsRegistryException("Output didn't look right: " + output);
    }
    String type = m.group(1);
    if (!"REG_DWORD".equals(type)) {
      throw new WindowsRegistryException(r.value + " was not a REG_DWORD (int): " + type);
    }
    String strValue = m.group(2);
    int value;
    if (isRegExeVersion1()) {
      value = Integer.parseInt(strValue);
    } else {
      value = Integer.parseInt(strValue, 16);
    }
    return value;
  }
Esempio n. 10
0
  public static void main(String[] args) {
    String s =
        "/*! Here's   a block of text to use as input to the regular expression matcher. Note that we'll first extract the block of text by looking for the special delimiters. then process the extracted block. !*/";

    Matcher m = Pattern.compile("/\\*!(.*)!\\*/", Pattern.DOTALL).matcher(s);
    if (m.find()) {
      s = m.group(1);
      System.out.println(s);
    }

    s = s.replaceAll(" {2,}", " ");
    System.out.println(s);

    s = s.replaceFirst("[aeiou]", "(VOWELL)");
    System.out.println(s);

    StringBuffer sbuf = new StringBuffer();
    Pattern p = Pattern.compile("[aeiou]");
    m = p.matcher(s);
    // appendReplacement()将当前匹配子串替换为指定字符串,并且将替换后的子串以及其之前到上次匹配子串之后的字符串段添加到一个 StringBuffer 对象里,而
    // appendTail(StringBuffer sb) 方法则将最后一次匹配工作后剩余的字符串添加到一个 StringBuffer
    // 对象里。
    while (m.find()) {
      m.appendReplacement(sbuf, m.group().toUpperCase());
    }
    m.appendTail(sbuf);
    System.out.println(sbuf);
  }
Esempio n. 11
0
 /** 设置颜色 */
 public void setResultColor(String checkName, String name, TextView result) {
   SpannableStringBuilder builder = new SpannableStringBuilder();
   int start = name.indexOf(checkName);
   int max = name.length();
   endMax = restrictMax;
   for (int i = 0; i < restrictMax; i++) { // 循环遍历字符串
     if (Pattern.compile("(?i)[a-z]").matcher(name).find()
         || Pattern.compile("(?i)[A-Z]").matcher(name).find()) { // 用char包装类中的判断数字的方法判断每一个字符
       endMax++;
     }
   }
   if (max > endMax) {
     name = name.substring(0, endMax);
     for (int i = 0; i < max - endMax; i++) {
       name += ".";
     }
   }
   builder.append(name);
   if (!checkName.equals("")) {
     builder.setSpan(
         new ForegroundColorSpan(Color.RED),
         start,
         start + checkName.length(),
         Spanned.SPAN_COMPOSING);
   }
   result.setText(builder, BufferType.EDITABLE);
 }
Esempio n. 12
0
  public static String expandEnvironment(String string1) {

    if (string1 == null) {
      return string1;
    }

    String environmentPattern = "([A-Za-z0-9_]+)";
    Pattern pattern1 = Pattern.compile("\\$\\{" + environmentPattern + "\\}");
    Pattern pattern2 = Pattern.compile("\\$" + environmentPattern);

    String string2 = null;

    while (!string1.equals(string2)) {
      if (string2 != null) {
        string1 = string2;
      }

      string2 = expandEnvironment(pattern1, string1);
      string2 = expandEnvironment(pattern2, string2);

      if (string2 == null) {
        return string2;
      }
    }

    return string2;
  }
Esempio n. 13
0
  static {
    String basicAddress = "^([\\w\\.-]+)@([\\w\\.-]+)$";
    String specialChars = "\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
    String validChars = "[^ \f\n\r\t" + specialChars + "]";
    String atom = validChars + "+";
    String quotedUser = "******"[^\"]+\")";
    String word = "(" + atom + "|" + quotedUser + ")";
    String validUser = "******" + word + "(\\." + word + ")*$";
    String domain = "^" + atom + "(\\." + atom + ")+$";
    String ipDomain = "^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$";
    String knownTLDs = "^\\.(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$";
    basicAddressPattern = Pattern.compile(basicAddress, 2);
    validUserPattern = Pattern.compile(validUser, 2);
    domainPattern = Pattern.compile(domain, 2);
    ipDomainPattern = Pattern.compile(ipDomain, 2);
    tldPattern = Pattern.compile(knownTLDs, 2);
    allowed_query = new BitSet(256);
    for (int i = 48; i <= 57; i++) allowed_query.set(i);

    for (int i = 97; i <= 122; i++) allowed_query.set(i);

    for (int i = 65; i <= 90; i++) allowed_query.set(i);

    allowed_query.set(45);
    allowed_query.set(95);
    allowed_query.set(46);
    allowed_query.set(33);
    allowed_query.set(126);
    allowed_query.set(42);
    allowed_query.set(39);
    allowed_query.set(40);
    allowed_query.set(41);
  }
  public void replaceSignatures(
      Document doc,
      byte[] empSign,
      byte[] rimDirSign,
      byte[] sjrlogo,
      SearchAndReplaceCallBack callback)
      throws Exception {
    if (empSign != null) {
      callback.setImage(empSign);
      doc.getRange()
          .replace(Pattern.compile("\\[\\[\\[EMPLOYEE_SIGNATURE\\]\\]\\]"), callback, true);
    }

    if (empSign != null) {
      callback.setImage(empSign);
      doc.getRange()
          .replace(Pattern.compile("\\[\\[\\[\\.EMPLOYEE_SIGNATURE\\.\\]\\]\\]"), callback, false);
    }

    if (rimDirSign != null) {
      callback.setImage(rimDirSign);
      doc.getRange()
          .replace(Pattern.compile("\\[\\[\\[RIM_DIRECTOR_SIGNATURE\\]\\]\\]"), callback, true);
    }

    if (sjrlogo != null) {
      callback.setImage(sjrlogo);
      doc.getRange().replace(Pattern.compile("\\[\\[\\[SJR_LOGO\\]\\]\\]"), callback, true);
    }
  }
  /**
   * 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;
  }
Esempio n. 16
0
public class Test {
  Pattern commandPattern = Pattern.compile("(\\w|[:]|[-])+");
  Pattern parameterPattern =
      Pattern.compile(
          "(\\b(\\w|[\u4e00-\u9fa5]|[/]|[.]|[-])+\\s*=\"[^\"]*\")|(\\b(\\w|[\u4e00-\u9fa5]|[/]|[.]|[-])+='[^\']*')|(\\b(\\w|[\u4e00-\u9fa5]|[/]|[.]|[-])+=(\\w|[\u4e00-\u9fa5]|[.]|[-])+)");

  public static void main(String[] args) {

    new Test().test("abc:ca a=b c=d e='a d e'");
    new Test().test("abc a=\"ab c d\" e=f");
    new Test().test("abc:ca-a");
    new Test().test("abc:ca_a");
  }

  private void test(String string) {
    Matcher m = commandPattern.matcher(string);
    if (m.find()) {
      System.out.println(m.group());
    } else {
      return;
    }
    int s = m.end();
    m = parameterPattern.matcher(string);
    while (m.find(s)) {
      System.out.println("\t" + m.group());
      s = m.end();
    }
  }
}
Esempio n. 17
0
 // 从context提取url地址,需要深度搜索时使用
 public void parseContext(String context, int dep) {
   String regex = "<a href.*?/a>";
   // String regex = "<title>.*?</title>";
   String s =
       "fdfd<title>我 是</title><a href=\"http://www.iteye.com/blogs/tag/Google\">Google</a>fdfd<>";
   // String regex ="http://.*?>";
   Pattern pt = Pattern.compile(regex);
   Matcher mt = pt.matcher(context);
   while (mt.find()) {
     // System.out.println(mt.group());
     Matcher myurl = Pattern.compile("href=\".*?\"").matcher(mt.group());
     while (myurl.find()) {
       String str = myurl.group().replaceAll("href=\"|\"", "");
       // System.out.println("网址是:"+ str);
       if (str.contains("http:")) { // 取出一些不是url的地址
         if (!allUrlList.contains(str)) {
           addUrl(str, dep); // 加入一个新的url
           if (waitingThreadCount > 0) { // 如果有等待的线程,则唤醒
             synchronized (signal) { // ---------------------(2)
               waitingThreadCount--;
               signal.notify();
             }
           }
         }
       }
     }
   }
 }
Esempio n. 18
0
  private List<String> processArgs(String[] args) {
    // Args4j has a different format that the old command-line parser.
    // So we use some voodoo to get the args into the format that args4j
    // expects.
    Pattern argPattern = Pattern.compile("(--[a-zA-Z_]+)=(.*)");
    Pattern quotesPattern = Pattern.compile("^['\"](.*)['\"]$");
    List<String> processedArgs = Lists.newArrayList();

    for (String arg : args) {
      Matcher matcher = argPattern.matcher(arg);
      if (matcher.matches()) {
        processedArgs.add(matcher.group(1));

        String value = matcher.group(2);
        Matcher quotesMatcher = quotesPattern.matcher(value);
        if (quotesMatcher.matches()) {
          processedArgs.add(quotesMatcher.group(1));
        } else {
          processedArgs.add(value);
        }
      } else {
        processedArgs.add(arg);
      }
    }

    return processedArgs;
  }
Esempio n. 19
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. 20
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;
  }
Esempio n. 21
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);
      }
    }
  @Test
  public void testToRoutePathPattern() {
    String patternStr = RouteUtil.toRoutePathPattern("/persons/{id}");
    Assert.assertTrue(Pattern.compile(patternStr).matcher("/persons/123").matches());

    String patternStr2 = RouteUtil.toRoutePathPattern("/persons/{id}/edit/{name}");
    Pattern pattern2 = Pattern.compile(patternStr2);
    Assert.assertTrue(pattern2.matcher("/persons/123/edit/basten").matches());

    Assert.assertTrue(pattern2.matcher("/persons/123/edit/basten.gao").matches());
    // Assert.assertTrue(pattern2.matcher("/persons/123/edit/basten<gao").matches());
    // Assert.assertTrue(pattern2.matcher("/persons/123/edit/basten>gao").matches());
    // Assert.assertTrue(pattern2.matcher("/persons/123/edit/basten^gao").matches());
    Assert.assertTrue(pattern2.matcher("/persons/123/edit/basten-gao").matches());
    Assert.assertTrue(pattern2.matcher("/persons/123/edit/basten_gao").matches());
    // Assert.assertTrue(pattern2.matcher("/persons/123/edit/basten`gao").matches());
    // Assert.assertTrue(pattern2.matcher("/persons/123/edit/basten}gao").matches());
    Assert.assertTrue(pattern2.matcher("/persons/123/edit/basten~gao").matches());
    // Assert.assertTrue(pattern2.matcher("/persons/123/edit/basten\"gao").matches());
    Assert.assertTrue(pattern2.matcher("/persons/123/edit/中文").matches());
    Assert.assertTrue(pattern2.matcher("/persons/123/edit/中.文").matches());
    Assert.assertTrue(pattern2.matcher("/persons/123/edit/中-文").matches());
    Assert.assertTrue(pattern2.matcher("/persons/123/edit/中_文").matches());
    Assert.assertTrue(pattern2.matcher("/persons/123/edit/中~文").matches());

    Assert.assertFalse(pattern2.matcher("/persons/123/edit/中文?").matches());
    Assert.assertFalse(pattern2.matcher("/persons/123/edit/中文#").matches());
    Assert.assertFalse(pattern2.matcher("/persons/123/edit/中文;").matches());
    Assert.assertFalse(pattern2.matcher("/persons/123/edit/中文,").matches());
  }
Esempio n. 23
0
  public interface Constants {
    char CARRIAGE_RETURN_CHAR = '\r';
    char LINE_FEED_CHAR = '\n';
    char NEW_LINE_CHAR = LINE_FEED_CHAR;
    char SPACE_CHAR = ' ';
    char DOT_CHAR = '.';
    char TAB_CHAR = '\t';
    char DQUOTE_CHAR = '"';

    String CARRIAGE_RETURN = String.valueOf(CARRIAGE_RETURN_CHAR);
    String EMPTY_STRING = ""; // $NON-NLS-1$
    String DBL_SPACE = "  "; // $NON-NLS-1$
    String LINE_FEED = String.valueOf(LINE_FEED_CHAR);
    String NEW_LINE = String.valueOf(NEW_LINE_CHAR);
    String SPACE = String.valueOf(SPACE_CHAR);
    String DOT = String.valueOf(DOT_CHAR);
    String TAB = String.valueOf(TAB_CHAR);
    String DQUOTE_STR = "\""; // $NON-NLS-1$
    String DOT_STR = "."; // $NON-NLS-1$

    String[] EMPTY_STRING_ARRAY = new String[0];

    // all patterns below copied from Eclipse's PatternConstructor class.
    final Pattern PATTERN_BACK_SLASH = Pattern.compile("\\\\"); // $NON-NLS-1$
    final Pattern PATTERN_QUESTION = Pattern.compile("\\?"); // $NON-NLS-1$
    final Pattern PATTERN_STAR = Pattern.compile("\\*"); // $NON-NLS-1$
  }
Esempio n. 24
0
 public static void main(String[] args) {
   Scanner reader = new Scanner(System.in);
   Pattern p = Pattern.compile("\\s{1,}");
   Pattern p1 =
       Pattern.compile(
           "[\\+\\-][0-9]*[xX]\\^[0-9]*|[\\+\\-][0-9]*\\*[xX]\\^[0-9]*|[0-9]*[xX]\\^[0-9]*|[\\+\\-][0-9]*|[0-9]*\\*[xX]\\^[0-9]*");
   String[] a = p.split(reader.nextLine());
   Node[] linkhead = new Node[a.length];
   for (int i = 0; i < a.length; i++) {
     Matcher matcher = p1.matcher(a[i]); // 正则匹配空格分离多个多项式
     int counter = 0;
     while (matcher.find()) {
       Node temp = convert(matcher.group()); // 依次读取系数和指数
       if (counter == 0) {
         linkhead[i] = temp;
         counter++;
       } else {
         linkhead[i] = ordersort(linkhead[i], temp); // 排序并把各个多项式的链表头分别储存
         counter++;
       }
     }
   }
   Node sumhead = add(linkhead); // 将各个多项式相加
   showit(sumhead);
 }
Esempio n. 25
0
    public LsCommand(String file) {
      super("toolbox ls -l " + file);

      // get only filename:
      this.fileName = (new File(file)).getName();
      Log.d(RootCommands.TAG, "fileName: " + fileName);

      /**
       * regex to get pid out of ps line, example:
       *
       * <pre>
       * with busybox:
       *     lrwxrwxrwx     1 root root            15 Aug 13 12:14 dev/stdin -> /proc/self/fd/0
       *
       * with toolbox:
       *     lrwxrwxrwx root root            15 Aug 13 12:14 stdin -> /proc/self/fd/0
       *
       * Regex:
       * ^.*?(\\S{10})                     .*                                                  $
       * </pre>
       */
      permissionRegex = "^.*?(\\S{10}).*$";
      permissionPattern = Pattern.compile(permissionRegex);

      /**
       * regex to get symlink
       *
       * <pre>
       *     ->           /proc/self/fd/0
       * ^.*?\\-\\> \\s+  (.*)           $
       * </pre>
       */
      symlinkRegex = "^.*?\\-\\>\\s+(.*)$";
      symlinkPattern = Pattern.compile(symlinkRegex);
    }
Esempio n. 26
0
public class WhitespaceTrimmer {

  private static String whiteRange = "\\p{javaWhitespace}\\p{Zs}";
  private static Pattern whiteStart = Pattern.compile("^[" + whiteRange + "]+");
  private static Pattern whiteEnd = Pattern.compile("[" + whiteRange + "]+$");

  private WhitespaceTrimmer() {}

  static String ltrim(String text) {
    if (text == null) {
      return "";
    }
    Matcher mStart = whiteStart.matcher(text);
    return mStart.find() ? text.substring(mStart.end()) : text;
  }

  static String rtrim(String text) {
    if (text == null) {
      return "";
    }
    Matcher mEnd = whiteEnd.matcher(text);
    if (mEnd.find()) {
      int matchStart = mEnd.start();
      return text.substring(0, matchStart);
    } else {
      return text;
    }
  }

  public static String trim(String text) {
    return (rtrim(ltrim(text.trim()))).trim();
  }
}
Esempio n. 27
0
  private static class ClassFilter implements FileFilter {
    private static final String DEFAULT_INCLUDE = "\\*";
    private static final String DEFAULT_EXCLUDE = "";
    private static final Pattern INCLUDE_PATTERN =
        Pattern.compile(
            SystemInstance.get()
                .getOptions()
                .get(OPENEJB_JAR_ENHANCEMENT_INCLUDE, DEFAULT_INCLUDE));
    private static final Pattern EXCLUDE_PATTERN =
        Pattern.compile(
            SystemInstance.get()
                .getOptions()
                .get(OPENEJB_JAR_ENHANCEMENT_EXCLUDE, DEFAULT_EXCLUDE));

    @Override
    public boolean accept(final File file) {
      boolean isClass = file.getName().endsWith(CLASS_EXT);
      if (DEFAULT_EXCLUDE.equals(EXCLUDE_PATTERN.pattern())
          && DEFAULT_INCLUDE.equals(INCLUDE_PATTERN.pattern())) {
        return isClass;
      }

      final String path = file.getAbsolutePath();
      return isClass
          && INCLUDE_PATTERN.matcher(path).matches()
          && !EXCLUDE_PATTERN.matcher(path).matches();
    }
  }
  // The service name pattern can be used to disambiguate situations where
  // VCAP_SERVICES contains multiple instances of the MQ Light service
  @Test
  public void specificServiceCanBePickedByServiceName() throws InterruptedException {
    BluemixEndpointService service =
        new MockBluemixEndpointService(
            null,
            Pattern.compile(Pattern.quote("MQ Light-9n")),
            twoMQLightServicesJSON,
            expectedTwoMQLightServicesUri1,
            servicesJson);
    MockEndpointPromise promise = new MockEndpointPromise(Method.SUCCESS);
    service.lookup(promise);
    waitForComplete(promise);
    assertTrue("Promise should have been marked done", promise.isComplete());

    service =
        new MockBluemixEndpointService(
            null,
            Pattern.compile("MQ Light\\-gs"),
            twoMQLightServicesJSON,
            expectedTwoMQLightServicesUri2,
            servicesJson);
    promise = new MockEndpointPromise(Method.SUCCESS);
    service.lookup(promise);
    waitForComplete(promise);
    assertTrue("Promise should have been marked done", promise.isComplete());
  }
Esempio n. 29
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;
 }
Esempio n. 30
0
  public static Pattern createPattern(String regex, boolean useRegex) {
    if (useRegex) {
      return Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    } else {
      String[] parts = regex.split("\\*+");
      StringBuilder sb = new StringBuilder();
      if (regex.startsWith("*")) sb.append("(.*)");
      int actualParts = 0;
      for (int i = 0; i < parts.length; i++) {

        if (parts[i].length() != 0) {
          if (actualParts > 0) {
            sb.append("(.*?)");
          }
          sb.append(Pattern.quote(parts[i]));
          actualParts++;
        }
      }
      if (sb.length() == 0) {
        sb.append("(.*?)");
      } else {
        if (regex.endsWith("*")) {
          sb.append("(.*)");
        }
      }
      return Pattern.compile(sb.toString(), Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    }
  }