Java Code Examples for com.google.common.collect.ImmutableTable#builder()

The following examples show how to use com.google.common.collect.ImmutableTable#builder() . 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: TableUI.java    From Rails with GNU General Public License v2.0 6 votes vote down vote up
public static TableUI from(GridTable gridTable) {

        TableAxis rows = TableAxis.from(gridTable.getRows());
        TableAxis cols = TableAxis.from(gridTable.getCols());

        ImmutableTable.Builder<TableCoordinate,TableCoordinate,TableField> tableFields =
                ImmutableTable.builder();

        for (TableCoordinate row:rows) {
            for (TableCoordinate col:cols) {
                log.debug("Try to add field at {},{} ", row, col);
                GridField gridField = gridTable.getFields().get(row.getGridCoordinate(), col.getGridCoordinate());
                Preconditions.checkState(gridField != null, "No gridField available for row %s, col %s ", row, col);
                TableField tableField = gridField.toTableField(row.getItem(), col.getItem());
                tableFields.put(row, col, tableField);
            }
        }
        TableUI table = new TableUI(rows, cols, tableFields.build());

        return table;
    }
 
Example 2
Source File: TableSerializationTest.java    From jackson-datatypes-collections with Apache License 2.0 6 votes vote down vote up
public void testSimpleKeyImmutableTableSerde() throws IOException
{
    final ImmutableTable.Builder<Integer, String, String> builder = ImmutableTable.builder();
    builder.put(Integer.valueOf(42), "column42", "some value 42");
    builder.put(Integer.valueOf(45), "column45", "some value 45");
    final ImmutableTable<Integer, String, String> simpleTable = builder.build();

    final String simpleJson = MAPPER.writeValueAsString(simpleTable);
    assertEquals("{\"42\":{\"column42\":\"some value 42\"},\"45\":{\"column45\":\"some value 45\"}}", simpleJson);

    // !!! TODO: support deser
    
    /*
    final ImmutableTable<Integer, String, String> reconstitutedTable =
            this.MAPPER.readValue(simpleJson, new TypeReference<ImmutableTable<Integer, String, String>>() {});
    assertEquals(simpleTable, reconstitutedTable);
    */
}
 
Example 3
Source File: TableSerializationTest.java    From jackson-datatypes-collections with Apache License 2.0 6 votes vote down vote up
/**
     * This test illustrates one way to use objects as keys in Tables.
     */
    public void testComplexKeyImmutableTableSerde() throws IOException
    {
        final ImmutableTable.Builder<Integer, ComplexKey, String> ckBuilder = ImmutableTable.builder();
        ckBuilder.put(Integer.valueOf(42), new ComplexKey("field1", "field2"), "some value 42");
        ckBuilder.put(Integer.valueOf(45), new ComplexKey("field1", "field2"), "some value 45");
        final ImmutableTable<Integer, ComplexKey, String> complexKeyTable = ckBuilder.build();

        final TypeReference<ImmutableTable<Integer, ComplexKey, String>> tableType = new TypeReference<ImmutableTable<Integer, ComplexKey, String>>()
        {};

        final String ckJson = this.MAPPER.writerFor(tableType).writeValueAsString(complexKeyTable);
        assertEquals("{\"42\":{\"field1:field2\":\"some value 42\"},\"45\":{\"field1:field2\":\"some value 45\"}}", ckJson);

        // !!! TODO: support deser
/*        
        
        final ImmutableTable<Integer, ComplexKey, String> reconstitutedTable = this.MAPPER.readValue(ckJson, tableType);
        assertEquals(complexKeyTable, reconstitutedTable);
        */
    }
 
Example 4
Source File: ImmutableTableCodec.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Override
public ImmutableTable<R, C, V> deserialize(
    DeserializationContext context, CodedInputStream codedIn)
    throws SerializationException, IOException {
  int length = codedIn.readInt32();
  if (length < 0) {
    throw new SerializationException("Expected non-negative length: " + length);
  }
  ImmutableTable.Builder<R, C, V> builder = ImmutableTable.builder();
  for (int i = 0; i < length; i++) {
    builder.put(
        /*rowKey=*/ context.deserialize(codedIn),
        /*columnKey=*/ context.deserialize(codedIn),
        /*value=*/ context.deserialize(codedIn));
  }
  return builder.build();
}
 
