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

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

Introduction

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

Prototype

@GwtIncompatible("NavigableMap")
public static <K, V1, V2> NavigableMap<K, V2> transformEntries(NavigableMap<K, V1> fromMap,
        EntryTransformer<? super K, ? super V1, V2> transformer) 

Source Link

Document

Returns a view of a navigable map whose values are derived from the original navigable map's entries.

Usage

From source file:com.spotify.helios.ZooKeeperClusterTestManager.java

private Map<Long, InetSocketAddress> allocateAddresses(final Map<Long, QuorumServer> peers) {
    return ImmutableMap.copyOf(
            Maps.transformEntries(peers, new Maps.EntryTransformer<Long, QuorumServer, InetSocketAddress>() {
                @Override/*from  www .  j  a  v a 2  s.  c o  m*/
                public InetSocketAddress transformEntry(@Nullable final Long key,
                        @Nullable final QuorumServer value) {
                    final int port = temporaryPorts.localPort("zk-client-" + key);
                    return new InetSocketAddress("127.0.0.1", port);
                }
            }));
}

From source file:com.simiacryptus.util.binary.bitset.CountTreeBitsCollection.java

private void write(final BitOutputStream out, final Bits currentCode, final NavigableMap<Bits, Long> sums)
        throws IOException {
    final Entry<Bits, Long> firstEntry = sums.firstEntry();
    final NavigableMap<Bits, Long> remainder = sums.tailMap(currentCode, false);
    final Bits splitCode = currentCode.concatenate(Bits.ONE);
    final NavigableMap<Bits, Long> zeroMap = remainder.headMap(splitCode, false);
    final NavigableMap<Bits, Long> oneMap = remainder.tailMap(splitCode, true);

    final int firstEntryCount = this.map.get(firstEntry.getKey()).get();
    final long baseCount = firstEntry.getValue() - firstEntryCount;
    final long endCount = sums.lastEntry().getValue();
    final long size = endCount - baseCount;

    final long terminals = firstEntry.getKey().equals(currentCode) ? firstEntryCount : 0;
    final long zeroCount = 0 == zeroMap.size() ? 0 : zeroMap.lastEntry().getValue() - baseCount - terminals;
    final long oneCount = size - terminals - zeroCount;

    final EntryTransformer<Bits, Long, Long> transformer = new EntryTransformer<Bits, Long, Long>() {
        @Override//from   ww  w. jav  a2  s  .  co m
        public Long transformEntry(final Bits key, final Long value) {
            return (long) CountTreeBitsCollection.this.map.get(key).get();
        }
    };
    assert size == this.sum(Maps.transformEntries(sums, transformer).values());
    assert zeroCount == this.sum(Maps.transformEntries(zeroMap, transformer).values());
    assert oneCount == this.sum(Maps.transformEntries(oneMap, transformer).values());

    final BranchCounts branchCounts = new BranchCounts(currentCode, size, terminals, zeroCount, oneCount);

    if (SERIALIZATION_CHECKS) {
        out.write(SerializationChecks.StartTree);
    }
    this.writeBranchCounts(branchCounts, out);
    if (0 < zeroCount) {
        this.write(out, currentCode.concatenate(Bits.ZERO), zeroMap);
    }
    if (0 < oneCount) {
        this.write(out, currentCode.concatenate(Bits.ONE), oneMap);
    }
    if (SERIALIZATION_CHECKS) {
        out.write(SerializationChecks.EndTree);
    }
}

From source file:com.google.gerrit.server.plugins.JarScanner.java

private Map<Object, String> attributesOf(JarEntry jarEntry) throws IOException {
    Attributes attributes = jarEntry.getAttributes();
    if (attributes == null) {
        return Collections.emptyMap();
    }//  w w w . j  av  a  2s.c om
    return Maps.transformEntries(attributes, new Maps.EntryTransformer<Object, Object, String>() {
        @Override
        public String transformEntry(Object key, Object value) {
            return (String) value;
        }
    });
}

From source file:additionalpipes.inventory.ContainerTeleportManager.java

