private Collection getFilterGroup(Activity activity) {
   Object obj =
       (FilteredActivity)
           activity
               .getClass()
               .getAnnotation(com / google / android / apps / wallet / filter / FilteredActivity);
   if (obj == null) {
     throw new IllegalArgumentException(
         String.valueOf(activity.getClass().getName())
             .concat(" missing FilteredActivity annotation"));
   }
   if (((FilteredActivity) (obj)).group().equals("NONE")) {
     return new ArrayList();
   }
   if (!activityFilters.containsKey(((FilteredActivity) (obj)).group())) {
     activity = String.valueOf(activity.getClass().getName());
     obj = ((FilteredActivity) (obj)).group();
     String s = String.valueOf(activityFilters.keySet());
     throw new IllegalArgumentException(
         (new StringBuilder(
                 String.valueOf(activity).length()
                     + 49
                     + String.valueOf(obj).length()
                     + String.valueOf(s).length()))
             .append(activity)
             .append(" has invalid group attribute: ")
             .append(((String) (obj)))
             .append(" valid groups are: ")
             .append(s)
             .toString());
   } else {
     return activityFilters.get(((FilteredActivity) (obj)).group());
   }
 }
Example #2
0
  @Override
  public void serialize(final MapGenerator gen) {
    final ListMultimap<String, MultipartItem> items = LinkedListMultimap.create();
    for (MultipartItem item : this.getItems()) {
      items.put(item.getName(), item);
    }

    for (final String name : items.keySet()) {
      final List<MultipartItem> values = items.get(name);
      if (values.size() == 1) {
        gen.map(name);
        MultipartItemMapper.serialize(gen, values.get(0));
        gen.end();
      } else {
        gen.array(name);
        values.forEach(
            (item) -> {
              gen.map();
              MultipartItemMapper.serialize(gen, item);
              gen.end();
            });
        gen.end();
      }
    }
  }
