Search in sources :

Example 51 with MutableBoolean

use of org.apache.commons.lang3.mutable.MutableBoolean in project hbase by apache.

the class TestSplitWalDataLoss method test.

@Test
public void test() throws IOException, InterruptedException {
    final HRegionServer rs = testUtil.getRSForFirstRegionInTable(tableName);
    final HRegion region = (HRegion) rs.getRegions(tableName).get(0);
    HRegion spiedRegion = spy(region);
    final MutableBoolean flushed = new MutableBoolean(false);
    final MutableBoolean reported = new MutableBoolean(false);
    doAnswer(new Answer<FlushResult>() {

        @Override
        public FlushResult answer(InvocationOnMock invocation) throws Throwable {
            synchronized (flushed) {
                flushed.setValue(true);
                flushed.notifyAll();
            }
            synchronized (reported) {
                while (!reported.booleanValue()) {
                    reported.wait();
                }
            }
            rs.getWAL(region.getRegionInfo()).abortCacheFlush(region.getRegionInfo().getEncodedNameAsBytes());
            throw new DroppedSnapshotException("testcase");
        }
    }).when(spiedRegion).internalFlushCacheAndCommit(Matchers.<WAL>any(), Matchers.<MonitoredTask>any(), Matchers.<PrepareFlushResult>any(), Matchers.<Collection<HStore>>any());
    // Find region key; don't pick up key for hbase:meta by mistake.
    String key = null;
    for (Map.Entry<String, HRegion> entry : rs.getOnlineRegions().entrySet()) {
        if (entry.getValue().getRegionInfo().getTable().equals(this.tableName)) {
            key = entry.getKey();
            break;
        }
    }
    rs.getOnlineRegions().put(key, spiedRegion);
    Connection conn = testUtil.getConnection();
    try (Table table = conn.getTable(tableName)) {
        table.put(new Put(Bytes.toBytes("row0")).addColumn(family, qualifier, Bytes.toBytes("val0")));
    }
    long oldestSeqIdOfStore = region.getOldestSeqIdOfStore(family);
    LOG.info("CHANGE OLDEST " + oldestSeqIdOfStore);
    assertTrue(oldestSeqIdOfStore > HConstants.NO_SEQNUM);
    rs.getMemStoreFlusher().requestFlush(spiedRegion, FlushLifeCycleTracker.DUMMY);
    synchronized (flushed) {
        while (!flushed.booleanValue()) {
            flushed.wait();
        }
    }
    try (Table table = conn.getTable(tableName)) {
        table.put(new Put(Bytes.toBytes("row1")).addColumn(family, qualifier, Bytes.toBytes("val1")));
    }
    long now = EnvironmentEdgeManager.currentTime();
    rs.tryRegionServerReport(now - 500, now);
    synchronized (reported) {
        reported.setValue(true);
        reported.notifyAll();
    }
    while (testUtil.getRSForFirstRegionInTable(tableName) == rs) {
        Thread.sleep(100);
    }
    try (Table table = conn.getTable(tableName)) {
        Result result = table.get(new Get(Bytes.toBytes("row0")));
        assertArrayEquals(Bytes.toBytes("val0"), result.getValue(family, qualifier));
    }
}
Also used : Table(org.apache.hadoop.hbase.client.Table) DroppedSnapshotException(org.apache.hadoop.hbase.DroppedSnapshotException) MutableBoolean(org.apache.commons.lang3.mutable.MutableBoolean) Connection(org.apache.hadoop.hbase.client.Connection) PrepareFlushResult(org.apache.hadoop.hbase.regionserver.HRegion.PrepareFlushResult) FlushResult(org.apache.hadoop.hbase.regionserver.HRegion.FlushResult) Put(org.apache.hadoop.hbase.client.Put) PrepareFlushResult(org.apache.hadoop.hbase.regionserver.HRegion.PrepareFlushResult) FlushResult(org.apache.hadoop.hbase.regionserver.HRegion.FlushResult) Result(org.apache.hadoop.hbase.client.Result) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Get(org.apache.hadoop.hbase.client.Get) Map(java.util.Map) Test(org.junit.Test)

