@Test
 public void testEqualsWithSamePatternButDiffFlagsGetsFalse() {
   Pattern p1 = Pattern.compile("(a)(b)(?:c)(?<named>x)");
   Pattern p2 =
       Pattern.compile("(a)(b)(?:c)(?<named>x)", java.util.regex.Pattern.CASE_INSENSITIVE);
   assertFalse(p1.equals(p2));
 }
 @Test
 public void testIndexOfWithInvalidPositiveInstanceIndex() {
   Pattern p = Pattern.compile("(a)(?<named>x)(b)(?:c)(?<named>y)");
   thrown.expect(IndexOutOfBoundsException.class);
   thrown.expectMessage("Index: 10000000, Size: 2");
   assertEquals(-1, p.indexOf("named", 10000000));
 }
Example #3
0
 GroupPattern(Pattern p1, Pattern p2) {
   super(
       p1.isNullable() && p2.isNullable(),
       combineHashCode(GROUP_HASH_CODE, p1.hashCode(), p2.hashCode()),
       p1,
       p2);
 }
Example #4
0
  /**
   * This method exports the single pattern decision instance to the XML. It MUST be called by an
   * XML exporter, as this will not have a complete header.
   *
   * @param ratDoc The ratDoc generated by the XML exporter
   * @return the SAX representation of the object.
   */
  public Element toXML(Document ratDoc) {
    Element decisionE;
    RationaleDB db = RationaleDB.getHandle();

    // Now, add pattern to doc
    String entryID = db.getRef(this);
    if (entryID == null) {
      entryID = db.addPatternDecisionRef(this);
    }

    decisionE = ratDoc.createElement("DR:patternDecision");
    decisionE.setAttribute("rid", entryID);
    decisionE.setAttribute("name", name);
    decisionE.setAttribute("type", type.toString());
    decisionE.setAttribute("phase", devPhase.toString());
    decisionE.setAttribute("status", status.toString());
    // decisionE.setAttribute("artifact", artifact);

    Element descE = ratDoc.createElement("description");
    Text descText = ratDoc.createTextNode(description);
    descE.appendChild(descText);
    decisionE.appendChild(descE);

    // Add child pattern references...
    Iterator<Pattern> cpi = candidatePatterns.iterator();
    while (cpi.hasNext()) {
      Pattern cur = cpi.next();
      Element curE = ratDoc.createElement("refChildPattern");
      Text curText = ratDoc.createTextNode("p" + new Integer(cur.getID()).toString());
      curE.appendChild(curText);
      decisionE.appendChild(curE);
    }

    return decisionE;
  }
Example #5
0
  private void readPattern(BufferedInputStream in, Pattern p) throws IOException {
    // Pattern header length
    read(in, 4);

    // Packing type (always 0)
    in.read();

    // Number of rows in pattern (1...256)
    int rows = make16Bit(read(in, 2));

    // Packed patterndata size
    int size = make16Bit(read(in, 2));

    int data[];
    if (size == 0) {
      data = new int[0];
    } else {
      byte[] b = read(in, size);
      data = new int[size];
      for (int i = 0; i < size; i++) {
        data[i] = b[i];
      }
    }
    p.setData(data);
    p.setRows(rows);
  }
Example #6
0
 public void testInvalidGroup(String text, String regexp, int group) {
   Pattern p = Pattern.compile(regexp, options);
   Matcher m = p.matcher(utf8Slice(text));
   m.find();
   m.group(group);
   fail(); // supposed to have exception by now
 }
Example #7
0
  public void testGroup(String text, String regexp, String[] output) {
    // RE2
    Pattern p = Pattern.compile(regexp, options);
    Matcher matchString = p.matcher(utf8Slice(text));
    assertEquals(true, matchString.find());
    assertEquals(utf8Slice(output[0]), matchString.group());
    for (int i = 0; i < output.length; i++) {
      assertEquals(output[i] == null ? null : utf8Slice(output[i]), matchString.group(i));
    }
    assertEquals(output.length - 1, matchString.groupCount());

    // JDK
    java.util.regex.Pattern pj = java.util.regex.Pattern.compile(regexp);
    java.util.regex.Matcher matchStringj = pj.matcher(text);
    // java.util.regex.Matcher matchBytes =
    //   p.matcher(text.getBytes(Charsets.UTF_8));
    assertEquals(true, matchStringj.find());
    // assertEquals(true, matchBytes.find());
    assertEquals(output[0], matchStringj.group());
    // assertEquals(output[0], matchBytes.group());
    for (int i = 0; i < output.length; i++) {
      assertEquals(output[i], matchStringj.group(i));
      // assertEquals(output[i], matchBytes.group(i));
    }
  }
 @Test
 public void testSuffix() {
   Pattern p = new Pattern("a/");
   assertEquals(1, p.size());
   assertEquals("a", p.peekLast());
   assertEquals("a", p.get(0));
 }
 @Test
 public void testStandardPatternGetsOrigWithoutNamed() {
   final String ORIG_PATT = "(a)(b)(?:c)(?<named>x)";
   final String PATT_W_NO_NAMED_GRPS = "(a)(b)(?:c)(x)";
   Pattern p = Pattern.compile(ORIG_PATT);
   assertEquals(PATT_W_NO_NAMED_GRPS, p.standardPattern());
 }
