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

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

Introduction

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

Prototype

@GwtIncompatible("NavigableMap")
public static <K, V1, V2> NavigableMap<K, V2> transformValues(NavigableMap<K, V1> fromMap,
        Function<? super V1, V2> function) 

Source Link

Document

Returns a view of a navigable map where each value is transformed by a function.

Usage

From source file:org.opendaylight.distributed.tx.impl.DtxImpl.java

private void dtxReleaseDevices() {
    Map<DTXLogicalTXProviderType, Set<InstanceIdentifier<?>>> devices = Maps.transformValues(
            perNodeTransactionsbyLogicalType,
            new Function<Map<InstanceIdentifier<?>, CachingReadWriteTx>, Set<InstanceIdentifier<?>>>() {
                @Nullable/*from  ww  w  . j  a va  2 s  .c  o m*/
                @Override
                public Set<InstanceIdentifier<?>> apply(
                        @Nullable Map<InstanceIdentifier<?>, CachingReadWriteTx> input) {
                    return input.keySet();
                }
            });
    deviceLock.releaseDevices(devices);
}

From source file:org.linagora.linshare.ldap.JScriptLdapQuery.java

/**
 * Convert database LDAP attributes map to a attribute name list.
 * //from w w w .j a  v a  2 s .  co  m
 * @param ldapDbAttributes
 *            : map of database LDAP attributes
 * @return List of attribute names.
 */
private Collection<String> getLdapAttrList(Map<String, LdapAttribute> ldapDbAttributes) {
    Collection<String> ldapAttrList = Maps
            .transformValues(ldapDbAttributes, new Function<LdapAttribute, String>() {
                public String apply(LdapAttribute input) {
                    return input.getAttribute();
                }
            }).values();
    return ldapAttrList;
}

From source file:org.easyrec.controller.dev.TenantsController.java

@RequestMapping
public ModelAndView viewpluginconfig(HttpServletRequest request, HttpServletResponse httpServletResponse) {
    String tenantId = ServletUtils.getSafeParameter(request, "tenantId", "");
    String operatorId = ServletUtils.getSafeParameter(request, "operatorId", "");

    ModelAndView mav = new ModelAndView("page");

    mav.addObject("title", "??::?");

    mav.addObject("operatorId", operatorId);
    mav.addObject("tenantId", tenantId);

    if (Security.isDeveloper(request)) {
        mav.setViewName("dev/page");
        mav.addObject("page", "viewpluginconfig");

        final RemoteTenant remoteTenant = remoteTenantDAO.get(operatorId, tenantId);

        if (remoteTenant != null) {
            Properties tenantConfig = tenantService.getTenantConfig(remoteTenant.getId());
            if (tenantConfig != null) {
                mav.addObject("schedulerEnabled", tenantConfig.getProperty(RemoteTenant.SCHEDULER_ENABLED));
                mav.addObject("schedulerExecutionTime",
                        tenantConfig.getProperty(RemoteTenant.SCHEDULER_EXECUTION_TIME));
                mav.addObject("backtrackingEnabled", tenantConfig.getProperty(RemoteTenant.BACKTRACKING));
                mav.addObject("backtrackingURL", tenantConfig.getProperty(RemoteTenant.BACKTRACKING_URL));
                mav.addObject("archivingEnabled", tenantConfig.getProperty(RemoteTenant.AUTO_ARCHIVER_ENABLED));
                mav.addObject("archivingTime", tenantConfig.getProperty(RemoteTenant.AUTO_ARCHIVER_TIME_RANGE));
                mav.addObject("sessionToUserMappingEnabled",
                        tenantConfig.getProperty(RemoteTenant.SESSION_TO_USER_MAPPING_ENABLED));
                mav.addObject("maxActions", tenantConfig.getProperty(RemoteTenant.MAXACTIONS));
                logger.info("DevController - view generators config - tenantConfig found!!!!!!!!!!!!!!!!");
                mav.addObject("selectedPlugin", tenantConfig.getProperty(PluginRegistry.GENERATOR_PROP));
            } else {
                mav.addObject("schedulerEnabled", "false");
                mav.addObject("backtrackingEnabled", "false");
                mav.addObject("pluginsActive", "false");
                logger.info("DevController - view generators config - tenantConfig NOT found!!!!!!!!!!!!!!!!");
            }/*w  w  w  .ja v a  2  s .  co m*/

            Map<String, Integer> assocTypes = assocTypeDAO.getMapping(remoteTenant.getId(), true);
            mav.addObject("assocTypes", assocTypes);

            Map<String, PluginId> activePlugins = Maps.transformValues(assocTypes,
                    new Function<Integer, PluginId>() {
                        @Override
                        public PluginId apply(Integer input) {
                            NamedConfiguration namedConfiguration = namedConfigurationDAO
                                    .readActiveConfiguration(remoteTenant.getId(), input);

                            return namedConfiguration != null ? namedConfiguration.getPluginId()
                                    : new PluginId("http://www.easyrec.org/plugins/ARM/",
                                            easyrecSettings.getVersion());
                        }
                    });
            mav.addObject("activePlugins", activePlugins);

            List<PluginVO> pluginList = pluginDAO.loadPluginInfos(LifecyclePhase.INITIALIZED.toString());
            mav.addObject("pluginList", pluginList);
        }

        mav.addObject("tenantId", tenantId);
        return mav;
    } else {
        return MessageBlock.createSingle(mav, MSG.NOT_SIGNED_IN, VIEW_PLUGIN_CONFIG, MSG.ERROR);
    }
}

