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

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

Introduction

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

Prototype

public static Function<Object, String> toStringFunction() 

Source Link

Document

Returns a function that calls toString() on its argument.

Usage

From source file:org.killbill.billing.plugin.adyen.dao.AdyenDao.java

private String getString(@Nullable final Iterable iterable) {
    if (iterable == null || !iterable.iterator().hasNext()) {
        return null;
    } else {//  w w  w.j  av a  2  s.  c  om
        return JOINER.join(Iterables.transform(iterable, Functions.toStringFunction()));
    }
}

From source file:com.blackducksoftware.bdio.io.Specification.java

/**
 * Returns a JSON-LD frame for reconstructing the data as if it had been generated by serializing a list model
 * objects.// w w w .j  av  a  2 s  . c  o  m
 */
public final Map<String, Object> importFrame() {
    final Map<String, Object> frame = new LinkedHashMap<>();

    // Start by keeping only the top-level types
    frame.put("@type", Lists.transform(importFrame.topLevelTypes(), Functions.toStringFunction()));

    // Frame definition to turn of embedding
    final Map<String, Object> embedOff = ImmutableMap.of("@embed", (Object) Boolean.FALSE, "@omitDefault",
            (Object) Boolean.TRUE);

    // Add the term filters to disable embedding
    for (TermDefinition termDefinition : Iterables.filter(definitions.values(), importFrame.referenceTerms())) {
        frame.put(termDefinition.getTerm().toString(), embedOff);
    }

    return frame;
}

From source file:com.facebook.buck.apple.NewNativeTargetProjectMutator.java

private ImmutableList<PBXShellScriptBuildPhase> createScriptsForTargetNodes(Iterable<TargetNode<?>> nodes)
        throws IllegalStateException {
    ImmutableList.Builder<PBXShellScriptBuildPhase> builder = ImmutableList.builder();
    for (TargetNode<?> node : nodes) {
        PBXShellScriptBuildPhase shellScriptBuildPhase = new PBXShellScriptBuildPhase();
        if (XcodePrebuildScriptDescription.TYPE.equals(node.getType())
                || XcodePostbuildScriptDescription.TYPE.equals(node.getType())) {
            XcodeScriptDescriptionArg arg = (XcodeScriptDescriptionArg) node.getConstructorArg();
            shellScriptBuildPhase.getInputPaths()
                    .addAll(FluentIterable.from(arg.srcs.get()).transform(sourcePathResolver)
                            .transform(pathRelativizer.outputDirToRootRelative())
                            .transform(Functions.toStringFunction()).toSet());
            shellScriptBuildPhase.getOutputPaths().addAll(arg.outputs.get());
            shellScriptBuildPhase.setShellScript(arg.cmd);
        } else if (IosReactNativeLibraryDescription.TYPE.equals(node.getType())) {
            shellScriptBuildPhase.setShellScript(generateXcodeShellScript(node));
        } else {//from w w w. j ava  2 s  . c om
            // unreachable
            throw new IllegalStateException("Invalid rule type for shell script build phase");
        }
        builder.add(shellScriptBuildPhase);
    }
    return builder.build();
}

From source file:clocker.mesos.entity.task.marathon.MarathonTaskImpl.java

