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

The following examples show how to use com.google.common.collect.LinkedHashMultimap#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: PluralsHolder.java    From mojito with Apache License 2.0 6 votes vote down vote up
Multimap<String, String> getFormsToCopy(LocaleId localeId) {

        LinkedHashMultimap<String, String> formsToCopy = LinkedHashMultimap.create();

        List<String> pluralForms = new ArrayList<>();
        pluralForms.add("zero");
        pluralForms.add("one");
        pluralForms.add("two");
        pluralForms.add("few");
        pluralForms.add("many");
        pluralForms.add("other");

        retainForms(localeId, pluralForms);

        for (String pluralForm : pluralForms) {
            formsToCopy.put("other", pluralForm);
        }

        return formsToCopy;
    }
 
Example 2
Source File: BalancingNodePlacementStrategyTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemovesFromBiggestLocation() throws Exception {
    LinkedHashMultimap<Location, Entity> currentMembers = LinkedHashMultimap.<Location,Entity>create();
    currentMembers.put(loc1, entity1);
    currentMembers.put(loc1, entity2);
    currentMembers.put(loc2, entity3);
    List<Entity> result = placementStrategy.entitiesToRemove(currentMembers, 1);
    Asserts.assertEqualsIgnoringOrder(result, ImmutableList.of(entity2));

    // and confirm that not just taking first location!
    currentMembers = LinkedHashMultimap.<Location,Entity>create();
    currentMembers.put(loc1, entity3);
    currentMembers.put(loc2, entity1);
    currentMembers.put(loc2, entity2);
    result = placementStrategy.entitiesToRemove(currentMembers, 1);
    Asserts.assertEqualsIgnoringOrder(result, ImmutableList.of(entity2));
}
 
Example 3
Source File: Scopes.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * indexes the IEObject description using the given
 */
public static <T> Multimap<T,IEObjectDescription> index(Iterable<IEObjectDescription> descriptions, Function<IEObjectDescription,T> indexer) {
	ArrayList<IEObjectDescription> list = Lists.newArrayList(descriptions);
	LinkedHashMultimap<T, IEObjectDescription> multimap = LinkedHashMultimap.create(list.size(),1);
	for (IEObjectDescription desc : list) {
		multimap.put(indexer.apply(desc), desc);
	}
	return multimap;
}
 
Example 4
Source File: SerializerFragment2.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private StringConcatenationClient genCondition(final List<ISerializationContext> contexts, final IGrammarConstraintProvider.IConstraint constraint, final Multimap<EObject, IGrammarConstraintProvider.IConstraint> ctx2ctr) {
  StringConcatenationClient _xblockexpression = null;
  {
    final List<ISerializationContext> sorted = IterableExtensions.<ISerializationContext>sort(contexts);
    final LinkedHashMultimap<EObject, ISerializationContext> index = LinkedHashMultimap.<EObject, ISerializationContext>create();
    final Consumer<ISerializationContext> _function = (ISerializationContext it) -> {
      index.put(this.getContextObject(it), it);
    };
    sorted.forEach(_function);
    StringConcatenationClient _client = new StringConcatenationClient() {
      @Override
      protected void appendTo(StringConcatenationClient.TargetStringConcatenation _builder) {
        {
          Set<EObject> _keySet = index.keySet();
          boolean _hasElements = false;
          for(final EObject obj : _keySet) {
            if (!_hasElements) {
              _hasElements = true;
            } else {
              _builder.appendImmediate("\n\t\t|| ", "");
            }
            StringConcatenationClient _genObjectSelector = SerializerFragment2.this.genObjectSelector(obj);
            _builder.append(_genObjectSelector);
            {
              int _size = ctx2ctr.get(obj).size();
              boolean _greaterThan = (_size > 1);
              if (_greaterThan) {
                StringConcatenationClient _genParameterSelector = SerializerFragment2.this.genParameterSelector(obj, index.get(obj), constraint);
                _builder.append(_genParameterSelector);
              }
            }
          }
        }
      }
    };
    _xblockexpression = _client;
  }
  return _xblockexpression;
}
 
