Search in sources :

Example 81 with Predicate

use of java.util.function.Predicate in project graal by oracle.

the class SuspensionFilterTest method testSourceFilter.

@Test
public void testSourceFilter() {
    final Source source1 = Source.newBuilder(InstrumentationTestLanguage.ID, "ROOT(\n" + "  DEFINE(foo1,\n" + "    STATEMENT(CONSTANT(43))\n" + "  ))\n", "Source1").buildLiteral();
    final Source source2 = Source.newBuilder(InstrumentationTestLanguage.ID, "ROOT(\n" + "  DEFINE(foo2,\n" + "    STATEMENT(CONSTANT(44))\n" + "  ))\n", "Source2").buildLiteral();
    final Source source3 = testSource("ROOT(\n" + "  CALL(foo1),\n" + "  CALL(foo2),\n" + "  STATEMENT(CALL(foo1)),\n" + "  STATEMENT(CALL(foo2)),\n" + "  STATEMENT(CALL(foo1)),\n" + "  STATEMENT(CALL(foo2)),\n" + "  STATEMENT(CONSTANT(100))\n" + ")\n");
    try (DebuggerSession session = startSession()) {
        // Filter out all sections
        SuspensionFilter suspensionFilter = SuspensionFilter.newBuilder().sourceIs(s -> false).build();
        session.setSteppingFilter(suspensionFilter);
        session.suspendNextExecution();
        startEval(source1);
        expectDone();
        startEval(source2);
        expectDone();
        startEval(source3);
        expectDone();
        Predicate<com.oracle.truffle.api.source.Source> filterSource1 = source -> {
            return source.getName().indexOf("Source1") < 0;
        };
        suspensionFilter = SuspensionFilter.newBuilder().sourceIs(filterSource1).build();
        session.setSteppingFilter(suspensionFilter);
        session.suspendNextExecution();
        startEval(source3);
        // Skip foo1 and suspend in foo2:
        expectSuspended((SuspendedEvent event) -> {
            checkState(event, 3, true, "STATEMENT(CONSTANT(44))");
            event.prepareStepOver(1);
        });
        expectSuspended((SuspendedEvent event) -> {
            checkState(event, 3, false, "CALL(foo2)");
            event.prepareStepInto(1);
        });
        expectSuspended((SuspendedEvent event) -> {
            checkState(event, 4, true, "STATEMENT(CALL(foo1))");
            event.prepareStepInto(1);
        });
        expectSuspended((SuspendedEvent event) -> {
            checkState(event, 5, true, "STATEMENT(CALL(foo2))");
            event.prepareStepInto(1);
        });
        expectSuspended((SuspendedEvent event) -> {
            checkState(event, 3, true, "STATEMENT(CONSTANT(44))");
            event.prepareStepInto(2);
        });
        // Change the filter to filter Source2 out:
        expectSuspended((SuspendedEvent event) -> {
            checkState(event, 6, true, "STATEMENT(CALL(foo1))");
            Predicate<com.oracle.truffle.api.source.Source> filterSource2 = source -> {
                return source.getName().indexOf("Source2") < 0;
            };
            session.setSteppingFilter(SuspensionFilter.newBuilder().sourceIs(filterSource2).build());
            event.prepareStepInto(1);
        });
        expectSuspended((SuspendedEvent event) -> {
            checkState(event, 3, true, "STATEMENT(CONSTANT(43))");
            event.prepareStepOut(1).prepareStepOver(1).prepareStepInto(1);
        });
        expectSuspended((SuspendedEvent event) -> {
            checkState(event, 8, true, "STATEMENT(CONSTANT(100))");
            event.prepareContinue();
        });
        expectDone();
    }
}
Also used : SuspendedEvent(com.oracle.truffle.api.debug.SuspendedEvent) SuspensionFilter(com.oracle.truffle.api.debug.SuspensionFilter) InstrumentationTestLanguage(com.oracle.truffle.api.instrumentation.test.InstrumentationTestLanguage) Breakpoint(com.oracle.truffle.api.debug.Breakpoint) DebuggerSession(com.oracle.truffle.api.debug.DebuggerSession) Predicate(java.util.function.Predicate) After(org.junit.After) Source(org.graalvm.polyglot.Source) HashMap(java.util.HashMap) Test(org.junit.Test) Assert(org.junit.Assert) Collections(java.util.Collections) DebuggerSession(com.oracle.truffle.api.debug.DebuggerSession) SuspendedEvent(com.oracle.truffle.api.debug.SuspendedEvent) SuspensionFilter(com.oracle.truffle.api.debug.SuspensionFilter) Source(org.graalvm.polyglot.Source) Test(org.junit.Test)

