Exemple #1
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;
  }
Exemple #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();
      }
    }
  }
  @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()));
  }
Exemple #4
0
 /**
  * Returns ids for dependent nodes of a given node, sorted by attribute. Note that some
  * dependencies do not have a corresponding attribute here, and we use the null attribute to
  * represent those edges. Visibility attributes are only visited if {@code visitVisibility} is
  * {@code true}.
  *
  * <p>If {@code aspect} is null, returns the dependent nodes of the configured target node
  * representing the given target and configuration, otherwise that of the aspect node accompanying
  * the aforementioned configured target node for the specified aspect.
  *
  * <p>The values are not simply labels because this also implements the first step of applying
  * configuration transitions, namely, split transitions. This needs to be done before the labels
  * are resolved because late bound attributes depend on the configuration. A good example for this
  * is @{code :cc_toolchain}.
  *
  * <p>The long-term goal is that most configuration transitions be applied here. However, in order
  * to do that, we first have to eliminate transitions that depend on the rule class of the
  * dependency.
  */
 public final ListMultimap<Attribute, Dependency> dependentNodeMap(
     TargetAndConfiguration node,
     BuildConfiguration hostConfig,
     AspectDefinition aspect,
     AspectParameters aspectParameters,
     Set<ConfigMatchingProvider> configConditions)
     throws EvalException, InterruptedException {
   Target target = node.getTarget();
   BuildConfiguration config = node.getConfiguration();
   ListMultimap<Attribute, Dependency> outgoingEdges = ArrayListMultimap.create();
   if (target instanceof OutputFile) {
     Preconditions.checkNotNull(config);
     visitTargetVisibility(node, outgoingEdges.get(null));
     Rule rule = ((OutputFile) target).getGeneratingRule();
     outgoingEdges.put(null, new Dependency(rule.getLabel(), config));
   } else if (target instanceof InputFile) {
     visitTargetVisibility(node, outgoingEdges.get(null));
   } else if (target instanceof EnvironmentGroup) {
     visitTargetVisibility(node, outgoingEdges.get(null));
   } else if (target instanceof Rule) {
     Preconditions.checkNotNull(config);
     visitTargetVisibility(node, outgoingEdges.get(null));
     Rule rule = (Rule) target;
     ListMultimap<Attribute, LabelAndConfiguration> labelMap =
         resolveAttributes(rule, aspect, config, hostConfig, configConditions);
     visitRule(rule, aspect, aspectParameters, labelMap, outgoingEdges);
   } else if (target instanceof PackageGroup) {
     visitPackageGroup(node, (PackageGroup) target, outgoingEdges.get(null));
   } else {
     throw new IllegalStateException(target.getLabel().toString());
   }
   return outgoingEdges;
 }
  @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));
  }
  /** This method builds an actual tree from multiple path. */
  private ARGState buildTreeFromMultiplePaths(final Collection<ARGPath> targetPaths) {
    ARGState itpTreeRoot = null;
    Deque<ARGState> todo = new ArrayDeque<>(extractTargets(targetPaths));

    // build the tree, bottom-up, starting from the target states
    while (!todo.isEmpty()) {
      final ARGState currentState = todo.removeFirst();

      if (currentState.getParents().iterator().hasNext()) {

        if (!predecessorRelation.containsKey(currentState)) {
          ARGState parentState = currentState.getParents().iterator().next();

          predecessorRelation.put(currentState, parentState);
          successorRelation.put(parentState, currentState);

          todo.addFirst(parentState);
        }

      } else if (itpTreeRoot == null) {
        itpTreeRoot = currentState;
      }
    }

    return itpTreeRoot;
  }
  /**
   * 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);
  }
  /**
   * Post merge clean up.
   *
   * <p>- Remove the removed items. - Clear the state of all the items (this allow newly overridden
   * items to lose their WRITTEN state) - Set the items that are part of the new merge to be WRITTEN
   * to allow the next merge to be incremental.
   */
  private void postMergeCleanUp() {
    ListMultimap<String, I> itemMap = ArrayListMultimap.create();

    // remove all removed items, and copy the rest in the full map while resetting their state.
    for (S dataSet : mDataSets) {
      ListMultimap<String, I> map = dataSet.getDataMap();

      List<String> keys = Lists.newArrayList(map.keySet());
      for (String key : keys) {
        List<I> list = map.get(key);
        for (int i = 0; i < list.size(); ) {
          I item = list.get(i);
          if (item.isRemoved()) {
            list.remove(i);
          } else {
            //noinspection unchecked
            itemMap.put(key, (I) item.resetStatus());
            i++;
          }
        }
      }
    }

    // for the last items (the one that have been written into the consumer), set their
    // state to WRITTEN
    for (String key : itemMap.keySet()) {
      List<I> itemList = itemMap.get(key);
      itemList.get(itemList.size() - 1).resetStatusToWritten();
    }
  }
  /**
   * 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));
      }
    }
  }
 private void doModEntityRegistration(Class<? extends Entity> entityClass, String entityName, int id, Object mod, int trackingRange, int updateFrequency, boolean sendsVelocityUpdates)
 {
     ModContainer mc = FMLCommonHandler.instance().findContainerFor(mod);
     EntityRegistration er = new EntityRegistration(mc, entityClass, entityName, id, trackingRange, updateFrequency, sendsVelocityUpdates);
     try
     {
         entityClassRegistrations.put(entityClass, er);
         entityNames.put(entityName, mc);
         if (!EntityList.classToStringMapping.containsKey(entityClass))
         {
             String entityModName = String.format("%s.%s", mc.getModId(), entityName);
             EntityList.classToStringMapping.put(entityClass, entityModName);
             EntityList.stringToClassMapping.put(entityModName, entityClass);
             FMLLog.finest("Automatically registered mod %s entity %s as %s", mc.getModId(), entityName, entityModName);
         }
         else
         {
             FMLLog.fine("Skipping automatic mod %s entity registration for already registered class %s", mc.getModId(), entityClass.getName());
         }
     }
     catch (IllegalArgumentException e)
     {
         FMLLog.log(Level.WARNING, e, "The mod %s tried to register the entity (name,class) (%s,%s) one or both of which are already registered", mc.getModId(), entityName, entityClass.getName());
         return;
     }
     entityRegistrations.put(mc, er);
 }
  private static void collectFiredRules(
      ListMultimap<String, SimpleRule> firedRules, Rule rule, EvaluationContext context) {
    Predicate predicate = rule.getPredicate();
    if (predicate == null) {
      throw new InvalidFeatureException(rule);
    }

    Boolean status = PredicateUtil.evaluate(predicate, context);
    if (status == null || !status.booleanValue()) {
      return;
    } // End if

    if (rule instanceof SimpleRule) {
      SimpleRule simpleRule = (SimpleRule) rule;

      firedRules.put(simpleRule.getScore(), simpleRule);
    } else if (rule instanceof CompoundRule) {
      CompoundRule compoundRule = (CompoundRule) rule;

      List<Rule> childRules = compoundRule.getRules();
      for (Rule childRule : childRules) {
        collectFiredRules(firedRules, childRule, context);
      }
    }
  }
  /**
   * Handles a character within {@link HtmlState#TAG_NAME}, where the name of a tag must be present.
   *
   * @param node The node that the current character belongs to.
   * @param c The current character being examined.
   */
  private void handleHtmlTagName(RawTextNode node, char c) {
    if (CharMatcher.WHITESPACE.matches(c) || c == '>') {
      currentTag = consumeText(false);

      // No tag name, saw something like <> or <  >.
      if (currentTag.length() <= 0) {
        SourceLocation sl = deriveSourceLocation(node);
        errorReporter.report(sl, MISSING_TAG_NAME);
      }

      // Currently, closing tags and open tags are handled through the states. If this is not a
      // closing tag, then an open tag needs to be started.
      if (!currentTag.startsWith("/")) {
        SourceLocation sl = deriveSourceLocation(node);
        transformMapping.put(node, new HtmlOpenTagStartNode(idGen.genId(), currentTag, sl));
      }

      if (c == '>') {
        // Handle close tags and tags that only have a tag name (e.g. <div>).
        handleHtmlTag(node, c);
      } else {
        // Get ready to capture attributes.
        currentAttributeValues = new ArrayList<>();
        setState(HtmlState.TAG);
      }
    } else {
      currentText.append(c);
    }
  }
 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));
 }
 /** Finds all block comments and associates them with their containing type. */
 private void findBlockComments(CompilationUnit unit, List<AbstractTypeDeclaration> types) {
   List<Comment> comments = ASTUtil.getCommentList(unit);
   for (Comment comment : comments) {
     if (!comment.isBlockComment()) {
       continue;
     }
     int commentPos = comment.getStartPosition();
     AbstractTypeDeclaration containingType = null;
     int containingTypePos = -1;
     for (AbstractTypeDeclaration type : types) {
       int typePos = type.getStartPosition();
       if (typePos < 0) {
         continue;
       }
       int typeEnd = typePos + type.getLength();
       if (commentPos > typePos && commentPos < typeEnd && typePos > containingTypePos) {
         containingType = type;
         containingTypePos = typePos;
       }
     }
     if (containingType != null) {
       blockComments.put(containingType, comment);
     }
   }
 }
  @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;
  }
