Java Code Examples for rx.functions.Func1#call()

The following examples show how to use rx.functions.Func1#call() . 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: Routers.java    From mantis with Apache License 2.0 6 votes vote down vote up
public static <K, V> Router<KeyValuePair<K, V>> consistentHashingLegacyTcpProtocol(String name,
                                                                                   final Func1<K, byte[]> keyEncoder,
                                                                                   final Func1<V, byte[]> valueEncoder) {
    return new ConsistentHashingRouter<K, V>(name, new Func1<KeyValuePair<K, V>, byte[]>() {
        @Override
        public byte[] call(KeyValuePair<K, V> kvp) {
            byte[] keyBytes = kvp.getKeyBytes();
            byte[] valueBytes = valueEncoder.call(kvp.getValue());
            return
                    // length + opcode + notification type + key length
                    ByteBuffer.allocate(4 + 1 + 1 + 4 + keyBytes.length + valueBytes.length)
                            .putInt(1 + 1 + 4 + keyBytes.length + valueBytes.length) // length
                            .put((byte) 1) // opcode
                            .put((byte) 1) // notification type
                            .putInt(keyBytes.length) // key length
                            .put(keyBytes) // key bytes
                            .put(valueBytes) // value bytes
                            .array();
        }
    }, HashFunctions.ketama());
}
 
Example 2
Source File: ParameterUtils.java    From mantis with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings( {"unchecked", "rawtypes"})
private static void validationCheck(Func1 validator, Object value,
                                    String name) throws IllegalArgumentException {
    if (validator == null) {
        throw new IllegalArgumentException("Validator for parameter definition: " + name + " is null");
    }
    Validation validatorOutcome = null;
    try {
        validatorOutcome = (Validation) validator.call(value);
    } catch (Throwable t) {
        throw new IllegalArgumentException("Parameter: " + name + " with value: "
                + value + " failed validator: "
                + t.getMessage(), t);
    }
    if (validatorOutcome.isFailedValidation()) {
        throw new IllegalArgumentException("Parameter: " + name + " with value: "
                + value + " failed validator: "
                + validatorOutcome.getFailedValidationReason());
    }
}
 
Example 3
Source File: MesosClientTest.java    From mesos-rxjava with Apache License 2.0 6 votes vote down vote up
@Test
public void testMesosStreamIdIsSavedForSuccessfulSubscribeCall() throws Exception {
    final AtomicReference<String> mesosStreamId = new AtomicReference<>(null);

    final Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>> f = MesosClient.verifyResponseOk(
        "Subscribe",
        mesosStreamId,
        StringMessageCodec.UTF8_STRING.mediaType()
    );

    final DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    nettyResponse.headers().add("Mesos-Stream-Id", "streamId");
    nettyResponse.headers().add("Content-Type", StringMessageCodec.UTF8_STRING.mediaType());
    final HttpClientResponse<ByteBuf> response = new HttpClientResponse<>(
        nettyResponse,
        UnicastContentSubject.create(1000, TimeUnit.MILLISECONDS)
    );

    f.call(response);


    assertThat(mesosStreamId.get()).isEqualTo("streamId");
}
 
Example 4
Source File: RTree3DTest.java    From rtree-3d with Apache License 2.0 6 votes vote down vote up
private static <T, S extends Geometry> Node<T, S> toLowerNode(
        com.github.davidmoten.rtree3d.proto.RTreeProtos.Node node, Context context,
        Func1<? super byte[], ? extends T> deserializer) {
    Preconditions.checkArgument(node.getSubTreeIdsCount() > 0);
    Box box = createBox(node.getMbb());
    if (node.getChildrenCount() > 0) {
        // is non-leaf
        List<Node<T, S>> children = new ArrayList<Node<T, S>>();
        for (com.github.davidmoten.rtree3d.proto.RTreeProtos.Node n : node.getChildrenList()) {
            Node<T, S> nd = toLowerNode(n, context, deserializer);
            children.add(nd);
        }
        return new NonLeaf<T, S>(children, box, context);
    } else {
        // is leaf
        List<Entry<T, S>> entries = new ArrayList<Entry<T, S>>();
        for (com.github.davidmoten.rtree3d.proto.RTreeProtos.Entry ent : node
                .getEntriesList()) {
            T t = deserializer.call(ent.getObject().toByteArray());
            S g = (S) createGeometry(ent.getGeometry());
            entries.add(Entry.entry(t, g));
        }
        return new Leaf<T, S>(entries, box, context);
    }
}
 