Example 5
Source File: BalancingNodePlacementStrategyTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddsToBalanceWhenPopulated() throws Exception {
    LinkedHashMultimap<Location, Entity> currentMembers = LinkedHashMultimap.<Location,Entity>create();
    currentMembers.put(loc1, entity1);
    currentMembers.put(loc1, entity2);
    List<Location> result = placementStrategy.locationsForAdditions(currentMembers, ImmutableList.of(loc1, loc2), 4);
    Asserts.assertEqualsIgnoringOrder(result, ImmutableList.of(loc1, loc2, loc2, loc2));
}
 
Example 6
Source File: BalancingNodePlacementStrategyTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddWillIgnoredDisallowedLocation() throws Exception {
    LinkedHashMultimap<Location, Entity> currentMembers = LinkedHashMultimap.<Location,Entity>create();
    currentMembers.put(loc1, entity1);
    currentMembers.put(loc2, entity2);
    List<Location> result = placementStrategy.locationsForAdditions(currentMembers, ImmutableList.of(loc1), 2);
    Asserts.assertEqualsIgnoringOrder(result, ImmutableList.of(loc1, loc1));
}
 
Example 7
Source File: BalancingNodePlacementStrategyTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemovesNewest() throws Exception {
    LinkedHashMultimap<Location, Entity> currentMembers = LinkedHashMultimap.<Location,Entity>create();
    currentMembers.put(loc1, entity1);
    currentMembers.put(loc1, entity2);
    List<Entity> result = placementStrategy.entitiesToRemove(currentMembers, 1);
    Asserts.assertEqualsIgnoringOrder(result, ImmutableList.of(entity2));
}
 
Example 8
Source File: SolrSearchProviderImpl.java    From swellrt with Apache License 2.0 5 votes vote down vote up
private void addSearchResultsToCurrentWaveView(
    LinkedHashMultimap<WaveId, WaveletId> currentUserWavesView, JsonArray docsJson) {
  for (JsonElement aDocsJson : docsJson) {
    JsonObject docJson = aDocsJson.getAsJsonObject();

    WaveId waveId = WaveId.deserialise(docJson.getAsJsonPrimitive(WAVE_ID).getAsString());
    WaveletId waveletId =
            WaveletId.deserialise(docJson.getAsJsonPrimitive(WAVELET_ID).getAsString());
    currentUserWavesView.put(waveId, waveletId);
  }
}
 
Example 9
Source File: MultimapCodecTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultimap() throws Exception {
  LinkedHashMultimap<String, String> linkedHashMultimap = LinkedHashMultimap.create();
  linkedHashMultimap.put("A", "//foo:B");
  new SerializationTester(
          ImmutableMultimap.of(),
          ImmutableMultimap.of("A", "//foo:A"),
          ImmutableMultimap.builder().putAll("B", "//foo:B1", "//foo:B2").build(),
          linkedHashMultimap)
      .runTests();
}
 
Example 10
Source File: SolrSearchProviderImpl.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
private void addSearchResultsToCurrentWaveView(
    LinkedHashMultimap<WaveId, WaveletId> currentUserWavesView, JsonArray docsJson) {
  for (JsonElement aDocsJson : docsJson) {
    JsonObject docJson = aDocsJson.getAsJsonObject();

    WaveId waveId = WaveId.deserialise(docJson.getAsJsonPrimitive(WAVE_ID).getAsString());
    WaveletId waveletId =
            WaveletId.deserialise(docJson.getAsJsonPrimitive(WAVELET_ID).getAsString());
    currentUserWavesView.put(waveId, waveletId);
  }
}
 
Example 11
Source File: ScriptApiTracker.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Looking for at.ProvidesDefaultImplementation on Methods. Normal method declarations are not taken into account,
 * since they would not be executed on the interface level.
 *
 * Beware: also the inheritance in the original API will be taken into account since compiled client code will link
 * against that.
 *
 * @param type
 *            type to search for apis.
 * @return List of {@link VirtualApiTMethod}
 */