private Map<String, Object> getMarathonFlags(Entity entity) {
    MutableMap.Builder<String, Object> builder = MutableMap.builder();
    ConfigBag provisioningProperties = ConfigBag
            .newInstance(entity.config().get(SoftwareProcess.PROVISIONING_PROPERTIES));

    // CPU/*from   w  w w .j a  v a  2  s.c o m*/
    Double cpus = entity.config().get(MarathonTask.CPU_RESOURCES);
    if (cpus == null)
        cpus = config().get(MarathonTask.CPU_RESOURCES);
    if (cpus == null) {
        Integer minCores = entity.config().get(JcloudsLocationConfig.MIN_CORES);
        if (minCores == null) {
            minCores = provisioningProperties.get(JcloudsLocationConfig.MIN_CORES);
        }
        if (minCores == null) {
            TemplateBuilder template = provisioningProperties.get(JcloudsLocationConfig.TEMPLATE_BUILDER);
            if (template != null) {
                minCores = 0;
                for (Processor cpu : template.build().getHardware().getProcessors()) {
                    minCores = minCores + (int) cpu.getCores();
                }
            }
        }
        if (minCores != null) {
            cpus = 1.0d * minCores;
        }
    }
    if (cpus == null)
        cpus = 0.25d;
    builder.put("cpus", cpus);

    // Memory
    Integer memory = entity.config().get(MarathonTask.MEMORY_RESOURCES);
    if (memory == null)
        memory = config().get(MarathonTask.MEMORY_RESOURCES);
    if (memory == null) {
        Integer minRam = parseMbSizeString(entity.config().get(JcloudsLocationConfig.MIN_RAM));
        if (minRam == null) {
            minRam = parseMbSizeString(provisioningProperties.get(JcloudsLocationConfig.MIN_RAM));
        }
        if (minRam == null) {
            TemplateBuilder template = provisioningProperties.get(JcloudsLocationConfig.TEMPLATE_BUILDER);
            if (template != null) {
                minRam = template.build().getHardware().getRam();
            }
        }
        if (minRam != null) {
            memory = minRam;
        }
    }
    if (memory == null)
        memory = 256;
    builder.put("memory", memory);

    // Inbound ports
    Set<Integer> entityOpenPorts = MutableSet.copyOf(DockerUtils.getContainerPorts(entity));
    entityOpenPorts.addAll(DockerUtils.getOpenPorts(entity));
    if (!config().get(DockerContainer.DOCKER_USE_SSH)) {
        entityOpenPorts.remove(22);
    }
    builder.put("openPorts", Ints.toArray(entityOpenPorts));
    sensors().set(DockerAttributes.DOCKER_CONTAINER_OPEN_PORTS, ImmutableList.copyOf(entityOpenPorts));
    entity.sensors().set(DockerAttributes.DOCKER_CONTAINER_OPEN_PORTS, ImmutableList.copyOf(entityOpenPorts));

    // Direct port mappings
    // Note that the Marathon map is reversed, from container to host, with 0 indicating any host port
    Map<Integer, Integer> bindings = MutableMap.of();
    Map<Integer, Integer> marathonBindings = MutableMap.of();
    for (Integer port : entityOpenPorts) {
        marathonBindings.put(port, 0);
    }
    Map<Integer, Integer> entityBindings = entity.config().get(DockerAttributes.DOCKER_PORT_BINDINGS);
    if (entityBindings != null) {
        for (Integer host : entityBindings.keySet()) {
            bindings.put(entityBindings.get(host), host);
            marathonBindings.put(host, entityBindings.get(host));
        }
    }
    if (bindings.isEmpty()) {
        List<PortAttributeSensorAndConfigKey> entityPortConfig = entity.config()
                .get(DockerAttributes.DOCKER_DIRECT_PORT_CONFIG);
        if (entityPortConfig != null) {
            for (PortAttributeSensorAndConfigKey key : entityPortConfig) {
                PortRange range = entity.config().get(key);
                if (range != null && !range.isEmpty()) {
                    Integer port = range.iterator().next();
                    if (port != null) {
                        bindings.put(port, port);
                        marathonBindings.put(port, port);
                    }
                }
            }
        }
        List<Integer> entityPorts = entity.config().get(DockerAttributes.DOCKER_DIRECT_PORTS);
        if (entityPorts != null) {
            for (Integer port : entityPorts) {
                bindings.put(port, port);
                marathonBindings.put(port, port);
            }
        }
    }
    sensors().set(DockerAttributes.DOCKER_CONTAINER_PORT_BINDINGS, bindings);
    entity.sensors().set(DockerAttributes.DOCKER_CONTAINER_PORT_BINDINGS, bindings);
    builder.put("portBindings", Lists.newArrayList(marathonBindings.entrySet()));

    // Environment variables and Docker links
    Map<String, Object> environment = MutableMap.copyOf(config().get(DOCKER_CONTAINER_ENVIRONMENT));
    environment.putAll(MutableMap.copyOf(entity.config().get(DOCKER_CONTAINER_ENVIRONMENT)));
    Map<String, Entity> links = entity.config().get(DockerAttributes.DOCKER_LINKS);
    if (links != null && links.size() > 0) {
        LOG.debug("Found links: {}", links);
        Map<String, String> extraHosts = MutableMap.of();
        for (Map.Entry<String, Entity> linked : links.entrySet()) {
            Map<String, Object> linkVars = DockerUtils.generateLinks(getRunningEntity(), linked.getValue(),
                    linked.getKey());
            environment.putAll(linkVars);
            String targetAddress = DockerUtils.getTargetAddress(getRunningEntity(), linked.getValue());
            extraHosts.put(linked.getKey(), targetAddress);
        }
        builder.put("extraHosts", Lists.newArrayList(extraHosts.entrySet()));
    }
    sensors().set(DockerContainer.DOCKER_CONTAINER_ENVIRONMENT, ImmutableMap.copyOf(environment));
    entity.sensors().set(DockerContainer.DOCKER_CONTAINER_ENVIRONMENT, ImmutableMap.copyOf(environment));
    builder.put("environment",
            Lists.newArrayList(Maps.transformValues(environment, Functions.toStringFunction()).entrySet()));

    // Volumes
    Map<String, String> volumes = MutableMap.of();
    Map<String, String> mapping = entity.config().get(DockerHost.DOCKER_HOST_VOLUME_MAPPING);
    if (mapping != null) {
        for (String source : mapping.keySet()) {
            volumes.put(source, mapping.get(source));
        }
    }
    sensors().set(DockerAttributes.DOCKER_VOLUME_MAPPING, volumes);
    entity.sensors().set(DockerAttributes.DOCKER_VOLUME_MAPPING, volumes);
    builder.put("volumes", Lists.newArrayList(volumes.entrySet()));

    // URIs to copy
    List<String> uris = MutableList.copyOf(config().get(TASK_URI_LIST));
    uris.addAll(MutableList.copyOf(entity.config().get(TASK_URI_LIST)));
    sensors().set(TASK_URI_LIST, uris);
    entity.sensors().set(TASK_URI_LIST, uris);
    builder.put("uris", uris);

    // Docker config
    Optional<String> imageName = Optional.fromNullable(config().get(DOCKER_IMAGE_NAME));
    if (imageName.isPresent()) {
        // Docker image
        builder.put("imageName", imageName.get());
        builder.put("imageVersion", config().get(DOCKER_IMAGE_TAG));

        // Docker command or args
        String command = config().get(COMMAND);
        builder.putIfNotNull("command", command);
        List<String> args = MutableList.copyOf(config().get(ARGS));
        builder.putIfNotNull("args", args);
    } else {
        // OS name for image
        OsFamily os = entity.config().get(JcloudsLocationConfig.OS_FAMILY);
        if (os == null) {
            os = provisioningProperties.get(JcloudsLocationConfig.OS_FAMILY);
        }
        if (os == null) {
            TemplateBuilder template = provisioningProperties.get(JcloudsLocationConfig.TEMPLATE_BUILDER);
            if (template != null) {
                os = template.build().getImage().getOperatingSystem().getFamily();
            }
        }
        if (os == null) {
            os = OsFamily.UBUNTU;
        }
        imageName = Optional.of(Strings.toLowerCase(os.value()));
        builder.put("imageName", "clockercentral/" + imageName.get());

        // OS version specified in regex config
        String version = entity.config().get(JcloudsLocationConfig.OS_VERSION_REGEX);
        if (version == null) {
            version = provisioningProperties.get(JcloudsLocationConfig.OS_VERSION_REGEX);
        }
        if (version == null) {
            TemplateBuilder template = provisioningProperties.get(JcloudsLocationConfig.TEMPLATE_BUILDER);
            if (template != null) {
                version = template.build().getImage().getOperatingSystem().getVersion();
            }
        }
        if (version == null) {
            version = "latest";
        }
        builder.put("imageVersion", version);

        // Empty args
        builder.put("args", ImmutableList.of());

        // Update volume to copy root's authorized keys from the host
        volumes.put("/root/.ssh/authorized_keys", "/root/.ssh/authorized_keys");
        builder.put("volumes", Lists.newArrayList(volumes.entrySet()));
    }

    return builder.build();
}