Example 82 with Predicate

use of java.util.function.Predicate in project minecolonies by Minecolonies.

the class AbstractBuilding method getRequiredItemsAndAmount.

/**
 * Override this method if you want to keep an amount of items in inventory.
 * When the inventory is full, everything get's dumped into the building chest.
 * But you can use this method to hold some stacks back.
 *
 * @return a list of objects which should be kept.
 */
public Map<Predicate<ItemStack>, Integer> getRequiredItemsAndAmount() {
    final Map<Predicate<ItemStack>, Integer> toKeep = new HashMap<>();
    toKeep.putAll(keepX);
    final IRequestManager manager = colony.getRequestManager();
    toKeep.put(stack -> this.getOpenRequestsByCitizen().values().stream().anyMatch(list -> list.stream().anyMatch(token -> manager.getRequestForToken(token).getRequest() instanceof IDeliverable && ((IDeliverable) manager.getRequestForToken(token).getRequest()).matches(stack))), Integer.MAX_VALUE);
    return toKeep;
}
Also used : IRequest(com.minecolonies.api.colony.requestsystem.request.IRequest) BuildingRequestResolver(com.minecolonies.coremod.colony.requestsystem.resolvers.BuildingRequestResolver) Constants(net.minecraftforge.common.util.Constants) ImmutableCollection(com.google.common.collect.ImmutableCollection) TextComponentTranslation(net.minecraft.util.text.TextComponentTranslation) StandardFactoryController(com.minecolonies.api.colony.requestsystem.StandardFactoryController) NBTTagList(net.minecraft.nbt.NBTTagList) Block(net.minecraft.block.Block) CombinedItemHandler(com.minecolonies.coremod.inventory.api.CombinedItemHandler) IItemHandlerModifiable(net.minecraftforge.items.IItemHandlerModifiable) NBTTagCompound(net.minecraft.nbt.NBTTagCompound) BuildingBuilderView(com.minecolonies.coremod.colony.buildings.views.BuildingBuilderView) InventoryHelper(net.minecraft.inventory.InventoryHelper) Predicate(java.util.function.Predicate) RequestState(com.minecolonies.api.colony.requestsystem.request.RequestState) TileEntityColonyBuilding(com.minecolonies.coremod.tileentities.TileEntityColonyBuilding) Collectors(java.util.stream.Collectors) Capability(net.minecraftforge.common.capabilities.Capability) InvocationTargetException(java.lang.reflect.InvocationTargetException) AbstractBuildingView(com.minecolonies.coremod.colony.buildings.views.AbstractBuildingView) Nullable(org.jetbrains.annotations.Nullable) IRequestResolver(com.minecolonies.api.colony.requestsystem.resolver.IRequestResolver) BuildingUtils(com.minecolonies.coremod.util.BuildingUtils) EntityPlayer(net.minecraft.entity.player.EntityPlayer) com.minecolonies.coremod.blocks(com.minecolonies.coremod.blocks) CapabilityItemHandler(net.minecraftforge.items.CapabilityItemHandler) IRequestResolverProvider(com.minecolonies.api.colony.requestsystem.resolver.IRequestResolverProvider) ItemStorage(com.minecolonies.api.crafting.ItemStorage) TickEvent(net.minecraftforge.fml.common.gameevent.TickEvent) NotNull(org.jetbrains.annotations.NotNull) NBTUtil(net.minecraft.nbt.NBTUtil) java.util(java.util) ColonyUtils(com.minecolonies.coremod.util.ColonyUtils) ICapabilityProvider(net.minecraftforge.common.capabilities.ICapabilityProvider) Suppression(com.minecolonies.api.util.constant.Suppression) AxisAlignedBB(net.minecraft.util.math.AxisAlignedBB) IToken(com.minecolonies.api.colony.requestsystem.token.IToken) EntityAIWorkDeliveryman(com.minecolonies.coremod.entity.ai.citizen.deliveryman.EntityAIWorkDeliveryman) TypeToken(com.google.common.reflect.TypeToken) Constructor(java.lang.reflect.Constructor) IRequestManager(com.minecolonies.api.colony.requestsystem.manager.IRequestManager) TileEntityChest(net.minecraft.tileentity.TileEntityChest) ITextComponent(net.minecraft.util.text.ITextComponent) ItemStack(net.minecraft.item.ItemStack) ImmutableList(com.google.common.collect.ImmutableList) ByteBuf(io.netty.buffer.ByteBuf) StructureWrapper(com.minecolonies.coremod.util.StructureWrapper) BuildingBasedRequester(com.minecolonies.coremod.colony.requestsystem.requesters.BuildingBasedRequester) ConstructionTapeHelper(com.minecolonies.coremod.entity.ai.citizen.builder.ConstructionTapeHelper) com.minecolonies.api.util(com.minecolonies.api.util) Nonnull(javax.annotation.Nonnull) WorkOrderBuild(com.minecolonies.coremod.colony.workorders.WorkOrderBuild) IDeliverable(com.minecolonies.api.colony.requestsystem.requestable.IDeliverable) IRequester(com.minecolonies.api.colony.requestsystem.requester.IRequester) BlockContainer(net.minecraft.block.BlockContainer) ILocation(com.minecolonies.api.colony.requestsystem.location.ILocation) World(net.minecraft.world.World) EnumFacing(net.minecraft.util.EnumFacing) Tuple(net.minecraft.util.Tuple) BlockPos(net.minecraft.util.math.BlockPos) IRequestable(com.minecolonies.api.colony.requestsystem.requestable.IRequestable) TileEntityRack(com.minecolonies.coremod.tileentities.TileEntityRack) TextComponentString(net.minecraft.util.text.TextComponentString) IBlockState(net.minecraft.block.state.IBlockState) TypeConstants(com.minecolonies.api.util.constant.TypeConstants) com.minecolonies.coremod.colony(com.minecolonies.coremod.colony) IInventory(net.minecraft.inventory.IInventory) NbtTagConstants(com.minecolonies.api.util.constant.NbtTagConstants) ByteBufUtils(net.minecraftforge.fml.common.network.ByteBufUtils) TileEntity(net.minecraft.tileentity.TileEntity) IRequestSystemBuildingDataStore(com.minecolonies.api.colony.requestsystem.data.IRequestSystemBuildingDataStore) IRequestManager(com.minecolonies.api.colony.requestsystem.manager.IRequestManager) IDeliverable(com.minecolonies.api.colony.requestsystem.requestable.IDeliverable) Predicate(java.util.function.Predicate)

