Search in sources :

Example 1 with ArrayListMultimap

use of com.google.common.collect.ArrayListMultimap in project fastjson by alibaba.

the class Issue2182 method test_for_issue.

public void test_for_issue() throws Exception {
    Multimap<String, String> multimap = ArrayListMultimap.create();
    multimap.put("admin", "admin.create");
    multimap.put("admin", "admin.update");
    multimap.put("admin", "admin.delete");
    multimap.put("user", "user.create");
    multimap.put("user", "user.delete");
    String json = JSON.toJSONString(multimap);
    assertEquals("{\"admin\":[\"admin.create\",\"admin.update\",\"admin.delete\"],\"user\":[\"user.create\",\"user.delete\"]}", json);
    ArrayListMultimap multimap1 = JSON.parseObject(json, ArrayListMultimap.class);
    assertEquals(multimap.size(), multimap1.size());
    assertEquals(json, JSON.toJSONString(multimap1));
}
Also used : ArrayListMultimap(com.google.common.collect.ArrayListMultimap)

Example 2 with ArrayListMultimap

use of com.google.common.collect.ArrayListMultimap in project immutables by immutables.

the class SourceOrdering method getAllAccessorsProvider.

/**
 * While we have {@link SourceOrdering}, there's still a problem: We have inheritance hierarchy
 * and
 * we want to have all defined or inherited accessors returned as members of target type, like
 * {@link Elements#getAllMembers(TypeElement)}, but we need to have them properly and stably
 * sorted.
 * This implementation doesn't try to correctly resolve order for accessors inherited from
 * different supertypes(interfaces), just something that stable and reasonable wrt source ordering
 * without handling complex cases.
 * @param elements the elements utility
 * @param types the types utility
 * @param originatingType the type to traverse
 * @return provider of all accessors in source order and mapping
 */
public static AccessorProvider getAllAccessorsProvider(final Elements elements, final Types types, final TypeElement originatingType) {
    class CollectedOrdering extends Ordering<Element> {

        class Intratype {

            final String inType;

            final Ordering<String> ordering;

            final int rank;

            Intratype(String inType, int rank, List<String> accessors) {
                this.inType = inType;
                this.rank = rank;
                this.ordering = Ordering.explicit(accessors);
            }

            @Override
            public String toString() {
                return "(<=> " + inType + ", " + rank + ", " + ordering + ")";
            }
        }

        final Map<String, Intratype> accessorOrderings = new LinkedHashMap<>();

        final Set<TypeElement> linearizedTypes = new LinkedHashSet<>();

        final ArrayListMultimap<String, TypeElement> accessorMapping = ArrayListMultimap.create();

        CollectedOrdering() {
            traverse(originatingType);
            collectAccessors();
        }

        void traverse(@Nullable TypeElement element) {
            if (element == null || isJavaLangObject(element)) {
                return;
            }
            for (TypeMirror implementedInterface : element.getInterfaces()) {
                traverse(toElement(implementedInterface));
            }
            if (element.getKind().isClass()) {
                // collectEnclosing(element);
                traverse(toElement(element.getSuperclass()));
            }
            // we add this after so we start with the deepest
            linearizedTypes.add(element);
        }

        @Nullable
        TypeElement toElement(TypeMirror type) {
            if (type.getKind() == TypeKind.DECLARED) {
                return (TypeElement) ((DeclaredType) type).asElement();
            }
            if (type.getKind() == TypeKind.ERROR) {
                try {
                    return (TypeElement) ((DeclaredType) type).asElement();
                } catch (Exception bestEffortToHandleErrorElement) {
                }
            }
            return null;
        }

        void collectAccessors() {
            int i = 0;
            for (TypeElement type : linearizedTypes) {
                List<String> accessorsInType = FluentIterable.from(SourceOrdering.getEnclosedElements(type)).filter(IsParameterlessNonstaticNonobject.PREDICATE).transform(ToSimpleName.FUNCTION).toList();
                String typeTag = type.getSimpleName().toString();
                Intratype intratype = new Intratype(typeTag, i++, accessorsInType);
                for (String name : accessorsInType) {
                    // we override accessors by the ones redeclared in later types
                    accessorMapping.put(name, type);
                    accessorOrderings.put(name, intratype);
                }
            }
        }

        @Override
        public int compare(Element left, Element right) {
            String leftKey = ToSimpleName.FUNCTION.apply(left);
            String rightKey = ToSimpleName.FUNCTION.apply(right);
            Intratype leftIntratype = accessorOrderings.get(leftKey);
            Intratype rightIntratype = accessorOrderings.get(rightKey);
            // can be issue under Eclipse (still?)
            if (leftIntratype == null || rightIntratype == null)
                return 0;
            return leftIntratype == rightIntratype ? leftIntratype.ordering.compare(leftKey, rightKey) : Integer.compare(leftIntratype.rank, rightIntratype.rank);
        }
    }
    final CollectedOrdering ordering = new CollectedOrdering();
    final ImmutableList<ExecutableElement> sortedList = ordering.immutableSortedCopy(disambiguateMethods(ElementFilter.methodsIn(elements.getAllMembers(originatingType))));
    return new AccessorProvider() {

        final ImmutableListMultimap<String, TypeElement> accessorMapping = ImmutableListMultimap.copyOf(ordering.accessorMapping);

        @Override
        public ImmutableListMultimap<String, TypeElement> accessorMapping() {
            return accessorMapping;
        }

        @Override
        public ImmutableList<ExecutableElement> get() {
            return sortedList;
        }
    };
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Set(java.util.Set) TypeElement(javax.lang.model.element.TypeElement) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) ExecutableElement(javax.lang.model.element.ExecutableElement) TypeMirror(javax.lang.model.type.TypeMirror) Ordering(com.google.common.collect.Ordering) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) ArrayListMultimap(com.google.common.collect.ArrayListMultimap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) IdentityHashMap(java.util.IdentityHashMap) Nullable(javax.annotation.Nullable)