Example #10
0
 @Test
 public void testIndexOfNamedGroupContainingSpecialConstruct() {
   Pattern p =
       Pattern.compile(
           "\\d{2}/\\d{2}/\\d{4}: EXCEPTION - (?<exception>(?s)(.+(?:Exception|Error)[^\\n]+(?:\\s++at [^\\n]+)++)(?:\\s*\\.{3}[^\\n]++)?\\s*)\\n");
   assertEquals(0, p.indexOf("exception"));
 }
Example #11
0
 @Test
 public void test6() {
   Pattern p = new Pattern("//a//b");
   assertEquals(2, p.size());
   assertEquals("a", p.get(0));
   assertEquals("b", p.get(1));
 }
Example #12
0
  private void scanDir(File dir, List<Pattern> includes) {
    if (!dir.canRead()) return;

    // See if patterns are specific enough to avoid scanning every file in the directory.
    boolean scanAll = false;
    for (Pattern include : includes) {
      if (include.value.indexOf('*') != -1 || include.value.indexOf('?') != -1) {
        scanAll = true;
        break;
      }
    }

    if (!scanAll) {
      // If not scanning all the files, we know exactly which ones to include.
      List matchingIncludes = new ArrayList(1);
      for (Pattern include : includes) {
        if (matchingIncludes.isEmpty()) matchingIncludes.add(include);
        else matchingIncludes.set(0, include);
        process(dir, include.value, matchingIncludes);
      }
    } else {
      // Scan every file.
      for (String fileName : dir.list()) {
        // Get all include patterns that match.
        List<Pattern> matchingIncludes = new ArrayList(includes.size());
        for (Pattern include : includes)
          if (include.matches(fileName)) matchingIncludes.add(include);
        if (matchingIncludes.isEmpty()) continue;
        process(dir, fileName, matchingIncludes);
      }
    }
  }
Example #13
0
  private void replaceDeclarations(
      DeclarationScopeResolver resolver, Pattern pattern, Constraint constraint) {
    Declaration[] decl = constraint.getRequiredDeclarations();
    for (Declaration aDecl : decl) {
      Declaration resolved = resolver.getDeclaration(null, aDecl.getIdentifier());

      if (constraint instanceof MvelConstraint && ((MvelConstraint) constraint).isUnification()) {
        if (ClassObjectType.DroolsQuery_ObjectType.isAssignableFrom(
            resolved.getPattern().getObjectType())) {
          Declaration redeclaredDeclr =
              new Declaration(
                  resolved.getIdentifier(),
                  ((MvelConstraint) constraint).getFieldExtractor(),
                  pattern,
                  false);
          pattern.addDeclaration(redeclaredDeclr);
        } else if (resolved.getPattern() != pattern) {
          ((MvelConstraint) constraint).unsetUnification();
        }
      }

      if (resolved != null && resolved != aDecl && resolved.getPattern() != pattern) {
        constraint.replaceDeclaration(aDecl, resolved);
      } else if (resolved == null) {
        // it is probably an implicit declaration, so find the corresponding pattern
        Pattern old = aDecl.getPattern();
        Pattern current = resolver.findPatternByIndex(old.getIndex());
        if (current != null && old != current) {
          resolved = new Declaration(aDecl.getIdentifier(), aDecl.getExtractor(), current);
          constraint.replaceDeclaration(aDecl, resolved);
        }
      }
    }
  }
Example #14
0
  /**
   * Get node number (level="multiple"). Return a vector giving the hierarchic position of this
   * node. See the XSLT spec for details.
   *
   * @exception XPathException
   * @param node The node to be numbered
   * @param count Pattern that identifies which nodes (ancestors and their previous siblings) should
   *     be counted. Default (null) is the element name if the current node is an element, or
   *     "node()" otherwise.
   * @param from Pattern that specifies where counting starts from. Default (null) is the root node.
   *     Only nodes below the first (most recent) node that matches the 'from' pattern are counted.
   * @param controller The controller for the transformation
   * @return a vector containing for each ancestor-or-self that matches the count pattern and that
   *     is below the nearest node that matches the from pattern, an Integer which is one greater
   *     than the number of previous siblings that match the count pattern.
   */
  public static List getNumberMulti(
      NodeInfo node, Pattern count, Pattern from, Controller controller) throws XPathException {

    // checkNumberable(node);

    ArrayList v = new ArrayList();

    if (count == null) {
      if (node.getFingerprint() == -1) { // unnamed node
        count = NodeKindTest.makeNodeKindTest(node.getNodeKind());
      } else {
        count = new NameTest(node);
      }
    }

    NodeInfo curr = node;

    while (true) {
      if (count.matches(curr, controller)) {
        int num = getNumberSingle(curr, count, null, controller);
        v.add(0, new Long(num));
      }
      curr = curr.getParent();
      if (curr == null) break;
      if (from != null && from.matches(curr, controller)) break;
    }

    return v;
  }
