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.kegbot.app.SessionStatsFragment.java

private void updateSessionView() {
    if (mView == null) {
        return;/*from w w  w  . j a  v a  2s.  c o  m*/
    }

    mView.setVisibility(View.GONE);

    if (mSession == null) {
        return;
    }

    JsonNode stats = mStats.get("volume_by_drinker");
    if (stats == null || !stats.isObject()) {
        Log.w(TAG, "Stats error: " + stats);
        return;
    }

    mView.setVisibility(View.VISIBLE);

    Map<String, Double> volumeMap;
    try {
        volumeMap = new ObjectMapper().readValue(stats, new TypeReference<Map<String, Double>>() {
        });
    } catch (JsonMappingException e) {
        Log.w(TAG, "Stats error", e);
        return;
    } catch (IOException e) {
        Log.w(TAG, "Stats error", e);
        return;
    }

    final Ordering<String> order = Ordering.natural().reverse().onResultOf(Functions.forMap(volumeMap))
            .compound(Ordering.<String>natural());
    final Map<String, Double> volumeMapSorted = ImmutableSortedMap.copyOf(volumeMap, order);

    // Session name.
    final String sessionName = mSession.getName();
    ((TextView) mView.findViewById(R.id.sessionTitle)).setText(sessionName);

    // Number of drinkers.
    final int numDrinkers = volumeMapSorted.size();
    mSessionDrinkersBadge.setBadgeValue(Integer.valueOf(numDrinkers).toString());
    mSessionDrinkersBadge.setBadgeCaption(numDrinkers == 1 ? "Drinker" : "Drinkers");

    // Total volume.
    final Pair<String, String> qty = Units.localize(mCore.getConfiguration(), mSession.getVolumeMl());
    mSessionVolumeBadge.setBadgeValue(qty.first);
    mSessionVolumeBadge.setBadgeCaption(String.format("Total %s", Units.capitalizeUnits(qty.second)));

    final BadgeView[] badges = { mDrinker1Badge, mDrinker2Badge, mDrinker3Badge };

    int i = 0;
    for (Map.Entry<String, Double> entry : volumeMapSorted.entrySet()) {
        if (i >= badges.length) {
            break;
        }
        final BadgeView badge = badges[i++];

        badge.setVisibility(View.VISIBLE);

        String strname = entry.getKey();
        if (strname.isEmpty()) {
            strname = "anonymous";
        }

        badge.setBadgeValue(strname);
        final Pair<String, String> drinkerQty = Units.localize(mCore.getConfiguration(),
                entry.getValue().doubleValue());
        badge.setBadgeCaption(String.format("%s %s", drinkerQty.first, drinkerQty.second));
    }

    for (; i < badges.length; i++) {
        final BadgeView badge = badges[i];
        badge.setVisibility(View.GONE);
    }

}

From source file:org.apache.ctakes.relationextractor.ae.baselines.Baseline2EntityMentionPairRelationExtractorAnnotator.java

