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

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

Introduction

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

Prototype

public static <K, V> ConcurrentMap<K, V> newConcurrentMap() 

Source Link

Document

Returns a general-purpose instance of ConcurrentMap , which supports all optional operations of the ConcurrentMap interface.

Usage

From source file:com.google.idea.blaze.cpp.BlazeConfigurationResolver.java

private static ImmutableMap<File, VirtualFile> doCollectHeaderRoots(BlazeContext context,
        BlazeProjectData projectData, Set<ExecutionRootPath> rootPaths) {
    ConcurrentMap<File, VirtualFile> rootsMap = Maps.newConcurrentMap();
    List<ListenableFuture<Void>> futures = Lists.newArrayListWithCapacity(rootPaths.size());
    for (ExecutionRootPath path : rootPaths) {
        futures.add(submit(() -> {//from  w  w w . j a v  a  2 s  .  c  o  m
            ImmutableList<File> possibleDirectories = projectData.workspacePathResolver
                    .resolveToIncludeDirectories(path);
            for (File file : possibleDirectories) {
                VirtualFile vf = getVirtualFile(file);
                if (vf != null) {
                    rootsMap.put(file, vf);
                } else if (!projectData.blazeRoots.isOutputArtifact(path)
                        && FileAttributeProvider.getInstance().exists(file)) {
                    // If it's not a blaze output file, we expect it to always resolve.
                    LOG.info(String.format("Unresolved header root %s", file.getAbsolutePath()));
                }
            }
            return null;
        }));
    }
    try {
        Futures.allAsList(futures).get();
        return ImmutableMap.copyOf(rootsMap);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        context.setCancelled();
    } catch (ExecutionException e) {
        IssueOutput.error("Error resolving header include roots: " + e).submit(context);
        LOG.error("Error resolving header include roots", e);
    }
    return ImmutableMap.of();
}

From source file:com.sk89q.worldguard.protection.flags.registry.SimpleFlagRegistry.java

@Override
public Map<Flag<?>, Object> unmarshal(Map<String, Object> rawValues, boolean createUnknown) {
    checkNotNull(rawValues, "rawValues");

    // Ensure that flags are registered.
    Flags.registerAll();//from   w  w w .  j a  v a 2s . c  o m

    ConcurrentMap<Flag<?>, Object> values = Maps.newConcurrentMap();
    ConcurrentMap<String, Object> regionFlags = Maps.newConcurrentMap();

    for (Entry<String, Object> entry : rawValues.entrySet()) {
        if (entry.getKey().endsWith("-group")) {
            regionFlags.put(entry.getKey(), entry.getValue());
            continue;
        }
        Flag<?> flag = createUnknown ? getOrCreate(entry.getKey()) : get(entry.getKey());

        if (flag != null) {
            try {
                Object unmarshalled = flag.unmarshal(entry.getValue());

                if (unmarshalled != null) {
                    values.put(flag, unmarshalled);
                } else {
                    log.warning("Failed to parse flag '" + flag.getName() + "' with value '" + entry.getValue()
                            + "'");
                }
            } catch (Exception e) {
                log.log(Level.WARNING, "Failed to unmarshal flag value for " + flag, e);
            }
        }
    }
    for (Entry<String, Object> entry : regionFlags.entrySet()) {
        String parentName = entry.getKey().replaceAll("-group", "");
        Flag<?> parent = get(parentName);
        if (parent == null || parent instanceof UnknownFlag) {
            if (createUnknown)
                forceRegister(new UnknownFlag(entry.getKey()));
        } else {
            values.put(parent.getRegionGroupFlag(), parent.getRegionGroupFlag().unmarshal(entry.getValue()));
        }
    }

    return values;
}

From source file:co.cask.common.security.zookeeper.SharedResourceCache.java

private Map<String, T> reloadAll() {
    final Map<String, T> loaded = Maps.newConcurrentMap();
    ZKOperations.watchChildren(zookeeper, parentZnode, new ZKOperations.ChildrenCallback() {
        @Override//from  www .ja  v a2 s.  c o m
        public void updated(NodeChildren nodeChildren) {
            LOG.info("Listing existing children for node {}", parentZnode);
            List<String> children = nodeChildren.getChildren();
            for (String child : children) {
                OperationFuture<NodeData> dataFuture = zookeeper.getData(joinZNode(parentZnode, child),
                        watcher);
                final String nodeName = getZNode(dataFuture.getRequestPath());
                Futures.addCallback(dataFuture, new FutureCallback<NodeData>() {
                    @Override
                    public void onSuccess(NodeData result) {
                        LOG.debug("Got data for child {}", nodeName);
                        try {
                            final T resource = codec.decode(result.getData());
                            loaded.put(nodeName, resource);
                            listeners.notifyResourceUpdate(nodeName, resource);
                        } catch (IOException ioe) {
                            throw Throwables.propagate(ioe);
                        }
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        LOG.error("Failed to get data for child node {}", nodeName, t);
                        listeners.notifyError(nodeName, t);
                    }
                });
                LOG.debug("Added future for {}", child);
            }
        }
    });

    return loaded;
}

