Java Code Examples for com.google.common.collect.HashBasedTable

The following examples show how to use com.google.common.collect.HashBasedTable. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
@Override
public FetchPartitionMessageRequest decode(JoyQueueHeader header, ByteBuf buffer) throws Exception {
    Table<String, Short, FetchPartitionMessageData> partitions = HashBasedTable.create();
    int topicSize = buffer.readShort();
    for (int i = 0; i < topicSize; i++) {
        String topic = Serializer.readString(buffer, Serializer.SHORT_SIZE);
        int partitionSize = buffer.readShort();
        for (int j = 0; j < partitionSize; j++) {
            short partition = buffer.readShort();
            int count = buffer.readInt();
            long index = buffer.readLong();

            partitions.put(topic, partition, new FetchPartitionMessageData(count, index));
        }
    }

    FetchPartitionMessageRequest fetchPartitionMessageRequest = new FetchPartitionMessageRequest();
    fetchPartitionMessageRequest.setPartitions(partitions);
    fetchPartitionMessageRequest.setApp(Serializer.readString(buffer, Serializer.SHORT_SIZE));
    return fetchPartitionMessageRequest;
}
 
Example 2
Source Project: joyqueue   Source File: CommitAckRequestHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Command handle(Transport transport, Command command) {
    CommitAckRequest commitAckRequest = (CommitAckRequest) command.getPayload();
    Connection connection = SessionHelper.getConnection(transport);

    if (connection == null || !connection.isAuthorized(commitAckRequest.getApp())) {
        logger.warn("connection is not exists, transport: {}, app: {}", transport, commitAckRequest.getApp());
        return BooleanAck.build(JoyQueueCode.FW_CONNECTION_NOT_EXISTS.getCode());
    }

    Table<String, Short, JoyQueueCode> result = HashBasedTable.create();

    for (Map.Entry<String, Map<Short, List<CommitAckData>>> entry : commitAckRequest.getData().rowMap().entrySet()) {
        String topic = entry.getKey();
        for (Map.Entry<Short, List<CommitAckData>> partitionEntry : entry.getValue().entrySet()) {
            JoyQueueCode ackCode = commitAck(connection, topic, commitAckRequest.getApp(), partitionEntry.getKey(), partitionEntry.getValue());
            result.put(topic, partitionEntry.getKey(), ackCode);
        }
    }

    CommitAckResponse commitAckResponse = new CommitAckResponse();
    commitAckResponse.setResult(result);
    return new Command(commitAckResponse);
}
 
Example 3
Source Project: joyqueue   Source File: FetchIndexRequestHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Command handle(Transport transport, Command command) {
    FetchIndexRequest fetchIndexRequest = (FetchIndexRequest) command.getPayload();
    Connection connection = SessionHelper.getConnection(transport);

    if (connection == null || !connection.isAuthorized(fetchIndexRequest.getApp())) {
        logger.warn("connection is not exists, transport: {}, app: {}", transport, fetchIndexRequest.getApp());
        return BooleanAck.build(JoyQueueCode.FW_CONNECTION_NOT_EXISTS.getCode());
    }

    Table<String, Short, FetchIndexData> result = HashBasedTable.create();

    for (Map.Entry<String, List<Short>> entry : fetchIndexRequest.getPartitions().entrySet()) {
        String topic = entry.getKey();
        Consumer consumer = new Consumer(connection.getId(), topic, fetchIndexRequest.getApp(), Consumer.ConsumeType.JOYQUEUE);
        for (Short partition : entry.getValue()) {
            FetchIndexData fetchIndexData = fetchIndex(connection, consumer, partition);
            result.put(topic, partition, fetchIndexData);
        }
    }

    FetchIndexResponse fetchIndexResponse = new FetchIndexResponse();
    fetchIndexResponse.setData(result);
    return new Command(fetchIndexResponse);
}
 
Example 4
Source Project: triplea   Source File: DiceRoll.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Sorts the specified collection of units in ascending order of their attack or defense strength.
 *
 * @param defending {@code true} if the units should be sorted by their defense strength;
 *     otherwise the units will be sorted by their attack strength.
 */
