Search in sources :

Example 51 with Multimap

use of com.google.common.collect.Multimap in project ImmersiveEngineering by BluSunrize.

the class ItemRevolver method getAttributeModifiers.

@Override
public Multimap getAttributeModifiers(EntityEquipmentSlot slot, ItemStack stack) {
    Multimap multimap = super.getAttributeModifiers(slot, stack);
    if (slot == EntityEquipmentSlot.MAINHAND) {
        double melee = getUpgrades(stack).getDouble("melee");
        if (melee != 0)
            multimap.put(SharedMonsterAttributes.ATTACK_DAMAGE.getAttributeUnlocalizedName(), new AttributeModifier(ATTACK_DAMAGE_MODIFIER, "Weapon modifier", melee, 0));
        double speed = getUpgrades(stack).getDouble("speed");
        if (speed != 0)
            multimap.put(SharedMonsterAttributes.MOVEMENT_SPEED.getAttributeUnlocalizedName(), new AttributeModifier(speedModUUID, "Weapon modifier", speed, 1));
    }
    return multimap;
}
Also used : ArrayListMultimap(com.google.common.collect.ArrayListMultimap) Multimap(com.google.common.collect.Multimap) AttributeModifier(net.minecraft.entity.ai.attributes.AttributeModifier)

Example 52 with Multimap

use of com.google.common.collect.Multimap in project presto by prestodb.

the class PipelineContext method getPipelineStats.