Example #15
0
 /** @see jaskell.compiler.JaskellVisitor#visit(ConstructorPattern) */
 public Object visit(ConstructorPattern a) {
   String cname = a.getConstructor().getName();
   /* retrieve parameter types of constructor */
   ConstructorDefinition ctor = (ConstructorDefinition) a.getConstructor().lookup(cname);
   if (ctor == null) throw new TypeError("Undefined constructor pattern  " + a);
   /* type of data constructed by constructor */
   TypeInstantiator ti = new TypeInstantiator(ctor.getDataType());
   Type rtype = ti.instance();
   Map map = ti.getMap();
   TypeSubstitution ts = new TypeSubstitution(map);
   Iterator ittypes = ctor.getParameters().iterator();
   /* retrieve type of patterns */
   Iterator it = a.getSubPatterns();
   while (it.hasNext()) {
     try {
       Pattern p = (Pattern) it.next();
       Type actual = TypeFactory.freshBinding();
       Type formal = ts.substitute((Type) ittypes.next());
       /* unify both types */
       p.setType(tu.unify(formal, actual, typeVariablesMap));
     } catch (NoSuchElementException nex) {
       throw new TypeError("Wrong number of arguments to pattern " + a);
     }
   }
   a.setType(rtype);
   return a.getType();
 }
Example #16
0
  @Test
  public void testGroupInfoMapHasCorrectPosAndGroupIndex() {
    final String PATT = "(foo)(?<X>a)(?<Y>b)(bar)(?<Z>c)(?<Z>d)"; // two groups named "Z"
    Pattern p = Pattern.compile(PATT);
    Map<String, List<GroupInfo>> map = p.groupInfo();
    assertNotNull(map);

    GroupInfo[] inf = (GroupInfo[]) map.get("X").toArray(new GroupInfo[0]);
    assertEquals(1, inf.length);
    assertEquals(PATT.indexOf("(?<X>"), inf[0].pos());
    assertEquals(1, inf[0].groupIndex());

    GroupInfo[] inf2 = (GroupInfo[]) map.get("Y").toArray(new GroupInfo[0]);
    assertEquals(1, inf2.length);
    assertEquals(PATT.indexOf("(?<Y>"), inf2[0].pos());
    assertEquals(2, inf2[0].groupIndex());

    // test both Z groups
    GroupInfo[] inf3 = (GroupInfo[]) map.get("Z").toArray(new GroupInfo[0]);
    assertEquals(2, inf3.length);
    int posZ = PATT.indexOf("(?<Z>");
    assertEquals(posZ, inf3[0].pos());
    assertEquals(4, inf3[0].groupIndex());
    assertEquals(PATT.indexOf("(?<Z>", posZ + 1), inf3[1].pos());
    assertEquals(5, inf3[1].groupIndex());
  }
Example #17
0
  public FBounds layoutPattern(LayoutManager manager) {

    double height = timerEvent.getHeight() + LayoutManager.HSPACING;
    double width = timerEvent.getWidth();

    double eventX;

    if (getNestedPatterns().isEmpty()) {
      height += placeHolder.getHeight();
      width = Math.max(width, placeHolder.getWidth());

      placeHolder.setCenter(0, height / 2 - placeHolder.getHeight() / 2);

      eventX = 0;
    } else {
      Pattern p = getNestedPattern();
      FBounds pSize = p.getBounds();
      eventX = -pSize.width / 2 + manager.getOriginOffset(p).x;

      height += pSize.height;
      width = Math.max(width, pSize.width);
      manager.setPatternPosition(p, -pSize.width / 2, height / 2 - pSize.height);
    }

    timerEvent.setCenter(eventX, -height / 2 + timerEvent.getHeight() / 2);

    getBorder().setClientRectangle(-width / 2, -height / 2, width, height);
    return getBorder().getBounds();
  }
Example #18
0
 @Override
 public Set<Pattern> gatherSubPatternsExcluding(Pattern except, boolean includeOptionals) {
   if (except.equals(this)) {
     return Collections.emptySet();
   } else {
     return graphPattern.gatherSubPatternsExcluding(except, includeOptionals);
   }
 }
