org.apache.commons.lang3.mutable.MutableObject Java Examples

The following examples show how to use org.apache.commons.lang3.mutable.MutableObject. 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: LocalContextTest.java    From flux with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAllowSameMethodRegistrationFromDifferentThreads() throws Exception {

    final MutableObject<StateMachineDefinition> definitionOne = new MutableObject<>(null);
    final MutableObject<StateMachineDefinition> definitionTwo = new MutableObject<>(null);

    final Thread thread1 = new Thread(() -> {
        localContext.registerNew("fooBar", 1, "someDescription",
                "someContext", "defaultElbId");
        definitionOne.setValue(tlStateMachineDef.get());
    });
    final Thread thread2 = new Thread(() -> {
        localContext.registerNew("fooBar", 1, "someDescription",
                "someContext", "defaultElbId");
        definitionTwo.setValue(tlStateMachineDef.get());
    });
    thread1.start();
    thread2.start();

    thread1.join();
    thread2.join();

    assertThat(definitionOne.getValue()).isNotNull().isEqualTo(definitionTwo.getValue()).isEqualTo(new StateMachineDefinition(
            "someDescription", "fooBar", 1l, new HashSet<>(), new HashSet<>(),
            "someContext", "defaultElbId"));
}
 
Example #2
Source File: PushAggregateIntoGroupbyRule.java    From vxquery with Apache License 2.0 6 votes vote down vote up
private void rewriteGroupByAggregate(LogicalVariable oldAggVar, GroupByOperator gbyOp,
        AggregateFunctionCallExpression aggFun, LogicalVariable newAggVar, IOptimizationContext context)
                throws AlgebricksException {
    for (int j = 0; j < gbyOp.getNestedPlans().size(); j++) {
        AggregateOperator aggOp = (AggregateOperator) gbyOp.getNestedPlans().get(j).getRoots().get(0).getValue();
        int n = aggOp.getVariables().size();
        for (int i = 0; i < n; i++) {
            LogicalVariable v = aggOp.getVariables().get(i);
            if (v.equals(oldAggVar)) {
                AbstractFunctionCallExpression oldAggExpr = (AbstractFunctionCallExpression) aggOp.getExpressions()
                        .get(i).getValue();
                AggregateFunctionCallExpression newAggFun = new AggregateFunctionCallExpression(
                        aggFun.getFunctionInfo(), false, new ArrayList<Mutable<ILogicalExpression>>());
                for (Mutable<ILogicalExpression> arg : oldAggExpr.getArguments()) {
                    ILogicalExpression cloned = ((AbstractLogicalExpression) arg.getValue()).cloneExpression();
                    newAggFun.getArguments().add(new MutableObject<ILogicalExpression>(cloned));
                }
                aggOp.getVariables().add(newAggVar);
                aggOp.getExpressions().add(new MutableObject<ILogicalExpression>(newAggFun));
                context.computeAndSetTypeEnvironmentForOperator(aggOp);
                break;
            }
        }
    }
}
 
Example #3
Source File: ConvertAssignToAggregateRule.java    From vxquery with Apache License 2.0 6 votes vote down vote up
private AggregateOperator getAggregateOperator(IFunctionInfo aggregateFunction,
        Mutable<ILogicalExpression> aggregateArgs, LogicalVariable aggregateVariable) {
    List<LogicalVariable> aggregateVariables = new ArrayList<LogicalVariable>();
    aggregateVariables.add(aggregateVariable);

    List<Mutable<ILogicalExpression>> aggregateSequenceArgs = new ArrayList<Mutable<ILogicalExpression>>();
    aggregateSequenceArgs.add(aggregateArgs);

    List<Mutable<ILogicalExpression>> exprs = new ArrayList<Mutable<ILogicalExpression>>();
    ILogicalExpression aggregateExp = new AggregateFunctionCallExpression(aggregateFunction, false,
            aggregateSequenceArgs);
    Mutable<ILogicalExpression> aggregateExpRef = new MutableObject<ILogicalExpression>(aggregateExp);
    exprs.add(aggregateExpRef);

    return new AggregateOperator(aggregateVariables, exprs);
}
 