public static void sortByStrength(final List<Unit> units, final boolean defending) {
  // Pre-compute unit strength information to speed up the sort.
  final Table<UnitType, GamePlayer, Integer> strengthTable = HashBasedTable.create();
  for (final Unit unit : units) {
    final UnitType type = unit.getType();
    final GamePlayer owner = unit.getOwner();
    if (!strengthTable.contains(type, owner)) {
      if (defending) {
        strengthTable.put(type, owner, UnitAttachment.get(type).getDefense(owner));
      } else {
        strengthTable.put(type, owner, UnitAttachment.get(type).getAttack(owner));
      }
    }
  }
  final Comparator<Unit> comp =
      (u1, u2) -> {
        final int v1 = strengthTable.get(u1.getType(), u1.getOwner());
        final int v2 = strengthTable.get(u2.getType(), u2.getOwner());
        return Integer.compare(v1, v2);
      };
  units.sort(comp);
}
 
Example 5
Source Project: joyqueue   Source File: DefaultMessageFetcher.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void fetchPartitionAsync(BrokerNode brokerNode, final String topic, final String app, final short partition,
                                final long index, int count, long timeout, final PartitionFetchListener listener) {
    Table<String, Short, Long> partitionTable = HashBasedTable.create();
    partitionTable.put(topic, partition, index);
    batchFetchPartitionsAsync(brokerNode, partitionTable, app, count, timeout, new BatchPartitionFetchListener() {
        @Override
        public void onMessage(Table<String, Short, FetchMessageData> fetchMessageTable) {
            FetchMessageData fetchMessageData = fetchMessageTable.get(topic, partition);
            listener.onMessage(fetchMessageData);
        }

        @Override
        public void onException(Throwable cause) {
            listener.onException(cause);
        }
    });
}
 
Example 6
Source Project: joyqueue   Source File: CommitAckResponseCodec.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CommitAckResponse decode(JoyQueueHeader header, ByteBuf buffer) throws Exception {
    short size = buffer.readShort();
    Table<String, Short, JoyQueueCode> result = HashBasedTable.create();

    for (int i = 0; i < size; i++) {
        String topic = Serializer.readString(buffer, Serializer.SHORT_SIZE);
        short partitionSize = buffer.readShort();
        for (int j = 0; j < partitionSize; j++) {
            short partition = buffer.readShort();
            result.put(topic, partition, JoyQueueCode.valueOf(buffer.readInt()));
        }
    }

    CommitAckResponse commitAckResponse = new CommitAckResponse();
    commitAckResponse.setResult(result);
    return commitAckResponse;
}
 
Example 7
@Override
public FetchPartitionMessageRequest decode(JoyQueueHeader header, ByteBuf buffer) throws Exception {
    Table<String, Short, FetchPartitionMessageData> partitions = HashBasedTable.create();
    int topicSize = buffer.readShort();
    for (int i = 0; i < topicSize; i++) {
        String topic = Serializer.readString(buffer, Serializer.SHORT_SIZE);
        int partitionSize = buffer.readShort();
        for (int j = 0; j < partitionSize; j++) {
            short partition = buffer.readShort();
            int count = buffer.readInt();
            long index = buffer.readLong();

            partitions.put(topic, partition, new FetchPartitionMessageData(count, index));
        }
    }

    FetchPartitionMessageRequest fetchPartitionMessageRequest = new FetchPartitionMessageRequest();
    fetchPartitionMessageRequest.setPartitions(partitions);
    fetchPartitionMessageRequest.setApp(Serializer.readString(buffer, Serializer.SHORT_SIZE));
    return fetchPartitionMessageRequest;
}
 
Example 8
@Override
public FetchPartitionMessageResponse decode(JoyQueueHeader header, ByteBuf buffer) throws Exception {
    Table<String, Short, FetchPartitionMessageAckData> data = HashBasedTable.create();
    short topicSize = buffer.readShort();
    for (int i = 0; i < topicSize; i++) {
        String topic = Serializer.readString(buffer, Serializer.SHORT_SIZE);
        int partitionSize = buffer.readShort();
        for (int j = 0; j < partitionSize; j++) {
            short partition = buffer.readShort();
            short messageSize = buffer.readShort();
            List<BrokerMessage> messages = Lists.newArrayListWithCapacity(messageSize);
            for (int k = 0; k < messageSize; k++) {
                messages.add(Serializer.readBrokerMessage(buffer));
            }
            JoyQueueCode code = JoyQueueCode.valueOf(buffer.readInt());
            FetchPartitionMessageAckData fetchPartitionMessageAckData = new FetchPartitionMessageAckData(messages, code);
            data.put(topic, partition, fetchPartitionMessageAckData);
        }
    }

    FetchPartitionMessageResponse fetchPartitionMessageResponse = new FetchPartitionMessageResponse();
    fetchPartitionMessageResponse.setData(data);
    return fetchPartitionMessageResponse;
}
 