public PipelineStats getPipelineStats() {
    // check for end state to avoid callback ordering problems
    if (taskContext.getState().isDone()) {
        DateTime now = DateTime.now();
        executionStartTime.compareAndSet(null, now);
        lastExecutionStartTime.compareAndSet(null, now);
        lastExecutionEndTime.compareAndSet(null, now);
    }
    List<DriverContext> driverContexts = ImmutableList.copyOf(this.drivers);
    int totalDriers = completedDrivers.get() + driverContexts.size();
    int queuedDrivers = 0;
    int queuedPartitionedDrivers = 0;
    int runningDrivers = 0;
    int runningPartitionedDrivers = 0;
    int completedDrivers = this.completedDrivers.get();
    Distribution queuedTime = new Distribution(this.queuedTime);
    Distribution elapsedTime = new Distribution(this.elapsedTime);
    long totalScheduledTime = this.totalScheduledTime.get();
    long totalCpuTime = this.totalCpuTime.get();
    long totalUserTime = this.totalUserTime.get();
    long totalBlockedTime = this.totalBlockedTime.get();
    long rawInputDataSize = this.rawInputDataSize.getTotalCount();
    long rawInputPositions = this.rawInputPositions.getTotalCount();
    long processedInputDataSize = this.processedInputDataSize.getTotalCount();
    long processedInputPositions = this.processedInputPositions.getTotalCount();
    long outputDataSize = this.outputDataSize.getTotalCount();
    long outputPositions = this.outputPositions.getTotalCount();
    List<DriverStats> drivers = new ArrayList<>();
    Multimap<Integer, OperatorStats> runningOperators = ArrayListMultimap.create();
    for (DriverContext driverContext : driverContexts) {
        DriverStats driverStats = driverContext.getDriverStats();
        drivers.add(driverStats);
        if (driverStats.getStartTime() == null) {
            queuedDrivers++;
            if (driverContext.isPartitioned()) {
                queuedPartitionedDrivers++;
            }
        } else {
            runningDrivers++;
            if (driverContext.isPartitioned()) {
                runningPartitionedDrivers++;
            }
        }
        queuedTime.add(driverStats.getQueuedTime().roundTo(NANOSECONDS));
        elapsedTime.add(driverStats.getElapsedTime().roundTo(NANOSECONDS));
        totalScheduledTime += driverStats.getTotalScheduledTime().roundTo(NANOSECONDS);
        totalCpuTime += driverStats.getTotalCpuTime().roundTo(NANOSECONDS);
        totalUserTime += driverStats.getTotalUserTime().roundTo(NANOSECONDS);
        totalBlockedTime += driverStats.getTotalBlockedTime().roundTo(NANOSECONDS);
        List<OperatorStats> operators = ImmutableList.copyOf(transform(driverContext.getOperatorContexts(), OperatorContext::getOperatorStats));
        for (OperatorStats operator : operators) {
            runningOperators.put(operator.getOperatorId(), operator);
        }
        rawInputDataSize += driverStats.getRawInputDataSize().toBytes();
        rawInputPositions += driverStats.getRawInputPositions();
        processedInputDataSize += driverStats.getProcessedInputDataSize().toBytes();
        processedInputPositions += driverStats.getProcessedInputPositions();
        outputDataSize += driverStats.getOutputDataSize().toBytes();
        outputPositions += driverStats.getOutputPositions();
    }
    // merge the running operator stats into the operator summary
    TreeMap<Integer, OperatorStats> operatorSummaries = new TreeMap<>(this.operatorSummaries);
    for (Entry<Integer, OperatorStats> entry : runningOperators.entries()) {
        OperatorStats current = operatorSummaries.get(entry.getKey());
        if (current == null) {
            current = entry.getValue();
        } else {
            current = current.add(entry.getValue());
        }
        operatorSummaries.put(entry.getKey(), current);
    }
    ImmutableSet<BlockedReason> blockedReasons = drivers.stream().filter(driver -> driver.getEndTime() == null && driver.getStartTime() != null).flatMap(driver -> driver.getBlockedReasons().stream()).collect(ImmutableCollectors.toImmutableSet());
    boolean fullyBlocked = drivers.stream().filter(driver -> driver.getEndTime() == null && driver.getStartTime() != null).allMatch(DriverStats::isFullyBlocked);
    return new PipelineStats(pipelineId, executionStartTime.get(), lastExecutionStartTime.get(), lastExecutionEndTime.get(), inputPipeline, outputPipeline, totalDriers, queuedDrivers, queuedPartitionedDrivers, runningDrivers, runningPartitionedDrivers, completedDrivers, succinctBytes(memoryReservation.get()), succinctBytes(systemMemoryReservation.get()), queuedTime.snapshot(), elapsedTime.snapshot(), new Duration(totalScheduledTime, NANOSECONDS).convertToMostSuccinctTimeUnit(), new Duration(totalCpuTime, NANOSECONDS).convertToMostSuccinctTimeUnit(), new Duration(totalUserTime, NANOSECONDS).convertToMostSuccinctTimeUnit(), new Duration(totalBlockedTime, NANOSECONDS).convertToMostSuccinctTimeUnit(), fullyBlocked && (runningDrivers > 0 || runningPartitionedDrivers > 0), blockedReasons, succinctBytes(rawInputDataSize), rawInputPositions, succinctBytes(processedInputDataSize), processedInputPositions, succinctBytes(outputDataSize), outputPositions, ImmutableList.copyOf(operatorSummaries.values()), drivers);
}
Also used : ArrayListMultimap(com.google.common.collect.ArrayListMultimap) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Iterables.transform(com.google.common.collect.Iterables.transform) NANOSECONDS(java.util.concurrent.TimeUnit.NANOSECONDS) DataSize.succinctBytes(io.airlift.units.DataSize.succinctBytes) CounterStat(io.airlift.stats.CounterStat) Multimap(com.google.common.collect.Multimap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Duration(io.airlift.units.Duration) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) ImmutableList(com.google.common.collect.ImmutableList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Objects.requireNonNull(java.util.Objects.requireNonNull) ImmutableSet(com.google.common.collect.ImmutableSet) Executor(java.util.concurrent.Executor) Session(com.facebook.presto.Session) DateTime(org.joda.time.DateTime) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ThreadSafe(javax.annotation.concurrent.ThreadSafe) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) TreeMap(java.util.TreeMap) TaskId(com.facebook.presto.execution.TaskId) Entry(java.util.Map.Entry) ImmutableCollectors(com.facebook.presto.util.ImmutableCollectors) Distribution(io.airlift.stats.Distribution) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Duration(io.airlift.units.Duration) TreeMap(java.util.TreeMap) DateTime(org.joda.time.DateTime) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Distribution(io.airlift.stats.Distribution)

Example 53 with Multimap

use of com.google.common.collect.Multimap in project RecurrentComplex by Ivorforce.

the class RCSaplingGenerator method growSapling.