Example 5
Source File: RuntimeEntityResolver.java    From bazel with Apache License 2.0 6 votes vote down vote up
private static ImmutableTable<Integer, ClassMemberKey<?>, Member> getReflectionBasedClassMembers(
    int round, Class<?> classLiteral) {
  ImmutableTable.Builder<Integer, ClassMemberKey<?>, Member> reflectionBasedMembers =
      ImmutableTable.builder();
  ClassName owner = ClassName.create(classLiteral);
  for (Field field : classLiteral.getDeclaredFields()) {
    reflectionBasedMembers.put(
        round,
        FieldKey.create(owner, field.getName(), Type.getDescriptor(field.getType())),
        field);
  }
  for (Constructor<?> constructor : classLiteral.getDeclaredConstructors()) {
    reflectionBasedMembers.put(
        round,
        MethodKey.create(owner, "<init>", Type.getConstructorDescriptor(constructor)),
        constructor);
  }
  for (Method method : classLiteral.getDeclaredMethods()) {
    reflectionBasedMembers.put(
        round,
        MethodKey.create(owner, method.getName(), Type.getMethodDescriptor(method)),
        method);
  }
  return reflectionBasedMembers.build();
}
 
Example 6
Source File: TableConfig.java    From qconfig with MIT License 5 votes vote down vote up
@Override
public Table<String, String, String> parse(String data) throws IOException {
    JsonNode jsonNode = mapper.readTree(data);

    ImmutableTable.Builder<String, String, String> builder = ImmutableTable.builder();
    Iterator<JsonNode> elements = jsonNode.elements();
    while (elements.hasNext()) {
        JsonNode rowNode = elements.next();
        String row = rowNode.get(Constants.ROW).asText();
        Iterator<Map.Entry<String, JsonNode>> fields = rowNode.get(Constants.COLUMNS).fields();
        while (fields.hasNext()) {
            Map.Entry<String, JsonNode> field = fields.next();
            JsonNode valueNode = field.getValue();
            if (valueNode != null && valueNode.asText() != null) {
                String column = field.getKey();
                String value = valueNode.asText();
                if (trimValue) {
                    value = value.trim();
                }
                if (!Strings.isNullOrEmpty(value)) {
                    builder.put(row, column, value);
                }
            }
        }
    }
    return builder.build();
}
 
Example 7
Source File: TableDeserializer.java    From bazel-tools with Apache License 2.0 5 votes vote down vote up
@Override
public ImmutableTable<?, ?, ?> deserialize(final JsonParser jp, final DeserializationContext ctxt)
    throws IOException {
  final ImmutableTable.Builder<Object, Object, Object> tableBuilder = ImmutableTable.builder();

  final JavaType javaType = Objects.requireNonNull(this.javaType);

  final JavaType rowKeyType = javaType.containedTypeOrUnknown(0);
  final JavaType columnKeyType = javaType.containedTypeOrUnknown(1);
  final JavaType valueType = javaType.containedTypeOrUnknown(2);
  final JavaType mapifiedType =
      ctxt.getTypeFactory()
          .constructMapType(
              Map.class,
              rowKeyType,
              ctxt.getTypeFactory().constructMapType(Map.class, columnKeyType, valueType));

  final Map<Object, Map<Object, Object>> rowMap = ctxt.readValue(jp, mapifiedType);

  for (final Map.Entry<Object, Map<Object, Object>> rowEntry : rowMap.entrySet()) {
    final Object rowKey = rowEntry.getKey();
    for (final Map.Entry<Object, Object> cellEntry : rowEntry.getValue().entrySet()) {
      final Object colKey = cellEntry.getKey();
      final Object val = cellEntry.getValue();
      tableBuilder.put(rowKey, colKey, val);
    }
  }
  return tableBuilder.build();
}
 