Example 9
Source Project: tutorials   Source File: GuavaTableUnitTest.java    License: MIT License 6 votes vote down vote up
@Test
public void givenTable_whenContains_returnsSuccessfully() {
    final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
    universityCourseSeatTable.put("Mumbai", "Chemical", 120);
    universityCourseSeatTable.put("Mumbai", "IT", 60);
    universityCourseSeatTable.put("Harvard", "Electrical", 60);
    universityCourseSeatTable.put("Harvard", "IT", 120);

    final boolean entryIsPresent = universityCourseSeatTable.contains("Mumbai", "IT");
    final boolean entryIsAbsent = universityCourseSeatTable.contains("Oxford", "IT");
    final boolean courseIsPresent = universityCourseSeatTable.containsColumn("IT");
    final boolean universityIsPresent = universityCourseSeatTable.containsRow("Mumbai");
    final boolean seatCountIsPresent = universityCourseSeatTable.containsValue(60);

    assertThat(entryIsPresent).isEqualTo(true);
    assertThat(entryIsAbsent).isEqualTo(false);
    assertThat(courseIsPresent).isEqualTo(true);
    assertThat(universityIsPresent).isEqualTo(true);
    assertThat(seatCountIsPresent).isEqualTo(true);
}
 
Example 10
Source Project: qmq   Source File: CheckpointManager.java    License: Apache License 2.0 6 votes vote down vote up
private ActionCheckpoint duplicateActionCheckpoint() {
    actionCheckpointGuard.lock();
    try {
        final Table<String, String, ConsumerGroupProgress> progresses = HashBasedTable.create();
        for (final ConsumerGroupProgress progress : actionCheckpoint.getProgresses().values()) {
            final Map<String, ConsumerProgress> consumers = progress.getConsumers();
            if (consumers == null) {
                continue;
            }

            final Map<String, ConsumerProgress> consumersCopy = new HashMap<>();
            for (final ConsumerProgress consumer : consumers.values()) {
                consumersCopy.put(consumer.getConsumerId(), new ConsumerProgress(consumer));
            }
            final String subject = progress.getSubject();
            final String group = progress.getGroup();
            progresses.put(subject, group, new ConsumerGroupProgress(subject, group, progress.isBroadcast(), progress.getPull(), consumersCopy));
        }
        final long offset = actionCheckpoint.getOffset();
        return new ActionCheckpoint(offset, progresses);
    } finally {
        actionCheckpointGuard.unlock();
    }
}
 
Example 11
Source Project: EasySRL   Source File: ChartCell.java    License: Apache License 2.0 6 votes vote down vote up
public ChartCellNbestFactory(final int nbest, final double nbestBeam, final int maxSentenceLength,
		final Collection<Category> categories) {
	super();
	this.nbest = nbest;
	this.nbestBeam = nbestBeam;
	final Random randomGenerator = new Random();

	// Build a hash for every possible dependency
	categoryToArgumentToHeadToModifierToHash = HashBasedTable.create();
	for (final Category c : categories) {
		for (int i = 1; i <= c.getNumberOfArguments(); i++) {
			final int[][] array = new int[maxSentenceLength][maxSentenceLength];
			categoryToArgumentToHeadToModifierToHash.put(c, i, array);
			for (int head = 0; head < maxSentenceLength; head++) {
				for (int child = 0; child < maxSentenceLength; child++) {
					array[head][child] = randomGenerator.nextInt();
				}
			}
		}
	}
}
 
Example 12
Source Project: SPDS   Source File: AbstractBoomerangResults.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public Table<Statement, Val, W> asStatementValWeightTable(ForwardQuery query) {
    final Table<Statement, Val, W> results = HashBasedTable.create();
    WeightedPAutomaton<Statement, INode<Val>, W> callAut = queryToSolvers.getOrCreate(query).getCallAutomaton();
    for (Entry<Transition<Statement, INode<Val>>, W> e : callAut.getTransitionsToFinalWeights().entrySet()) {
        Transition<Statement, INode<Val>> t = e.getKey();
        W w = e.getValue();
        if (t.getLabel().equals(Statement.epsilon()))
            continue;
        if (t.getStart().fact().value() instanceof Local
                && !t.getLabel().getMethod().equals(t.getStart().fact().m()))
            continue;
        if (t.getLabel().getUnit().isPresent())
            results.put(t.getLabel(), t.getStart().fact(), w);
    }
    return results;
}
 