Example #3
0
  /**
   * Remove the targets and rules defined by {@code path} from the cache and recursively remove the
   * targets and rules defined by files that transitively include {@code path} from the cache.
   *
   * @param path The File that has changed.
   */
  private synchronized void invalidateDependents(Path path) {
    // Normalize path to ensure it hashes equally with map keys.
    path = normalize(path);

    if (parsedBuildFiles.containsKey(path)) {
      if (console.getVerbosity() == Verbosity.ALL) {
        console.getStdErr().printf("Parser invalidating %s cache\n", path.toAbsolutePath());
      }

      // Remove all targets defined by path from cache.
      for (Map<String, Object> rawRule : parsedBuildFiles.get(path)) {
        BuildTarget target = parseBuildTargetFromRawRule(rawRule);
        knownBuildTargets.remove(target);
      }

      // Remove all rules defined in path from cache.
      parsedBuildFiles.removeAll(path);

      // All targets have no longer been parsed and cached.
      allBuildFilesParsed = false;
    }

    // Recursively invalidate dependents.
    for (Path dependent : buildFileDependents.get(path)) {

      if (!dependent.equals(path)) {
        invalidateDependents(dependent);
      }
    }

    // Dependencies will be repopulated when files are re-parsed.
    buildFileDependents.removeAll(path);
  }
  public void testInheritedOuterMethod() {
    resolveSource(
        "Test",
        "class Test { class A { void foo() {} } class B extends A { "
            + "class Inner { void test() { foo(); } } } }");

    TypeDeclaration aNode = (TypeDeclaration) nodesByType.get(ASTNode.TYPE_DECLARATION).get(1);
    TypeDeclaration bNode = (TypeDeclaration) nodesByType.get(ASTNode.TYPE_DECLARATION).get(2);
    TypeDeclaration innerNode = (TypeDeclaration) nodesByType.get(ASTNode.TYPE_DECLARATION).get(3);
    assertFalse(OuterReferenceResolver.needsOuterReference(aNode.resolveBinding()));
    assertFalse(OuterReferenceResolver.needsOuterReference(bNode.resolveBinding()));
    assertTrue(OuterReferenceResolver.needsOuterReference(innerNode.resolveBinding()));

    // B will need an outer reference to Test so it can initialize its
    // superclass A.
    List<IVariableBinding> bPath = OuterReferenceResolver.getPath(bNode);
    assertNotNull(bPath);
    assertEquals(1, bPath.size());
    assertEquals(OuterReferenceResolver.OUTER_PARAMETER, bPath.get(0));

    // foo() call will need to get to B's scope to call the inherited method.
    MethodInvocation fooCall = (MethodInvocation) nodesByType.get(ASTNode.METHOD_INVOCATION).get(0);
    List<IVariableBinding> fooPath = OuterReferenceResolver.getPath(fooCall);
    assertNotNull(fooPath);
    assertEquals(1, fooPath.size());
    assertEquals("B", fooPath.get(0).getType().getName());
  }
 /**
  * Using the criteria in {@code parentIdMap}, recursively adds all children under the partition ID
  * of {@code parentNode} to {@code parentNode}.
  *
  * @param parentNode required
  * @param parentIdMap the multimap from parent partition ID to list of child criteria
  */
 private static void addChildNodes(
     ProductPartitionNode parentNode, ListMultimap<Long, AdGroupCriterion> parentIdMap) {
   if (parentIdMap.containsKey(parentNode.getProductPartitionId())) {
     parentNode = parentNode.asSubdivision();
   }
   for (AdGroupCriterion adGroupCriterion : parentIdMap.get(parentNode.getProductPartitionId())) {
     ProductPartition partition = (ProductPartition) adGroupCriterion.getCriterion();
     ProductPartitionNode childNode = parentNode.addChild(partition.getCaseValue());
     childNode = childNode.setProductPartitionId(partition.getId());
     if (ProductPartitionType.SUBDIVISION.equals(partition.getPartitionType())) {
       childNode = childNode.asSubdivision();
     } else {
       if (adGroupCriterion instanceof BiddableAdGroupCriterion) {
         childNode = childNode.asBiddableUnit();
         Money cpcBidAmount = getBid((BiddableAdGroupCriterion) adGroupCriterion);
         if (cpcBidAmount != null) {
           childNode = childNode.setBid(cpcBidAmount.getMicroAmount());
         }
       } else {
         childNode = childNode.asExcludedUnit();
       }
     }
     addChildNodes(childNode, parentIdMap);
   }
 }
  /**
   * Returns a new instance of this class based on the collection of ad group criteria provided.
   *
   * <p>NOTE: If retrieving existing criteria for use with this method, you must include all of the
   * fields in {@link #REQUIRED_SELECTOR_FIELDS} in your {@link Selector}.
   *
   * @param adGroupId the ID of the ad group
   * @param biddingStrategyConfig the {@link BiddingStrategyConfiguration} for the ad group
   * @param adGroupCriteria the non-null (but possibly empty) list of ad group criteria
   * @throws NullPointerException if any argument is null, any element in {@code adGroupCriteria} is
   *     null, or any required field from {@link #REQUIRED_SELECTOR_FIELDS} is missing from an
   *     element in {@code adGroupCriteria}
   * @throws IllegalArgumentException if {@code adGroupCriteria} does not include the root criterion
   *     of the product partition tree
   */
  public static ProductPartitionTree createAdGroupTree(
      Long adGroupId,
      BiddingStrategyConfiguration biddingStrategyConfig,
      List<AdGroupCriterion> adGroupCriteria) {
    Preconditions.checkNotNull(adGroupId, "Null ad group ID");
    Preconditions.checkNotNull(biddingStrategyConfig, "Null bidding strategy configuration");
    Preconditions.checkNotNull(adGroupCriteria, "Null criteria list");
    if (adGroupCriteria.isEmpty()) {
      return createEmptyAdGroupTree(adGroupId, biddingStrategyConfig);
    }

    ListMultimap<Long, AdGroupCriterion> parentIdMap = LinkedListMultimap.create();
    for (AdGroupCriterion adGroupCriterion : adGroupCriteria) {
      Preconditions.checkNotNull(
          adGroupCriterion.getCriterion(), "AdGroupCriterion has a null criterion");
      if (adGroupCriterion instanceof BiddableAdGroupCriterion) {
        BiddableAdGroupCriterion biddableCriterion = (BiddableAdGroupCriterion) adGroupCriterion;
        Preconditions.checkNotNull(
            biddableCriterion.getUserStatus(),
            "User status is null for criterion ID %s",
            biddableCriterion.getCriterion().getId());
        if (UserStatus.REMOVED.equals(biddableCriterion.getUserStatus())) {
          // Skip REMOVED criteria.
          continue;
        }
      }
      if (adGroupCriterion.getCriterion() instanceof ProductPartition) {
        ProductPartition partition = (ProductPartition) adGroupCriterion.getCriterion();
        parentIdMap.put(partition.getParentCriterionId(), adGroupCriterion);
      }
    }

    return createNonEmptyAdGroupTree(adGroupId, parentIdMap);
  }
