Ejemplo n.º 1
0
  /** Reconstruct the statement. */
  protected For_c reconstruct(List inits, Expr cond, List iters, Stmt body) {
    if (!CollectionUtil.equals(inits, this.inits)
        || cond != this.cond
        || !CollectionUtil.equals(iters, this.iters)
        || body != this.body) {
      For_c n = (For_c) copy();
      n.inits = TypedList.copyAndCheck(inits, ForInit.class, true);
      n.cond = cond;
      n.iters = TypedList.copyAndCheck(iters, ForUpdate.class, true);
      n.body = body;
      return n;
    }

    return this;
  }
Ejemplo n.º 2
0
  @Test
  public void testEnumIterator() {
    @SuppressWarnings("unchecked")
    Iterator<String> iterator =
        CollectionUtil.iterator((Enumeration) new StringTokenizer("foo, bar, baz", ", "));

    int count = 0;
    for (Object stringObject : stringObjects) {
      assertTrue(iterator.hasNext());
      assertEquals(stringObject, iterator.next());

      try {
        iterator.remove();
        fail("Enumeration has no remove method, iterator.remove() must throw exception");
      } catch (UnsupportedOperationException expected) {
      }

      count++;
    }

    assertEquals(3, count);
    assertFalse(iterator.hasNext());

    try {
      iterator.next();
      fail("Iterator has more elements than enumeration");
    } catch (NoSuchElementException expected) {
    }
  }
Ejemplo n.º 3
0
  @Test
  public void testMergeArraysObjectAssignable() {
    Integer[] integers = {1, 2, 3}; // Integer assignable to Object

    Object[] merged = (Object[]) CollectionUtil.mergeArrays(stringObjects, integers);
    assertArrayEquals(new Object[] {"foo", "bar", "baz", 1, 2, 3}, merged);
  }
Ejemplo n.º 4
0
  @Test
  public void testReverseOrderRandomIntegers() {
    Comparator<Integer> naturalOrder = new NaturalOrder<Integer>();
    Comparator<Integer> reverse = CollectionUtil.reverseOrder(naturalOrder);

    Random random = new Random(243249878l); // Stable "random" sequence

    for (int i = 0; i < 65536; i++) {
      // Verified to be ~ 50/50 lt/gt
      int integer = random.nextInt();
      int integerToo = random.nextInt();

      assertEquals(0, reverse.compare(integer, integer));
      assertEquals(0, reverse.compare(integerToo, integerToo));

      int natural = naturalOrder.compare(integer, integerToo);

      if (natural == 0) {
        // Actually never hits, but eq case is tested above
        assertEquals(0, reverse.compare(integer, integerToo));
      } else if (natural < 0) {
        assertTrue(reverse.compare(integer, integerToo) > 0);
      } else {
        assertTrue(reverse.compare(integer, integerToo) < 0);
      }
    }
  }
Ejemplo n.º 5
0
  @Test(expected = ArrayStoreException.class)
  public void testMergeArraysNativeIllegalType() {
    char[] chars = {'a', 'b', 'c'};
    int[] integers = {1, 2, 3}; // Integer not assignable to String

    CollectionUtil.mergeArrays(chars, integers);
  }
Ejemplo n.º 6
0
  @Test(expected = ArrayStoreException.class)
  public void testMergeArraysObjectIllegalType() {
    String[] strings = {"foo", "bar", "baz"};
    Integer[] integers = {1, 2, 3}; // Integer not assignable to String

    CollectionUtil.mergeArrays(strings, integers);
  }
Ejemplo n.º 7
0
  @Test
  public void testArrayIterator() {
    Iterator<String> iterator = CollectionUtil.iterator(new String[] {"foo", "bar", "baz"});

    int count = 0;
    for (Object stringObject : stringObjects) {
      assertTrue(iterator.hasNext());
      assertEquals(stringObject, iterator.next());

      try {
        iterator.remove();
        fail("Array have fixed length, iterator.remove() must throw exception");
      } catch (UnsupportedOperationException expected) {
      }

      count++;
    }

    assertEquals(3, count);
    assertFalse(iterator.hasNext());

    try {
      iterator.next();
      fail("Iterator has more elements than array");
    } catch (NoSuchElementException expected) {
    }
  }
