コード例 #1
1
ファイル: PCNode.java プロジェクト: shahidminhas/abc
 public Set /*<PCNode>*/ matchClass(Pattern simple_name_pattern) {
   Set this_class = matchSpecific(simple_name_pattern);
   Set this_class_names = new HashSet();
   Iterator tsi = this_class.iterator();
   while (tsi.hasNext()) {
     PCNode pc = (PCNode) tsi.next();
     this_class_names.add(pc.name);
   }
   Iterator pi = parents.iterator();
   while (pi.hasNext()) {
     PCNode parent = (PCNode) pi.next();
     // System.out.println("Parent: "+parent);
     Set parent_class = parent.matchClass(simple_name_pattern);
     Iterator osi = parent_class.iterator();
     while (osi.hasNext()) {
       PCNode pc = (PCNode) osi.next();
       if (!this_class_names.contains(pc.name)) {
         this_class.add(pc);
       }
     }
   }
   if (abc.main.Debug.v().namePatternProcessing)
     System.out.println(this + ".matchClass " + simple_name_pattern.pattern() + ": " + this_class);
   return this_class;
 }
コード例 #2
0
 @org.testng.annotations.Test
 public void testJSONEncoding() throws ParseException {
   String json =
       "{ 'str' : 'asdfasd' , 'long' : 123123123123 , 'int' : 5 , 'float' : 0.4 , 'bool' : false , 'date' : { '$date' : '2011-05-18T18:56:00Z'} , 'pat' : { '$regex' : '.*' , '$options' : ''} , 'oid' : { '$oid' : '4d83ab3ea39562db9c1ae2ae'} , 'ref' : { '$ref' : 'test.test' , '$id' : { '$oid' : '4d83ab59a39562db9c1ae2af'}} , 'code' : { '$code' : 'asdfdsa'} , 'codews' : { '$code' : 'ggggg' , '$scope' : { }} , 'ts' : { '$ts' : 1300474885 , '$inc' : 10} , 'null' :  null, 'uuid' : { '$uuid' : '60f65152-6d4a-4f11-9c9b-590b575da7b5' }}";
   BasicDBObject a = (BasicDBObject) JSON.parse(json);
   assert (a.get("str").equals("asdfasd"));
   assert (a.get("int").equals(5));
   assert (a.get("long").equals(123123123123L));
   assert (a.get("float").equals(0.4d));
   assert (a.get("bool").equals(false));
   SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
   format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT")));
   assert (a.get("date").equals(format.parse("2011-05-18T18:56:00Z")));
   Pattern pat = (Pattern) a.get("pat");
   Pattern pat2 = Pattern.compile(".*", BSON.regexFlags(""));
   assert (pat.pattern().equals(pat2.pattern()));
   assert (pat.flags() == (pat2.flags()));
   ObjectId oid = (ObjectId) a.get("oid");
   assert (oid.equals(new ObjectId("4d83ab3ea39562db9c1ae2ae")));
   DBRef ref = (DBRef) a.get("ref");
   assert (ref.equals(new DBRef(null, "test.test", new ObjectId("4d83ab59a39562db9c1ae2af"))));
   assert (a.get("code").equals(new Code("asdfdsa")));
   assert (a.get("codews").equals(new CodeWScope("ggggg", new BasicBSONObject())));
   assert (a.get("ts").equals(new BSONTimestamp(1300474885, 10)));
   assert (a.get("uuid").equals(UUID.fromString("60f65152-6d4a-4f11-9c9b-590b575da7b5")));
   String json2 = JSON.serialize(a);
   BasicDBObject b = (BasicDBObject) JSON.parse(json2);
   a.equals(b);
   assert (a.equals(b));
 }
コード例 #3
0
 // Note that changeReferences assumes that the number of the source/patch
 // has *already been set*.  If this is not true, it will simply do nothing
 public void changeReferences(int oldPatchNumber) {
   Specfile specfile = this.getSpecfile();
   Pattern patchPattern;
   if (oldPatchNumber == 0) {
     patchPattern =
         Pattern.compile("%patch" + oldPatchNumber + "|%patch"); // $NON-NLS-1$ //$NON-NLS-2$
   } else {
     patchPattern = Pattern.compile("%patch" + oldPatchNumber); // $NON-NLS-1$
   }
   for (int lineNumber : getLinesUsed()) {
     String line;
     try {
       line = specfile.getLine(lineNumber);
       Matcher patchMatcher = patchPattern.matcher(line);
       if (!patchMatcher.find()) {
         System.out.println(
             Messages.getString("SpecfileSource.0") + patchPattern.pattern()); // $NON-NLS-1$
         //					throw new BadLocationException("can't match " + patchPattern);
       }
       specfile.changeLine(
           lineNumber,
           line.replaceAll(
               patchPattern.pattern(),
               Messages.getString("SpecfileSource.1") + number)); // $NON-NLS-1$
     } catch (BadLocationException e) {
       SpecfileLog.logError(e);
     }
   }
 }