Example #7
0
  public void print(
      PdfWriter pdfWriter, GroupingContainer groupingContainer, Document document, Locale locale)
      throws DocumentException {
    if (notPrintOperationAtFirstPage()) {
      document.newPage();
    }

    ListMultimap<String, OrderOperationComponent> titleToOperationComponent =
        groupingContainer.getTitleToOperationComponent();
    for (String title : titleToOperationComponent.keySet()) {
      operationSectionHeader.print(document, title);
      int count = 0;
      for (OrderOperationComponent orderOperationComponent :
          groupingContainer.getTitleToOperationComponent().get(title)) {
        count++;
        operationOrderSection.print(
            pdfWriter,
            groupingContainer,
            orderOperationComponent.getOrder(),
            orderOperationComponent.getOperationComponent(),
            document,
            locale);
        if (count != titleToOperationComponent.get(title).size()) {
          if (notPrintOperationAtFirstPage()) {
            document.add(Chunk.NEXTPAGE);
          }
        }
      }
    }
  }
    @Override
    public PlanNode visitUnion(UnionNode node, RewriteContext<Set<Symbol>> context) {
      // Find out which output symbols we need to keep
      ImmutableListMultimap.Builder<Symbol, Symbol> rewrittenSymbolMappingBuilder =
          ImmutableListMultimap.builder();
      for (Symbol symbol : node.getOutputSymbols()) {
        if (context.get().contains(symbol)) {
          rewrittenSymbolMappingBuilder.putAll(symbol, node.getSymbolMapping().get(symbol));
        }
      }
      ListMultimap<Symbol, Symbol> rewrittenSymbolMapping = rewrittenSymbolMappingBuilder.build();

      // Find the corresponding input symbol to the remaining output symbols and prune the subplans
      ImmutableList.Builder<PlanNode> rewrittenSubPlans = ImmutableList.builder();
      for (int i = 0; i < node.getSources().size(); i++) {
        ImmutableSet.Builder<Symbol> expectedInputSymbols = ImmutableSet.builder();
        for (Collection<Symbol> symbols : rewrittenSymbolMapping.asMap().values()) {
          expectedInputSymbols.add(Iterables.get(symbols, i));
        }
        rewrittenSubPlans.add(
            context.rewrite(node.getSources().get(i), expectedInputSymbols.build()));
      }

      return new UnionNode(
          node.getId(),
          rewrittenSubPlans.build(),
          rewrittenSymbolMapping,
          ImmutableList.copyOf(rewrittenSymbolMapping.keySet()));
    }
