Example #1
0
 private ImmutableList<ColumnIdent> getPrimaryKey() {
   Map<String, Object> metaMap = getNested(defaultMappingMap, "_meta");
   if (metaMap != null) {
     ImmutableList.Builder<ColumnIdent> builder = ImmutableList.builder();
     Object pKeys = metaMap.get("primary_keys");
     if (pKeys != null) {
       if (pKeys instanceof String) {
         builder.add(ColumnIdent.fromPath((String) pKeys));
         return builder.build();
       } else if (pKeys instanceof Collection) {
         Collection keys = (Collection) pKeys;
         if (!keys.isEmpty()) {
           for (Object pkey : keys) {
             builder.add(ColumnIdent.fromPath(pkey.toString()));
           }
           return builder.build();
         }
       }
     }
   }
   if (getCustomRoutingCol() == null && partitionedByList.isEmpty()) {
     hasAutoGeneratedPrimaryKey = true;
     return ImmutableList.of(ID_IDENT);
   }
   return ImmutableList.of();
 }
Example #2
0
 private ColumnIdent getRoutingCol() {
   ColumnIdent col = getCustomRoutingCol();
   if (col != null) {
     return col;
   }
   if (primaryKey.size() == 1) {
     return primaryKey.get(0);
   }
   return ID_IDENT;
 }
Example #3
0
 final Set<UUID> getPlayersOnServer(@NonNull String server) {
   checkArgument(getProxy().getServers().containsKey(server), "server does not exist");
   Collection<String> asStrings =
       (Collection<String>)
           getServerPlayersScript.eval(
               ImmutableList.<String>of(), ImmutableList.<String>of(server));
   ImmutableSet.Builder<UUID> builder = ImmutableSet.builder();
   for (String s : asStrings) {
     builder.add(UUID.fromString(s));
   }
   return builder.build();
 }
 private static ImmutableSortedSet copyOfInternal(Comparator comparator1, Iterable iterable) {
   if (SortedIterables.hasSameComparator(comparator1, iterable)
       && (iterable instanceof ImmutableSortedSet)) {
     ImmutableSortedSet immutablesortedset = (ImmutableSortedSet) iterable;
     if (!immutablesortedset.isPartialView()) return immutablesortedset;
   }
   ImmutableList immutablelist =
       ImmutableList.copyOf(SortedIterables.sortedUnique(comparator1, iterable));
   Object obj;
   if (immutablelist.isEmpty()) obj = emptySet(comparator1);
   else obj = new RegularImmutableSortedSet(immutablelist, comparator1);
   return ((ImmutableSortedSet) (obj));
 }
Example #5
0
 private ImmutableList<ColumnIdent> getPartitionedBy() {
   ImmutableList.Builder<ColumnIdent> builder = ImmutableList.builder();
   for (List<String> partitionedByInfo : partitionedByList) {
     builder.add(ColumnIdent.fromPath(partitionedByInfo.get(0)));
   }
   return builder.build();
 }
Example #6
0
 private List<String> getCurrentServerIds(boolean nag, boolean lagged) {
   try (Jedis jedis = pool.getResource()) {
     long time = getRedisTime(jedis.time());
     int nagTime = 0;
     if (nag) {
       nagTime = nagAboutServers.decrementAndGet();
       if (nagTime <= 0) {
         nagAboutServers.set(10);
       }
     }
     ImmutableList.Builder<String> servers = ImmutableList.builder();
     Map<String, String> heartbeats = jedis.hgetAll("heartbeats");
     for (Map.Entry<String, String> entry : heartbeats.entrySet()) {
       try {
         long stamp = Long.parseLong(entry.getValue());
         if (lagged ? time >= stamp + 30 : time <= stamp + 30) servers.add(entry.getKey());
         else if (nag && nagTime <= 0) {
           getLogger()
               .severe(
                   entry.getKey()
                       + " is "
                       + (time - stamp)
                       + " seconds behind! (Time not synchronized or server down?)");
         }
       } catch (NumberFormatException ignored) {
       }
     }
     return servers.build();
   } catch (JedisConnectionException e) {
     getLogger().log(Level.SEVERE, "Unable to fetch server IDs", e);
     return Collections.singletonList(configuration.getServerId());
   }
 }
Example #7
0
  /**
   * Returns true if the schema of this and <code>other</code> is the same, this includes the table
   * name, as this is reflected in the ReferenceIdents of the columns.
   */
  public boolean schemaEquals(DocIndexMetaData other) {
    if (this == other) return true;
    if (other == null) return false;

    // TODO: when analyzers are exposed in the info, equality has to be checked on them
    // see: TransportSQLActionTest.testSelectTableAliasSchemaExceptionColumnDefinition
    if (columns != null ? !columns.equals(other.columns) : other.columns != null) return false;
    if (primaryKey != null ? !primaryKey.equals(other.primaryKey) : other.primaryKey != null)
      return false;
    if (indices != null ? !indices.equals(other.indices) : other.indices != null) return false;
    if (references != null ? !references.equals(other.references) : other.references != null)
      return false;
    if (routingCol != null ? !routingCol.equals(other.routingCol) : other.routingCol != null)
      return false;

    return true;
  }
 /** update the current replacement of any original reader back to its original start */
 private List<SSTableReader> restoreUpdatedOriginals() {
   Iterable<SSTableReader> torestore = filterIn(originals, logged.update, logged.obsolete);
   return ImmutableList.copyOf(
       transform(
           torestore,
           new Function<SSTableReader, SSTableReader>() {
             public SSTableReader apply(SSTableReader reader) {
               return current(reader).cloneWithNewStart(reader.first, null);
             }
           }));
 }