From source file:org.apache.tez.runtime.task.TezChild.java

/**
 * Handles any additional resources to be localized for the new task
 * //from   www. j a va  2 s.co  m
 * @param containerTask
 * @throws IOException
 * @throws TezException
 */
private void handleNewTaskLocalResources(ContainerTask containerTask, UserGroupInformation ugi)
        throws IOException, TezException {

    final Map<String, TezLocalResource> additionalResources = containerTask.getAdditionalResources();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Additional Resources added to container: " + additionalResources);
    }

    if (additionalResources != null && !additionalResources.isEmpty()) {
        LOG.info("Localizing additional local resources for Task : " + additionalResources);

        try {
            List<URL> downloadedUrls = ugi.doAs(new PrivilegedExceptionAction<List<URL>>() {
                @Override
                public List<URL> run() throws Exception {
                    return RelocalizationUtils.processAdditionalResources(
                            Maps.transformValues(additionalResources, new Function<TezLocalResource, URI>() {
                                @Override
                                public URI apply(TezLocalResource input) {
                                    return input.getUri();
                                }
                            }), defaultConf, workingDir);
                }
            });
            RelocalizationUtils.addUrlsToClassPath(downloadedUrls);
        } catch (InterruptedException e) {
            throw new TezException(e);
        }
        LOG.info("Done localizing additional resources");
    }
}

From source file:org.janusgraph.graphdb.olap.computer.FulgoraGraphComputer.java