Exemple #16
0
 private void readInjectedDependencies() {
   File injectedDepFile = new File(getConfigDir(), "injectedDependencies.json");
   if (!injectedDepFile.exists()) {
     FMLLog.getLogger()
         .log(
             Level.DEBUG,
             "File {} not found. No dependencies injected",
             injectedDepFile.getAbsolutePath());
     return;
   }
   JsonParser parser = new JsonParser();
   JsonElement injectedDeps;
   try {
     injectedDeps = parser.parse(new FileReader(injectedDepFile));
     for (JsonElement el : injectedDeps.getAsJsonArray()) {
       JsonObject jo = el.getAsJsonObject();
       String modId = jo.get("modId").getAsString();
       JsonArray deps = jo.get("deps").getAsJsonArray();
       for (JsonElement dep : deps) {
         JsonObject depObj = dep.getAsJsonObject();
         String type = depObj.get("type").getAsString();
         if (type.equals("before")) {
           injectedBefore.put(
               modId, VersionParser.parseVersionReference(depObj.get("target").getAsString()));
         } else if (type.equals("after")) {
           injectedAfter.put(
               modId, VersionParser.parseVersionReference(depObj.get("target").getAsString()));
         } else {
           FMLLog.getLogger().log(Level.ERROR, "Invalid dependency type {}", type);
           throw new RuntimeException("Unable to parse type");
         }
       }
     }
   } catch (Exception e) {
     FMLLog.getLogger().log(Level.ERROR, "Unable to parse {} - skipping", injectedDepFile);
     FMLLog.getLogger().throwing(Level.ERROR, e);
     return;
   }
   FMLLog.getLogger()
       .log(
           Level.DEBUG,
           "Loaded {} injected dependencies on modIds: {}",
           injectedBefore.size(),
           injectedBefore.keySet());
 }