Example #9
0
 public RelOptTableImpl getTable(final List<String> names) {
   // First look in the default schema, if any.
   if (defaultSchema != null) {
     RelOptTableImpl table = getTableFrom(names, defaultSchema);
     if (table != null) {
       return table;
     }
   }
   // If not found, look in the root schema
   return getTableFrom(names, ImmutableList.<String>of());
 }
Example #10
0
 private ReferenceInfo newInfo(
     ColumnIdent column,
     DataType type,
     ColumnPolicy columnPolicy,
     ReferenceInfo.IndexType indexType) {
   RowGranularity granularity = RowGranularity.DOC;
   if (partitionedBy.contains(column)) {
     granularity = RowGranularity.PARTITION;
   }
   return new ReferenceInfo(
       new ReferenceIdent(ident, column), granularity, type, columnPolicy, indexType);
 }
Example #11
0
  /*
   * Get the exponentially-decayed approximate counts of values in multiple buckets. The elements in
   * the provided list denote the upper bound each of the buckets and must be sorted in ascending
   * order.
   *
   * The approximate count in each bucket is guaranteed to be within 2 * totalCount * maxError of
   * the real count.
   */
  public List<Bucket> getHistogram(List<Long> bucketUpperBounds) {
    checkArgument(
        Ordering.natural().isOrdered(bucketUpperBounds),
        "buckets must be sorted in increasing order");

    final ImmutableList.Builder<Bucket> builder = ImmutableList.builder();
    final PeekingIterator<Long> iterator = Iterators.peekingIterator(bucketUpperBounds.iterator());

    final AtomicDouble sum = new AtomicDouble();
    final AtomicDouble lastSum = new AtomicDouble();

    // for computing weighed average of values in bucket
    final AtomicDouble bucketWeightedSum = new AtomicDouble();

    final double normalizationFactor = weight(TimeUnit.NANOSECONDS.toSeconds(ticker.read()));

    postOrderTraversal(
        root,
        new Callback() {
          @Override
          public boolean process(Node node) {

            while (iterator.hasNext() && iterator.peek() <= node.getUpperBound()) {
              double bucketCount = sum.get() - lastSum.get();

              Bucket bucket =
                  new Bucket(
                      bucketCount / normalizationFactor, bucketWeightedSum.get() / bucketCount);

              builder.add(bucket);
              lastSum.set(sum.get());
              bucketWeightedSum.set(0);
              iterator.next();
            }

            bucketWeightedSum.addAndGet(node.getMiddle() * node.weightedCount);
            sum.addAndGet(node.weightedCount);
            return iterator.hasNext();
          }
        });

    while (iterator.hasNext()) {
      double bucketCount = sum.get() - lastSum.get();
      Bucket bucket =
          new Bucket(bucketCount / normalizationFactor, bucketWeightedSum.get() / bucketCount);

      builder.add(bucket);

      iterator.next();
    }

    return builder.build();
  }
Example #12
0
 private void prepareCrateMeta() {
   metaMap = getNested(defaultMappingMap, "_meta");
   if (metaMap != null) {
     indicesMap = getNested(metaMap, "indices");
     if (indicesMap == null) {
       indicesMap = ImmutableMap.of();
     }
     metaColumnsMap = getNested(metaMap, "columns");
     if (metaColumnsMap == null) {
       metaColumnsMap = ImmutableMap.of();
     }
     partitionedByList = getNested(metaMap, "partitioned_by");
     if (partitionedByList == null) {
       partitionedByList = ImmutableList.of();
     }
   } else {
     metaMap = new HashMap<>();
     indicesMap = new HashMap<>();
     metaColumnsMap = new HashMap<>();
     partitionedByList = ImmutableList.of();
   }
 }
Example #13
0
 private Collection<Function> getFunctionsFrom(List<String> names) {
   final List<Function> functions2 = Lists.newArrayList();
   final List<? extends List<String>> schemaNameList;
   if (names.size() > 1) {
     // If name is qualified, ignore path.
     schemaNameList = ImmutableList.of(ImmutableList.<String>of());
   } else {
     OptiqSchema schema = getSchema(defaultSchema);
     if (schema == null) {
       schemaNameList = ImmutableList.of();
     } else {
       schemaNameList = schema.getPath();
     }
   }
   for (List<String> schemaNames : schemaNameList) {
     OptiqSchema schema = getSchema(Iterables.concat(schemaNames, Util.skipLast(names)));
     if (schema != null) {
       final String name = Util.last(names);
       functions2.addAll(schema.getFunctions(name, true));
     }
   }
   return functions2;
 }
