List of usage examples for com.google.common.collect Table rowMap
Map<R, Map<C, V>> rowMap();
From source file:org.hawk.service.emf.EffectiveMetamodelRulesetSerializer.java
private void save(Table<String, String, ImmutableSet<String>> table, String suffix, Properties props) { int iMetamodel = 0; for (Entry<String, Map<String, ImmutableSet<String>>> mmEntry : table.rowMap().entrySet()) { final String mmURI = mmEntry.getKey(); props.put(propertyPrefix + suffix + iMetamodel, mmURI); int iType = 0; for (Entry<String, ImmutableSet<String>> typeEntry : mmEntry.getValue().entrySet()) { final String type = typeEntry.getKey(); props.put(propertyPrefix + suffix + iMetamodel + SEPARATOR + iType, type); final Set<String> slots = typeEntry.getValue(); final StringBuffer sbuf = new StringBuffer(); boolean first = true; for (String slot : slots) { if (first) { first = false;/*from ww w.j a v a 2s .co m*/ } else { sbuf.append(SEPARATOR); } sbuf.append(slot); } props.put(propertyPrefix + suffix + iMetamodel + SEPARATOR + iType + SEPARATOR + "slots", sbuf.toString()); iType++; } iMetamodel++; } }
From source file:com.sk89q.worldguard.protection.managers.storage.sql.DataLoader.java
private void loadFlags() throws SQLException { Closer closer = Closer.create();//ww w . j a v a2s. c o m try { PreparedStatement stmt = closer.register(conn.prepareStatement( "SELECT region_id, flag, value " + "FROM " + config.getTablePrefix() + "region_flag " + "WHERE world_id = " + worldId + " AND region_id IN " + "(SELECT id FROM " + config.getTablePrefix() + "region " + "WHERE world_id = " + worldId + ")")); ResultSet rs = closer.register(stmt.executeQuery()); Table<String, String, Object> data = HashBasedTable.create(); while (rs.next()) { data.put(rs.getString("region_id"), rs.getString("flag"), unmarshalFlagValue(rs.getString("value"))); } for (Entry<String, Map<String, Object>> entry : data.rowMap().entrySet()) { ProtectedRegion region = loaded.get(entry.getKey()); region.setFlags(flagRegistry.unmarshal(entry.getValue(), true)); } } finally { closer.closeQuietly(); } }
From source file:com.ngdata.hbaseindexer.indexer.Indexer.java
/** * groups a map of (id->document) pairs by shard * (consider moving this to a BaseSharder class) *///from w w w .jav a2 s . c o m private Map<Integer, Map<String, SolrInputDocument>> shardByMapKey( Map<String, SolrInputDocument> documentsToAdd) throws SharderException { Table<Integer, String, SolrInputDocument> table = HashBasedTable.create(); for (Map.Entry<String, SolrInputDocument> entry : documentsToAdd.entrySet()) { table.put(sharder.getShard(entry.getKey()), entry.getKey(), entry.getValue()); } return table.rowMap(); }
From source file:co.cask.cdap.data2.dataset2.lib.cube.DefaultCube.java
private Collection<TimeSeries> convertToQueryResult(CubeQuery query, Table<Map<String, String>, String, Map<Long, Long>> resultTable) { List<TimeSeries> result = Lists.newArrayList(); // iterating each groupValue dimensions for (Map.Entry<Map<String, String>, Map<String, Map<Long, Long>>> row : resultTable.rowMap().entrySet()) { // iterating each measure for (Map.Entry<String, Map<Long, Long>> measureEntry : row.getValue().entrySet()) { // generating time series for a grouping and a measure int count = 0; List<TimeValue> timeValues = Lists.newArrayList(); for (Map.Entry<Long, Long> timeValue : measureEntry.getValue().entrySet()) { timeValues.add(new TimeValue(timeValue.getKey(), timeValue.getValue())); }//from ww w.ja v a 2 s. com Collections.sort(timeValues); PeekingIterator<TimeValue> timeValueItor = Iterators.peekingIterator( new TimeSeriesInterpolator(timeValues, query.getInterpolator(), query.getResolution()) .iterator()); List<TimeValue> resultTimeValues = Lists.newArrayList(); while (timeValueItor.hasNext()) { TimeValue timeValue = timeValueItor.next(); resultTimeValues.add(new TimeValue(timeValue.getTimestamp(), timeValue.getValue())); if (++count >= query.getLimit()) { break; } } result.add(new TimeSeries(measureEntry.getKey(), row.getKey(), resultTimeValues)); } } return result; }
From source file:org.pau.assetmanager.viewmodel.stocks.HistoricalStockBalanceState.java
private static Table<Integer, Integer, Set<StockState>> getDiscontiniousHistoricalStockBalanceStateTable( BookSelection bookSelection, Integer lastYear, Optional<String> optionalStockLabel) { // year --> month --> symbol Table<Integer, Integer, Set<StockState>> historicalStockBalanceStateTable = HashBasedTable .<Integer, Integer, Set<StockState>>create(); Calendar calendar = GregorianCalendar.getInstance(); List<Annotation> annotations = StocksYearlyReportViewModel.getStocksAnnotationsUntilYear(bookSelection, lastYear);//from w ww. j a v a 2s. co m if (optionalStockLabel.isPresent()) { final String stockLabel = optionalStockLabel.get(); annotations = Lists.newArrayList(Collections2.filter(annotations, new Predicate<Annotation>() { @Override public boolean apply(Annotation annotation) { if (annotation instanceof StockIncomeAnnotation || annotation instanceof StockExpensesAnnotation) { return annotation.getConcept().equals(stockLabel); } else { return false; } } })); } Map<String, StockState> symbolToCurrentStockState = new HashMap<String, StockState>(); for (Annotation annotation : annotations) { calendar.setTime(annotation.getDate()); Integer currentYear = calendar.get(Calendar.YEAR); Integer currentMonth = calendar.get(Calendar.MONTH); updateCurrentSymbolToCurrentStockState(symbolToCurrentStockState, annotation, currentMonth, currentYear); StockState stockState = symbolToCurrentStockState.get(annotation.getConcept()); Set<StockState> setOfStockStates = null; if (historicalStockBalanceStateTable.rowMap().get(currentYear) == null || historicalStockBalanceStateTable.rowMap().get(currentYear).get(currentMonth) == null) { setOfStockStates = new HashSet<StockState>(); } else { setOfStockStates = historicalStockBalanceStateTable.rowMap().get(currentYear).get(currentMonth); } if (setOfStockStates.contains(stockState)) { setOfStockStates.remove(stockState); } setOfStockStates.add(stockState); historicalStockBalanceStateTable.put(currentYear, currentMonth, setOfStockStates); } return historicalStockBalanceStateTable; }
From source file:org.caleydo.core.data.collection.table.NumericalTable.java
/** * *//*from w w w. jav a 2 s .co m*/ private void performImputation(KNNImputeDescription desc) { Stopwatch w = new Stopwatch().start(); ImmutableList.Builder<Gene> b = ImmutableList.builder(); final int rows = getNrRows(); final int cols = columns.size(); // create data if (desc.getDimension().isRecord()) { for (int i = 0; i < rows; ++i) { float[] data = new float[cols]; int nans = 0; int j = 0; for (AColumn<?, ?> column : columns) { @SuppressWarnings("unchecked") NumericalColumn<?, Float> nColumn = (NumericalColumn<?, Float>) column; Float raw = nColumn.getRaw(i); if (raw == null || raw.isNaN()) nans++; data[j++] = raw == null ? Float.NaN : raw.floatValue(); } b.add(new Gene(i, nans, data)); } } else { int i = 0; for (AColumn<?, ?> column : columns) { float[] data = new float[rows]; int nans = 0; @SuppressWarnings("unchecked") NumericalColumn<?, Float> nColumn = (NumericalColumn<?, Float>) column; for (int j = 0; j < rows; j++) { Float raw = nColumn.getRaw(i); if (raw == null || raw.isNaN()) nans++; data[j++] = raw == null ? Float.NaN : raw.floatValue(); } b.add(new Gene(i++, nans, data)); } } System.out.println("NumericalTable.performImputation() data creation:\t" + w); w.reset().start(); KNNImpute task = new KNNImpute(desc, b.build()); ForkJoinPool pool = new ForkJoinPool(); com.google.common.collect.Table<Integer, Integer, Float> impute = pool.invoke(task); pool.shutdown(); System.out.println("NumericalTable.performImputation() computation:\t" + w); w.reset().start(); // update data final boolean isColumnFirstDimension = desc.getDimension().isDimension(); // in either case iterate over the columns first and update a columns at once for (Map.Entry<Integer, Map<Integer, Float>> entry : (isColumnFirstDimension ? impute.rowMap() : impute.columnMap()).entrySet()) { AColumn<?, ?> aColumn = columns.get(entry.getKey().intValue()); @SuppressWarnings("unchecked") NumericalColumn<?, Float> nColumn = (NumericalColumn<?, Float>) aColumn; // apply updates for (Map.Entry<Integer, Float> entry2 : entry.getValue().entrySet()) { nColumn.setRaw(entry2.getKey(), entry2.getValue()); } } System.out.println("NumericalTable.performImputation() update:\t" + w); }
From source file:io.druid.server.http.TiersResource.java
@GET @Path("/{tierName}") @Produces(MediaType.APPLICATION_JSON)//from w w w .ja v a 2 s. co m public Response getTierDatasources(@PathParam("tierName") String tierName, @QueryParam("simple") String simple) { if (simple != null) { Table<String, Interval, Map<String, Object>> retVal = HashBasedTable.create(); for (DruidServer druidServer : serverInventoryView.getInventory()) { if (druidServer.getTier().equalsIgnoreCase(tierName)) { for (DataSegment dataSegment : druidServer.getSegments().values()) { Map<String, Object> properties = retVal.get(dataSegment.getDataSource(), dataSegment.getInterval()); if (properties == null) { properties = Maps.newHashMap(); retVal.put(dataSegment.getDataSource(), dataSegment.getInterval(), properties); } properties.put("size", MapUtils.getLong(properties, "size", 0L) + dataSegment.getSize()); properties.put("count", MapUtils.getInt(properties, "count", 0) + 1); } } } return Response.ok(retVal.rowMap()).build(); } Set<String> retVal = Sets.newHashSet(); for (DruidServer druidServer : serverInventoryView.getInventory()) { if (druidServer.getTier().equalsIgnoreCase(tierName)) { retVal.addAll(Lists.newArrayList( Iterables.transform(druidServer.getDataSources(), new Function<DruidDataSource, String>() { @Override public String apply(DruidDataSource input) { return input.getName(); } }))); } } return Response.ok(retVal).build(); }
From source file:org.ow2.authzforce.core.pdp.impl.policy.CoreRefPolicyProvider.java
/** * Creates an instance from XACML/JAXB Policy(Set) elements * * @param jaxbPolicies/* w w w.j a v a 2s.c o m*/ * XACML Policy elements * @param jaxbPolicySets * XACML PolicySets * @param maxPolicySetRefDepth * maximum allowed depth of PolicySet reference chain (via PolicySetIdReference): PolicySet1 -> PolicySet2 -> ... * @param combiningAlgRegistry * registry of policy/rule combining algorithms * @param expressionFactory * Expression factory for parsing Expressions used in the policy(set) * @return instance of this module * @throws java.lang.IllegalArgumentException * if both {@code jaxbPolicies} and {@code jaxbPolicySets} are null/empty, or expressionFactory/combiningAlgRegistry undefined; or one of the Policy(Set)s is not valid or conflicts * with another because it has same Policy(Set)Id and Version. */ public static CoreRefPolicyProvider getInstance(final List<PolicyWithNamespaces<Policy>> jaxbPolicies, final List<PolicyWithNamespaces<PolicySet>> jaxbPolicySets, final int maxPolicySetRefDepth, final ExpressionFactory expressionFactory, final CombiningAlgRegistry combiningAlgRegistry) throws IllegalArgumentException { if ((jaxbPolicies == null || jaxbPolicies.isEmpty()) && (jaxbPolicySets == null || jaxbPolicySets.isEmpty())) { throw NO_POLICY_ARG_EXCEPTION; } if (expressionFactory == null) { throw ILLEGAL_EXPRESSION_FACTORY_ARGUMENT_EXCEPTION; } if (combiningAlgRegistry == null) { throw ILLEGAL_COMBINING_ALG_REGISTRY_ARGUMENT_EXCEPTION; } final PolicyMap<StaticTopLevelPolicyElementEvaluator> policyMap; if (jaxbPolicies == null) { policyMap = new PolicyMap<>( Collections.<String, Map<PolicyVersion, StaticTopLevelPolicyElementEvaluator>>emptyMap()); } else { final Table<String, PolicyVersion, StaticTopLevelPolicyElementEvaluator> updatablePolicyTable = HashBasedTable .create(); for (final PolicyWithNamespaces<Policy> jaxbPolicyWithNs : jaxbPolicies) { final Policy jaxbPolicy = jaxbPolicyWithNs.policy; final String policyId = jaxbPolicy.getPolicyId(); final String policyVersion = jaxbPolicy.getVersion(); final StaticTopLevelPolicyElementEvaluator policyEvaluator; try { policyEvaluator = PolicyEvaluators.getInstance(jaxbPolicy, null, jaxbPolicyWithNs.nsPrefixUriMap, expressionFactory, combiningAlgRegistry); } catch (final IllegalArgumentException e) { throw new IllegalArgumentException( "Invalid Policy with PolicyId=" + policyId + ", Version=" + policyVersion, e); } final StaticTopLevelPolicyElementEvaluator previousValue = updatablePolicyTable.put(policyId, new PolicyVersion(policyVersion), policyEvaluator); if (previousValue != null) { throw new IllegalArgumentException("Policy conflict: two <Policy>s with same PolicyId=" + policyId + ", Version=" + policyVersion); } } policyMap = new PolicyMap<>(updatablePolicyTable.rowMap()); } final PolicyMap<PolicyWithNamespaces<PolicySet>> jaxbPolicySetMap; if (jaxbPolicySets == null) { jaxbPolicySetMap = new PolicyMap<>( Collections.<String, Map<PolicyVersion, PolicyWithNamespaces<PolicySet>>>emptyMap()); } else { final Table<String, PolicyVersion, PolicyWithNamespaces<PolicySet>> updatablePolicySetTable = HashBasedTable .create(); for (final PolicyWithNamespaces<PolicySet> jaxbPolicySetWithNs : jaxbPolicySets) { final PolicySet jaxbPolicySet = jaxbPolicySetWithNs.policy; final String policyId = jaxbPolicySet.getPolicySetId(); final String policyVersion = jaxbPolicySet.getVersion(); // check if any version of the same policy exist in the map final PolicyWithNamespaces<PolicySet> previousValue = updatablePolicySetTable.put(policyId, new PolicyVersion(policyVersion), jaxbPolicySetWithNs); if (previousValue != null) { throw new IllegalArgumentException("Policy conflict: two PolicySets with same PolicySetId=" + policyId + ", Version=" + policyVersion); } /* * PolicySets cannot be parsed before we have collected them all, because each PolicySet may refer to others via PolicySetIdReferences */ } jaxbPolicySetMap = new PolicyMap<>(updatablePolicySetTable.rowMap()); } return new CoreRefPolicyProvider(policyMap, jaxbPolicySetMap, maxPolicySetRefDepth, expressionFactory, combiningAlgRegistry); }
From source file:org.caleydo.view.search.internal.RcpSearchView.java
/** * search implementation of the given query * * @param query//from www . jav a2 s.c o m * @param caseSensitive * @param regexSearch */ private void search(String query, boolean caseSensitive, boolean regexSearch) { // delete old results deleteOldSearchResult(true); com.google.common.collect.Table<IDCategory, IDType, Set<?>> result = searchImpl( toPattern(query, caseSensitive, regexSearch)); if (result.isEmpty()) { nothingFound.show(); nothingFound.showHoverText("No Entries were found matching your query"); return; } else { nothingFound.hide(); // order by number of hits List<Map.Entry<IDCategory, Map<IDType, Set<?>>>> entries = new ArrayList<>(result.rowMap().entrySet()); Collections.sort(entries, new Comparator<Map.Entry<IDCategory, Map<IDType, Set<?>>>>() { @Override public int compare(Entry<IDCategory, Map<IDType, Set<?>>> o1, Entry<IDCategory, Map<IDType, Set<?>>> o2) { return o1.getValue().size() - o2.getValue().size(); } }); // create table per category for (Map.Entry<IDCategory, Map<IDType, Set<?>>> entry : entries) { createResultTable(results, entry.getKey(), entry.getValue()); } } // update layouts results.layout(); resultsScrolled.setMinSize(results.computeSize(SWT.DEFAULT, SWT.DEFAULT)); root.layout(); }
From source file:com.google.gerrit.server.notedb.NoteDbUpdateManager.java
/** * Stage updates in the manager's internal list of commands. * * @return map of the state that would get written to the applicable repo(s) for each affected * change.//ww w. jav a 2s . c om * @throws OrmException if a database layer error occurs. * @throws IOException if a storage layer error occurs. */ public Map<Change.Id, StagedResult> stage() throws OrmException, IOException { if (staged != null) { return staged; } try (Timer1.Context timer = metrics.stageUpdateLatency.start(CHANGES)) { staged = new HashMap<>(); if (isEmpty()) { return staged; } initChangeRepo(); if (!draftUpdates.isEmpty() || !toDelete.isEmpty()) { initAllUsersRepo(); } checkExpectedState(); addCommands(); Table<Change.Id, Account.Id, ObjectId> allDraftIds = getDraftIds(); Set<Change.Id> changeIds = new HashSet<>(); for (ReceiveCommand cmd : changeRepo.getCommandsSnapshot()) { Change.Id changeId = Change.Id.fromRef(cmd.getRefName()); if (changeId == null || !cmd.getRefName().equals(RefNames.changeMetaRef(changeId))) { // Not a meta ref update, likely due to a repo update along with the change meta update. continue; } changeIds.add(changeId); Optional<ObjectId> metaId = Optional.of(cmd.getNewId()); staged.put(changeId, StagedResult.create(changeId, NoteDbChangeState.Delta.create(changeId, metaId, allDraftIds.rowMap().remove(changeId)), changeRepo, allUsersRepo)); } for (Map.Entry<Change.Id, Map<Account.Id, ObjectId>> e : allDraftIds.rowMap().entrySet()) { // If a change remains in the table at this point, it means we are // updating its drafts but not the change itself. StagedResult r = StagedResult.create(e.getKey(), NoteDbChangeState.Delta.create(e.getKey(), Optional.empty(), e.getValue()), changeRepo, allUsersRepo); checkState(r.changeCommands().isEmpty(), "should not have change commands when updating only drafts: %s", r); staged.put(r.id(), r); } return staged; } }