Example 13
Source Project: OpenModsLib   Source File: ConfigurableFeatureManager.java    License: MIT License 6 votes vote down vote up
public Table<String, String, Property> loadFromConfiguration(Configuration config) {
	final Table<String, String, Property> properties = HashBasedTable.create();
	for (Table.Cell<String, String, FeatureEntry> cell : features.cellSet()) {
		final FeatureEntry entry = cell.getValue();
		if (!entry.isConfigurable) continue;

		final String categoryName = cell.getRowKey();
		final String featureName = cell.getColumnKey();
		final Property prop = config.get(categoryName, featureName, entry.isEnabled);
		properties.put(categoryName, featureName, prop);
		if (!prop.wasRead()) continue;

		if (!prop.isBooleanValue()) prop.set(entry.isEnabled);
		else entry.isEnabled = prop.getBoolean(entry.isEnabled);
	}

	return ImmutableTable.copyOf(properties);
}
 
Example 14
Source Project: Rails   Source File: MapManager.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Calculate the distances between a given tokenable city hex
 * and all other tokenable city hexes.
 * <p> Distances are cached.
 * @param initHex Start hex
 * @return Sorted integer list containing all occurring distances only once.
 */
public SortedSet<Integer> getCityDistances (MapHex initHex) {
    
    if (hexDistances == null) {
        hexDistances = HashBasedTable.create();
    }

    if (!hexDistances.containsRow(initHex)) {
        calculateHexDistances(initHex, initHex, 0);
    }
    
    ImmutableSortedSet.Builder<Integer> distances = 
            ImmutableSortedSet.naturalOrder();
    
    for (Entry<MapHex, Integer> otherHex:hexDistances.row(initHex).entrySet()) {
        if (otherHex.getKey().getCurrentTile().hasStations()) {
            distances.add(otherHex.getValue());
        }
    }
    return distances.build();
}
 
Example 15
Source Project: javaide   Source File: DeviceManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns the known {@link Device} list.
 *
 * @param deviceFilter A combination of the {@link DeviceFilter} constants
 *                     or the constant {@link DeviceManager#ALL_DEVICES}.
 * @return A copy of the list of {@link Device}s. Can be empty but not null.
 */
@NonNull
public Collection<Device> getDevices(@NonNull EnumSet<DeviceFilter> deviceFilter) {
    initDevicesLists();
    Table<String, String, Device> devices = HashBasedTable.create();
    if (mUserDevices != null && (deviceFilter.contains(DeviceFilter.USER))) {
        devices.putAll(mUserDevices);
    }
    if (mDefaultDevices != null && (deviceFilter.contains(DeviceFilter.DEFAULT))) {
        devices.putAll(mDefaultDevices);
    }
    if (mVendorDevices != null && (deviceFilter.contains(DeviceFilter.VENDOR))) {
        devices.putAll(mVendorDevices);
    }
    if (mSysImgDevices != null && (deviceFilter.contains(DeviceFilter.SYSTEM_IMAGES))) {
        devices.putAll(mSysImgDevices);
    }
    return Collections.unmodifiableCollection(devices.values());
}
 
Example 16
Source Project: bazel   Source File: ConfigCommand.java    License: Apache License 2.0 6 votes vote down vote up
private static Table<Class<? extends FragmentOptions>, String, Pair<Object, Object>>
    diffConfigurations(BuildConfiguration config1, BuildConfiguration config2) {
  Table<Class<? extends FragmentOptions>, String, Pair<Object, Object>> diffs =
      HashBasedTable.create();

  for (Class<? extends FragmentOptions> fragment :
      Sets.union(
          config1.getOptions().getFragmentClasses(), config2.getOptions().getFragmentClasses())) {
    FragmentOptions options1 = config1.getOptions().get(fragment);
    FragmentOptions options2 = config2.getOptions().get(fragment);
    diffs.row(fragment).putAll(diffOptions(fragment, options1, options2));
  }

  diffs.row(UserDefinedFragment.class).putAll(diffStarlarkOptions(config1, config2));
  return diffs;
}
 
Example 17
Source Project: dremio-oss   Source File: ImmutableCollectionSerializers.java    License: Apache License 2.0 6 votes vote down vote up
public static void register(final Kryo kryo) {
  // register list
  final ImmutableListSerializer serializer = new ImmutableListSerializer();
  kryo.register(ImmutableList.class, serializer);
  kryo.register(ImmutableList.of().getClass(), serializer);
  kryo.register(ImmutableList.of(Integer.valueOf(1)).getClass(), serializer);
  kryo.register(ImmutableList.of(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)).subList(1, 2).getClass(), serializer);
  kryo.register(ImmutableList.of().reverse().getClass(), serializer);
  kryo.register(Lists.charactersOf("dremio").getClass(), serializer);

  final HashBasedTable baseTable = HashBasedTable.create();
  baseTable.put(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3));
  baseTable.put(Integer.valueOf(4), Integer.valueOf(5), Integer.valueOf(6));
  ImmutableTable table = ImmutableTable.copyOf(baseTable);
  kryo.register(table.values().getClass(), serializer);
}
 