Example #14
0
 /** Returns the path of an object in this schema. */
 public List<String> path(String name) {
   final List<String> list = new ArrayList<String>();
   if (name != null) {
     list.add(name);
   }
   for (OptiqSchema s = this; s != null; s = s.parent) {
     if (s.parent != null || !s.name.equals("")) {
       // Omit the root schema's name from the path if it's the empty string,
       // which it usually is.
       list.add(s.name);
     }
   }
   return ImmutableList.copyOf(Lists.reverse(list));
 }
Example #15
0
 private ColumnIdent childIdent(ColumnIdent ident, String name) {
   if (ident == null) {
     return new ColumnIdent(name);
   }
   if (ident.isColumn()) {
     return new ColumnIdent(ident.name(), name);
   } else {
     ImmutableList.Builder<String> builder = ImmutableList.builder();
     for (String s : ident.path()) {
       builder.add(s);
     }
     builder.add(name);
     return new ColumnIdent(ident.name(), builder.build());
   }
 }
Example #16
0
  public DocIndexMetaData build() {
    partitionedBy = getPartitionedBy();
    columnPolicy = getColumnPolicy();
    createColumnDefinitions();
    indices = createIndexDefinitions();
    columns = ImmutableList.copyOf(columnsBuilder.build());
    partitionedByColumns = partitionedByColumnsBuilder.build();

    for (Tuple<ColumnIdent, ReferenceInfo> sysColumn : DocSysColumns.forTable(ident)) {
      referencesBuilder.put(sysColumn.v1(), sysColumn.v2());
    }
    references = referencesBuilder.build();
    primaryKey = getPrimaryKey();
    routingCol = getRoutingCol();
    return this;
  }
Example #17
0
 private void add(
     ColumnIdent column,
     DataType type,
     ColumnPolicy columnPolicy,
     ReferenceInfo.IndexType indexType,
     boolean partitioned) {
   ReferenceInfo info = newInfo(column, type, columnPolicy, indexType);
   // don't add it if there is a partitioned equivalent of this column
   if (partitioned || !(partitionedBy != null && partitionedBy.contains(column))) {
     if (info.ident().isColumn()) {
       columnsBuilder.add(info);
     }
     referencesBuilder.put(info.ident().columnIdent(), info);
   }
   if (partitioned) {
     partitionedByColumnsBuilder.add(info);
   }
 }
Example #18
0
  /**
   * Gets the values at the specified quantiles +/- maxError. The list of quantiles must be sorted
   * in increasing order, and each value must be in the range [0, 1]
   */
  public List<Long> getQuantiles(List<Double> quantiles) {
    checkArgument(
        Ordering.natural().isOrdered(quantiles), "quantiles must be sorted in increasing order");
    for (double quantile : quantiles) {
      checkArgument(quantile >= 0 && quantile <= 1, "quantile must be between [0,1]");
    }

    final ImmutableList.Builder<Long> builder = ImmutableList.builder();
    final PeekingIterator<Double> iterator = Iterators.peekingIterator(quantiles.iterator());

    postOrderTraversal(
        root,
        new Callback() {
          private double sum = 0;

          @Override
          public boolean process(Node node) {
            sum += node.weightedCount;

            while (iterator.hasNext() && sum > iterator.peek() * weightedCount) {
              iterator.next();

              // we know the max value ever seen, so cap the percentile to provide better error
              // bounds in this case
              long value = Math.min(node.getUpperBound(), max);

              builder.add(value);
            }

            return iterator.hasNext();
          }
        });

    // we finished the traversal without consuming all quantiles. This means the remaining quantiles
    // correspond to the max known value
    while (iterator.hasNext()) {
      builder.add(max);
      iterator.next();
    }

    return builder.build();
  }
Example #19
0
 public final Table getTable(String tableName, boolean caseSensitive) {
   if (caseSensitive) {
     return compositeTableMap.get(tableName);
   } else {
     final TableEntry tableEntry = tableMapInsensitive.get(tableName);
     if (tableEntry != null) {
       return tableEntry.getTable();
     }
     final FunctionEntry entry = nullaryFunctionMapInsensitive.get(tableName);
     if (entry != null) {
       return ((TableMacro) entry.getFunction()).apply(ImmutableList.of());
     }
     for (String name : schema.getTableNames()) {
       if (name.equalsIgnoreCase(tableName)) {
         return schema.getTable(name);
       }
     }
     return null;
   }
 }
Example #20
0
  public List<SqlMoniker> getAllSchemaObjectNames(List<String> names) {
    final OptiqSchema schema = getSchema(names);
    if (schema == null) {
      return ImmutableList.of();
    }
    final List<SqlMoniker> result = new ArrayList<SqlMoniker>();
    final Map<String, OptiqSchema> schemaMap = schema.getSubSchemaMap();

    for (String subSchema : schemaMap.keySet()) {
      result.add(new SqlMonikerImpl(schema.path(subSchema), SqlMonikerType.SCHEMA));
    }

    for (String table : schema.getTableNames()) {
      result.add(new SqlMonikerImpl(schema.path(table), SqlMonikerType.TABLE));
    }

    final NavigableSet<String> functions = schema.getFunctionNames();
    for (String function : functions) { // views are here as well
      result.add(new SqlMonikerImpl(schema.path(function), SqlMonikerType.FUNCTION));
    }
    return result;
  }
