Example usage for com.google.common.collect Maps immutableEntry

List of usage examples for com.google.common.collect Maps immutableEntry

Introduction

In this page you can find the example usage for com.google.common.collect Maps immutableEntry.

Prototype

@GwtCompatible(serializable = true)
public static <K, V> Entry<K, V> immutableEntry(@Nullable K key, @Nullable V value) 

Source Link

Document

Returns an immutable map entry with the specified key and value.

Usage

From source file:com.infinities.keystone4j.token.controller.action.AuthenticateAction.java

private Entry<Project, Set<String>> getProjectRolesAndRef(String userid, String tenantid) {
    Project tenantRef = null;//from www .  j av  a  2s  .  c  om
    Set<String> roleList = new HashSet<String>();

    if (!Strings.isNullOrEmpty(tenantid)) {
        try {
            tenantRef = assignmentApi.getProject(tenantid);
            roleList = new HashSet<String>(assignmentApi.getRolesForUserAndProject(userid, tenantid));
        } catch (Exception e) {
            // pass
        }

        if (roleList.isEmpty()) {
            String msg = String.format("User %s is unauthorized for tenant %s", userid, tenantid);
            logger.warn(msg);
            throw Exceptions.UnauthorizedException.getInstance(msg);
        }
    }
    return Maps.immutableEntry(tenantRef, roleList);
}

From source file:org.opendaylight.controller.config.util.xml.XmlElement.java

/**
 * Search for element's attributes defining namespaces. Look for the one
 * namespace that matches prefix of element's text content. E.g.
 *
 * <pre>/*from  w  ww  . ja  va  2  s.c  o  m*/
 * &lt;type
 * xmlns:th-java="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl"&gt;th-java:threadfactory-naming&lt;/type&gt;
 * </pre>
 *
 * returns {"th-java","urn:.."}. If no prefix is matched, then default
 * namespace is returned with empty string as key. If no default namespace
 * is found value will be null.
 */
public Map.Entry<String/* prefix */, String/* namespace */> findNamespaceOfTextContent()
        throws DocumentedException {
    Map<String, String> namespaces = extractNamespaces();
    String textContent = getTextContent();
    int indexOfColon = textContent.indexOf(':');
    String prefix;
    if (indexOfColon > -1) {
        prefix = textContent.substring(0, indexOfColon);
    } else {
        prefix = DEFAULT_NAMESPACE_PREFIX;
    }
    if (!namespaces.containsKey(prefix)) {
        throw new IllegalArgumentException("Cannot find namespace for " + XmlUtil.toString(element)
                + ". Prefix from content is " + prefix + ". Found namespaces " + namespaces);
    }
    return Maps.immutableEntry(prefix, namespaces.get(prefix));
}

From source file:ome.services.graphs.GraphPathBean.java

/**
 * Process the Hibernate domain object model to initialize this class' instance fields.
 * No other method should write to them.
 * @param sessionFactory the Hibernate session factory
 *///w ww  . j a v  a 2 s.co m