Example 3 with ArrayListMultimap

use of com.google.common.collect.ArrayListMultimap in project cas by apereo.

the class ReturnMappedAttributeReleasePolicyTests method verifyConcurrentScript.

@Test
public void verifyConcurrentScript() throws Exception {
    val allowedAttributes = ArrayListMultimap.<String, Object>create();
    allowedAttributes.put("taxId", "groovy { attributes['fiscalNumber'][0] }");
    allowedAttributes.put("uid", "uid");
    val wrap = CollectionUtils.<String, Object>wrap(allowedAttributes);
    val policy = new ReturnMappedAttributeReleasePolicy(wrap);
    val registeredService = CoreAttributesTestUtils.getRegisteredService();
    when(registeredService.getAttributeReleasePolicy()).thenReturn(policy);
    val service = Executors.newFixedThreadPool(50);
    IntStream.range(0, 1000).forEach(Unchecked.intConsumer(count -> {
        val future = service.submit(() -> {
            val principalAttributes = new HashMap<String, List<Object>>();
            val uid = "user" + count;
            principalAttributes.put("uid", List.of(uid));
            principalAttributes.put("fiscalNumber", List.of(uid + '-' + RandomUtils.randomAlphabetic(9)));
            val principal = CoreAttributesTestUtils.getPrincipal(uid, principalAttributes);
            val releasePolicyContext = RegisteredServiceAttributeReleasePolicyContext.builder().registeredService(registeredService).service(CoreAuthenticationTestUtils.getService()).principal(principal).build();
            var result = policy.getAttributes(releasePolicyContext);
            assertNotNull(result);
            assertTrue(result.containsKey("uid"));
            assertTrue(result.containsKey("taxId"));
            assertEquals(uid, result.get("uid").get(0));
            assertTrue(result.get("taxId").get(0).toString().contains(uid));
        });
        future.get();
    }));
    service.awaitTermination(5, TimeUnit.SECONDS);
}
Also used : lombok.val(lombok.val) ArrayListMultimap(com.google.common.collect.ArrayListMultimap) IntStream(java.util.stream.IntStream) BeforeEach(org.junit.jupiter.api.BeforeEach) RandomUtils(org.apereo.cas.util.RandomUtils) ClassPathResource(org.springframework.core.io.ClassPathResource) Autowired(org.springframework.beans.factory.annotation.Autowired) ArrayUtils(org.apache.commons.lang3.ArrayUtils) HashMap(java.util.HashMap) RefreshAutoConfiguration(org.springframework.cloud.autoconfigure.RefreshAutoConfiguration) ScriptResourceCacheManager(org.apereo.cas.util.scripting.ScriptResourceCacheManager) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) CollectionUtils(org.apereo.cas.util.CollectionUtils) Tag(org.junit.jupiter.api.Tag) ApplicationContextProvider(org.apereo.cas.util.spring.ApplicationContextProvider) CoreAttributesTestUtils(org.apereo.cas.CoreAttributesTestUtils) Unchecked(org.jooq.lambda.Unchecked) GroovyScriptResourceCacheManager(org.apereo.cas.util.scripting.GroovyScriptResourceCacheManager) Collection(java.util.Collection) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) lombok.val(lombok.val) FileUtils(org.apache.commons.io.FileUtils) IOException(java.io.IOException) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) Test(org.junit.jupiter.api.Test) TimeUnit(java.util.concurrent.TimeUnit) IOUtils(org.apache.commons.io.IOUtils) Mockito(org.mockito.Mockito) List(java.util.List) Stream(java.util.stream.Stream) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) TreeMap(java.util.TreeMap) JacksonObjectMapperFactory(org.apereo.cas.util.serialization.JacksonObjectMapperFactory) Assertions(org.junit.jupiter.api.Assertions) CasCoreUtilConfiguration(org.apereo.cas.config.CasCoreUtilConfiguration) CoreAuthenticationTestUtils(org.apereo.cas.authentication.CoreAuthenticationTestUtils) List(java.util.List) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 4 with ArrayListMultimap