From source file:brooklyn.entity.mesos.task.marathon.MarathonTaskImpl.java

private Map<String, Object> getMarathonFlags(Entity entity) {
    MutableMap.Builder<String, Object> builder = MutableMap.builder();
    ConfigBag provisioningProperties = ConfigBag
            .newInstance(entity.config().get(SoftwareProcess.PROVISIONING_PROPERTIES));

    // CPU//from w w w.  jav  a2s . c  o m
    Double cpus = entity.config().get(MarathonTask.CPU_RESOURCES);
    if (cpus == null)
        cpus = config().get(MarathonTask.CPU_RESOURCES);
    if (cpus == null) {
        Integer minCores = entity.config().get(JcloudsLocationConfig.MIN_CORES);
        if (minCores == null) {
            minCores = provisioningProperties.get(JcloudsLocationConfig.MIN_CORES);
        }
        if (minCores == null) {
            TemplateBuilder template = provisioningProperties.get(JcloudsLocationConfig.TEMPLATE_BUILDER);
            if (template != null) {
                minCores = 0;
                for (Processor cpu : template.build().getHardware().getProcessors()) {
                    minCores = minCores + (int) cpu.getCores();
                }
            }
        }
        if (minCores != null) {
            cpus = 1.0d * minCores;
        }
    }
    if (cpus == null)
        cpus = 0.25d;
    builder.put("cpus", cpus);

    // Memory
    Integer memory = entity.config().get(MarathonTask.MEMORY_RESOURCES);
    if (memory == null)
        memory = config().get(MarathonTask.MEMORY_RESOURCES);
    if (memory == null) {
        Integer minRam = parseMbSizeString(entity.config().get(JcloudsLocationConfig.MIN_RAM));
        if (minRam == null) {
            minRam = parseMbSizeString(provisioningProperties.get(JcloudsLocationConfig.MIN_RAM));
        }
        if (minRam == null) {
            TemplateBuilder template = provisioningProperties.get(JcloudsLocationConfig.TEMPLATE_BUILDER);
            if (template != null) {
                minRam = template.build().getHardware().getRam();
            }
        }
        if (minRam != null) {
            memory = minRam;
        }
    }
    if (memory == null)
        memory = 256;
    builder.put("memory", memory);

    // Inbound ports
    Set<Integer> entityOpenPorts = MutableSet.copyOf(DockerUtils.getContainerPorts(entity));
    entityOpenPorts.addAll(DockerUtils.getOpenPorts(entity));
    if (!config().get(DockerContainer.DOCKER_USE_SSH)) {
        entityOpenPorts.remove(22);
    }
    builder.put("openPorts", Ints.toArray(entityOpenPorts));
    sensors().set(DockerAttributes.DOCKER_CONTAINER_OPEN_PORTS, ImmutableList.copyOf(entityOpenPorts));
    entity.sensors().set(DockerAttributes.DOCKER_CONTAINER_OPEN_PORTS, ImmutableList.copyOf(entityOpenPorts));

    // Direct port mappings
    // Note that the Marathon map is reversed, from container to host, with 0 indicating any host port
    Map<Integer, Integer> bindings = MutableMap.of();
    Map<Integer, Integer> marathonBindings = MutableMap.of();
    for (Integer port : entityOpenPorts) {
        marathonBindings.put(port, 0);
    }
    Map<Integer, Integer> entityBindings = entity.config().get(DockerAttributes.DOCKER_PORT_BINDINGS);
    if (entityBindings != null) {
        for (Integer host : entityBindings.keySet()) {
            bindings.put(entityBindings.get(host), host);
            marathonBindings.put(host, entityBindings.get(host));
        }
    }
    if (bindings.isEmpty()) {
        List<PortAttributeSensorAndConfigKey> entityPortConfig = entity.config()
                .get(DockerAttributes.DOCKER_DIRECT_PORT_CONFIG);
        if (entityPortConfig != null) {
            for (PortAttributeSensorAndConfigKey key : entityPortConfig) {
                PortRange range = entity.config().get(key);
                if (range != null && !range.isEmpty()) {
                    Integer port = range.iterator().next();
                    if (port != null) {
                        bindings.put(port, port);
                        marathonBindings.put(port, port);
                    }
                }
            }
        }
        List<Integer> entityPorts = entity.config().get(DockerAttributes.DOCKER_DIRECT_PORTS);
        if (entityPorts != null) {
            for (Integer port : entityPorts) {
                bindings.put(port, port);
                marathonBindings.put(port, port);
            }
        }
    }
    sensors().set(DockerAttributes.DOCKER_CONTAINER_PORT_BINDINGS, bindings);
    entity.sensors().set(DockerAttributes.DOCKER_CONTAINER_PORT_BINDINGS, bindings);
    builder.put("portBindings", Lists.newArrayList(marathonBindings.entrySet()));

    // Environment variables and Docker links
    Map<String, Object> environment = MutableMap.copyOf(config().get(DOCKER_CONTAINER_ENVIRONMENT));
    environment.putAll(MutableMap.copyOf(entity.config().get(DOCKER_CONTAINER_ENVIRONMENT)));
    List<Entity> links = entity.config().get(DockerAttributes.DOCKER_LINKS);
    if (links != null && links.size() > 0) {
        LOG.debug("Found links: {}", links);
        Map<String, String> extraHosts = MutableMap.of();
        for (Entity linked : links) {
            Map<String, Object> linkVars = DockerUtils.generateLinks(getRunningEntity(), linked);
            environment.putAll(linkVars);
            Optional<String> alias = DockerUtils.getUniqueContainerName(linked);
            if (alias.isPresent()) {
                String targetAddress = DockerUtils.getTargetAddress(getRunningEntity(), linked);
                extraHosts.put(alias.get(), targetAddress);
            }
        }
        builder.put("extraHosts", Lists.newArrayList(extraHosts.entrySet()));
    }
    sensors().set(DockerContainer.DOCKER_CONTAINER_ENVIRONMENT, ImmutableMap.copyOf(environment));
    entity.sensors().set(DockerContainer.DOCKER_CONTAINER_ENVIRONMENT, ImmutableMap.copyOf(environment));
    builder.put("environment",
            Lists.newArrayList(Maps.transformValues(environment, Functions.toStringFunction()).entrySet()));

    // Volumes
    Map<String, String> volumes = MutableMap.of();
    Map<String, String> mapping = entity.config().get(DockerHost.DOCKER_HOST_VOLUME_MAPPING);
    if (mapping != null) {
        for (String source : mapping.keySet()) {
            volumes.put(source, mapping.get(source));
        }
    }
    sensors().set(DockerAttributes.DOCKER_VOLUME_MAPPING, volumes);
    entity.sensors().set(DockerAttributes.DOCKER_VOLUME_MAPPING, volumes);
    builder.put("volumes", Lists.newArrayList(volumes.entrySet()));

    // URIs to copy
    List<String> uris = MutableList.copyOf(config().get(TASK_URI_LIST));
    uris.addAll(MutableList.copyOf(entity.config().get(TASK_URI_LIST)));
    sensors().set(TASK_URI_LIST, uris);
    entity.sensors().set(TASK_URI_LIST, uris);
    builder.put("uris", uris);

    // Docker config
    Optional<String> imageName = Optional.fromNullable(config().get(DOCKER_IMAGE_NAME));
    if (imageName.isPresent()) {
        // Docker image
        builder.put("imageName", imageName.get());
        builder.put("imageVersion", config().get(DOCKER_IMAGE_TAG));

        // Docker command or args
        String command = config().get(COMMAND);
        builder.putIfNotNull("command", command);
        List<String> args = MutableList.copyOf(config().get(ARGS));
        builder.putIfNotNull("args", args);
    } else {
        // OS name for image
        OsFamily os = entity.config().get(JcloudsLocationConfig.OS_FAMILY);
        if (os == null) {
            os = provisioningProperties.get(JcloudsLocationConfig.OS_FAMILY);
        }
        if (os == null) {
            TemplateBuilder template = provisioningProperties.get(JcloudsLocationConfig.TEMPLATE_BUILDER);
            if (template != null) {
                os = template.build().getImage().getOperatingSystem().getFamily();
            }
        }
        if (os == null) {
            os = OsFamily.UBUNTU;
        }
        imageName = Optional.of(Strings.toLowerCase(os.value()));
        builder.put("imageName", "clockercentral/" + imageName.get());

        // OS version specified in regex config
        String version = entity.config().get(JcloudsLocationConfig.OS_VERSION_REGEX);
        if (version == null) {
            version = provisioningProperties.get(JcloudsLocationConfig.OS_VERSION_REGEX);
        }
        if (version == null) {
            TemplateBuilder template = provisioningProperties.get(JcloudsLocationConfig.TEMPLATE_BUILDER);
            if (template != null) {
                version = template.build().getImage().getOperatingSystem().getVersion();
            }
        }
        if (version == null) {
            version = "latest";
        }
        builder.put("imageVersion", version);

        // Empty args
        builder.put("args", ImmutableList.of());

        // Update volume to copy root's authorized keys from the host
        volumes.put("/root/.ssh/authorized_keys", "/root/.ssh/authorized_keys");
        builder.put("volumes", Lists.newArrayList(volumes.entrySet()));
    }

    return builder.build();
}