From source file:com.mpush.common.net.HttpProxyDnsMappingManager.java

@Override
public void run() {
    logger.debug("do dns mapping checkHealth ...");
    Map<String, List<DnsMapping>> all = this.getAll();
    Map<String, List<DnsMapping>> available = Maps.newConcurrentMap();
    all.forEach((key, dnsMappings) -> {
        List<DnsMapping> okList = Lists.newArrayList();
        dnsMappings.forEach(dnsMapping -> {
            if (checkHealth(dnsMapping.getIp(), dnsMapping.getPort())) {
                okList.add(dnsMapping);//  w  w  w .  j  a v a  2s  . c o m
            } else {
                logger.warn("dns can not reachable:" + Jsons.toJson(dnsMapping));
            }
        });
        available.put(key, okList);
    });
    this.update(available);
}

From source file:com.pinterest.terrapin.client.FileSetViewManager.java

public FileSetViewManager(ZooKeeperClient zkClient, String clusterName) throws Exception {
    this.clusterName = clusterName;
    this.fileSetInfoBackupMap = Maps.newConcurrentMap();
    this.zkBackedFileSetInfoMap = ZooKeeperMap.create(zkClient, "/" + this.clusterName + "/filesets",
            fileSetInfoFunction);/*from ww  w  . j  a  va  2s. co m*/
    this.zkBackedViewInfoMap = ZooKeeperMap.create(zkClient, "/" + this.clusterName + "/views",
            viewInfoFunction);
}

From source file:io.atomix.core.map.impl.AbstractAtomicMapService.java

protected Map<K, MapEntryValue> createMap() {
    return Maps.newConcurrentMap();
}

From source file:org.eclipse.milo.opcua.stack.core.security.DefaultTrustListManager.java

public DefaultTrustListManager(File baseDir) throws IOException {
    this.baseDir = baseDir;
    ensureDirectoryExists(baseDir);/*from  ww w  . j  ava2 s . co  m*/

    issuerDir = baseDir.toPath().resolve("issuers").toFile();
    ensureDirectoryExists(issuerDir);

    issuerCertsDir = issuerDir.toPath().resolve("certs").toFile();
    ensureDirectoryExists(issuerCertsDir);

    issuerCrlsDir = issuerDir.toPath().resolve("crls").toFile();
    ensureDirectoryExists(issuerCrlsDir);

    trustedDir = baseDir.toPath().resolve("trusted").toFile();
    ensureDirectoryExists(trustedDir);

    trustedCertsDir = trustedDir.toPath().resolve("certs").toFile();
    ensureDirectoryExists(trustedCertsDir);

    trustedCrlsDir = trustedDir.toPath().resolve("crls").toFile();
    ensureDirectoryExists(trustedCrlsDir);

    rejectedDir = baseDir.toPath().resolve("rejected").toFile();
    ensureDirectoryExists(rejectedDir);

    watchService = FileSystems.getDefault().newWatchService();

    Map<WatchKey, Runnable> watchKeys = Maps.newConcurrentMap();

    watchKeys.put(
            issuerCertsDir.toPath().register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
                    StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY),
            this::synchronizeIssuerCerts);
    watchKeys.put(
            issuerCrlsDir.toPath().register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
                    StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY),
            this::synchronizeIssuerCrls);
    watchKeys.put(
            trustedCertsDir.toPath().register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
                    StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY),
            this::synchronizeTrustedCerts);
    watchKeys.put(
            trustedCrlsDir.toPath().register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
                    StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY),
            this::synchronizeTrustedCrls);

    watchThread = new Thread(new Watcher(watchService, watchKeys));
    watchThread.setName("certificate-store-watcher");
    watchThread.setDaemon(true);
    watchThread.start();

    synchronizeIssuerCerts();
    synchronizeIssuerCrls();
    synchronizeTrustedCerts();
}

From source file:org.geogit.repository.WorkingTreeInsertHelper.java

public Map<NodeRef, RevTree> buildTrees() {

    final Map<NodeRef, RevTree> result = Maps.newConcurrentMap();

    List<AsyncBuildTree> tasks = Lists.newArrayList();

    for (Entry<String, RevTreeBuilder2> builderEntry : treeBuilders.entrySet()) {
        final String treePath = builderEntry.getKey();
        final RevTreeBuilder2 builder = builderEntry.getValue();
        tasks.add(new AsyncBuildTree(treePath, builder, result));
    }//w w w . j av a 2 s  .  c o  m
    try {
        executorService.invokeAll(tasks);
    } catch (InterruptedException e) {
        throw Throwables.propagate(e);
    }
    return result;
}