public List<TMethod> computeMissingApiMethods(TInterface type, EObject context) {

	Optional<ProjectComparisonAdapter> optAdapt = firstProjectComparisonAdapter(context.eResource());
	if (optAdapt.isPresent()) {
		ProjectComparisonAdapter projectComparisonAdapter = optAdapt.get();
		ProjectComparisonEntry compareEntry = projectComparisonAdapter.getEntryFor(
				EcoreUtil2.getContainerOfType(type, TModule.class));
		ProjectComparisonEntry typeCompare = compareEntry.getChildForElementImpl(type);
		// compute real super-types and API-missing super-types then add result for each going through
		// computeMissingApiMethodsPlain.

		if (typeCompare == null) {
			// are we in a completely missing API implementation (super-interfaces not implemented ?)
			typeCompare = compareEntry.getChildForElementAPI(type);
		}
		if (typeCompare == null) {
			if (logger.isDebugEnabled()) {
				logger.debug(
						" want to throw new IllegalstateException() --> comparison for implementation not found type="
								+ type.getTypeAsString()
								+ " in Implementation " + compareEntry.getElementImpl()[0]);
			}
			return emptyList();
		}

		LinkedHashMultimap<TMethod, TInterface> lhmmMehodInterface = LinkedHashMultimap
				.<TMethod, TInterface> create();

		Predicate<ProjectComparisonEntry> filter = (pce -> pce.getElementAPI() instanceof TMethod);
		filter = filter
				.and(pce -> pce.getElementImpl()[0] == null)
				.and(pce -> PROVIDES_DEFAULT_IMPLEMENTATION.hasAnnotation((TMethod) pce.getElementAPI()));

		Function<TInterface, Consumer<? super ProjectComparisonEntry>> actionProvider = pivot -> pce -> {
			TMethod method = ((TMethod) pce.getElementAPI());
			lhmmMehodInterface.put(method, pivot);
		};

		if (!checkInterfaceImplementsInterface(type, typeCompare.getElementAPI())) {
			return emptyList();
		}

		// Call the supertype iterations scaffolding:
		interfaceApiSupertypeWalker(filter, actionProvider, projectComparisonAdapter,
				(TInterface) typeCompare.getElementAPI(), TInterface.class);

		// now that we know about expected mixed-in methods we need to filter out
		// given concrete implementations overriding these mix-ins ... mmmhhh this should be
		// done when calculating the outer concrete super-member computation. --> the result we found here should be
		// filtered
		// out in the caller when processing our results...
		return lhmmMehodInterface
				.keySet()
				.stream()
				.map(m -> new VirtualApiTMethod(m.getName(), TypeUtils.copyPartial(m,
						TypesPackage.Literals.SYNTAX_RELATED_TELEMENT__AST_ELEMENT)))
				.collect(Collectors.toList());

	}
	return emptyList();

}
 