private void initialize(SessionFactoryImplementor sessionFactory) {
    /* note all the direct superclasses */
    final Map<String, String> superclasses = new HashMap<String, String>();
    final Map<String, ClassMetadata> classesMetadata = sessionFactory.getAllClassMetadata();
    for (final String className : classesMetadata.keySet()) {
        try {
            final Class<?> actualClass = Class.forName(className);
            if (IObject.class.isAssignableFrom(actualClass)) {
                classesBySimpleName.put(actualClass.getSimpleName(), actualClass.asSubclass(IObject.class));
                final Set<String> subclassNames = sessionFactory.getEntityPersister(className)
                        .getEntityMetamodel().getSubclassEntityNames();
                for (final String subclassName : subclassNames) {
                    if (!subclassName.equals(className)) {
                        final Class<?> actualSubclass = Class.forName(subclassName);
                        if (actualSubclass.getSuperclass() == actualClass) {
                            superclasses.put(subclassName, className);
                        }
                    }
                }
            } else {
                log.warn("mapped class " + className + " is not a " + IObject.class.getName());
            }
        } catch (ClassNotFoundException e) {
            log.error("could not instantiate class", e);
        }
    }
    /* note the indirect superclasses and subclasses */
    for (final Entry<String, String> superclassRelationship : superclasses.entrySet()) {
        final String startClass = superclassRelationship.getKey();
        String superclass = superclassRelationship.getValue();
        while (superclass != null) {
            allSuperclasses.put(startClass, superclass);
            allSubclasses.put(superclass, startClass);
            superclass = superclasses.get(superclass);
        }
    }
    /* queue for processing all the properties of all the mapped entities: name, type, nullability */
    final Queue<PropertyDetails> propertyQueue = new LinkedList<PropertyDetails>();
    final Map<String, Set<String>> allPropertyNames = new HashMap<String, Set<String>>();
    for (final Entry<String, ClassMetadata> classMetadata : classesMetadata.entrySet()) {
        final String className = classMetadata.getKey();
        final ClassMetadata metadata = classMetadata.getValue();
        /* note name of identifier property */
        classIdProperties.put(metadata.getEntityName(), metadata.getIdentifierPropertyName());
        /* queue other properties */
        final String[] propertyNames = metadata.getPropertyNames();
        final Type[] propertyTypes = metadata.getPropertyTypes();
        final boolean[] propertyNullabilities = metadata.getPropertyNullability();
        for (int i = 0; i < propertyNames.length; i++) {
            final List<String> propertyPath = Collections.singletonList(propertyNames[i]);
            propertyQueue.add(
                    new PropertyDetails(className, propertyPath, propertyTypes[i], propertyNullabilities[i]));
        }
        final Set<String> propertyNamesSet = new HashSet<String>(propertyNames.length);
        propertyNamesSet.addAll(Arrays.asList(propertyNames));
        allPropertyNames.put(className, propertyNamesSet);
    }
    /* process each property to note entity linkages */
    while (!propertyQueue.isEmpty()) {
        final PropertyDetails property = propertyQueue.remove();
        if (ignoreProperty(property.path.get(property.path.size() - 1))) {
            continue;
        }
        /* if the property has a component type, queue the parts for processing */
        if (property.type instanceof ComponentType) {
            final ComponentType componentType = (ComponentType) property.type;
            final String[] componentPropertyNames = componentType.getPropertyNames();
            final Type[] componentPropertyTypes = componentType.getSubtypes();
            final boolean[] componentPropertyNullabilities = componentType.getPropertyNullability();
            for (int i = 0; i < componentPropertyNames.length; i++) {
                final List<String> componentPropertyPath = new ArrayList<String>(property.path.size() + 1);
                componentPropertyPath.addAll(property.path);
                componentPropertyPath.add(componentPropertyNames[i]);
                propertyQueue.add(new PropertyDetails(property.holder, componentPropertyPath,
                        componentPropertyTypes[i], componentPropertyNullabilities[i]));
            }
        } else {
            /* determine if another mapped entity class is linked by this property */
            final boolean isAssociatedEntity;
            if (property.type instanceof CollectionType) {
                final CollectionType ct = (CollectionType) property.type;
                isAssociatedEntity = sessionFactory.getCollectionPersister(ct.getRole()).getElementType()
                        .isEntityType();
            } else {
                isAssociatedEntity = property.type instanceof AssociationType;
            }
            /* the property can link to entities, so process it further */
            String propertyPath = Joiner.on('.').join(property.path);
            /* find if the property is accessible (e.g., not protected) */
            boolean propertyIsAccessible = false;
            String classToInstantiateName = property.holder;
            Class<?> classToInstantiate = null;
            try {
                classToInstantiate = Class.forName(classToInstantiateName);
                while (Modifier.isAbstract(classToInstantiate.getModifiers())) {
                    classToInstantiateName = allSubclasses.get(classToInstantiateName).iterator().next();
                    classToInstantiate = Class.forName(classToInstantiateName);
                }
                try {
                    PropertyUtils.getNestedProperty(classToInstantiate.newInstance(), propertyPath);
                    propertyIsAccessible = true;
                } catch (NoSuchMethodException e) {
                    /* expected for collection properties */
                } catch (NestedNullException e) {
                    log.warn("guessing " + propertyPath + " of " + property.holder + " to be accessible");
                    propertyIsAccessible = true;
                }
            } catch (ReflectiveOperationException e) {
                log.error("could not probe property " + propertyPath + " of " + property.holder, e);
                continue;
            }
            /* build property report line for log */
            final char arrowShaft = property.isNullable ? '-' : '=';
            final StringBuffer sb = new StringBuffer();
            sb.append(property.holder);
            sb.append(' ');
            for (final String propertyName : property.path) {
                sb.append(arrowShaft);
                sb.append(arrowShaft);
                sb.append(propertyName);
            }
            sb.append(arrowShaft);
            sb.append(arrowShaft);
            sb.append("> ");
            final String valueClassName;
            if (isAssociatedEntity) {
                valueClassName = ((AssociationType) property.type).getAssociatedEntityName(sessionFactory);
                sb.append(valueClassName);
            } else {
                valueClassName = null;
                sb.append("value");
            }
            if (property.type.isCollectionType()) {
                sb.append("[]");
            }
            if (!propertyIsAccessible) {
                sb.append(" (inaccessible)");
            }
            /* determine from which class the property is inherited, if at all */
            String superclassWithProperty = null;
            String currentClass = property.holder;
            while (true) {
                currentClass = superclasses.get(currentClass);
                if (currentClass == null) {
                    break;
                } else if (allPropertyNames.get(currentClass).contains(property.path.get(0))) {
                    superclassWithProperty = currentClass;
                }
            }
            /* check if the property actually comes from an interface */
            final String declaringClassName = superclassWithProperty == null ? property.holder
                    : superclassWithProperty;
            final Class<? extends IObject> interfaceForProperty = getInterfaceForProperty(declaringClassName,
                    property.path.get(0));
            /* report where the property is declared */
            if (superclassWithProperty != null) {
                sb.append(" from ");
                sb.append(superclassWithProperty);
            } else {
                if (interfaceForProperty != null) {
                    sb.append(" see ");
                    sb.append(interfaceForProperty.getName());
                    /* It would be nice to set PropertyDetails to have the interface as the holder,
                     * but then properties would not be unique by declarer class and instance ID. */
                }
                /* entity linkages by non-inherited properties are recorded */
                if (valueClassName == null && property.path.size() > 1) {
                    /* assume that the top-level property suffices for describing simple properties */
                    log.debug("recording " + propertyPath + " as " + property.path.get(0));
                    propertyPath = property.path.get(0);
                }
                final Entry<String, String> classPropertyName = Maps.immutableEntry(property.holder,
                        propertyPath);
                if (valueClassName == null) {
                    simpleProperties.put(property.holder, propertyPath);
                } else {
                    linkedTo.put(property.holder, Maps.immutableEntry(valueClassName, propertyPath));
                    linkedBy.put(valueClassName, classPropertyName);
                }
                final PropertyKind propertyKind;
                if (property.type.isCollectionType()) {
                    propertyKind = PropertyKind.COLLECTION;
                } else if (property.isNullable) {
                    propertyKind = PropertyKind.OPTIONAL;
                } else {
                    propertyKind = PropertyKind.REQUIRED;
                }
                propertyKinds.put(classPropertyName, propertyKind);
                if (propertyIsAccessible) {
                    accessibleProperties.add(classPropertyName);
                }
            }
            if (log.isDebugEnabled()) {
                log.debug(sb.toString());
            }
        }
    }
    log.info("initialized graph path bean with " + propertyKinds.size() + " properties");
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java

/** Get a set of field mappings from the "dynamic_templates" section of a mapping
 * @param index//from  w  ww.ja  va2s  .  c  o m
 * @return
 */
protected static LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> getTemplates(
        final JsonNode index, final JsonNode default_string_mapping,
        final Set<Either<String, Tuple2<String, String>>> already_processed) {
    return Optional.ofNullable(index.get("dynamic_templates")).filter(p -> !p.isNull()).map(p -> {
        if (!p.isArray())
            throw new RuntimeException("dynamic_templates must be object");
        return p;
    }).map(p -> {
        return StreamSupport
                .stream(Spliterators.spliteratorUnknownSize(p.elements(), Spliterator.ORDERED), false)
                .map(pf -> {
                    if (!pf.isObject())
                        throw new RuntimeException("dynamic_templates[*] must be object");
                    return pf;
                })
                .flatMap(pp -> StreamSupport
                        .stream(Spliterators.spliteratorUnknownSize(pp.fields(), Spliterator.ORDERED), false))
                .filter(kv -> !kv.getKey().equals(STRING_OVERRIDE_NAME)
                        || !already_processed.contains(Either.right(Tuples._2T("*", "string")))) // (don't override a specified string)
                .map(kv -> !kv.getKey().equals(STRING_OVERRIDE_NAME) ? kv
                        : Maps.immutableEntry(kv.getKey(), default_string_mapping)) //(special case - overwrite with system default)
                .collect(
                        Collectors.<Map.Entry<String, JsonNode>, Either<String, Tuple2<String, String>>, JsonNode, LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode>>toMap(
                                kv -> Either.right(buildMatchPair(kv.getValue())), kv -> kv.getValue(),
                                (v1, v2) -> v1, // (should never happen)
                                () -> new LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode>()));
    }).orElse(new LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode>());
}

From source file:me.lucko.luckperms.common.storage.dao.file.AbstractConfigurateDao.java

private static Map.Entry<String, ConfigurationNode> parseEntry(ConfigurationNode appended,
        String keyFieldName) {/*  w w  w  .  j a va2 s  .c o m*/
    if (!appended.hasMapChildren()) {
        return null;
    }

    Map<Object, ? extends ConfigurationNode> children = appended.getChildrenMap();
    if (children.isEmpty()) {
        return null;
    }

    // if children.size == 1 and the only entry doesn't have a key called "permission" - assume
    // the key refers to the name of the permission
    if (children.size() == 1) {
        Map.Entry<Object, ? extends ConfigurationNode> entry = Iterables.getFirst(children.entrySet(), null);
        if (entry != null) {
            String permission = entry.getKey().toString();
            ConfigurationNode attributes = entry.getValue();

            if (!permission.equals(keyFieldName)) {
                return Maps.immutableEntry(permission, attributes);
            }
        }
    }

    // assume 'appended' is the actual entry.
    String permission = children.get(keyFieldName).getString(null);
    if (permission == null) {
        return null;
    }

    return Maps.immutableEntry(permission, appended);
}

From source file:org.jooby.exec.Exec.java

protected void configure(final Env env, final Config conf, final Binder binder,
        final BiConsumer<String, Executor> callback) {
    List<Map<String, Object>> executors = conf.hasPath(namespace)
            ? executors(conf.getValue(namespace), daemon, priority, Runtime.getRuntime().availableProcessors())
            : Collections.emptyList();
    List<Entry<String, ExecutorService>> services = new ArrayList<>(executors.size());
    for (Map<String, Object> options : executors) {
        // thread factory options
        String name = (String) options.remove("name");
        log.debug("found executor: {}{}", name, options);
        Boolean daemon = (Boolean) options.remove("daemon");
        Integer priority = (Integer) options.remove("priority");
        String type = String.valueOf(options.remove("type"));
        // number of processors
        Integer n = (Integer) options.remove(type);

        // create executor
        Throwing.Function4<String, Integer, Supplier<ThreadFactory>, Map<String, Object>, ExecutorService> factory = f
                .get(type);//from ww w . jav  a  2 s.  com
        if (factory == null) {
            throw new IllegalArgumentException("Unknown executor: " + type + " must be one of " + f.keySet());
        }
        ExecutorService executor = factory.apply(type, n, () -> factory(name, daemon, priority), options);

        bind(binder, name, executor);
        callback.accept(name, executor);

        services.add(Maps.immutableEntry(name, executor));
    }

    services.stream().filter(it -> it.getKey().equals("default")).findFirst()
            .ifPresent(e -> bind(binder, null, e.getValue()));

    env.onStop(() -> {
        services.forEach(exec -> Try.run(() -> exec.getValue().shutdown())
                .onFailure(cause -> log.error("shutdown of {} resulted in error", exec.getKey(), cause)));
        services.clear();
    });
}

From source file:uk.ac.cam.cl.dtg.segue.dao.content.GitContentManager.java

@Override
public ContentDTO populateRelatedContent(final String version, final ContentDTO contentDTO)
        throws ContentManagerException {
    if (contentDTO.getRelatedContent() == null || contentDTO.getRelatedContent().isEmpty()) {
        return contentDTO;
    }//from  w ww .  j av a2  s .c o m

    // build query the db to get full content information
    Map<Map.Entry<Constants.BooleanOperator, String>, List<String>> fieldsToMap = new HashMap<>();

    List<String> relatedContentIds = Lists.newArrayList();
    for (ContentSummaryDTO summary : contentDTO.getRelatedContent()) {
        relatedContentIds.add(summary.getId());
    }

    fieldsToMap.put(
            Maps.immutableEntry(Constants.BooleanOperator.OR,
                    Constants.ID_FIELDNAME + '.' + Constants.UNPROCESSED_SEARCH_FIELD_SUFFIX),
            relatedContentIds);

    ResultsWrapper<ContentDTO> results = this.findByFieldNames(version, fieldsToMap, 0,
            relatedContentIds.size());

    List<ContentSummaryDTO> relatedContentDTOs = Lists.newArrayList();

    for (ContentDTO relatedContent : results.getResults()) {
        ContentSummaryDTO summary = this.mapper.getAutoMapper().map(relatedContent, ContentSummaryDTO.class);
        relatedContentDTOs.add(summary);
    }

    contentDTO.setRelatedContent(relatedContentDTOs);

    return contentDTO;
}

From source file:org.apache.tephra.hbase.txprune.HBaseTransactionPruningPlugin.java

private void logPruneUpperBoundRegions(Map<byte[], Long> pruneUpperBoundRegions) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Got region - prune upper bound map: {}",
                Iterables.transform(pruneUpperBoundRegions.entrySet(),
                        new Function<Map.Entry<byte[], Long>, Map.Entry<String, Long>>() {
                            @Override
                            public Map.Entry<String, Long> apply(Map.Entry<byte[], Long> input) {
                                String regionName = TimeRegions.BYTE_ARR_TO_STRING_FN.apply(input.getKey());
                                return Maps.immutableEntry(regionName, input.getValue());
                            }/*from   w  w  w . j  a  v a2 s.  c  o m*/
                        }));
    }
}