Exemple #17
0
 public Builder transition(Transition transition) {
   Preconditions.checkArgument(
       states.contains(transition.from()),
       "Originating state does not exist: " + transition.from());
   Preconditions.checkArgument(
       states.contains(transition.to()), "Destination state does not exist: " + transition.to());
   outTransitions.put(transition.from(), transition);
   return this;
 }
  /**
   * Creates a new {@link HtmlAttributeNode} and maps it to node, taking all the attribute values
   * (text, conditionals, print statements) and adding them to the new attribute node.
   *
   * @param node The node that the mapped node comes from.
   */
  private void createAttribute(RawTextNode node) {
    SourceLocation sl = deriveSourceLocation(node);
    HtmlAttributeNode htmlAttributeNode =
        new HtmlAttributeNode(idGen.genId(), currentAttributeName, sl);
    htmlAttributeNode.addChildren(currentAttributeValues);
    transformMapping.put(node, htmlAttributeNode);

    currentAttributeValues = new ArrayList<>();
  }
  /**
   * Creates a new {@link HtmlTextNode} and maps it to node.
   *
   * @param node The node that the mapped node comes from.
   */
  private void createTextNode(RawTextNode node) {
    // Consume text, removing unnecessary whitespace
    String currentString = consumeText(true);

    if (currentString.length() > 0) {
      SourceLocation sl = deriveSourceLocation(node);
      transformMapping.put(node, new HtmlTextNode(idGen.genId(), currentString, sl));
    }
  }