Example 8
Source File: CodeReferenceMap.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public CodeReferenceMap build() {
  ImmutableTable.Builder<String, String, ImmutableSet<String>> deadMethodsBuilder =
      ImmutableTable.builder();
  for (Table.Cell<String, String, Set<String>> cell : this.deadMethods.cellSet()) {
    deadMethodsBuilder.put(
        cell.getRowKey(),
        cell.getColumnKey(),
        ImmutableSet.copyOf(cell.getValue()));
  }
  return new CodeReferenceMap(
      ImmutableSet.copyOf(deadClasses),
      deadMethodsBuilder.build(),
      ImmutableMultimap.copyOf(deadFields));
}
 
Example 9
Source File: Adapters.java    From activitystreams with Apache License 2.0 5 votes vote down vote up
public Table<?, ?, ?> deserialize(
  JsonElement json, 
  Type typeOfT,
  JsonDeserializationContext context) 
    throws JsonParseException {
  ImmutableTable.Builder<String,String,Object> table = 
    ImmutableTable.builder();
  checkArgument(json.isJsonObject());
  JsonObject obj = json.getAsJsonObject();
  for (Map.Entry<String,JsonElement> rowentry : obj.entrySet()) {
    String row = rowentry.getKey();
    JsonElement cell = rowentry.getValue();
    checkArgument(cell.isJsonObject());
    for (Map.Entry<String,JsonElement> cellentry : cell.getAsJsonObject().entrySet()) {
      String ckey = cellentry.getKey();
      JsonElement val = cellentry.getValue();
      Object desval = null;
      if (val.isJsonArray())
        desval = MultimapAdapter.arraydes(val.getAsJsonArray(),context);
      else if (val.isJsonObject())
        desval = context.deserialize(val, ASObject.class);
      else if (val.isJsonPrimitive())
        desval = primConverter.convert(val.getAsJsonPrimitive());
      if (desval != null)
        table.put(row,ckey,desval);
    }
  }
  return table.build();
}
 
Example 10
Source File: ImmutableTableCodecTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void smoke() throws Exception {
  ImmutableTable.Builder<String, String, Integer> builder = ImmutableTable.builder();
  builder.put("a", "b", 1);
  builder.put("c", "d", -200);
  builder.put("a", "d", 4);
  new SerializationTester(ImmutableTable.of(), builder.build()).runTests();
}
 
Example 11
Source File: TradeReportRunner.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Override
public TradeReport runReport(ReportCalculationResults results, TradeReportTemplate reportTemplate) {
  ImmutableTable.Builder<Integer, Integer, Result<?>> resultTable = ImmutableTable.builder();

  for (int reportColumnIdx = 0; reportColumnIdx < reportTemplate.getColumns().size(); reportColumnIdx++) {
    TradeReportColumn reportColumn = reportTemplate.getColumns().get(reportColumnIdx);
    List<Result<?>> columnResults;

    if (reportColumn.getValue().isPresent()) {
      columnResults = ValuePathEvaluator.evaluate(reportColumn.getValue().get(), results);
    } else {
      columnResults = IntStream.range(0, results.getTargets().size())
          .mapToObj(i -> Result.failure(FailureReason.INVALID, "No value specified in report template"))
          .collect(toImmutableList());
    }
    int rowCount = results.getCalculationResults().getRowCount();

    for (int rowIdx = 0; rowIdx < rowCount; rowIdx++) {
      resultTable.put(rowIdx, reportColumnIdx, columnResults.get(rowIdx));
    }
  }

  return TradeReport.builder()
      .runInstant(Instant.now())
      .valuationDate(results.getValuationDate())
      .columns(reportTemplate.getColumns())
      .data(resultTable.build())
      .build();
}
 
Example 12
Source File: CashFlowReportRunner.java    From Strata with Apache License 2.0 5 votes vote down vote up
private ImmutableTable<Integer, Integer, Object> getData(List<ExplainMap> flatMap, List<ExplainKey<?>> keys) {
  ImmutableTable.Builder<Integer, Integer, Object> builder = ImmutableTable.builder();

  for (int rowIdx = 0; rowIdx < flatMap.size(); rowIdx++) {
    ExplainMap rowMap = flatMap.get(rowIdx);

    for (int colIdx = 0; colIdx < keys.size(); colIdx++) {
      builder.put(rowIdx, colIdx, rowMap.get(keys.get(colIdx)));
    }
  }
  return builder.build();
}
 