Example #4
Source File: ConvertAssignSortDistinctNodesToOperatorsRule.java    From vxquery with Apache License 2.0 6 votes vote down vote up
private AggregateOperator getAggregateOperator(LogicalVariable unnestVariable, LogicalVariable aggregateVariable) {
    List<LogicalVariable> aggregateVariables = new ArrayList<LogicalVariable>();
    aggregateVariables.add(aggregateVariable);

    List<Mutable<ILogicalExpression>> aggregateSequenceArgs = new ArrayList<Mutable<ILogicalExpression>>();
    Mutable<ILogicalExpression> unnestVariableRef = new MutableObject<ILogicalExpression>(
            new VariableReferenceExpression(unnestVariable));
    aggregateSequenceArgs.add(unnestVariableRef);

    List<Mutable<ILogicalExpression>> exprs = new ArrayList<Mutable<ILogicalExpression>>();
    ILogicalExpression aggregateExp = new AggregateFunctionCallExpression(BuiltinOperators.SEQUENCE, false,
            aggregateSequenceArgs);
    Mutable<ILogicalExpression> aggregateExpRef = new MutableObject<ILogicalExpression>(aggregateExp);
    exprs.add(aggregateExpRef);

    return new AggregateOperator(aggregateVariables, exprs);
}
 
Example #5
Source File: TestReloadingController.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests a reloading check with a positive result.
 */
@Test
public void testCheckForReloadingTrue()
{
    final EventListener<ReloadingEvent> l = createListenerMock();
    final EventListener<ReloadingEvent> lRemoved = createListenerMock();
    final MutableObject<ReloadingEvent> evRef = new MutableObject<>();
    expectEvent(l, evRef);
    EasyMock.expect(detector.isReloadingRequired()).andReturn(Boolean.TRUE);
    EasyMock.replay(detector, l, lRemoved);
    final ReloadingController ctrl = createController();
    ctrl.addEventListener(ReloadingEvent.ANY, lRemoved);
    ctrl.addEventListener(ReloadingEvent.ANY, l);
    assertTrue("Wrong result",
            ctrl.removeEventListener(ReloadingEvent.ANY, lRemoved));
    final Object testData = "Some test data";
    assertTrue("Wrong result", ctrl.checkForReloading(testData));
    assertTrue("Not in reloading state", ctrl.isInReloadingState());
    assertSame("Wrong event source", ctrl, evRef.getValue().getSource());
    assertSame("Wrong controller", ctrl, evRef.getValue().getController());
    assertEquals("Wrong event data", testData, evRef.getValue().getData());
    EasyMock.verify(l, lRemoved, detector);
}
 
Example #6
Source File: ManagedLedgerTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
private boolean updateCusorMetadataByCreatingMetadataLedger(MutableObject<ManagedCursorImpl> cursor2)
        throws InterruptedException {
    MutableObject<Boolean> failed = new MutableObject<>();
    failed.setValue(false);
    CountDownLatch createLedgerDoneLatch = new CountDownLatch(1);
    cursor2.getValue().createNewMetadataLedger(new VoidCallback() {

        @Override
        public void operationComplete() {
            createLedgerDoneLatch.countDown();
        }

        @Override
        public void operationFailed(ManagedLedgerException exception) {
            failed.setValue(true);
            createLedgerDoneLatch.countDown();
        }

    });
    createLedgerDoneLatch.await();
    return failed.getValue();
}
 
Example #7
Source File: MultiStoreResultValidator.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
public <T> Builder withAggregate(BiFunction<StoreResult, T, T> aggregator,
                                 T initialValue,
                                 Predicate<T> finalValuePredicate,
                                 Description description) {
    MutableObject<T> total = new MutableObject<>(initialValue);
    validators.add(new MultiStoreResultValidator() {

        @Override
        public void validate(List<StoreResult> storeResults) {
            for(StoreResult srr: storeResults) {
                total.setValue(aggregator.apply(srr, total.getValue()));
            }

            assertThat(finalValuePredicate.test(total.getValue()))
                    .describedAs(Description.mostRelevantDescription(description,
                                                                     String.format("actual value %s.",
                                                                                   total.getValue().toString())))
                    .isTrue();
        }
    });
    return this;
}
 