Exemple #20
0
    @Override
    public Void visit(NamedTableNode tableNode) throws SQLException {
      String alias = tableNode.getAlias();
      TableRef tableRef = createTableRef(tableNode, true);
      PTable theTable = tableRef.getTable();

      if (alias != null) {
        tableMap.put(alias, tableRef);
      }

      String name = theTable.getName().getString();
      // avoid having one name mapped to two identical TableRef.
      if (alias == null || !alias.equals(name)) {
        tableMap.put(name, tableRef);
      }
      tables.add(tableRef);
      return null;
    }
 /**
  * Add the element object to a list associated with the key. Any preexisting elements are removed.
  *
  * @param key the key to which the element object will be linked
  * @param element the single object to stored
  * @return true if the element was successfully added
  */
 public boolean addSingleton(Object key, Object element) {
   if (lookupMultimap.containsKey(key)) {
     // Remove all elements associated with this key
     while (!lookupMultimap.get(key).isEmpty()) {
       lookupMultimap.get(key).remove(0);
     }
   }
   lookupMultimap.put(key, element);
   return true;
 }
  /**
   * 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;
  }
  /** Test {@link com.google.common.collect.ListMultimap} */
  @Test
  public void testListMultiMap() {
    // collection person by age.
    ListMultimap<Integer, Person> personAgeCollection = ArrayListMultimap.create();
    Person p1 = new Person("Hoang", 10);
    Person p2 = new Person("Khanh", 11);
    Person p3 = new Person("Hoang", 20);
    Person p4 = new Person("Dong", 11);

    personAgeCollection.put(p1.getAge(), p1);
    personAgeCollection.put(p2.getAge(), p2);
    personAgeCollection.put(p3.getAge(), p3);
    personAgeCollection.put(p4.getAge(), p4);

    Assert.assertEquals(2, personAgeCollection.get(11).size());
    Assert.assertTrue(personAgeCollection.containsEntry(p1.getAge(), p1));
    Assert.assertTrue(personAgeCollection.remove(p2.getAge(), p2));
    Assert.assertEquals(1, personAgeCollection.get(11).size());
  }
 /**
  * Adds the element object to a list associated with the key. Only one instance of an element can
  * be stored.
  *
  * @param key the key to which the element object will be linked
  * @param element the object to store
  * @return true if the element was successfully added
  */
 public boolean add(Object key, Object element) {
   // This is necessary to prevent multiple entries of the same element
   if (lookupMultimap.get(key).contains(element)) {
     fireChangeEvent(key);
     return true;
   }
   boolean b = lookupMultimap.put(key, element);
   fireChangeEvent(key);
   return b;
 }
  /**
   * Handles a character within {@link HtmlState#TAG}, where either an attribute declaration or the
   * end of a tag may appear.
   *
   * @param node The node that the current character belongs to.
   * @param c The current character being examined.
   */
  private void handleHtmlTag(RawTextNode node, char c) {
    if (c == '>') {
      // Found the end of the tag - create the appropriate open tag or close tag node, depending
      // on which we are ending.
      SourceLocation sl = deriveSourceLocation(node);

      if (currentTag.startsWith("/")) {
        transformMapping.put(
            node, new HtmlCloseTagNode(idGen.genId(), currentTag.substring(1), sl));
      } else {
        transformMapping.put(node, new HtmlOpenTagEndNode(idGen.genId(), currentTag, sl));
      }

      setState(HtmlState.PCDATA);
    } else if (CharMatcher.WHITESPACE.matches(c)) {
      // Skip whitespace characters.
    } else {
      setState(HtmlState.ATTRIBUTE_NAME);
      currentText.append(c);
    }
  }