Example #9
0
 public void addCell(String parent, String child, String label, Multiplicity m, Sort contents) {
   if (parent != null) {
     if (!children.containsKey(Sort(parent))) {
       // create a fragment label for the parent cell.
       cellFragmentLabels.put(
           Sort(parent), KLabel(cellLabels.get(Sort(parent)).name() + "-fragment"));
     }
     if (m != Multiplicity.STAR) {
       cellAbsentLabels.put(Sort(child), KLabel("no" + child));
     }
     if (m == Multiplicity.STAR) {
       cellCollectionSorts.put(Sort(child + "Bag"), Sort(child));
     }
     parents.put(Sort(child), Sort(parent));
     children.put(Sort(parent), Sort(child));
     levels.put(Sort(child), 1 + levels.get(Sort(parent)));
   } else {
     levels.put(Sort(child), 0);
   }
   if (contents != null) {
     leafCellTypes.put(Sort(child), contents);
   }
   multiplicities.put(Sort(child), m);
   cellLabels.put(Sort(child), KLabel(label));
 }
  @GET
  @ApiOperation(
      value = "Get topology of hosts, schedulers and vms",
      response = HostInfo.class,
      responseContainer = ResourceList.CLASS_NAME)
  @ApiResponses(value = {@ApiResponse(code = 200, message = "Get topology from schedulers")})
  public Response get() throws RpcException, InterruptedException, TException, IOException {
    List<SchedulerEntry> schedulers = chairmanClient.getSchedulers().getSchedulers();

    List<String> agents = new ArrayList<>();
    ListMultimap<String, SchedulerRole> schedulerMap = ArrayListMultimap.create();
    for (SchedulerEntry entry : schedulers) {
      agents.addAll(entry.getRole().getHosts());
      schedulerMap.put(entry.getAgent(), entry.getRole());
    }

    ConcurrentHashMap<String, List<Resource>> resources = new ConcurrentHashMap<>();
    CountDownLatch done = new CountDownLatch(agents.size());
    for (String agent : agents) {
      getAgentResources(resources, done, agent);
    }

    done.await(32, TimeUnit.SECONDS);

    List<HostInfo> result = new ArrayList<>();

    for (String agentId : agents) {
      List<VmInfo> respondedVms = new ArrayList<>();

      for (Resource resource : resources.get(agentId)) {
        VmInfo vmInfo = new VmInfo();
        vmInfo.setId(resource.getVm().getId());
        vmInfo.setState(resource.getVm().getState().toString());
        vmInfo.setFlavor(resource.getVm().getFlavor());

        respondedVms.add(vmInfo);
      }

      List<SchedulerInfo> respondedSchedulers = new ArrayList<>();

      for (SchedulerRole schedulerRole : schedulerMap.get(agentId)) {
        SchedulerInfo schedulerInfo = new SchedulerInfo();
        schedulerInfo.setId(schedulerRole.getId());
        schedulerInfo.setHosts(schedulerRole.getHosts());
        schedulerInfo.setSchedulers(schedulerRole.getSchedulers());
        schedulerInfo.setParent(schedulerRole.getParent_id());

        respondedSchedulers.add(schedulerInfo);
      }

      HostInfo hostInfo = new HostInfo();
      hostInfo.setId(agentId);
      hostInfo.setSchedulers(respondedSchedulers);
      hostInfo.setVms(respondedVms);

      result.add(hostInfo);
    }

    return generateResourceListResponse(Response.Status.OK, new ResourceList<>(result));
  }