コード例 #4
0
  /**
   * checks input against whitelists.
   *
   * @param context The context to include in exception messages
   * @param input the input to check
   * @param orig A origional input to include in exception messages. This is not included if it is
   *     the same as input.
   * @return input upon a successful check
   * @throws ValidationException if the check fails.
   */
  private String checkWhitelist(String context, String input, String orig)
      throws ValidationException {
    // check whitelist patterns
    for (Pattern p : whitelistPatterns) {
      if (!p.matcher(input).matches()) {
        throw new ValidationException(
            context
                + ": Invalid input. Please conform to regex "
                + p.pattern()
                + (maxLength == Integer.MAX_VALUE ? "" : " with a maximum length of " + maxLength),
            "Invalid input: context="
                + context
                + ", type("
                + getTypeName()
                + ")="
                + p.pattern()
                + ", input="
                + input
                + (NullSafe.equals(orig, input) ? "" : ", orig=" + orig),
            context);
      }
    }

    return input;
  }
コード例 #5
0
 /**
  * Cuts the path of a type name if it is from the java.lang package or from
  * org.eclipse.jubula.toolkit.enums.ValueSets or leaves it as it is
  *
  * @param paramType the type name
  * @return the shortened type name
  */
 public static String beautifyParamType(String paramType) {
   if (javaLang.matcher(paramType).matches()) {
     return paramType.replaceAll(javaLang.pattern(), "$1"); // $NON-NLS-1$
   } else if (jubulaEnum.matcher(paramType).matches()) {
     return paramType.replaceAll(jubulaEnum.pattern(), "$1"); // $NON-NLS-1$
   }
   return paramType;
 }
コード例 #6
0
 public void testRegexps() throws IOException {
   final String PATTERN_STR = "abc:\\s?(\\d+)";
   Pattern exp = Pattern.compile(PATTERN_STR);
   /* Ok: easiest way is to just serialize first; problem
    * is the backslash
    */
   String json = MAPPER.writeValueAsString(exp);
   Pattern result = MAPPER.readValue(json, Pattern.class);
   assertEquals(exp.pattern(), result.pattern());
 }
コード例 #7
0
 public SystemMeasurement(String key, String host, String type, Date date, Float measure) {
   this.key = new Text(key);
   this.value =
       new Text(
           host
               + sep.pattern()
               + type
               + sep.pattern()
               + date.getTime()
               + sep.pattern()
               + Float.toString(measure));
 }
コード例 #8
0
 /**
  * Returns true if the given string is a stop word.
  *
  * @param word the word to test
  * @return true if the word is a stopword
  */
 @Override
 protected synchronized boolean is(String word) {
   for (Pattern pattern : m_Patterns) {
     if (pattern.matcher(word.trim().toLowerCase()).matches()) {
       if (m_Debug) debug(pattern.pattern() + " --> true");
       return true;
     } else {
       if (m_Debug) debug(pattern.pattern() + " --> false");
     }
   }
   return false;
 }
コード例 #9
0
    @Override
    public boolean accept(final File file) {
      boolean isClass = file.getName().endsWith(CLASS_EXT);
      if (DEFAULT_EXCLUDE.equals(EXCLUDE_PATTERN.pattern())
          && DEFAULT_INCLUDE.equals(INCLUDE_PATTERN.pattern())) {
        return isClass;
      }

      final String path = file.getAbsolutePath();
      return isClass
          && INCLUDE_PATTERN.matcher(path).matches()
          && !EXCLUDE_PATTERN.matcher(path).matches();
    }
コード例 #10
0
ファイル: Predicates.java プロジェクト: devinrsmith/guava
    @Override
    public int hashCode() {
      // Pattern uses Object.hashCode, so we have to reach
      // inside to build a hashCode consistent with equals.

      return Objects.hashCode(pattern.pattern(), pattern.flags());
    }