Example 18
Source Project: synthea   Source File: Demographics.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get a Table of (State, CityId, Demographics), with the given restrictions on state and city.
 * 
 * @param state
 *          The state that is desired. Other states will be excluded from the results.
 * @return Table of (State, CityId, Demographics)
 * @throws IOException
 *           if any exception occurs in reading the demographics file
 */
public static Table<String, String, Demographics> load(String state) 
    throws IOException {
  String filename = Config.get("generate.demographics.default_file");
  String csv = Utilities.readResource(filename);
  
  List<? extends Map<String,String>> demographicsCsv = SimpleCSV.parse(csv);
  
  Table<String, String, Demographics> table = HashBasedTable.create();
  
  for (Map<String,String> demographicsLine : demographicsCsv) {
    String currCityId = demographicsLine.get("ID");
    String currState = demographicsLine.get("STNAME");
    
    // for now, only allow one state at a time
    if (state != null && state.equalsIgnoreCase(currState)) {
      Demographics parsed = csvLineToDemographics(demographicsLine);
      
      table.put(currState, currCityId, parsed);
    }
  }
  
  return table;
}
 
Example 19
Source Project: synthea   Source File: FhirR4.java    License: Apache License 2.0 6 votes vote down vote up
private static Table<String, String, String> loadMapping(String filename) {
  Table<String, String, String> mappingTable = HashBasedTable.create();

  List<LinkedHashMap<String, String>> csvData;
  try {
    csvData = SimpleCSV.parse(Utilities.readResource(filename));
  } catch (IOException e) {
    e.printStackTrace();
    return null;
  }

  for (LinkedHashMap<String, String> line : csvData) {
    String system = line.get("SYSTEM");
    String code = line.get("CODE");
    String url = line.get("URL");

    mappingTable.put(system, code, url);
  }

  return mappingTable;
}
 
Example 20
Source Project: cloudbreak   Source File: SaltStates.java    License: Apache License 2.0 6 votes vote down vote up
public static Map<String, Map<String, String>> getPackageVersions(SaltConnector sc, Map<String, Optional<String>> packages) {
    if (packages.keySet().size() == 1) {
        Entry<String, Optional<String>> next = packages.entrySet().iterator().next();
        return getSinglePackageVersion(sc, next.getKey(), next.getValue());
    } else if (packages.keySet().size() > 1) {
        // Table<host, packageName, version>
        Table<String, String, String> packageTable = HashBasedTable.create();
        packages.entrySet().forEach(singlePackage -> {
            Map<String, Map<String, String>> singlePackageVersionByHost = getSinglePackageVersion(sc, singlePackage.getKey(), singlePackage.getValue());
            singlePackageVersionByHost.entrySet()
                    .stream()
                    .forEach(singlePackageVersionByHostEntry -> singlePackageVersionByHostEntry.getValue().entrySet()
                            .stream()
                            .forEach(singlePackageVersion -> packageTable.put(singlePackageVersionByHostEntry.getKey(),
                                    singlePackageVersion.getKey(), singlePackageVersion.getValue())));
        });
        return packageTable.rowMap();
    } else {
        return Collections.emptyMap();
    }
}
 
