List of usage examples for com.google.common.collect ArrayListMultimap create
public static <K, V> ArrayListMultimap<K, V> create()
From source file:com.opengamma.web.analytics.rest.MarketDataSnapshotListResource.java
/** * @return JSON {@code [{basisViewName: basisViewName1, snapshots: [{id: snapshot1Id, name: snapshot1Name}, ...]}, ...]} *//* w w w.ja v a 2s. c o m*/ @GET @Produces(MediaType.APPLICATION_JSON) public String getMarketDataSnapshotList() { MarketDataSnapshotSearchRequest snapshotSearchRequest = new MarketDataSnapshotSearchRequest(); snapshotSearchRequest.setIncludeData(false); Multimap<String, ManageableMarketDataSnapshot> snapshotsByBasisView = ArrayListMultimap.create(); for (MarketDataSnapshotDocument doc : MarketDataSnapshotSearchIterator.iterable(_snapshotMaster, snapshotSearchRequest)) { ManageableMarketDataSnapshot snapshot = doc.getSnapshot(); if (snapshot.getUniqueId() == null) { s_logger.warn("Ignoring snapshot with null unique identifier {}", snapshot.getName()); continue; } if (StringUtils.isBlank(snapshot.getName())) { s_logger.warn("Ignoring snapshot {} with no name", snapshot.getUniqueId()); continue; } if (s_guidPattern.matcher(snapshot.getName()).find()) { s_logger.debug("Ignoring snapshot which appears to have an auto-generated name: {}", snapshot.getName()); continue; } String basisViewName = snapshot.getBasisViewName() != null ? snapshot.getBasisViewName() : "unknown"; snapshotsByBasisView.put(basisViewName, snapshot); } // list of maps for each basis view: {"basisViewName": basisViewName, "snapshots", [...]} List<Map<String, Object>> basisViewSnapshotList = new ArrayList<Map<String, Object>>(); for (String basisViewName : snapshotsByBasisView.keySet()) { Collection<ManageableMarketDataSnapshot> viewSnapshots = snapshotsByBasisView.get(basisViewName); // list of maps containing snapshot IDs and names: {"id", snapshotId, "name", snapshotName} List<Map<String, Object>> snapshotsList = new ArrayList<Map<String, Object>>(viewSnapshots.size()); for (ManageableMarketDataSnapshot viewSnapshot : viewSnapshots) { // map for a single snapshot: {"id", snapshotId, "name", snapshotName} Map<String, Object> snapshotMap = ImmutableMap.<String, Object>of(ID, viewSnapshot.getUniqueId(), NAME, viewSnapshot.getName()); snapshotsList.add(snapshotMap); } basisViewSnapshotList.add(ImmutableMap.of(BASIS_VIEW_NAME, basisViewName, SNAPSHOTS, snapshotsList)); } return new JSONArray(basisViewSnapshotList).toString(); }
From source file:blackboard.plugin.hayabusa.provider.ModuleItemProvider.java
@Override public Iterable<Command> getCommands() { try {//from w ww. j a v a 2s. c o m // TODO wire these dependencies as fields/constructor inject ModuleDbLoader moduleLoader = ModuleDbLoader.Default.getInstance(); NavigationItemDbLoader niLoader = NavigationItemDbLoader.Default.getInstance(); Multimap<Module, NavigationItemControl> nicByModule = ArrayListMultimap.create(); for (Module module : moduleLoader.heavyLoadByModuleType("bb/admin")) { String subgroup = module.getPortalExtraInfo().getExtraInfo().getValue("subgroup"); List<NavigationItemControl> nics = NavigationItemControl .createList(niLoader.loadBySubgroup(subgroup)); nicByModule.putAll(module, nics); } Set<Command> commands = Sets.newTreeSet(); for (Module module : nicByModule.keys()) { Collection<NavigationItemControl> nics = nicByModule.get(module); for (NavigationItemControl nic : nics) { if (!nic.userHasAccess()) { continue; } String title = String.format("%s: %s", module.getTitle(), nic.getLabel()); String url = FramesetUtil.getTabGroupUrl(blackboard.data.navigation.Tab.TabType.admin, nic.getUrl()); commands.add(new SimpleCommand(title, url, Category.SYSTEM_ADMIN)); } } return commands; } catch (PersistenceException e) { throw new PersistenceRuntimeException(e); } }
From source file:org.fim.internal.StateComparator.java
private void init() { if (lastState != null && !lastState.getModelVersion().equals(currentState.getModelVersion())) { Logger.warning("Not able to compare with a State that have a different model version."); lastState = null;// w ww .j av a2 s . co m } makeLastStateComparable(); result = new CompareResult(context, lastState); previousFileStates = ArrayListMultimap.create(); notFoundInCurrentFileState = new ArrayList<>(); addedOrModified = new ArrayList<>(); }
From source file:org.apache.cassandra.client.RingCache.java
public void refreshEndpointMap() { for (String seed : seeds_) { try {/*from ww w. j a va 2 s . c o m*/ TSocket socket = new TSocket(seed, port_); TBinaryProtocol binaryProtocol = new TBinaryProtocol(new TFramedTransport(socket)); Cassandra.Client client = new Cassandra.Client(binaryProtocol); socket.open(); List<TokenRange> ring = client.describe_ring(keyspace); rangeMap = ArrayListMultimap.create(); for (TokenRange range : ring) { Token<?> left = partitioner_.getTokenFactory().fromString(range.start_token); Token<?> right = partitioner_.getTokenFactory().fromString(range.end_token); Range r = new Range(left, right, partitioner_); for (String host : range.endpoints) { try { rangeMap.put(r, InetAddress.getByName(host)); } catch (UnknownHostException e) { throw new AssertionError(e); // host strings are IPs } } } break; } catch (InvalidRequestException e) { throw new RuntimeException(e); } catch (TException e) { /* let the Exception go and try another seed. log this though */ logger_.debug("Error contacting seed " + seed + " " + e.getMessage()); } } }
From source file:org.apache.brooklyn.core.typereg.TypePlanTransformers.java
/** returns a list of {@link BrooklynTypePlanTransformer} instances for this {@link ManagementContext} * which may be able to handle the given plan; the list is sorted with highest-score transformer first */ @Beta//from w ww .j a v a 2s . c o m public static List<BrooklynTypePlanTransformer> forType(ManagementContext mgmt, RegisteredType type, RegisteredTypeLoadingContext constraint) { Multimap<Double, BrooklynTypePlanTransformer> byScoreMulti = ArrayListMultimap.create(); Collection<BrooklynTypePlanTransformer> transformers = all(mgmt); for (BrooklynTypePlanTransformer transformer : transformers) { double score = transformer.scoreForType(type, constraint); if (score > 0) byScoreMulti.put(score, transformer); } Map<Double, Collection<BrooklynTypePlanTransformer>> tree = new TreeMap<Double, Collection<BrooklynTypePlanTransformer>>( byScoreMulti.asMap()); List<Collection<BrooklynTypePlanTransformer>> highestFirst = new ArrayList<Collection<BrooklynTypePlanTransformer>>( tree.values()); Collections.reverse(highestFirst); return ImmutableList.copyOf(Iterables.concat(highestFirst)); }
From source file:com.palantir.atlasdb.keyvalue.jdbc.impl.MultiTimestampPutBatch.java
@Override @Nullable//from w w w . j a v a 2 s . c o m public PutBatch getNextBatch(Result<? extends Record> existingRecords) { Map<CellTimestamp, byte[]> existing = Maps.newHashMapWithExpectedSize(existingRecords.size()); for (Record record : existingRecords) { existing.put( new CellTimestamp(record.getValue(JdbcConstants.A_ROW_NAME), record.getValue(JdbcConstants.A_COL_NAME), record.getValue(JdbcConstants.A_TIMESTAMP)), record.getValue(JdbcConstants.A_VALUE)); } Multimap<Cell, Value> nextBatch = ArrayListMultimap.create(); for (Entry<Cell, Value> entry : data.entries()) { Cell cell = entry.getKey(); Value newValue = entry.getValue(); byte[] oldValue = existing .get(new CellTimestamp(cell.getRowName(), cell.getColumnName(), newValue.getTimestamp())); if (oldValue == null) { nextBatch.put(cell, newValue); } else if (!Arrays.equals(oldValue, newValue.getContents())) { return null; } } return new MultiTimestampPutBatch(nextBatch); }
From source file:old.MetaboliteComparison.java
/** * Generates a comparison table//from w w w.j a v a 2 s . co m * @param type * @return */ public JTable getComparisconTable(final TableData type) { JTable table = new JTable(); Reconstruction[] recons = comparison.getReconstructions(); Map<Long, Multimap<Reconstruction, Metabolite>> map = new HashMap<Long, Multimap<Reconstruction, Metabolite>>(); for (int i = 0; i < recons.length; i++) { Reconstruction reconstruction = recons[i]; for (Entry<Metabolite, Long> e : comparison.getMoleculeHashMap(reconstruction).entrySet()) { Long key = e.getValue(); if (!map.containsKey(key)) { Multimap<Reconstruction, Metabolite> sub = ArrayListMultimap.create(); map.put(key, sub); } map.get(key).put(reconstruction, e.getKey()); } } List<IAtomContainer> structures = new ArrayList(); Object[][] data = new Object[map.keySet().size()][recons.length]; int i = 0; for (Entry<Long, Multimap<Reconstruction, Metabolite>> e : map.entrySet()) { Long key = e.getKey(); Multimap<Reconstruction, Metabolite> sub = e.getValue(); for (int j = 0; j < recons.length; j++) { Reconstruction recon = recons[j]; switch (type) { case PRESENCE: data[i][j] = sub.containsKey(recon) ? "x" : ""; break; case OCCURANCE: data[i][j] = sub.containsKey(recon) ? sub.get(recon).size() : 0; break; case NAME: List<String> names = new ArrayList(); if (sub.containsKey(recon)) { for (Metabolite m : sub.get(recon)) { names.add(m.getName()); } } data[i][j] = names; break; case ABBREVIATION: List<String> abbrv = new ArrayList(); if (sub.containsKey(recon)) { for (Metabolite m : sub.get(recon)) { abbrv.add(m.getAbbreviation()); } } data[i][j] = abbrv; break; case STRUCTURE: List<AtomContainerAnnotation> structure = new ArrayList(); if (sub.containsKey(recon)) { for (Metabolite m : sub.get(recon)) { if (m.hasStructure()) { Collection<AtomContainerAnnotation> collection = m .getAnnotationsExtending(AtomContainerAnnotation.class); if (!collection.isEmpty()) { structure.add(collection.iterator().next()); } } } } data[i][j] = structure; break; } } i++; } DefaultTableModel model = new DefaultTableModel(data, recons) { @Override public Class<?> getColumnClass(int columnIndex) { switch (type) { case STRUCTURE: return AtomContainerAnnotation.class; case NAME: return List.class; case ABBREVIATION: return List.class; default: return Object.class; } } }; table.setModel(model); table.setDefaultRenderer(List.class, new AnnotationCellRenderer()); if (type == TableData.STRUCTURE) { table.setDefaultRenderer(AtomContainerAnnotation.class, new ChemicalStructureRenderer()); table.setRowHeight(64); } return table; }
From source file:org.terasology.engine.ComponentSystemManager.java
public void loadSystems(ModuleEnvironment environment, NetworkMode netMode) { DisplayDevice displayDevice = CoreRegistry.get(DisplayDevice.class); boolean isHeadless = displayDevice.isHeadless(); ListMultimap<Name, Class<?>> systemsByModule = ArrayListMultimap.create(); for (Class<?> type : environment.getTypesAnnotatedWith(RegisterSystem.class)) { if (!ComponentSystem.class.isAssignableFrom(type)) { logger.error("Cannot load {}, must be a subclass of ComponentSystem", type.getSimpleName()); continue; }// w ww.ja v a2 s.c o m Name moduleId = environment.getModuleProviding(type); RegisterSystem registerInfo = type.getAnnotation(RegisterSystem.class); if (registerInfo.value().isValidFor(netMode, isHeadless)) { systemsByModule.put(moduleId, type); } } for (Module module : environment.getModulesOrderedByDependencies()) { for (Class<?> system : systemsByModule.get(module.getId())) { String id = module.getId() + ":" + system.getSimpleName(); logger.debug("Registering system {}", id); try { ComponentSystem newSystem = (ComponentSystem) system.newInstance(); InjectionHelper.share(newSystem); register(newSystem, id); logger.debug("Loaded system {}", id); } catch (InstantiationException | IllegalAccessException e) { logger.error("Failed to load system {}", id, e); } } } }
From source file:com.medallia.spider.api.DynamicInputImpl.java
/** * Creates a new {@link DynamicInputImpl} * @param request from which to read the request parameters *//*w w w . j ava2 s.c o m*/ public DynamicInputImpl(HttpServletRequest request) { @SuppressWarnings("unchecked") Map<String, String[]> reqParams = Maps.newHashMap(request.getParameterMap()); this.inputParams = reqParams; if (ServletFileUpload.isMultipartContent(request)) { this.fileUploads = Maps.newHashMap(); Multimap<String, String> inputParamsWithList = ArrayListMultimap.create(); ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String fieldName = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { inputParamsWithList.put(fieldName, Streams.asString(stream, Charsets.UTF_8.name())); } else { final String filename = item.getName(); final byte[] bytes = ByteStreams.toByteArray(stream); fileUploads.put(fieldName, new UploadedFile() { @Override public String getFilename() { return filename; } @Override public byte[] getBytes() { return bytes; } @Override public int getSize() { return bytes.length; } }); } } for (Entry<String, Collection<String>> entry : inputParamsWithList.asMap().entrySet()) { inputParams.put(entry.getKey(), entry.getValue().toArray(new String[0])); } } catch (IOException | FileUploadException e) { throw new IllegalArgumentException("Failed to parse multipart", e); } } else { this.fileUploads = Collections.emptyMap(); } }
From source file:com.foundationdb.server.types.service.ResolvablesRegistry.java
private static <R extends TOverload, V extends TValidatedOverload> ListMultimap<String, ScalarsGroup<V>> createScalars( InstanceFinder finder, TCastResolver castResolver, Class<R> plainClass, Function<R, V> validator) { Multimap<String, V> overloadsByName = ArrayListMultimap.create(); int errors = 0; for (R scalar : finder.find(plainClass)) { try {/* ww w. jav a 2 s . c om*/ V validated = validator.apply(scalar); String[] names = validated.registeredNames(); for (int i = 0; i < names.length; ++i) names[i] = names[i].toLowerCase(); for (String name : names) overloadsByName.put(name, validated); } catch (RuntimeException e) { rejectTOverload(scalar, e); ++errors; } catch (AssertionError e) { rejectTOverload(scalar, e); ++errors; } } if (errors > 0) { StringBuilder sb = new StringBuilder("Found ").append(errors).append(" error"); if (errors != 1) sb.append('s'); sb.append(" while collecting scalar functions. Check logs for details."); throw new AkibanInternalException(sb.toString()); } ArrayListMultimap<String, ScalarsGroup<V>> results = ArrayListMultimap.create(); for (Map.Entry<String, Collection<V>> entry : overloadsByName.asMap().entrySet()) { String overloadName = entry.getKey(); Collection<V> allOverloads = entry.getValue(); for (Collection<V> priorityGroup : scalarsByPriority(allOverloads)) { ScalarsGroup<V> scalarsGroup = new ScalarsGroupImpl<>(priorityGroup, castResolver); results.put(overloadName, scalarsGroup); } } results.trimToSize(); return Multimaps.unmodifiableListMultimap(results); }