public static String getGoalText(
     final ChallengeGoalData goal, final ChallengeData data, final ChallengeDataModel model) {
   String rawText = goal.getFormattedString();
   if (rawText == null || rawText.length() == 0) {
     return null;
   }
   rawText =
       (String)
           ChallengeFormatter.extractValue(
               rawText, ChallengeFormatter.Type.STRING, model.getParams());
   for (Matcher match = ChallengeGoalView.GOAL_BREED_PATTERN.matcher(rawText);
       match.find();
       match = ChallengeGoalView.GOAL_BREED_PATTERN.matcher(rawText)) {
     final String name =
         WakfuTranslator.getInstance()
             .getString(7, PrimitiveConverter.getInteger(match.group(1)), new Object[0]);
     rawText = match.replaceFirst(name);
   }
   for (Matcher match = ChallengeGoalView.GOAL_RESOURCE_PATTERN.matcher(rawText);
       match.find();
       match = ChallengeGoalView.GOAL_RESOURCE_PATTERN.matcher(rawText)) {
     final String name =
         WakfuTranslator.getInstance()
             .getString(12, PrimitiveConverter.getInteger(match.group(1)), new Object[0]);
     rawText = match.replaceFirst(name);
   }
   for (Matcher match = ChallengeGoalView.GOAL_VAR_PATTERN.matcher(rawText);
       match.find();
       match = ChallengeGoalView.GOAL_VAR_PATTERN.matcher(rawText)) {
     final Long value = data.getVarValue(match.group().substring(1, match.group().length() - 1));
     rawText = match.replaceFirst(value.toString());
   }
   return rawText;
 }
  private static String processHtml(final String source, StringBuilder errorMessages) {
    if (M_evilTags == null) init();

    // normalize all variants of the "<br>" HTML tag to be "<br />\n"
    // TODO call a method to do this in each process routine
    String Html = M_patternTagBr.matcher(source).replaceAll("<br />");

    // process text and tags
    StringBuilder buf = new StringBuilder();
    if (Html != null) {
      try {
        int start = 0;
        Matcher m = M_patternTag.matcher(Html);

        // if there are no tags, return as is
        if (!m.find()) return Html;
        m.reset(Html);

        // if there are tags, make sure they are safe
        while (m.find()) {
          // append text that isn't part of a tag
          if (m.start() > start) buf.append(Html.substring(start, m.start()));
          start = m.end();

          buf.append(checkTag(m.group(), errorMessages));
        }

        // tail
        if (Html.length() > start) buf.append(Html.substring((start)));
      } catch (Exception e) {
        M_log.warn("FormattedText.processEscapedHtml M_patternTag.matcher(Html):", e);
      }
    }
    return new String(buf.toString());
  }
Exemple #3
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;
  }
  @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;
  }
  private List parseCompileFailuresFromFormattedMessage(String target, String message) {
    final List errors = new ArrayList();

    final Pattern pattern = Pattern.compile("^(.+):\\[(\\d+),\\d+\\] ", Pattern.MULTILINE);

    final Matcher matcher = pattern.matcher(message);

    boolean found = matcher.find();

    while (found) {
      final String file = toRelative(matcher.group(1));
      final Integer line = Integer.valueOf(matcher.group(2));
      // final String msg = matcher.group(3);

      int start = matcher.end();

      found = matcher.find();
      int end = message.length() - 1;
      if (found) {
        end = matcher.start();
      }

      final String msg = message.substring(start, end).replaceAll("\r", "").trim();

      errors.add(
          new AntEventSummary(
              Constants.MESSAGE_LOGGED, "project", target, "task", msg, 0, file, line, null));
    }

    return errors;
  }
Exemple #6
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);
        }
      }
    }
  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;
  }
Exemple #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();
  }
Exemple #9
0
  public boolean isUpdateAvailable(String mcVersion, String mpVersion) {
    RSSFeedParser rssFeedParser =
        new RSSFeedParser("http://dev.bukkit.org/server-mods/mywolf/files.rss");
    rssFeedParser.readFeed();
    lastAvailableUpdate = null;

    for (FeedItem feedItem : feedItemList) {
      String description = feedItem.getDescription();
      Matcher mcRegexMatcher = mcVersionRegex.matcher(description);
      while (mcRegexMatcher.find()) {
        if (mcVersion.equals(mcRegexMatcher.group(1))) {
          Matcher mpRegexMatcher = mpVersionRegex.matcher(description);

          while (mpRegexMatcher.find()) {
            if (isNewer(mpVersion, mpRegexMatcher.group(1))) {
              if (lastAvailableUpdate == null
                  || isNewer(lastAvailableUpdate.getDate(), mpRegexMatcher.group(1))) {
                lastAvailableUpdate = feedItem;
              }
            }
          }
          break;
        }
      }
    }
    return lastAvailableUpdate != null;
  }
  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);
  }
