Java Code Examples for com.google.common.collect.HashMultimap#put()

The following examples show how to use com.google.common.collect.HashMultimap#put() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ToolMetaItem.java    From GregTech with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Multimap<String, AttributeModifier> getAttributeModifiers(EntityEquipmentSlot slot, ItemStack stack) {
    T metaValueItem = getItem(stack);
    HashMultimap<String, AttributeModifier> modifiers = HashMultimap.create();
    modifiers.putAll(super.getAttributeModifiers(slot, stack));
    if (metaValueItem != null && slot == EntityEquipmentSlot.MAINHAND) {
        IToolStats toolStats = metaValueItem.getToolStats();
        if (toolStats == null) {
            return HashMultimap.create();
        }
        float attackDamage = getToolAttackDamage(stack);
        float attackSpeed = toolStats.getAttackSpeed(stack);

        modifiers.put(SharedMonsterAttributes.ATTACK_DAMAGE.getName(), new AttributeModifier(ATTACK_DAMAGE_MODIFIER, "Weapon modifier", attackDamage, 0));
        modifiers.put(SharedMonsterAttributes.ATTACK_SPEED.getName(), new AttributeModifier(ATTACK_SPEED_MODIFIER, "Weapon modifier", attackSpeed, 0));
    }
    return modifiers;
}
 