private void rebuildPipeProps() {
    ListMultimap<PropertyInteger, ITeleportPipe> pipeMultimap = ArrayListMultimap.create();
    for (ITeleportPipe pipe : TeleportManager.getPipes()) {
        for (int map : manager.getMapsLinkTo(pipe)) {
            pipeMultimap.put(PropertyInteger.create(map), pipe);
        }//from  w w  w . j  a  v a 2 s .  c om
    }
    pipes = Maps.newHashMap(Maps.transformEntries(pipeMultimap.asMap(),
            new EntryTransformer<PropertyInteger, Collection<ITeleportPipe>, PropertyIntArray>() {
                @Override
                public PropertyIntArray transformEntry(PropertyInteger key, Collection<ITeleportPipe> value) {
                    int[] result = new int[value.size() * 3];
                    int i = 0;
                    for (ITeleportPipe pipe : value) {
                        result[i++] = pipe.getType().ordinal();
                        ChunkCoordinates pos = pipe.getPosition();
                        MapData mapData = Item.map.getMapData(
                                APUtils.createMapStack(key.value, manager.worldObj), manager.worldObj);
                        int size = 1 << mapData.scale;
                        float var11 = (pos.posX - mapData.xCenter) / (float) size;
                        float var12 = (pos.posZ - mapData.zCenter) / (float) size;
                        result[i++] = (int) (var11 * 2.0F + 0.5D);
                        result[i++] = (int) (var12 * 2.0F + 0.5D);
                    }
                    return PropertyIntArray.create(result);
                }
            }));

    if (!needToRebuild) {
        MinecraftForge.EVENT_BUS.post(new ContainerModifyEvent(this, manager));
    }
}

From source file:info.bunji.mongodb.synces.elasticsearch.EsStatusChecker.java

@Override
public Map<String, SyncConfig> getConfigs(boolean withExtendInfo) {
    // get configs from elasticsearch.
    SearchResponse res = esClient.prepareSearch(CONFIG_INDEX).setTypes("config", "status")
            .addSort(SortBuilders.fieldSort("_type")).setSize(1000).execute().actionGet();

    // failed shards check
    if (res.getFailedShards() > 0) {
        logger.trace("failure shards found in config index.");
        throw new IndexNotFoundException("failed shards found.");
    }//from www . j av  a 2  s.  c  om

    List<String> indexNames = new ArrayList<>();
    Map<String, SyncConfig> configMap = new TreeMap<>();
    for (SearchHit hit : res.getHits().getHits()) {
        String syncName = hit.getId();
        String type = hit.getType();
        if ("config".equals(type)) {
            SyncConfig config = gson.fromJson(hit.getSourceAsString(), SyncConfig.class);
            config.setSyncName(syncName);
            config.setConfigDbName(CONFIG_INDEX);
            configMap.put(syncName, config);
            indexNames.add(config.getDestDbName());
        } else if ("status".equals(type) && configMap.containsKey(syncName)) {
            SyncConfig config = configMap.get(hit.getId());
            SyncStatus status = new SyncStatus(hit.sourceAsMap());
            config.setStatus(status.getStatus());
            config.setLastOpTime(status.getLastOpTime());
            config.setLastSyncTime(status.getLastSyncTime());
            if (getIndexer(config.getSyncName()) != null) {
                config.addSyncCount(getIndexer(config.getSyncName()).getConfig().getSyncCount());
            }
        }
    }

    // get index aliases
    if (withExtendInfo) {
        try {
            final Map<String, Collection<String>> aliasMap = EsUtils.getIndexAliases(esClient, indexNames);
            configMap = Maps.transformEntries(configMap,
                    new EntryTransformer<String, SyncConfig, SyncConfig>() {
                        @Override
                        public SyncConfig transformEntry(String syncName, SyncConfig config) {
                            config.getExtendInfo().put("aliases", aliasMap.get(config.getDestDbName()));
                            return config;
                        }
                    });
        } catch (Exception e) {
            // do nothing.
        }
    }
    return configMap;
}