Example 52 with MutableBoolean

use of org.apache.commons.lang3.mutable.MutableBoolean in project midpoint by Evolveum.

the class SearchEvaluator method evaluate.

public <T extends ObjectType> PipelineData evaluate(SearchExpressionType searchExpression, PipelineData input, ExecutionContext context, OperationResult globalResult) throws ScriptExecutionException, SchemaException, ConfigurationException, ObjectNotFoundException, CommunicationException, SecurityViolationException, ExpressionEvaluationException {
    Validate.notNull(searchExpression.getType());
    ExpressionProfile expressionProfile = MiscSchemaUtil.getExpressionProfile();
    List<PipelineItem> data = input.getData();
    if (data.isEmpty()) {
        // TODO fix this brutal hack (with dummyValue)
        PrismContainerValue<?> dummyValue = prismContext.itemFactory().createContainerValue();
        PipelineItem dummyItem = new PipelineItem(dummyValue, PipelineData.newOperationResult(), context.getInitialVariables());
        data = Collections.singletonList(dummyItem);
    }
    final PipelineData outputData = PipelineData.createEmpty();
    final MutableBoolean atLeastOne = new MutableBoolean(false);
    for (PipelineItem item : data) {
        // TODO variables from current item
        // TODO operation result handling (global vs local)
        boolean noFetch = expressionHelper.getArgumentAsBoolean(searchExpression.getParameter(), PARAM_NO_FETCH, input, context, false, "search", globalResult);
        Class<T> objectClass = ObjectTypes.getObjectTypeFromTypeQName(searchExpression.getType()).getClassDefinition();
        ObjectQuery unresolvedObjectQuery = null;
        if (searchExpression.getQuery() != null) {
            try {
                unresolvedObjectQuery = context.getQueryConverter().createObjectQuery(objectClass, searchExpression.getQuery());
            } catch (SchemaException e) {
                throw new ScriptExecutionException("Couldn't parse object query. Reason: " + e.getMessage(), e);
            }
        } else if (searchExpression.getSearchFilter() != null) {
            unresolvedObjectQuery = prismContext.queryFactory().createQuery();
            try {
                ObjectFilter filter = prismContext.getQueryConverter().parseFilter(searchExpression.getSearchFilter(), objectClass);
                unresolvedObjectQuery.setFilter(filter);
            } catch (SchemaException e) {
                throw new ScriptExecutionException("Couldn't parse object query. Reason: " + e.getMessage(), e);
            }
        }
        ObjectQuery objectQuery;
        if (unresolvedObjectQuery != null) {
            VariablesMap variables = new VariablesMap();
            // noinspection unchecked
            item.getVariables().forEach((name, value) -> variables.put(name, cloneIfNecessary(name, value)));
            try {
                objectQuery = ExpressionUtil.evaluateQueryExpressions(unresolvedObjectQuery, variables, expressionProfile, expressionFactory, prismContext, "bulk action query", context.getTask(), globalResult);
            } catch (SchemaException | ObjectNotFoundException | ExpressionEvaluationException | CommunicationException | ConfigurationException | SecurityViolationException e) {
                // TODO continue on any error?
                throw new ScriptExecutionException("Couldn't evaluate expressions in object query: " + e.getMessage(), e);
            }
        } else {
            objectQuery = null;
        }
        final String variableName = searchExpression.getVariable();
        ResultHandler<T> handler = (object, parentResult) -> {
            context.checkTaskStop();
            atLeastOne.setValue(true);
            if (searchExpression.getScriptingExpression() != null) {
                if (variableName != null) {
                // TODO
                }
                JAXBElement<?> childExpression = searchExpression.getScriptingExpression();
                try {
                    PipelineData expressionResult = scriptingExpressionEvaluator.evaluateExpression((ScriptingExpressionType) childExpression.getValue(), PipelineData.create(object.getValue(), item.getVariables()), context, globalResult);
                    if (!BooleanUtils.isFalse(searchExpression.isAggregateOutput())) {
                        outputData.addAllFrom(expressionResult);
                    }
                    globalResult.setSummarizeSuccesses(true);
                    globalResult.summarize();
                } catch (ScriptExecutionException | SchemaException | ConfigurationException | ObjectNotFoundException | CommunicationException | SecurityViolationException | ExpressionEvaluationException e) {
                    // todo think about this
                    if (context.isContinueOnAnyError()) {
                        LoggingUtils.logUnexpectedException(LOGGER, "Exception when evaluating item from search result list.", e);
                    } else {
                        throw new SystemException(e);
                    }
                }
            } else {
                outputData.addValue(object.getValue(), item.getVariables());
            }
            return true;
        };
        try {
            Collection<SelectorOptions<GetOperationOptions>> options = operationsHelper.createGetOptions(searchExpression.getOptions(), noFetch);
            modelService.searchObjectsIterative(objectClass, objectQuery, handler, options, context.getTask(), globalResult);
        } catch (SchemaException | ObjectNotFoundException | SecurityViolationException | CommunicationException | ConfigurationException | ExpressionEvaluationException e) {
            // TODO continue on any error?
            throw new ScriptExecutionException("Couldn't execute searchObjects operation: " + e.getMessage(), e);
        }
    }
    if (atLeastOne.isFalse()) {
        // temporary hack, this will be configurable
        context.println("Warning: no matching object found");
    }
    return outputData;
}
Also used : ObjectType(com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType) OperationsHelper(com.evolveum.midpoint.model.impl.scripting.helpers.OperationsHelper) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) Autowired(org.springframework.beans.factory.annotation.Autowired) BooleanUtils(org.apache.commons.lang3.BooleanUtils) Trace(com.evolveum.midpoint.util.logging.Trace) com.evolveum.midpoint.util.exception(com.evolveum.midpoint.util.exception) ExpressionHelper(com.evolveum.midpoint.model.impl.scripting.helpers.ExpressionHelper) ObjectFilter(com.evolveum.midpoint.prism.query.ObjectFilter) MiscSchemaUtil(com.evolveum.midpoint.schema.util.MiscSchemaUtil) PipelineItem(com.evolveum.midpoint.model.api.PipelineItem) VariablesMap(com.evolveum.midpoint.schema.expression.VariablesMap) ResultHandler(com.evolveum.midpoint.schema.ResultHandler) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) Collection(java.util.Collection) JAXBElement(javax.xml.bind.JAXBElement) ExecutionContext(com.evolveum.midpoint.model.impl.scripting.ExecutionContext) LoggingUtils(com.evolveum.midpoint.util.logging.LoggingUtils) PipelineData(com.evolveum.midpoint.model.impl.scripting.PipelineData) List(java.util.List) Component(org.springframework.stereotype.Component) ExpressionFactory(com.evolveum.midpoint.repo.common.expression.ExpressionFactory) PrismContainerValue(com.evolveum.midpoint.prism.PrismContainerValue) ScriptingExpressionType(com.evolveum.midpoint.xml.ns._public.model.scripting_3.ScriptingExpressionType) MutableBoolean(org.apache.commons.lang.mutable.MutableBoolean) ExpressionUtil(com.evolveum.midpoint.repo.common.expression.ExpressionUtil) GetOperationOptions(com.evolveum.midpoint.schema.GetOperationOptions) ExpressionProfile(com.evolveum.midpoint.schema.expression.ExpressionProfile) ObjectTypes(com.evolveum.midpoint.schema.constants.ObjectTypes) VariablesUtil.cloneIfNecessary(com.evolveum.midpoint.model.impl.scripting.VariablesUtil.cloneIfNecessary) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) SearchExpressionType(com.evolveum.midpoint.xml.ns._public.model.scripting_3.SearchExpressionType) Collections(java.util.Collections) Validate(org.apache.commons.lang.Validate) TraceManager(com.evolveum.midpoint.util.logging.TraceManager) PipelineData(com.evolveum.midpoint.model.impl.scripting.PipelineData) ScriptingExpressionType(com.evolveum.midpoint.xml.ns._public.model.scripting_3.ScriptingExpressionType) VariablesMap(com.evolveum.midpoint.schema.expression.VariablesMap) MutableBoolean(org.apache.commons.lang.mutable.MutableBoolean) ExpressionProfile(com.evolveum.midpoint.schema.expression.ExpressionProfile) ObjectFilter(com.evolveum.midpoint.prism.query.ObjectFilter) JAXBElement(javax.xml.bind.JAXBElement) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) PipelineItem(com.evolveum.midpoint.model.api.PipelineItem) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions)