Example #21
0
 @Override
 public Map<String, Object> getValuesDeep() {
   final Tag tag = this.findLastTag(this.path, false);
   if (!(tag instanceof CompoundTag)) {
     return Collections.emptyMap();
   }
   final Queue<Node> node =
       new ArrayDeque<Node>(
           (Collection<? extends Node>) ImmutableList.of((Object) new Node(tag)));
   final Map<String, Object> values = (Map<String, Object>) Maps.newHashMap();
   while (!node.isEmpty()) {
     final Node root = node.poll();
     for (final Map.Entry<String, Tag> entry : root.values.entrySet()) {
       final String key = this.createRelativeKey(root.parent, entry.getKey());
       if (entry.getValue() instanceof CompoundTag) {
         node.add(new Node(key, entry.getValue()));
       } else {
         values.put(key, entry.getValue().getValue());
       }
     }
   }
   return values;
 }
 private static ImmutableSortedSet copyOfInternal(Comparator comparator1, Iterator iterator1) {
   ImmutableList immutablelist =
       ImmutableList.copyOf(SortedIterables.sortedUnique(comparator1, iterator1));
   if (immutablelist.isEmpty()) return emptySet(comparator1);
   else return new RegularImmutableSortedSet(immutablelist, comparator1);
 }
public class JmsMapRoundtripTest extends AbstractJmsSenderFactoryTest {

  private static final String OPERATION_FIELD_NAME = "event";

  private static final class SimpleServiceCall {
    private final String operation;
    private final String argument;
    private final Class<?> type;
    private final Object value;

    SimpleServiceCall(String operation, String argument, Class<?> type, Object value) {
      this.operation = operation;
      this.argument = argument;
      this.type = type;
      this.value = value;
    }

    @Override
    public String toString() {
      return "SimpleServiceCall [" + type + "]";
    }
  }

  public static final Collection<SimpleServiceCall> PRIMITIVE_CALLS =
      ImmutableList.of( //
          new SimpleServiceCall("booleanCall", "b", boolean.class, false), //
          new SimpleServiceCall("byteCall", "b", byte.class, (byte) 0), //
          new SimpleServiceCall("charCall", "c", char.class, 'c'), //
          new SimpleServiceCall("shortCall", "s", short.class, (short) 0), //
          new SimpleServiceCall("intCall", "i", int.class, 0), //
          new SimpleServiceCall("longCall", "l", long.class, 0L), //
          new SimpleServiceCall("floatCall", "f", float.class, 0.0f), //
          new SimpleServiceCall("doubleCall", "d", double.class, 0.0));

  public static final Collection<SimpleServiceCall> BOXED_PRIMITIVE_CALLS =
      ImmutableList.of( //
          new SimpleServiceCall("boxedBooleanCall", "b", Boolean.class, false), //
          new SimpleServiceCall("boxedByteCall", "b", Byte.class, (byte) 0), //
          new SimpleServiceCall("boxedCharCall", "c", Character.class, 'c'), //
          new SimpleServiceCall("boxedShortCall", "s", Short.class, (short) 0), //
          new SimpleServiceCall("boxedIntCall", "i", Integer.class, 0), //
          new SimpleServiceCall("boxedLongCall", "l", Long.class, 0L), //
          new SimpleServiceCall("boxedFloatCall", "f", Float.class, 0.0f), //
          new SimpleServiceCall("boxedDoubleCall", "d", Double.class, 0.0));

  @Mock private MappedApi serviceMock;

  @Mock private PrimitivesTestApi primitivesServiceMock;

  @Mock private BoxedPrimitivesTestApi boxedPrimitivesServiceMock;

  @Mock private OneCharTestApi oneCharServiceMock;

  @Test
  public void shouldCallServiceWhenSendingAsMapMessage() {
    // Given
    MappedApi sendProxy = MessageSender.of(MappedApi.class);
    Mapping receiveMapping =
        new MappingBuilder(OPERATION_FIELD_NAME) //
            .mapField("s1", FieldMapping.map("A")) //
            .mapField("s2", FieldMapping.map("B")) //
            .build();

    // When
    sendProxy.mappedCall("a", 0L);
    receive(captureMessage(), receiveMapping);

    // Then
    verify(serviceMock).mappedCall("a", 0L);
  }

  @Test
  public void shouldCallServiceOneCharMethod() {
    // Given
    JmsSenderFactory factory = new JmsSenderFactory(CONFIG, new MapJmsPayloadHandler());
    OneCharTestApi sendProxy = factory.create(OneCharTestApi.class);
    Mapping receiveMapping = new MappingBuilder("METHOD").build();

    // When
    sendProxy.a("content");
    MapMessageDecoder.of(OneCharTestApi.class, oneCharServiceMock, receiveMapping) //
        .onMessage(captureMessage());

    // Then
    verify(oneCharServiceMock).a("content");
  }