Example #11
0
 /**
  * Remove a listener.
  *
  * @param key the associated key object
  * @param listener the listener to remove
  */
 public void removeListner(Object key, UniversalLookupListener listener) {
   listeners.get(key).remove(listener);
   // Some cleanup
   if (listeners.get(key).isEmpty()) {
     listeners.removeAll(key);
   }
 }
  /**
   * Validate domain service Ids are unique, and that the {@link PostConstruct} method, if present,
   * must either take no arguments or take a {@link Map} object), and that the {@link PreDestroy}
   * method, if present, must take no arguments.
   *
   * <p>TODO: there seems to be some duplication/overlap with {@link ServiceInitializer}.
   */
  private void validateServices(List<Object> serviceList) {
    for (Object service : serviceList) {
      final Method[] methods = service.getClass().getMethods();
      for (Method method : methods) {
        validatePostConstructMethods(service, method);
        validatePreDestroyMethods(service, method);
      }
    }

    ListMultimap<String, Object> servicesById = ArrayListMultimap.create();
    for (Object service : serviceList) {
      String id = ServiceUtil.id(service);
      servicesById.put(id, service);
    }
    for (Entry<String, Collection<Object>> servicesForId : servicesById.asMap().entrySet()) {
      String serviceId = servicesForId.getKey();
      Collection<Object> services = servicesForId.getValue();
      if (services.size() > 1) {
        throw new IllegalStateException(
            "Service ids must be unique; serviceId '"
                + serviceId
                + "' is declared by domain services "
                + classNamesFor(services));
      }
    }
  }
Example #13
0
  /** Test for date extraction function in alignment */
  @Test
  public void testDateExtraction() {
    Collection<? extends Cell> cells = alignment.getCells();

    Iterator<? extends Cell> it = cells.iterator();

    Cell cell = null;
    while (it.hasNext()) {
      Cell temp = it.next();

      if (temp.getTransformationIdentifier()
          .equals("eu.esdihumboldt.cst.functions.string.dateextraction")) {
        cell = temp;
        break;
      }
    }

    ListMultimap<String, ParameterValue> params = cell.getTransformationParameters();
    List<ParameterValue> values = params.get("dateFormat");

    assertEquals(1, values.size());

    String date = values.get(0).as(String.class);

    assertEquals("yyyy-MM-dd HH:mm:ss", date);
  }
  @Test
  public void testExecuteConcurrentModification() throws Exception {

    String sql = "SELECT * FROM " + DATA_SERVICE_NAME;
    DataServiceExecutor executor =
        new DataServiceExecutor.Builder(new SQL(sql), dataService, context)
            .prepareExecution(false)
            .sqlTransGenerator(sqlTransGenerator)
            .serviceTrans(serviceTrans)
            .genTrans(genTrans)
            .build();

    final DataServiceExecutor.ExecutionPoint stage = DataServiceExecutor.ExecutionPoint.OPTIMIZE;
    final ListMultimap<DataServiceExecutor.ExecutionPoint, Runnable> listenerMap =
        executor.getListenerMap();
    final Runnable task =
        new Runnable() {
          @Override
          public void run() {
            // Remove itself on run
            assertTrue(listenerMap.remove(stage, this));
          }
        };

    listenerMap.put(stage, task);
    executor.executeQuery();

    // Note the error reported to logs
    verify(genTrans.getLogChannel())
        .logError(anyString(), eq(stage), eq(ImmutableList.of(task)), eq(ImmutableList.of()));
  }
Example #15
0
  /** Test for network expansion function in alignment4 */
  @Test
  public void testNetworkExpansion1() {

    Collection<? extends Cell> cells = alignment4.getCells();

    Iterator<? extends Cell> it = cells.iterator();

    Cell cell = null;
    while (it.hasNext()) {
      Cell temp = it.next();

      if (temp.getTransformationIdentifier()
          .equals("eu.esdihumboldt.cst.functions.geometric.networkexpansion")) {
        cell = temp;
        break;
      }
    }

    ListMultimap<String, ParameterValue> params = cell.getTransformationParameters();
    List<ParameterValue> values = params.get("bufferWidth");

    assertEquals(1, values.size());
    // size is always 1
    String temp = values.get(0).as(String.class);

    assertEquals("0.005", temp);
  }
