public void testCreateFromMultimap() { Multimap<String, Integer> multimap = LinkedHashMultimap.create(); multimap.put("a", 1); multimap.put("b", 2); multimap.put("a", 3); multimap.put("c", 4); LinkedHashMultimap<String, Integer> copy = LinkedHashMultimap.create(multimap); new EqualsTester().addEqualityGroup(multimap, copy).testEquals(); }
public void testCreateFromIllegalSizes() { try { LinkedHashMultimap.create(-20, 15); fail(); } catch (IllegalArgumentException expected) { } try { LinkedHashMultimap.create(20, -15); fail(); } catch (IllegalArgumentException expected) { } }
public void testCreateFromSizes() { LinkedHashMultimap<String, Integer> multimap = LinkedHashMultimap.create(20, 15); multimap.put("foo", 1); multimap.put("bar", 2); multimap.put("foo", 3); assertEquals(ImmutableSet.of(1, 3), multimap.get("foo")); }
/** Builder of {@link ImportManager} instances. */ public static class Builder { /** * Simple names of implicitly imported types, mapped to qualified name if that type is safe to * use, null otherwise. */ private final SetMultimap<String, TypeReference> implicitImports = LinkedHashMultimap.create(); /** Adds a type which is implicitly imported into the current compilation unit. */ public Builder addImplicitImport(TypeReference type) { implicitImports.put(type.getSimpleName(), type); return this; } public ImportManager build() { Set<String> nonConflictingImports = new LinkedHashSet<String>(); for (Set<TypeReference> importGroup : Multimaps.asMap(implicitImports).values()) { if (importGroup.size() == 1) { TypeReference implicitImport = getOnlyElement(importGroup); if (implicitImport.isTopLevel()) { nonConflictingImports.add(implicitImport.getQualifiedName()); } } } return new ImportManager(implicitImports.keySet(), nonConflictingImports); } }
public String configFile() { // Check template URL exists String templateUrl = driver.getEntity().getConfig(NginxController.SERVER_CONF_TEMPLATE_URL); ResourceUtils.create(this).checkUrlExists(templateUrl); // Check SSL configuration ProxySslConfig ssl = driver.getEntity().getConfig(NginxController.SSL_CONFIG); if (ssl != null && Strings.isEmpty(ssl.getCertificateDestination()) && Strings.isEmpty(ssl.getCertificateSourceUrl())) { throw new IllegalStateException( "ProxySslConfig can't have a null certificateDestination and null certificateSourceUrl. One or both need to be set"); } // For mapping by URL Iterable<UrlMapping> mappings = ((NginxController) driver.getEntity()).getUrlMappings(); Multimap<String, UrlMapping> mappingsByDomain = LinkedHashMultimap.create(); for (UrlMapping mapping : mappings) { Collection<String> addrs = mapping.getAttribute(UrlMapping.TARGET_ADDRESSES); if (addrs != null && addrs.size() > 0) { mappingsByDomain.put(mapping.getDomain(), mapping); } } Map<String, Object> substitutions = MutableMap.<String, Object>builder() .putIfNotNull("ssl", ssl) .put("urlMappings", mappings) .put("domainMappings", mappingsByDomain) .build(); // Get template contents and process String contents = ResourceUtils.create(driver.getEntity()).getResourceAsString(templateUrl); return TemplateProcessor.processTemplateContents(contents, driver, substitutions); }
private Multimap<String, String> computeUserParameters() { Multimap<String, String> result = LinkedHashMultimap.create(); for (String key : suite.parameterNames()) { // first check if the user has specified values Collection<String> userValues = userParameterArguments.get(key); if (!userValues.isEmpty()) { result.putAll(key, userValues); // TODO: type convert 'em to validate? } else { // otherwise use the default values from the suite Set<String> values = suite.parameterValues(key); if (values.isEmpty()) { throw new ConfigurationException( key + " has no values. " + "Did you forget a -D" + key + "=<value> command line argument?"); } result.putAll(key, values); } } return result; }
@Override public Multimap<K, V> apply(Map<K, Set<V>> from) { Multimap<K, V> returnV = LinkedHashMultimap.create(); for (Entry<K, Set<V>> entry : from.entrySet()) { for (V value : entry.getValue()) returnV.put(entry.getKey(), value); } return returnV; }
public void testConstrainedTypePreservingSet() { SetMultimap<String, Integer> multimap = MapConstraints.constrainedSetMultimap( LinkedHashMultimap.<String, Integer>create(), TEST_CONSTRAINT); multimap.put("foo", 1); Map.Entry<String, Collection<Integer>> entry = multimap.asMap().entrySet().iterator().next(); assertTrue(entry.getValue() instanceof Set); }
public void testToString() { Multimap<String, Integer> multimap = LinkedHashMultimap.create(); multimap.put("foo", 3); multimap.put("bar", 1); multimap.putAll("foo", Arrays.asList(-1, 2, 4)); multimap.putAll("bar", Arrays.asList(2, 3)); multimap.put("foo", 1); assertEquals("{foo=[3, -1, 2, 4, 1], bar=[1, 2, 3]}", multimap.toString()); }
private Multimap<String, Integer> initializeMultimap5() { Multimap<String, Integer> multimap = LinkedHashMultimap.create(); multimap.put("foo", 5); multimap.put("bar", 4); multimap.put("foo", 3); multimap.put("cow", 2); multimap.put("bar", 1); return multimap; }
public <S, P, R, D extends Pda<S, P>> D filterEdges( Pda<S, P> pda, Traverser<? super Pda<S, P>, S, R> traverser, PdaFactory<D, S, P, S> factory) { HashStack<TraversalItem<S, R>> trace = new HashStack<TraversalItem<S, R>>(); R previous = traverser.enter(pda, pda.getStart(), null); if (previous == null) return factory == null ? null : factory.create(pda.getStart(), pda.getStop()); Map<S, Integer> distances = new NfaUtil().distanceToFinalStateMap(pda); MappedComparator<S, Integer> distanceComp = new MappedComparator<S, Integer>(distances); trace.push(newItem(pda, distanceComp, distances, pda.getStart(), previous)); Multimap<S, S> edges = LinkedHashMultimap.create(); HashSet<S> states = Sets.newLinkedHashSet(); HashSet<Pair<S, R>> success = Sets.newLinkedHashSet(); states.add(pda.getStart()); states.add(pda.getStop()); ROOT: while (!trace.isEmpty()) { TraversalItem<S, R> current = trace.peek(); while (current.followers.hasNext()) { S next = current.followers.next(); R item = traverser.enter(pda, next, current.data); if (item != null) { if ((next == pda.getStop() && traverser.isSolution(item)) || success.contains(Tuples.create(next, item))) { S s = null; for (TraversalItem<S, R> i : trace) { if (s != null) edges.put(s, i.state); states.add(i.state); success.add(Tuples.create(i.state, i.data)); s = i.state; } edges.put(s, next); } else { if (trace.push(newItem(pda, distanceComp, distances, next, item))) continue ROOT; } } } trace.pop(); } if (factory == null) return null; D result = factory.create(pda.getStart(), pda.getStop()); Map<S, S> old2new = Maps.newLinkedHashMap(); old2new.put(pda.getStart(), result.getStart()); old2new.put(pda.getStop(), result.getStop()); for (S old : states) { if (old == pda.getStart() || old == pda.getStop()) continue; else if (pda.getPop(old) != null) old2new.put(old, factory.createPop(result, old)); else if (pda.getPush(old) != null) old2new.put(old, factory.createPush(result, old)); else old2new.put(old, factory.createState(result, old)); } for (S old : states) { List<S> followers = Lists.newArrayList(); for (S f : edges.get(old)) followers.add(old2new.get(f)); factory.setFollowers(result, old2new.get(old), followers); } return result; }
/** * Replaces the current payload with one that is a urlencoded payload including the following * parameters and any formerly set. * * @see HttpRequest#getPayload() */ public T addFormParams(Multimap<String, String> parameters) { checkNotNull(endpoint, "endpoint"); Multimap<String, String> map = payload != null ? queryParser().apply(payload.getRawContent().toString()) : LinkedHashMultimap.<String, String>create(); map.putAll(parameters); payload = newUrlEncodedFormPayload(map); return self(); }
@Override public void run() { try { // Authenticate URLConnection connection = new URL(this.postURL).openConnection(); JsonObject json; try (InputStream is = connection.getInputStream()) { if (is.available() == 0) { this.session.disconnect("Invalid username or session id!"); return; } try { json = gson.fromJson(new InputStreamReader(is), JsonObject.class); } catch (Exception e) { LanternGame.log().warn("Username \"" + this.username + "\" failed to authenticate!"); this.session.disconnect("Failed to verify username!"); return; } } String name = json.get("name").getAsString(); String id = json.get("id").getAsString(); // Parse UUID UUID uuid; try { uuid = UUIDHelper.fromFlatString(id); } catch (IllegalArgumentException e) { LanternGame.log().error("Returned authentication UUID invalid: " + id, e); this.session.disconnect("Invalid UUID."); return; } JsonArray propsArray = json.getAsJsonArray("properties"); // Parse properties Multimap<String, ProfileProperty> properties = LinkedHashMultimap.create(); for (JsonElement element : propsArray) { JsonObject json0 = element.getAsJsonObject(); String propName = json0.get("name").getAsString(); String value = json0.get("value").getAsString(); String signature = json0.has("signature") ? json0.get("signature").getAsString() : null; properties.put(propName, new LanternProfileProperty(propName, value, signature)); } LanternGame.log().info("Finished authenticating."); this.session.messageReceived( new MessageLoginInFinish(new LanternGameProfile(uuid, name, properties))); } catch (Exception e) { LanternGame.log().error("Error in authentication thread", e); this.session.disconnect("Internal error during authentication.", true); } }
@Test public void serializeEmpty() { // given Multimap<HttpMethod, RestParameter> map = LinkedHashMultimap.create(); // when String serialized = serializer.serialize(map); // then assertEquals("{}", serialized); }
/** * Replaces the current payload with one that is a urlencoded payload including the following * parameters and any formerly set. * * @see HttpRequest#getPayload() */ public T replaceFormParams(Multimap<String, String> parameters) { checkNotNull(endpoint, "endpoint"); Multimap<String, String> map = payload != null ? queryParser().apply(payload.getRawContent().toString()) : LinkedHashMultimap.<String, String>create(); for (Map.Entry<String, Collection<String>> entry : parameters.asMap().entrySet()) { map.replaceValues(entry.getKey(), entry.getValue()); } payload = newUrlEncodedFormPayload(map); return self(); }
@Test public void serializeSimple() { // given Multimap<HttpMethod, RestParameter> map = LinkedHashMultimap.create(); map.put(HttpMethod.GET, new RestParameter("a", 1)); // when String serialized = serializer.serialize(map); // then assertEquals("{\"GET\":[{\"key\": \"a\", \"value\": \"1\"}]}", serialized); }
public SetMultimap<AbstractModule, FeatureProject> resolveResolutionContext( AbstractModule module, boolean scopeTest) { final SetMultimap<AbstractModule, FeatureProject> result = LinkedHashMultimap.create(); for (FeatureProject featureProject : requiredFeatures) { result.get(featureProject.getParent().getParent()).add(featureProject); } if (scopeTest) { for (FeatureProject featureProject : requiredTestFeatures) { result.get(featureProject.getParent().getParent()).add(featureProject); } } return result; }
/** * Initializes the PDPModel. * * @param twp The {@link rinde.sim.core.model.pdp.twpolicy.TimeWindowPolicy} which is used in the * model. */ public DefaultTripleDJPDPModel(TimeWindowPolicy twp) { timeWindowPolicy = twp; containerContents = LinkedHashMultimap.create(); containerContentsSize = newLinkedHashMap(); containerCapacities = newLinkedHashMap(); pendingVehicleActions = newLinkedHashMap(); vehicleState = newLinkedHashMap(); parcelState = CategoryMap.create(); eventDispatcher = new EventDispatcher(PDPModelEventType.values()); roadModel = Optional.absent(); }
@GwtIncompatible // SeriazableTester public void testSerializationOrderingKeysAndEntries() { Multimap<String, Integer> multimap = LinkedHashMultimap.create(); multimap.put("a", 1); multimap.put("b", 2); multimap.put("a", 3); multimap.put("c", 4); multimap.remove("a", 1); multimap = SerializableTester.reserializeAndAssert(multimap); assertThat(multimap.keySet()).containsExactly("a", "b", "c").inOrder(); assertThat(multimap.entries()) .containsExactly(mapEntry("b", 2), mapEntry("a", 3), mapEntry("c", 4)) .inOrder(); // note that the keys and entries are in different orders }
public void testValueSetHashTableExpansion() { LinkedHashMultimap<String, Integer> multimap = LinkedHashMultimap.create(); for (int z = 1; z <= 100; z++) { multimap.put("a", z); // The Eclipse compiler (and hence GWT) rejects a parameterized cast. @SuppressWarnings("unchecked") LinkedHashMultimap<String, Integer>.ValueSet valueSet = (LinkedHashMultimap.ValueSet) multimap.backingMap().get("a"); assertEquals(z, valueSet.size()); assertFalse( Hashing.needsResizing( valueSet.size(), valueSet.hashTable.length, LinkedHashMultimap.VALUE_SET_LOAD_FACTOR)); } }
public void after(EObject grammarElement) { EObject foundGrammarElement = grammarElements.remove(grammarElements.size() - 1); if (grammarElement != foundGrammarElement) throw new IllegalStateException( "expected element: '" + grammarElement + "', but was: '" + foundGrammarElement + "'"); if (grammarElement instanceof UnorderedGroup && indexToHandledElements != null) { indexToHandledElements.removeAll(grammarElements.size()); } else if (!grammarElements.isEmpty()) { int index = grammarElements.size() - 1; if (grammarElements.get(index) instanceof UnorderedGroup) { if (indexToHandledElements == null) { indexToHandledElements = LinkedHashMultimap.create(); } indexToHandledElements.put(index, (AbstractElement) grammarElement); } } }
@Test public void serializeComplex() { // given Multimap<HttpMethod, RestParameter> map = LinkedHashMultimap.create(); map.put(HttpMethod.GET, new RestParameter("a", 1)); map.put(HttpMethod.GET, new RestParameter("b", false)); map.put(HttpMethod.POST, new RestParameter("c", "some string")); map.put(HttpMethod.POST, new RestParameter("d", 29L)); // when String serialized = serializer.serialize(map); // then assertEquals( "{\"GET\":[{\"key\": \"a\", \"value\": \"1\"}, {\"key\": \"b\", \"value\": \"false\"}]," + "\"POST\":[{\"key\": \"c\", \"value\": \"some string\"}, {\"key\": \"d\", \"value\": \"29\"}]}", serialized); }
private GeoServerTileLayer mockTileLayer(String layerName, List<String> gridSetNames) throws Exception { GeoServerTileLayer tileLayer = mock(GeoServerTileLayer.class); when(tld.layerExists(eq(layerName))).thenReturn(true); when(tld.getTileLayer(eq(layerName))).thenReturn(tileLayer); when(tileLayer.getName()).thenReturn(layerName); when(tileLayer.isEnabled()).thenReturn(true); final MimeType mimeType1 = MimeType.createFromFormat("image/png"); final MimeType mimeType2 = MimeType.createFromFormat("image/jpeg"); when(tileLayer.getMimeTypes()).thenReturn(ImmutableList.of(mimeType1, mimeType2)); Map<String, GridSubset> subsets = Maps.newHashMap(); Multimap<SRS, GridSubset> bySrs = LinkedHashMultimap.create(); GridSetBroker broker = gridSetBroker; for (String gsetName : gridSetNames) { GridSet gridSet = broker.get(gsetName); XMLGridSubset xmlGridSubset = new XMLGridSubset(); String gridSetName = gridSet.getName(); xmlGridSubset.setGridSetName(gridSetName); GridSubset gridSubSet = xmlGridSubset.getGridSubSet(broker); subsets.put(gsetName, gridSubSet); bySrs.put(gridSet.getSrs(), gridSubSet); when(tileLayer.getGridSubset(eq(gsetName))).thenReturn(gridSubSet); } for (SRS srs : bySrs.keySet()) { List<GridSubset> list = ImmutableList.copyOf(bySrs.get(srs)); when(tileLayer.getGridSubsetsForSRS(eq(srs))).thenReturn(list); } when(tileLayer.getGridSubsets()).thenReturn(subsets.keySet()); // sanity check for (String gsetName : gridSetNames) { assertTrue(tileLayer.getGridSubsets().contains(gsetName)); assertNotNull(tileLayer.getGridSubset(gsetName)); } return tileLayer; }
public <S, P, T, D extends Pda<S, P>> D expand( Pda<S, P> pda, Function<S, Pda<S, P>> expand, Function<S, T> tokens, PdaFactory<D, S, P, T> fact) { D result = fact.create(tokens.apply(pda.getStart()), tokens.apply(pda.getStop())); Identity<S> identity = new Identity<S>(); Map<S, S> idstates = Maps.newIdentityHashMap(); Multimap<S, S> followers = LinkedHashMultimap.create(); for (S s_old : nfaUtil.collect(pda)) { S s_new = idstates.get(s_old); if (s_new == null) { Pda<S, P> sub = expand.apply(s_old); if (sub != null) { S s_start = identity.get(fact.createPush(result, tokens.apply(s_old))); S s_stop = identity.get(fact.createPop(result, tokens.apply(s_old))); idstates.put(s_old, s_start); idstates.put(sub.getStart(), s_start); idstates.put(sub.getStop(), s_stop); followers.putAll(s_start, sub.getFollowers(sub.getStart())); followers.putAll(s_stop, pda.getFollowers(s_old)); for (S f_old : nfaUtil.collect(sub)) if (f_old != sub.getStart() && f_old != sub.getStop()) { S f_new = idstates.get(f_old); if (f_new == null) { idstates.put(f_old, f_new = clone(f_old, sub, result, tokens, fact, identity)); followers.putAll(f_new, pda.getFollowers(f_old)); } } } else { idstates.put(s_old, s_new = clone(s_old, pda, result, tokens, fact, identity)); followers.putAll(s_new, pda.getFollowers(s_old)); } } } for (Map.Entry<S, Collection<S>> entry : followers.asMap().entrySet()) { Set<S> f = Sets.newLinkedHashSet(); for (S s : entry.getValue()) f.add(idstates.get(s)); fact.setFollowers(result, entry.getKey(), f); } return result; }
private List<RobotElement> groupedChildren(final List<? extends RobotElement> children) { final List<RobotElement> grouped = new ArrayList<>(children); final Multimap<SettingsGroup, RobotSetting> removedElements = LinkedHashMultimap.create(); for (final RobotElement element : children) { if (element instanceof RobotSetting) { final RobotSetting setting = (RobotSetting) element; final SettingsGroup group = setting.getGroup(); if (group != SettingsGroup.NO_GROUP) { grouped.remove(element); removedElements.put(group, setting); } } } for (final SettingsGroup key : removedElements.keySet()) { grouped.add( new ArtificialGroupingRobotElement(key, new ArrayList<>(removedElements.get(key)))); } return grouped; }
@Override public ImmutableMultimap<Attribute, Label> computeAspectDependencies(Target target) throws InterruptedException { if (!(target instanceof Rule)) { return ImmutableMultimap.of(); } Multimap<Attribute, Label> result = LinkedHashMultimap.create(); for (Attribute attribute : ((Rule) target).getAttributes()) { for (Class<? extends AspectFactory<?, ?, ?>> aspectFactory : attribute.getAspects()) { AspectDefinition.addAllAttributesOfAspect( (Rule) target, result, AspectFactory.Util.create(aspectFactory).getDefinition(), Rule.ALL_DEPS); } } return ImmutableMultimap.copyOf(result); }
public HttpResponse apply(Response nativeResponse) { InputStream in = null; try { in = BaseHttpCommandExecutorService.consumeOnClose(nativeResponse.getResponseBodyAsStream()); } catch (IOException e) { Closeables.closeQuietly(in); propagate(e); assert false : "should have propagated exception"; } Payload payload = in != null ? Payloads.newInputStreamPayload(in) : null; HttpResponse response = new HttpResponse(nativeResponse.getStatusCode(), nativeResponse.getStatusText(), payload); Multimap<String, String> headers = LinkedHashMultimap.create(); for (Entry<String, List<String>> header : nativeResponse.getHeaders()) { headers.putAll(header.getKey(), header.getValue()); } utils.setPayloadPropertiesFromHeaders(headers, response); return response; }
public void testToStringNullExact() { Multimap<String, Integer> multimap = LinkedHashMultimap.create(); multimap.put("foo", 3); multimap.put("foo", -1); multimap.put(null, null); multimap.put("bar", 1); multimap.put("foo", 2); multimap.put(null, 0); multimap.put("bar", 2); multimap.put("bar", null); multimap.put("foo", null); multimap.put("foo", 4); multimap.put(null, -1); multimap.put("bar", 3); multimap.put("bar", 1); multimap.put("foo", 1); assertEquals( "{foo=[3, -1, 2, null, 4, 1], null=[null, 0, -1], bar=[1, 2, null, 3]}", multimap.toString()); }
private void identifyDuplicates(List<ModContainer> mods) { TreeMultimap<ModContainer, File> dupsearch = TreeMultimap.create(new ModIdComparator(), Ordering.arbitrary()); for (ModContainer mc : mods) { if (mc.getSource() != null) { dupsearch.put(mc, mc.getSource()); } } ImmutableMultiset<ModContainer> duplist = Multisets.copyHighestCountFirst(dupsearch.keys()); SetMultimap<ModContainer, File> dupes = LinkedHashMultimap.create(); for (Entry<ModContainer> e : duplist.entrySet()) { if (e.getCount() > 1) { FMLLog.severe( "Found a duplicate mod %s at %s", e.getElement().getModId(), dupsearch.get(e.getElement())); dupes.putAll(e.getElement(), dupsearch.get(e.getElement())); } } if (!dupes.isEmpty()) { throw new DuplicateModsFoundException(dupes); } }
@Override public Boolean caseAlternatives(Alternatives object) { Multimap<String, AbstractElement> prevAssignedFeatures = assignedFeatures; Multimap<String, AbstractElement> mergedAssignedFeatures = LinkedHashMultimap.create(); for (AbstractElement element : object.getElements()) { assignedFeatures = newMultimap(prevAssignedFeatures); doSwitch(element); mergedAssignedFeatures.putAll(assignedFeatures); } if (GrammarUtil.isOptionalCardinality(object)) { mergedAssignedFeatures.putAll(prevAssignedFeatures); } assignedFeatures = mergedAssignedFeatures; if (GrammarUtil.isMultipleCardinality(object)) { prevAssignedFeatures = assignedFeatures; for (AbstractElement element : object.getElements()) { assignedFeatures = newMultimap(prevAssignedFeatures); doSwitch(element); mergedAssignedFeatures.putAll(assignedFeatures); } assignedFeatures = mergedAssignedFeatures; } return Boolean.FALSE; }