  @Test
  public void sendShouldFailWithUnmappedName() {
    // Given
    Mapping mapping = partialMapping();
    MappedApi service = service(mapping);

    // When
    String message = null;
    try {
      service.mappedCall("a", 0L);
      fail("IllegalArgumentException expected");
    } catch (IllegalArgumentException e) {
      message = e.getMessage();
    }

    // Then
    assertEquals("no mapping for field: s2", message);
  }

  private Mapping partialMapping() {
    Mapping mapping = mock(Mapping.class);
    given(mapping.getOperationMessageAttibute()).willReturn(OPERATION_FIELD_NAME);
    given(mapping.getOperationForMethod("mappedCall")).willReturn("OP");
    given(mapping.getMethodForOperation("OP")).willReturn("mappedCall");
    givenFieldMapping(mapping, "s1", FieldMapping.map("a"));
    return new CheckedMapping(mapping);
  }

  @Test
  public void receiveShouldFailWithUnmappedName() {
    // Given
    Mapping sendMapping =
        new MappingBuilder(OPERATION_FIELD_NAME).mapOperation("mappedCall", "OP").build();
    MappedApi service = service(sendMapping);
    service.mappedCall("a", 0L);

    Mapping receiveMapping = partialMapping();

    // When
    String message = null;
    try {
      MapMessageDecoder.of(MappedApi.class, serviceMock, receiveMapping)
          .onMessage(captureMessage());
      fail("RuntimeException expected");
    } catch (RuntimeException e) {
      message = e.getCause().getMessage();
    }

    // Then
    assertEquals("no mapping for field: s2", message);
  }

  @Test
  public void shouldMapSendAttributes() throws JMSException {
    // Given
    MappedApi proxy = MessageSender.of(MappedApi.class);

    // When
    proxy.mappedCall("a", 0L);

    // Then
    MapMessage message = (MapMessage) captureMessage();
    assertEquals("a", message.getObject("A"));
    assertEquals("0", message.getObject("B"));
  }

  @Test
  public void shouldMapReceiveAttributes() throws JMSException {
    // Given
    Mapping mapping = MessageSender.getJmsMappingFor(MappedApi.class);

    MapMessage message = createPayload(OPERATION_FIELD_NAME, "mappedCall", "A", "value1", "B", 0L);

    // When
    receive(message, mapping);

    // Then
    verify(serviceMock).mappedCall("value1", 0L);
  }

  @Test
  public void shouldSendAttributesUsingExplicitConversion(boolean flag) throws JMSException {
    // Given
    LocalDate today = new LocalDate();
    String pattern = "dd.MM.YYYY";
    Mapping mapping =
        new MappingBuilder(OPERATION_FIELD_NAME) //
            .mapField("date", FieldMapping.map("date", new JodaLocalDateConverter(pattern))) //
            .mapField("flag", FieldMapping.map("flag", new StringToBooleanConverter("1", "0"))) //
            .build();
    MapJmsPayloadHandler payloadHandler = new MapJmsPayloadHandler(mapping);
    JodaTimeApi service = JmsSenderFactory.create(CONFIG, payloadHandler).create(JodaTimeApi.class);

    // When
    service.localDateCall(today, flag);

    // Then
    MapMessage message = (MapMessage) captureMessage();
    assertEquals(today.toString(pattern), message.getString("date"));
    assertEquals(flag ? "1" : "0", message.getString("flag"));
  }

  @Test
  public void shouldReceiveAttributesUsingExplicitConversion(boolean flag) throws JMSException {
    // Given
    String pattern = "dd.MM.YYYY";
    LocalDate today = new LocalDate();
    Mapping mapping =
        new MappingBuilder(OPERATION_FIELD_NAME) //
            .mapField("date", FieldMapping.map("date", new JodaLocalDateConverter(pattern))) //
            .mapField("flag", FieldMapping.map("flag", new StringToBooleanConverter("1", "0"))) //
            .build();

    MapMessage message =
        createPayload(
            OPERATION_FIELD_NAME,
            "localDateCall",
            "date",
            today.toString(pattern),
            "flag",
            flag ? "1" : "0");

    // When
    JodaTimeApi mock = mock(JodaTimeApi.class);
    MapMessageDecoder.of(JodaTimeApi.class, mock, mapping).onMessage(message);

    // Then
    verify(mock).localDateCall(today, flag);
  }

  @Test
  public void shouldMapSendOperationAttribute() throws JMSException {
    MappedApi service = service(new MappingBuilder("myop").build());

    // When
    service.mappedNoArgCall();

    // Then
    MapMessage message = (MapMessage) captureMessage();
    assertEquals("mappedNoArgCall", message.getObject("myop"));
  }

  @Test
  public void shouldMapReceiveOperationAttibute() throws JMSException {
    // Given
    MappingBuilder myMapping = new MappingBuilder("myop");

    MapMessage message = createPayload("myop", "mappedNoArgCall");

    // When
    MapMessageDecoder.of(MappedApi.class, serviceMock, myMapping.build()).onMessage(message);

    // Then
    verify(serviceMock).mappedNoArgCall();
  }