Example #16
0
  /** Test for ordinates to point function in alignment5 */
  @Test
  public void testOrdinatesToPoint1() {

    Collection<? extends Cell> cells = alignment5.getCells();

    Iterator<? extends Cell> it = cells.iterator();

    Cell cell = null;

    while (it.hasNext()) {
      Cell temp = it.next();

      if (temp.getTransformationIdentifier()
          .equals("eu.esdihumboldt.cst.functions.geometric.ordinates_to_point")) {
        cell = temp;
        break;
      }
    }

    ListMultimap<String, ? extends Entity> src = cell.getSource();

    // the parameters were moved to the source entities with the appropriate
    // names so get the source entities with name "X"/"Y"
    Entity srcX = src.get("X").get(0);
    Entity srcY = src.get("Y").get(0);

    // check if the source entity has the correct value
    assertEquals("HOCHWERT", srcX.getDefinition().getDefinition().getDisplayName());
    assertEquals("RECHTSWERT", srcY.getDefinition().getDefinition().getDisplayName());
  }
Example #17
0
  private Path[] createFiles() throws IOException {
    int numberOfStreams = Math.max(2, rnd.nextInt(10));
    mergeFactor = Math.max(mergeFactor, numberOfStreams);
    LOG.info("No of streams : " + numberOfStreams);

    Path[] paths = new Path[numberOfStreams];
    for (int i = 0; i < numberOfStreams; i++) {
      paths[i] = new Path(baseDir, "ifile_" + i + ".out");
      FSDataOutputStream out = fs.create(paths[i]);
      // write data with RLE
      IFile.Writer writer = new IFile.Writer(conf, out, keyClass, valClass, null, null, null, true);
      Map<Writable, Writable> data = createData();

      for (Map.Entry<Writable, Writable> entry : data.entrySet()) {
        writer.append(entry.getKey(), entry.getValue());
        originalData.put(entry.getKey(), entry.getValue());
        if (rnd.nextInt() % 2 == 0) {
          for (int j = 0; j < rnd.nextInt(100); j++) {
            // add some duplicate keys
            writer.append(entry.getKey(), entry.getValue());
            originalData.put(entry.getKey(), entry.getValue());
          }
        }
      }
      LOG.info("Wrote " + data.size() + " in " + paths[i]);
      data.clear();
      writer.close();
      out.close();
    }
    return paths;
  }
Example #18
0
  /** Test for formatted string function in alignment5 */
  @Test
  public void testFormattedString3() {

    Collection<? extends Cell> cells = alignment5.getCells();

    Iterator<? extends Cell> it = cells.iterator();

    Cell cell = null;
    while (it.hasNext()) {
      Cell temp = it.next();

      if (temp.getTransformationIdentifier().equals("eu.esdihumboldt.hale.align.formattedstring")) {
        cell = temp;
        break;
      }
    }
    assertNotNull(cell);

    ListMultimap<String, ParameterValue> params = cell.getTransformationParameters();
    List<ParameterValue> values = params.get("pattern");

    assertEquals(1, values.size());
    // size is 1
    assertEquals("{Grundbuch}:{Nummer}:{Einlage}", values.get(0).getValue());
  }