コード例 #11
0
  @Override
  public boolean isIgnored(
      @NonNull Context context,
      @NonNull Issue issue,
      @Nullable Location location,
      @NonNull String message,
      @Nullable Object data) {
    ensureInitialized();

    String id = issue.getId();
    List<String> paths = mSuppressed.get(id);
    if (paths == null) {
      paths = mSuppressed.get(VALUE_ALL);
    }
    if (paths != null && location != null) {
      File file = location.getFile();
      String relativePath = context.getProject().getRelativePath(file);
      for (String suppressedPath : paths) {
        if (suppressedPath.equals(relativePath)) {
          return true;
        }
        // Also allow a prefix
        if (relativePath.startsWith(suppressedPath)) {
          return true;
        }
      }
    }

    if (mRegexps != null) {
      List<Pattern> regexps = mRegexps.get(id);
      if (regexps == null) {
        regexps = mRegexps.get(VALUE_ALL);
      }
      if (regexps != null && location != null) {
        File file = location.getFile();
        String relativePath = context.getProject().getRelativePath(file);
        boolean checkUnixPath = false;
        for (Pattern regexp : regexps) {
          Matcher matcher = regexp.matcher(relativePath);
          if (matcher.find()) {
            return true;
          } else if (regexp.pattern().indexOf('/') != -1) {
            checkUnixPath = true;
          }
        }

        if (checkUnixPath && CURRENT_PLATFORM == PLATFORM_WINDOWS) {
          relativePath = relativePath.replace('\\', '/');
          for (Pattern regexp : regexps) {
            Matcher matcher = regexp.matcher(relativePath);
            if (matcher.find()) {
              return true;
            }
          }
        }
      }
    }

    return mParent != null && mParent.isIgnored(context, issue, location, message, data);
  }
コード例 #12
0
ファイル: FNPat.java プロジェクト: sandeepyohans/basex
  /**
   * Evaluates the replace function.
   *
   * @param val input value
   * @param ctx query context
   * @return function result
   * @throws QueryException query exception
   */
  private Item replace(final byte[] val, final QueryContext ctx) throws QueryException {
    final byte[] rep = checkStr(expr[2], ctx);
    for (int i = 0; i < rep.length; ++i) {
      if (rep[i] == '\\') {
        if (i + 1 == rep.length || rep[i + 1] != '\\' && rep[i + 1] != '$') FUNREPBS.thrw(info);
        ++i;
      }
      if (rep[i] == '$'
          && (i == 0 || rep[i - 1] != '\\')
          && (i + 1 == rep.length || !digit(rep[i + 1]))) FUNREPDOL.thrw(info);
    }

    final Pattern p = pattern(expr[1], expr.length == 4 ? expr[3] : null, ctx);
    if (p.pattern().isEmpty()) REGROUP.thrw(info);

    String r = string(rep);
    if ((p.flags() & Pattern.LITERAL) != 0) {
      r = SLASH.matcher(BSLASH.matcher(r).replaceAll("\\\\\\\\")).replaceAll("\\\\\\$");
    }

    try {
      return Str.get(p.matcher(string(val)).replaceAll(r));
    } catch (final Exception ex) {
      if (ex.getMessage().contains("No group")) REGROUP.thrw(info);
      throw REGPAT.thrw(info, ex);
    }
  }
コード例 #13
0
 private Filter regexFilterNew(Pattern pattern) {
   return new SingleColumnValueFilter(
       COLUMN_FAMILY,
       COLUMN_QUALIFIER,
       CompareOp.EQUAL,
       new RegexStringComparator(pattern.pattern(), pattern.flags()));
 }
コード例 #14
0
ファイル: HarvestSentences.java プロジェクト: damiano/mavuno
    @SuppressWarnings({"unchecked", "rawtypes"})
    @Override
    public void map(
        Writable key, Indexable doc, Mapper<Writable, Indexable, Text, Text>.Context context)
        throws IOException, InterruptedException {

      List<String> sentences = new ArrayList<String>();

      if (doc instanceof SentenceSegmentedDocument) {
        List<SentenceWritable> segmentedSentences =
            ((SentenceSegmentedDocument) doc).getSentences();
        for (SentenceWritable sentence : segmentedSentences) {
          sentences.add(sentence.toString());
        }
      } else {
        sentences =
            Arrays.asList(mSentenceDetector.sentDetect(doc.getContent().replace('\n', ' ')));
      }

      for (String sentence : sentences) {
        for (Pattern p : mPatterns) {
          mKey.set(p.pattern());
          if (p.matcher(sentence).find()) {
            mValue.set(sentence);
            context.write(mKey, mValue);
          }
        }
      }
    }