Example 2
Source File: UIResourceChangeRegistry.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public void readState(final InputStream in) {
  try {
    final DataInputStream reader = new DataInputStream(in);
    for (final HashMultimap<String, URI> map : Collections.<HashMultimap<String, URI>>unmodifiableList(CollectionLiterals.<HashMultimap<String, URI>>newArrayList(this.existsListeners, this.charsetListeners, this.childrenListeners, this.contentsListeners))) {
      {
        final int urisForExists = reader.readInt();
        for (int i = 0; (i < urisForExists); i++) {
          {
            final String path = reader.readUTF();
            final String uri = reader.readUTF();
            map.put(path, URI.createURI(uri));
          }
        }
      }
    }
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 3
Source File: AnnotationPublisher.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Populate existing issues for type.
 *
 * @param ruleParam the rule param
 * @throws Exception the exception
 */
public void populateExistingIssuesForType(Map<String, String> ruleParam) throws Exception {

    String esUrl = ESUtils.getEsUrl();
    String ruleId = ruleParam.get(PacmanSdkConstants.RULE_ID);
    String indexName = CommonUtils.getIndexNameFromRuleParam(ruleParam);
    Map<String, Object> mustFilter = new HashMap<>();
    String attributeToQuery = ESUtils.convertAttributetoKeyword(PacmanSdkConstants.RULE_ID); //actual attribute will be  tokenized hence querying on keyword
    mustFilter.put(attributeToQuery, ruleId);
    List<String> fields = new ArrayList<String>();
    Map<String, Object> mustNotFilter = new HashMap<>();
    mustNotFilter.put("issueStatus.keyword", "closed");
    HashMultimap<String, Object> shouldFilter = HashMultimap.create();
    shouldFilter.put("type.keyword", "recommendation");
    shouldFilter.put("type.keyword", "issue");
    Long totalDocs = ESUtils.getTotalDocumentCountForIndexAndType(esUrl, indexName, null, mustFilter, mustNotFilter,
            shouldFilter);
    // get all the issues for this ruleId
    List<Map<String, String>> existingIssues = ESUtils.getDataFromES(esUrl, indexName.toLowerCase(), null,
            mustFilter, mustNotFilter, shouldFilter, fields, 0, totalDocs);
    existingIssues.stream().forEach(obj -> {
        existingIssuesMapWithAnnotationIdAsKey.put(obj.get(PacmanSdkConstants.ES_DOC_ID_KEY), obj);
    });
}
 
Example 4
Source File: AutoFixManager.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the open and excepmted annotation for rule.
 *
 * @param ruleParam the rule param
 * @return the open and excepmted annotation for rule
 * @throws Exception the exception
 */
private List<Map<String, String>> getOpenAndExcepmtedAnnotationForRule(Map<String, String> ruleParam)
        throws Exception {

    String esUrl = ESUtils.getEsUrl();
    String ruleId = ruleParam.get(PacmanSdkConstants.RULE_ID);
    String indexName = CommonUtils.getIndexNameFromRuleParam(ruleParam);
    String attributeToQuery = ESUtils.convertAttributetoKeyword(PacmanSdkConstants.RULE_ID);
    Map<String, Object> mustFilter = new HashMap<>();
    mustFilter.put(attributeToQuery, ruleId);
    mustFilter.put("type.keyword", "issue");
    HashMultimap<String, Object> shouldFilter = HashMultimap.create();
    shouldFilter.put(ESUtils.convertAttributetoKeyword(PacmanSdkConstants.ISSUE_STATUS_KEY),
            PacmanSdkConstants.STATUS_OPEN);
    shouldFilter.put(ESUtils.convertAttributetoKeyword(PacmanSdkConstants.ISSUE_STATUS_KEY),
            PacmanSdkConstants.STATUS_EXEMPTED);
    List<String> fields = new ArrayList<>();
    Long totalDocs = ESUtils.getTotalDocumentCountForIndexAndType(esUrl, indexName, null, mustFilter, null,
            shouldFilter);
    // get all the issues for this ruleId
    return ESUtils.getDataFromES(esUrl, indexName.toLowerCase(), null,
            mustFilter, null, shouldFilter, fields, 0, totalDocs);
}
 
Example 5
Source File: ForTestUtils.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private Object test3() {
	ElasticSearchRepository elasticSearchRepository = PowerMockito.spy(new ElasticSearchRepository());
	Map<String, Object> mustFilter = Maps.newHashMap();
	Map<String, Object> mustFilterDetails = Maps.newHashMap();
	Gson gson = new Gson();
	String jsonObject = "{\"count\":\"123\",\"hits\":{\"total\":1000,\"max_score\":null,\"hits\":[{\"_index\":\"bank\",\"_type\":\"_doc\",\"_id\":\"0\",\"sort\":[0],\"_score\":null,\"_source\":{\"account_number\":0,\"balance\":16623,\"firstname\":\"Bradshaw\",\"lastname\":\"Mckenzie\",\"age\":29,\"gender\":\"F\",\"address\":\"244 Columbus Place\",\"employer\":\"Euron\",\"email\":\"[email protected]\",\"city\":\"Hobucken\",\"state\":\"CO\"}}]},\"aggregations\":{\"avg-values-per-day\":{\"buckets\":[{\"key_as_string\":\"ID\",\"Avg-CPU-Utilization\":{\"value\":12},\"Avg-NetworkIn\":{\"value\":12},\"Avg-NetworkOut\":{\"value\":12},\"Avg-DiskReadinBytes\":{\"value\":12},\"Avg-DiskWriteinBytes\":{\"value\":12}}]}}}";
	Map<String, Object> json = (Map<String, Object>) gson.fromJson(jsonObject, Object.class);
	mustFilterDetails.put("has_child", "has_child123");
	mustFilter.put("has_child", mustFilterDetails);
	mustFilter.put("has_parent", mustFilterDetails);
	mustFilter.put("test", json);
	HashMultimap<String, Object> shouldFilter = HashMultimap.create();
	shouldFilter.put("has_child", mustFilterDetails);
	String searchText = "searchText";
	Map<String, List<String>> matchPhrasePrefix = (Map<String, List<String>>) gson.fromJson("{\"count\":[\"ABC\",\"BCD\",\"OPD\"]}", Object.class);
	Map<String, Object> response = elasticSearchRepository.buildQuery(mustFilter, mustFilter, shouldFilter, searchText, mustFilter, matchPhrasePrefix);
	return response.get("name");
}
 
Example 6
Source File: CommonUtilsTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
   public void buildQueryForMustTermsFilter() throws Exception{
	Map<String, Object> mustFilter = Maps.newHashMap();
	Map<String, Object> mustFilterDetails = Maps.newHashMap();
	Gson gson = new Gson();
	String jsonObject = "{\"count\":\"123\",\"hits\":{\"total\":1000,\"max_score\":null,\"hits\":[{\"_index\":\"bank\",\"_type\":\"_doc\",\"_id\":\"0\",\"sort\":[0],\"_score\":null,\"_source\":{\"account_number\":0,\"balance\":16623,\"firstname\":\"Bradshaw\",\"lastname\":\"Mckenzie\",\"age\":29,\"gender\":\"F\",\"address\":\"244 Columbus Place\",\"employer\":\"Euron\",\"email\":\"[email protected]\",\"city\":\"Hobucken\",\"state\":\"CO\"}}]},\"aggregations\":{\"avg-values-per-day\":{\"buckets\":[{\"key_as_string\":\"ID\",\"Avg-CPU-Utilization\":{\"value\":12},\"Avg-NetworkIn\":{\"value\":12},\"Avg-NetworkOut\":{\"value\":12},\"Avg-DiskReadinBytes\":{\"value\":12},\"Avg-DiskWriteinBytes\":{\"value\":12}}]}}}";
	Map<String, Object> json = (Map<String, Object>) gson.fromJson(jsonObject, Object.class);
	mustFilterDetails.put("has_child", "has_child123");
	mustFilter.put("has_child", mustFilterDetails);
	mustFilter.put("has_parent", mustFilterDetails);
	mustFilter.put("test", json);
	mustFilter.put("range", json);
	HashMultimap<String, Object> shouldFilter = HashMultimap.create();
	shouldFilter.put("has_child", mustFilterDetails);
	final ElasticSearchRepository classUnderTest = PowerMockito.spy(new ElasticSearchRepository());
	String searchText = "searchText";
	Map<String, Object> result = Whitebox.invokeMethod(classUnderTest, "buildQueryForMustTermsFilter", mustFilter, mustFilter, shouldFilter, searchText, mustFilter, mustFilter, mustFilter);
	assertEquals(result.keySet().size()>0,  true);
}
 
Example 7
Source File: QueryContext.java    From datawave with Apache License 2.0 6 votes vote down vote up
private static StringBuilder splitCompoundValue(String name, String operator, String value, HashMultimap<String,String> preFilterValues,
                boolean updateWhitelist) {
    StringBuilder sb = new StringBuilder();
    
    String[] parts = value.split("-");
    
    // parts should be length 1 or 2 if its not return nothing
    if (parts.length == 1) {
        sb.append(name).append(" " + operator + " '").append(parts[0]).append("'");
    } else if (parts.length == 2) {
        sb.append(name).append(" " + operator + " '").append(parts[0]).append("'");
        // don't need the second value since that would be the sink's relationship and we don't return stats edges for the sink
        
        // If we do split then we need to add the two new values to the pre-filter white list
        if (updateWhitelist) {
            preFilterValues.put(name, parts[0]);
        }
    }
    
    return sb;
    
}
 
Example 8
Source File: FetchTaskTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testSearcherIsAcquiredForShard() throws Exception {
    IntArrayList shards = IntArrayList.from(1, 2);
    Routing routing = new Routing(Map.of("dummy", Map.of("i1", shards)));
    IndexBaseBuilder ibb = new IndexBaseBuilder();
    ibb.allocate("i1", shards);

    HashMultimap<RelationName, String> tableIndices = HashMultimap.create();
    tableIndices.put(new RelationName(Schemas.DOC_SCHEMA_NAME, "i1"), "i1");

    MetaData metaData = MetaData.builder()
        .put(IndexMetaData.builder("i1")
            .settings(Settings.builder()
                .put(SETTING_NUMBER_OF_SHARDS, 1)
                .put(SETTING_NUMBER_OF_REPLICAS, 0)
                .put(SETTING_VERSION_CREATED, Version.CURRENT))
            .build(), true)
        .build();
    final FetchTask context = new FetchTask(
        UUID.randomUUID(),
        new FetchPhase(
            1,
            null,
            ibb.build(),
            tableIndices,
            ImmutableList.of(createReference("i1", new ColumnIdent("x"), DataTypes.STRING))),
        "dummy",
        new SharedShardContexts(mock(IndicesService.class, RETURNS_MOCKS), UnaryOperator.identity()),
        metaData,
        relationName -> null,
        ImmutableList.of(routing));

    context.prepare();

    assertThat(context.searcher(1), Matchers.notNullValue());
    assertThat(context.searcher(2), Matchers.notNullValue());
}
 
Example 9
Source File: StendhalBuddyDAO.java    From stendhal with GNU General Public License v2.0 5 votes vote down vote up
/**
 * loads the relationship lists for the specified charname
 *
 * @param transaction DBTransaction
 * @param charname name of char
 * @return buddy list
 * @throws SQLException in case of an database error
 */
public Multimap<String, String> loadRelations(DBTransaction transaction, String charname) throws SQLException {
	HashMultimap<String, String> map = HashMultimap.create();
	String query = "SELECT relationtype, buddy FROM buddy WHERE charname='[charname]'";
	Map<String, Object> params = new HashMap<String, Object>();
	params.put("charname", charname);
	ResultSet resultSet = transaction.query(query, params);
	while (resultSet.next()) {
		map.put(resultSet.getString(1), resultSet.getString(2));
	}
	return map;
}
 
Example 10
Source File: RemoteDelivery.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Map<Domain, Collection<MailAddress>> groupByServer(Collection<MailAddress> recipients) {
    // Must first organize the recipients into distinct servers (name made case insensitive)
    HashMultimap<Domain, MailAddress> groupByServerMultimap = HashMultimap.create();
    for (MailAddress recipient : recipients) {
        groupByServerMultimap.put(recipient.getDomain(), recipient);
    }
    return groupByServerMultimap.asMap();
}
 
Example 11
Source File: ClipboardFormats.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @return a multimap from a file extension to the potential matching formats.
 */
public static Multimap<String, ClipboardFormat> getFileExtensionMap() {
    HashMultimap<String, ClipboardFormat> map = HashMultimap.create();
    for (ClipboardFormat format : ClipboardFormat.values()) {
        map.put(format.getExtension(), format);
    }
    return map;
}
 
Example 12
Source File: CardinalityRecord.java    From datawave with Apache License 2.0 5 votes vote down vote up
public HashMultimap<Integer,DateFieldValueCardinalityRecord> getCardinalityMap() {
    HashMultimap<Integer,DateFieldValueCardinalityRecord> newCardinalityMap = HashMultimap.create();
    synchronized (this) {
        for (Map.Entry<Integer,DateFieldValueCardinalityRecord> entry : cardinalityMap.entries()) {
            newCardinalityMap.put(entry.getKey(), new DateFieldValueCardinalityRecord(entry.getValue()));
        }
    }
    return newCardinalityMap;
}
 
Example 13
Source File: PacmanUtils.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Check instance id for port rule in ES.
 *
 * @param instanceId
 *            the instance id
 * @param ec2PortUrl
 *            the ec 2 port url
 * @param ruleId
 *            the rule id
 * @param type
 *            the type
 * @return true, if successful
 * @throws Exception
 *             the exception
 */
public static boolean checkInstanceIdForPortRuleInES(String instanceId, String ec2PortUrl, String ruleId,
		String type) throws Exception {
	JsonParser jsonParser = new JsonParser();
	String resourceid = null;
	Map<String, Object> mustFilter = new HashMap<>();
	Map<String, Object> mustNotFilter = new HashMap<>();
	HashMultimap<String, Object> shouldFilter = HashMultimap.create();
	Map<String, Object> mustTermsFilter = new HashMap<>();
	if (StringUtils.isEmpty(type)) {
		shouldFilter.put(convertAttributetoKeyword(PacmanSdkConstants.ISSUE_STATUS_KEY),
				PacmanSdkConstants.STATUS_OPEN);
	} else {
		shouldFilter.put(convertAttributetoKeyword(PacmanSdkConstants.ISSUE_STATUS_KEY),
				PacmanSdkConstants.STATUS_OPEN);
		shouldFilter.put(convertAttributetoKeyword(PacmanSdkConstants.ISSUE_STATUS_KEY),
				PacmanRuleConstants.STATUS_EXEMPTED);
	}

	mustFilter.put(convertAttributetoKeyword(PacmanSdkConstants.RULE_ID), ruleId);
	mustFilter.put(convertAttributetoKeyword(PacmanSdkConstants.RESOURCE_ID), instanceId);

	JsonObject resultJson = RulesElasticSearchRepositoryUtil.getQueryDetailsFromES(ec2PortUrl, mustFilter,
			mustNotFilter, shouldFilter, null, 0, mustTermsFilter, null, null);

	if (resultJson != null && resultJson.has(PacmanRuleConstants.HITS)) {
		JsonObject hitsJson = (JsonObject) jsonParser.parse(resultJson.get(PacmanRuleConstants.HITS).toString());
		JsonArray hitsArray = hitsJson.getAsJsonArray(PacmanRuleConstants.HITS);
		for (int i = 0; i < hitsArray.size(); i++) {
			JsonObject source = hitsArray.get(i).getAsJsonObject().get(PacmanRuleConstants.SOURCE)
					.getAsJsonObject();
			resourceid = source.get(PacmanSdkConstants.RESOURCE_ID).getAsString();
			if (!org.apache.commons.lang.StringUtils.isEmpty(resourceid)) {
				return true;
			}
		}
	}
	return false;
}
 
Example 14
Source File: CommonTestUtils.java    From pacbot with Apache License 2.0 5 votes vote down vote up
public static HashMultimap<String, Object> getMulHashMapObject(String passRuleResourceId) {
	HashMultimap<String, Object> commonMap = HashMultimap.create();
    commonMap.put("region", "region");
    commonMap.put("_resourceid", passRuleResourceId);
    commonMap.put("issueCount", "issueCount");
    commonMap.put("OU", "OU");
    commonMap.put("created_event_found", true);
    return commonMap;
}
 
Example 15
Source File: ZooKeeperWriteProviderFunctionalTest.java    From xio with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteHttp1DeterministicRuleEngineConfig() throws Exception {
  try (TestingServer server = new TestingServer()) {
    server.start();

    Http1DeterministicRuleEngineConfig config = new Http1DeterministicRuleEngineConfig();

    HashMultimap<String, String> headers = HashMultimap.create();
    headers.put("User-Agent", "Bad-actor: 1.0");
    Http1DeterministicRuleEngineConfig.Rule bad =
        new Http1DeterministicRuleEngineConfig.Rule(
            HttpMethod.GET, "/path/to/failure", HttpVersion.HTTP_1_0, headers);
    Http1DeterministicRuleEngineConfig.Rule good =
        new Http1DeterministicRuleEngineConfig.Rule(null, null, null, null);
    config.blacklistRule(bad);
    config.whitelistRule(good);

    ThriftMarshaller marshaller = new ThriftMarshaller();
    RetryPolicy retryPolicy = new RetryOneTime(1);
    try (CuratorFramework client =
        CuratorFrameworkFactory.newClient(server.getConnectString(), retryPolicy)) {
      client.start();
      String path = "/some/path/to/nodes/http1Rules";

      ZooKeeperWriteProvider provider = new ZooKeeperWriteProvider(marshaller, client);

      provider.write(path, config);

      byte[] data = client.getData().forPath(path);
      ThriftUnmarshaller unmarshaller = new ThriftUnmarshaller();
      Http1DeterministicRuleEngineConfig read = new Http1DeterministicRuleEngineConfig();
      unmarshaller.unmarshall(read, data);

      assertEquals(config, read);
    }
  }
}
 
Example 16
Source File: ConstraintValueUtil.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Buck does not allow duplicate {@code config_setting} in a set of {@code constraint_value} in
 * {@code config_setting} or {@code platform} rules.
 */
public static void validateUniqueConstraintSettings(
    String ruleType,
    BuildTarget buildTarget,
    DependencyStack dependencyStack,
    ImmutableSet<ConstraintValue> constraintValues) {
  HashMultimap<ConstraintSetting, ConstraintValue> valuesBySetting = HashMultimap.create();

  for (ConstraintValue constraintValue : constraintValues) {
    valuesBySetting.put(constraintValue.getConstraintSetting(), constraintValue);
  }

  for (Map.Entry<ConstraintSetting, Collection<ConstraintValue>> e :
      valuesBySetting.asMap().entrySet()) {
    ConstraintSetting constraintSetting = e.getKey();
    Collection<ConstraintValue> constraintValuesForSetting = e.getValue();
    if (constraintValuesForSetting.size() > 1) {
      throw new HumanReadableException(
          dependencyStack,
          "in %s rule %s: Duplicate constraint values detected: constraint_setting %s has %s",
          ruleType,
          buildTarget,
          constraintSetting.getBuildTarget(),
          constraintValuesForSetting.stream()
              .map(ConstraintValue::getBuildTarget)
              .sorted(Comparator.comparing(BuildTarget::toString))
              .collect(ImmutableList.toImmutableList()));
    }
  }
}
 
Example 17
Source File: FormHttpMessageConverterUnitTest.java    From vertx-rest-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testWrite() {
    final FormHttpMessageConverter converter = new FormHttpMessageConverter();
    final HttpOutputMessage message = new BufferedHttpOutputMessage();

    final HashMultimap<String, Object> values = HashMultimap.create();
    values.put("test", "value");

    converter.write(values, MediaType.APPLICATION_FORM_URLENCODED, message);

    assertThat(message.getBody().toString(Charsets.UTF_8), is("test=value"));
}
 
Example 18
Source File: EssentialsMissingHandler.java    From Cyberware with MIT License 4 votes vote down vote up
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void overlayPre(RenderGameOverlayEvent.Pre event)
{

	if (event.getType() == ElementType.ALL)
	{
		EntityPlayer e = Minecraft.getMinecraft().thePlayer;
		
		HashMultimap<String, AttributeModifier> multimap = HashMultimap.<String, AttributeModifier>create();
		multimap.put(SharedMonsterAttributes.MOVEMENT_SPEED.getAttributeUnlocalizedName(), new AttributeModifier(speedId, "Missing leg speed", -100F, 0));
		//e.getAttributeMap().removeAttributeModifiers(multimap);
		
		
		if (CyberwareAPI.hasCapability(e))
		{
			ICyberwareUserData cyberware = CyberwareAPI.getCapability(e);
			
			if (!cyberware.hasEssential(EnumSlot.EYES) && !e.isCreative())
			{
				GlStateManager.pushMatrix();
				GlStateManager.enableBlend();
				GlStateManager.color(1F, 1F, 1F, .9F);
				Minecraft.getMinecraft().getTextureManager().bindTexture(BLACK_PX);
				ClientUtils.drawTexturedModalRect(0, 0, 0, 0, Minecraft.getMinecraft().displayWidth, Minecraft.getMinecraft().displayHeight);
				GlStateManager.popMatrix();
			}
		}
		
		if (TileEntitySurgery.workingOnPlayer)
		{
			float trans = 1.0F;
			float ticks = TileEntitySurgery.playerProgressTicks + event.getPartialTicks();
			if (ticks < 20F)
			{
				trans = ticks / 20F;
			}
			else if (ticks > 60F)
			{
				trans = (80F - ticks) / 20F;
			}
			GL11.glEnable(GL11.GL_BLEND);
			GL11.glColor4f(1.0F, 1.0F, 1.0F, trans);
			Minecraft.getMinecraft().getTextureManager().bindTexture(BLACK_PX);
			ClientUtils.drawTexturedModalRect(0, 0, 0, 0, Minecraft.getMinecraft().displayWidth, Minecraft.getMinecraft().displayHeight);
			GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
			GL11.glDisable(GL11.GL_BLEND);
		}
	}
}
 
Example 19
Source File: ObjectSizer.java    From titan1withtp3.1 with Apache License 2.0 4 votes vote down vote up
public static HashMultimap fill(HashMultimap m, int size) {
    for (int i = 0; i < size; i++) m.put(i, i);
    return m;
}
 
Example 20
Source File: DefaultTaskExecutionPlan.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void determineExecutionPlan() {
    List<TaskInfoInVisitingSegment> nodeQueue = Lists.newArrayList(Iterables.transform(entryTasks, new Function<TaskInfo, TaskInfoInVisitingSegment>() {
        int index;

        public TaskInfoInVisitingSegment apply(TaskInfo taskInfo) {
            return new TaskInfoInVisitingSegment(taskInfo, index++);
        }
    }));
    int visitingSegmentCounter = nodeQueue.size();

    HashMultimap<TaskInfo, Integer> visitingNodes = HashMultimap.create();
    Stack<GraphEdge> walkedShouldRunAfterEdges = new Stack<GraphEdge>();
    Stack<TaskInfo> path = new Stack<TaskInfo>();
    HashMap<TaskInfo, Integer> planBeforeVisiting = new HashMap<TaskInfo, Integer>();

    while (!nodeQueue.isEmpty()) {
        TaskInfoInVisitingSegment taskInfoInVisitingSegment = nodeQueue.get(0);
        int currentSegment = taskInfoInVisitingSegment.visitingSegment;
        TaskInfo taskNode = taskInfoInVisitingSegment.taskInfo;

        if (taskNode.isIncludeInGraph() || executionPlan.containsKey(taskNode.getTask())) {
            nodeQueue.remove(0);
            maybeRemoveProcessedShouldRunAfterEdge(walkedShouldRunAfterEdges, taskNode);
            continue;
        }

        boolean alreadyVisited = visitingNodes.containsKey(taskNode);
        visitingNodes.put(taskNode, currentSegment);

        if (!alreadyVisited) {
            // Have not seen this task before - add its dependencies to the head of the queue and leave this
            // task in the queue
            recordEdgeIfArrivedViaShouldRunAfter(walkedShouldRunAfterEdges, path, taskNode);
            removeShouldRunAfterSuccessorsIfTheyImposeACycle(visitingNodes, taskInfoInVisitingSegment);
            takePlanSnapshotIfCanBeRestoredToCurrentTask(planBeforeVisiting, taskNode);
            ArrayList<TaskInfo> successors = new ArrayList<TaskInfo>();
            addAllSuccessorsInReverseOrder(taskNode, successors);
            for (TaskInfo successor : successors) {
                if (visitingNodes.containsEntry(successor, currentSegment)) {
                    if (!walkedShouldRunAfterEdges.empty()) {
                        //remove the last walked should run after edge and restore state from before walking it
                        GraphEdge toBeRemoved = walkedShouldRunAfterEdges.pop();
                        toBeRemoved.from.removeShouldRunAfterSuccessor(toBeRemoved.to);
                        restorePath(path, toBeRemoved);
                        restoreQueue(nodeQueue, visitingNodes, toBeRemoved);
                        restoreExecutionPlan(planBeforeVisiting, toBeRemoved);
                        break;
                    } else {
                        onOrderingCycle();
                    }
                }
                nodeQueue.add(0, new TaskInfoInVisitingSegment(successor, currentSegment));
            }
            path.push(taskNode);
        } else {
            // Have visited this task's dependencies - add it to the end of the plan
            nodeQueue.remove(0);
            visitingNodes.remove(taskNode, currentSegment);
            path.pop();
            executionPlan.put(taskNode.getTask(), taskNode);
            // Add any finalizers to the queue
            ArrayList<TaskInfo> finalizerTasks = new ArrayList<TaskInfo>();
            addAllReversed(finalizerTasks, taskNode.getFinalizers());
            for (TaskInfo finalizer : finalizerTasks) {
                if (!visitingNodes.containsKey(finalizer)) {
                    nodeQueue.add(finalizerTaskPosition(finalizer, nodeQueue), new TaskInfoInVisitingSegment(finalizer, visitingSegmentCounter++));
                }
            }
        }
    }
}