@Override
public Future<ComputerResult> submit() {
    if (executed)
        throw Exceptions.computerHasAlreadyBeenSubmittedAVertexProgram();
    else/*from  w  ww . j a  v a 2s  .  c  o m*/
        executed = true;

    // it is not possible execute a computer if it has no vertex program nor mapreducers
    if (null == vertexProgram && mapReduces.isEmpty())
        throw GraphComputer.Exceptions.computerHasNoVertexProgramNorMapReducers();
    // it is possible to run mapreducers without a vertex program
    if (null != vertexProgram) {
        GraphComputerHelper.validateProgramOnComputer(this, vertexProgram);
        this.mapReduces.addAll(this.vertexProgram.getMapReducers());
    }

    // if the user didn't set desired persistence/resultgraph, then get from vertex program or else, no persistence
    this.persistMode = GraphComputerHelper.getPersistState(Optional.ofNullable(this.vertexProgram),
            Optional.ofNullable(this.persistMode));
    this.resultGraphMode = GraphComputerHelper.getResultGraphState(Optional.ofNullable(this.vertexProgram),
            Optional.ofNullable(this.resultGraphMode));
    // determine the legality persistence and result graph options
    if (!this.features().supportsResultGraphPersistCombination(this.resultGraphMode, this.persistMode))
        throw GraphComputer.Exceptions.resultGraphPersistCombinationNotSupported(this.resultGraphMode,
                this.persistMode);
    // ensure requested workers are not larger than supported workers
    if (this.numThreads > this.features().getMaxWorkers())
        throw GraphComputer.Exceptions.computerRequiresMoreWorkersThanSupported(this.numThreads,
                this.features().getMaxWorkers());

    memory = new FulgoraMemory(vertexProgram, mapReduces);

    return CompletableFuture.<ComputerResult>supplyAsync(() -> {
        final long time = System.currentTimeMillis();
        if (null != vertexProgram) {
            // ##### Execute vertex program
            vertexMemory = new FulgoraVertexMemory(expectedNumVertices, graph.getIDManager(), vertexProgram);
            // execute the vertex program
            vertexProgram.setup(memory);

            try (VertexProgramScanJob.Executor job = VertexProgramScanJob.getVertexProgramScanJob(graph, memory,
                    vertexMemory, vertexProgram)) {
                for (int iteration = 1;; iteration++) {
                    memory.completeSubRound();
                    vertexMemory.nextIteration(vertexProgram.getMessageScopes(memory));

                    jobId = name + "#" + iteration;
                    StandardScanner.Builder scanBuilder = graph.getBackend().buildEdgeScanJob();
                    scanBuilder.setJobId(jobId);
                    scanBuilder.setNumProcessingThreads(numThreads);
                    scanBuilder.setWorkBlockSize(readBatchSize);
                    scanBuilder.setJob(job);
                    PartitionedVertexProgramExecutor pvpe = new PartitionedVertexProgramExecutor(graph, memory,
                            vertexMemory, vertexProgram);
                    try {
                        //Iterates over all vertices and computes the vertex program on all non-partitioned vertices. For partitioned ones, the data is aggregated
                        ScanMetrics jobResult = scanBuilder.execute().get();
                        long failures = jobResult.get(ScanMetrics.Metric.FAILURE);
                        if (failures > 0) {
                            throw new JanusGraphException("Failed to process [" + failures
                                    + "] vertices in vertex program iteration [" + iteration
                                    + "]. Computer is aborting.");
                        }
                        //Runs the vertex program on all aggregated, partitioned vertices.
                        pvpe.run(numThreads, jobResult);
                        failures = jobResult
                                .getCustom(PartitionedVertexProgramExecutor.PARTITION_VERTEX_POSTFAIL);
                        if (failures > 0) {
                            throw new JanusGraphException("Failed to process [" + failures
                                    + "] partitioned vertices in vertex program iteration [" + iteration
                                    + "]. Computer is aborting.");
                        }
                    } catch (Exception e) {
                        throw new JanusGraphException(e);
                    }

                    vertexMemory.completeIteration();
                    memory.completeSubRound();
                    try {
                        if (this.vertexProgram.terminate(this.memory)) {
                            break;
                        }
                    } finally {
                        memory.incrIteration();
                    }
                }
            }
        }

        // ##### Execute mapreduce jobs
        // Collect map jobs
        Map<MapReduce, FulgoraMapEmitter> mapJobs = new HashMap<>(mapReduces.size());
        for (MapReduce mapReduce : mapReduces) {
            if (mapReduce.doStage(MapReduce.Stage.MAP)) {
                FulgoraMapEmitter mapEmitter = new FulgoraMapEmitter<>(
                        mapReduce.doStage(MapReduce.Stage.REDUCE));
                mapJobs.put(mapReduce, mapEmitter);
            }
        }
        // Execute map jobs
        jobId = name + "#map";
        try (VertexMapJob.Executor job = VertexMapJob.getVertexMapJob(graph, vertexMemory, mapJobs)) {
            StandardScanner.Builder scanBuilder = graph.getBackend().buildEdgeScanJob();
            scanBuilder.setJobId(jobId);
            scanBuilder.setNumProcessingThreads(numThreads);
            scanBuilder.setWorkBlockSize(readBatchSize);
            scanBuilder.setJob(job);
            try {
                ScanMetrics jobResult = scanBuilder.execute().get();
                long failures = jobResult.get(ScanMetrics.Metric.FAILURE);
                if (failures > 0) {
                    throw new JanusGraphException("Failed to process [" + failures
                            + "] vertices in map phase. Computer is aborting.");
                }
                failures = jobResult.getCustom(VertexMapJob.MAP_JOB_FAILURE);
                if (failures > 0) {
                    throw new JanusGraphException(
                            "Failed to process [" + failures + "] individual map jobs. Computer is aborting.");
                }
            } catch (Exception e) {
                throw new JanusGraphException(e);
            }
            // Execute reduce phase and add to memory
            for (Map.Entry<MapReduce, FulgoraMapEmitter> mapJob : mapJobs.entrySet()) {
                FulgoraMapEmitter<?, ?> mapEmitter = mapJob.getValue();
                MapReduce mapReduce = mapJob.getKey();
                mapEmitter.complete(mapReduce); // sort results if a map output sort is defined
                if (mapReduce.doStage(MapReduce.Stage.REDUCE)) {
                    final FulgoraReduceEmitter<?, ?> reduceEmitter = new FulgoraReduceEmitter<>();
                    try (WorkerPool workers = new WorkerPool(numThreads)) {
                        workers.submit(() -> mapReduce.workerStart(MapReduce.Stage.REDUCE));
                        for (final Map.Entry queueEntry : mapEmitter.reduceMap.entrySet()) {
                            if (null == queueEntry)
                                break;
                            workers.submit(() -> mapReduce.reduce(queueEntry.getKey(),
                                    ((Iterable) queueEntry.getValue()).iterator(), reduceEmitter));
                        }
                        workers.submit(() -> mapReduce.workerEnd(MapReduce.Stage.REDUCE));
                    } catch (Exception e) {
                        throw new JanusGraphException("Exception while executing reduce phase", e);
                    }
                    //                    mapEmitter.reduceMap.entrySet().parallelStream().forEach(entry -> mapReduce.reduce(entry.getKey(), entry.getValue().iterator(), reduceEmitter));

                    reduceEmitter.complete(mapReduce); // sort results if a reduce output sort is defined
                    mapReduce.addResultToMemory(this.memory, reduceEmitter.reduceQueue.iterator());
                } else {
                    mapReduce.addResultToMemory(this.memory, mapEmitter.mapQueue.iterator());
                }
            }
        }
        memory.attachReferenceElements(graph);

        // #### Write mutated properties back into graph
        Graph resultgraph = graph;
        if (persistMode == Persist.NOTHING && resultGraphMode == ResultGraph.NEW) {
            resultgraph = EmptyGraph.instance();
        } else if (persistMode != Persist.NOTHING && vertexProgram != null
                && !vertexProgram.getVertexComputeKeys().isEmpty()) {
            //First, create property keys in graph if they don't already exist
            JanusGraphManagement mgmt = graph.openManagement();
            try {
                for (VertexComputeKey key : vertexProgram.getVertexComputeKeys()) {
                    if (!mgmt.containsPropertyKey(key.getKey()))
                        log.warn(
                                "Property key [{}] is not part of the schema and will be created. It is advised to initialize all keys.",
                                key.getKey());
                    mgmt.getOrCreatePropertyKey(key.getKey());
                }
                mgmt.commit();
            } finally {
                if (mgmt != null && mgmt.isOpen())
                    mgmt.rollback();
            }

            //TODO: Filter based on VertexProgram
            Map<Long, Map<String, Object>> mutatedProperties = Maps.transformValues(
                    vertexMemory.getMutableVertexProperties(),
                    new Function<Map<String, Object>, Map<String, Object>>() {
                        @Nullable
                        @Override
                        public Map<String, Object> apply(@Nullable Map<String, Object> o) {
                            return Maps.filterKeys(o, s -> !VertexProgramHelper.isTransientVertexComputeKey(s,
                                    vertexProgram.getVertexComputeKeys()));
                        }
                    });

            if (resultGraphMode == ResultGraph.ORIGINAL) {
                AtomicInteger failures = new AtomicInteger(0);
                try (WorkerPool workers = new WorkerPool(numThreads)) {
                    List<Map.Entry<Long, Map<String, Object>>> subset = new ArrayList<>(
                            writeBatchSize / vertexProgram.getVertexComputeKeys().size());
                    int currentSize = 0;
                    for (Map.Entry<Long, Map<String, Object>> entry : mutatedProperties.entrySet()) {
                        subset.add(entry);
                        currentSize += entry.getValue().size();
                        if (currentSize >= writeBatchSize) {
                            workers.submit(new VertexPropertyWriter(subset, failures));
                            subset = new ArrayList<>(subset.size());
                            currentSize = 0;
                        }
                    }
                    if (!subset.isEmpty())
                        workers.submit(new VertexPropertyWriter(subset, failures));
                } catch (Exception e) {
                    throw new JanusGraphException("Exception while attempting to persist result into graph", e);
                }
                if (failures.get() > 0)
                    throw new JanusGraphException(
                            "Could not persist program results to graph. Check log for details.");
            } else if (resultGraphMode == ResultGraph.NEW) {
                resultgraph = graph.newTransaction();
                for (Map.Entry<Long, Map<String, Object>> vprop : mutatedProperties.entrySet()) {
                    Vertex v = resultgraph.vertices(vprop.getKey()).next();
                    for (Map.Entry<String, Object> prop : vprop.getValue().entrySet()) {
                        v.property(VertexProperty.Cardinality.single, prop.getKey(), prop.getValue());
                    }
                }
            }
        }
        // update runtime and return the newly computed graph
        this.memory.setRuntime(System.currentTimeMillis() - time);
        this.memory.complete();
        return new DefaultComputerResult(resultgraph, this.memory);
    });
}