Example 83 with Predicate

use of java.util.function.Predicate in project minecolonies by Minecolonies.

the class AbstractBuilding method buildingRequiresCertainAmountOfItem.

/**
 * Check if the worker requires a certain amount of that item and the alreadykept list contains it.
 * Always leave one stack behind if the worker requires a certain amount of it. Just to be sure.
 *
 * @param stack            the stack to check it with.
 * @param localAlreadyKept already kept items.
 * @return true if it should be leave it behind.
 */
public boolean buildingRequiresCertainAmountOfItem(final ItemStack stack, final List<ItemStorage> localAlreadyKept) {
    for (final Map.Entry<Predicate<ItemStack>, Integer> entry : getRequiredItemsAndAmount().entrySet()) {
        if (entry.getKey().test(stack)) {
            final ItemStorage kept = ItemStorage.getItemStackOfListMatchingPredicate(localAlreadyKept, entry.getKey());
            if (kept != null) {
                if (kept.getAmount() >= entry.getValue()) {
                    return false;
                }
                localAlreadyKept.remove(kept);
                kept.setAmount(kept.getAmount() + ItemStackUtils.getSize(stack));
                localAlreadyKept.add(kept);
                return true;
            }
            localAlreadyKept.add(new ItemStorage(stack));
            return true;
        }
    }
    return false;
}
Also used : ItemStorage(com.minecolonies.api.crafting.ItemStorage) Predicate(java.util.function.Predicate)