@Override
public List<IdentifiedAnnotationPair> getCandidateRelationArgumentPairs(JCas identifiedAnnotationView,
        Annotation sentence) {//from w  ww.  j  ava 2s.  c o m

    // collect all possible relation arguments from the sentence
    List<EntityMention> args = JCasUtil.selectCovered(identifiedAnnotationView, EntityMention.class, sentence);

    // Create pairings
    List<IdentifiedAnnotationPair> pairs = new ArrayList<IdentifiedAnnotationPair>();
    for (EntityMention arg1 : args) {
        for (EntityMention arg2 : args) {
            if (arg1.getBegin() == arg2.getBegin() && arg1.getEnd() == arg2.getEnd()) {
                continue;
            }
            pairs.add(new IdentifiedAnnotationPair(arg1, arg2));
        }
    }

    // look for sentences with one legitimate arg2 and multiple anatomical sties (arg1)
    int legitimateArg1Count = 0;
    int legitimateArg2Count = 0;
    for (EntityMention entityMention : args) {
        if (entityMention.getTypeID() == 6) {
            legitimateArg1Count++;
        }
        HashSet<Integer> okArg2Types = new HashSet<Integer>(Arrays.asList(2, 3, 5));
        if (okArg2Types.contains(entityMention.getTypeID())) {
            legitimateArg2Count++;
        }
    }
    if (!(legitimateArg1Count >= 1 && legitimateArg2Count == 1)) {
        return new ArrayList<IdentifiedAnnotationPair>();
    }

    // compute distance between entities for the pairs where entity types are correct
    HashMap<IdentifiedAnnotationPair, Integer> distanceLookup = new HashMap<IdentifiedAnnotationPair, Integer>();
    for (IdentifiedAnnotationPair pair : pairs) {
        if (Utils.validateLocationOfArgumentTypes(pair)) {
            try {
                int distance = Utils.getDistance(identifiedAnnotationView.getView(CAS.NAME_DEFAULT_SOFA), pair);
                distanceLookup.put(pair, distance);
            } catch (CASException e) {
                System.out.println("couldn't get default sofa");
                break;
            }
        }
    }

    if (distanceLookup.isEmpty()) {
        return new ArrayList<IdentifiedAnnotationPair>(); // no pairs with suitable argument types
    }

    // find the pair where the distance between entities is the smallest and return it
    List<IdentifiedAnnotationPair> rankedPairs = new ArrayList<IdentifiedAnnotationPair>(
            distanceLookup.keySet());
    Function<IdentifiedAnnotationPair, Integer> getValue = Functions.forMap(distanceLookup);
    Collections.sort(rankedPairs, Ordering.natural().onResultOf(getValue));

    List<IdentifiedAnnotationPair> result = new ArrayList<IdentifiedAnnotationPair>();
    result.add(rankedPairs.get(0));

    System.out.println(sentence.getCoveredText());
    System.out.println("arg1: " + result.get(0).getArg1().getCoveredText());
    System.out.println("arg2: " + result.get(0).getArg2().getCoveredText());
    System.out.println();

    return result;
}

From source file:it.anyplace.sync.discovery.protocol.ld.LocalDiscorveryHandler.java

public List<DeviceAddress> queryAndClose(final Set<String> deviceIds) {
    try {//from w  w  w. ja  v a 2  s. c o  m
        final Object lock = new Object();
        synchronized (lock) {
            eventBus.register(new Object() {
                @Subscribe
                public void handleMessageReceivedEvent(MessageReceivedEvent event) {
                    if (deviceIds.contains(event.getDeviceId())) {
                        synchronized (lock) {
                            lock.notify();
                        }
                    }
                }
            });
            startListener();
            sendAnnounceMessage();
            try {
                lock.wait(MAX_WAIT);
            } catch (InterruptedException ex) {
            }
            synchronized (localDiscoveryRecords) {
                return Lists.newArrayList(Iterables.concat(
                        Iterables.transform(deviceIds, Functions.forMap(localDiscoveryRecords.asMap()))));
            }
        }
    } finally {
        close();
    }
}

From source file:org.apache.brooklyn.location.jclouds.JcloudsStubTemplateBuilder.java

public TemplateBuilder createTemplateBuilder() {
    final Supplier<Set<? extends Image>> images = Suppliers
            .<Set<? extends Image>>ofInstance(ImmutableSet.of(getImage()));
    ImmutableMap<RegionAndName, Image> imageMap = (ImmutableMap<RegionAndName, Image>) ImagesToRegionAndIdMap
            .imagesToMap(images.get());/*from   w  ww .  ja v a  2 s  .c  om*/
    Supplier<LoadingCache<RegionAndName, ? extends Image>> imageCache = Suppliers
            .<LoadingCache<RegionAndName, ? extends Image>>ofInstance(CacheBuilder.newBuilder()
                    .<RegionAndName, Image>build(CacheLoader.from(Functions.forMap(imageMap))));
    return newTemplateBuilder(images, imageCache);
}

From source file:org.jahia.services.templates.ComponentRegistry.java