Example #19
0
 @Test
 public void testIndexOfNamedGroupAfterNonEscapedParenAfterEscapedOpenBracket() {
   // since the open-bracket is escaped, it doesn't create a character class,
   // so the parentheses inside the "foo" group is a capturing group (that
   // currently captures nothing but still valid regex and thus counted)
   Pattern p = Pattern.compile("(a)(?<foo>\\[()])(?:c)(?<named>x)");
   assertEquals(3, p.indexOf("named"));
 }
Example #20
0
 @Test
 public void test2() {
   Pattern p = new Pattern("a/b");
   assertEquals(2, p.size());
   assertEquals("b", p.peekLast());
   assertEquals("a", p.get(0));
   assertEquals("b", p.get(1));
 }
Example #21
0
 @Test
 public void test4() {
   Pattern p = new Pattern("/a123/b1234/cvvsdf");
   assertEquals(3, p.size());
   assertEquals("a123", p.get(0));
   assertEquals("b1234", p.get(1));
   assertEquals("cvvsdf", p.get(2));
 }
Example #22
0
 public String pprint(int opPrec) {
   String s = "[";
   for (Pattern e : patterns) {
     s = s + e.pprint();
     if (e != patterns[patterns.length - 1]) s = s + ",";
   }
   return s + "]";
 }
Example #23
0
 @Test
 public void testCompileBackrefTakesFirstClosingAngleBracket() {
   String GROUP_NAME = "foo bar  >";
   Pattern p = Pattern.compile("(?<foo>xyz)(?<" + GROUP_NAME + ">\\d+)abc\\k<" + GROUP_NAME + ">");
   // The first closing bracket encountered is used. The second becomes a literal,
   // so we check for it in the standard pattern (two actually).
   assertEquals("(xyz)(>\\d+)abc\\2>", p.standardPattern());
 }
Example #24
0
 @Test
 public void testSplitGetsArrayOfTextAroundMatches() {
   Pattern p = Pattern.compile("(a)(b)(?:c)(?<named>x)");
   assertArrayEquals(new String[] {"foo ", " bar "}, p.split("foo abcx bar abcx"));
   // when the limit is specified, the last element contains
   // the remainder of the string
   assertArrayEquals(new String[] {"foo ", " bar abcx"}, p.split("foo abcx bar abcx", 2));
 }
Example #25
0
 /* Pattern */
 public R visit(com.biosimilarity.lift.model.specialK.Absyn.Element p, A arg) {
   R r = leaf(arg);
   r = combine(p.symbol_.accept(this, arg), r, arg);
   for (Pattern x : p.listpattern_) {
     r = combine(x.accept(this, arg), r, arg);
   }
   return r;
 }
Example #26
0
 @Test
 public void testCompileRegexWithFlags() {
   final String PATT = "(?<name>abc) # comment 1";
   int flags = java.util.regex.Pattern.CASE_INSENSITIVE | java.util.regex.Pattern.COMMENTS;
   Pattern p = Pattern.compile(PATT, flags);
   assertEquals(PATT, p.namedPattern());
   assertEquals(flags, p.flags());
 }
Example #27
0
 @Test
 public void testTakesPatternWithEscapedEscape() {
   // it looks like an escaped parenthesis, but the escape char is
   // itself escaped and is thus a literal
   final String PATT = "\\\\(?<name>abc)";
   Pattern p = Pattern.compile(PATT);
   assertEquals("\\\\(abc)", p.standardPattern());
 }
 /** Comparator of pattern, order by cRatio desc, length desc and pos_sup desc */
 @Override
 public int compare(Pattern o1, Pattern o2) {
   /**
    * since the rules of comparators of both pattern and peerkey is the same, we use pkc to
    * implement the comparator of pattern *
    */
   int p = pkc.compare(o1.getPeerKey(), o2.getPeerKey());
   return p;
 }
Example #29
0
 public void pushGraphRestrictions() {
   if (graphPattern != null) {
     if (graphRestriction != null) {
       graphPattern.setGraphRestriction(graphRestriction);
     }
     pushGraphRestrictions(Collections.singletonList(graphPattern));
   }
   super.pushGraphRestrictions();
 }
Example #30
0
 @Test
 public void testIndexOfWithInvalidNegativeInstanceIndex() {
   Pattern p = Pattern.compile("(a)(?<named>x)(b)(?:c)(?<named>y)");
   // Negative index causes ArrayIndexOutOfBoundsException (which
   // is a subclass of IndexOutOfBoundsException)
   thrown.expect(ArrayIndexOutOfBoundsException.class);
   thrown.expectMessage("-100");
   assertEquals(-1, p.indexOf("named", -100));
 }