Example #1
1
 private String getTailFromName(String currentName) {
   Matcher m = fileNameRE.matcher(currentName);
   m.matches();
   String tail = "";
   int groupCount = m.groupCount();
   if (prepend) {
     tail += '\n';
   } else {
     if (groupCount > 0) {
       tail += separator;
     }
   }
   for (int i = 1; i <= groupCount; i++) {
     tail += m.group(i);
     if (i < groupCount) {
       tail += separator;
     }
   }
   if (prepend) {
     if (groupCount > 0) {
       tail += separator;
     }
   } else {
     tail += '\n';
   }
   return tail;
 }
  /** 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;
  }
Example #3
0
 private void route(HttpServerRequest request, List<PatternBinding> bindings) {
   for (PatternBinding binding : bindings) {
     Matcher m = binding.pattern.matcher(request.path);
     if (m.matches()) {
       Map<String, String> params = new HashMap<>(m.groupCount());
       if (binding.paramNames != null) {
         // Named params
         for (String param : binding.paramNames) {
           params.put(param, m.group(param));
         }
       } else {
         // Un-named params
         for (int i = 0; i < m.groupCount(); i++) {
           params.put("param" + i, m.group(i + 1));
         }
       }
       request.getParams().putAll(params);
       binding.handler.handle(request);
       return;
     }
   }
   // If we get here it wasn't routed
   request.response.statusCode = 404;
   request.response.end();
 }
  /**
   * (1)能匹配的年月日类型有: 2014年4月19日 2014年4月19号 2014-4-19 2014/4/19 2014.4.19 (2)能匹配的时分秒类型有: 15:28:21
   * 15:28 5:28 pm 15点28分21秒 15点28分 15点 (3)能匹配的年月日时分秒类型有: (1)和(2)的任意组合,二者中间可有任意多个空格
   * 如果dateStr中有多个时间串存在,只会匹配第一个串,其他的串忽略
   *
   * @param text
   * @return
   */
  @SuppressWarnings("unchecked")
  private static String matchDateString(String dateStr) {
    try {
      List<String> matches = null;
      Pattern p =
          Pattern.compile(
              "(\\d{1,4}[-|\\/|年|\\.]\\d{1,2}[-|\\/|月|\\.]\\d{1,2}([日|号])?(\\s)*(\\d{1,2}([点|时])?((:)?\\d{1,2}(分)?((:)?\\d{1,2}(秒)?)?)?)?(\\s)*(PM|AM)?)",
              Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
      Matcher matcher = p.matcher(dateStr);
      if (matcher.find() && matcher.groupCount() >= 1) {
        matches = new ArrayList<String>();
        for (int i = 1; i <= matcher.groupCount(); i++) {
          String temp = matcher.group(i);
          matches.add(temp);
        }
      } else {
        matches = Collections.EMPTY_LIST;
      }
      if (matches.size() > 0) {
        return ((String) matches.get(0)).trim();
      } else {
      }
    } catch (Exception e) {
      return "";
    }

    return dateStr;
  }
  public Properties getViewData(String viewTag) throws IOException, InterruptedException {
    Properties resPrp = new Properties();
    ArgumentListBuilder cmd = new ArgumentListBuilder();
    cmd.add("lsview");
    cmd.add("-l", viewTag);

    Pattern uuidPattern = Pattern.compile("View uuid: (.*)");
    Pattern globalPathPattern = Pattern.compile("View server access path: (.*)");
    boolean res = true;
    IOException exception = null;
    List<IOException> exceptions = new ArrayList<IOException>();

    String output = runAndProcessOutput(cmd, null, null, true, exceptions);
    // handle the use case in which view doesn't exist and therefore error is thrown
    if (!exceptions.isEmpty() && !output.contains("No matching entries found for view")) {
      throw exceptions.get(0);
    }

    if (res && exception == null) {
      String[] lines = output.split("\n");
      for (String line : lines) {
        Matcher matcher = uuidPattern.matcher(line);
        if (matcher.find() && matcher.groupCount() == 1) resPrp.put("UUID", matcher.group(1));

        matcher = globalPathPattern.matcher(line);
        if (matcher.find() && matcher.groupCount() == 1)
          resPrp.put("STORAGE_DIR", matcher.group(1));
      }
    }

    return resPrp;
  }
  public static String formatKernelVersion(String rawKernelVersion) {
    // Example (see tests for more):
    // Linux version 3.0.31-g6fb96c9 ([email protected]) \
    //     (gcc version 4.6.x-xxx 20120106 (prerelease) (GCC) ) #1 SMP PREEMPT \
    //     Thu Jun 28 11:02:39 PDT 2012

    final String PROC_VERSION_REGEX =
        "Linux version (\\S+) "
            + /* group 1: "3.0.31-g6fb96c9" */ "\\((\\S+?)\\) "
            + /* group 2: "*****@*****.**" (kernel builder) */ "(?:\\(gcc.+? \\)) "
            + /* ignore: GCC version information */ "(#\\d+) "
            + /* group 3: "#1" */ "(?:.*?)?"
            + /* ignore: optional SMP, PREEMPT, and any CONFIG_FLAGS */ "((Sun|Mon|Tue|Wed|Thu|Fri|Sat).+)"; /* group 4: "Thu Jun 28 11:02:39 PDT 2012" */

    Matcher m = Pattern.compile(PROC_VERSION_REGEX).matcher(rawKernelVersion);
    if (!m.matches()) {
      Log.e(LOG_TAG, "Regex did not match on /proc/version: " + rawKernelVersion);
      return "Unavailable";
    } else if (m.groupCount() < 4) {
      Log.e(LOG_TAG, "Regex match on /proc/version only returned " + m.groupCount() + " groups");
      return "Unavailable";
    }
    return m.group(1)
        + "\n"
        + // 3.0.31-g6fb96c9
        m.group(2)
        + " "
        + m.group(3)
        + "\n"
        + // [email protected] #1
        m.group(4); // Thu Jun 28 11:02:39 PDT 2012
  }
Example #7
0
  /**
   * Creates a new {@code UriPathTemplate} from the given {@code uriPattern}.
   *
   * @param uriPattern The pattern to be used by the template
   */
  public UriPathTemplate(String uriPattern) {
    String s = "^" + uriPattern;

    Matcher m = NAME_SPLAT_PATTERN.matcher(s);
    while (m.find()) {
      for (int i = 1; i <= m.groupCount(); i++) {
        String name = m.group(i);
        pathVariables.add(name);
        s = m.replaceFirst(NAME_SPLAT_REPLACEMENT.replaceAll("%NAME%", name));
        m.reset(s);
      }
    }

    m = NAME_PATTERN.matcher(s);
    while (m.find()) {
      for (int i = 1; i <= m.groupCount(); i++) {
        String name = m.group(i);
        pathVariables.add(name);
        s = m.replaceFirst(NAME_REPLACEMENT.replaceAll("%NAME%", name));
        m.reset(s);
      }
    }

    m = FULL_SPLAT_PATTERN.matcher(s);
    while (m.find()) {
      s = m.replaceAll(FULL_SPLAT_REPLACEMENT);
      m.reset(s);
    }

    this.uriPattern = Pattern.compile(s + "$");
  }
  /**
   * Clear the results and display notice to say an error occurred.
   *
   * @param error the error that occurred.
   */
  public void displayErrorResult(final Throwable error) {
    // match some friendly error messages.
    String errorText = null;
    if (error.getCause() != null && error.getCause() instanceof CheckstyleException) {

      for (final Pattern errorPattern : CHECKSTYLE_ERROR_PATTERNS.keySet()) {
        final Matcher errorMatcher = errorPattern.matcher(error.getCause().getMessage());
        if (errorMatcher.find()) {
          final Object[] args = new Object[errorMatcher.groupCount()];

          for (int i = 0; i < errorMatcher.groupCount(); ++i) {
            args[i] = errorMatcher.group(i + 1);
          }

          errorText = CheckStyleBundle.message(CHECKSTYLE_ERROR_PATTERNS.get(errorPattern), args);
        }
      }
    }

    if (errorText == null) {
      errorText = CheckStyleBundle.message("plugin.results.error");
    }

    treeModel.clear();
    treeModel.setRootText(errorText);

    clearProgress();
  }
  // From: line processing
  public static int detectFeature7(String[] tmp) {
    int result = 0;
    if (fromLine == 0) return result; // nothing can be done

    // String inputStr = "abbabcd";
    String inputStr = arrayOfLines[fromLine];
    // String patternStr = "(a(?:b*))+(c*)";
    String patternStr = "([A-Z][a-z]+\\s\\s?[A-Z]?[\\.]?\\s\\s?([A-Z][a-z]+))";

    // Compile and use regular expression
    Pattern mypattern = Pattern.compile(patternStr);
    Matcher matcher = mypattern.matcher(inputStr);
    boolean matchFound = matcher.find();

    if (matchFound) {
      int groupsize = matcher.groupCount() + 1;
      String[] groupStr = new String[groupsize];

      for (int j = 0; j <= matcher.groupCount(); j++) {
        groupStr[j] = matcher.group(j);
        // System.out.println("groupSTR = " + groupStr[j]);

        for (int i = lastSearchLine; i >= firstSearchLine; i--) {
          if (myMatcher(groupStr[j], tmp[i])) {
            log.debug(tmp[i]);

            return i;
          }
        }
      }
    } else {
      // another string pattern
      patternStr = "([A-Z][a-z]+\\s\\s?([A-Z][a-z]+))";

      // Compile and use regular expression
      Pattern myPattern = Pattern.compile(patternStr);
      Matcher myMatcher = myPattern.matcher(inputStr);
      matchFound = myMatcher.find();

      if (matchFound) {
        int groupsize = matcher.groupCount() + 1;
        String[] groupStr = new String[groupsize];

        for (int j = 0; j <= myMatcher.groupCount(); j++) {
          groupStr[j] = myMatcher.group(j);
          // System.out.println("groupSTR = " + groupStr[j]);

          for (int i = lastSearchLine; i >= firstSearchLine; i--) {
            if (myMatcher(groupStr[j], tmp[i])) {
              log.debug(tmp[i]);
              return i;
            }
          }
        }
      }
    }

    return result;
  }
Example #10
0
  public static AnyRequest parse(final String originalTarget) throws MalformedRequestException {
    final Matcher matcher = DOCUMENT_PATTERN.matcher(originalTarget);
    if (matcher.find() && matcher.groupCount() >= 4) {

      // Document source name plus extension, minus page identifier.
      final String fullTarget = matcher.group(2) + "." + matcher.group(4);

      final boolean showProblems = fullTarget.endsWith(ERRORPAGE_SUFFIX);

      final String targetMinusError;
      if (showProblems) {
        targetMinusError = fullTarget.substring(0, fullTarget.length() - ERRORPAGE_SUFFIX.length());
      } else {
        targetMinusError = fullTarget;
      }

      final String rawDocumentMimeType = extractExtension(targetMinusError);
      final String rawDocumentSourceName =
          targetMinusError.substring(
              0, targetMinusError.length() - rawDocumentMimeType.length() - 1);

      final String maybePageIdentifier = matcher.group(3);
      final PageIdentifier pageIdentifier =
          maybePageIdentifier == null ? null : new PageIdentifier(maybePageIdentifier);

      final RenditionMimeType renditionMimeType =
          RenditionMimeType.maybeValueOf(
              rawDocumentMimeType == null ? null : rawDocumentMimeType.toUpperCase());

      final ImmutableMap<String, String> parameterMap =
          matcher.groupCount() >= 5
              ? getQueryMap(matcher.group(5))
              : ImmutableMap.<String, String>of();
      verifyAllParameterNames(parameterMap.keySet());

      final ResourceName alternateStylesheet = extractResourceName(parameterMap);

      final ImmutableSet<Tag> tagset = extractTags(parameterMap);

      final AnyRequest request;
      if (renditionMimeType == null) {
        request = new GenericRequest(originalTarget, rawDocumentSourceName, rawDocumentMimeType);
      } else {
        request =
            new GenericRequest(
                originalTarget,
                rawDocumentSourceName,
                showProblems,
                renditionMimeType,
                pageIdentifier,
                alternateStylesheet,
                tagset);
      }
      return request;

    } else {
      throw new MalformedRequestException("Could not parse: '" + originalTarget + "'.");
    }
  }
Example #11
0
 Object invokeMethod(Object objectToInvoke) {
   Method method = getNaturalLanguageMethod().getMethod();
   List<ArgumentConverter> argumentConverters = naturalLanguageMethod.getArgumentConverters();
   Object[] args = new Object[matcher.groupCount()];
   for (int i = 0; i < matcher.groupCount(); i++) {
     String group = matcher.group(i + 1);
     args[i] = argumentConverters.get(i).convertArgument(group, naturalLanguageMethod, i);
   }
   return ReflectionUtil.invokeWithArgs(method, objectToInvoke, args);
 }
  private static String checkAttributes(final String tag, StringBuilder errorMessages) {
    if (M_goodAttributes == null) init();

    Matcher fullTag = M_patternTagPieces.matcher(tag);
    String close = "";
    StringBuilder buf = new StringBuilder();
    String leftOvers = "";

    if (fullTag.matches() && fullTag.groupCount() > 2) {
      leftOvers = fullTag.group(2);
      buf.append(fullTag.group(1));
      close = fullTag.group(fullTag.groupCount());
    } else {
      if (M_log.isDebugEnabled()) M_log.debug("Could not parse " + tag);
      return "";
    }
    String tagName = tag;
    if (tag != null && tag.length() > 2) {
      int pos = tag.indexOf(' ');
      if (pos <= 0) {
        pos = tag.indexOf('/');
      }
      if (pos <= 0) {
        pos = tag.indexOf('>');
      }
      if (pos > 0) {
        tagName = tag.substring(1, pos);
      }
    }
    Matcher matcher;
    for (int i = 0; i < M_goodAttributePatterns.length; i++) {
      matcher = M_goodAttributePatterns[i].matcher(tag);
      if (matcher.find()) {
        for (int j = 0; j < matcher.groupCount(); j++) {
          if (checkValue(tagName, matcher.group(j) + " ", errorMessages)) {
            buf.append(matcher.group(j) + " ");

            try {
              leftOvers = leftOvers.replace(matcher.group(j), "");
            } catch (Exception e) {
              M_log.warn(matcher.group(j));
              e.printStackTrace();
            }
          }
        }
      }
    }

    if (leftOvers != null && leftOvers.trim().length() > 1) {
      errorMessages.append("The HTML attribute pattern '" + leftOvers + "' is not allowed\n");
    }

    buf.append(close);
    return buf.toString();
  }
Example #13
0
 public static String[] regGroup(String text, String reg) {
   Matcher m = Pattern.compile(reg, Pattern.CASE_INSENSITIVE).matcher(text);
   if (!m.find()) {
     return null;
   }
   String[] res = new String[m.groupCount() + 1];
   for (int i = 0; i <= m.groupCount(); i++) {
     res[i] = m.group(i).trim();
   }
   return res;
 }
Example #14
0
  /** Extracts document location from a Zope-like URL ie : server/path_or_docId/view_id/tab_id . */
  @Override
  public DocumentView getDocumentViewFromUrl(String url) {
    final Pattern pattern = Pattern.compile(getPrefix() + URLPattern);
    Matcher m = pattern.matcher(url);
    if (m.matches()) {
      if (m.groupCount() >= 4) {

        // for debug
        // for (int i = 1; i < m.groupCount() + 1; i++) {
        // System.err.println(i + ": " + m.group(i));
        // }

        final String server = m.group(1);
        String uuid = m.group(2);
        final DocumentRef docRef = new IdRef(uuid);

        // get other parameters

        Map<String, String> params = new HashMap<String, String>();
        if (m.groupCount() >= 4) {
          String filePropertyPath = m.group(4);
          params.put(FILE_PROPERTY_PATH_KEY, filePropertyPath);
        }

        if (m.groupCount() >= 6) {
          String filename = m.group(6);
          try {
            filename = URLDecoder.decode(filename, "UTF-8");
          } catch (UnsupportedEncodingException e) {
            filename = StringUtils.toAscii(filename);
          }
          int jsessionidIndex = filename.indexOf(";jsessionid");
          if (jsessionidIndex != -1) {
            filename = filename.substring(0, jsessionidIndex);
          }
          params.put(FILENAME_KEY, filename);
        }

        if (m.groupCount() >= 8) {
          String query = m.group(8);
          Map<String, String> requestParams = URIUtils.getRequestParameters(query);
          if (requestParams != null) {
            params.putAll(requestParams);
          }
        }

        final DocumentLocation docLoc = new DocumentLocationImpl(server, docRef);

        return new DocumentViewImpl(docLoc, null, params);
      }
    }

    return null;
  }
Example #15
0
 public static List<String[]> regGroupAll(String text, String reg) {
   List<String[]> ans = new ArrayList<String[]>();
   Matcher m = Pattern.compile(reg, Pattern.CASE_INSENSITIVE).matcher(text);
   while (m.find()) {
     String[] res = new String[m.groupCount() + 1];
     for (int i = 0; i <= m.groupCount(); i++) {
       res[i] = m.group(i).trim();
     }
     ans.add(res);
   }
   return ans;
 }
 protected List<String> getFinderComponents(String finderName) {
   Matcher matcher = validFinderPattern.matcher(finderName);
   if (!matcher.matches()) {
     return null;
   } else {
     List<String> matches = new ArrayList<String>(matcher.groupCount());
     for (int i = 1; i <= matcher.groupCount(); i++) {
       matches.add(matcher.group(i));
     }
     return matches;
   }
 }
 public ControllerRequest(Class<? extends Controller> controllerClass, Matcher matchedUrl) {
   this.controllerClass = controllerClass;
   if (matchedUrl.groupCount() > 0) {
     List<String> argsList = new ArrayList<String>(matchedUrl.groupCount());
     for (int i = 1; i <= matchedUrl.groupCount(); i++) {
       argsList.add(matchedUrl.group(i));
     }
     this.args = argsList;
   } else {
     this.args = new ArrayList<String>(0);
   }
 }
Example #18
0
  public static String[] regexGroup(String regex, String str) {
    Pattern p = Pattern.compile(regex, Pattern.MULTILINE); // "");
    Matcher m = p.matcher(str);
    if (m.find()) {
      String[] result = new String[m.groupCount() + 1];
      for (int i = 0; i <= m.groupCount(); i++) {
        result[i] = m.group(i);
      }

      return result;
    }

    return null;
  }
Example #19
0
 /**
  * Try to parse a prefix of current string by given pattern. If succeed current string will be
  * replaced by remaining suffix. Else will return null and current string will not change.
  *
  * @param pattern
  * @return array of matcher groups if pattern successfully matches prefix of current string,
  *     otherwise - null. First element of returned array (index - 0) contains whole string matched
  *     by given pattern.
  */
 public String[] consumeOptional(Pattern pattern) {
   Matcher m = pattern.matcher(currentString);
   if (m.lookingAt()) {
     String[] result = new String[m.groupCount() + 1];
     result[0] = m.group();
     for (int i = 1; i <= m.groupCount(); i++) {
       result[i] = m.group(i);
     }
     currentString = currentString.substring(m.end());
     return result;
   } else {
     return null;
   }
 }
Example #20
0
  Request(String str) throws ParseException {
    Matcher matcher = requestPattern.matcher(str);
    if (!matcher.matches()) {
      throw new ParseException("No matches found when parsing request: " + str, 0);
    }

    if (3 != matcher.groupCount()) {
      throw new ParseException(
          "Error parsing request: " + str + " ; groupCount = " + matcher.groupCount(), 0);
    }

    this.method = matcher.group(1);
    this.url = matcher.group(2);
    this.protocol = matcher.group(3);
  }
  /** Tests {@link PatternConsts#LANG_AND_COUNTRY} regular expression. */
  public void testLangAndCountry() {
    String LC_BAD = "abc*DEF";
    Matcher m = PatternConsts.LANG_AND_COUNTRY.matcher(LC_BAD);
    if (m.matches())
      fail(
          "Language and Country pattern '"
              + PatternConsts.LANG_AND_COUNTRY.pattern()
              + "' incorrectly matches a wrong string '"
              + LC_BAD
              + "'");
    String LC_GOOD = "abc-DEF";
    m = PatternConsts.LANG_AND_COUNTRY.matcher(LC_GOOD);
    if (!m.matches())
      fail(
          "Language and Country pattern '"
              + PatternConsts.LANG_AND_COUNTRY.pattern()
              + "' does not match a good string '"
              + LC_GOOD
              + "'");
    if (m.groupCount() != 2)
      fail("Wrong group count extracted (" + m.groupCount() + "), should be 2.");
    if (!m.group(1).equals("abc")) fail("Wrong language extracted");
    if (!m.group(2).equals("DEF")) fail("Wrong country extracted");

    String L_GOOD = "abc";
    m = PatternConsts.LANG_AND_COUNTRY.matcher(L_GOOD);
    if (!m.matches())
      fail(
          "Language and Country pattern '"
              + PatternConsts.LANG_AND_COUNTRY.pattern()
              + "' does not match a good string '"
              + L_GOOD
              + "'");
    if (!m.group(1).equals("abc")) fail("Wrong language extracted");
    if (m.group(2) != null) fail("Country extracted, but it should not");

    String C_GOOD = "Z-abc";
    m = PatternConsts.LANG_AND_COUNTRY.matcher(C_GOOD);
    if (!m.matches())
      fail(
          "Language and Country pattern '"
              + PatternConsts.LANG_AND_COUNTRY.pattern()
              + "' does not match a good string '"
              + C_GOOD
              + "'");
    if (!m.group(1).equals("Z")) fail("Wrong language extracted");
    if (!m.group(2).equals("abc")) fail("Wrong country extracted");
  }
Example #22
0
  public Date getDateFromName(Path target, boolean fillEmptyDateSection) {
    String name = target.getFileName().toString();
    String year = null, month = null, day = null;
    Pattern pattern =
        Pattern.compile(
            getRegexp(mask.replaceAll(FULL_YEAR_PATTERN, "([0-9]{4})")), Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(name);
    if (matcher.find() && matcher.groupCount() > 0) {
      year = matcher.group(1).substring(2);
    }
    pattern =
        Pattern.compile(
            getRegexp(mask.replaceAll(SHORT_YEAR_PATTERN, "([0-9]{2})")), Pattern.CASE_INSENSITIVE);
    matcher = pattern.matcher(name);
    if (matcher.find() && matcher.groupCount() > 0) {
      year = matcher.group(1);
    }
    pattern =
        Pattern.compile(
            getRegexp(mask.replaceAll(MONTH_PATTERN, "([0-9]{2})")), Pattern.CASE_INSENSITIVE);
    matcher = pattern.matcher(name);
    if (matcher.find() && matcher.groupCount() > 0) {
      month = matcher.group(1);
    }
    pattern =
        Pattern.compile(
            getRegexp(mask.replaceAll(DAY_PATTERN, "([0-9]{2})")), Pattern.CASE_INSENSITIVE);
    matcher = pattern.matcher(name);
    if (matcher.find() && matcher.groupCount() > 0) {
      day = matcher.group(1);
    }

    if (fillEmptyDateSection) {
      year = year == null ? "70" : year;
      month = month == null ? "01" : month;
      day = day == null ? "01" : day;
    } else if (year == null || month == null || day == null) {
      return null;
    }

    try {
      String stringDate = String.format("%s%s%s", year, month, day);
      return new SimpleDateFormat(SHORT_DATE_PATTERN).parse(stringDate);
    } catch (ParseException ex) {
      LOGGER.error("Parse date exception", ex);
      return null;
    }
  }
Example #23
0
  public static int calculateVersion(String version) {
    if (null == version) {
      return UNKNOWN_HAZELCAST_VERSION;
    }

    Matcher matcher = VERSION_PATTERN.matcher(version);
    if (matcher.matches()) {
      try {
        int calculatedVersion =
            MAJOR_VERSION_MULTIPLIER * Integer.parseInt(matcher.group(1))
                + MINOR_VERSION_MULTIPLIER * Integer.parseInt(matcher.group(2));

        int groupCount = matcher.groupCount();
        if (groupCount >= PATCH_GROUP_COUNT) {
          String patchVersionString = matcher.group(PATCH_GROUP_COUNT);
          if (null != patchVersionString && !patchVersionString.startsWith("-")) {
            calculatedVersion += Integer.parseInt(patchVersionString);
          }
        }
        return calculatedVersion;
      } catch (Exception e) {
        Logger.getLogger(BuildInfo.class)
            .warning("Failed to calculate version using version string " + version, e);
      }
    }

    return UNKNOWN_HAZELCAST_VERSION;
  }
Example #24
0
  /**
   * Match a URI against the pattern.
   *
   * <p>If the URI matches against the pattern then the capturing group values (if any) will be
   * added to a list passed in as parameter.
   *
   * @param uri the uri to match against the template.
   * @param groupValues the list to add the values of a pattern's capturing groups if matching is
   *     successful. The values are added in the same order as the pattern's capturing groups. The
   *     list is cleared before values are added.
   * @return true if the URI matches the pattern, otherwise false.
   * @throws IllegalArgumentException if the uri or capturingGroupValues is null.
   */
  public final boolean match(CharSequence uri, List<String> groupValues) {
    if (groupValues == null) throw new IllegalArgumentException();

    // Check for match against the empty pattern
    if (uri == null || uri.length() == 0) return (regexPattern == null) ? true : false;
    else if (regexPattern == null) return false;

    // Match the URI to the URI template regular expression
    Matcher m = regexPattern.matcher(uri);
    if (!m.matches()) return false;

    groupValues.clear();
    if (groupIndexes.length > 0) {
      for (int i = 0; i < groupIndexes.length - 1; i++) {
        groupValues.add(m.group(groupIndexes[i]));
      }
    } else {
      for (int i = 1; i <= m.groupCount(); i++) {
        groupValues.add(m.group(i));
      }
    }

    // TODO check for consistency of different capturing groups
    // that must have the same value

    return true;
  }
Example #25
0
  /**
   * Return info about this regex. Does it match the text, how many groups, etc.
   *
   * @param text body of text
   * @param regex regex expression to run against the text
   * @param flags Pattern.DOTALL, MULTILINE, CASE_INSENSITIVE, etc.
   * @return text about matches
   */
  public static String getRegexInfo(String text, String regex, int flags) {

    try {

      if (text.isEmpty() || regex.isEmpty()) {
        return "";
      }

      Pattern pat = Pattern.compile(regex, flags);
      Matcher mat = pat.matcher(text);

      int matchCount = 0;
      StringBuilder builder = new StringBuilder();

      while (mat.find()) {

        matchCount++;

        builder.append(String.format("  Match: \"%s\"\n", mat.group(0)));

        // Weirdness alert: groupCount() doesn't include group(0), which is the full match.
        // Thus if groupCount() == 1, we want to display group(1), not group(0).

        for (int gCount = 1; gCount <= mat.groupCount(); gCount++) {
          builder.append(String.format("  Group %d: \"%s\"\n", gCount, mat.group(gCount)));
        }

        builder.append("\n");
      }

      return String.format("Matches: %d\n%s", matchCount, builder.toString());
    } catch (Exception e) {
      return "";
    }
  }
Example #26
0
  /**
   * Obtains the version numbers of CraftBukkit, Minecraft, and Minequery.
   *
   * @return A <code>Map</code> of versions.
   */
  private static Map<String, String> getVersions() {
    Map<String, String> versions = new HashMap<String, String>();

    // Find the CraftBukkit build and the Minecraft version.
    String version = minequery.getServer().getVersion();
    Matcher matcher = Pattern.compile("git-Bukkit-.*-b(\\d+)jnks \\(MC: (.*)\\)").matcher(version);
    List<Object> matchList = new ArrayList<Object>();

    while (matcher.find()) {
      for (int i = 1; i <= matcher.groupCount(); i++) {
        matchList.add(matcher.group(i));
      }
    }

    // One day the version string could completely change,
    // so check if we have at last two matches.
    if (matchList.size() > 1) {
      versions.put("craftbukkit", matchList.get(0).toString());
      versions.put("minecraft", matchList.get(1).toString());
    }

    // Add the Minequery version.
    versions.put("minequery", minequery.getDescription().getVersion());

    return versions;
  }
Example #27
0
  /**
   * @param string
   * @param pattern
   * @param flags
   * @return
   * @throws XPathException
   */
  private Sequence match(String string, String pattern, int flags) throws XPathException {
    try {
      Matcher matcher;
      if (cachedRegexp == null
          || (!cachedRegexp.equals(pattern))
          || flags != cachedPattern.flags()) {
        matcher = Pattern.compile(pattern, flags).matcher(string);
        cachedPattern = matcher.pattern();
        cachedRegexp = string;
      } else {
        matcher = cachedPattern.matcher(string);
      }

      if (!matcher.find()) {
        return Sequence.EMPTY_SEQUENCE;
      } else {
        int items = matcher.groupCount() + 1;
        Sequence seq = new ValueSequence();
        seq.add(new StringValue(string));
        for (int i = 1; i < items; i++) {
          String val = matcher.group(i);
          if (val == null) {
            val = "";
          }
          seq.add(new StringValue(val));
        }
        return seq;
      }
    } catch (PatternSyntaxException e) {
      throw new XPathException("Invalid regular expression: " + e.getMessage(), e);
    }
  }
  /** Parse PID line from 'qstat' (Cmd) */
  public String parsePidLine(String line) {
    if (pidPattern == null || line.isEmpty()) return "";

    // Pattern pattern = Pattern.compile("Your job (\\S+)");
    Matcher matcher = pidPattern.matcher(line);
    if (matcher.find()) {
      String pid = null;
      if (matcher.groupCount() > 0) pid = matcher.group(1); // Use first group
      else pid = matcher.group(0); // Use whole pattern

      if (debug)
        log(
            "Regex '"
                + pidPatternStr
                + "' ("
                + Config.PID_CHECK_TASK_RUNNING_REGEX
                + ") matched '"
                + pid
                + "' in line: '"
                + line
                + "'");
      return pid;
    } else if (debug)
      log(
          "Regex '"
              + pidPatternStr
              + "' ("
              + Config.PID_CHECK_TASK_RUNNING_REGEX
              + ") did NOT match line: '"
              + line
              + "'");

    return line;
  }
Example #29
0
  public static void main(String[] args) throws PatternSyntaxException {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter pattern: ");
    String patternString = in.nextLine();

    Pattern pattern = Pattern.compile(patternString);

    while (true) {
      System.out.println("Enter string to match: ");
      String input = in.nextLine();
      if (input == null || input.equals("")) return;
      Matcher matcher = pattern.matcher(input);
      if (matcher.matches()) {
        System.out.println("Match");
        int g = matcher.groupCount();
        if (g > 0) {
          for (int i = 0; i < input.length(); i++) {
            // Print any empty groups
            for (int j = 1; j <= g; j++)
              if (i == matcher.start(j) && i == matcher.end(j)) System.out.print("()");
            // Print ( for non-empty groups starting here
            for (int j = 1; j <= g; j++)
              if (i == matcher.start(j) && i != matcher.end(j)) System.out.print('(');
            System.out.print(input.charAt(i));
            // Print ) for non-empty groups ending here
            for (int j = 1; j <= g; j++)
              if (i + 1 != matcher.start(j) && i + 1 == matcher.end(j)) System.out.print(')');
          }
          System.out.println();
        }
      } else System.out.println("No match");
    }
  }
Example #30
0
  /**
   * 检验是否有效的邮件地址
   *
   * @param addr
   * @return
   */
  public static boolean isValidEmailAddress(String addr) {
    if (addr == null) return false;
    addr = addr.trim();
    if (addr.length() == 0) return false;
    Matcher matcher = basicAddressPattern.matcher(addr);
    if (!matcher.matches()) return false;
    String userPart = matcher.group(1);
    String domainPart = matcher.group(2);
    matcher = validUserPattern.matcher(userPart);
    if (!matcher.matches()) return false;
    matcher = ipDomainPattern.matcher(domainPart);
    if (matcher.matches()) {
      for (int i = 1; i < 5; i++) {
        String num = matcher.group(i);
        if (num == null) return false;
        if (Integer.parseInt(num) > 254) return false;
      }

      return true;
    }
    matcher = domainPattern.matcher(domainPart);
    if (matcher.matches()) {
      String tld = matcher.group(matcher.groupCount());
      matcher = tldPattern.matcher(tld);
      return tld.length() == 3 || matcher.matches();
    } else {
      return false;
    }
  }