public static void growSapling(WorldServer world, BlockPos pos, Random random, Structure<?> structure, SaplingGeneration saplingGenInfo) {
    int[] strucSize = structure.size();
    Multimap<AxisAlignedTransform2D, BlockPos> placeables = saplingGenInfo.pattern.testAll(world, pos, strucSize, structure.isRotatable(), structure.isMirrorable());
    // Use keys() here to get the correct distribution
    AxisAlignedTransform2D transform = Lists.newArrayList(placeables.keys()).get(random.nextInt(placeables.keys().size()));
    Collection<BlockPos> transformedPositions = placeables.get(transform);
    BlockPos startPos = Lists.newArrayList(transformedPositions).get(random.nextInt(transformedPositions.size()));
    Map<BlockPos, IBlockState> before = new HashMap<>();
    IBlockState air = Blocks.AIR.getDefaultState();
    saplingGenInfo.pattern.copy(transform, strucSize).forEach(i -> i.delete, entry -> {
        BlockPos ePos = entry.getKey().add(startPos);
        before.put(ePos, world.getBlockState(ePos));
        world.setBlockState(ePos, air, 4);
    });
    BlockPos spawnPos = transform.apply(saplingGenInfo.spawnShift, new int[] { 1, 1, 1 }).add(startPos);
    boolean success = new StructureGenerator<>(structure).world(world).generationInfo(saplingGenInfo).transform(transform).seed(random.nextLong()).maturity(StructureSpawnContext.GenerateMaturity.SUGGEST).memorize(RCConfig.memorizeSaplings).allowOverlaps(true).randomPosition(BlockSurfacePos.from(spawnPos), (context, blockCollection) -> spawnPos.getY()).generate() != null;
    if (!success)
        before.forEach((pos1, state) -> world.setBlockState(pos1, state, 4));
}
Also used : BlockSurfacePos(ivorius.ivtoolkit.blocks.BlockSurfacePos) java.util(java.util) Blocks(net.minecraft.init.Blocks) AxisAlignedTransform2D(ivorius.ivtoolkit.math.AxisAlignedTransform2D) World(net.minecraft.world.World) Structure(ivorius.reccomplex.world.gen.feature.structure.Structure) StructureSpawnContext(ivorius.reccomplex.world.gen.feature.structure.context.StructureSpawnContext) StructureRegistry(ivorius.reccomplex.world.gen.feature.structure.StructureRegistry) StructureGenerator(ivorius.reccomplex.world.gen.feature.StructureGenerator) BlockPos(net.minecraft.util.math.BlockPos) Multimap(com.google.common.collect.Multimap) WeightedSelector(ivorius.ivtoolkit.random.WeightedSelector) RCConfig(ivorius.reccomplex.RCConfig) Collectors(java.util.stream.Collectors) Environment(ivorius.reccomplex.world.gen.feature.structure.Environment) IBlockState(net.minecraft.block.state.IBlockState) IvFunctions(ivorius.ivtoolkit.util.IvFunctions) Lists(com.google.common.collect.Lists) Pair(org.apache.commons.lang3.tuple.Pair) ImmutableMultimap(com.google.common.collect.ImmutableMultimap) WorldServer(net.minecraft.world.WorldServer) StructureBoundingBox(net.minecraft.world.gen.structure.StructureBoundingBox) Nullable(javax.annotation.Nullable) SaplingGeneration(ivorius.reccomplex.world.gen.feature.structure.generic.generation.SaplingGeneration) IBlockState(net.minecraft.block.state.IBlockState) StructureGenerator(ivorius.reccomplex.world.gen.feature.StructureGenerator) AxisAlignedTransform2D(ivorius.ivtoolkit.math.AxisAlignedTransform2D) BlockPos(net.minecraft.util.math.BlockPos)

Example 54 with Multimap

use of com.google.common.collect.Multimap in project cdap by caskdata.

the class ServiceLifeCycleTestRun method testLifecycleWithGC.

@Test
public void testLifecycleWithGC() throws Exception {
    // Set the http server properties to speed up test
    System.setProperty(ServiceHttpServer.THREAD_POOL_SIZE, "1");
    System.setProperty(ServiceHttpServer.THREAD_KEEP_ALIVE_SECONDS, "1");
    System.setProperty(ServiceHttpServer.HANDLER_CLEANUP_PERIOD_MILLIS, "100");
    try {
        ApplicationManager appManager = deployWithArtifact(ServiceLifecycleApp.class, artifactJar);
        final ServiceManager serviceManager = appManager.getServiceManager("test").start();
        // Make 5 consecutive calls, there should be one handler instance being created,
        // since there is only one handler thread.
        Multimap<Integer, String> states = null;
        for (int i = 0; i < 5; i++) {
            states = getStates(serviceManager);
            // There should only be one instance created
            Assert.assertEquals(1, states.size());
            // For the instance, there should only be INIT state.
            Assert.assertEquals(ImmutableList.of("INIT"), ImmutableList.copyOf(states.get(states.keySet().iterator().next())));
        }
        // Capture the current state
        final Multimap<Integer, String> lastStates = states;
        // TTL for the thread is 1 second, hence sleep for 2 second to make sure the thread is gone
        TimeUnit.SECONDS.sleep(2);
        Tasks.waitFor(true, new Callable<Boolean>() {

            @Override
            public Boolean call() throws Exception {
                // Force a gc to have weak references cleanup
                System.gc();
                Multimap<Integer, String> newStates = getStates(serviceManager);
                // and an INIT for the new handler that just handle the getState call
                if (newStates.size() != 3) {
                    return false;
                }
                // A INIT and a DESTROY is expected for the old handler
                return ImmutableList.of("INIT", "DESTROY").equals(ImmutableList.copyOf(newStates.get(lastStates.keySet().iterator().next())));
            }
        }, 10, TimeUnit.SECONDS, 100, TimeUnit.MILLISECONDS);
    } finally {
        // Reset the http server properties to speed up test
        System.clearProperty(ServiceHttpServer.THREAD_POOL_SIZE);
        System.clearProperty(ServiceHttpServer.THREAD_KEEP_ALIVE_SECONDS);
        System.clearProperty(ServiceHttpServer.HANDLER_CLEANUP_PERIOD_MILLIS);
    }
}
Also used : Multimap(com.google.common.collect.Multimap) LinkedListMultimap(com.google.common.collect.LinkedListMultimap) ApplicationManager(co.cask.cdap.test.ApplicationManager) ServiceManager(co.cask.cdap.test.ServiceManager) IOException(java.io.IOException) Test(org.junit.Test)

