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;
 }
Example #2
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 #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;
  }
  /**
   * {@inheritDoc} <br>
   * Overridden to always compute the class name and the object number.
   *
   * @see org.xwiki.model.reference.EntityReference#setName(java.lang.String)
   */
  @Override
  protected void setName(String name) {
    super.setName(name);

    String classReferenceStr;
    String objectNumberStr;

    Matcher matcher = NUMBERPATTERN.matcher(name);
    if (matcher.find()) {
      if (matcher.group(1).length() % 2 == 0) {
        classReferenceStr = name.substring(0, matcher.end(1));
        objectNumberStr = matcher.group(2);
      } else {
        classReferenceStr = name;
        objectNumberStr = null;
      }
    } else {
      classReferenceStr = name;
      objectNumberStr = null;
    }

    this.xclassReference = RESOLVER.resolve(classReferenceStr);
    if (objectNumberStr != null) {
      this.objectNumber = Integer.valueOf(objectNumberStr);
    }
  }
  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;
  }
Example #6
0
 /**
  * Tries to parse the given input text.
  *
  * @param input the text to parse
  * @return the parsed {@link LedVisualize} or null
  */
 static Target tryParseTarget(String input) {
   CmdAndAddressRet header = CmdAndAddressRet.parse(input, false);
   if (header != null) {
     Matcher matcher;
     switch (header.getCmd().toUpperCase()) {
       case "LED_STATE":
         if ((matcher = PATTERN_LED.matcher(header.getRestInput())).matches()) {
           int ledId = Integer.parseInt(matcher.group("ledId")) - 1;
           if (ledId < 12) {
             String[] stateTexts =
                 new String[] {
                   "off", "on", "blink", "flicker" // Defaults
                 };
             for (int i = 0; i < 4; ++i) {
               String s = matcher.group(String.format("text%d", i));
               if (s != null) {
                 stateTexts[i] = s;
               }
             }
             return new LedVisualize((LcnAddrMod) header.getAddr(), ledId, stateTexts);
           }
         }
         break;
     }
   }
   return null;
 }
  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;
  }