Example 12
Source File: WebIntegrationFragment.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
protected Multimap<String, String> createCodeMirrorPatterns(final String langId, final Set<String> keywords) {
  final boolean inheritsTerminals = GrammarUtil2.inherits(this.getGrammar(), GrammarUtil2.TERMINALS);
  final boolean inheritsXbase = this._xbaseUsageDetector.inheritsXbase(this.getGrammar());
  final LinkedHashMultimap<String, String> patterns = LinkedHashMultimap.<String, String>create();
  final boolean hasSingleLineComment = (this.enabledPatterns.contains("comment_singleLine") || ((inheritsTerminals || inheritsXbase) && (!this.suppressedPatterns.contains("comment_singleLine"))));
  if (hasSingleLineComment) {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("{token: \"comment\", regex: \"\\\\/\\\\/.*$\"}");
    patterns.put("start", _builder.toString());
  }
  if ((this.enabledPatterns.contains("comment_block") || ((inheritsTerminals || inheritsXbase) && (!this.suppressedPatterns.contains("comment_block"))))) {
    StringConcatenation _builder_1 = new StringConcatenation();
    _builder_1.append("{token: \"comment\", regex: \"\\\\/\\\\*\", next : \"comment\"}");
    patterns.put("start", _builder_1.toString());
    StringConcatenation _builder_2 = new StringConcatenation();
    _builder_2.append("{token: \"comment\", regex: \".*?\\\\*\\\\/\", next : \"start\"}");
    patterns.put("comment", _builder_2.toString());
    StringConcatenation _builder_3 = new StringConcatenation();
    _builder_3.append("{token: \"comment\", regex: \".+\"}");
    patterns.put("comment", _builder_3.toString());
  }
  if ((this.enabledPatterns.contains("string_doubleQuote") || ((inheritsTerminals || inheritsXbase) && (!this.suppressedPatterns.contains("string_doubleQuote"))))) {
    StringConcatenation _builder_4 = new StringConcatenation();
    _builder_4.append("{token: \"string\", regex: \'[\"](?:(?:\\\\\\\\.)|(?:[^\"\\\\\\\\]))*?[\"]\'}");
    patterns.put("start", _builder_4.toString());
  }
  if ((this.enabledPatterns.contains("string_singleQuote") || ((inheritsTerminals || inheritsXbase) && (!this.suppressedPatterns.contains("string_singleQuote"))))) {
    StringConcatenation _builder_5 = new StringConcatenation();
    _builder_5.append("{token: \"string\", regex: \"[\'](?:(?:\\\\\\\\.)|(?:[^\'\\\\\\\\]))*?[\']\"}");
    patterns.put("start", _builder_5.toString());
  }
  if ((this.enabledPatterns.contains("number_decimal") || ((inheritsTerminals || inheritsXbase) && (!this.suppressedPatterns.contains("number_decimal"))))) {
    StringConcatenation _builder_6 = new StringConcatenation();
    _builder_6.append("{token: \"constant.numeric\", regex: \"[+-]?\\\\d+(?:(?:\\\\.\\\\d*)?(?:[eE][+-]?\\\\d+)?)?\\\\b\"}");
    patterns.put("start", _builder_6.toString());
  }
  if ((this.enabledPatterns.contains("number_hex") || (inheritsXbase && (!this.suppressedPatterns.contains("number_hex"))))) {
    StringConcatenation _builder_7 = new StringConcatenation();
    _builder_7.append("{token: \"constant.numeric\", regex: \"0[xX][0-9a-fA-F]+\\\\b\"}");
    patterns.put("start", _builder_7.toString());
  }
  final boolean bracketOpen = (this.enabledPatterns.contains("bracket_open") || (keywords.contains("[") && (!this.suppressedPatterns.contains("bracket_open"))));
  final boolean parenOpen = (this.enabledPatterns.contains("parenthesis_open") || (keywords.contains("(") && (!this.suppressedPatterns.contains("parenthesis_open"))));
  final boolean braceOpen = (this.enabledPatterns.contains("brace_open") || (keywords.contains("{") && (!this.suppressedPatterns.contains("brace_open"))));
  if (((bracketOpen || parenOpen) || braceOpen)) {
    StringConcatenation _builder_8 = new StringConcatenation();
    _builder_8.append("{token: \"lparen\", regex: \"[");
    {
      if (bracketOpen) {
        _builder_8.append("\\\\[");
      }
    }
    {
      if (parenOpen) {
        _builder_8.append("(");
      }
    }
    {
      if (braceOpen) {
        _builder_8.append("{");
      }
    }
    _builder_8.append("]\"}");
    patterns.put("start", _builder_8.toString());
  }
  final boolean bracketClose = (this.enabledPatterns.contains("bracket_close") || (keywords.contains("]") && (!this.suppressedPatterns.contains("bracket_close"))));
  final boolean parenClose = (this.enabledPatterns.contains("parenthesis_close") || (keywords.contains(")") && (!this.suppressedPatterns.contains("parenthesis_close"))));
  final boolean braceClose = (this.enabledPatterns.contains("brace_close") || (keywords.contains("}") && (!this.suppressedPatterns.contains("brace_close"))));
  if (((bracketClose || parenClose) || braceClose)) {
    StringConcatenation _builder_9 = new StringConcatenation();
    _builder_9.append("{token: \"rparen\", regex: \"[");
    {
      if (bracketClose) {
        _builder_9.append("\\\\]");
      }
    }
    {
      if (parenClose) {
        _builder_9.append(")");
      }
    }
    {
      if (braceClose) {
        _builder_9.append("}");
      }
    }
    _builder_9.append("]\"}");
    patterns.put("start", _builder_9.toString());
  }
  if ((Objects.equal(this.framework.get(), WebIntegrationFragment.Framework.CODEMIRROR) && patterns.containsKey("comment"))) {
    StringConcatenation _builder_10 = new StringConcatenation();
    _builder_10.append("dontIndentStates: [\"comment\"]");
    patterns.put("meta", _builder_10.toString());
  }
  if ((Objects.equal(this.framework.get(), WebIntegrationFragment.Framework.CODEMIRROR) && hasSingleLineComment)) {
    StringConcatenation _builder_11 = new StringConcatenation();
    _builder_11.append("lineComment: \"//\"");
    patterns.put("meta", _builder_11.toString());
  }
  return patterns;
}
 