From source file:org.sonatype.nexus.extdirect.internal.ExtDirectServlet.java

@Override
protected RequestRouter createRequestRouter(final Registry registry,
        final GlobalConfiguration globalConfiguration) {
    final Dispatcher dispatcher = createDispatcher(globalConfiguration.getDispatcherClass());
    return new RequestRouter(registry, globalConfiguration, dispatcher) {
        @Override//from ww  w . j  a  v a 2  s  .co  m
        public void processPollRequest(final Reader reader, final Writer writer, final String pathInfo)
                throws IOException {
            new PollRequestProcessor(registry, dispatcher, globalConfiguration) {
                @Override
                // HACK: we determine parameters from request not by reading request content as request content could had
                // been already read exactly for getting the params, case when request content is already empty
                protected Object[] getParameters() {
                    if (reader instanceof RequestBoundReader) {
                        ServletRequest request = ((RequestBoundReader) reader).getRequest();
                        Map<String, String[]> parameterMap = request.getParameterMap();
                        Map<String, String> parameters = Maps.newHashMap();
                        if (parameterMap != null) {
                            parameters = Maps.transformEntries(parameterMap,
                                    new EntryTransformer<String, String[], String>() {
                                        @Override
                                        public String transformEntry(@Nullable final String key,
                                                @Nullable final String[] values) {
                                            return values == null || values.length == 0 ? null : values[0];
                                        }
                                    });
                        }
                        return new Object[] { parameters };
                    }
                    return super.getParameters();
                }
            }.process(reader, writer, pathInfo);
        }
    };
}

From source file:com.android.tools.idea.avdmanager.AvdEditWizard.java