Example #8
0
  // helper method for repeatHelper.
  private static int findInterval(String inputText) {
    HashMap<String, Integer> wordsToNum = new HashMap<String, Integer>();
    String[] words =
        new String[] {
          "one", "two", "three", "four", "five", "six",
          "seven", "eight", "nine", "ten", "eleven", "twelve"
        };
    for (int i = 0; i < words.length; i++) {
      wordsToNum.put(words[i], i + 1);
      wordsToNum.put(Integer.toString(i + 1), i + 1);
    }
    wordsToNum.put("other", 2);

    Pattern pattern = Pattern.compile("(?i)\\bevery (\\w*)\\b");
    int interval = 1;
    Matcher m = pattern.matcher(inputText);
    if (m.find() && m.group(1) != null) {
      String intervalStr = m.group(1);
      if (wordsToNum.containsKey(intervalStr)) {
        interval = wordsToNum.get(intervalStr);
      } else {
        try {
          interval = Integer.parseInt(intervalStr);
        } catch (NumberFormatException e) {
          // Ah well
        }
      }
    }
    return interval;
  }
  public static void main(String[] args) throws IOException {
    // Get input html
    StringBuffer sb = new StringBuffer();
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    for (String str = in.readLine(); str != null; str = in.readLine()) {
      sb.append("\n" + str);
    }
    String html = sb.toString();

    // Match all the questions
    Matcher matcher =
        Pattern.compile(
                "<\\s*div\\s+class\\s*=\\s*\"question-summary\"\\s*id\\s*=\\s*\"question-summary-(?<id>\\d+)\"\\s*>"
                    + ".*?<\\s*div\\s+class\\s*=\\s*\"summary\"\\s*>"
                    + ".*?<\\s*a\\s+.*?class\\s*=\\s*\"question-hyperlink\"\\s*>"
                    + "(?<title>.*?)"
                    + "</\\s*a\\s*>.*?<\\s*div\\s+class\\s*=\\s*\"user-action-time\"\\s*>"
                    + ".*?<\\s*span\\s+.*?>(?<time>.*?)</\\s*span\\s*>",
                Pattern.CASE_INSENSITIVE | Pattern.DOTALL)
            .matcher(html);

    // Output the information
    while (matcher.find()) {
      String id = matcher.group("id");
      String title = matcher.group("title");
      String time = matcher.group("time");
      System.out.println(id + ";" + title + ";" + time);
    }
  }
  private void directPage(String text) {

    text = text.trim();
    // LOG.debug("directPage(" + text + ')');
    Matcher mat = PAGE_DIRECTIVE_PATTERN.matcher(text);
    for (int ix = 0; ; ) {
      if (!mat.find(ix)) {
        return;
      }
      String name = mat.group(1);
      String value = mat.group(2);
      if (name.equals(IMPORT_DIRECTIVE)) {
        pageImport(value);
      }
      if (name.equalsIgnoreCase(CONTENT_TYPE_DIRECTIVE)) {
        contentType(value);
      }
      if (name.equalsIgnoreCase(EXPRESSION_CODEC_DIRECTIVE)) {
        expressionCodecDirectiveValue = value.trim();
      }
      if (name.equalsIgnoreCase(EXPRESSION_CODEC_DIRECTIVE_ALIAS)) {
        expressionCodecDirectiveValue = value.trim();
      }
      if (name.equalsIgnoreCase(STATIC_CODEC_DIRECTIVE)) {
        staticCodecDirectiveValue = value.trim();
      }
      if (name.equalsIgnoreCase(OUT_CODEC_DIRECTIVE)) {
        outCodecDirectiveValue = value.trim();
      }
      if (name.equalsIgnoreCase(TAGLIB_CODEC_DIRECTIVE)) {
        taglibCodecDirectiveValue = value.trim();
      }
      ix = mat.end();
    }
  }
  /**
   * The coder shall be able to decode all stock mechs.
   *
   * @throws Exception
   */
  @Test
  public void testDecodeAllStock() throws Exception {
    InputStream is = LoadoutCoderV2.class.getResourceAsStream("/resources/lsmlv2stock.txt");
    Scanner sc = new Scanner(is);

    Base64 base64 = new Base64();

    // [JENNER JR7-D(F)]=lsml://rQAD5AgQCAwOFAYQCAwIuipmzMO3aIExIyk9jt2DMA==
    while (sc.hasNextLine()) {
      String line = sc.nextLine();
      Pattern pat = Pattern.compile("\\[([^\\]]*)\\]\\s*=\\s*lsml://(\\S*).*");
      Matcher m = pat.matcher(line);
      m.matches();
      ChassisBase chassi = ChassisDB.lookup(m.group(1));
      String lsml = m.group(2);
      LoadoutStandard reference = new LoadoutStandard(chassi.getName());
      LoadoutStandard decoded = cut.decode(base64.decode(lsml.toCharArray()));

      // Name is not encoded
      OperationStack stack = new OperationStack(0);
      stack.pushAndApply(new OpRename(decoded, null, reference.getName()));

      // Verify
      assertEquals(reference, decoded);
    }

    sc.close();
  }
Example #12
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;
  }
  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;
  }