Example 53 with MutableBoolean

use of org.apache.commons.lang3.mutable.MutableBoolean in project AgriCraft by AgriCraft.

the class VanillaSeedConversionHandler method runPlantingConversion.

protected boolean runPlantingConversion(World world, BlockPos pos, ItemStack stack, PlayerEntity player, Hand hand) {
    return !AgriCraft.instance.getConfig().convertSeedsOnlyInAnalyzer() && AgriApi.getGenomeAdapterizer().valueOf(stack).map(seed -> {
        // The player is attempting to plant a seed, convert it to an agricraft crop
        return AgriApi.getSoil(world, pos.down()).map(soil -> {
            // check if there are crop sticks above
            MutableBoolean consumed = new MutableBoolean(false);
            boolean cropSticks = AgriApi.getCrop(world, pos).map(crop -> {
                if (!crop.hasPlant() && !crop.isCrossCrop() && crop.plantGenome(seed, player)) {
                    if (player == null || !player.isCreative()) {
                        stack.shrink(1);
                        consumed.setValue(true);
                    }
                    if (player != null) {
                        player.swingArm(hand);
                    }
                }
                return true;
            }).orElse(false);
            // if there were crop sticks, return the result of the crop sticks action
            if (cropSticks) {
                return consumed.getValue();
            }
            // no crop sticks, try planting as a plant
            BlockState newState = AgriCraft.instance.getModBlockRegistry().crop_plant.getStateForPlacement(world, pos);
            if (newState != null && world.setBlockState(pos, newState, 11)) {
                boolean planted = AgriApi.getCrop(world, pos).map(crop -> crop.plantGenome(seed, player)).orElse(false);
                if (planted) {
                    // reduce stack size
                    if (player == null || !player.isCreative()) {
                        stack.shrink(1);
                    }
                    // return success
                    return true;
                } else {
                    world.setBlockState(pos, Blocks.AIR.getDefaultState());
                }
            }
            return false;
        }).orElse(false);
    }).orElse(false);
}
Also used : AgriCraft(com.infinityraider.agricraft.AgriCraft) AgriApi(com.infinityraider.agricraft.api.v1.AgriApi) PlayerEntity(net.minecraft.entity.player.PlayerEntity) LivingEntity(net.minecraft.entity.LivingEntity) Item(net.minecraft.item.Item) World(net.minecraft.world.World) Set(java.util.Set) BlockPos(net.minecraft.util.math.BlockPos) Sets(com.google.common.collect.Sets) Blocks(net.minecraft.block.Blocks) ItemStack(net.minecraft.item.ItemStack) TileEntitySeedAnalyzer(com.infinityraider.agricraft.content.core.TileEntitySeedAnalyzer) EventPriority(net.minecraftforge.eventbus.api.EventPriority) Event(net.minecraftforge.eventbus.api.Event) TileEntity(net.minecraft.tileentity.TileEntity) Hand(net.minecraft.util.Hand) SubscribeEvent(net.minecraftforge.eventbus.api.SubscribeEvent) BlockState(net.minecraft.block.BlockState) PlayerInteractEvent(net.minecraftforge.event.entity.player.PlayerInteractEvent) MutableBoolean(org.apache.commons.lang3.mutable.MutableBoolean) IAgriSeedItem(com.infinityraider.agricraft.api.v1.content.items.IAgriSeedItem) BlockState(net.minecraft.block.BlockState) MutableBoolean(org.apache.commons.lang3.mutable.MutableBoolean)