Example 13
Source File: ImportForeignIDs.java    From tac-kbp-eal with MIT License 4 votes vote down vote up
public static void importForeignIDs(final File source, final File outputDirectory,
    final LinkingStoreSource linkingStoreSource, final SystemOutputLayout outputLayout)
    throws IOException {
  final ArgumentStore originalArgumentStore =
      AssessmentSpecFormats.openSystemOutputStore(new File(source, "arguments"),
          AssessmentSpecFormats.Format.KBP2015);

  final LinkingStore originalLinkingStore =
      linkingStoreSource.openLinkingStore(new File(source, "linking"));

  final SystemOutputStore newOutput = outputLayout.openOrCreate(outputDirectory);

  // aggregate any changes in response sets ids
  final ImmutableTable.Builder<Symbol, String, String> docIdOldLinkingToNewB =
      ImmutableTable.builder();
  final Set<String> knownResponseIds = Sets.newHashSet();
  for (final Symbol docid : originalArgumentStore.docIDs()) {
    log.info("Converting {}", docid);
    final ImmutableMap.Builder<String, String> originalToSystem = ImmutableMap.builder();
    final ArgumentOutput originalArguments = AssessmentSpecFormats
        .uncachedReadFromArgumentStoreCachingOldIDS(originalArgumentStore, docid,
            originalToSystem);

    final ImmutableMap.Builder<String, String> originalLinkingIDToSystem = ImmutableMap.builder();
    final Optional<ResponseLinking> transformedLinking =
        originalLinkingStore.readTransformingIDs(docid,
            originalArguments.responses(),
            Optional.of(originalToSystem.build()), Optional.of(originalLinkingIDToSystem));
    for (final Map.Entry<String, String> e : originalLinkingIDToSystem.build().entrySet()) {
      docIdOldLinkingToNewB.put(docid, e.getKey(), e.getValue());
    }
    if (transformedLinking.isPresent()) {
      knownResponseIds.addAll(transformedLinking.get().responseSetIds().get().keySet());
      // create system output
      final DocumentSystemOutput2015 newSystemOutput =
          DocumentSystemOutput2015.from(originalArguments, transformedLinking.get());
      newOutput.write(newSystemOutput);
    } else {
      throw new IOException("No linking found for " + docid);
    }
  }
  final File corpusLinkingdir = new File(source, "corpusLinking");
  if (corpusLinkingdir.exists()) {
    final ImmutableTable<Symbol, String, String> oldLinkingIDToNew =
        docIdOldLinkingToNewB.build();
    final CorpusEventLinking corpusEventLinking = new CorpusEventFrameLoader2016()
        .loadCorpusEventFrames(
            Files.asCharSource(new File(corpusLinkingdir, "corpusLinking"), Charsets.UTF_8));
    final CorpusEventLinking.Builder nuLinking = CorpusEventLinking.builder();
    for (final CorpusEventFrame cef : corpusEventLinking.corpusEventFrames()) {
      final CorpusEventFrame.Builder cefb = CorpusEventFrame.builder();
      cefb.id(cef.id());
      final ImmutableSet.Builder<DocEventFrameReference> newDocEventFrameReferences =
          ImmutableSet.builder();
      for (final DocEventFrameReference defr : cef.docEventFrames()) {
        if(!oldLinkingIDToNew.containsRow(defr.docID())) {
          newDocEventFrameReferences.add(defr);
          checkState(knownResponseIds.contains(defr.eventFrameID()));
        } else {
          final String nuId =
              checkNotNull(oldLinkingIDToNew.get(defr.docID(), defr.eventFrameID()));
          checkState(knownResponseIds.contains(nuId));
          newDocEventFrameReferences.add(DocEventFrameReference.of(defr.docID(), nuId));
        }
      }
      cefb.addAllDocEventFrames(newDocEventFrameReferences.build());
      nuLinking.addCorpusEventFrames(cefb.build());
    }
    ((CrossDocSystemOutputStore) newOutput).writeCorpusEventFrames(nuLinking.build());
  }

  originalArgumentStore.close();
  originalLinkingStore.close();
  newOutput.close();
}