Example #14
0
  public void run() {
    Scanner in = new Scanner(System.in);

    while (true) {
      String msg;

      try {
        msg = in.nextLine().trim();

        Pattern p = Pattern.compile("^@(\\w+)\\s+(.+)");
        Matcher m = p.matcher(msg);

        if (msg.equals("quit")) {
          this.server.disconnect(this);
          in.close();
          System.exit(0);
        } else if (msg.equals("list")) {
          this.server.list(this);
        } else if (m.find()) {
          String receiverName = m.group(1);
          BaseClient receiver = server.lookup(receiverName);

          if (receiver != null) {
            receiver.receive(this.name, "<private> %s".format(m.group(2)));
          } else {
            this.server.broadcast(this.name, m.group(2));
          }
        } else {
          this.server.broadcast(this.name, msg);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
Example #15
0
 private SlimTestResult doRange(Matcher matcher) {
   boolean closedLeft = matcher.group(2).equals("=");
   boolean closedRight = matcher.group(3).equals("=");
   boolean pass =
       (arg1 < v && v < arg2) || (closedLeft && arg1 == v) || (closedRight && arg2 == v);
   return rangeMessage(pass);
 }
  private String urlEncodeQueryParams(String url) {
    final StringBuilder sb = new StringBuilder((int) (url.length() * 1.2));

    final int pos = url.indexOf('?');
    if (pos > 0) {
      // split url into base and query expression
      final String queryExpr = url.substring(pos + 1);
      LOG.trace("queryExpr {}", queryExpr);

      final Pattern p =
          Pattern.compile(
              "\\G([A-Za-z0-9-_]+)=([A-Za-z0-9-+:#|^\\.,<>;%*\\(\\)_/\\[\\]\\{\\}\\\\ ]+)[&]?");
      final Matcher m = p.matcher(queryExpr);
      while (m.find()) {
        LOG.trace("group 1: {}   group 2: {}", m.group(1), m.group(2));
        if (sb.length() > 0) {
          sb.append("&");
        }
        sb.append(m.group(1));
        sb.append("=");
        try {
          // URL Encode the value of each query parameter
          sb.append(URLEncoder.encode(m.group(2), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
          // Ignore - We know UTF-8 is supported
        }
      }

      LOG.trace("new query Expr: {}", sb.toString());

      sb.insert(0, url.substring(0, pos + 1));
    }
    return sb.toString();
  }
Example #17
0
  public void parseStatusXml(String statusXml) {
    try {
      Document statusDoc = SubmissionUtils.emptyDocument();
      SubmissionUtils.transform(new StringReader(statusXml), statusDoc);

      if (statusDoc.getDocumentElement().getTagName().equals("error")) {
        String runName = statusDoc.getElementsByTagName("RunName").item(0).getTextContent();
        String runDirRegex = "(\\d{6})_([A-z0-9]+)_(\\d+)_[A-z0-9_]*";
        Matcher m = Pattern.compile(runDirRegex).matcher(runName);
        if (m.matches()) {
          setStartDate(new SimpleDateFormat("yyMMdd").parse(m.group(1)));
          setInstrumentName(m.group(2));
        }
        setRunName(runName);
        setHealth(HealthType.Unknown);
      } else {
        String runStarted = statusDoc.getElementsByTagName("RunStarted").item(0).getTextContent();
        setStartDate(new SimpleDateFormat("EEEE, MMMMM dd, yyyy h:mm aaa").parse(runStarted));
        setInstrumentName(
            statusDoc.getElementsByTagName("InstrumentName").item(0).getTextContent());
        setRunName(statusDoc.getElementsByTagName("RunName").item(0).getTextContent());
        setHealth(HealthType.Unknown);
      }
      setXml(statusXml);
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (TransformerException e) {
      e.printStackTrace();
    } catch (ParseException e) {
      e.printStackTrace();
    }
  }
Example #18
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);
        }
      }
    }
  private String blankSectionHeaders(String markup, StringBuffer context) {

    Pattern p = Pattern.compile("(={2,})([^=]+)\\1");
    Matcher m = p.matcher(markup);

    int lastPos = 0;
    StringBuilder sb = new StringBuilder();

    while (m.find()) {
      sb.append(markup.substring(lastPos, m.start()));
      sb.append(getSpaceString(m.group().length()));

      String title = m.group(2).trim();

      if (!title.equalsIgnoreCase("see also")
          && !title.equalsIgnoreCase("external links")
          && !title.equalsIgnoreCase("references")
          && !title.equalsIgnoreCase("further reading")) context.append("\n").append(title);

      lastPos = m.end();
    }

    sb.append(markup.substring(lastPos));
    return sb.toString();
  }
Example #20
0
File: Z.java Project: adamldavis/z
  protected void addFieldLinks() {
    log.info("addFieldLinks()");
    final Map<String, ZNode> nodeMap = new HashMap<String, ZNode>();
    final Pattern patt = Pattern.compile("(private |protected |public |final |static )+\\s*(\\w+)");

    // TODO redo this to actually include packages
    for (ZNode node : selectedNode.getSubmodules()) {
      if (node.getNodeType() == ZNodeType.CLASS) {
        nodeMap.put(node.getName(), node);
      }
    }
    log.info("nodeMap={}", nodeMap);
    for (ZNode node : selectedNode.getSubmodules()) {
      for (String line : node.getCodeLines()) {
        final Matcher matcher = patt.matcher(line);
        if (matcher.find()) {
          log.info("group2={}", matcher.group(2));
          if (nodeMap.containsKey(matcher.group(2))) {
            links.add(new ZNodeLink(node, nodeMap.get(matcher.group(2)), LinkType.HAS_A));
          }
        }
      }
    }
    // just add 1 so there's at least 1
    links.add(new ZNodeLink(selectedNode, selectedNode, LinkType.HAS_A));
  }
Example #21
0
  // Chamando Robot
  public static void robot() throws Exception {
    Database db = new Database();
    db.connect();
    ResultSet rs = Page.findAll(db);

    Page p = null;
    while ((p = Page.next(rs)) != null) {
      String body = Robot.get(p.getUrl());

      // procurar por urls dentro do body
      // buscar por essas paginas

      // String expr = "href=\"([^\"]*)";
      String ereg = "href=\"https{0,1}:\\/\\/([^\"]*)\"";
      Pattern pt = Pattern.compile(ereg);
      Matcher m = pt.matcher(body);

      while (m.find()) {
        System.out.println(m.group());
        String[] _url = m.group().split("\"");
        Page.newUrl(_url[1]);
      }

      p.setBody(body);
      p.update();
    }

    db.close();
  }
Example #22
0
 /**
  * Checks a prospective crontab specification to see if it could benefit from balanced hashes.
  *
  * @param spec a (legal) spec
  * @return a similar spec that uses a hash, if such a transformation is necessary; null if it is
  *     OK as is
  * @since 1.510
  */
 public static @CheckForNull String hashify(String spec) {
   if (spec.contains("H")) {
     // if someone is already using H, presumably he knows what it is, so a warning is likely false
     // positive
     return null;
   } else if (spec.startsWith("*/")) { // "*/15 ...." (every N minutes) to hash
     return "H" + spec.substring(1);
   } else if (spec.matches("\\d+ .+")) { // "0 ..." (certain minute) to hash
     return "H " + spec.substring(spec.indexOf(' ') + 1);
   } else {
     Matcher m = Pattern.compile("0(,(\\d+)(,\\d+)*)( .+)").matcher(spec);
     if (m.matches()) { // 0,15,30,45 to H/15
       int period = Integer.parseInt(m.group(2));
       if (period > 0) {
         StringBuilder b = new StringBuilder();
         for (int i = period; i < 60; i += period) {
           b.append(',').append(i);
         }
         if (b.toString().equals(m.group(1))) {
           return "H/" + period + m.group(4);
         }
       }
     }
     return null;
   }
 }
  @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 Dependency toDependency(String id, String version, String type) throws ResolveException {
    Matcher matcher = PARSER_ID.matcher(id);
    if (!matcher.matches()) {
      throw new ResolveException(
          "Bad id " + id + ", expected format is <groupId>:<artifactId>[:<classifier>]");
    }

    Dependency dependency = new Dependency();

    dependency.setGroupId(matcher.group(1));
    dependency.setArtifactId(matcher.group(2));
    if (matcher.group(4) != null) {
      dependency.setClassifier(StringUtils.defaultString(matcher.group(4), ""));
    }

    if (version != null) {
      dependency.setVersion(version);
    }

    if (type != null) {
      dependency.setType(type);
    }

    return dependency;
  }
Example #25
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;
  }
  /**
   * 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);
  }
Example #27
0
  /**
   * Parse a (possibly) indexed path segment out of a string. Make sure no path delimiters appear in
   * the string, as this would not be an individual path segment.
   *
   * @param string a string to parse.
   * @return an PathSegment object.
   * @throws PathSegmentSyntaxException if invalid index value or key segment delimiter appears in
   *     the input string.
   */
  public static PathSegment parse(String string) throws PathSegmentSyntaxException {
    if (string == null || string.trim().isEmpty()) return null;

    string = string.trim();

    if (string.contains(PATH_SEPARATOR))
      throw new PathSegmentSyntaxException("Path segment parsing error.");

    Matcher matcher = INDEX_PATTERN.matcher(string);

    if (!matcher.find()) return new PathSegment(string, null); // Not an indexed key

    String name = matcher.group(1);
    String indexStr = matcher.group(2);

    int index;

    try {
      index = Integer.parseInt(indexStr);
    } catch (NumberFormatException e) {
      // Should never happen as the regex only matches integers in this group
      throw new PathSegmentSyntaxException("Only integer key indices are allowed");
    }

    return new PathSegment(name, index);
  }
Example #28
0
 private SlimTestResult evaluateCustomComparatorIfPresent() {
   SlimTestResult message = null;
   if (customComparatorRegistry == null) {
     return null;
   }
   Matcher customComparatorMatcher = customComparatorPattern.matcher(expression);
   if (customComparatorMatcher.matches()) {
     String prefix = customComparatorMatcher.group(1);
     CustomComparator customComparator =
         customComparatorRegistry.getCustomComparatorForPrefix(prefix);
     if (customComparator != null) {
       String expectedString = customComparatorMatcher.group(2);
       try {
         if (customComparator.matches(actual, expectedString)) {
           message = SlimTestResult.pass(expectedString + " matches " + actual);
         } else {
           message = SlimTestResult.fail(expectedString + " doesn't match " + actual);
         }
       } catch (Exception e) {
         message =
             SlimTestResult.fail(
                 expectedString + " doesn't match " + actual + ":\n" + e.getMessage());
       }
     }
   }
   return message;
 }
 /** {@inheritDoc} */
 @Override
 protected SCMRevision retrieve(String unparsedRevision, TaskListener listener)
     throws IOException, InterruptedException {
   try {
     listener.getLogger().println("Opening connection to " + remoteBase);
     SVNURL repoURL = SVNURL.parseURIEncoded(remoteBase);
     SVNRepositoryView repository = openSession(repoURL);
     String repoPath =
         SubversionSCM.DescriptorImpl.getRelativePath(repoURL, repository.getRepository());
     String base;
     long revision;
     Matcher pathAtRev = Pattern.compile("(.+)@(\\d+)").matcher(unparsedRevision);
     if (pathAtRev.matches()) {
       base = pathAtRev.group(1);
       revision = Long.parseLong(pathAtRev.group(2));
     } else {
       base = unparsedRevision;
       revision = -1;
     }
     String path = SVNPathUtil.append(repoPath, base);
     long resolvedRevision = repository.getNode(path, -1).getRevision();
     if (resolvedRevision == -1) {
       listener.getLogger().println("Could not find " + path);
       return null;
     }
     return new SCMRevisionImpl(new SCMHead(base), revision == -1 ? resolvedRevision : revision);
   } catch (SVNException e) {
     throw new IOException(e);
   }
 }
  @Override
  public Talk convertLineToTalk(String line) {

    if (line == null || line.isEmpty()) {
      throw new IllegalArgumentException("line must not be null or empty");
    }

    line = line.replaceAll("\\s+", " ").trim();
    Pattern pattern = Pattern.compile("(.*)(\\s){1}([0-2]?[0-9]?[0-9]{1}min|lightning)\\b");
    Matcher matcher = pattern.matcher(line);
    if (!matcher.matches()) {
      LOG.log(Level.SEVERE, "Line [{0}] is not recognised by the converter", line);
      throw new ProposalConverterException();
    }

    final String title = matcher.group(1);
    final String duration = matcher.group(3);
    int durationMinutes = 0;

    if (duration.equals(IProposalLineConverter.LIGHTNING_TEXT)) {
      durationMinutes = IProposalLineConverter.LIGHTNING_DURATION;
    } else {
      try {
        durationMinutes = Integer.parseInt(duration.substring(0, duration.indexOf(MINUTE_SUFFIX)));
      } catch (NumberFormatException e) {
        LOG.log(Level.SEVERE, "NumberFormatException while parsing minutes into Integer", e);
        throw new ProposalConverterException();
      }
    }

    return new Talk(title, durationMinutes);
  }