From source file:me.lucko.luckperms.common.core.model.PermissionHolder.java

public MetaHolder accumulateMeta(MetaHolder holder, List<String> excludedGroups, ExtractedContexts contexts) {
    if (holder == null) {
        holder = new MetaHolder(plugin.getConfiguration().get(ConfigKeys.PREFIX_FORMATTING_OPTIONS).copy(),
                plugin.getConfiguration().get(ConfigKeys.SUFFIX_FORMATTING_OPTIONS).copy());
    }//  w w  w. j  a  v  a  2 s  .c  o  m

    if (excludedGroups == null) {
        excludedGroups = new ArrayList<>();
    }

    excludedGroups.add(getObjectName().toLowerCase());

    Contexts context = contexts.getContexts();
    String server = contexts.getServer();
    String world = contexts.getWorld();

    SortedSet<LocalizedNode> all = new TreeSet<>((SortedSet<LocalizedNode>) getPermissions(true));
    for (LocalizedNode ln : all) {
        Node n = ln.getNode();

        if (!n.getValue())
            continue;
        if (!n.isMeta() && !n.isPrefix() && !n.isSuffix())
            continue;
        if (!n.shouldApplyOnServer(server, context.isIncludeGlobal(), false))
            continue;
        if (!n.shouldApplyOnWorld(world, context.isIncludeGlobalWorld(), false))
            continue;
        if (!n.shouldApplyWithContext(contexts.getContextSet(), false))
            continue;

        holder.accumulateNode(ln);
    }

    Set<Node> parents = all.stream().map(LocalizedNode::getNode).filter(Node::getValue)
            .filter(Node::isGroupNode).collect(Collectors.toSet());

    parents.removeIf(node -> !node.shouldApplyOnServer(server, context.isApplyGlobalGroups(),
            plugin.getConfiguration().get(ConfigKeys.APPLYING_REGEX))
            || !node.shouldApplyOnWorld(world, context.isApplyGlobalWorldGroups(),
                    plugin.getConfiguration().get(ConfigKeys.APPLYING_REGEX))
            || !node.shouldApplyWithContext(contexts.getContextSet(), false));

    TreeSet<Map.Entry<Integer, Node>> sortedParents = new TreeSet<>(Util.META_COMPARATOR.reversed());
    for (Node node : parents) {
        Group group = plugin.getGroupManager().getIfLoaded(node.getGroupName());
        if (group != null) {
            OptionalInt weight = group.getWeight();
            if (weight.isPresent()) {
                sortedParents.add(Maps.immutableEntry(weight.getAsInt(), node));
                continue;
            }
        }

        sortedParents.add(Maps.immutableEntry(0, node));
    }

    for (Map.Entry<Integer, Node> e : sortedParents) {
        Node parent = e.getValue();
        Group group = plugin.getGroupManager().getIfLoaded(parent.getGroupName());
        if (group == null) {
            continue;
        }

        if (excludedGroups.contains(group.getObjectName().toLowerCase())) {
            continue;
        }

        group.accumulateMeta(holder, excludedGroups, contexts);
    }

    return holder;
}