Exemple #11
0
  private String addDataRights(String content, String classification, Artifact artifact) {
    String toReturn = content;
    PageOrientation orientation = WordRendererUtil.getPageOrientation(artifact);
    DataRightInput request = new DataRightInput();
    request.addData(artifact.getGuid(), classification, orientation, 0);

    DataRightProvider provider = new DataRightProviderImpl();
    DataRightResult dataRights = provider.getDataRights(request);
    String footer = dataRights.getContent(artifact.getGuid(), orientation);

    Matcher startFtr = START_PATTERN.matcher(footer);
    Matcher endFtr = END_PATTERN.matcher(footer);
    if (startFtr.find() && endFtr.find()) {
      ChangeSet ftrCs = new ChangeSet(footer);
      ftrCs.delete(0, startFtr.end());
      ftrCs.delete(endFtr.start(), footer.length());
      footer = ftrCs.applyChangesToSelf().toString();
    }

    startFtr.reset(content);
    endFtr.reset(content);
    ChangeSet cs = new ChangeSet(content);
    while (startFtr.find()) {
      if (endFtr.find()) {
        cs.replace(startFtr.end(), endFtr.start(), footer);
      }
    }
    toReturn = cs.applyChangesToSelf().toString();
    return toReturn;
  }
  /** Modifies events in-place. */
  public Event intercept(Event event) {
    Map<String, String> headers = event.getHeaders();
    String msg = new String(event.getBody(), charset);

    logger.debug(String.format("MsmRegexExtractInterceptor original body=%s", msg));

    Matcher matcher = this.pattern.matcher(msg);

    final List<String> tagValues = new ArrayList<String>();
    while (matcher.find() && matcher.groupCount() > 0) {
      tagValues.add(matcher.group(1));
    }

    if (tagValues.size() > 0) {
      msg = StringUtils.join(tagValues, "\n");
    }

    logger.debug(String.format("MsmRegexExtractInterceptor extract body=%s", msg));
    event.setBody(msg.getBytes());

    // set header based on the message type (for demonstration purpose)
    Matcher typeMatcher =
        Pattern.compile("<repd:IdPRM>([0-9]+)</repd:IdPRM>", Pattern.DOTALL | Pattern.MULTILINE)
            .matcher(msg);
    String messageType =
        (typeMatcher.find() && typeMatcher.groupCount() > 0)
            ? ((Integer.parseInt(typeMatcher.group(1))) % 2 == 0 ? "TypeA" : "TypeB")
            : "unknown";

    logger.debug(String.format("MsmRegexExtractInterceptor type-id=%s", messageType));
    headers.put("type-id", messageType);

    return event;
  }
 @Override
 public void onConfigurationRead() {
   disabled = "true".equals(Play.configuration.getProperty("betterlogs.disabled"));
   if (disabled)
     Logger.warn(
         "BetterLogs is disabled. The classes are no more enhanced. If you enable it again, don't forget to clean your app before to force Play to enhance all the classes.");
   ArrayList<String> newArgsPrefix = new ArrayList<String>();
   String prefix =
       Play.configuration.getProperty("betterlogs.prefix", "[%relativeFile:%line] %method() ::");
   Matcher matcher = PREFIX_PATTERN.matcher(prefix);
   StringBuffer sb = new StringBuffer();
   if (matcher.find()) {
     int lastEnd = 0;
     do {
       newArgsPrefix.add(matcher.group().substring(1));
       sb.append(prefix.substring(lastEnd, matcher.start()).replace("%", "%%")).append("%s");
       lastEnd = matcher.end();
     } while (matcher.find());
     sb.append(prefix.substring(lastEnd));
   }
   String trailingSpaces =
       Play.configuration.getProperty("betterlogs.prefix.trailingSpaces", "1ws");
   matcher = TRAILING_SPACES_PATTERN.matcher(trailingSpaces);
   if (matcher.matches()) {
     int nb = Integer.parseInt(matcher.group(1));
     char c = "t".equals(matcher.group(2)) ? '\t' : ' ';
     while (nb > 0) {
       sb.append(c);
       nb--;
     }
   }
   argsPrefix = newArgsPrefix;
   stringFormatPrefix = sb.toString();
 }
  private String levelUpEntityId(String requestAsJsonString) {

    String entityIdRegex = "\\\"entityId\\\":(.+?)\\}";

    Pattern pattern = Pattern.compile(entityIdRegex);

    String entityRegex = "\\{(.+?)\\}";

    Pattern entityPattern = Pattern.compile(entityRegex);

    Matcher matcher = pattern.matcher(requestAsJsonString);
    String entityId = null;
    String entity = requestAsJsonString;
    String newRequest = requestAsJsonString;
    while (matcher.find()) {
      entityId = matcher.group(0);

      Matcher entityMatcher = entityPattern.matcher(entityId);
      if (entityMatcher.find()) {
        entity = entityMatcher.group(1);
      }

      newRequest = newRequest.replace(entityId, entity);
    }

    return newRequest;
  }