Example 5
Source File: MesosClientTest.java    From mesos-rxjava with Apache License 2.0 6 votes vote down vote up
@Test
public void testVerifyResponseOk_ensuresContentTypeOfResponseMatchesReceiveCodec() throws Exception {
    final Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>> f = MesosClient.verifyResponseOk(
        "Subscribe",
        new AtomicReference<>(),
        StringMessageCodec.UTF8_STRING.mediaType()
    );

    final DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    nettyResponse.headers().add("Content-Type", "text/html");
    final HttpClientResponse<ByteBuf> response = new HttpClientResponse<>(
        nettyResponse,
        UnicastContentSubject.create(1000, TimeUnit.MILLISECONDS)
    );

    try {
        f.call(response);
    } catch (MesosException e) {
        final String expected = String.format(
            "Response had Content-Type \"%s\" expected \"%s\"",
            "text/html",
            StringMessageCodec.UTF8_STRING.mediaType()
        );
        assertThat(e.getContext().getMessage()).isEqualTo(expected);
    }
}
 
Example 6
Source File: MesosClientTest.java    From mesos-rxjava with Apache License 2.0 6 votes vote down vote up
@Test
public void testMesosStreamIdIsNotSavedForUnsuccessfulSubscribeCall() throws Exception {
    final AtomicReference<String> mesosStreamId = new AtomicReference<>(null);

    final Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>> f = MesosClient.verifyResponseOk(
        "Subscribe",
        mesosStreamId,
        StringMessageCodec.UTF8_STRING.mediaType()
    );

    final DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
    nettyResponse.headers().add("Mesos-Stream-Id", "streamId");
    nettyResponse.headers().add("Content-Type", StringMessageCodec.UTF8_STRING.mediaType());
    final HttpClientResponse<ByteBuf> response = new HttpClientResponse<>(
        nettyResponse,
        UnicastContentSubject.create(1000, TimeUnit.MILLISECONDS)
    );

    try {
        f.call(response);
    } catch (Mesos4xxException e) {
        // expected
    }

    assertThat(mesosStreamId.get()).isEqualTo(null);
}
 
Example 7
Source File: Routers.java    From mantis with Apache License 2.0 5 votes vote down vote up
public static <T> Router<T> roundRobinLegacyTcpProtocol(String name, final Func1<T, byte[]> toBytes) {
    return new RoundRobinRouter<>(name, new Func1<T, byte[]>() {
        @Override
        public byte[] call(T t1) {
            byte[] data = toBytes.call(t1);
            return dataPayload(data);
        }
    });
}
 
Example 8
Source File: PlaceholderResolver.java    From datamill with ISC License 5 votes vote down vote up
private String resolvePlaceholders(String value, Func1<String, String> placeholderValueLookup) {
    StringBuilder resolved = new StringBuilder();

    int startIndex = 0;

    Matcher matcher = PLACEHOLDER_PATTERN.matcher(value);
    while (matcher.find(startIndex)) {
        String placeholder = matcher.group(1);
        String replacement = placeholderValueLookup.call(placeholder);

        resolved.append(value.substring(startIndex, matcher.start()));

        if (replacement != null) {
            resolved.append(replacement);
            startIndex = matcher.end();
        } else {
            resolved.append('{');
            startIndex = matcher.start() + 1;
        }
    }

    if (startIndex > -1 && startIndex < value.length()) {
        resolved.append(value.substring(startIndex, value.length()));
    }

    return resolved.toString();
}
 