Example #8
Source File: InMemoryNodeModel.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Allows tracking all nodes selected by a key. This method evaluates the
 * specified key on the current nodes structure. For all selected nodes
 * corresponding {@code NodeSelector} objects are created, and they are
 * tracked. The returned collection of {@code NodeSelector} objects can be
 * used for interacting with the selected nodes.
 *
 * @param key the key for selecting the nodes to track
 * @param resolver the {@code NodeKeyResolver}
 * @return a collection with the {@code NodeSelector} objects for the new
 *         tracked nodes
 */
public Collection<NodeSelector> selectAndTrackNodes(final String key,
        final NodeKeyResolver<ImmutableNode> resolver)
{
    final Mutable<Collection<NodeSelector>> refSelectors =
            new MutableObject<>();
    boolean done;
    do
    {
        final TreeData current = structure.get();
        final List<ImmutableNode> nodes =
                resolver.resolveNodeKey(current.getRootNode(), key, current);
        if (nodes.isEmpty())
        {
            return Collections.emptyList();
        }
        done =
                structure.compareAndSet(
                        current,
                        createSelectorsForTrackedNodes(refSelectors, nodes,
                                current, resolver));
    } while (!done);
    return refSelectors.getValue();
}
 
Example #9
Source File: ConfigValues.java    From SkyblockAddons with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <E extends Enum<?>> void deserializeEnumValueFromOrdinal(MutableObject<E> value, String path) {
    try {
        Class<? extends Enum<?>> enumClass = value.getValue().getDeclaringClass();
        Method method = enumClass.getDeclaredMethod("values");
        Object valuesObject = method.invoke(null);
        E[] values = (E[])valuesObject;

        if (settingsConfig.has(path)) {
            int ordinal = settingsConfig.get(path).getAsInt();
            if (values.length > ordinal) {
                E enumValue = values[ordinal];
                if (enumValue != null) {
                    value.setValue(values[ordinal]);
                }
            }
        }
    } catch (Exception ex) {
        SkyblockAddons.getInstance().getLogger().error("Failed to deserialize path: "+ path);
        ex.printStackTrace();
    }
}
 
Example #10
Source File: ListCodec.java    From DataFixerUpper with MIT License 6 votes vote down vote up
@Override
public <T> DataResult<Pair<List<A>, T>> decode(final DynamicOps<T> ops, final T input) {
    return ops.getList(input).setLifecycle(Lifecycle.stable()).flatMap(stream -> {
        final ImmutableList.Builder<A> read = ImmutableList.builder();
        final Stream.Builder<T> failed = Stream.builder();
        // TODO: AtomicReference.getPlain/setPlain in java9+
        final MutableObject<DataResult<Unit>> result = new MutableObject<>(DataResult.success(Unit.INSTANCE, Lifecycle.stable()));

        stream.accept(t -> {
            final DataResult<Pair<A, T>> element = elementCodec.decode(ops, t);
            element.error().ifPresent(e -> failed.add(t));
            result.setValue(result.getValue().apply2stable((r, v) -> {
                read.add(v.getFirst());
                return r;
            }, element));
        });

        final ImmutableList<A> elements = read.build();
        final T errors = ops.createList(failed.build());

        final Pair<List<A>, T> pair = Pair.of(elements, errors);

        return result.getValue().map(unit -> pair).setPartial(pair);
    });
}
 
Example #11
Source File: XMLConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes this configuration from an XML document.
 *
 * @param docHelper the helper object with the document to be parsed
 * @param elemRefs a flag whether references to the XML elements should be set
 */