  @Test
  public void shouldMapSendOperationName() throws JMSException {
    // Given
    Mapping mapping =
        new MappingBuilder(OPERATION_FIELD_NAME) //
            .mapOperation("mappedNoArgCall", "MAPPED_NOARG_OP")
            .build();
    MappedApi service = service(mapping);

    // When
    service.mappedNoArgCall();

    // Then
    MapMessage message = (MapMessage) captureMessage();
    assertEquals("MAPPED_NOARG_OP", message.getObject(OPERATION_FIELD_NAME));
  }

  @Test
  public void shouldMapReceiveOperationName() throws JMSException {
    // Given
    Mapping mapping =
        new MappingBuilder(OPERATION_FIELD_NAME) //
            .mapOperation("mappedNoArgCall", "MAPPED_NOARG_OP")
            .build();

    MapMessage message = createPayload(OPERATION_FIELD_NAME, "MAPPED_NOARG_OP");

    // When
    receive(message, mapping);

    // Then
    verify(serviceMock).mappedNoArgCall();
  }

  @Test
  public void shouldCallServiceIfSendingOptionalParameter() {
    // Given
    Mapping mapping = new MappingBuilder(OPERATION_FIELD_NAME).build();
    MappedApi service = service(mapping);

    // When
    service.optionalMappedCall("optional");
    receive(captureMessage(), mapping);

    // Then
    verify(serviceMock).optionalMappedCall("optional");
  }

  @Test
  public void shouldCallServiceWithEmptyValueIfNotSendingOptionalParameter() {
    // Given
    Mapping mapping = new MappingBuilder(OPERATION_FIELD_NAME).build();
    MappedApi service = service(mapping);

    // When
    service.optionalMappedCall(null);
    receive(captureMessage(), mapping);

    // Then
    verify(serviceMock).optionalMappedCall(null);
  }

  @Test
  public void shouldCallServiceWithDefaultValueIfNotSendingOptionalParameter() {
    // Given
    Mapping mapping =
        new MappingBuilder(OPERATION_FIELD_NAME)
            .mapField("string", FieldMapping.mapWithDefault("string", "default value"))
            .build();
    MappedApi service = service(mapping);

    // When
    service.optionalMappedCall(null);
    receive(captureMessage(), mapping);

    // Then
    verify(serviceMock).optionalMappedCall("default value");
  }

  @Test
  public void shouldCallServiceWithDefaultValueIfNotSendingMandatoryParameter() {
    // Given
    Mapping mapping =
        new MappingBuilder(OPERATION_FIELD_NAME)
            .mapField("s1", FieldMapping.mapWithDefault("s1", "default value"))
            .build();
    MappedApi service = service(mapping);

    // When
    service.mappedCall(null, 1L);
    receive(captureMessage(), mapping);

    // Then
    verify(serviceMock).mappedCall("default value", 1L);
  }

  @Test
  @Ignore
  // TODO reenable
  public void shouldMapReceivePrimitiveAttributesIfWrittenAsStrings(
      /* @Values("PRIMITIVE_CALLS") */ SimpleServiceCall call) throws Exception {
    // Given
    MappingBuilder mapping = new MappingBuilder(OPERATION_FIELD_NAME);
    String operation = call.operation;
    String argument = call.argument;
    Class<?> type = call.type;
    Object value = call.value;
    mapping.mapField(argument, FieldMapping.map(argument));

    MapMessage message =
        createPayload(OPERATION_FIELD_NAME, operation, argument, String.valueOf(value));

    // When
    MapMessageDecoder.of(PrimitivesTestApi.class, primitivesServiceMock, mapping.build())
        .onMessage(message);

    // Then
    invoke(verify(primitivesServiceMock), operation, type, value);
  }

  @Test
  @Ignore
  // TODO reenable
  public void shouldMapReceiveBoxedPrimitiveAttributesIfWrittenAsStrings(
      /* @Values("BOXED_PRIMITIVE_CALLS") */ SimpleServiceCall call) throws Exception {
    // Given
    MappingBuilder mapping = new MappingBuilder(OPERATION_FIELD_NAME);
    String operation = call.operation;
    String argument = call.argument;
    Class<?> type = call.type;
    Object value = call.value;
    mapping.mapField(argument, FieldMapping.map(argument));

    MapMessage message =
        createPayload(OPERATION_FIELD_NAME, operation, argument, String.valueOf(value));

    // When
    MapMessageDecoder.of(BoxedPrimitivesTestApi.class, boxedPrimitivesServiceMock, mapping.build())
        .onMessage(message);

    // Then
    invoke(verify(boxedPrimitivesServiceMock), operation, type, value);
  }

  private void invoke(Object target, String method, Class<?> type, Object value) throws Exception {
    Method m = target.getClass().getMethod(method, type);
    m.invoke(target, value);
  }

  private MapMessage newMapMessage(Map<String, Object> body) throws JMSException {
    MapMessage message = new MapMessageImpl();
    for (String key : body.keySet()) {
      Object value = body.get(key);
      message.setObject(key, value);
    }
    return message;
  }