public static Map<String, String> getComponentTypes(final JCRNodeWrapper node,
        final List<String> includeTypeList, final List<String> excludeTypeList, Locale displayLocale)
        throws PathNotFoundException, RepositoryException {

    long timer = System.currentTimeMillis();

    if (displayLocale == null) {
        displayLocale = node.getSession().getLocale();
    }/*ww  w  . j  a v  a  2 s.  c o  m*/

    Map<String, String> finalComponents = new HashMap<String, String>();

    JCRSiteNode resolvedSite = node.getResolveSite();

    String[] constraints = Patterns.SPACE.split(ConstraintsHelper.getConstraints(node));

    Set<String> l = new HashSet<String>();
    l.add("system-jahia");

    if (resolvedSite != null) {
        l.addAll(resolvedSite.getInstalledModulesWithAllDependencies());
    }

    for (String aPackage : l) {
        for (ExtendedNodeType type : NodeTypeRegistry.getInstance().getNodeTypes(aPackage)) {
            if (allowType(type, includeTypeList, excludeTypeList)) {
                for (String s : constraints) {
                    if (!finalComponents.containsKey(type.getName()) && type.isNodeType(s)) {
                        finalComponents.put(type.getName(), type.getLabel(displayLocale));
                        break;
                    }
                }
            }
        }
    }

    SortedMap<String, String> sortedComponents = new TreeMap<String, String>(
            CASE_INSENSITIVE_ORDERING.onResultOf(Functions.forMap(finalComponents)));
    sortedComponents.putAll(finalComponents);

    if (logger.isDebugEnabled()) {
        logger.debug("Execution took {} ms", (System.currentTimeMillis() - timer));
    }

    return sortedComponents;
}

From source file:com.facebook.buck.cli.TargetPatternEvaluator.java

ImmutableMap<String, ImmutableSet<QueryTarget>> resolveTargetPatterns(Iterable<String> patterns,
        ListeningExecutorService executor)
        throws InterruptedException, BuildFileParseException, BuildTargetException, IOException {
    ImmutableMap.Builder<String, ImmutableSet<QueryTarget>> resolved = ImmutableMap.builder();

    Map<String, String> unresolved = new HashMap<>();
    for (String pattern : patterns) {

        // First check if this pattern was resolved before.
        ImmutableSet<QueryTarget> targets = resolvedTargets.get(pattern);
        if (targets != null) {
            resolved.put(pattern, targets);
            continue;
        }//from   w w  w.  j a va2s  .  c om

        // Check if this is an alias.
        Set<BuildTarget> aliasTargets = buckConfig.getBuildTargetsForAlias(pattern);
        if (!aliasTargets.isEmpty()) {
            for (BuildTarget alias : aliasTargets) {
                unresolved.put(alias.getFullyQualifiedName(), pattern);
            }
        } else {
            // Check if the pattern corresponds to a build target or a path.
            if (pattern.contains("//") || pattern.startsWith(":")) {
                unresolved.put(pattern, pattern);
            } else {
                ImmutableSet<QueryTarget> fileTargets = resolveFilePattern(pattern);
                resolved.put(pattern, fileTargets);
                resolvedTargets.put(pattern, fileTargets);
            }
        }
    }

    // Resolve any remaining target patterns using the parser.
    ImmutableMap<String, ImmutableSet<QueryTarget>> results = MoreMaps.transformKeys(
            resolveBuildTargetPatterns(ImmutableList.copyOf(unresolved.keySet()), executor),
            Functions.forMap(unresolved));
    resolved.putAll(results);
    resolvedTargets.putAll(results);

    return resolved.build();
}

From source file:com.isotrol.impe3.core.engine.ATOMRenderingEngine.java

private Function<CIP, RenderContext> rc(final Ok result, final List<Frame> layout) {
    Map<CIP, RenderContext> map = Maps.newHashMap();
    for (CIPResult cr : result.getCips().values()) {
        map.put(cr.getCip(), RequestContexts.render(cr.getContext(), null, result.getQuery()));
    }//from  w  w  w  .j av a  2 s. com
    return Functions.forMap(map);
}

From source file:edu.uci.ics.jung.samples.LensDemo.java

/**
 * create an instance of a simple graph with controls to
 * demo the zoomand hyperbolic features.
 * /*w w w.  ja v a  2 s .c o m*/
 */