private void initProperties(final XMLDocumentHelper docHelper, final boolean elemRefs)
{
    final Document document = docHelper.getDocument();
    setPublicID(docHelper.getSourcePublicID());
    setSystemID(docHelper.getSourceSystemID());

    final ImmutableNode.Builder rootBuilder = new ImmutableNode.Builder();
    final MutableObject<String> rootValue = new MutableObject<>();
    final Map<ImmutableNode, Object> elemRefMap =
            elemRefs ? new HashMap<>() : null;
    final Map<String, String> attributes =
            constructHierarchy(rootBuilder, rootValue,
                    document.getDocumentElement(), elemRefMap, true, 0);
    attributes.remove(ATTR_SPACE_INTERNAL);
    final ImmutableNode top =
            rootBuilder.value(rootValue.getValue())
                    .addAttributes(attributes).create();
    getSubConfigurationParentModel().mergeRoot(top,
            document.getDocumentElement().getTagName(), elemRefMap,
            elemRefs ? docHelper : null, this);
}
 
Example #12
Source File: AttackThread.java    From attack-surface-detector-zap with Mozilla Public License 2.0 6 votes vote down vote up
private SiteNode sendAndProcess(HttpMessage msg) throws IOException, InvocationTargetException, InterruptedException {
    try {
        getHttpSender().sendAndReceive(msg, true);
    } catch (ConnectException ce) {
        String warningMsg = Constant.messages.getString("attacksurfacedetector.connectfailed.warning",
                msg.getRequestHeader().getURI().toString(), ce.getMessage());
        logger.warn(warningMsg);
        if (View.isInitialised()) {
            View.getSingleton().showWarningDialog(warningMsg);
        }
        return null;
    }
    ExtensionHistory extHistory = Control.getSingleton().getExtensionLoader().getExtension(ExtensionHistory.class);
    extHistory.addHistory(msg, HistoryReference.TYPE_ZAP_USER);
    HistoryReference hRef = msg.getHistoryRef();
    hRef.setNote("Endpoint generated by Attack Surface Detector");
    MutableObject<SiteNode> siteNodeWrapper = new MutableObject<>();
    SwingUtilities.invokeAndWait(() -> {
        // Needs to be done on the EDT
        SiteNode node = Model.getSingleton().getSession().getSiteTree().addPath(msg.getHistoryRef(), msg);
        siteNodeWrapper.setValue(node);
    });
    return siteNodeWrapper.getValue();
}
 
Example #13
Source File: StatefulFSMImpl.java    From statefulj with Apache License 2.0 6 votes vote down vote up
@Override
public Object onEvent(T stateful, String event, Object... parms) throws TooBusyException {
	ArrayList<Object> parmList = new ArrayList<Object>(Arrays.asList(parms));
	
	// Create a Mutable Object and add it to the Parameter List - it will be used
	// to return the returned value from the Controller as the FSM returns the State
	//
	MutableObject<T> returnValue = new MutableObject<T>();
	ArrayList<Object> invokeParmlist = new ArrayList<Object>(parms.length + 1);
	invokeParmlist.add(returnValue);
	invokeParmlist.addAll(parmList);
	
	// Call the FSM
	// 
	fsm.onEvent(stateful, event, invokeParmlist.toArray());
	return returnValue.getValue();
}
 
Example #14
Source File: TestPeriodicReloadingTrigger.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests whether the trigger can be started.
 */
@Test
public void testStart()
{
    final ScheduledFuture<Void> future = createFutureMock();
    final MutableObject<Runnable> refTask = new MutableObject<>();
    expectSchedule(null);
    EasyMock.expectLastCall().andAnswer(
            () -> {
                refTask.setValue((Runnable) EasyMock
                        .getCurrentArguments()[0]);
                return future;
            });
    EasyMock.expect(controller.checkForReloading(CTRL_PARAM)).andReturn(
            Boolean.FALSE);
    EasyMock.replay(future, controller, executor);
    final PeriodicReloadingTrigger trigger = createTrigger();
    trigger.start();
    assertTrue("Not started", trigger.isRunning());
    refTask.getValue().run();
    EasyMock.verify(future, controller, executor);
}
 