Example 9
Source File: RTree3DTest.java    From rtree-3d with Apache License 2.0 5 votes vote down vote up
private static <T, S extends Geometry> com.github.davidmoten.rtree3d.proto.RTreeProtos.Entry createProtoEntry(
        Entry<T, S> entry, Func1<? super T, byte[]> serializer) {
    // Position p =
    // Position.newBuilder().setIdentifierType(1).setValueInteger(123456789)
    // .setLatitude(entry.invX(point.geometry().x()))
    // .setLongitude(entry.invY(point.geometry().y()))
    // .setTimeEpochMs(Math.round((double)
    // entry.invZ(point.geometry().z()))).build();

    byte[] p = serializer.call(entry.value());
    com.github.davidmoten.rtree3d.proto.RTreeProtos.Entry ent = com.github.davidmoten.rtree3d.proto.RTreeProtos.Entry
            .newBuilder().setGeometry(createGeom(entry.geometry()))
            .setObject(ByteString.copyFrom(p)).build();
    return ent;
}
 
Example 10
Source File: Backpressure.java    From rtree-3d with Apache License 2.0 5 votes vote down vote up
private static <S extends Geometry, T> ImmutableStack<NodePosition<T, S>> searchNonLeaf(
        final Func1<? super Geometry, Boolean> condition,
        ImmutableStack<NodePosition<T, S>> stack, NodePosition<T, S> np) {
    Node<T, S> child = ((NonLeaf<T, S>) np.node()).children().get(np.position());
    if (condition.call(child.geometry())) {
        stack = stack.push(new NodePosition<T, S>(child, 0));
    } else {
        stack = stack.pop().push(np.nextPosition());
    }
    return stack;
}
 
Example 11
Source File: Backpressure.java    From rtree-3d with Apache License 2.0 5 votes vote down vote up
private static <T, S extends Geometry> StackAndRequest<NodePosition<T, S>> searchLeaf(
        final Func1<? super Geometry, Boolean> condition,
        final Subscriber<? super Entry<T, S>> subscriber,
        StackAndRequest<NodePosition<T, S>> state, NodePosition<T, S> np) {
    final long nextRequest;
    Entry<T, S> entry = ((Leaf<T, S>) np.node()).entries().get(np.position());
    if (condition.call(entry.geometry())) {
        subscriber.onNext(entry);
        nextRequest = state.request - 1;
    } else
        nextRequest = state.request;
    return StackAndRequest.create(state.stack.pop().push(np.nextPosition()), nextRequest);
}
 
Example 12
Source File: ExtTestSubscriber.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public <R> void assertProducesInAnyOrder(Collection<R> expected,
                                         Func1<T, R> mapFun,
                                         long timeout,
                                         TimeUnit timeUnit) throws InterruptedException {
    HashSet<R> left = new HashSet<>(expected);
    while (!left.isEmpty()) {
        R next = mapFun.call(takeNext(timeout, timeUnit));
        if (next != null && !left.remove(next)) {
            fail(formatAnyOrderFailure(next, expected.size(), left));
        }
    }
}
 
Example 13
Source File: ExtTestSubscriber.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public <R> void assertContainsInAnyOrder(Collection<R> expected, Func1<T, R> mapFun) {
    HashSet<R> left = new HashSet<>(expected);
    while (!left.isEmpty()) {
        R next = mapFun.call(takeNextOrFail());
        if (!left.remove(next)) {
            fail(formatAnyOrderFailure(next, expected.size(), left));
        }
    }
}
 
Example 14
Source File: WhereBuilderImpl.java    From datamill with ISC License 5 votes vote down vote up
@Override
public TerminalCondition or(
        Func1<ConditionBuilder, TerminalCondition> left,
        Func1<ConditionBuilder, TerminalCondition> right) {
    query.append(SqlSyntax.OPEN_PARENTHESIS);
    left.call(this);
    query.append(SqlSyntax.CLOSE_PARENTHESIS);
    query.append(SqlSyntax.SQL_OR);
    query.append(SqlSyntax.OPEN_PARENTHESIS);
    right.call(this);
    query.append(SqlSyntax.CLOSE_PARENTHESIS);

    return this;
}
 
Example 15
Source File: RetryUtilsTest.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
/**
 * This method will test retries on inBackoffAlternateCallbackMethod, eventually
 * returning success response after some failures and making sure it failed for
 * at least specific number before passing.
 */