From source file:org.dllearner.algorithms.properties.MultiPropertyAxiomLearner.java

public void start() {
    startTime = System.currentTimeMillis();

    checkConfigOptions();/* ww  w. j av  a 2 s .c  o  m*/

    // check if entity is empty
    int popularity = reasoner.getPopularity(entity);
    if (popularity == 0) {
        logger.warn("Cannot make axiom suggestions for empty " + entity.getEntityType().getName() + " "
                + entity.toStringID());
        return;
    }

    results = Maps.newConcurrentMap();

    EntityType<?> entityType = entity.getEntityType();

    // check for axiom types that are not appropriate for the given entity
    Set<AxiomType<? extends OWLAxiom>> possibleAxiomTypes = AxiomAlgorithms.getAxiomTypes(entityType);
    SetView<AxiomType<? extends OWLAxiom>> notAllowed = Sets.difference(axiomTypes, possibleAxiomTypes);
    if (!notAllowed.isEmpty()) {
        logger.warn("Not supported axiom types for entity " + entity + " :" + notAllowed);
    }

    Set<AxiomType<? extends OWLAxiom>> todo = Sets.intersection(axiomTypes, possibleAxiomTypes);

    // compute samples for axiom types
    Set<AxiomTypeCluster> sampleClusters = AxiomAlgorithms.getSameSampleClusters(entityType);

    ExecutorService tp = Executors.newFixedThreadPool(maxNrOfThreads);

    for (final AxiomTypeCluster cluster : sampleClusters) {
        final SetView<AxiomType<? extends OWLAxiom>> sampleAxiomTypes = Sets
                .intersection(cluster.getAxiomTypes(), todo);

        if (!sampleAxiomTypes.isEmpty()) {
            tp.submit(() -> {
                try {
                    SparqlEndpointKS ks1 = MultiPropertyAxiomLearner.this.ks;

                    // get sample if enabled
                    if (useSampling) {
                        Model sample = generateSample(entity, cluster);

                        // if sampling failed, we skip
                        if (sample == null) {
                            return;
                        }

                        // if the sample is empty, we skip and show warning
                        if (sample.isEmpty()) {
                            logger.warn("Empty sample. Skipped learning.");
                            return;
                        }

                        ks1 = new LocalModelBasedSparqlEndpointKS(sample);
                    }

                    // process each axiom type
                    for (AxiomType<? extends OWLAxiom> axiomType : sampleAxiomTypes) {
                        try {
                            List<EvaluatedAxiom<OWLAxiom>> result = applyAlgorithm(axiomType, ks1);
                            results.put(axiomType, result);
                        } catch (Exception e) {
                            logger.error("An error occurred while generating " + axiomType.getName()
                                    + " axioms for " + OWLAPIUtils.getPrintName(entity.getEntityType()) + " "
                                    + entity.toStringID(), e);
                        }
                    }
                } catch (Exception e) {
                    logger.error("Failed to process " + cluster, e);
                }
            });

        }
    }

    try {
        tp.shutdown();
        tp.awaitTermination(1, TimeUnit.HOURS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    //      
    //      for (AxiomType<? extends OWLAxiom> axiomType : todo) {
    //         try {
    //            applyAlgorithm(entity, axiomType, useSampling ? axiomType2Ks.get(axiomType) : ks);
    //         } catch (Exception e) {
    //            logger.error("Error occurred while generating " + axiomType.getName() + " for entity " + entity, e);
    //         }
    //      }
}

From source file:hudson.util.DescribableListUtil.java

/**
 * Converts describableList data to project properties map. {@link hudson.model.Descriptor#getJsonSafeClassName()}
 * is used as key, value - {@link BaseProjectProperty}.
 *
 * @param describableList source./*ww w . j a  v  a2 s. c om*/
 * @param owner new owner for properties.
 * @param <T> T describable
 * @param <D> Descriptor
 * @return map of converted properties.
 */
public static <T extends Describable<T>, D extends Descriptor<T>> Map<String, ExternalProjectProperty<T>> convertToProjectProperties(
        DescribableList<T, D> describableList, Job owner) {
    Map<String, ExternalProjectProperty<T>> result = Maps.newConcurrentMap();
    if (null != describableList) {
        for (Map.Entry<D, T> entry : describableList.toMap().entrySet()) {
            ExternalProjectProperty<T> property = new ExternalProjectProperty<T>(owner);
            String key = entry.getKey().getJsonSafeClassName();
            property.setKey(key);
            property.setValue(entry.getValue());
            result.put(key, property);
        }
    }
    return result;
}