From source file:ninja.leaping.permissionsex.backend.memory.MemoryOptionSubjectData.java

@Override
public Map<Set<Entry<String, String>>, Integer> getAllDefaultValues() {
    return Maps.filterValues(Maps.transformValues(contexts, new Function<DataEntry, Integer>() {
        @Nullable//  www.j av  a 2 s.  c  o  m
        @Override
        public Integer apply(@Nullable DataEntry dataEntry) {
            return dataEntry == null ? null : dataEntry.defaultValue;
        }
    }), Predicates.notNull());
}

From source file:co.cask.cdap.metrics.query.MetricsHandler.java

private Map<String, String> transformTagMap(Map<String, String> tags) {
    return Maps.transformValues(tags, new Function<String, String>() {
        @Override/* w w w .j  a v a 2s .  c om*/
        public String apply(String value) {
            if (ANY_TAG_VALUE.equals(value)) {
                return null;
            } else {
                return value;
            }
        }
    });
}

From source file:com.facebook.buck.features.python.PythonTestDescription.java

@Override
public PythonTest createBuildRule(BuildRuleCreationContextWithTargetGraph context, BuildTarget buildTarget,
        BuildRuleParams params, PythonTestDescriptionArg args) {

    FlavorDomain<PythonPlatform> pythonPlatforms = toolchainProvider
            .getByName(PythonPlatformsProvider.DEFAULT_NAME, PythonPlatformsProvider.class)
            .getPythonPlatforms();//from www.  j  a v  a2  s.  c o m

    ActionGraphBuilder graphBuilder = context.getActionGraphBuilder();
    PythonPlatform pythonPlatform = pythonPlatforms.getValue(buildTarget)
            .orElse(pythonPlatforms.getValue(args.getPlatform().<Flavor>map(InternalFlavor::of)
                    .orElse(pythonPlatforms.getFlavors().iterator().next())));
    CxxPlatform cxxPlatform = getCxxPlatform(buildTarget, args).resolve(graphBuilder);
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(graphBuilder);
    SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);
    Path baseModule = PythonUtil.getBasePath(buildTarget, args.getBaseModule());
    Optional<ImmutableMap<BuildTarget, Version>> selectedVersions = context.getTargetGraph().get(buildTarget)
            .getSelectedVersions();

    ImmutableMap<Path, SourcePath> srcs = PythonUtil.getModules(buildTarget, graphBuilder, ruleFinder,
            pathResolver, pythonPlatform, cxxPlatform, "srcs", baseModule, args.getSrcs(),
            args.getPlatformSrcs(), args.getVersionedSrcs(), selectedVersions);

    ImmutableMap<Path, SourcePath> resources = PythonUtil.getModules(buildTarget, graphBuilder, ruleFinder,
            pathResolver, pythonPlatform, cxxPlatform, "resources", baseModule, args.getResources(),
            args.getPlatformResources(), args.getVersionedResources(), selectedVersions);

    // Convert the passed in module paths into test module names.
    ImmutableSet.Builder<String> testModulesBuilder = ImmutableSet.builder();
    for (Path name : srcs.keySet()) {
        testModulesBuilder.add(PythonUtil.toModuleName(buildTarget, name.toString()));
    }
    ImmutableSet<String> testModules = testModulesBuilder.build();

    ProjectFilesystem projectFilesystem = context.getProjectFilesystem();

    // Construct a build rule to generate the test modules list source file and
    // add it to the build.
    BuildRule testModulesBuildRule = createTestModulesSourceBuildRule(buildTarget, projectFilesystem,
            getTestModulesListPath(buildTarget, projectFilesystem), testModules);
    graphBuilder.addToIndex(testModulesBuildRule);

    String mainModule;
    if (args.getMainModule().isPresent()) {
        mainModule = args.getMainModule().get();
    } else {
        mainModule = PythonUtil.toModuleName(buildTarget, getTestMainName().toString());
    }

    // Build up the list of everything going into the python test.
    PythonPackageComponents testComponents = PythonPackageComponents.of(
            ImmutableMap.<Path, SourcePath>builder()
                    .put(getTestModulesListName(), testModulesBuildRule.getSourcePathToOutput())
                    .put(getTestMainName(), requireTestMain(buildTarget, projectFilesystem, graphBuilder))
                    .putAll(srcs).build(),
            resources, ImmutableMap.of(), ImmutableMultimap.of(), args.getZipSafe());
    ImmutableList<BuildRule> deps = RichStream
            .from(PythonUtil.getDeps(pythonPlatform, cxxPlatform, args.getDeps(), args.getPlatformDeps()))
            .concat(args.getNeededCoverage().stream().map(NeededCoverageSpec::getBuildTarget))
            .map(graphBuilder::getRule).collect(ImmutableList.toImmutableList());

    CellPathResolver cellRoots = context.getCellPathResolver();
    StringWithMacrosConverter macrosConverter = StringWithMacrosConverter.builder().setBuildTarget(buildTarget)
            .setCellPathResolver(cellRoots).setExpanders(PythonUtil.MACRO_EXPANDERS).build();
    PythonPackageComponents allComponents = PythonUtil.getAllComponents(cellRoots, buildTarget,
            projectFilesystem, params, graphBuilder, ruleFinder, deps, testComponents, pythonPlatform,
            cxxBuckConfig, cxxPlatform,
            args.getLinkerFlags().stream().map(x -> macrosConverter.convert(x, graphBuilder))
                    .collect(ImmutableList.toImmutableList()),
            pythonBuckConfig.getNativeLinkStrategy(), args.getPreloadDeps());

    // Build the PEX using a python binary rule with the minimum dependencies.
    buildTarget.assertUnflavored();
    PythonBinary binary = binaryDescription.createPackageRule(buildTarget.withAppendedFlavors(BINARY_FLAVOR),
            projectFilesystem, params, graphBuilder, ruleFinder, pythonPlatform, cxxPlatform, mainModule,
            args.getExtension(), allComponents, args.getBuildArgs(),
            args.getPackageStyle().orElse(pythonBuckConfig.getPackageStyle()),
            PythonUtil.getPreloadNames(graphBuilder, cxxPlatform, args.getPreloadDeps()));
    graphBuilder.addToIndex(binary);

    ImmutableList.Builder<Pair<Float, ImmutableSet<Path>>> neededCoverageBuilder = ImmutableList.builder();
    for (NeededCoverageSpec coverageSpec : args.getNeededCoverage()) {
        BuildRule buildRule = graphBuilder.getRule(coverageSpec.getBuildTarget());
        if (deps.contains(buildRule) && buildRule instanceof PythonLibrary) {
            PythonLibrary pythonLibrary = (PythonLibrary) buildRule;
            ImmutableSortedSet<Path> paths;
            if (coverageSpec.getPathName().isPresent()) {
                Path path = coverageSpec.getBuildTarget().getBasePath()
                        .resolve(coverageSpec.getPathName().get());
                if (!pythonLibrary.getPythonPackageComponents(pythonPlatform, cxxPlatform, graphBuilder)
                        .getModules().keySet().contains(path)) {
                    throw new HumanReadableException(
                            "%s: path %s specified in needed_coverage not found in target %s", buildTarget,
                            path, buildRule.getBuildTarget());
                }
                paths = ImmutableSortedSet.of(path);
            } else {
                paths = ImmutableSortedSet.copyOf(
                        pythonLibrary.getPythonPackageComponents(pythonPlatform, cxxPlatform, graphBuilder)
                                .getModules().keySet());
            }
            neededCoverageBuilder
                    .add(new Pair<>(coverageSpec.getNeededCoverageRatioPercentage() / 100.f, paths));
        } else {
            throw new HumanReadableException(
                    "%s: needed_coverage requires a python library dependency. Found %s instead", buildTarget,
                    buildRule);
        }
    }

    Function<BuildRuleResolver, ImmutableMap<String, Arg>> testEnv = (ruleResolverInner) -> ImmutableMap
            .copyOf(Maps.transformValues(args.getEnv(), x -> macrosConverter.convert(x, graphBuilder)));

    // Additional CXX Targets used to generate CXX coverage.
    ImmutableSet<UnflavoredBuildTarget> additionalCoverageTargets = RichStream
            .from(args.getAdditionalCoverageTargets()).map(target -> target.getUnflavoredBuildTarget())
            .collect(ImmutableSet.toImmutableSet());
    ImmutableSortedSet<SourcePath> additionalCoverageSourcePaths = additionalCoverageTargets.isEmpty()
            ? ImmutableSortedSet.of()
            : binary.getRuntimeDeps(ruleFinder)
                    .filter(target -> additionalCoverageTargets.contains(target.getUnflavoredBuildTarget()))
                    .map(target -> DefaultBuildTargetSourcePath.of(target))
                    .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural()));

    // Generate and return the python test rule, which depends on the python binary rule above.
    return PythonTest.from(buildTarget, projectFilesystem, params, graphBuilder, testEnv, binary,
            args.getLabels(), neededCoverageBuilder.build(), additionalCoverageSourcePaths,
            args.getTestRuleTimeoutMs().map(Optional::of).orElse(
                    cxxBuckConfig.getDelegate().getView(TestBuckConfig.class).getDefaultTestRuleTimeoutMs()),
            args.getContacts());
}