From source file:com.palantir.atlasdb.transaction.impl.SerializableTransaction.java

private void verifyRanges(Transaction ro) {
    // verify each set of reads to ensure they are the same.
    for (String table : rangeEndByTable.keySet()) {
        for (Entry<RangeRequest, byte[]> e : rangeEndByTable.get(table).entrySet()) {
            RangeRequest range = e.getKey();
            byte[] rangeEnd = e.getValue();
            if (rangeEnd.length != 0 && !RangeRequests.isTerminalRow(range.isReverse(), rangeEnd)) {
                range = range.getBuilder()
                        .endRowExclusive(RangeRequests.getNextStartRow(range.isReverse(), rangeEnd)).build();
            }//  ww w. j  av a2  s .co m

            final ConcurrentNavigableMap<Cell, byte[]> writes = writesByTable.get(table);
            BatchingVisitableView<RowResult<byte[]>> bv = BatchingVisitableView.of(ro.getRange(table, range));
            NavigableMap<Cell, ByteBuffer> readsInRange = Maps.transformValues(getReadsInRange(table, e, range),
                    new Function<byte[], ByteBuffer>() {
                        @Override
                        public ByteBuffer apply(byte[] input) {
                            return ByteBuffer.wrap(input);
                        }
                    });
            boolean isEqual = bv
                    .transformBatch(new Function<List<RowResult<byte[]>>, List<Entry<Cell, ByteBuffer>>>() {
                        @Override
                        public List<Entry<Cell, ByteBuffer>> apply(List<RowResult<byte[]>> input) {
                            List<Entry<Cell, ByteBuffer>> ret = Lists.newArrayList();
                            for (RowResult<byte[]> row : input) {
                                for (Entry<Cell, byte[]> cell : row.getCells()) {

                                    // NB: We filter our write set out here because our normal SI checking handles this case to ensure the value hasn't changed.
                                    if (writes == null || !writes.containsKey(cell.getKey())) {
                                        ret.add(Maps.immutableEntry(cell.getKey(),
                                                ByteBuffer.wrap(cell.getValue())));
                                    }
                                }
                            }
                            return ret;
                        }
                    }).isEqual(readsInRange.entrySet());
            if (!isEqual) {
                throw TransactionSerializableConflictException.create(table, getTimestamp(),
                        System.currentTimeMillis() - timeCreated);
            }
        }
    }
}