From source file:brooklyn.util.text.Strings.java

public static Supplier<String> toStringSupplier(Object src) {
    return Suppliers.compose(Functions.toStringFunction(), Suppliers.ofInstance(src));
}

From source file:org.apache.brooklyn.container.location.kubernetes.KubernetesLocation.java

protected Map<String, String> findMetadata(Entity entity, ConfigBag setup, String value) {
    Map<String, String> podMetadata = Maps.newLinkedHashMap();
    if (isDockerContainer(entity)) {
        podMetadata.put(IMMUTABLE_CONTAINER_KEY, value);
    } else {//from   w w w  . ja va  2s .c  o m
        podMetadata.put(SSHABLE_CONTAINER, value);
    }

    Map<String, Object> metadata = MutableMap.<String, Object>builder()
            .putAll(MutableMap.copyOf(setup.get(KubernetesPod.METADATA)))
            .putAll(MutableMap.copyOf(entity.config().get(KubernetesPod.METADATA))).putAll(podMetadata).build();
    return Maps.transformValues(metadata, Functions.toStringFunction());
}

From source file:org.apache.brooklyn.container.location.kubernetes.KubernetesLocation.java

/**
 * Sets the {@code BROOKLYN_ROOT_PASSWORD} variable in the container environment if appropriate.
 * This is (approximately) the same behaviour as the {@link DockerJcloudsLocation} used for
 * Swarm./*w ww.  j a v a 2 s. c  o  m*/
 * <p>
 * Side-effects the location {@code config} to set the {@link KubernetesLocationConfig#LOGIN_USER_PASSWORD loginUser.password}
 * if one is auto-generated. Note that this injected value overrides any other settings configured for the
 * container environment.
 */
protected Map<String, String> findEnvironmentVariables(Entity entity, ConfigBag setup, String imageName) {
    String loginUser = setup.get(LOGIN_USER);
    String loginPassword = setup.get(LOGIN_USER_PASSWORD);
    Map<String, String> injections = Maps.newLinkedHashMap();

    // Check if login credentials should be injected
    Boolean injectLoginCredentials = setup.get(INJECT_LOGIN_CREDENTIAL);
    if (injectLoginCredentials == null) {
        for (String regex : IMAGE_DESCRIPTION_REGEXES_REQUIRING_INJECTED_LOGIN_CREDS) {
            if (imageName != null && imageName.matches(regex)) {
                injectLoginCredentials = true;
                break;
            }
        }
    }

    if (Boolean.TRUE.equals(injectLoginCredentials)) {
        if ((Strings.isBlank(loginUser) || "root".equals(loginUser))) {
            loginUser = "root";
            setup.configure(LOGIN_USER, loginUser);

            if (Strings.isBlank(loginPassword)) {
                loginPassword = Identifiers.makeRandomPassword(12);
                setup.configure(LOGIN_USER_PASSWORD, loginPassword);
            }

            injections.put(BROOKLYN_ROOT_PASSWORD, loginPassword);
        }
    }

    Map<String, Object> rawEnv = MutableMap.<String, Object>builder().putAll(MutableMap.copyOf(setup.get(ENV)))
            .putAll(MutableMap.copyOf(entity.config().get(DockerContainer.CONTAINER_ENVIRONMENT)))
            .putAll(injections).build();
    return Maps.transformValues(rawEnv, Functions.toStringFunction());
}

From source file:com.facebook.buck.apple.ProjectGenerator.java

private PBXNativeTarget generateBinaryTarget(PBXProject project,
        Optional<? extends TargetNode<? extends HasAppleBundleFields>> bundle,
        TargetNode<? extends CxxLibraryDescription.Arg> targetNode, ProductType productType,
        String productOutputFormat, Optional<Path> infoPlistOptional, boolean includeFrameworks,
        ImmutableSet<AppleResourceDescription.Arg> recursiveResources,
        ImmutableSet<AppleResourceDescription.Arg> directResources,
        ImmutableSet<AppleAssetCatalogDescription.Arg> recursiveAssetCatalogs,
        ImmutableSet<AppleAssetCatalogDescription.Arg> directAssetCatalogs,
        Optional<Iterable<PBXBuildPhase>> copyFilesPhases,
        Optional<TargetNode<AppleBundleDescription.Arg>> bundleLoaderNode) throws IOException {

    LOG.debug("Generating binary target for node %s", targetNode);

    TargetNode<?> buildTargetNode = bundle.isPresent() ? bundle.get() : targetNode;
    final BuildTarget buildTarget = buildTargetNode.getBuildTarget();

    String buildTargetName = getProductNameForBuildTarget(buildTarget);
    CxxLibraryDescription.Arg arg = targetNode.getConstructorArg();
    NewNativeTargetProjectMutator mutator = new NewNativeTargetProjectMutator(pathRelativizer,
            sourcePathResolver);//  w  ww.ja v  a  2  s. c  o  m
    ImmutableSet<SourcePath> exportedHeaders = ImmutableSet.copyOf(getHeaderSourcePaths(arg.exportedHeaders));
    ImmutableSet<SourcePath> headers = ImmutableSet.copyOf(getHeaderSourcePaths(arg.headers));
    ImmutableMap<CxxSource.Type, ImmutableList<String>> langPreprocessorFlags = targetNode
            .getConstructorArg().langPreprocessorFlags.get();

    mutator.setTargetName(getXcodeTargetName(buildTarget)).setLangPreprocessorFlags(langPreprocessorFlags)
            .setProduct(productType, buildTargetName,
                    Paths.get(String.format(productOutputFormat, buildTargetName)))
            .setSourcesWithFlags(ImmutableSet.copyOf(arg.srcs.get())).setPublicHeaders(exportedHeaders)
            .setPrivateHeaders(headers).setPrefixHeader(arg.prefixHeader)
            .setRecursiveResources(recursiveResources).setDirectResources(directResources);

    if (bundle.isPresent()) {
        HasAppleBundleFields bundleArg = bundle.get().getConstructorArg();
        mutator.setInfoPlist(Optional.of(bundleArg.getInfoPlist()));
    }

    Optional<TargetNode<AppleNativeTargetDescriptionArg>> appleTargetNode = targetNode
            .castArg(AppleNativeTargetDescriptionArg.class);
    if (appleTargetNode.isPresent()) {
        AppleNativeTargetDescriptionArg appleArg = appleTargetNode.get().getConstructorArg();
        mutator = mutator.setExtraXcodeSources(ImmutableSet.copyOf(appleArg.extraXcodeSources.get()));
    }

    if (options.contains(Option.CREATE_DIRECTORY_STRUCTURE)) {
        mutator.setTargetGroupPath(FluentIterable.from(buildTarget.getBasePath())
                .transform(Functions.toStringFunction()).toList());
    }

    if (!recursiveAssetCatalogs.isEmpty()) {
        mutator.setRecursiveAssetCatalogs(recursiveAssetCatalogs);
    }

    if (!directAssetCatalogs.isEmpty()) {
        mutator.setDirectAssetCatalogs(directAssetCatalogs);
    }

    if (includeFrameworks) {
        ImmutableSet.Builder<FrameworkPath> frameworksBuilder = ImmutableSet.builder();
        frameworksBuilder.addAll(targetNode.getConstructorArg().frameworks.get());
        frameworksBuilder.addAll(targetNode.getConstructorArg().libraries.get());
        frameworksBuilder.addAll(collectRecursiveFrameworkDependencies(ImmutableList.of(targetNode)));
        mutator.setFrameworks(frameworksBuilder.build());

        mutator.setArchives(collectRecursiveLibraryDependencies(ImmutableList.of(targetNode)));
    }

    // TODO(Task #3772930): Go through all dependencies of the rule
    // and add any shell script rules here
    ImmutableList.Builder<TargetNode<?>> preScriptPhases = ImmutableList.builder();
    ImmutableList.Builder<TargetNode<?>> postScriptPhases = ImmutableList.builder();
    boolean skipRNBundle = ReactNativeFlavors.skipBundling(buildTargetNode.getBuildTarget());
    if (bundle.isPresent() && targetNode != bundle.get()) {
        collectBuildScriptDependencies(targetGraph.getAll(bundle.get().getDeclaredDeps()), preScriptPhases,
                postScriptPhases, skipRNBundle);
    }
    collectBuildScriptDependencies(targetGraph.getAll(targetNode.getDeclaredDeps()), preScriptPhases,
            postScriptPhases, skipRNBundle);
    mutator.setPreBuildRunScriptPhasesFromTargetNodes(preScriptPhases.build());
    if (copyFilesPhases.isPresent()) {
        mutator.setCopyFilesPhases(copyFilesPhases.get());
    }
    mutator.setPostBuildRunScriptPhasesFromTargetNodes(postScriptPhases.build());
    mutator.skipReactNativeBundle(skipRNBundle);

    NewNativeTargetProjectMutator.Result targetBuilderResult;
    try {
        targetBuilderResult = mutator.buildTargetAndAddToProject(project);
    } catch (NoSuchBuildTargetException e) {
        throw new HumanReadableException(e);
    }
    PBXGroup targetGroup = targetBuilderResult.targetGroup;

    SourceTreePath buckFilePath = new SourceTreePath(PBXReference.SourceTree.SOURCE_ROOT,
            pathRelativizer.outputPathToBuildTargetPath(buildTarget).resolve(buildFileName),
            Optional.<String>absent());
    PBXFileReference buckReference = targetGroup.getOrCreateFileReferenceBySourceTreePath(buckFilePath);
    buckReference.setExplicitFileType(Optional.of("text.script.python"));

    // -- configurations
    ImmutableMap.Builder<String, String> extraSettingsBuilder = ImmutableMap.builder();
    extraSettingsBuilder.put("TARGET_NAME", buildTargetName).put("SRCROOT",
            pathRelativizer.outputPathToBuildTargetPath(buildTarget).toString());
    if (bundleLoaderNode.isPresent()) {
        TargetNode<AppleBundleDescription.Arg> bundleLoader = bundleLoaderNode.get();
        String bundleLoaderProductName = getProductNameForBuildTarget(bundleLoader.getBuildTarget());
        String bundleLoaderBundleName = bundleLoaderProductName + "."
                + getExtensionString(bundleLoader.getConstructorArg().getExtension());
        // NOTE(grp): This is a hack. We need to support both deep (OS X) and flat (iOS)
        // style bundles for the bundle loader, but at this point we don't know what platform
        // the bundle loader (or current target) is going to be built for. However, we can be
        // sure that it's the same as the target (presumably a test) we're building right now.
        //
        // Using that knowledge, we can do build setting tricks to defer choosing the bundle
        // loader path until Xcode build time, when the platform is known. There's no build
        // setting that conclusively says whether the current platform uses deep bundles:
        // that would be too easy. But in the cases we care about (unit test bundles), the
        // current bundle will have a style matching the style of the bundle loader app, so
        // we can take advantage of that to do the determination.
        //
        // Unfortunately, the build setting for the bundle structure (CONTENTS_FOLDER_PATH)
        // includes the WRAPPER_NAME, so we can't just interpolate that in. Instead, we have
        // to use another trick with build setting operations and evaluation. By using the
        // $(:file) operation, we can extract the last component of the contents path: either
        // "Contents" or the current bundle name. Then, we can interpolate with that expected
        // result in the build setting name to conditionally choose a different loader path.

        // The conditional that decdies which path is used. This is a complex Xcode build setting
        // expression that expands to one of two values, depending on the last path component of
        // the CONTENTS_FOLDER_PATH variable. As described above, this will be either "Contents"
        // for deep bundles or the bundle file name itself for flat bundles. Finally, to santiize
        // the potentially invalid build setting names from the bundle file name, it converts that
        // to an identifier. We rely on BUNDLE_LOADER_BUNDLE_STYLE_CONDITIONAL_<bundle file name>
        // being undefined (and thus expanding to nothing) for the path resolution to work.
        //
        // The operations on the CONTENTS_FOLDER_PATH are documented here:
        // http://codeworkshop.net/posts/xcode-build-setting-transformations
        String bundleLoaderOutputPathConditional = "$(BUNDLE_LOADER_BUNDLE_STYLE_CONDITIONAL_$(CONTENTS_FOLDER_PATH:file:identifier))";

        // If the $(CONTENTS_FOLDER_PATH:file:identifier) expands to this, we add the deep bundle
        // path into the bundle loader. See above for the case when it will expand to this value.
        String bundleLoaderOutputPathDeepSetting = "BUNDLE_LOADER_BUNDLE_STYLE_CONDITIONAL_Contents";
        String bundleLoaderOutputPathDeepValue = "Contents/MacOS/";

        String bundleLoaderOutputPathValue = Joiner.on('/').join(getTargetOutputPath(bundleLoader),
                bundleLoaderBundleName, bundleLoaderOutputPathConditional, bundleLoaderProductName);

        extraSettingsBuilder.put(bundleLoaderOutputPathDeepSetting, bundleLoaderOutputPathDeepValue)
                .put("BUNDLE_LOADER", bundleLoaderOutputPathValue).put("TEST_HOST", "$(BUNDLE_LOADER)");
    }
    if (infoPlistOptional.isPresent()) {
        Path infoPlistPath = pathRelativizer.outputDirToRootRelative(infoPlistOptional.get());
        extraSettingsBuilder.put("INFOPLIST_FILE", infoPlistPath.toString());
    }
    Optional<SourcePath> prefixHeaderOptional = targetNode.getConstructorArg().prefixHeader;
    if (prefixHeaderOptional.isPresent()) {
        Path prefixHeaderRelative = sourcePathResolver.apply(prefixHeaderOptional.get());
        Path prefixHeaderPath = pathRelativizer.outputDirToRootRelative(prefixHeaderRelative);
        extraSettingsBuilder.put("GCC_PREFIX_HEADER", prefixHeaderPath.toString());
        extraSettingsBuilder.put("GCC_PRECOMPILE_PREFIX_HEADER", "YES");
    }
    extraSettingsBuilder.put("USE_HEADERMAP", "NO");

    ImmutableMap.Builder<String, String> defaultSettingsBuilder = ImmutableMap.builder();
    defaultSettingsBuilder.put("REPO_ROOT",
            projectFilesystem.getRootPath().toAbsolutePath().normalize().toString());
    defaultSettingsBuilder.put(PRODUCT_NAME, getProductName(buildTargetNode, buildTarget));
    if (bundle.isPresent()) {
        defaultSettingsBuilder.put("WRAPPER_EXTENSION",
                getExtensionString(bundle.get().getConstructorArg().getExtension()));
    }

    // We use BUILT_PRODUCTS_DIR as the root for the everything being built. Target-
    // specific output is placed within CONFIGURATION_BUILD_DIR, inside BUILT_PRODUCTS_DIR.
    // That allows Copy Files build phases to reference files in the CONFIGURATION_BUILD_DIR
    // of other targets by using paths relative to the target-independent BUILT_PRODUCTS_DIR.
    defaultSettingsBuilder.put("BUILT_PRODUCTS_DIR",
            // $EFFECTIVE_PLATFORM_NAME starts with a dash, so this expands to something like:
            // $SYMROOT/Debug-iphonesimulator
            Joiner.on('/').join("$SYMROOT", "$CONFIGURATION$EFFECTIVE_PLATFORM_NAME"));
    defaultSettingsBuilder.put("CONFIGURATION_BUILD_DIR", "$BUILT_PRODUCTS_DIR");
    if (!bundle.isPresent() && (targetNode.getType().equals(AppleLibraryDescription.TYPE)
            || targetNode.getType().equals(CxxLibraryDescription.TYPE))) {
        defaultSettingsBuilder.put("EXECUTABLE_PREFIX", "lib");
    }

    ImmutableMap.Builder<String, String> appendConfigsBuilder = ImmutableMap.builder();

    ImmutableSet<Path> recursiveHeaderSearchPaths = collectRecursiveHeaderSearchPaths(targetNode);
    ImmutableSet<Path> headerMapBases = recursiveHeaderSearchPaths.isEmpty() ? ImmutableSet.<Path>of()
            : ImmutableSet.of(pathRelativizer.outputDirToRootRelative(BuckConstant.BUCK_OUTPUT_PATH));

    appendConfigsBuilder
            .put("HEADER_SEARCH_PATHS",
                    Joiner.on(' ').join(Iterables.concat(recursiveHeaderSearchPaths, headerMapBases)))
            .put("LIBRARY_SEARCH_PATHS",
                    Joiner.on(' ').join(collectRecursiveLibrarySearchPaths(ImmutableSet.of(targetNode))))
            .put("FRAMEWORK_SEARCH_PATHS",
                    Joiner.on(' ').join(collectRecursiveFrameworkSearchPaths(ImmutableList.of(targetNode))))
            .put("OTHER_CFLAGS",
                    Joiner.on(' ')
                            .join(Iterables.transform(
                                    Iterables.concat(cxxBuckConfig.getFlags("cflags").or(DEFAULT_CFLAGS),
                                            collectRecursiveExportedPreprocessorFlags(
                                                    ImmutableList.of(targetNode)),
                                            targetNode.getConstructorArg().compilerFlags.get(),
                                            targetNode.getConstructorArg().preprocessorFlags.get()),
                                    Escaper.BASH_ESCAPER)))
            .put("OTHER_CPLUSPLUSFLAGS",
                    Joiner.on(' ')
                            .join(Iterables.transform(
                                    Iterables.concat(cxxBuckConfig.getFlags("cxxflags").or(DEFAULT_CXXFLAGS),
                                            collectRecursiveExportedPreprocessorFlags(
                                                    ImmutableList.of(targetNode)),
                                            targetNode.getConstructorArg().compilerFlags.get(),
                                            targetNode.getConstructorArg().preprocessorFlags.get()),
                                    Escaper.BASH_ESCAPER)))
            .put("OTHER_LDFLAGS",
                    Joiner.on(' ')
                            .join(Iterables
                                    .transform(
                                            Iterables.concat(targetNode.getConstructorArg().linkerFlags.get(),
                                                    collectRecursiveExportedLinkerFlags(
                                                            ImmutableList.of(targetNode))),
                                            Escaper.BASH_ESCAPER)));

    ImmutableMap<String, String> appendedConfig = appendConfigsBuilder.build();

    Optional<ImmutableSortedMap<String, ImmutableMap<String, String>>> configs = getXcodeBuildConfigurationsForTargetNode(
            targetNode, appendedConfig);

    PBXNativeTarget target = targetBuilderResult.target;
    setTargetBuildConfigurations(getConfigurationNameToXcconfigPath(buildTarget), target,
            project.getMainGroup(), configs.get(), extraSettingsBuilder.build(), defaultSettingsBuilder.build(),
            appendedConfig);

    // -- phases
    createHeaderSymlinkTree(sourcePathResolver, getPublicCxxHeaders(targetNode),
            AppleDescriptions.getPathToHeaderSymlinkTree(targetNode, HeaderVisibility.PUBLIC));
    createHeaderSymlinkTree(sourcePathResolver, getPrivateCxxHeaders(targetNode),
            AppleDescriptions.getPathToHeaderSymlinkTree(targetNode, HeaderVisibility.PRIVATE));

    if (appleTargetNode.isPresent()) {
        // Use Core Data models from immediate dependencies only.
        addCoreDataModelsIntoTarget(appleTargetNode.get(), targetGroup);
    }

    return target;
}

From source file:gobblin.compaction.mapreduce.MRCompactor.java

/**
 * Submit an event when completeness verification is successful
 *///  w w w. j  ava 2  s  . co m
private void submitVerificationSuccessSlaEvent(Results.Result result) {
    try {
        CompactionSlaEventHelper.getEventSubmitterBuilder(result.dataset(), Optional.<Job>absent(), this.fs)
                .eventSubmitter(this.eventSubmitter)
                .eventName(CompactionSlaEventHelper.COMPLETION_VERIFICATION_SUCCESS_EVENT_NAME)
                .additionalMetadata(
                        Maps.transformValues(result.verificationContext(), Functions.toStringFunction()))
                .build().submit();
    } catch (Throwable t) {
        LOG.warn("Failed to submit verification success event:" + t, t);
    }
}