Example #19
0
 /** @see Alignment#getCells(EntityDefinition, boolean) */
 @Override
 public Collection<? extends Cell> getCells(
     EntityDefinition entityDefinition, boolean includeInherited) {
   if (!includeInherited)
     return Collections.unmodifiableCollection(cellsPerEntity.get(entityDefinition));
   else {
     // Set for safety to return each cell only once.
     // Duplicates shouldn't happen in usual cases, though.
     Collection<Cell> cells = new HashSet<Cell>();
     EntityDefinition e = entityDefinition;
     do {
       cells.addAll(cellsPerEntity.get(e));
       if (e.getFilter() != null) {
         cells.addAll(
             cellsPerEntity.get(
                 AlignmentUtil.createEntity(
                     e.getType(), e.getPropertyPath(), e.getSchemaSpace(), null)));
       }
       TypeDefinition superType = e.getType().getSuperType();
       e =
           superType == null
               ? null
               : AlignmentUtil.createEntity(
                   superType, e.getPropertyPath(), e.getSchemaSpace(), e.getFilter());
     } while (e != null);
     return cells;
   }
 }
 private void reportMissingDependencies(
     String type,
     ListMultimap<Artifact, DependencyNode> artifactNotFoundMap,
     ReportEntryType reportEntryType,
     TestSetStats testSuite) {
   for (Artifact artifact : sortArtifacts(artifactNotFoundMap.keySet())) {
     List<DependencyNode> roots = sortDependencyNodes(artifactNotFoundMap.get(artifact));
     if (roots.size() == 1) {
       String msg =
           "Miss "
               + artifact
               + " in "
               + roots.get(0).getArtifact()
               + " (path "
               + findPathToDependency(artifact, roots.get(0))
               + ")";
       reportTestCase(type, reportEntryType, msg, null, testSuite);
     } else {
       String msg = "Miss " + artifact + " in " + roots.size() + " artifacts ...";
       StringBuilder dsc = new StringBuilder();
       dsc.append("Miss " + artifact + " in ...");
       dsc.append(LINE_SEPARATOR).append(LINE_SEPARATOR);
       for (DependencyNode root : roots) {
         dsc.append(root.getArtifact() + " (path " + findPathToDependency(artifact, root) + ")");
         dsc.append(LINE_SEPARATOR).append(LINE_SEPARATOR);
       }
       reportTestCase(type, reportEntryType, msg, dsc.toString(), testSuite);
     }
   }
 }
Example #21
0
  /**
   * Tests whether data in valuesIterator matches with sorted input data set.
   *
   * <p>Returns a list of value counts for each key.
   *
   * @param valuesIterator
   * @return List
   * @throws IOException
   */
  private List<Integer> verifyIteratorData(ValuesIterator valuesIterator) throws IOException {
    boolean result = true;

    ArrayList<Integer> sequence = new ArrayList<Integer>();

    // sort original data based on comparator
    ListMultimap<Writable, Writable> sortedMap =
        new ImmutableListMultimap.Builder<Writable, Writable>()
            .orderKeysBy(this.correctComparator)
            .putAll(originalData)
            .build();

    Set<Map.Entry<Writable, Writable>> oriKeySet = Sets.newSet();
    oriKeySet.addAll(sortedMap.entries());

    // Iterate through sorted data and valuesIterator for verification
    for (Map.Entry<Writable, Writable> entry : oriKeySet) {

      assertTrue(valuesIterator.moveToNext());

      Writable oriKey = entry.getKey();
      // Verify if the key and the original key are same
      if (!oriKey.equals((Writable) valuesIterator.getKey())) {
        result = false;
        break;
      }

      int valueCount = 0;
      // Verify values
      Iterator<Writable> vItr = valuesIterator.getValues().iterator();
      for (Writable val : sortedMap.get(oriKey)) {
        assertTrue(vItr.hasNext());

        // Verify if the values are same
        if (!val.equals((Writable) vItr.next())) {
          result = false;
          break;
        }

        valueCount++;
      }
      sequence.add(valueCount);
      assertTrue("At least 1 value per key", valueCount > 0);
    }
    if (expectedTestResult) {
      assertTrue(result);

      assertFalse(valuesIterator.moveToNext());
      getNextFromFinishedIterator(valuesIterator);
    } else {
      while (valuesIterator.moveToNext()) {
        // iterate through all keys
      }
      getNextFromFinishedIterator(valuesIterator);
      assertFalse(result);
    }

    return sequence;
  }
Example #22
0
 /**
  * Returns a combined map of user and group permissions, with group names prefixed by {@link
  * AccessControlLists#GROUP_PREFIX}.
  */
 public ListMultimap<String, T> getAllPermissions() {
   ListMultimap<String, T> tmp = ArrayListMultimap.create();
   tmp.putAll(userCache);
   for (String group : groupCache.keySet()) {
     tmp.putAll(AccessControlLists.GROUP_PREFIX + group, groupCache.get(group));
   }
   return tmp;
 }