Example #15
Source File: InMemoryNodeModel.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tracks all nodes which are children of the node selected by the passed in
 * key. If the key selects exactly one node, for all children of this node
 * {@code NodeSelector} objects are created, and they become tracked nodes.
 * The returned collection of {@code NodeSelector} objects can be used for
 * interacting with the selected nodes.
 *
 * @param key the key for selecting the parent node whose children are to be
 *        tracked
 * @param resolver the {@code NodeKeyResolver}
 * @return a collection with the {@code NodeSelector} objects for the new
 *         tracked nodes
 */
public Collection<NodeSelector> trackChildNodes(final String key,
        final NodeKeyResolver<ImmutableNode> resolver)
{
    final Mutable<Collection<NodeSelector>> refSelectors =
            new MutableObject<>();
    boolean done;
    do
    {
        refSelectors.setValue(Collections.<NodeSelector> emptyList());
        final TreeData current = structure.get();
        final List<ImmutableNode> nodes =
                resolver.resolveNodeKey(current.getRootNode(), key, current);
        if (nodes.size() == 1)
        {
            final ImmutableNode node = nodes.get(0);
            done =
                    node.getChildren().isEmpty()
                            || structure.compareAndSet(
                                    current,
                                    createSelectorsForTrackedNodes(
                                            refSelectors,
                                            node.getChildren(), current,
                                            resolver));
        }
        else
        {
            done = true;
        }
    } while (!done);
    return refSelectors.getValue();
}
 
Example #16
Source File: InMemoryNodeModel.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new data object with a tracked child node of the given parent
 * node. If such a child node already exists, it is used. Otherwise, a new
 * one is created.
 *
 * @param current the current {@code TreeData} object
 * @param parent the parent node
 * @param childName the name of the child node
 * @param resolver the {@code NodeKeyResolver}
 * @param refSelector here the newly created {@code NodeSelector} is
 *        returned
 * @return the new {@code TreeData} instance
 */
private static TreeData createDataWithTrackedChildNode(final TreeData current,
        final ImmutableNode parent, final String childName,
        final NodeKeyResolver<ImmutableNode> resolver,
        final MutableObject<NodeSelector> refSelector)
{
    TreeData newData;
    final List<ImmutableNode> namedChildren =
            current.getChildren(parent, childName);
    if (!namedChildren.isEmpty())
    {
        newData =
                updateDataWithNewTrackedNode(current, namedChildren.get(0),
                        resolver, refSelector);
    }
    else
    {
        final ImmutableNode child =
                new ImmutableNode.Builder().name(childName).create();
        final ModelTransaction tx = new ModelTransaction(current, null, resolver);
        tx.addAddNodeOperation(parent, child);
        newData =
                updateDataWithNewTrackedNode(tx.execute(), child, resolver,
                        refSelector);
    }
    return newData;
}
 
Example #17
Source File: ConvertAssignSortDistinctNodesToOperatorsRule.java    From vxquery with Apache License 2.0 5 votes vote down vote up
private UnnestOperator getUnnestOperator(LogicalVariable inputVariable, LogicalVariable unnestVariable) {
    VariableReferenceExpression inputVre = new VariableReferenceExpression(inputVariable);

    List<Mutable<ILogicalExpression>> iterateArgs = new ArrayList<Mutable<ILogicalExpression>>();
    iterateArgs.add(new MutableObject<ILogicalExpression>(inputVre));

    ILogicalExpression unnestExp = new UnnestingFunctionCallExpression(BuiltinOperators.ITERATE, iterateArgs);
    Mutable<ILogicalExpression> unnestExpRef = new MutableObject<ILogicalExpression>(unnestExp);

    return new UnnestOperator(unnestVariable, unnestExpRef);
}
 
Example #18
Source File: ConvertAssignSortDistinctNodesToOperatorsRule.java    From vxquery with Apache License 2.0 5 votes vote down vote up
private AssignOperator getAssignOperator(LogicalVariable unnestVariable, LogicalVariable outputVariable,
        IFunctionInfo inputFunction) {
    List<Mutable<ILogicalExpression>> nodeArgs = new ArrayList<Mutable<ILogicalExpression>>();
    nodeArgs.add(new MutableObject<ILogicalExpression>(new VariableReferenceExpression(unnestVariable)));
    ScalarFunctionCallExpression unctionExpression = new ScalarFunctionCallExpression(inputFunction, nodeArgs);
    Mutable<ILogicalExpression> nodeTreeIdExpression = new MutableObject<ILogicalExpression>(unctionExpression);
    return new AssignOperator(outputVariable, nodeTreeIdExpression);
}
 