Exemple #26
0
  private void visitRule(
      Rule rule,
      AspectDefinition aspect,
      AspectParameters aspectParameters,
      ListMultimap<Attribute, LabelAndConfiguration> labelMap,
      ListMultimap<Attribute, Dependency> outgoingEdges) {
    Preconditions.checkNotNull(labelMap);
    for (Map.Entry<Attribute, Collection<LabelAndConfiguration>> entry :
        labelMap.asMap().entrySet()) {
      Attribute attribute = entry.getKey();
      for (LabelAndConfiguration dep : entry.getValue()) {
        Label label = dep.getLabel();
        BuildConfiguration config = dep.getConfiguration();

        Target toTarget;
        try {
          toTarget = getTarget(label);
        } catch (NoSuchThingException e) {
          throw new IllegalStateException(
              "not found: " + label + " from " + rule + " in " + attribute.getName());
        }
        if (toTarget == null) {
          continue;
        }
        BuildConfiguration.TransitionApplier transitionApplier = config.getTransitionApplier();
        if (config.useDynamicConfigurations()
            && config.isHostConfiguration()
            && !BuildConfiguration.usesNullConfiguration(toTarget)) {
          // This condition is needed because resolveLateBoundAttributes may switch config to
          // the host configuration, which is the only case DependencyResolver applies a
          // configuration transition outside of this method. We need to reflect that
          // transition in the results of this method, but config.evaluateTransition is hard-set
          // to return a NONE transition when the input is a host config. Since the outside
          // caller originally passed the *original* value of config (before the possible
          // switch), it can mistakenly interpret the result as a NONE transition from the
          // original value of config. This condition fixes that. Another fix would be to have
          // config.evaluateTransition return a HOST transition when the input config is a host,
          // but since this blemish is specific to DependencyResolver it seems best to keep the
          // fix here.
          // TODO(bazel-team): eliminate this special case by passing transitionApplier to
          // resolveLateBoundAttributes, so that method uses the same interface for transitions.
          transitionApplier.applyTransition(Attribute.ConfigurationTransition.HOST);
        } else {
          config.evaluateTransition(rule, attribute, toTarget, transitionApplier);
        }
        for (Dependency dependency :
            transitionApplier.getDependencies(
                label, requiredAspects(aspect, aspectParameters, attribute, toTarget, rule))) {
          outgoingEdges.put(entry.getKey(), dependency);
        }
      }
    }
  }
  private Optional<ListMultimap<Integer, int[]>> getMatchIndexesTable(
      String str1, int[][] indexTracker) {
    ListMultimap<Integer, int[]> result = ArrayListMultimap.create();

    int firstChar = str1.charAt(0);
    Optional<int[]> potentialCharIndexes = getCharIndexes(firstChar, indexTracker);
    if (!potentialCharIndexes.isPresent()) {
      return Optional.empty();
    }

    int[] charIndexes = potentialCharIndexes.get();
    for (int charIndex : charIndexes) {
      result.put(firstChar, new int[] {charIndex});
    }

    int previousChar = firstChar;
    for (int i = 1; i < str1.length(); i++) {
      int currentChar = str1.charAt(i);
      potentialCharIndexes = getCharIndexes(currentChar, indexTracker);

      if (!potentialCharIndexes.isPresent()) {
        return Optional.empty();
      }

      charIndexes = potentialCharIndexes.get();
      for (int charIndex : charIndexes) {
        List<int[]> previousCharIndexes = result.get(previousChar);
        for (int[] previousCharIndex : previousCharIndexes) {
          if (charIndex > previousCharIndex[previousCharIndex.length - 1]) {
            int[] newCharIndex = new int[i + 1];
            System.arraycopy(previousCharIndex, 0, newCharIndex, 0, previousCharIndex.length);
            newCharIndex[i] = charIndex;
            result.put(currentChar, newCharIndex);
          }
        }
      }
      previousChar = currentChar;
    }
    return Optional.of(result);
  }
  /** @return */
  private String generateSynonymsQuery() {
    ListMultimap<String, String> fieldList = ArrayListMultimap.create();
    if (StringUtils.isNotBlank(themeKeyword)) {
      fieldList.put(SolrRecord.LAYER_DISPLAY_NAME_SYNONYMS, "(" + themeKeyword + ")");
      fieldList.put(SolrRecord.THEME_KEYWORDS_SYNONYMS_LCSH, "(" + themeKeyword + ")");
    }
    if (StringUtils.isNotBlank(placeKeyword)) {
      fieldList.put(SolrRecord.PLACE_KEYWORDS_SYNONYMS, "(" + placeKeyword + ")");
      fieldList.put(SolrRecord.LAYER_DISPLAY_NAME_SYNONYMS, "(" + placeKeyword + ")");
    }
    StringBuilder synonymsQuery = new StringBuilder();
    Iterator<Entry<String, String>> entryIterator = fieldList.entries().iterator();
    while (entryIterator.hasNext()) {
      Entry<String, String> entry = entryIterator.next();
      synonymsQuery.append(entry.getKey()).append(":").append(entry.getValue());

      if (entryIterator.hasNext()) {
        synonymsQuery.append(" OR ");
      }
    }
    return synonymsQuery.toString();
  }
