Example usage for com.google.common.base Functions forMap

List of usage examples for com.google.common.base Functions forMap

Introduction

In this page you can find the example usage for com.google.common.base Functions forMap.

Prototype

public static <K, V> Function<K, V> forMap(Map<K, V> map) 

Source Link

Document

Returns a function which performs a map lookup.

Usage

From source file:org.eclipse.sirius.diagram.ui.internal.edit.commands.DistributeCommand.java

/**
 * Must be called only when <code>wrappedCommand</code> is initialized.
 *
 * @param partsToBounds//from w w  w  .jav a  2  s. c  o m
 *            List of parts to distribute associated with their bounds.
 */
private void distributeCentersVertically(final HashMap<IGraphicalEditPart, Rectangle> partsToBounds) {
    GetNewBoundsFunction setMiddleFunction = new GetNewBoundsFunction() {
        @Override
        public Rectangle apply(IGraphicalEditPart input) {
            Rectangle r = partsToBounds.get(input).getCopy();
            return r.setY(previousPartBounds.getCenter().y + gap - (r.height / 2));
        };
    };
    distributeCenters(partsToBounds.keySet(), new GetMiddleFunction(partsToBounds),
            new GetLeftFunction(partsToBounds), new GetRightFunction(partsToBounds),
            new GetHeightFunction(partsToBounds), new PartByMiddle(partsToBounds), setMiddleFunction,
            Functions.forMap(partsToBounds));
}

From source file:com.b2international.snowowl.snomed.datastore.converter.SnomedConceptConverter.java

private void expandDescendants(List<SnomedConcept> results, final Set<String> conceptIds, String descendantKey,
        boolean stated) {
    if (!expand().containsKey(descendantKey)) {
        return;/*from   w w w .  j  a  v a 2  s  .  c o m*/
    }

    final Options expandOptions = expand().get(descendantKey, Options.class);
    final boolean direct = checkDirect(expandOptions);

    try {

        final ExpressionBuilder expression = Expressions.builder();
        expression.filter(active());
        final ExpressionBuilder descendantFilter = Expressions.builder();
        if (stated) {
            descendantFilter.should(statedParents(conceptIds));
            if (!direct) {
                descendantFilter.should(statedAncestors(conceptIds));
            }
        } else {
            descendantFilter.should(parents(conceptIds));
            if (!direct) {
                descendantFilter.should(ancestors(conceptIds));
            }
        }
        expression.filter(descendantFilter.build());

        final Query<SnomedConceptDocument> query = Query.select(SnomedConceptDocument.class)
                .where(expression.build()).limit(Integer.MAX_VALUE).build();

        final RevisionSearcher searcher = context().service(RevisionSearcher.class);
        final Hits<SnomedConceptDocument> hits = searcher.search(query);

        if (hits.getTotal() < 1) {
            final SnomedConcepts descendants = new SnomedConcepts(0, 0);
            for (SnomedConcept concept : results) {
                if (stated) {
                    concept.setStatedDescendants(descendants);
                } else {
                    concept.setDescendants(descendants);
                }
            }
            return;
        }

        // in case of only one match and limit zero, use shortcut instead of loading all IDs and components
        // XXX won't work if number of results is greater than one, either use custom ConceptSearch or figure out how to expand descendants effectively
        final int limit = getLimit(expandOptions);
        if (conceptIds.size() == 1 && limit == 0) {
            for (SnomedConcept concept : results) {
                final SnomedConcepts descendants = new SnomedConcepts(0, hits.getTotal());
                if (stated) {
                    concept.setStatedDescendants(descendants);
                } else {
                    concept.setDescendants(descendants);
                }
            }
            return;
        }

        final Multimap<String, String> descendantsByAncestor = TreeMultimap.create();
        for (SnomedConceptDocument hit : hits) {
            final Set<String> parentsAndAncestors = newHashSet();
            if (stated) {
                parentsAndAncestors.addAll(LongSets.toStringSet(hit.getStatedParents()));
                if (!direct) {
                    parentsAndAncestors.addAll(LongSets.toStringSet(hit.getStatedAncestors()));
                }
            } else {
                parentsAndAncestors.addAll(LongSets.toStringSet(hit.getParents()));
                if (!direct) {
                    parentsAndAncestors.addAll(LongSets.toStringSet(hit.getAncestors()));
                }
            }

            parentsAndAncestors.retainAll(conceptIds);
            for (String ancestor : parentsAndAncestors) {
                descendantsByAncestor.put(ancestor, hit.getId());
            }
        }

        final Collection<String> componentIds = newHashSet(descendantsByAncestor.values());

        if (limit > 0 && !componentIds.isEmpty()) {
            // query descendants again
            final SnomedConcepts descendants = SnomedRequests.prepareSearchConcept().all().filterByActive(true)
                    .filterByIds(componentIds).setLocales(locales())
                    .setExpand(expandOptions.get("expand", Options.class)).build().execute(context());

            final Map<String, SnomedConcept> descendantsById = newHashMap();
            descendantsById.putAll(Maps.uniqueIndex(descendants, ID_FUNCTION));
            for (SnomedConcept concept : results) {
                final Collection<String> descendantIds = descendantsByAncestor.get(concept.getId());
                final List<SnomedConcept> currentDescendants = FluentIterable.from(descendantIds).limit(limit)
                        .transform(Functions.forMap(descendantsById)).toList();
                final SnomedConcepts descendantConcepts = new SnomedConcepts(currentDescendants, null, null,
                        limit, descendantIds.size());
                if (stated) {
                    concept.setStatedDescendants(descendantConcepts);
                } else {
                    concept.setDescendants(descendantConcepts);
                }
            }
        } else {
            for (SnomedConcept concept : results) {
                final Collection<String> descendantIds = descendantsByAncestor.get(concept.getId());
                final SnomedConcepts descendants = new SnomedConcepts(limit, descendantIds.size());
                if (stated) {
                    concept.setStatedDescendants(descendants);
                } else {
                    concept.setDescendants(descendants);
                }
            }
        }

    } catch (IOException e) {
        throw SnowowlRuntimeException.wrap(e);
    }
}