use of com.google.common.collect.ArrayListMultimap in project MinecraftForge by MinecraftForge.

the class ForgeChunkManager method loadWorld.

static void loadWorld(World world) {
    ArrayListMultimap<String, Ticket> newTickets = ArrayListMultimap.create();
    tickets.put(world, newTickets);
    forcedChunks.put(world, ImmutableSetMultimap.<ChunkPos, Ticket>of());
    if (!(world instanceof WorldServer)) {
        return;
    }
    if (dormantChunkCacheSize != 0) {
        // only put into cache if we're using dormant chunk caching
        dormantChunkCache.put(world, CacheBuilder.newBuilder().maximumSize(dormantChunkCacheSize).<Long, Chunk>build());
    }
    WorldServer worldServer = (WorldServer) world;
    File chunkDir = worldServer.getChunkSaveLocation();
    File chunkLoaderData = new File(chunkDir, "forcedchunks.dat");
    if (chunkLoaderData.exists() && chunkLoaderData.isFile()) {
        ArrayListMultimap<String, Ticket> loadedTickets = ArrayListMultimap.create();
        Map<String, ListMultimap<String, Ticket>> playerLoadedTickets = Maps.newHashMap();
        NBTTagCompound forcedChunkData;
        try {
            forcedChunkData = CompressedStreamTools.read(chunkLoaderData);
        } catch (IOException e) {
            FMLLog.log(Level.WARN, e, "Unable to read forced chunk data at %s - it will be ignored", chunkLoaderData.getAbsolutePath());
            return;
        }
        NBTTagList ticketList = forcedChunkData.getTagList("TicketList", Constants.NBT.TAG_COMPOUND);
        for (int i = 0; i < ticketList.tagCount(); i++) {
            NBTTagCompound ticketHolder = ticketList.getCompoundTagAt(i);
            String modId = ticketHolder.getString("Owner");
            boolean isPlayer = ForgeVersion.MOD_ID.equals(modId);
            if (!isPlayer && !Loader.isModLoaded(modId)) {
                FMLLog.warning("Found chunkloading data for mod %s which is currently not available or active - it will be removed from the world save", modId);
                continue;
            }
            if (!isPlayer && !callbacks.containsKey(modId)) {
                FMLLog.warning("The mod %s has registered persistent chunkloading data but doesn't seem to want to be called back with it - it will be removed from the world save", modId);
                continue;
            }
            NBTTagList tickets = ticketHolder.getTagList("Tickets", Constants.NBT.TAG_COMPOUND);
            for (int j = 0; j < tickets.tagCount(); j++) {
                NBTTagCompound ticket = tickets.getCompoundTagAt(j);
                modId = ticket.hasKey("ModId") ? ticket.getString("ModId") : modId;
                Type type = Type.values()[ticket.getByte("Type")];
                //byte ticketChunkDepth = ticket.getByte("ChunkListDepth");
                Ticket tick = new Ticket(modId, type, world);
                if (ticket.hasKey("ModData")) {
                    tick.modData = ticket.getCompoundTag("ModData");
                }
                if (ticket.hasKey("Player")) {
                    tick.player = ticket.getString("Player");
                    if (!playerLoadedTickets.containsKey(tick.modId)) {
                        playerLoadedTickets.put(modId, ArrayListMultimap.<String, Ticket>create());
                    }
                    playerLoadedTickets.get(tick.modId).put(tick.player, tick);
                } else {
                    loadedTickets.put(modId, tick);
                }
                if (type == Type.ENTITY) {
                    tick.entityChunkX = ticket.getInteger("chunkX");
                    tick.entityChunkZ = ticket.getInteger("chunkZ");
                    UUID uuid = new UUID(ticket.getLong("PersistentIDMSB"), ticket.getLong("PersistentIDLSB"));
                    // add the ticket to the "pending entity" list
                    pendingEntities.put(uuid, tick);
                }
            }
        }
        for (Ticket tick : ImmutableSet.copyOf(pendingEntities.values())) {
            if (tick.ticketType == Type.ENTITY && tick.entity == null) {
                // force the world to load the entity's chunk
                // the load will come back through the loadEntity method and attach the entity
                // to the ticket
                world.getChunkFromChunkCoords(tick.entityChunkX, tick.entityChunkZ);
            }
        }
        for (Ticket tick : ImmutableSet.copyOf(pendingEntities.values())) {
            if (tick.ticketType == Type.ENTITY && tick.entity == null) {
                FMLLog.warning("Failed to load persistent chunkloading entity %s from store.", pendingEntities.inverse().get(tick));
                loadedTickets.remove(tick.modId, tick);
            }
        }
        pendingEntities.clear();
        // send callbacks
        for (String modId : loadedTickets.keySet()) {
            LoadingCallback loadingCallback = callbacks.get(modId);
            if (loadingCallback == null) {
                continue;
            }
            int maxTicketLength = getMaxTicketLengthFor(modId);
            List<Ticket> tickets = loadedTickets.get(modId);
            if (loadingCallback instanceof OrderedLoadingCallback) {
                OrderedLoadingCallback orderedLoadingCallback = (OrderedLoadingCallback) loadingCallback;
                tickets = orderedLoadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world, maxTicketLength);
            }
            if (tickets.size() > maxTicketLength) {
                FMLLog.warning("The mod %s has too many open chunkloading tickets %d. Excess will be dropped", modId, tickets.size());
                tickets.subList(maxTicketLength, tickets.size()).clear();
            }
            ForgeChunkManager.tickets.get(world).putAll(modId, tickets);
            loadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world);
        }
        for (String modId : playerLoadedTickets.keySet()) {
            LoadingCallback loadingCallback = callbacks.get(modId);
            if (loadingCallback == null) {
                continue;
            }
            ListMultimap<String, Ticket> tickets = playerLoadedTickets.get(modId);
            if (loadingCallback instanceof PlayerOrderedLoadingCallback) {
                PlayerOrderedLoadingCallback orderedLoadingCallback = (PlayerOrderedLoadingCallback) loadingCallback;
                tickets = orderedLoadingCallback.playerTicketsLoaded(ImmutableListMultimap.copyOf(tickets), world);
                playerTickets.putAll(tickets);
            }
            ForgeChunkManager.tickets.get(world).putAll(ForgeVersion.MOD_ID, tickets.values());
            loadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets.values()), world);
        }
    }
}
Also used : NBTTagCompound(net.minecraft.nbt.NBTTagCompound) WorldServer(net.minecraft.world.WorldServer) IOException(java.io.IOException) NBTTagList(net.minecraft.nbt.NBTTagList) ArrayListMultimap(com.google.common.collect.ArrayListMultimap) ListMultimap(com.google.common.collect.ListMultimap) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) UUID(java.util.UUID) File(java.io.File)