Example #19
Source File: InMemoryNodeModel.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tracks a node which is a child of another node selected by the passed in
 * key. If the selected node has a child node with this name, it is tracked
 * and its selector is returned. Otherwise, a new child node with this name
 * is created first.
 *
 * @param key the key for selecting the parent node
 * @param childName the name of the child node
 * @param resolver the {@code NodeKeyResolver}
 * @return the {@code NodeSelector} for the tracked child node
 * @throws ConfigurationRuntimeException if the passed in key does not
 *         select a single node
 */
public NodeSelector trackChildNodeWithCreation(final String key,
        final String childName, final NodeKeyResolver<ImmutableNode> resolver)
{
    final MutableObject<NodeSelector> refSelector =
            new MutableObject<>();
    boolean done;

    do
    {
        final TreeData current = structure.get();
        final List<ImmutableNode> nodes =
                resolver.resolveNodeKey(current.getRootNode(), key, current);
        if (nodes.size() != 1)
        {
            throw new ConfigurationRuntimeException(
                    "Key does not select a single node: " + key);
        }

        final ImmutableNode parent = nodes.get(0);
        final TreeData newData =
                createDataWithTrackedChildNode(current, parent, childName,
                        resolver, refSelector);

        done = structure.compareAndSet(current, newData);
    } while (!done);

    return refSelector.getValue();
}
 
Example #20
Source File: InMemoryNodeModel.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a tracked node that has already been resolved to the specified data
 * object.
 *
 * @param current the current {@code TreeData} object
 * @param node the node in question
 * @param resolver the {@code NodeKeyResolver}
 * @param refSelector here the newly created {@code NodeSelector} is
 *        returned
 * @return the new {@code TreeData} instance
 */
private static TreeData updateDataWithNewTrackedNode(final TreeData current,
        final ImmutableNode node, final NodeKeyResolver<ImmutableNode> resolver,
        final MutableObject<NodeSelector> refSelector)
{
    final NodeSelector selector =
            new NodeSelector(resolver.nodeKey(node,
                    new HashMap<ImmutableNode, String>(), current));
    refSelector.setValue(selector);
    final NodeTracker newTracker =
            current.getNodeTracker().trackNodes(
                    Collections.singleton(selector),
                    Collections.singleton(node));
    return current.updateNodeTracker(newTracker);
}
 
Example #21
Source File: ConvertFromAlgebricksExpressionsRule.java    From vxquery with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private boolean convertAlgebricksExpression(Mutable<ILogicalExpression> searchM, IFunctionInfo funcInfo,
        boolean isBoolean) {
    AbstractFunctionCallExpression searchFunction = (AbstractFunctionCallExpression) searchM.getValue();
    searchFunction.setFunctionInfo(funcInfo);

    if (isBoolean) {
        ScalarFunctionCallExpression functionCallExp = new ScalarFunctionCallExpression(
                BuiltinFunctions.FN_BOOLEAN_1, new MutableObject<ILogicalExpression>(searchM.getValue()));
        searchM.setValue(functionCallExp);
    }
    return true;
}
 
Example #22
Source File: TestReloadingController.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that no further checks are performed when already in reloading
 * state.
 */
@Test
public void testCheckForReloadingInReloadingState()
{
    final EventListener<ReloadingEvent> l = createListenerMock();
    EasyMock.expect(detector.isReloadingRequired()).andReturn(Boolean.TRUE);
    expectEvent(l, new MutableObject<ReloadingEvent>());
    EasyMock.replay(detector, l);
    final ReloadingController ctrl = createController();
    ctrl.addEventListener(ReloadingEvent.ANY, l);
    assertTrue("Wrong result (1)", ctrl.checkForReloading(1));
    assertTrue("Wrong result (2)", ctrl.checkForReloading(2));
    EasyMock.verify(detector, l);
}
 