Example 55 with Multimap

use of com.google.common.collect.Multimap in project dhis2-core by dhis2.

the class Jackson2PropertyIntrospectorService method collectProperties.

private List<Property> collectProperties(Class<?> klass) {
    Multimap<String, Method> multimap = ReflectionUtils.getMethodsMultimap(klass);
    List<String> fieldNames = ReflectionUtils.getAllFields(klass).stream().map(Field::getName).collect(Collectors.toList());
    List<Property> properties = new ArrayList<>();
    Map<String, Method> methodMap = multimap.keySet().stream().filter(key -> {
        List<Method> methods = multimap.get(key).stream().filter(method -> AnnotationUtils.isAnnotationPresent(method, JsonProperty.class) && method.getParameterTypes().length == 0).collect(Collectors.toList());
        if (methods.size() > 1) {
            log.error("More than one web-api exposed method with name '" + key + "' found on class '" + klass.getName() + "' please fix as this is known to cause issues with Schema / Query services.");
            log.debug("Methods found: " + methods);
        }
        return methods.size() == 1;
    }).collect(Collectors.toMap(Function.identity(), key -> {
        List<Method> collect = multimap.get(key).stream().filter(method -> AnnotationUtils.isAnnotationPresent(method, JsonProperty.class) && method.getParameterTypes().length == 0).collect(Collectors.toList());
        return collect.get(0);
    }));
    methodMap.keySet().forEach(key -> {
        String fieldName = getFieldName(methodMap.get(key));
        String setterName = "set" + StringUtils.capitalize(fieldName);
        Property property = new Property(klass, methodMap.get(key), null);
        if (fieldNames.contains(fieldName)) {
            property.setFieldName(fieldName);
        }
        Iterator<Method> methodIterator = multimap.get(setterName).iterator();
        if (methodIterator.hasNext()) {
            property.setSetterMethod(methodIterator.next());
        }
        properties.add(property);
    });
    return properties;
}
Also used : JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) JacksonXmlProperty(com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty) ReflectionUtils(org.hisp.dhis.system.util.ReflectionUtils) JacksonXmlRootElement(com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement) JacksonXmlElementWrapper(com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper) Multimap(com.google.common.collect.Multimap) Function(java.util.function.Function) EmbeddedObject(org.hisp.dhis.common.EmbeddedObject) AnnotationUtils(org.hisp.dhis.system.util.AnnotationUtils) ArrayList(java.util.ArrayList) Map(java.util.Map) Method(java.lang.reflect.Method) SchemaUtils(org.hisp.dhis.system.util.SchemaUtils) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) NameableObject(org.hisp.dhis.common.NameableObject) Iterator(java.util.Iterator) Collection(java.util.Collection) Field(java.lang.reflect.Field) Maps(com.google.common.collect.Maps) Collectors(java.util.stream.Collectors) Primitives(com.google.common.primitives.Primitives) List(java.util.List) ParameterizedType(java.lang.reflect.ParameterizedType) Description(org.hisp.dhis.common.annotation.Description) Type(java.lang.reflect.Type) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) StringUtils(org.springframework.util.StringUtils) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) Method(java.lang.reflect.Method) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) JacksonXmlProperty(com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty)

Aggregations

Multimap (com.google.common.collect.Multimap)61 HashMultimap (com.google.common.collect.HashMultimap)25 List (java.util.List)25 Test (org.junit.Test)20 Map (java.util.Map)17 ImmutableList (com.google.common.collect.ImmutableList)15 Collection (java.util.Collection)14 Set (java.util.Set)14 ImmutableMap (com.google.common.collect.ImmutableMap)13 HashMap (java.util.HashMap)13 ImmutableMultimap (com.google.common.collect.ImmutableMultimap)12 ImmutableSet (com.google.common.collect.ImmutableSet)11 ArrayList (java.util.ArrayList)11 Collectors (java.util.stream.Collectors)11 ArrayListMultimap (com.google.common.collect.ArrayListMultimap)10 Nullable (javax.annotation.Nullable)10 IOException (java.io.IOException)9 Stream (java.util.stream.Stream)9 InetAddress (java.net.InetAddress)8 Objects (java.util.Objects)8