Exemple #15
0
 void setText(final String charSeq) {
   colors.clear();
   if (charSeq == null) {
     return;
   }
   Matcher m = colorPattern.matcher(charSeq);
   if (m.find()) {
     StringBuilder builder = new StringBuilder(charSeq.length() - 7);
     int startIndex = 0;
     do {
       String colorStr = null;
       for (int i = 1; i <= 4 && colorStr == null; i++) {
         colorStr = m.group(i);
       }
       builder.append(charSeq.subSequence(startIndex, m.start()));
       Range range = new Range(builder.length(), colorStr);
       startIndex = m.end();
       colors.add(range);
     } while (m.find());
     builder.append(charSeq.subSequence(startIndex, charSeq.length()));
     text = builder.toString();
   } else {
     text = charSeq;
   }
 }
  private static ScoreRecord parseScore(Matcher m, String difficulty, ScoreRecord score)
      throws ParseException {
    if (score == null) score = new ScoreRecord();

    Pattern RE_DIFFICULTY = Pattern.compile(Pattern.quote(difficulty) + "</b><br>\\s*★(\\d+)");
    m = m.usePattern(RE_DIFFICULTY);
    if (!m.find()) return null;
    score.difficulty = Integer.valueOf(m.group(1));

    int end = m.regionEnd();
    int start = m.end();
    m = m.usePattern(RE_BLOCKEND);
    if (!m.find(start)) throw new ParseException();
    m.region(start, m.start());

    score.clear_status =
        5 - findLiteral(m, "clear4.jpg", "clear3.jpg", "clear2.jpg", "clear1.jpg", "-");
    score.trial_status = findLiteral(m, "C-TRIAL", "G-TRIAL", "E-TRIAL", "COMPLETE");
    m = m.usePattern(RE_ACHIVEMENT);
    if (m.find()) {
      score.achievement = m.group(3) == null ? 0 : Integer.valueOf(m.group(3));
      score.achievement += Integer.valueOf(m.group(2)) * 10;
      score.achievement += Integer.valueOf(m.group(1)) * 100;
    }
    m = m.usePattern(RE_HIGHSCORE);
    if (m.find()) score.high_score = Integer.valueOf(m.group(1));

    m.region(m.end(), end);
    return score;
  }
  public static String parseRankingList(InputStream content, List<Ranking> list)
      throws ParseException {
    String body = Parser.read(content);
    Matcher m = RE_RANKING_TITLE.matcher(body);
    int last = m.regionEnd();
    for (MatchResult r = m.find() ? m.toMatchResult() : null; r != null; ) {
      String id = r.group(1);
      String title = r.group(2);
      int start = r.end();

      m = m.usePattern(RE_RANKING_TITLE);
      m.region(start, last);
      if (m.find()) {
        r = m.toMatchResult();
        m.region(start, r.start());
      } else {
        r = null;
      }

      for (int rank = 3; rank > 1; --rank) {
        Ranking entry = parseRankIn(m, DIFFICULTIES[rank]);
        if (entry != null) {
          entry.id = id;
          entry.title = title;
          entry.rank = rank;
          entry.rival_code = null;
          list.add(entry);
        }
      }
    }

    m = m.usePattern(Parser.RE_NEXT);
    return m.find() ? m.group(1) : null;
  }