Example 54 with MutableBoolean

use of org.apache.commons.lang3.mutable.MutableBoolean in project janusgraph by JanusGraph.

the class CloseableIteratorUtilsTest method testFilter.

@Test
public void testFilter() {
    MutableBoolean closed = new MutableBoolean(false);
    Iterator<Integer> raw = IntStream.range(0, 10).iterator();
    CloseableIterator<Integer> unfiltered = new CloseableIterator<Integer>() {

        @Override
        public boolean hasNext() {
            return raw.hasNext();
        }

        @Override
        public Integer next() {
            return raw.next();
        }

        @Override
        public void close() {
            closed.setTrue();
        }
    };
    CloseableIterator iterator = CloseableIteratorUtils.filter(unfiltered, num -> num % 2 == 0);
    for (int i = 0; i < 10; i += 2) {
        assertEquals(i, iterator.next());
    }
    assertFalse(closed.getValue());
    assertFalse(iterator.hasNext());
    assertTrue(closed.getValue());
}
Also used : CloseableIterator(org.apache.tinkerpop.gremlin.structure.util.CloseableIterator) MutableBoolean(org.apache.commons.lang3.mutable.MutableBoolean) Test(org.junit.jupiter.api.Test)

Example 55 with MutableBoolean

use of org.apache.commons.lang3.mutable.MutableBoolean in project apex-malhar by apache.