@Override
public void performFinishingActions() {
    Device device = myState.get(DEVICE_DEFINITION_KEY);
    assert device != null; // Validation should be done by individual steps
    SystemImageDescription systemImageDescription = myState.get(SYSTEM_IMAGE_KEY);
    assert systemImageDescription != null;
    ScreenOrientation orientation = myState.get(DEFAULT_ORIENTATION_KEY);
    if (orientation == null) {
        orientation = device.getDefaultState().getOrientation();
    }/*from   w  ww  .j a  va 2  s . co  m*/

    Map<String, String> hardwareProperties = DeviceManager.getHardwareProperties(device);
    Map<String, Object> userEditedProperties = myState.flatten();

    // Remove the SD card setting that we're not using
    String sdCard = null;

    Boolean useExternalSdCard = myState.get(DISPLAY_USE_EXTERNAL_SD_KEY);
    boolean useExisting = useExternalSdCard != null && useExternalSdCard;
    if (!useExisting) {
        if (Objects.equal(myState.get(SD_CARD_STORAGE_KEY), myState.get(DISPLAY_SD_SIZE_KEY))) {
            // unchanged, use existing card
            useExisting = true;
        }
    }
    boolean hasSdCard;
    if (!useExisting) {
        userEditedProperties.remove(EXISTING_SD_LOCATION.name);
        Storage storage = myState.get(DISPLAY_SD_SIZE_KEY);
        myState.put(SD_CARD_STORAGE_KEY, storage);
        if (storage != null) {
            sdCard = toIniString(storage, false);
        }
        hasSdCard = storage != null && storage.getSize() > 0;
    } else {
        sdCard = myState.get(DISPLAY_SD_LOCATION_KEY);
        myState.put(EXISTING_SD_LOCATION, sdCard);
        userEditedProperties.remove(SD_CARD_STORAGE_KEY.name);
        assert sdCard != null;
        hasSdCard = true;
        hardwareProperties.put(HardwareProperties.HW_SDCARD, toIniString(true));
    }
    hardwareProperties.put(HardwareProperties.HW_SDCARD, toIniString(hasSdCard));
    // Remove any internal keys from the map
    userEditedProperties = Maps.filterEntries(userEditedProperties, new Predicate<Map.Entry<String, Object>>() {
        @Override
        public boolean apply(Map.Entry<String, Object> input) {
            return !input.getKey().startsWith(WIZARD_ONLY) && input.getValue() != null;
        }
    });
    // Call toString() on all remaining values
    hardwareProperties.putAll(
            Maps.transformEntries(userEditedProperties, new Maps.EntryTransformer<String, Object, String>() {
                @Override
                public String transformEntry(String key, Object value) {
                    if (value instanceof Storage) {
                        if (key.equals(AvdWizardConstants.RAM_STORAGE_KEY.name)
                                || key.equals(AvdWizardConstants.VM_HEAP_STORAGE_KEY.name)) {
                            return toIniString((Storage) value, true);
                        } else {
                            return toIniString((Storage) value, false);
                        }
                    } else if (value instanceof Boolean) {
                        return toIniString((Boolean) value);
                    } else if (value instanceof AvdScaleFactor) {
                        return toIniString((AvdScaleFactor) value);
                    } else if (value instanceof File) {
                        return toIniString((File) value);
                    } else if (value instanceof Double) {
                        return toIniString((Double) value);
                    } else {
                        return value.toString();
                    }
                }
            }));

    File skinFile = myState.get(CUSTOM_SKIN_FILE_KEY);
    if (skinFile == null) {
        skinFile = resolveSkinPath(device.getDefaultHardware().getSkinFile(), systemImageDescription);
    }
    File backupSkinFile = myState.get(BACKUP_SKIN_FILE_KEY);
    if (backupSkinFile != null) {
        hardwareProperties.put(AvdManager.AVD_INI_BACKUP_SKIN_PATH, backupSkinFile.getPath());
    }

    // Add defaults if they aren't already set differently
    if (!hardwareProperties.containsKey(AvdManager.AVD_INI_SKIN_DYNAMIC)) {
        hardwareProperties.put(AvdManager.AVD_INI_SKIN_DYNAMIC, toIniString(true));
    }
    if (!hardwareProperties.containsKey(HardwareProperties.HW_KEYBOARD)) {
        hardwareProperties.put(HardwareProperties.HW_KEYBOARD, toIniString(false));
    }

    boolean isCircular = device.isScreenRound();

    String tempAvdName = myState.get(AvdWizardConstants.AVD_ID_KEY);
    if (tempAvdName == null || tempAvdName.isEmpty()) {
        tempAvdName = calculateAvdName(myAvdInfo, hardwareProperties, device, myForceCreate);
    }
    final String avdName = tempAvdName;

    // If we're editing an AVD and we downgrade a system image, wipe the user data with confirmation
    if (myAvdInfo != null && !myForceCreate) {
        IAndroidTarget target = myAvdInfo.getTarget();
        if (target != null) {

            int oldApiLevel = target.getVersion().getFeatureLevel();
            int newApiLevel = systemImageDescription.getVersion().getFeatureLevel();
            final String oldApiName = target.getVersion().getApiString();
            final String newApiName = systemImageDescription.getVersion().getApiString();
            if (oldApiLevel > newApiLevel || (oldApiLevel == newApiLevel && target.getVersion().isPreview()
                    && !systemImageDescription.getVersion().isPreview())) {
                final AtomicReference<Boolean> shouldContinue = new AtomicReference<Boolean>();
                ApplicationManager.getApplication().invokeAndWait(new Runnable() {
                    @Override
                    public void run() {
                        String message = String.format(Locale.getDefault(),
                                "You are about to downgrade %1$s from API level %2$s to API level %3$s.\n"
                                        + "This requires a wipe of the userdata partition of the AVD.\nDo you wish to "
                                        + "continue with the data wipe?",
                                avdName, oldApiName, newApiName);
                        int result = Messages.showYesNoDialog((Project) null, message, "Confirm Data Wipe",
                                AllIcons.General.QuestionDialog);
                        shouldContinue.set(result == Messages.YES);
                    }
                }, ModalityState.any());
                if (shouldContinue.get()) {
                    AvdManagerConnection.getDefaultAvdManagerConnection().wipeUserData(myAvdInfo);
                } else {
                    return;
                }
            }
        }
    }

    AvdManagerConnection connection = AvdManagerConnection.getDefaultAvdManagerConnection();
    connection.createOrUpdateAvd(myForceCreate ? null : myAvdInfo, avdName, device, systemImageDescription,
            orientation, isCircular, sdCard, skinFile, hardwareProperties, false);
}