Example 21
Source Project: bioasq   Source File: ClassifierPredictor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(UimaContext context) throws ResourceInitializationException {
  super.initialize(context);
  String candidateProviderName = UimaContextHelper
          .getConfigParameterStringValue(context, "candidate-provider");
  candidateProvider = ProviderCache.getProvider(candidateProviderName, CandidateProvider.class);
  String scorerNames = UimaContextHelper.getConfigParameterStringValue(context, "scorers");
  scorers = ProviderCache.getProviders(scorerNames, Scorer.class).stream()
          .map(scorer -> (Scorer<? super T>) scorer).collect(toList());
  String classifierName = UimaContextHelper.getConfigParameterStringValue(context, "classifier");
  classifier = ProviderCache.getProvider(classifierName, ClassifierProvider.class);
  if ((featureFilename = UimaContextHelper.getConfigParameterStringValue(context, "feature-file",
          null)) != null) {
    feat2value = HashBasedTable.create();
  }
}
 
Example 22
Source Project: bioasq   Source File: CVPredictLoader.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(UimaContext context) throws ResourceInitializationException {
  super.initialize(context);
  String candidateProviderName = UimaContextHelper
          .getConfigParameterStringValue(context, "candidate-provider");
  candidateProvider = ProviderCache.getProvider(candidateProviderName, CandidateProvider.class);
  // load cv
  String cvPredictFile = UimaContextHelper.getConfigParameterStringValue(context,
          "cv-predict-file");
  List<String> lines;
  try {
    lines = Resources.readLines(getClass().getResource(cvPredictFile), Charsets.UTF_8);
  } catch (IOException e) {
    throw new ResourceInitializationException(e);
  }
  qid2uri2score = HashBasedTable.create();
  lines.stream().map(line -> line.split("\t"))
          .forEach(segs -> qid2uri2score.put(segs[0], segs[1], Double.parseDouble(segs[2])));
}
 
Example 23
Source Project: blueflood   Source File: DAbstractMetricIO.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Fetch values for a list of {@link com.rackspacecloud.blueflood.types.Locator}
 * from the specified column family and range.
 *
 * This is a base behavior for most rollup types. IO subclasses can override
 * this behavior as they see fit.
 *
 * @param locators
 * @param columnFamily
 * @param range
 * @return
 */
protected <T extends Object> Table<Locator, Long, T> getValuesForLocators( final List<Locator> locators,
                                                                           String columnFamily,
                                                                           Range range ) {

    Table<Locator, Long, T> locatorTimestampRollup = HashBasedTable.create();

    Map<Locator, List<ResultSetFuture>> resultSetFuturesMap = selectForLocatorListAndRange(columnFamily, locators, range);

    for (Map.Entry<Locator, List<ResultSetFuture>> entry : resultSetFuturesMap.entrySet() ) {
        Locator locator = entry.getKey();
        List<ResultSetFuture> futures = entry.getValue();

        Table<Locator, Long, T> result = toLocatorTimestampValue(futures, locator,
                                                columnFamily,
                                                range);
        locatorTimestampRollup.putAll(result);
    }
    return locatorTimestampRollup;
}
 
Example 24
Source Project: factions-top   Source File: ChunkLoader.java    License: MIT License 6 votes vote down vote up
private Table<Integer, WorthType, Double> loadChunkWorth() throws SQLException {
    Table<Integer, WorthType, Double> target = HashBasedTable.create();
    ResultSet resultSet = selectChunkWorth.executeQuery();

    while (resultSet.next()) {
        int id = resultSet.getInt("id");
        int chunkId = resultSet.getInt("chunk_id");
        int worthId = resultSet.getInt("worth_id");
        double worth = resultSet.getDouble("worth");

        identityCache.setChunkWorthId(chunkId, worthId, id);
        identityCache.getWorthType(worthId).ifPresent(worthType ->
                target.put(chunkId, worthType, worth));
    }

    resultSet.close();
    return target;
}
 
Example 25
Source Project: twill   Source File: RunningContainers.java    License: Apache License 2.0 6 votes vote down vote up
RunningContainers(TwillRuntimeSpecification twillRuntimeSpec, String appId, TwillRunResources appMasterResources,
                  ZKClient zookeeperClient, Location applicationLocation,
                  Map<String, RuntimeSpecification> runnables,
                  EventHandler eventHandler) {
  containers = HashBasedTable.create();
  runnableInstances = Maps.newHashMap();
  completedContainerCount = Maps.newHashMap();
  startSequence = Lists.newLinkedList();
  containerLock = new ReentrantLock();
  containerChange = containerLock.newCondition();
  resourceReport = new DefaultResourceReport(appId, appMasterResources);
  zkClient = zookeeperClient;
  containerStats = HashMultimap.create();
  this.applicationLocation = applicationLocation;
  this.runnableNames = runnables.keySet();
  this.logLevels = new TreeMap<>();
  this.maxRetries = Maps.newHashMap(twillRuntimeSpec.getMaxRetries());
  this.numRetries = Maps.newHashMap();
  this.eventHandler = eventHandler;
}
 