Example #23
Source File: DynamicLike.java    From DataFixerUpper with MIT License 5 votes vote down vote up
public <R> DataResult<R> readMap(final DataResult<R> empty, final Function3<R, Dynamic<T>, Dynamic<T>, DataResult<R>> combiner) {
    return asMapOpt().flatMap(stream -> {
        // TODO: AtomicReference.getPlain/setPlain in java9+
        final MutableObject<DataResult<R>> result = new MutableObject<>(empty);
        stream.forEach(p -> result.setValue(result.getValue().flatMap(r -> combiner.apply(r, p.getFirst(), p.getSecond()))));
        return result.getValue();
    });
}
 
Example #24
Source File: CompoundListCodec.java    From DataFixerUpper with MIT License 5 votes vote down vote up
@Override
public <T> DataResult<Pair<List<Pair<K, V>>, T>> decode(final DynamicOps<T> ops, final T input) {
    return ops.getMapEntries(input).flatMap(map -> {
        final ImmutableList.Builder<Pair<K, V>> read = ImmutableList.builder();
        final ImmutableMap.Builder<T, T> failed = ImmutableMap.builder();

        // TODO: AtomicReference.getPlain/setPlain in java9+
        final MutableObject<DataResult<Unit>> result = new MutableObject<>(DataResult.success(Unit.INSTANCE, Lifecycle.experimental()));

        map.accept((key, value) -> {
            final DataResult<K> k = keyCodec.parse(ops, key);
            final DataResult<V> v = elementCodec.parse(ops, value);

            final DataResult<Pair<K, V>> readEntry = k.apply2stable(Pair::new, v);

            readEntry.error().ifPresent(e -> failed.put(key, value));

            result.setValue(result.getValue().apply2stable((u, e) -> {
                read.add(e);
                return u;
            }, readEntry));
        });

        final ImmutableList<Pair<K, V>> elements = read.build();
        final T errors = ops.createMap(failed.build());

        final Pair<List<Pair<K, V>>, T> pair = Pair.of(elements, errors);

        return result.getValue().map(unit -> pair).setPartial(pair);
    });
}
 
Example #25
Source File: DynamicOps.java    From DataFixerUpper with MIT License 5 votes vote down vote up
default DataResult<T> mergeToMap(final T map, final MapLike<T> values) {
    // TODO: AtomicReference.getPlain/setPlain in java9+
    final MutableObject<DataResult<T>> result = new MutableObject<>(DataResult.success(map));

    values.entries().forEach(entry ->
        result.setValue(result.getValue().flatMap(r -> mergeToMap(r, entry.getFirst(), entry.getSecond())))
    );
    return result.getValue();
}
 
Example #26
Source File: DynamicOps.java    From DataFixerUpper with MIT License 5 votes vote down vote up
default <R> DataResult<R> readMap(final T input, final DataResult<R> empty, final Function3<R, T, T, DataResult<R>> combiner) {
    return getMapValues(input).flatMap(stream -> {
        // TODO: AtomicReference.getPlain/setPlain in java9+
        final MutableObject<DataResult<R>> result = new MutableObject<>(empty);
        stream.forEach(p -> result.setValue(result.getValue().flatMap(r -> combiner.apply(r, p.getFirst(), p.getSecond()))));
        return result.getValue();
    });
}
 
Example #27
Source File: ManagedLedgerTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
/**
 * It verifies that managed-cursor can recover metadata-version if it fails to update due to version conflict. This
 * test verifies that version recovery happens if checkOwnership supplier is passed while creating managed-ledger.
 *
 * @param checkOwnershipFlag
 * @throws Exception
 */