From source file:com.b2international.snowowl.snomed.datastore.converter.SnomedConceptConverter.java

private void expandAncestors(List<SnomedConcept> results, Set<String> conceptIds, String key, boolean stated) {
    if (!expand().containsKey(key)) {
        return;/*from  w  w w.  j av  a 2 s .com*/
    }

    final Options expandOptions = expand().get(key, Options.class);
    final boolean direct = checkDirect(expandOptions);

    final Multimap<String, String> ancestorsByDescendant = TreeMultimap.create();

    final LongToStringFunction toString = new LongToStringFunction();
    for (SnomedConcept concept : results) {
        final long[] parentIds = stated ? concept.getStatedParentIds() : concept.getParentIds();
        if (parentIds != null) {
            for (long parent : parentIds) {
                if (IComponent.ROOT_IDL != parent) {
                    ancestorsByDescendant.put(concept.getId(), toString.apply(parent));
                }
            }
        }
        if (!direct) {
            final long[] ancestorIds = stated ? concept.getStatedAncestorIds() : concept.getAncestorIds();
            if (ancestorIds != null) {
                for (long ancestor : ancestorIds) {
                    if (IComponent.ROOT_IDL != ancestor) {
                        ancestorsByDescendant.put(concept.getId(), toString.apply(ancestor));
                    }
                }
            }
        }
    }

    final int limit = getLimit(expandOptions);

    final Collection<String> componentIds = newHashSet(ancestorsByDescendant.values());

    if (limit > 0 && !componentIds.isEmpty()) {
        final SnomedConcepts ancestors = SnomedRequests.prepareSearchConcept().all().filterByActive(true)
                .filterByIds(componentIds).setLocales(locales())
                .setExpand(expandOptions.get("expand", Options.class)).build().execute(context());

        final Map<String, SnomedConcept> ancestorsById = newHashMap();
        ancestorsById.putAll(Maps.uniqueIndex(ancestors, ID_FUNCTION));
        for (SnomedConcept concept : results) {
            final Collection<String> ancestorIds = ancestorsByDescendant.get(concept.getId());
            final List<SnomedConcept> conceptAncestors = FluentIterable.from(ancestorIds).limit(limit)
                    .transform(Functions.forMap(ancestorsById)).toList();
            final SnomedConcepts ancestorConcepts = new SnomedConcepts(conceptAncestors, null, null, limit,
                    ancestorIds.size());
            if (stated) {
                concept.setStatedAncestors(ancestorConcepts);
            } else {
                concept.setAncestors(ancestorConcepts);
            }
        }
    } else {
        for (SnomedConcept concept : results) {
            final Collection<String> ancestorIds = ancestorsByDescendant.get(concept.getId());
            final SnomedConcepts ancestors = new SnomedConcepts(limit, ancestorIds.size());
            if (stated) {
                concept.setStatedAncestors(ancestors);
            } else {
                concept.setAncestors(ancestors);
            }
        }
    }
}

From source file:com.eucalyptus.loadbalancing.workflow.LoadBalancingActivitiesImpl.java