Exemple #29
0
  /**
   * Add a cell to the internal indexes, based on the given associated entities.
   *
   * @param entities the cell entities (usually either source or target)
   * @param cell the cell to add
   */
  private void internalAddToMaps(ListMultimap<String, ? extends Entity> entities, Cell cell) {
    if (entities == null) {
      return;
    }

    for (Entity entity : entities.values()) {
      EntityDefinition entityDef = entity.getDefinition();
      cellsPerEntity.put(entityDef, cell);

      switch (entityDef.getSchemaSpace()) {
        case TARGET:
          cellsPerTargetType.put(entityDef.getType(), cell);
          break;
        case SOURCE:
          cellsPerSourceType.put(entityDef.getType(), cell);
          break;
        default:
          throw new IllegalStateException(
              "Entity definition with illegal schema space encountered");
      }
    }
  }
  /**
   * This method builds a (linear) tree from a single path.
   *
   * <p>Note that, while this is just a special case of {@link #buildTreeFromMultiplePaths}, this is
   * the preferred way, because the given path could come from any analysis, e.g., a predicate
   * analysis, and the exact given path should be used for interpolation. This is not guaranteed by
   * the more general approach given in {@link #buildTreeFromMultiplePaths}, because there the
   * interpolation tree is build from a (non-unambiguous) set of states.
   */
  private ARGState buildTreeFromSinglePath(final ARGPath targetPath) {
    ImmutableList<ARGState> states = targetPath.asStatesList();

    for (int i = 0; i < states.size() - 1; i++) {
      ARGState predecessorState = states.get(i);

      ARGState successorState = states.get(i + 1);
      predecessorRelation.put(successorState, predecessorState);
      successorRelation.put(predecessorState, successorState);
    }

    return states.get(0);
  }