@Test(groups = { "unit" }, timeOut = TIMEOUT)
public void toRetryWithAlternateFuncTestingMethodTwo() {
    Func1<Throwable, Single<StoreResponse>> onErrorFunc = RetryUtils.toRetryWithAlternateFunc(callbackMethod,
            retryPolicy, inBackoffAlternateCallbackMethod, minBackoffForInBackoffCallback);
    Mockito.when(callbackMethod.call(Matchers.any())).thenReturn(Single.error(new GoneException()));
    toggleMockFuncBtwFailureSuccess(inBackoffAlternateCallbackMethod);
    Mockito.when(retryPolicy.shouldRetry(Matchers.any()))
            .thenReturn(Single.just(ShouldRetryResult.retryAfter(BACK_OFF_DURATION)));
    Single<StoreResponse> response = onErrorFunc.call(new GoneException());
    StoreResponseValidator validator = StoreResponseValidator.create().withStatus(storeResponse.getStatus())
            .withContent(storeResponse.getResponseBody()).build();
    validateSuccess(response, validator, TIMEOUT);
    Mockito.verify(inBackoffAlternateCallbackMethod, Mockito.times(4)).call(Matchers.any());
}
 
Example 16
Source File: RetryUtilsTest.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
/**
 * This method will test retries on callbackMethod, eventually returning success
 * response after some failures and making sure it failed for at least specific
 * number before passing.
 */
@Test(groups = { "unit" }, timeOut = TIMEOUT)
public void toRetryWithAlternateFuncTestingMethodOne() {
    Func1<Throwable, Single<StoreResponse>> onErrorFunc = RetryUtils.toRetryWithAlternateFunc(callbackMethod,
            retryPolicy, null, minBackoffForInBackoffCallback);

    toggleMockFuncBtwFailureSuccess(callbackMethod);
    Mockito.when(retryPolicy.shouldRetry(Matchers.any()))
            .thenReturn(Single.just(ShouldRetryResult.retryAfter(BACK_OFF_DURATION)));
    Single<StoreResponse> response = onErrorFunc.call(new GoneException());
    StoreResponseValidator validator = StoreResponseValidator.create().withStatus(storeResponse.getStatus())
            .withContent(storeResponse.getResponseBody()).build();
    validateSuccess(response, validator, TIMEOUT);
    Mockito.verify(callbackMethod, Mockito.times(4)).call(Matchers.any());
}
 