コード例 #15
0
ファイル: Countif.java プロジェクト: enricospataro/dynswc
 @Override
 protected String getValueText() {
   if (_pattern == null) {
     return _value;
   }
   return _pattern.pattern();
 }
コード例 #16
0
 private int putPattern(String name, Pattern p) {
   int start = _buf.position();
   _put(REGEX, name);
   _put(p.pattern());
   _put(patternFlags(p.flags()));
   return _buf.position() - start;
 }
コード例 #17
0
ファイル: FileSearchQuery.java プロジェクト: sielay/ide_core
  /**
   * @see
   *     org.eclipse.search.internal.ui.text.FileSearchQuery#run(org.eclipse.core.runtime.IProgressMonitor)
   */
  public IStatus run(final IProgressMonitor monitor) {
    AbstractTextSearchResult textResult = (AbstractTextSearchResult) this.getSearchResult();
    textResult.removeAll();

    Pattern searchPattern = this.getSearchPattern();
    boolean isFileSearchOnly = searchPattern.pattern().length() == 0;
    boolean searchInBinaries = !this.isScopeAllFileTypes();

    if (this.directory != null || this.isOpenEditorsOnly) {
      boolean onlyFilesEditorInput = isAllOpenEditorsOnWorkspace();
      if (!onlyFilesEditorInput || !isOpenEditorsOnly) {
        FileTextSearchResultCollector fcollector =
            new FileTextSearchResultCollector(textResult, isFileSearchOnly, searchInBinaries);
        String fs = directory == null ? "." : directory; // $NON-NLS-1$
        FileSystemTextSearchScope newSearchScope =
            FileNamePatternSearchScope.newSearchScope(
                new File[] {new File(fs)}, this.fScope.getFileNamePatterns());
        newSearchScope.setOpenEditors(this.isOpenEditorsOnly);
        return FileTextSearchEngine.createDefault()
            .search(newSearchScope, fcollector, searchPattern, monitor);
      }
    }
    TextSearchResultCollector collector =
        new TextSearchResultCollector(textResult, isFileSearchOnly, searchInBinaries);
    AptanaTextEngine aptanaTextEngine = new AptanaTextEngine();
    aptanaTextEngine.setOpenEditorsOnly(this.isOpenEditorsOnly);
    aptanaTextEngine.needsRefresh(this.refresh);
    return aptanaTextEngine.search(this.fScope, collector, searchPattern, monitor);
  }
コード例 #18
0
 @Test
 public void ensure_name_with_spaces_works_with_cucumber_options() {
   Properties properties = new Properties();
   properties.setProperty("cucumber.options", "--name 'some Name'");
   RuntimeOptions options = new RuntimeOptions(properties);
   Pattern actualPattern = (Pattern) options.filters.iterator().next();
   assertEquals("some Name", actualPattern.pattern());
 }
コード例 #19
0
ファイル: OptionsAndArgsTest.java プロジェクト: n1603/jolokia
 @Test
 public void toggleDefaultWithPattern() {
   OptionsAndArgs o = opts("bla");
   assertNull(o.getPid());
   Pattern pat = o.getProcessPattern();
   assertEquals(pat.pattern(), "bla");
   assertEquals(o.getCommand(), "toggle");
 }
コード例 #20
0
ファイル: NodePattern.java プロジェクト: justkunz/CoreNLP
  @SuppressWarnings("unchecked")
  public boolean nodeAttrMatch(IndexedWord node, final SemanticGraph sg, boolean ignoreCase) {
    // System.out.println(node.word());
    if (isRoot) return (negDesc ? !sg.getRoots().contains(node) : sg.getRoots().contains(node));
    // System.out.println("not root");
    if (isEmpty)
      return (negDesc ? !node.equals(IndexedWord.NO_WORD) : node.equals(IndexedWord.NO_WORD));

    // System.err.println("Attributes are: " + attributes);
    for (Map.Entry<String, Pattern> attr : attributes.entrySet()) {
      String key = attr.getKey();
      // System.out.println(key);
      String nodeValue;
      // if (key.equals("idx"))
      // nodeValue = Integer.toString(node.index());
      // else {

      Class c = Env.lookupAnnotationKey(env, key);
      // find class for the key

      Object value = node.get(c);
      if (value == null) nodeValue = null;
      else nodeValue = value.toString();
      // }
      // System.out.println(nodeValue);
      if (nodeValue == null) return negDesc;
      Pattern valuePattern = attr.getValue();
      boolean matches = false;
      if (ignoreCase) {
        if (Pattern.compile(valuePattern.pattern(), Pattern.CASE_INSENSITIVE)
            .matcher(nodeValue)
            .matches()) matches = true;
      } else {
        if (nodeValue.matches(valuePattern.pattern())) matches = true;
      }
      if (!matches) {

        // System.out.println("doesn't match");
        // System.out.println("");
        return negDesc;
      }
    }
    // System.out.println("matches");
    // System.out.println("");
    return !negDesc;
  }