  private MapMessage createPayload(String key, Object value) throws JMSException {
    return newMapMessage(ImmutableMap.<String, Object>of(key, value));
  }

  private MapMessage createPayload(String key1, Object value1, String key2, Object value2)
      throws JMSException {
    return newMapMessage(ImmutableMap.<String, Object>of(key1, value1, key2, value2));
  }

  private MapMessage createPayload(
      String key1, Object value1, String key2, Object value2, String key3, Object value3)
      throws JMSException {
    return newMapMessage(ImmutableMap.<String, Object>of(key1, value1, key2, value2, key3, value3));
  }

  private MappedApi service(Mapping mapping) {
    return JmsSenderFactory.create(CONFIG, new MapJmsPayloadHandler(mapping))
        .create(MappedApi.class);
  }

  private void receive(Message message, Mapping mapping) {
    MapMessageDecoder.of(MappedApi.class, serviceMock, mapping).onMessage(message);
  }

  private <T> void givenFieldMapping(
      Mapping receiveMapping, String attributeName, FieldMapping<T> fieldMapping) {
    @SuppressWarnings("unchecked")
    FieldMapping<T> mapping = (FieldMapping<T>) receiveMapping.getMappingForField(attributeName);
    given(mapping).willReturn(fieldMapping);
  }
}
Example #24
0
 /** @return collection of the non-system tables */
 public List<String> getNonSystemTables() {
   return ImmutableList.copyOf(Sets.difference(tables.keySet(), systemKeyspaceNames));
 }
Example #25
0
 final int getCurrentCount() {
   Long count =
       (Long) getPlayerCountScript.eval(ImmutableList.<String>of(), ImmutableList.<String>of());
   return count.intValue();
 }
Example #26
0
  /**
   * Parse the given array of arguments.
   *
   * <p>Empty arguments are removed from the list of arguments.
   *
   * @param args an array with arguments
   * @param expectedValueFlags a set containing all value flags (pass null to disable value flag
   *     parsing)
   * @param allowHangingFlag true if hanging flags are allowed
   * @param namespace the locals, null to create empty one
   * @throws CommandException thrown on a parsing error
   */
  public CommandContext(
      String[] args,
      Set<Character> expectedValueFlags,
      boolean allowHangingFlag,
      Namespace namespace)
      throws CommandException {
    if (expectedValueFlags == null) {
      expectedValueFlags = Collections.emptySet();
    }

    originalArgs = args;
    command = args[0];
    this.namespace = namespace != null ? namespace : new Namespace();
    boolean isHanging = false;
    SuggestionContext suggestionContext = SuggestionContext.hangingValue();

    // Eliminate empty args and combine multiword args first
    List<Integer> argIndexList = new ArrayList<Integer>(args.length);
    List<String> argList = new ArrayList<String>(args.length);
    for (int i = 1; i < args.length; ++i) {
      isHanging = false;

      String arg = args[i];
      if (arg.isEmpty()) {
        isHanging = true;
        continue;
      }

      argIndexList.add(i);

      switch (arg.charAt(0)) {
        case '\'':
        case '"':
          final StringBuilder build = new StringBuilder();
          final char quotedChar = arg.charAt(0);

          int endIndex;
          for (endIndex = i; endIndex < args.length; ++endIndex) {
            final String arg2 = args[endIndex];
            if (arg2.charAt(arg2.length() - 1) == quotedChar && arg2.length() > 1) {
              if (endIndex != i) build.append(' ');
              build.append(arg2.substring(endIndex == i ? 1 : 0, arg2.length() - 1));
              break;
            } else if (endIndex == i) {
              build.append(arg2.substring(1));
            } else {
              build.append(' ').append(arg2);
            }
          }

          if (endIndex < args.length) {
            arg = build.toString();
            i = endIndex;
          }

          // In case there is an empty quoted string
          if (arg.isEmpty()) {
            continue;
          }
          // else raise exception about hanging quotes?
      }
      argList.add(arg);
    }

    // Then flags

    List<Integer> originalArgIndices = Lists.newArrayListWithCapacity(argIndexList.size());
    List<String> parsedArgs = Lists.newArrayListWithCapacity(argList.size());
    Map<Character, String> valueFlags = Maps.newHashMap();
    List<Character> booleanFlags = Lists.newArrayList();

    for (int nextArg = 0; nextArg < argList.size(); ) {
      // Fetch argument
      String arg = argList.get(nextArg++);
      suggestionContext = SuggestionContext.hangingValue();

      // Not a flag?
      if (arg.charAt(0) != '-' || arg.length() == 1 || !arg.matches("^-[a-zA-Z\\?]+$")) {
        if (!isHanging) {
          suggestionContext = SuggestionContext.lastValue();
        }

        originalArgIndices.add(argIndexList.get(nextArg - 1));
        parsedArgs.add(arg);
        continue;
      }

      // Handle flag parsing terminator --
      if (arg.equals("--")) {
        while (nextArg < argList.size()) {
          originalArgIndices.add(argIndexList.get(nextArg));
          parsedArgs.add(argList.get(nextArg++));
        }
        break;
      }

      // Go through the flag characters
      for (int i = 1; i < arg.length(); ++i) {
        char flagName = arg.charAt(i);

        if (expectedValueFlags.contains(flagName)) {
          if (valueFlags.containsKey(flagName)) {
            throw new CommandException("Value flag '" + flagName + "' already given");
          }

          if (nextArg >= argList.size()) {
            if (allowHangingFlag) {
              suggestionContext = SuggestionContext.flag(flagName);
              break;
            } else {
              throw new CommandException("No value specified for the '-" + flagName + "' flag.");
            }
          }

          // If it is a value flag, read another argument and add it
          valueFlags.put(flagName, argList.get(nextArg++));
          if (!isHanging) {
            suggestionContext = SuggestionContext.flag(flagName);
          }
        } else {
          booleanFlags.add(flagName);
        }
      }
    }

    ImmutableMap.Builder<Character, String> allFlagsBuilder =
        new ImmutableMap.Builder<Character, String>().putAll(valueFlags);
    for (Character flag : booleanFlags) {
      allFlagsBuilder.put(flag, "true");
    }

    this.parsedArgs = ImmutableList.copyOf(parsedArgs);
    this.originalArgIndices = ImmutableList.copyOf(originalArgIndices);
    this.booleanFlags = ImmutableSet.copyOf(booleanFlags);
    this.valueFlags = ImmutableMap.copyOf(valueFlags);
    this.allFlags = allFlagsBuilder.build();
    this.suggestionContext = suggestionContext;
  }