Example 5 with ArrayListMultimap

use of com.google.common.collect.ArrayListMultimap in project fastjson by alibaba.

the class GuavaCodec method deserialze.

public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
    Type rawType = type;
    if (type instanceof ParameterizedType) {
        rawType = ((ParameterizedType) type).getRawType();
    }
    if (rawType == ArrayListMultimap.class) {
        ArrayListMultimap multimap = ArrayListMultimap.create();
        JSONObject object = parser.parseObject();
        for (Map.Entry entry : object.entrySet()) {
            Object value = entry.getValue();
            if (value instanceof Collection) {
                multimap.putAll(entry.getKey(), (List) value);
            } else {
                multimap.put(entry.getKey(), value);
            }
        }
        return (T) multimap;
    }
    return null;
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) JSONObject(com.alibaba.fastjson.JSONObject) Collection(java.util.Collection) ArrayListMultimap(com.google.common.collect.ArrayListMultimap) JSONObject(com.alibaba.fastjson.JSONObject) Map(java.util.Map)

Aggregations

ArrayListMultimap (com.google.common.collect.ArrayListMultimap)6 ImmutableListMultimap (com.google.common.collect.ImmutableListMultimap)2 ListMultimap (com.google.common.collect.ListMultimap)2 File (java.io.File)2 IOException (java.io.IOException)2 Collection (java.util.Collection)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 UUID (java.util.UUID)2 JSONObject (com.alibaba.fastjson.JSONObject)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 Multimap (com.google.common.collect.Multimap)1 Ordering (com.google.common.collect.Ordering)1 JoinDefinition (eu.esdihumboldt.cst.functions.core.join.JoinUtil.JoinDefinition)1 JoinParameter (eu.esdihumboldt.hale.common.align.model.functions.join.JoinParameter)1 PropertyEntityDefinition (eu.esdihumboldt.hale.common.align.model.impl.PropertyEntityDefinition)1 TypeEntityDefinition (eu.esdihumboldt.hale.common.align.model.impl.TypeEntityDefinition)1 TransformationException (eu.esdihumboldt.hale.common.align.transformation.function.TransformationException)1 FamilyInstance (eu.esdihumboldt.hale.common.instance.model.FamilyInstance)1 Instance (eu.esdihumboldt.hale.common.instance.model.Instance)1