コード例 #21
0
ファイル: RegexUtils.java プロジェクト: javasparx/PhyloUz
  public static Pattern grabUntilClosingElement(String tag, Pattern inside) {
    String ins = inside.pattern();

    String start = "<" + nb + tag + nb + ">";
    String end = "</" + nb + tag + nb + ">";

    return createPattern("(" + inside + d + end + ")");
  }
コード例 #22
0
 public void testRegexps() throws IOException {
   final String PATTERN_STR = "\\s+([a-b]+)\\w?";
   Pattern p = Pattern.compile(PATTERN_STR);
   Map<String, Object> input = new HashMap<String, Object>();
   input.put("p", p);
   Map<String, Object> result = writeAndMap(input);
   assertEquals(p.pattern(), result.get("p"));
 }
コード例 #23
0
ファイル: RegexMatcher.java プロジェクト: cwjcsu/jopt-simple
  public String convert(String value) {
    if (!pattern.matcher(value).matches()) {
      throw new ValueConversionException(
          "Value [" + value + "] did not match regex [" + pattern.pattern() + ']');
    }

    return value;
  }
コード例 #24
0
 public String getNoKeepAliveUserAgents() {
   Pattern p = noKeepAliveUserAgents;
   if (p == null) {
     return null;
   } else {
     return p.pattern();
   }
 }
コード例 #25
0
  @Test
  public void processFromDirectoryTest() throws Exception {
    SslRedirectConfigProcessor proc = new SslRedirectConfigProcessor();
    proc.processFromDirectory("./src/test/resources");

    assertTrue(
        "No paths were read in.",
        !proc.stagedConfiguration.sslPaths.isEmpty()
            || !proc.stagedConfiguration.sslPatterns.isEmpty());
    for (String path : proc.stagedConfiguration.sslPaths) {
      System.out.println("Path [" + path + "]");
      assertTrue("Path is empty", path.length() > 0);
    }
    for (Pattern pattern : proc.stagedConfiguration.sslPatterns) {
      System.out.println("Pattern [" + pattern.pattern() + "]");
      assertTrue("Pattern is empty", pattern.pattern().length() > 0);
    }
  }
コード例 #26
0
    /**
     * check if the rule matches with this pattern
     *
     * @param rule the rule
     * @return true if the rule matches to this pattern
     */
    public final boolean matches(String rule) {
      matcher = pattern.matcher(rule);

      if (log.isTraceEnabled()) {
        log.tracef("Trying to match '%s' with pattern '%s%", rule, pattern.pattern());
      }

      return matcher.matches();
    }
コード例 #27
0
 public String toString() {
   StringBuilder sb = new StringBuilder(getClass().getName());
   if (stringPattern != null) {
     sb.append(" with string pattern=" + stringPattern.pattern());
   } else {
     sb.append(" with token pattern=" + tokenPattern.pattern());
   }
   return sb.toString();
 }
コード例 #28
0
 private void validate(final ScimUser user) throws InvalidScimResourceException {
   if (!usernamePattern.matcher(user.getUserName()).matches()) {
     throw new InvalidScimResourceException(
         "Username must match pattern: " + usernamePattern.pattern());
   }
   if (user.getEmails() == null || user.getEmails().isEmpty()) {
     throw new InvalidScimResourceException("An email must be provided.");
   }
 }
コード例 #29
0
ファイル: Predicates.java プロジェクト: devinrsmith/guava
 @Override
 public String toString() {
   String patternString =
       MoreObjects.toStringHelper(pattern)
           .add("pattern", pattern.pattern())
           .add("pattern.flags", pattern.flags())
           .toString();
   return "Predicates.contains(" + patternString + ")";
 }
コード例 #30
0
 /** {@inheritDoc} */
 @Override
 public boolean valueIsAcceptable(ByteSequence value, MessageBuilder invalidReason) {
   String strValue = value.toString();
   boolean matches = pattern.matcher(strValue).matches();
   if (!matches) {
     Message message =
         WARN_ATTR_SYNTAX_LDAPSYNTAX_REGEX_INVALID_VALUE.get(strValue, pattern.pattern());
     invalidReason.append(message);
   }
   return matches;
 }