Example 26
Source Project: twill   Source File: YarnTwillRunnerService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates an instance.
 *
 * @param config Configuration of the yarn cluster
 * @param zkConnect ZooKeeper connection string
 * @param locationFactory Factory to create {@link Location} instances that are readable and writable by this service
 */
public YarnTwillRunnerService(YarnConfiguration config, String zkConnect, LocationFactory locationFactory) {
  this.yarnConfig = config;
  this.locationFactory = locationFactory;
  this.zkClientService = getZKClientService(zkConnect);
  this.controllers = HashBasedTable.create();
  this.serviceDelegate = new AbstractIdleService() {
    @Override
    protected void startUp() throws Exception {
      YarnTwillRunnerService.this.startUp();
    }

    @Override
    protected void shutDown() throws Exception {
      YarnTwillRunnerService.this.shutDown();
    }
  };
}
 
Example 27
Source Project: hop   Source File: ExtensionPointMap.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Reinitialize the extension point plugins map
 */
public void reInitialize() {
  lock.writeLock().lock();
  try {
    extensionPointPluginMap = HashBasedTable.create();
    final PluginRegistry registry = PluginRegistry.getInstance();
    List<IPlugin> extensionPointPlugins = registry.getPlugins( ExtensionPointPluginType.class );
    for ( IPlugin extensionPointPlugin : extensionPointPlugins ) {
      addExtensionPoint( extensionPointPlugin );
    }
  } finally {
    lock.writeLock().unlock();
  }
}
 
Example 28
Source Project: qconfig   Source File: FileDescriptionServiceImpl.java    License: MIT License 5 votes vote down vote up
@Override
public Table<String, String, String> getDescriptions(Multimap<String, String> groupDataIdMappings) {
    Table<String, String, String> table = HashBasedTable.create();
    for (Map.Entry<String, String> groupDataId : groupDataIdMappings.entries()) {
        table.put(groupDataId.getKey(), groupDataId.getValue(), "");
    }
    for (Map.Entry<String, Collection<String>> groupDataIdMapping : groupDataIdMappings.asMap().entrySet()) {
        Map<String, String> dataIdDescriptions = fileDescriptionDao.selectDescriptions(groupDataIdMapping.getKey(), groupDataIdMapping.getValue());
        for (Map.Entry<String, String> dataIdDesc : dataIdDescriptions.entrySet()) {
            table.put(groupDataIdMapping.getKey(), dataIdDesc.getKey(), dataIdDesc.getValue());
        }
    }
    return table;
}
 
Example 29
Source Project: joyqueue   Source File: BrokerMessageConverter.java    License: Apache License 2.0 5 votes vote down vote up
public static Table<String, Short, FetchMessageData> convert(String app, Table<String, Short, FetchPartitionMessageAckData> topicMessageTable) {
    Table<String, Short, FetchMessageData> result = HashBasedTable.create();
    if (topicMessageTable == null || topicMessageTable.isEmpty()) {
        return result;
    }
    for (Map.Entry<String, Map<Short, FetchPartitionMessageAckData>> topicEntry : topicMessageTable.rowMap().entrySet()) {
        String topic = topicEntry.getKey();
        Map<Short, FetchPartitionMessageAckData> partitionMap = topicEntry.getValue();
        for (Map.Entry<Short, FetchPartitionMessageAckData> partitionEntry : partitionMap.entrySet()) {
            result.put(topic, partitionEntry.getKey(),
                    new FetchMessageData(convert(topic, app, partitionEntry.getValue().getMessages()), partitionEntry.getValue().getCode()));
        }
    }
    return result;
}
 
Example 30
Source Project: CardinalPGM   Source File: FlatFile.java    License: MIT License 5 votes vote down vote up
@Override
public void save() {
    for (String key : tables.keySet()) {
        File saveFile = new File(dir, key + ".json");
        try {
            JsonWriter writer = new JsonWriter(new FileWriter(saveFile));
            gson.toJson(tables.get(key), HashBasedTable.class, writer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}