@Override
public AutoscalingGroupSetupActivityResult autoscalingGroupSetup(final String accountNumber,
        final String lbName, String instanceProfileName, String securityGroupName, List<String> zones,
        Map<String, String> zoneToSubnetIdMap) throws LoadBalancingActivityException {
    if (LoadBalancingWorkerProperties.IMAGE == null)
        throw new LoadBalancingActivityException("Loadbalancer's EMI is not configured");
    final AutoscalingGroupSetupActivityResult activityResult = new AutoscalingGroupSetupActivityResult();
    final LoadBalancer lbEntity;
    final LoadBalancer.LoadBalancerCoreView lb;
    try {//from w  w w.  j  ava  2s .  c o m
        lbEntity = LoadBalancers.getLoadbalancer(accountNumber, lbName);
        lb = lbEntity.getCoreView();
        if (zoneToSubnetIdMap == null) {
            zoneToSubnetIdMap = CollectionUtils.putAll(
                    Iterables.filter(lbEntity.getZones(), Predicates.compose(Predicates.notNull(), subnetId())),
                    Maps.<String, String>newHashMap(), name(), subnetId());
        }
    } catch (NoSuchElementException ex) {
        throw new LoadBalancingActivityException("Failed to find the loadbalancer " + lbName, ex);
    } catch (Exception ex) {
        throw new LoadBalancingActivityException("Failed due to query exception", ex);
    }

    if (zones == null)
        return null; // do nothing when zone/groups are not specified

    for (final String availabilityZone : zones) {
        final String groupName = getAutoScalingGroupName(accountNumber, lbName, availabilityZone);
        String launchConfigName = null;

        boolean asgFound = false;
        try {
            final DescribeAutoScalingGroupsResponseType response = EucalyptusActivityTasks.getInstance()
                    .describeAutoScalingGroups(Lists.newArrayList(groupName), lb.useSystemAccount());

            final List<AutoScalingGroupType> groups = response.getDescribeAutoScalingGroupsResult()
                    .getAutoScalingGroups().getMember();
            if (groups.size() > 0 && groups.get(0).getAutoScalingGroupName().equals(groupName)) {
                asgFound = true;
                launchConfigName = groups.get(0).getLaunchConfigurationName();
            }
        } catch (final Exception ex) {
            asgFound = false;
        }

        activityResult.setGroupNames(Sets.<String>newHashSet());
        activityResult.setLaunchConfigNames(Sets.<String>newHashSet());
        activityResult.setCreatedGroupNames(Sets.<String>newHashSet());
        activityResult.setCreatedLaunchConfigNames(Sets.<String>newHashSet());
        final List<String> availabilityZones = Lists.newArrayList(availabilityZone);
        String vpcZoneIdentifier = null;
        String systemVpcZoneIdentifier = null;
        if (!asgFound) {
            try {
                vpcZoneIdentifier = zoneToSubnetIdMap.isEmpty() ? null
                        : Strings.emptyToNull(Joiner.on(',').skipNulls().join(
                                Iterables.transform(availabilityZones, Functions.forMap(zoneToSubnetIdMap))));
                if (vpcZoneIdentifier != null)
                    systemVpcZoneIdentifier = LoadBalancingSystemVpcs.getSystemVpcSubnetId(vpcZoneIdentifier);
                else
                    systemVpcZoneIdentifier = null;
            } catch (final Exception ex) {
                throw new LoadBalancingActivityException("Failed to look up subnet ID", ex);
            }

            try {
                Set<String> securityGroupNamesOrIds = null;
                if (systemVpcZoneIdentifier == null) {
                    securityGroupNamesOrIds = Sets.newHashSet();
                    if (!lb.getSecurityGroupIdsToNames().isEmpty()) {
                        securityGroupNamesOrIds.addAll(lb.getSecurityGroupIdsToNames().keySet());
                    } else {
                        if (securityGroupName != null) {
                            securityGroupNamesOrIds.add(securityGroupName);
                        }
                    }
                } else { // if system VPC is used, use it's security group
                    securityGroupNamesOrIds = Sets.newHashSet();
                    securityGroupNamesOrIds
                            .add(LoadBalancingSystemVpcs.getSecurityGroupId(systemVpcZoneIdentifier));
                }

                final String KEYNAME = LoadBalancingWorkerProperties.KEYNAME;
                final String keyName = KEYNAME != null && KEYNAME.length() > 0 ? KEYNAME : null;

                final String userData = B64.standard
                        .encString(String.format("%s\n%s", getCredentialsString(), getLoadBalancerUserData(
                                LoadBalancingWorkerProperties.INIT_SCRIPT, lb.getOwnerAccountNumber())));

                launchConfigName = getLaunchConfigName(lb.getOwnerAccountNumber(), lb.getDisplayName(),
                        availabilityZone);
                EucalyptusActivityTasks.getInstance().createLaunchConfiguration(
                        LoadBalancingWorkerProperties.IMAGE, LoadBalancingWorkerProperties.INSTANCE_TYPE,
                        instanceProfileName, launchConfigName, securityGroupNamesOrIds, keyName, userData,
                        zoneToSubnetIdMap.isEmpty() ? null : false, lb.useSystemAccount());
                activityResult.getLaunchConfigNames().add(launchConfigName);
                activityResult.getCreatedLaunchConfigNames().add(launchConfigName);
            } catch (Exception ex) {
                throw new LoadBalancingActivityException("Failed to create launch configuration", ex);
            }
        }
        activityResult.getLaunchConfigNames().add(launchConfigName);

        /// FIXME 
        Integer capacity = LoadBalancingServiceProperties.getCapacityPerZone();

        if (!asgFound) {
            // create autoscaling group with the zone and desired capacity
            try {
                EucalyptusActivityTasks.getInstance().createAutoScalingGroup(groupName, availabilityZones,
                        systemVpcZoneIdentifier, capacity, launchConfigName, TAG_KEY, TAG_VALUE,
                        lb.useSystemAccount());

                activityResult.getGroupNames().add(groupName);
                activityResult.getCreatedGroupNames().add(groupName);
                if (activityResult.getNumVMsPerZone() == null || activityResult.getNumVMsPerZone() == 0) {
                    activityResult.setNumVMsPerZone(capacity);
                } else {
                    activityResult.setNumVMsPerZone(activityResult.getNumVMsPerZone() + capacity);
                }
            } catch (Exception ex) {
                throw new LoadBalancingActivityException("Failed to create autoscaling group", ex);
            }
        } else {
            try {
                EucalyptusActivityTasks.getInstance().updateAutoScalingGroup(groupName, availabilityZones,
                        capacity, launchConfigName, lb.useSystemAccount());
            } catch (Exception ex) {
                throw new LoadBalancingActivityException("Failed to update the autoscaling group", ex);
            }
        }
        activityResult.getGroupNames().add(groupName);
        if (activityResult.getNumVMsPerZone() == null || activityResult.getNumVMsPerZone() == 0) {
            activityResult.setNumVMsPerZone(capacity);
        } else {
            activityResult.setNumVMsPerZone(activityResult.getNumVMsPerZone() + capacity);
        }
        // commit ASG record to the database
        try (final TransactionResource db = Entities.transactionFor(LoadBalancerAutoScalingGroup.class)) {
            try {
                final LoadBalancerAutoScalingGroup group = Entities
                        .uniqueResult(LoadBalancerAutoScalingGroup.named(lbEntity, availabilityZone));
                if (capacity != null)
                    group.setCapacity(capacity);
            } catch (NoSuchElementException ex) {
                final LoadBalancerAutoScalingGroup group = LoadBalancerAutoScalingGroup.newInstance(lbEntity,
                        availabilityZone, vpcZoneIdentifier, systemVpcZoneIdentifier, groupName,
                        launchConfigName);
                if (capacity != null)
                    group.setCapacity(capacity);
                Entities.persist(group);
            }
            db.commit();
        } catch (final Exception ex) {
            throw new LoadBalancingActivityException("Failed to commit the database", ex);
        }
    } // end of for all zones
    return activityResult;
}