Example #23
0
 /**
  * Converts the given multimap of attributes to labels into a multi map of attributes to {@link
  * Dependency} objects using the proper configuration transition for each attribute.
  *
  * @throws IllegalArgumentException if the {@code node} does not refer to a {@link Rule} instance
  */
 public final Collection<Dependency> resolveRuleLabels(
     TargetAndConfiguration node, ListMultimap<Attribute, LabelAndConfiguration> labelMap) {
   Preconditions.checkArgument(node.getTarget() instanceof Rule);
   Rule rule = (Rule) node.getTarget();
   ListMultimap<Attribute, Dependency> outgoingEdges = ArrayListMultimap.create();
   visitRule(rule, labelMap, outgoingEdges);
   return outgoingEdges.values();
 }
Example #24
0
 private void processInvalidatedChunks(NetData.NetMessage message) {
   for (NetData.InvalidateChunkMessage chunk : message.getInvalidateChunkList()) {
     Vector3i chunkPos = NetMessageUtil.convert(chunk.getPos());
     remoteWorldProvider.invalidateChunks(chunkPos);
     awaitingChunkReadyBlockUpdates.removeAll(chunkPos);
     awaitingChunkReadyBiomeUpdates.removeAll(chunkPos);
   }
 }
  @Override
  public ListMultimap<String, ParameterValue> getConfiguration() {
    ListMultimap<String, ParameterValue> result = ArrayListMultimap.create(selected.size(), 1);
    for (Entry<FunctionParameterDefinition, Boolean> entry : selected.entrySet())
      result.put(entry.getKey().getName(), new ParameterValue(entry.getValue().toString()));

    return result;
  }
Example #26
0
 @Override
 public void clearCells() {
   // clear all cells except base alignment cells
   cells.removeIf(cell -> !(cell instanceof BaseAlignmentCell));
   cellsPerEntity.values().removeIf(cell -> !(cell instanceof BaseAlignmentCell));
   cellsPerSourceType.values().removeIf(cell -> !(cell instanceof BaseAlignmentCell));
   cellsPerTargetType.values().removeIf(cell -> !(cell instanceof BaseAlignmentCell));
   idToCell.values().removeIf(cell -> !(cell instanceof BaseAlignmentCell));
   typeCells.removeIf(cell -> !(cell instanceof BaseAlignmentCell));
 }
Example #27
0
  @Test
  public void checkResult() throws Exception {
    final BenchmarkResult result = runTest();
    System.out.println(result);
    System.out.println(result.csvMatches());
    System.out.println(result.csvTimes());

    final ListMultimap<RailwayQuery, Integer> allMatches = result.getLastRunResult().getMatches();
    collector.checkThat(allMatches.get(RailwayQuery.SWITCHSET).get(0), Matchers.equalTo(5));
  }
  /**
   * Merge with another validation report
   *
   * @param other the report to merge with
   */
  public void mergeWith(final ValidationReport other) {
    if (fatal) return;

    if (other.fatal) {
      msgMap.clear();
      fatal = true;
    }

    msgMap.putAll(other.msgMap);
  }
  /**
   * Add one validation message to the report
   *
   * @param message the message
   * @return true if the added message is fatal, or if {@link #fatal} is already {@code true}
   */
  public boolean addMessage(final Message message) {
    if (fatal) return true;

    if (message.isFatal()) {
      fatal = true;
      msgMap.clear();
    }
    msgMap.put(path, message);
    return fatal;
  }
Example #30
0
 /** Builds a new {@code CellCollection} by removing all the given cell labels. */
 public Term removeAll(Set<CellLabel> removeLabels) {
   Builder builder = builder();
   cells
       .keySet()
       .stream()
       .filter(label -> !removeLabels.contains(label))
       .forEach(label -> builder.addAll(cells.get(label)));
   builder.concatenate(collectionVariables);
   return builder.build();
 }