@Test(dataProvider = "checkOwnershipFlag")
public void recoverMLWithBadVersion(boolean checkOwnershipFlag) throws Exception {

    ManagedLedgerFactoryConfig conf = new ManagedLedgerFactoryConfig();
    ManagedLedgerFactoryImpl factory1 = new ManagedLedgerFactoryImpl(bkc, zkc, conf);
    ManagedLedgerFactoryImpl factory2 = new ManagedLedgerFactoryImpl(bkc, zkc, conf);

    final MutableObject<ManagedLedger> ledger1 = new MutableObject<>(), ledger2 = new MutableObject<>();
    final MutableObject<ManagedCursorImpl> cursor1 = new MutableObject<>(), cursor2 = new MutableObject<>();

    createLedger(factory1, ledger1, cursor1, checkOwnershipFlag);
    ledger1.getValue().addEntry("test1".getBytes(Encoding));
    ledger1.getValue().addEntry("test2".getBytes(Encoding));
    Entry entry = cursor1.getValue().readEntries(1).get(0);
    cursor1.getValue().delete(entry.getPosition());

    createLedger(factory2, ledger2, cursor2, checkOwnershipFlag);
    entry = cursor2.getValue().readEntries(1).get(0);

    // 1. closing cursor will change the zk-version
    cursor1.getValue().close();

    // 2. try to creatCursorLedger which should fail first time because of BadVersionException
    // However, if checkOwnershipFlag is eanbled the managed-cursor will reover from that exception.
    boolean isFailed = updateCusorMetadataByCreatingMetadataLedger(cursor2);
    Assert.assertTrue(isFailed);

    isFailed = updateCusorMetadataByCreatingMetadataLedger(cursor2);
    if (checkOwnershipFlag) {
        Assert.assertFalse(isFailed);
    } else {
        Assert.assertTrue(isFailed);
    }

    log.info("Test completed");
}
 
Example #28
Source File: TestReloadingController.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Prepares the given event listener mock to expect an event notification.
 * The event received is stored in the given mutable object.
 *
 * @param l the listener mock
 * @param evRef the reference where to store the event
 */
private void expectEvent(final EventListener<ReloadingEvent> l,
        final MutableObject<ReloadingEvent> evRef)
{
    l.onEvent(EasyMock.anyObject(ReloadingEvent.class));
    EasyMock.expectLastCall().andAnswer(() -> {
        evRef.setValue((ReloadingEvent) EasyMock.getCurrentArguments()[0]);
        return null;
    });
}
 
Example #29
Source File: TestPropertiesConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests setting an IOFactory that uses a specialized writer.
 */
@Test
public void testSetIOFactoryWriter() throws ConfigurationException, IOException
{
    final MutableObject<Writer> propertiesWriter = new MutableObject<>();
    conf.setIOFactory(new PropertiesConfiguration.IOFactory()
    {
        @Override
        public PropertiesConfiguration.PropertiesReader createPropertiesReader(
                final Reader in)
        {
            throw new UnsupportedOperationException("Unexpected call!");
        }

        @Override
        public PropertiesConfiguration.PropertiesWriter createPropertiesWriter(
                final Writer out, final ListDelimiterHandler handler)
        {
            try
            {
                final PropertiesWriterTestImpl propWriter = new PropertiesWriterTestImpl(handler);
                propertiesWriter.setValue(propWriter);
                return propWriter;
            }
            catch (final IOException e)
            {
                return null;
            }
        }
    });
    new FileHandler(conf).save(new StringWriter());
    propertiesWriter.getValue().close();
    checkSavedConfig();
}
 
Example #30
Source File: ConvertAssignToAggregateRule.java    From vxquery with Apache License 2.0 5 votes vote down vote up
private UnnestOperator getUnnestOperator(LogicalVariable inputVariable, LogicalVariable unnestVariable) {
    VariableReferenceExpression inputVre = new VariableReferenceExpression(inputVariable);

    List<Mutable<ILogicalExpression>> iterateArgs = new ArrayList<Mutable<ILogicalExpression>>();
    iterateArgs.add(new MutableObject<ILogicalExpression>(inputVre));

    ILogicalExpression unnestExp = new UnnestingFunctionCallExpression(BuiltinOperators.ITERATE, iterateArgs);
    Mutable<ILogicalExpression> unnestExpRef = new MutableObject<ILogicalExpression>(unnestExp);

    return new UnnestOperator(unnestVariable, unnestExpRef);
}