Exemple #18
0
  public static String parseDiagnosedRanges(String text, List<DiagnosedRange> result) {
    Matcher matcher = RANGE_START_OR_END_PATTERN.matcher(text);

    Stack<DiagnosedRange> opened = new Stack<DiagnosedRange>();

    int offsetCompensation = 0;

    while (matcher.find()) {
      int effectiveOffset = matcher.start() - offsetCompensation;
      String matchedText = matcher.group();
      if ("<!>".equals(matchedText)) {
        opened.pop().setEnd(effectiveOffset);
      } else {
        Matcher diagnosticTypeMatcher = INDIVIDUAL_DIAGNOSTIC_PATTERN.matcher(matchedText);
        DiagnosedRange range = new DiagnosedRange(effectiveOffset);
        while (diagnosticTypeMatcher.find()) {
          range.addDiagnostic(diagnosticTypeMatcher.group());
        }
        opened.push(range);
        result.add(range);
      }
      offsetCompensation += matchedText.length();
    }

    assert opened.isEmpty() : "Stack is not empty";

    matcher.reset();
    return matcher.replaceAll("");
  }
Exemple #19
0
  /**
   * Method that extract a lineup from the full match comment
   *
   * @param home true for home lineup, false for away
   * @return The Lineup object
   */
  public final TeamLineup getTeamLineup(boolean home) {
    final TeamLineup lineup = new TeamLineup();

    try {
      final Pattern p = Pattern.compile(".-.-.");
      final Matcher m = p.matcher(m_sMatchreport);
      m.find();

      if (!home) {
        m.find();
      }

      int start = m.end();
      start = m_sMatchreport.indexOf(":", start);

      final int end = m_sMatchreport.indexOf(".", start);

      final String[] zones = m_sMatchreport.substring(start + 1, end).split(" - ");

      for (int i = 0; i < zones.length; i++) {
        final String[] pNames = zones[i].split(",");

        for (int j = 0; j < pNames.length; j++) {
          lineup.add(pNames[j], i);
        }
      }
    } catch (RuntimeException e) {
      return new TeamLineup();
    }

    return lineup;
  }
  /**
   * 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;
  }
Exemple #21
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();
  }
 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());
 }
  /**
   * 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);
  }
  /**
   * 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;
  }
Exemple #25
0
  /** Returns the places of possible breaks between sentences. */
  private static List<BreakPosition> getBreaks(String paragraph, Rule rule) {
    List<BreakPosition> res = new ArrayList<BreakPosition>();

    Matcher bbm = null;
    if (rule.getBeforebreak() != null) bbm = rule.getCompiledBeforebreak().matcher(paragraph);
    Matcher abm = null;
    if (rule.getAfterbreak() != null) abm = rule.getCompiledAfterbreak().matcher(paragraph);

    if (bbm == null && abm == null) return res;

    if (abm != null) if (!abm.find()) return res;

    if (bbm == null) bbm = DEFAULT_BEFOREBREAK_PATTERN.matcher(paragraph);

    while (bbm.find()) {
      int bbe = bbm.end();
      if (abm == null) res.add(new BreakPosition(bbe, rule));
      else {
        int abs = abm.start();
        while (abs < bbe) {
          boolean found = abm.find();
          if (!found) return res;
          abs = abm.start();
        }
        if (abs == bbe) res.add(new BreakPosition(bbe, rule));
      }
    }

    return res;
  }
  /**
   * 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;
  }
  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;
  }
Exemple #28
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();
             }
           }
         }
       }
     }
   }
 }
Exemple #29
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);
      }
    }
Exemple #30
0
 private static String[] parseLetv(String url) {
   String[] result = new String[2];
   String id = "";
   String html = getUrlContent(url);
   Pattern pId = Pattern.compile("(?<=vplay/)([0-9]*)");
   Matcher mId = pId.matcher(url);
   if (mId.find()) {
     id = mId.group();
     Pattern pVideo = Pattern.compile("(?<=value=\")([^\"]*swf\\?id=" + id + "&amp[^\"]*)(?=\")");
     Matcher mVideo = pVideo.matcher(html);
     if (mVideo.find()) {
       result[0] = StringEscapeUtils.unescapeHtml(mVideo.group());
     } else {
       return null;
     }
   } else {
     return null;
   }
   Pattern pImage = Pattern.compile("(?<=pic:\")([^\"]*)(?=\")");
   Matcher mImage = pImage.matcher(html);
   if (mImage.find()) {
     result[1] = mImage.group();
   } else {
     return null;
   }
   return result;
 }