Example #27
0
  private void init(
      PName name,
      PTableType type,
      long timeStamp,
      long sequenceNumber,
      String pkName,
      List<PColumn> columns,
      PTableStats stats) {
    this.name = name;
    this.type = type;
    this.timeStamp = timeStamp;
    this.sequenceNumber = sequenceNumber;
    this.columnsByName = ArrayListMultimap.create(columns.size(), 1);
    this.pkName = pkName;
    List<PColumn> pkColumns = Lists.newArrayListWithExpectedSize(columns.size() - 1);
    PColumn[] allColumns = new PColumn[columns.size()];
    RowKeySchemaBuilder builder = new RowKeySchemaBuilder();
    for (int i = 0; i < allColumns.length; i++) {
      PColumn column = columns.get(i);
      allColumns[column.getPosition()] = column;
      PName familyName = column.getFamilyName();
      if (familyName == null) {
        pkColumns.add(column);
        builder.addField(column);
      }
      columnsByName.put(column.getName().getString(), column);
    }
    this.pkColumns = ImmutableList.copyOf(pkColumns);
    this.rowKeySchema = builder.setMinNullable(pkColumns.size()).build();
    this.allColumns = ImmutableList.copyOf(allColumns);

    // Two pass so that column order in column families matches overall column order
    // and to ensure that column family order is constant
    int maxExpectedSize = allColumns.length - pkColumns.size();
    // Maintain iteration order so that column families are ordered as they are listed
    Map<PName, List<PColumn>> familyMap = Maps.newLinkedHashMap();
    for (PColumn column : allColumns) {
      PName familyName = column.getFamilyName();
      if (familyName != null) {
        List<PColumn> columnsInFamily = familyMap.get(familyName);
        if (columnsInFamily == null) {
          columnsInFamily = Lists.newArrayListWithExpectedSize(maxExpectedSize);
          familyMap.put(familyName, columnsInFamily);
        }
        columnsInFamily.add(column);
      }
    }

    Iterator<Map.Entry<PName, List<PColumn>>> iterator = familyMap.entrySet().iterator();
    PColumnFamily[] families = new PColumnFamily[familyMap.size()];
    ImmutableMap.Builder<String, PColumnFamily> familyByString = ImmutableMap.builder();
    ImmutableSortedMap.Builder<byte[], PColumnFamily> familyByBytes =
        ImmutableSortedMap.orderedBy(Bytes.BYTES_COMPARATOR);
    for (int i = 0; i < families.length; i++) {
      Map.Entry<PName, List<PColumn>> entry = iterator.next();
      PColumnFamily family = new PColumnFamilyImpl(entry.getKey(), entry.getValue());
      families[i] = family;
      familyByString.put(family.getName().getString(), family);
      familyByBytes.put(family.getName().getBytes(), family);
    }
    this.families = ImmutableList.copyOf(families);
    this.familyByBytes = familyByBytes.build();
    this.familyByString = familyByString.build();
    this.stats = stats;
  }
Example #28
0
 /**
  * Gets the value at the specified quantile +/- maxError. The quantile must be in the range [0, 1]
  */
 public long getQuantile(double quantile) {
   return getQuantiles(ImmutableList.of(quantile)).get(0);
 }
 public static ImmutableSortedSet of(Comparable comparable) {
   return new RegularImmutableSortedSet(ImmutableList.of(comparable), Ordering.natural());
 }
 @RequiredModules
 public List<Module> requiredModules() {
   return (List<Module>) ImmutableList.of((Object) new ServiceModule());
 }