Example 17
Source File: AddressResolverTest.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
@BeforeClass(groups = "unit")
public void setup() throws Exception {
    this.addressResolver = new AddressResolver();
    this.collectionCache = Mockito.mock(RxCollectionCache.class);
    this.collectionRoutingMapCache = Mockito.mock(ICollectionRoutingMapCache.class);
    this.fabricAddressCache = Mockito.mock(IAddressCache.class);
    this.addressResolver.initializeCaches(this.collectionCache, this.collectionRoutingMapCache, this.fabricAddressCache);

    this.collection1 = new DocumentCollection();
    this.collection1.setId("coll");
    this.collection1.setResourceId("rid1");
    PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition();
    partitionKeyDef.setPaths(ImmutableList.of("/field1"));
    this.collection1.setPartitionKey(partitionKeyDef);

    this.collection2 = new DocumentCollection();
    this.collection2.setId("coll");
    this.collection2.setResourceId("rid2");
    new PartitionKeyDefinition();
    partitionKeyDef.setPaths(ImmutableList.of("/field1"));
    this.collection2.setPartitionKey(partitionKeyDef);

    Func1<List<ImmutablePair<PartitionKeyRange, IServerIdentity>>, Void> addPartitionKeyRangeFunc = listArg -> {
        listArg.forEach(tuple -> ((ServiceIdentity) tuple.right).partitionKeyRangeIds.add(new PartitionKeyRangeIdentity(collection1.getResourceId(), tuple.left.getId())));
        return null;
    };

    List<ImmutablePair<PartitionKeyRange, IServerIdentity>> rangesBeforeSplit1 =
        new ArrayList<>();
    ServiceIdentity serverServiceIdentity = new ServiceIdentity("federation1", new URI("fabric://serverservice1"), false);

    rangesBeforeSplit1.add(
        ImmutablePair.of(new PartitionKeyRange("0", PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey,
            PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey), serverServiceIdentity));

    addPartitionKeyRangeFunc.call(rangesBeforeSplit1);


    this.routingMapCollection1BeforeSplit =
        InMemoryCollectionRoutingMap.tryCreateCompleteRoutingMap(
            rangesBeforeSplit1,
            collection1.getResourceId());

    List<ImmutablePair<PartitionKeyRange, IServerIdentity>> rangesAfterSplit1 =
        new ArrayList<>();
    ServiceIdentity serverServiceIdentity2 = new ServiceIdentity("federation1", new URI("fabric://serverservice2"), false);
    ServiceIdentity serverServiceIdentity3 = new ServiceIdentity("federation1", new URI("fabric://serverservice3"), false);

    rangesAfterSplit1.add(
        ImmutablePair.of(
            new PartitionKeyRange("1", PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey, "5E", ImmutableList.of("0")),
            serverServiceIdentity2));

    rangesAfterSplit1.add(
        ImmutablePair.of(
            new PartitionKeyRange("2", "5E", PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, ImmutableList.of("0")),
            serverServiceIdentity3));

    addPartitionKeyRangeFunc.call(rangesAfterSplit1);

    this.routingMapCollection1AfterSplit = InMemoryCollectionRoutingMap.tryCreateCompleteRoutingMap(rangesAfterSplit1, collection1.getResourceId());

    List<ImmutablePair<PartitionKeyRange, IServerIdentity>> rangesBeforeSplit2 =
        new ArrayList<>();
    ServiceIdentity serverServiceIdentity4 = new ServiceIdentity("federation1", new URI("fabric://serverservice4"), false);

    rangesBeforeSplit2.add(
        ImmutablePair.of(
            new PartitionKeyRange("0", PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey, PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey),
            serverServiceIdentity4));

    addPartitionKeyRangeFunc.call(rangesBeforeSplit2);


    this.routingMapCollection2BeforeSplit = InMemoryCollectionRoutingMap.tryCreateCompleteRoutingMap(rangesBeforeSplit2, collection2.getResourceId());

    List<ImmutablePair<PartitionKeyRange, IServerIdentity>> rangesAfterSplit2 =
        new ArrayList<>();

    ServiceIdentity serverServiceIdentity5 = new ServiceIdentity("federation1", new URI("fabric://serverservice5"), false);
    ServiceIdentity serverServiceIdentity6 = new ServiceIdentity("federation1", new URI("fabric://serverservice6"), false);
    rangesAfterSplit2.add(
        ImmutablePair.of(
            new PartitionKeyRange("1", PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey, "5E", ImmutableList.of("0")),
            serverServiceIdentity5));

    rangesAfterSplit2.add(
        ImmutablePair.of(
            new PartitionKeyRange("2", "5E", PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, ImmutableList.of("0")),
            serverServiceIdentity6));


    addPartitionKeyRangeFunc.call(rangesAfterSplit2);


    this.routingMapCollection2AfterSplit = InMemoryCollectionRoutingMap.tryCreateCompleteRoutingMap(rangesAfterSplit2, collection2.getResourceId());
}
 
Example 18
Source File: Wiring.java    From datamill with ISC License 4 votes vote down vote up
public <R> R with(PropertySource propertySource, FactoryChain factoryChain, Func1<Wiring, R> wiringConsumer) {
    return wiringConsumer.call(new Wiring(propertySource, factoryChain, defaultScope, singletonScope));
}
 
Example 19
Source File: AbstractSource.java    From datamill with ISC License 4 votes vote down vote up
@Override
public <R> R with(Func1<PropertySource, R> propertiesConsumer) {
    return propertiesConsumer.call(this);
}
 
Example 20
Source File: PropertyNameTransformers.java    From datamill with ISC License 2 votes vote down vote up
/**
 * <p>
 * Returns a transformation function that applies the first function, and then the second function on the result
 * of the first. So compose(LEAF, LOWER_CAMEL_TO_UPPER_UNDERSCORE) will return a function that transforms:
 * </p>
 * <p>
 * category/propertyName -> PROPERTY_NAME
 * </p>
 */
public static final Func1<String, String> compose(Func1<String, String> a, Func1<String, String> b) {
    return name -> b.call(a.call(name));
}