Example 13
Source File: BundleUpgradeParser.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
static Multimap<VersionedName,VersionRangedName> parseVersionRangedNameEqualsVersionedNameList(String input, boolean singleVersionIsOsgiRange,
        List<String> wildcardNames, List<String> wildcardVersions,
        Function<VersionRangedName,VersionedName> defaultTargetFunction) {
    LinkedHashMultimap<VersionedName,VersionRangedName> result = LinkedHashMultimap.create();
    if (input == null) return result;
    
    List<String> vals = QuotedStringTokenizer.builder()
            .delimiterChars(",")
            .includeQuotes(false)
            .includeDelimiters(false)
            .buildList(input);
    
    for (String entry : vals) {
        entry = entry.trim();
        String key, val;
        String[] keVals = entry.split("=");
        if (keVals.length>2) {
            throw new IllegalArgumentException("Max one = permitted in entry (\""+entry+"\"). If defining a range on an entry you must quote the entry.");
        } else if (keVals.length==2) {
            key = keVals[0];
            val = keVals[1];
        } else {
            key = keVals[0];
            val = null;
        }
        
        List<String> sourceNames, sourceVersions;
        if (key.startsWith("*")) {
            if (wildcardNames==null) {
                throw new IllegalArgumentException("Wildcard cannot be inferred");
            }
            if  ("*".equals(key)) {
                if (wildcardVersions==null) {
                    throw new IllegalArgumentException("Version for wildcard cannot be inferred");
                }
                sourceVersions = wildcardVersions;
            } else if (key.startsWith("*:")) {
                sourceVersions = MutableList.of(key.substring(2));
            } else {
                throw new IllegalArgumentException("Wildcard entry key must be of the form \"*\" or \"*:range\"");
            }
            sourceNames = MutableList.copyOf(wildcardNames);
        } else {
            String[] parts = key.split(":");
            if (parts.length==1) {
                if (wildcardVersions==null) {
                    throw new IllegalArgumentException("Version for "+key+" cannot be inferred");
                }
                sourceNames = MutableList.of(key);
                sourceVersions = wildcardVersions;
            } else if (parts.length==2) {
                sourceNames = MutableList.of(parts[0]);
                sourceVersions = MutableList.of(parts[1]);
            } else {
                throw new IllegalArgumentException("Entry '"+entry+"' should be of form 'name[:versionRange][=name[:version]]'");
            }
        }
        for (String item: sourceNames) {
            for (String v: sourceVersions) {
                VersionRangedName source = parseVersionRangedName(item, v, false);
                VersionedName target;
                if (val!=null) {
                    target = VersionedName.fromString(val);
                } else if (defaultTargetFunction!=null) {
                    target = defaultTargetFunction.apply(source);
                } else {
                    throw new IllegalArgumentException("Wildcard entry key must be of the form \"*\" or \"*:range\"");
                }
                result.put(target, source);
            }
        }
    }
    return result;
}