public LensDemo() {

    // create a simple graph for the demo
    graph = TestGraphs.getOneComponentGraph();

    graphLayout = new FRLayout<String, Number>(graph);
    graphLayout.setMaxIterations(1000);

    Dimension preferredSize = new Dimension(600, 600);
    Map<String, Point2D> map = new HashMap<String, Point2D>();
    Function<String, Point2D> vlf = Functions.forMap(map);
    grid = this.generateVertexGrid(map, preferredSize, 25);
    gridLayout = new StaticLayout<String, Number>(grid, vlf, preferredSize);

    final VisualizationModel<String, Number> visualizationModel = new DefaultVisualizationModel<String, Number>(
            graphLayout, preferredSize);
    vv = new VisualizationViewer<String, Number>(visualizationModel, preferredSize);

    PickedState<String> ps = vv.getPickedVertexState();
    PickedState<Number> pes = vv.getPickedEdgeState();
    vv.getRenderContext().setVertexFillPaintTransformer(
            new PickableVertexPaintTransformer<String>(ps, Color.red, Color.yellow));
    vv.getRenderContext().setEdgeDrawPaintTransformer(
            new PickableEdgePaintTransformer<Number>(pes, Color.black, Color.cyan));
    vv.setBackground(Color.white);

    vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());

    final Function<? super String, Shape> ovals = vv.getRenderContext().getVertexShapeTransformer();
    final Function<? super String, Shape> squares = Functions
            .<Shape>constant(new Rectangle2D.Float(-10, -10, 20, 20));

    // add a listener for ToolTips
    vv.setVertexToolTipTransformer(new ToStringLabeller());

    Container content = getContentPane();
    GraphZoomScrollPane gzsp = new GraphZoomScrollPane(vv);
    content.add(gzsp);

    /**
     * the regular graph mouse for the normal view
     */
    final DefaultModalGraphMouse<String, Number> graphMouse = new DefaultModalGraphMouse<String, Number>();

    vv.setGraphMouse(graphMouse);
    vv.addKeyListener(graphMouse.getModeKeyListener());

    hyperbolicViewSupport = new ViewLensSupport<String, Number>(vv,
            new HyperbolicShapeTransformer(vv,
                    vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW)),
            new ModalLensGraphMouse());
    hyperbolicLayoutSupport = new LayoutLensSupport<String, Number>(vv,
            new HyperbolicTransformer(vv,
                    vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT)),
            new ModalLensGraphMouse());
    magnifyViewSupport = new ViewLensSupport<String, Number>(vv,
            new MagnifyShapeTransformer(vv,
                    vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW)),
            new ModalLensGraphMouse(new LensMagnificationGraphMousePlugin(1.f, 6.f, .2f)));
    magnifyLayoutSupport = new LayoutLensSupport<String, Number>(vv,
            new MagnifyTransformer(vv,
                    vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT)),
            new ModalLensGraphMouse(new LensMagnificationGraphMousePlugin(1.f, 6.f, .2f)));
    hyperbolicLayoutSupport.getLensTransformer()
            .setLensShape(hyperbolicViewSupport.getLensTransformer().getLensShape());
    magnifyViewSupport.getLensTransformer()
            .setLensShape(hyperbolicLayoutSupport.getLensTransformer().getLensShape());
    magnifyLayoutSupport.getLensTransformer()
            .setLensShape(magnifyViewSupport.getLensTransformer().getLensShape());

    final ScalingControl scaler = new CrossoverScalingControl();

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });

    ButtonGroup radio = new ButtonGroup();
    JRadioButton normal = new JRadioButton("None");
    normal.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                if (hyperbolicViewSupport != null) {
                    hyperbolicViewSupport.deactivate();
                }
                if (hyperbolicLayoutSupport != null) {
                    hyperbolicLayoutSupport.deactivate();
                }
                if (magnifyViewSupport != null) {
                    magnifyViewSupport.deactivate();
                }
                if (magnifyLayoutSupport != null) {
                    magnifyLayoutSupport.deactivate();
                }
            }
        }
    });

    final JRadioButton hyperView = new JRadioButton("Hyperbolic View");
    hyperView.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            hyperbolicViewSupport.activate(e.getStateChange() == ItemEvent.SELECTED);
        }
    });
    final JRadioButton hyperModel = new JRadioButton("Hyperbolic Layout");
    hyperModel.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            hyperbolicLayoutSupport.activate(e.getStateChange() == ItemEvent.SELECTED);
        }
    });
    final JRadioButton magnifyView = new JRadioButton("Magnified View");
    magnifyView.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            magnifyViewSupport.activate(e.getStateChange() == ItemEvent.SELECTED);
        }
    });
    final JRadioButton magnifyModel = new JRadioButton("Magnified Layout");
    magnifyModel.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            magnifyLayoutSupport.activate(e.getStateChange() == ItemEvent.SELECTED);
        }
    });
    JLabel modeLabel = new JLabel("     Mode Menu >>");
    modeLabel.setUI(new VerticalLabelUI(false));
    radio.add(normal);
    radio.add(hyperModel);
    radio.add(hyperView);
    radio.add(magnifyModel);
    radio.add(magnifyView);
    normal.setSelected(true);

    graphMouse.addItemListener(hyperbolicLayoutSupport.getGraphMouse().getModeListener());
    graphMouse.addItemListener(hyperbolicViewSupport.getGraphMouse().getModeListener());
    graphMouse.addItemListener(magnifyLayoutSupport.getGraphMouse().getModeListener());
    graphMouse.addItemListener(magnifyViewSupport.getGraphMouse().getModeListener());

    ButtonGroup graphRadio = new ButtonGroup();
    JRadioButton graphButton = new JRadioButton("Graph");
    graphButton.setSelected(true);
    graphButton.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                visualizationModel.setGraphLayout(graphLayout);
                vv.getRenderContext().setVertexShapeTransformer(ovals);
                vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
                vv.repaint();
            }
        }
    });
    JRadioButton gridButton = new JRadioButton("Grid");
    gridButton.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                visualizationModel.setGraphLayout(gridLayout);
                vv.getRenderContext().setVertexShapeTransformer(squares);
                vv.getRenderContext().setVertexLabelTransformer(Functions.<String>constant(null));
                vv.repaint();
            }
        }
    });
    graphRadio.add(graphButton);
    graphRadio.add(gridButton);

    JPanel modePanel = new JPanel(new GridLayout(3, 1));
    modePanel.setBorder(BorderFactory.createTitledBorder("Display"));
    modePanel.add(graphButton);
    modePanel.add(gridButton);

    JMenuBar menubar = new JMenuBar();
    menubar.add(graphMouse.getModeMenu());
    gzsp.setCorner(menubar);

    Box controls = Box.createHorizontalBox();
    JPanel zoomControls = new JPanel(new GridLayout(2, 1));
    zoomControls.setBorder(BorderFactory.createTitledBorder("Zoom"));
    JPanel hyperControls = new JPanel(new GridLayout(3, 2));
    hyperControls.setBorder(BorderFactory.createTitledBorder("Examiner Lens"));
    zoomControls.add(plus);
    zoomControls.add(minus);

    hyperControls.add(normal);
    hyperControls.add(new JLabel());

    hyperControls.add(hyperModel);
    hyperControls.add(magnifyModel);

    hyperControls.add(hyperView);
    hyperControls.add(magnifyView);

    controls.add(zoomControls);
    controls.add(hyperControls);
    controls.add(modePanel);
    controls.add(modeLabel);
    content.add(controls, BorderLayout.SOUTH);
}

From source file:com.facebook.buck.distributed.DistBuildExecutor.java

private TargetGraph createTargetGraph() throws IOException, InterruptedException {
    if (targetGraph != null) {
        return targetGraph;
    }/*from   w w w  .  j a  v a2 s  . c  o  m*/

    DistributedBuildTargetGraphCodec codec = createGraphCodec();
    targetGraph = Preconditions.checkNotNull(codec.createTargetGraph(
            args.getState().getRemoteState().getTargetGraph(), Functions.forMap(args.getState().getCells())));
    return targetGraph;
}

From source file:com.technophobia.substeps.execution.ImplementationCache.java

private Collection<Object> findSuitableInstancesOf(final Class<?> methodClass) {
    final Collection<Class<?>> suitableClassDefs = Collections2.filter(instanceMap.keySet(),
            new Predicate<Class<?>>() {

                @Override//from   ww  w . j ava 2s.co m
                public boolean apply(final Class<?> instanceClass) {
                    return methodClass.isAssignableFrom(instanceClass);
                }
            });

    return Collections2.transform(suitableClassDefs, Functions.forMap(instanceMap));
}