Example 84 with Predicate

use of java.util.function.Predicate in project bookkeeper by apache.

the class ListUnderReplicatedLedgerService method handle.

/*
     * Print the node which holds the auditor lock.
     */
@Override
public HttpServiceResponse handle(HttpServiceRequest request) throws Exception {
    HttpServiceResponse response = new HttpServiceResponse();
    // parameter as this: ?missingreplica=<bookie_address>&excludingmissingreplica=<bookid_address>
    Map<String, String> params = request.getParams();
    if (HttpServer.Method.GET == request.getMethod()) {
        final String includingBookieId;
        final String excludingBookieId;
        if (params != null && params.containsKey("missingreplica")) {
            includingBookieId = params.get("missingreplica");
        } else {
            includingBookieId = null;
        }
        if (params != null && params.containsKey("excludingmissingreplica")) {
            excludingBookieId = params.get("excludingmissingreplica");
        } else {
            excludingBookieId = null;
        }
        Predicate<List<String>> predicate = null;
        if (!StringUtils.isBlank(includingBookieId) && !StringUtils.isBlank(excludingBookieId)) {
            predicate = replicasList -> (replicasList.contains(includingBookieId) && !replicasList.contains(excludingBookieId));
        } else if (!StringUtils.isBlank(includingBookieId)) {
            predicate = replicasList -> replicasList.contains(includingBookieId);
        } else if (!StringUtils.isBlank(excludingBookieId)) {
            predicate = replicasList -> !replicasList.contains(excludingBookieId);
        }
        try {
            List<Long> outputLedgers = Lists.newArrayList();
            LedgerManagerFactory mFactory = bookieServer.getBookie().getLedgerManagerFactory();
            LedgerUnderreplicationManager underreplicationManager = mFactory.newLedgerUnderreplicationManager();
            Iterator<Long> iter = underreplicationManager.listLedgersToRereplicate(predicate);
            while (iter.hasNext()) {
                outputLedgers.add(iter.next());
            }
            if (outputLedgers.isEmpty()) {
                response.setCode(HttpServer.StatusCode.NOT_FOUND);
                response.setBody("No under replicated ledgers found");
                return response;
            } else {
                response.setCode(HttpServer.StatusCode.OK);
                String jsonResponse = JsonUtil.toJson(outputLedgers);
                LOG.debug("output body: " + jsonResponse);
                response.setBody(jsonResponse);
                return response;
            }
        } catch (Exception e) {
            LOG.error("Exception occurred while listing under replicated ledgers", e);
            response.setCode(HttpServer.StatusCode.NOT_FOUND);
            response.setBody("Exception when get." + e.getMessage());
            return response;
        }
    } else {
        response.setCode(HttpServer.StatusCode.NOT_FOUND);
        response.setBody("Not found method. Should be GET method");
        return response;
    }
}
Also used : HttpServiceRequest(org.apache.bookkeeper.http.service.HttpServiceRequest) StringUtils(org.apache.commons.lang.StringUtils) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) LedgerUnderreplicationManager(org.apache.bookkeeper.meta.LedgerUnderreplicationManager) Predicate(java.util.function.Predicate) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) LoggerFactory(org.slf4j.LoggerFactory) HttpServiceResponse(org.apache.bookkeeper.http.service.HttpServiceResponse) ServerConfiguration(org.apache.bookkeeper.conf.ServerConfiguration) HttpServer(org.apache.bookkeeper.http.HttpServer) BookieServer(org.apache.bookkeeper.proto.BookieServer) LedgerManagerFactory(org.apache.bookkeeper.meta.LedgerManagerFactory) List(java.util.List) Lists(com.google.common.collect.Lists) Map(java.util.Map) HttpEndpointService(org.apache.bookkeeper.http.service.HttpEndpointService) JsonUtil(org.apache.bookkeeper.util.JsonUtil) LedgerUnderreplicationManager(org.apache.bookkeeper.meta.LedgerUnderreplicationManager) HttpServiceResponse(org.apache.bookkeeper.http.service.HttpServiceResponse) List(java.util.List) LedgerManagerFactory(org.apache.bookkeeper.meta.LedgerManagerFactory)