From source file:com.google.inject.servlet.ServletScopes.java

/**
 * Scopes the given callable inside a request scope. This is not the same
 * as the HTTP request scope, but is used if no HTTP request scope is in
 * progress. In this way, keys can be scoped as @RequestScoped and exist
 * in non-HTTP requests (for example: RPC requests) as well as in HTTP
 * request threads./*from   www .  j a v  a  2s  . c o m*/
 *
 * <p>The returned callable will throw a {@link ScopingException} when called
 * if there is a request scope already active on the current thread.
 *
 * @param callable code to be executed which depends on the request scope.
 *     Typically in another thread, but not necessarily so.
 * @param seedMap the initial set of scoped instances for Guice to seed the
 *     request scope with.  To seed a key with null, use {@code null} as
 *     the value.
 * @return a callable that when called will run inside the a request scope
 *     that exposes the instances in the {@code seedMap} as scoped keys.
 * @since 3.0
 */
public static <T> Callable<T> scopeRequest(final Callable<T> callable, Map<Key<?>, Object> seedMap) {
    Preconditions.checkArgument(null != seedMap,
            "Seed map cannot be null, try passing in Collections.emptyMap() instead.");

    // Copy the seed values into our local scope map.
    final Context context = new Context();
    Map<Key<?>, Object> validatedAndCanonicalizedMap = Maps.transformEntries(seedMap,
            new EntryTransformer<Key<?>, Object, Object>() {
                @Override
                public Object transformEntry(Key<?> key, Object value) {
                    return validateAndCanonicalizeValue(key, value);
                }
            });
    context.map.putAll(validatedAndCanonicalizedMap);

    return new Callable<T>() {
        public T call() throws Exception {
            checkScopingState(null == GuiceFilter.localContext.get(),
                    "An HTTP request is already in progress, cannot scope a new request in this thread.");
            checkScopingState(null == requestScopeContext.get(),
                    "A request scope is already in progress, cannot scope a new request in this thread.");
            return context.call(callable);
        }
    };
}

From source file:org.zanata.service.impl.CopyVersionServiceImpl.java

private Map<Long, Long> copyTextFlows(final Long documentId, final Long newDocumentId, final int batchStart,
        final int batchLength) throws Exception {
    Map<Long, HTextFlow> tfMap = Maps.newHashMap();
    List<HTextFlow> textFlows = textFlowDAO.getTextFlowsByDocumentId(documentId, batchStart, batchLength);
    HDocument newDocument = documentDAO.getById(newDocumentId);
    for (HTextFlow textFlow : textFlows) {
        HTextFlow newTextFlow = copyTextFlow(newDocument, textFlow);
        newDocument.getTextFlows().add(newTextFlow);
        newDocument.getAllTextFlows().put(newTextFlow.getResId(), newTextFlow);
        tfMap.put(textFlow.getId(), newTextFlow);
    }/*from   w  w w  . j ava2  s  .  c o m*/
    documentDAO.makePersistent(newDocument);
    documentDAO.flush();
    return Maps.transformEntries(tfMap, (key, value) -> value.getId());
}

From source file:org.onosproject.store.primitives.resources.impl.AtomixLeaderElectorState.java

/**
 * Applies an {@link AtomixLeaderElectorCommands.GetAllLeaderships} commit.
 * @param commit GetAllLeaderships commit
 * @return topic to leader mapping//  w w w  .j  av  a 2 s  . c o m
 */
public Map<String, Leadership> allLeaderships(Commit<? extends GetAllLeaderships> commit) {
    Map<String, Leadership> result = new HashMap<>();
    try {
        result.putAll(Maps.transformEntries(elections, (k, v) -> leadership(k)));
        return result;
    } catch (Exception e) {
        log.error("State machine operation failed", e);
        throw Throwables.propagate(e);
    } finally {
        commit.close();
    }
}