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));
}
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;
}
};
}
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);
}
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);
}
}
}
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;
}
Aggregations