From source file:net.sourceforge.fenixedu.presentationTier.util.ExceptionInformation.java

@SuppressWarnings("unchecked")
private Map<String, String> getRequestParameters(HttpServletRequest request) {
    Map<String, String[]> parametersMap = request.getParameterMap();
    final Function<String[], String> valuesJoiner = new Function<String[], String>() {
        @Override/* w  ww  . j a va2 s .  c  om*/
        public String apply(String[] parameters) {
            return Joiner.on(", ").join(parameters);
        }
    };
    return Maps.newHashMap(Maps.transformValues(parametersMap, valuesJoiner));
}

From source file:com.google.devtools.build.skyframe.SkyFunctionEnvironment.java

@Override
protected Map<SkyKey, ValueOrUntypedException> getValueOrUntypedExceptions(Iterable<SkyKey> depKeys)
        throws InterruptedException {
    checkActive();/*from   w  ww .j av a  2  s  .co  m*/
    Map<SkyKey, SkyValue> values = getValuesMaybeFromError(depKeys);
    for (Map.Entry<SkyKey, SkyValue> depEntry : values.entrySet()) {
        SkyKey depKey = depEntry.getKey();
        SkyValue depValue = depEntry.getValue();
        if (depValue == NULL_MARKER) {
            if (directDeps.containsKey(depKey)) {
                throw new IllegalStateException("Undone key " + depKey + " was already in deps of " + skyKey
                        + "( dep: " + evaluatorContext.getGraph().get(skyKey, Reason.OTHER, depKey)
                        + ", parent: " + evaluatorContext.getGraph().get(null, Reason.OTHER, skyKey));
            }
            valuesMissing = true;
            addDep(depKey);
            continue;
        }
        ErrorInfo errorInfo = ValueWithMetadata.getMaybeErrorInfo(depEntry.getValue());
        if (errorInfo != null) {
            childErrorInfos.add(errorInfo);
            if (bubbleErrorInfo != null) {
                // Set interrupted status, to try to prevent the calling SkyFunction from doing anything
                // fancy after this. SkyFunctions executed during error bubbling are supposed to
                // (quickly) rethrow errors or return a value/null (but there's currently no way to
                // enforce this).
                Thread.currentThread().interrupt();
            }
            if ((!evaluatorContext.keepGoing() && bubbleErrorInfo == null)
                    || errorInfo.getException() == null) {
                valuesMissing = true;
                // We arbitrarily record the first child error if we are about to abort.
                if (!evaluatorContext.keepGoing() && depErrorKey == null) {
                    depErrorKey = depKey;
                }
            }
        }

        if (!directDeps.containsKey(depKey)) {
            if (bubbleErrorInfo == null) {
                addDep(depKey);
            }
            evaluatorContext.getReplayingNestedSetEventVisitor().visit(ValueWithMetadata.getEvents(depValue));
        }
    }

    return Maps.transformValues(values, new Function<SkyValue, ValueOrUntypedException>() {
        @Override
        public ValueOrUntypedException apply(SkyValue maybeWrappedValue) {
            if (maybeWrappedValue == NULL_MARKER) {
                return ValueOrExceptionUtils.ofNull();
            }
            SkyValue justValue = ValueWithMetadata.justValue(maybeWrappedValue);
            ErrorInfo errorInfo = ValueWithMetadata.getMaybeErrorInfo(maybeWrappedValue);

            if (justValue != null && (evaluatorContext.keepGoing() || errorInfo == null)) {
                // If the dep did compute a value, it is given to the caller if we are in
                // keepGoing mode or if we are in noKeepGoingMode and there were no errors computing
                // it.
                return ValueOrExceptionUtils.ofValueUntyped(justValue);
            }

            // There was an error building the value, which we will either report by throwing an
            // exception or insulate the caller from by returning null.
            Preconditions.checkNotNull(errorInfo, "%s %s", skyKey, maybeWrappedValue);
            Exception exception = errorInfo.getException();

            if (!evaluatorContext.keepGoing() && exception != null && bubbleErrorInfo == null) {
                // Child errors should not be propagated in noKeepGoing mode (except during error
                // bubbling). Instead we should fail fast.
                return ValueOrExceptionUtils.ofNull();
            }

            if (exception != null) {
                // Give builder a chance to handle this exception.
                return ValueOrExceptionUtils.ofExn(exception);
            }
            // In a cycle.
            Preconditions.checkState(!Iterables.isEmpty(errorInfo.getCycleInfo()), "%s %s %s", skyKey,
                    errorInfo, maybeWrappedValue);
            return ValueOrExceptionUtils.ofNull();
        }
    });
}