the class SimpleDoneQueryQueueManagerTest method simpleEnqueueDequeue.

@Test
public void simpleEnqueueDequeue() {
    SimpleDoneQueueManager<Query, Void> sdqqm = new SimpleDoneQueueManager<Query, Void>();
    sdqqm.setup(null);
    sdqqm.beginWindow(0);
    Query query = new MockQuery("1");
    sdqqm.enqueue(query, null, new MutableBoolean(false));
    QueryBundle<Query, Void, MutableBoolean> qb = sdqqm.dequeue();
    Assert.assertEquals("Should return same query.", query, qb.getQuery());
    qb = sdqqm.dequeue();
    Assert.assertEquals("Should return back null.", null, qb);
    sdqqm.endWindow();
    sdqqm.beginWindow(1);
    qb = sdqqm.dequeue();
    Assert.assertEquals("Should return same query.", query, qb.getQuery());
    qb = sdqqm.dequeue();
    Assert.assertEquals("Should return back null.", null, qb);
    sdqqm.endWindow();
    sdqqm.teardown();
}
Also used : Query(org.apache.apex.malhar.lib.appdata.schemas.Query) MutableBoolean(org.apache.commons.lang3.mutable.MutableBoolean) Test(org.junit.Test)

Aggregations

MutableBoolean (org.apache.commons.lang3.mutable.MutableBoolean)107 Test (org.junit.Test)28 Path (java.nio.file.Path)26 Test (org.junit.jupiter.api.Test)17 IOException (java.io.IOException)16 ArrayList (java.util.ArrayList)12 Query (org.apache.apex.malhar.lib.appdata.schemas.Query)11 HyracksDataException (org.apache.hyracks.api.exceptions.HyracksDataException)11 List (java.util.List)9 AMutableInt64 (org.apache.asterix.om.base.AMutableInt64)8 MutableInt (org.apache.commons.lang3.mutable.MutableInt)7 MutableLong (org.apache.commons.lang3.mutable.MutableLong)7 Collections (java.util.Collections)6 AMutableDouble (org.apache.asterix.om.base.AMutableDouble)6 Set (java.util.Set)5 Assertions.assertFalse (org.junit.jupiter.api.Assertions.assertFalse)5 Assertions.assertTrue (org.junit.jupiter.api.Assertions.assertTrue)5 PageCache (org.neo4j.io.pagecache.PageCache)5 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)4 ClassAd (org.apache.asterix.external.classad.ClassAd)4