Example 85 with Predicate

use of java.util.function.Predicate in project bookkeeper by apache.

the class BookKeeperAdmin method decommissionBookie.

/**
 * Triggers AuditTask by resetting lostBookieRecoveryDelay and then make
 * sure the ledgers stored in the given decommissioning bookie are properly
 * replicated and they are not underreplicated because of the given bookie.
 * This method waits untill there are no underreplicatedledgers because of this
 * bookie. If the given Bookie is not shutdown yet, then it will throw
 * BKIllegalOpException.
 *
 * @param bookieAddress
 *            address of the decommissioning bookie
 * @throws CompatibilityException
 * @throws UnavailableException
 * @throws KeeperException
 * @throws InterruptedException
 * @throws IOException
 * @throws BKAuditException
 * @throws TimeoutException
 * @throws BKException
 */
public void decommissionBookie(BookieSocketAddress bookieAddress) throws CompatibilityException, UnavailableException, KeeperException, InterruptedException, IOException, BKAuditException, TimeoutException, BKException {
    if (getAvailableBookies().contains(bookieAddress) || getReadOnlyBookies().contains(bookieAddress)) {
        LOG.error("Bookie: {} is not shutdown yet", bookieAddress);
        throw BKException.create(BKException.Code.IllegalOpException);
    }
    triggerAudit();
    /*
         * Sleep for 30 secs, so that Auditor gets chance to trigger its
         * force audittask and let the underreplicationmanager process
         * to do its replication process
         */
    Thread.sleep(30 * 1000);
    /*
         * get the collection of the ledgers which are stored in this
         * bookie, by making a call to
         * bookieLedgerIndexer.getBookieToLedgerIndex.
         */
    BookieLedgerIndexer bookieLedgerIndexer = new BookieLedgerIndexer(bkc.ledgerManager);
    Map<String, Set<Long>> bookieToLedgersMap = bookieLedgerIndexer.getBookieToLedgerIndex();
    Set<Long> ledgersStoredInThisBookie = bookieToLedgersMap.get(bookieAddress.toString());
    if ((ledgersStoredInThisBookie != null) && (!ledgersStoredInThisBookie.isEmpty())) {
        /*
             * wait untill all the ledgers are replicated to other
             * bookies by making sure that these ledgers metadata don't
             * contain this bookie as part of their ensemble.
             */
        waitForLedgersToBeReplicated(ledgersStoredInThisBookie, bookieAddress, bkc.ledgerManager);
    }
    // for double-checking, check if any ledgers are listed as underreplicated because of this bookie
    Predicate<List<String>> predicate = replicasList -> replicasList.contains(bookieAddress.toString());
    Iterator<Long> urLedgerIterator = underreplicationManager.listLedgersToRereplicate(predicate);
    if (urLedgerIterator.hasNext()) {
        // if there are any then wait and make sure those ledgers are replicated properly
        LOG.info("Still in some underreplicated ledgers metadata, this bookie is part of its ensemble. " + "Have to make sure that those ledger fragments are rereplicated");
        List<Long> urLedgers = new ArrayList<>();
        urLedgerIterator.forEachRemaining(urLedgers::add);
        waitForLedgersToBeReplicated(urLedgers, bookieAddress, bkc.ledgerManager);
    }
}
Also used : Enumeration(java.util.Enumeration) OpenCallback(org.apache.bookkeeper.client.AsyncCallback.OpenCallback) GenericCallback(org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.GenericCallback) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) Random(java.util.Random) RegistrationListener(org.apache.bookkeeper.discover.RegistrationClient.RegistrationListener) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) SingleFragmentCallback(org.apache.bookkeeper.client.LedgerFragmentReplicator.SingleFragmentCallback) Map(java.util.Map) BKAuditException(org.apache.bookkeeper.replication.ReplicationException.BKAuditException) BookieException(org.apache.bookkeeper.bookie.BookieException) NullStatsLogger(org.apache.bookkeeper.stats.NullStatsLogger) AuditorElector(org.apache.bookkeeper.replication.AuditorElector) BookieLedgerIndexer(org.apache.bookkeeper.replication.BookieLedgerIndexer) LedgerUnderreplicationManager(org.apache.bookkeeper.meta.LedgerUnderreplicationManager) Predicate(java.util.function.Predicate) Collection(java.util.Collection) Set(java.util.Set) Sets(com.google.common.collect.Sets) List(java.util.List) Entry(java.util.Map.Entry) StatsLogger(org.apache.bookkeeper.stats.StatsLogger) Optional(java.util.Optional) MetadataDrivers.runFunctionWithRegistrationManager(org.apache.bookkeeper.meta.MetadataDrivers.runFunctionWithRegistrationManager) UnavailableException(org.apache.bookkeeper.replication.ReplicationException.UnavailableException) SortedMap(java.util.SortedMap) MultiCallback(org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.MultiCallback) LedgerRangeIterator(org.apache.bookkeeper.meta.LedgerManager.LedgerRangeIterator) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) CompatibilityException(org.apache.bookkeeper.replication.ReplicationException.CompatibilityException) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) Processor(org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.Processor) HashSet(java.util.HashSet) Lists(com.google.common.collect.Lists) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) RecoverCallback(org.apache.bookkeeper.client.AsyncCallback.RecoverCallback) SyncReadCallback(org.apache.bookkeeper.client.SyncCallbackUtils.SyncReadCallback) LinkedList(java.util.LinkedList) NoSuchElementException(java.util.NoSuchElementException) Bookie(org.apache.bookkeeper.bookie.Bookie) MetadataDrivers.runFunctionWithMetadataBookieDriver(org.apache.bookkeeper.meta.MetadataDrivers.runFunctionWithMetadataBookieDriver) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) KeeperException(org.apache.zookeeper.KeeperException) LedgerManager(org.apache.bookkeeper.meta.LedgerManager) IOException(java.io.IOException) Maps(com.google.common.collect.Maps) SyncOpenCallback(org.apache.bookkeeper.client.SyncCallbackUtils.SyncOpenCallback) File(java.io.File) ServerConfiguration(org.apache.bookkeeper.conf.ServerConfiguration) ExecutionException(java.util.concurrent.ExecutionException) LedgerManagerFactory(org.apache.bookkeeper.meta.LedgerManagerFactory) IOUtils(org.apache.bookkeeper.util.IOUtils) ConcurrentSkipListMap(java.util.concurrent.ConcurrentSkipListMap) BookieSocketAddress(org.apache.bookkeeper.net.BookieSocketAddress) ClientConfiguration(org.apache.bookkeeper.conf.ClientConfiguration) AsyncCallback(org.apache.zookeeper.AsyncCallback) AbstractFuture(com.google.common.util.concurrent.AbstractFuture) Set(java.util.Set) HashSet(java.util.HashSet) ArrayList(java.util.ArrayList) BookieLedgerIndexer(org.apache.bookkeeper.replication.BookieLedgerIndexer) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList)

Aggregations

Predicate (java.util.function.Predicate)589 List (java.util.List)266 ArrayList (java.util.ArrayList)170 Collectors (java.util.stream.Collectors)167 Map (java.util.Map)164 Set (java.util.Set)137 Test (org.junit.Test)133 IOException (java.io.IOException)122 Collections (java.util.Collections)118 Arrays (java.util.Arrays)110 HashMap (java.util.HashMap)105 Collection (java.util.Collection)93 Optional (java.util.Optional)87 HashSet (java.util.HashSet)85 Stream (java.util.stream.Stream)69 Function (java.util.function.Function)61 File (java.io.File)60 Iterator (java.util.Iterator)55 Logger (org.slf4j.Logger)53 LoggerFactory (org.slf4j.LoggerFactory)52