From source file:org.eclipse.sirius.ui.debug.SiriusDebugView.java

/**
 * Prints a report of which elements changed position in a sequence diagram
 * since the last call to "Store positions". Only the elements whose
 * position is different are shown (i.e. an empty report means nothing
 * changed)./*from w  w w. j  a v a  2 s. c  o  m*/
 */
private void addShowPositionChangesAction() {
    addAction("Show Position Changes", new Runnable() {
        @Override
        public void run() {
            if (selection instanceof SequenceDiagramEditPart) {
                SequenceDiagramEditPart sdep = (SequenceDiagramEditPart) selection;
                if (storedPositions != null) {
                    Map<EObject, Integer> newPositions = readVerticalPositions(sdep);
                    List<EObject> elements = Lists.newArrayList(newPositions.keySet());
                    Collections.sort(elements, Ordering.natural().onResultOf(Functions.forMap(newPositions)));
                    TabularReport report = new TabularReport("Semantic element", "Old Position", "New Position",
                            "deltaY");
                    AdapterFactoryLabelProvider lp = new AdapterFactoryLabelProvider(getAdapterFactory());
                    for (EObject element : elements) {
                        Integer oldY = storedPositions.get(element);
                        Integer newY = newPositions.get(element);
                        if (oldY != null && !oldY.equals(newY)) {
                            report.addLine(lp.getText(element), String.valueOf(oldY), String.valueOf(newY),
                                    String.valueOf(newY - oldY));
                        } else if (oldY == null) {
                            report.addLine(lp.getText(element), "-", String.valueOf(newY), "n/a");
                        } else if (newY == VerticalPositionFunction.INVALID_POSITION) {
                            report.addLine(lp.getText(element), String.valueOf(oldY), "-", "n/a");
                        }
                    }
                    setText(report.print());
                }
            }
        }
    });
}