Ejemplo n.º 8
0
  @Ignore("For development only")
  @Test
  @SuppressWarnings({"UnusedDeclaration"})
  public void testGenerify() {
    List list = Collections.singletonList("foo");
    @SuppressWarnings({"unchecked"})
    Set set = new HashSet(list);

    List<String> strs0 = CollectionUtil.generify(list, String.class);
    List<Object> objs0 = CollectionUtil.generify(list, String.class);
    //        List<String> strs01 = CollectionUtil.generify(list, Object.class); // Not okay
    try {
      List<String> strs1 =
          CollectionUtil.generify(set, String.class); // Not ok, runtime CCE unless set is null
    } catch (RuntimeException e) {
      e.printStackTrace();
    }

    try {
      ArrayList<String> strs01 =
          CollectionUtil.generify(list, String.class); // Not ok, runtime CCE unless list is null
    } catch (RuntimeException e) {
      e.printStackTrace();
    }

    Set<String> setstr1 = CollectionUtil.generify(set, String.class);
    Set<Object> setobj1 = CollectionUtil.generify(set, String.class);
    try {
      Set<Object> setobj44 =
          CollectionUtil.generify(list, String.class); // Not ok, runtime CCE unless list is null
    } catch (RuntimeException e) {
      e.printStackTrace();
    }

    List<String> strs2 = CollectionUtil.<List<String>, String>generify2(list);
    List<Object> objs2 = CollectionUtil.<List<Object>, String>generify2(list);
    //        List<String> morestrs = CollectionUtil.<List<Object>, String>generify2(list); // Not
    // ok
    try {
      List<String> strs3 =
          CollectionUtil.<List<String>, String>generify2(
              set); // Not ok, runtime CCE unless set is null
    } catch (RuntimeException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 9
0
  @Test
  public void testMergeArraysNative() {
    char[] chars = {'a', 'b', 'c'};
    char[] more = {'x', 'y', 'z'};

    char[] merged = (char[]) CollectionUtil.mergeArrays(chars, more);
    assertArrayEquals(new char[] {'a', 'b', 'c', 'x', 'y', 'z'}, merged);
  }
Ejemplo n.º 10
0
  public void testNamePollTally() throws Exception {
    V1NamePoll np;
    // test a name poll we won
    np = makeCompletedNamePoll(4, 1, 0);
    assertEquals(5, np.m_tally.numAgree);
    assertEquals(1, np.m_tally.numDisagree);
    assertEquals(Tallier.RESULT_WON, np.m_tally.getTallyResult());

    // test a name poll we lost with a dissenting vote
    np = makeCompletedNamePoll(1, 8, 1);

    assertEquals(2, np.m_tally.numAgree);
    assertEquals(9, np.m_tally.numDisagree);

    // build a master list
    np.buildPollLists(np.m_tally.pollVotes.iterator());

    // these should be different since we lost the poll
    assertFalse(CollectionUtil.isIsomorphic(np.m_tally.localEntries, np.m_tally.votedEntries));

    // the expected "correct" set is in our disagree msg
    assertTrue(CollectionUtil.isIsomorphic(disagree_entries, np.m_tally.votedEntries));
  }
Ejemplo n.º 11
0
  @Test
  public void testReverseOrder() {
    Comparator<String> naturalOrder = new NaturalOrder<String>();
    Comparator<String> reverse = CollectionUtil.reverseOrder(naturalOrder);

    assertNotNull(reverse);

    assertEquals(0, naturalOrder.compare("foo", "foo"));
    assertEquals(0, reverse.compare("foo", "foo"));

    assertTrue(naturalOrder.compare("bar", "baz") < 0);
    assertTrue(reverse.compare("bar", "baz") > 0);

    assertTrue(naturalOrder.compare("baz", "bar") > 0);
    assertTrue(reverse.compare("baz", "bar") < 0);
  }
Ejemplo n.º 12
0
  // method calls with spread-dot operator are not rewritten, hence this method doesn't have to care
  // about spread-dot
  public static void verifyMethodCondition(
      @Nullable ErrorCollector errorCollector,
      @Nullable ValueRecorder recorder,
      @Nullable String text,
      int line,
      int column,
      @Nullable Object message,
      Object target,
      String method,
      Object[] args,
      boolean safe,
      boolean explicit,
      int lastVariableNum) {
    MatcherCondition matcherCondition = MatcherCondition.parse(target, method, args, safe);
    if (matcherCondition != null) {
      matcherCondition.verify(
          errorCollector, getValues(recorder), text, line, column, messageToString(message));
      return;
    }

    if (recorder != null) {
      recorder.startRecordingValue(lastVariableNum);
    }
    Object result =
        safe
            ? GroovyRuntimeUtil.invokeMethodNullSafe(target, method, args)
            : GroovyRuntimeUtil.invokeMethod(target, method, args);

    if (!explicit && result == null && GroovyRuntimeUtil.isVoidMethod(target, method, args)) return;

    if (!GroovyRuntimeUtil.isTruthy(result)) {
      List<Object> values = getValues(recorder);
      if (values != null) CollectionUtil.setLastElement(values, result);
      final ConditionNotSatisfiedError conditionNotSatisfiedError =
          new ConditionNotSatisfiedError(
              new Condition(
                  values,
                  text,
                  TextPosition.create(line, column),
                  messageToString(message),
                  null,
                  null));
      errorCollector.collectOrThrow(conditionNotSatisfiedError);
    }
  }
Ejemplo n.º 13
0
    public void lockssRun() {
      setPriority(PRIORITY_PARAM_SIZE_CALC, PRIORITY_DEFAULT_SIZE_CALC);
      startWDog(WDOG_PARAM_SIZE_CALC, WDOG_DEFAULT_SIZE_CALC);
      triggerWDogOnExit(true);
      nowRunning();

      while (goOn) {
        try {
          pokeWDog();
          if (sizeCalcQueue.isEmpty()) {
            Deadline timeout = Deadline.in(Constants.HOUR);
            sizeCalcSem.take(timeout);
          }
          RepositoryNode node;
          synchronized (sizeCalcQueue) {
            node = (RepositoryNode) CollectionUtil.getAnElement(sizeCalcQueue);
          }
          if (node != null) {
            long start = TimeBase.nowMs();
            log.debug2("CalcSize start: " + node);
            long dur = 0;
            try {
              doSizeCalc(node);
              dur = TimeBase.nowMs() - start;
              log.debug2("CalcSize finish (" + StringUtil.timeIntervalToString(dur) + "): " + node);
            } catch (RuntimeException e) {
              log.warning("doSizeCalc: " + node, e);
            }
            synchronized (sizeCalcQueue) {
              sizeCalcQueue.remove(node);
            }
            pokeWDog();
            long sleep = sleepTimeToAchieveLoad(dur, sizeCalcMaxLoad);
            Deadline.in(sleep).sleep();
          }
        } catch (InterruptedException e) {
          // just wakeup and check for exit
        }
      }
      if (!goOn) {
        triggerWDogOnExit(false);
      }
    }
Ejemplo n.º 14
0
    void verify(
        @Nullable ErrorCollector errorCollector,
        @Nullable List<Object> values,
        @Nullable String text,
        int line,
        int column,
        @Nullable String message) {
      if (HamcrestFacade.matches(matcher, actual)) return;

      if (values != null) {
        CollectionUtil.setLastElement(values, shortSyntax ? actual : false);
        replaceMatcherValues(values);
      }

      String description = HamcrestFacade.getFailureDescription(matcher, actual, message);
      Condition condition =
          new Condition(values, text, TextPosition.create(line, column), description, null, null);
      errorCollector.collectOrThrow(new ConditionNotSatisfiedError(condition));
    }
Ejemplo n.º 15
0
  @Test
  public void testArrayIteratorRange() {
    Iterator<String> iterator =
        CollectionUtil.iterator(new String[] {"foo", "bar", "baz", "xyzzy"}, 1, 2);

    for (int i = 1; i < 3; i++) {
      assertTrue(iterator.hasNext());
      assertEquals(stringObjects[i], iterator.next());

      try {
        iterator.remove();
        fail("Array has no remove method, iterator.remove() must throw exception");
      } catch (UnsupportedOperationException expected) {
      }
    }

    assertFalse(iterator.hasNext());

    try {
      iterator.next();
      fail("Iterator has more elements than array range");
    } catch (NoSuchElementException expected) {
    }
  }
Ejemplo n.º 16
0
  /**
   * @param args
   * @throws Exception
   */
  @SuppressWarnings("unchecked")
  public void process(String[] args, String... required) throws Exception {
    final boolean debug = LOG.isDebugEnabled();

    if (debug) LOG.debug("Processing " + args.length + " parameters...");
    final Pattern p = Pattern.compile("=");
    for (int i = 0, cnt = args.length; i < cnt; i++) {
      final String arg = args[i];
      final String[] parts = p.split(arg, 2);
      if (parts[0].startsWith("-")) parts[0] = parts[0].substring(1);

      if (parts.length == 1) {
        if (parts[0].startsWith("${") == false) this.opt_params.add(parts[0]);
        continue;
      } else if (parts[0].equalsIgnoreCase("tag")) {
        continue;
      } else if (parts[1].startsWith("${") || parts[0].startsWith("#")) {
        continue;
      }
      if (debug) LOG.debug(String.format("%-35s = %s", parts[0], parts[1]));

      // DesignerHints Override
      if (parts[0].startsWith(PARAM_DESIGNER_HINTS_PREFIX)) {
        String param = parts[0].replace(PARAM_DESIGNER_HINTS_PREFIX, "").toLowerCase();
        try {
          Field f = DesignerHints.class.getField(param);
          this.hints_params.put(f.getName(), parts[1]);
          if (debug) LOG.debug(String.format("DesignerHints.%s = %s", param, parts[1]));
        } catch (NoSuchFieldException ex) {
          throw new Exception("Unknown DesignerHints parameter: " + param, ex);
        }

      }
      // HStoreConf Parameter
      else if (HStoreConf.isConfParameter(parts[0])) {
        this.conf_params.put(parts[0].toLowerCase(), parts[1]);
      }
      // ArgumentsParser Parameter
      else if (PARAMS.contains(parts[0].toLowerCase())) {
        this.params.put(parts[0].toLowerCase(), parts[1]);
      }
      // Invalid!
      else {
        String suggestions = "";
        i = 0;
        String end = CollectionUtil.last(parts[0].split("\\."));
        for (String param : PARAMS) {
          String param_end = CollectionUtil.last(param.split("\\."));
          if (param.startsWith(parts[0])
              || (end != null && param.endsWith(end))
              || (end != null && param_end != null && param_end.startsWith(end))) {
            if (suggestions.isEmpty()) suggestions = ". Possible Matches:";
            suggestions += String.format("\n [%02d] %s", ++i, param);
          }
        } // FOR
        throw new Exception("Unknown parameter '" + parts[0] + "'" + suggestions);
      }
    } // FOR

    // -------------------------------------------------------
    // CATALOGS
    // -------------------------------------------------------

    // Text File
    if (this.params.containsKey(PARAM_CATALOG)) {
      String path = this.params.get(PARAM_CATALOG);
      if (debug) LOG.debug("Loading catalog from file '" + path + "'");
      Catalog catalog = CatalogUtil.loadCatalog(path);
      if (catalog == null)
        throw new Exception("Failed to load catalog object from file '" + path + "'");
      this.updateCatalog(catalog, new File(path));
    }
    // Jar File
    else if (this.params.containsKey(PARAM_CATALOG_JAR)) {
      String path = this.params.get(PARAM_CATALOG_JAR);
      this.params.put(PARAM_CATALOG, path);
      File jar_file = new File(path);
      Catalog catalog = CatalogUtil.loadCatalogFromJar(path);
      if (catalog == null)
        throw new Exception("Failed to load catalog object from jar file '" + path + "'");
      if (debug) LOG.debug("Loaded catalog from jar file '" + path + "'");
      this.updateCatalog(catalog, jar_file);

      if (!this.params.containsKey(PARAM_CATALOG_TYPE)) {
        String jar_name = jar_file.getName();
        int jar_idx = jar_name.lastIndexOf(".jar");
        if (jar_idx != -1) {
          ProjectType type = ProjectType.get(jar_name.substring(0, jar_idx));
          if (type != null) {
            if (debug) LOG.debug("Set catalog type '" + type + "' from catalog jar file name");
            this.catalog_type = type;
            this.params.put(PARAM_CATALOG_TYPE, this.catalog_type.toString());
          }
        }
      }
    }
    // Schema File
    else if (this.params.containsKey(PARAM_CATALOG_SCHEMA)) {
      String path = this.params.get(PARAM_CATALOG_SCHEMA);
      Catalog catalog = CompilerUtil.compileCatalog(path);
      if (catalog == null) throw new Exception("Failed to load schema from '" + path + "'");
      if (debug) LOG.debug("Loaded catalog from schema file '" + path + "'");
      this.updateCatalog(catalog, new File(path));
    }

    // Catalog Type
    if (this.params.containsKey(PARAM_CATALOG_TYPE)) {
      String catalog_type = this.params.get(PARAM_CATALOG_TYPE);
      ProjectType type = ProjectType.get(catalog_type);
      if (type == null) {
        throw new Exception("Unknown catalog type '" + catalog_type + "'");
      }
      this.catalog_type = type;
    }

    // Update Cluster Configuration
    if (this.params.containsKey(ArgumentsParser.PARAM_CATALOG_HOSTS)) {
      ClusterConfiguration cc =
          new ClusterConfiguration(this.getParam(ArgumentsParser.PARAM_CATALOG_HOSTS));
      this.updateCatalog(FixCatalog.addHostInfo(this.catalog, cc), null);
    }

    // Check the requirements after loading the catalog, because some of the
    // above parameters will set the catalog one
    if (required != null && required.length > 0) this.require(required);

    // -------------------------------------------------------
    // PHYSICAL DESIGN COMPONENTS
    // -------------------------------------------------------
    if (this.params.containsKey(PARAM_PARTITION_PLAN)) {
      assert (this.catalog_db != null);
      File path = new File(this.params.get(PARAM_PARTITION_PLAN));
      boolean ignoreMissing =
          this.getBooleanParam(ArgumentsParser.PARAM_PARTITION_PLAN_IGNORE_MISSING, false);
      if (path.exists() || (path.exists() == false && ignoreMissing == false)) {
        if (debug) LOG.debug("Loading in partition plan from '" + path + "'");
        this.pplan = new PartitionPlan();
        this.pplan.load(path.getAbsolutePath(), this.catalog_db);

        // Apply!
        if (this.params.containsKey(PARAM_PARTITION_PLAN_APPLY)
            && this.getBooleanParam(PARAM_PARTITION_PLAN_APPLY)) {
          boolean secondaryIndexes =
              this.getBooleanParam(PARAM_PARTITION_PLAN_NO_SECONDARY, false) == false;
          LOG.info(
              String.format(
                  "Applying PartitionPlan '%s' to catalog [enableSecondary=%s]",
                  path.getName(), secondaryIndexes));
          this.pplan.apply(this.catalog_db, secondaryIndexes);
        }
      }
    }

    // -------------------------------------------------------
    // DESIGNER COMPONENTS
    // -------------------------------------------------------

    if (this.params.containsKey(PARAM_DESIGNER_THREADS)) {
      this.max_concurrent = Integer.valueOf(this.params.get(PARAM_DESIGNER_THREADS));
    }
    if (this.params.containsKey(PARAM_DESIGNER_INTERVALS)) {
      this.num_intervals = Integer.valueOf(this.params.get(PARAM_DESIGNER_INTERVALS));
    }
    if (this.params.containsKey(PARAM_DESIGNER_HINTS)) {
      String path = this.params.get(PARAM_DESIGNER_HINTS);
      if (debug)
        LOG.debug(
            "Loading in designer hints from '"
                + path
                + "'.\nForced Values:\n"
                + StringUtil.formatMaps(this.hints_params));
      this.designer_hints.load(path, catalog_db, this.hints_params);
    }
    if (this.params.containsKey(PARAM_DESIGNER_CHECKPOINT)) {
      this.designer_checkpoint = new File(this.params.get(PARAM_DESIGNER_CHECKPOINT));
    }

    String designer_attributes[] = {
      PARAM_DESIGNER_PARTITIONER,
      PARAM_DESIGNER_MAPPER,
      PARAM_DESIGNER_INDEXER,
      PARAM_DESIGNER_COSTMODEL
    };
    ClassLoader loader = ClassLoader.getSystemClassLoader();
    for (String key : designer_attributes) {
      if (this.params.containsKey(key)) {
        String target_name = this.params.get(key);
        Class<?> target_class = loader.loadClass(target_name);
        assert (target_class != null);
        if (debug) LOG.debug("Set " + key + " class to " + target_class.getName());

        if (key.equals(PARAM_DESIGNER_PARTITIONER)) {
          this.partitioner_class = (Class<? extends AbstractPartitioner>) target_class;
        } else if (key.equals(PARAM_DESIGNER_MAPPER)) {
          this.mapper_class = (Class<? extends AbstractMapper>) target_class;
        } else if (key.equals(PARAM_DESIGNER_INDEXER)) {
          this.indexer_class = (Class<? extends AbstractIndexSelector>) target_class;
        } else if (key.equals(PARAM_DESIGNER_COSTMODEL)) {
          this.costmodel_class = (Class<? extends AbstractCostModel>) target_class;

          // Special Case: TimeIntervalCostModel
          if (target_name.endsWith(TimeIntervalCostModel.class.getSimpleName())) {
            this.costmodel =
                new TimeIntervalCostModel<SingleSitedCostModel>(
                    this.catalog_db, SingleSitedCostModel.class, this.num_intervals);
          } else {
            this.costmodel =
                ClassUtil.newInstance(
                    this.costmodel_class,
                    new Object[] {this.catalog_db},
                    new Class[] {Database.class});
          }
        } else {
          assert (false) : "Invalid key '" + key + "'";
        }
      }
    } // FOR

    // -------------------------------------------------------
    // TRANSACTION ESTIMATION COMPONENTS
    // -------------------------------------------------------
    if (this.params.containsKey(PARAM_MAPPINGS)) {
      assert (this.catalog_db != null);
      File path = new File(this.params.get(PARAM_MAPPINGS));
      if (path.exists()) {
        this.param_mappings.load(path.getAbsolutePath(), this.catalog_db);
      } else {
        LOG.warn("The ParameterMappings file '" + path + "' does not exist");
      }
    }
    if (this.params.containsKey(PARAM_MARKOV_THRESHOLDS_VALUE)) {
      assert (this.catalog_db != null);
      float defaultValue = this.getDoubleParam(PARAM_MARKOV_THRESHOLDS_VALUE).floatValue();
      this.thresholds = new EstimationThresholds(defaultValue);
      this.params.put(PARAM_MARKOV_THRESHOLDS, this.thresholds.toString());
      LOG.debug("CREATED THRESHOLDS: " + this.thresholds);

    } else if (this.params.containsKey(PARAM_MARKOV_THRESHOLDS)) {
      assert (this.catalog_db != null);
      this.thresholds = new EstimationThresholds();
      File path = new File(this.params.get(PARAM_MARKOV_THRESHOLDS));
      if (path.exists()) {
        this.thresholds.load(path.getAbsolutePath(), this.catalog_db);
      } else {
        LOG.warn("The estimation thresholds file '" + path + "' does not exist");
      }
      LOG.debug("LOADED THRESHOLDS: " + this.thresholds);
    }

    // -------------------------------------------------------
    // HASHER
    // -------------------------------------------------------
    if (this.catalog != null) {
      if (this.params.containsKey(PARAM_HASHER_CLASS)) {
        String hasherClassName = this.params.get(PARAM_HASHER_CLASS);
        this.hasher_class = (Class<? extends AbstractHasher>) loader.loadClass(hasherClassName);
      }
      Constructor<? extends AbstractHasher> constructor =
          this.hasher_class.getConstructor(new Class[] {Database.class, Integer.class});
      int num_partitions = CatalogUtil.getNumberOfPartitions(this.catalog_db);
      this.hasher = constructor.newInstance(new Object[] {this.catalog_db, num_partitions});
      if (!(this.hasher instanceof DefaultHasher))
        LOG.debug("Loaded hasher " + this.hasher.getClass());

      if (this.params.containsKey(PARAM_HASHER_PROFILE)) {
        this.hasher.load(this.params.get(PARAM_HASHER_PROFILE), null);
      }
    }

    // -------------------------------------------------------
    // SAMPLE WORKLOAD TRACE
    // -------------------------------------------------------
    this.loadWorkload();
  }
Ejemplo n.º 17
0
 @Test(expected = IndexOutOfBoundsException.class)
 public void testMergeArraysObjectNegativeSecondLength() {
   CollectionUtil.mergeArrays(stringObjects, 1, 2, integerObjects, 2, -1);
 }
Ejemplo n.º 18
0
 @Test(expected = IndexOutOfBoundsException.class)
 public void testMergeArraysObjectBadSecondOffset() {
   CollectionUtil.mergeArrays(stringObjects, 1, 2, integerObjects, 4, 1);
 }
Ejemplo n.º 19
0
 @Test
 public void testMergeArraysObjectOffset() {
   Object[] merged =
       (Object[]) CollectionUtil.mergeArrays(stringObjects, 1, 2, integerObjects, 2, 1);
   assertArrayEquals(new Object[] {"bar", "baz", 3}, merged);
 }
Ejemplo n.º 20
0
 @Test
 public void testArrayListIterator() {
   assertCorrectListIterator(
       CollectionUtil.iterator(new String[] {"foo", "bar", "baz"}), stringObjects);
 }
Ejemplo n.º 21
0
 @Test(expected = IllegalArgumentException.class)
 public void testReverseOrderNull() {
   CollectionUtil.reverseOrder(null);
 }
Ejemplo n.º 22
0
 @Test(expected = IllegalArgumentException.class)
 public void testEnumIteratorNull() {
   CollectionUtil.iterator((Enumeration<Object>) null);
 }
Ejemplo n.º 23
0
 @Test(expected = IllegalArgumentException.class)
 public void testArrayIteratorRangeNull() {
   CollectionUtil.iterator(null, 0, 0);
 }
Ejemplo n.º 24
0
 @Test
 public void testArrayListIteratorRange() {
   assertCorrectListIterator(
       CollectionUtil.iterator(new String[] {"foo", "bar", "baz", "boo"}, 1, 2),
       new String[] {"bar", "baz"});
 }
  /**
   * Find a type object in the context of the class.
   *
   * @param name The name to search for.
   */
  public Named find(Matcher<Named> matcher, Context context) throws SemanticException {
    Name name = matcher.name();

    if (Report.should_report(TOPICS, 2)) Report.report(2, "Looking for " + name + " in " + this);

    if (!(type instanceof ClassType)) {
      throw new NoClassException(name.toString(), type);
    }

    ClassType type = (ClassType) this.type;

    Named m = null;

    QName fullName = null;
    QName rawName = null;

    if (type.isGloballyAccessible()) {
      fullName = QName.make(type.fullName(), name);
      QName q = ts.getTransformedClassName(type.def());
      rawName = QName.make(q.qualifier(), Name.make(q.name() + "$" + name));
    }

    if (fullName != null) {
      // First check the system resolver.
      m = ts.systemResolver().check(fullName);

      // Try the raw class file name.
      if (m == null) {
        m = ts.systemResolver().check(rawName);
      }

      if (m == null) {
        // Go to disk, but only if there is no job for the type.
        // If there is a job, all members should be in the resolver
        // already.
        boolean useLoadedResolver = true;

        if (type instanceof ParsedTypeObject) {
          ParsedTypeObject pto = (ParsedTypeObject) type;
          if (pto.job() != null) {
            useLoadedResolver = false;
          }
        }

        if (useLoadedResolver) {
          try {
            m = ts.systemResolver().find(rawName);
          } catch (SemanticException e) {
            // Not found; will fall through to error handling code
          }
        }
      }

      // If we found something, verify that it matches.
      if (m != null) {
        try {
          m = matcher.instantiate(m);
        } catch (SemanticException e) {
          // Doesn't match; try again.
          m = null;
        }
      }
    }

    // Check if the member was explicitly declared.
    if (m == null) {
      m = type.memberTypeMatching(matcher);
    }

    // If we found something, make sure it's accessible.
    if (m instanceof ClassType) {
      ClassType mt = (ClassType) m;

      if (!mt.isMember()) {
        throw new SemanticException(
            "Class " + mt + " is not a member class, " + " but was found in " + type + ".");
      }

      if (!mt.outer().equals((Object) type)) {
        throw new SemanticException(
            "Class " + mt + " is not a member class " + " of " + type + ".");
      }

      return mt;
    }

    if (m instanceof MemberInstance) {
      MemberInstance<?> mi = (MemberInstance<?>) m;

      if (!mi.container().equals((Object) type)) {
        throw new SemanticException("Type " + mi + " is not a member " + " of " + type + ".");
      }
    }

    if (m != null) {
      if (!canAccess(m, context.currentClassDef(), context)) {
        throw new SemanticException("Cannot access member type \"" + m + "\".");
      }
      return m;
    }

    // If we struck out, try the super types.

    // Collect all members of the super types.
    // Use a Set to eliminate duplicates.
    Set<Named> acceptable = new HashSet<Named>();

    if (type.superClass() != null) {
      Type sup = type.superClass();
      if (sup instanceof ClassType) {
        Resolver r = ts.classContextResolver((ClassType) sup, context);
        try {
          Named n = r.find(matcher);
          acceptable.add(n);
        } catch (SemanticException e) {
        }
      }
    }

    for (Iterator<Type> i = type.interfaces().iterator(); i.hasNext(); ) {
      Type sup = (Type) i.next();
      if (sup instanceof ClassType) {
        Resolver r = ts.classContextResolver((ClassType) sup, context);
        try {
          Named n = r.find(matcher);
          acceptable.add(n);
        } catch (SemanticException e) {
        }
      }
    }

    if (acceptable.size() == 0) {
      throw new NoClassException(name.toString(), type);
    } else if (acceptable.size() > 1) {
      Set<Type> containers = new HashSet<Type>(acceptable.size());
      for (Named n : acceptable) {
        if (n instanceof MemberInstance) {
          MemberInstance<?> mi = (MemberInstance<?>) n;
          containers.add(mi.container());
        }
      }

      if (containers.size() == 2) {
        Iterator<Type> i = containers.iterator();
        Type t1 = (Type) i.next();
        Type t2 = (Type) i.next();
        throw new SemanticException(
            "Member \""
                + name
                + "\" of "
                + type
                + " is ambiguous; it is defined in both "
                + t1
                + " and "
                + t2
                + ".");
      } else if (containers.size() == 0) {
        throw new SemanticException("Member \"" + name + "\" of " + type + " is ambiguous.");
      } else {
        throw new SemanticException(
            "Member \""
                + name
                + "\" of "
                + type
                + " is ambiguous; it is defined in "
                + CollectionUtil.listToString(new ArrayList<Type>(containers))
                + ".");
      }
    }

    assert acceptable.size() == 1;

    Named t = acceptable.iterator().next();

    if (Report.should_report(TOPICS, 2)) Report.report(2, "Found member type " + t);

    return t;
  }
Ejemplo n.º 26
0
 @Test
 public void testSubArrayNative() {
   int[] numbers = (int[]) CollectionUtil.subArray(new int[] {1, 2, 3, 4, 5}, 1, 3);
   assertArrayEquals(new int[] {2, 3, 4}, numbers);
 }
Ejemplo n.º 27
0
 @Test
 public void testSubArrayObject() {
   String[] strings = CollectionUtil.subArray(new String[] {"foo", "bar", "baz", "xyzzy"}, 1, 2);
   assertArrayEquals(new String[] {"bar", "baz"}, strings);
 }
Ejemplo n.º 28
0
 @Test(expected = IllegalArgumentException.class)
 public void testArrayIteratorRangeBadLength() {
   CollectionUtil.iterator(stringObjects, 1, stringObjects.length);
 }
Ejemplo n.º 29
0
 @Test(expected = IllegalArgumentException.class)
 public void testArrayIteratorNull() {
   CollectionUtil.iterator((Object[]) null);
 }