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:com.facebook.buck.android.MergeAndroidResourcesStep.java

@Override
public String getDescription(ExecutionContext context) {
    ImmutableList<String> sortedSymbolsFiles = FluentIterable.from(symbolsFileToRDotJavaPackage.keySet())
            .transform(Functions.toStringFunction()).toSortedList(natural());
    return getShortName() + " " + Joiner.on(' ').join(sortedSymbolsFiles) + " -o " + pathToGeneratedJavaFiles;
}

From source file:com.cloudera.director.aws.ec2.EphemeralDeviceMappings.java

/**
 * Gets a test instance of this class that uses only the given mapping.
 *
 * @param counts                      map of instance types to counts
 * @param launcherLocalizationContext the parent launcher localization context
 * @return new mapping object/*from ww  w. j  a v  a2s .  c  o  m*/
 */
public static EphemeralDeviceMappings getTestInstance(Map<String, Integer> counts,
        LocalizationContext launcherLocalizationContext) {
    Map<String, String> propertyMap = Maps.transformValues(counts, Functions.toStringFunction());
    PropertyResolver ephemeralDeviceMappingsResolver = PropertyResolvers.newMapPropertyResolver(propertyMap);
    File tempDir = Files.createTempDir();
    tempDir.deleteOnExit();
    EphemeralDeviceMappingsConfigProperties ephemeralDeviceMappingsConfigProperties = new EphemeralDeviceMappingsConfigProperties(
            new SimpleConfiguration(), tempDir, launcherLocalizationContext);
    return new EphemeralDeviceMappings(ephemeralDeviceMappingsConfigProperties,
            ephemeralDeviceMappingsResolver);
}

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

/**
 * Unlike expand, we need an intermediate "compact" operation to allow for recursion and handling of input from the
 * expansion operation. Embedded nodes should have an associated term definition, the top level term definition can
 * be omitted.//from   ww  w  .  j a  v a 2  s  . c  o m
 */
private Map<String, Object> compactNode(@Nullable TermDefinition definition, Map<?, ?> expanded) {
    Map<String, Object> result = new LinkedHashMap<>();
    for (Entry<?, ?> entry : expanded.entrySet()) {
        Term term = term(entry.getKey().toString());
        Object value = entry.getValue();
        if (term == JsonLdKeyword.TYPE && definition != null) {
            // Omit types specified by the definition
            Set<String> declaredTypes = FluentIterable.from((Iterable<?>) entry.getValue())
                    .transform(Functions.toStringFunction()).toSet();
            Set<String> definedTypes = FluentIterable.from(definition.getTypes())
                    .transform(Functions.toStringFunction()).toSet();
            value = ImmutableList.copyOf(Sets.difference(declaredTypes, definedTypes));
        }

        value = compactValue(termDefinitions.getUnchecked(term), value);
        if (value != null) {
            // Compact the key as well
            result.put(compactIri(term.toString()), value);
        }
    }
    return result;
}

From source file:com.eucalyptus.sla.ClusterAllocator.java

private QueuedEventCallback makeRunRequest(RunInstancesType request, final ResourceToken childToken,
        String rsvId, VmImageInfo imgInfo, VmKeyInfo keyInfo, VmTypeInfo vmInfo, byte[] userData) {
    List<String> macs = Lists.transform(childToken.getInstanceIds(), new Function<String, String>() {
        @Override//from  w w w  . java 2 s.  c o  m
        public String apply(String instanceId) {
            return VmInstances.getAsMAC(instanceId);
        }
    });

    NetworkToken primaryNet = childToken.getPrimaryNetwork();
    int vlan;
    List<String> netIndexes;
    List<String> networkNames;
    if (primaryNet != null) {
        vlan = primaryNet.getVlan();
        networkNames = Lists.newArrayList(primaryNet.getNetworkName());
        netIndexes = Lists
                .newArrayList(Iterables.transform(primaryNet.getIndexes(), Functions.toStringFunction()));
    } else {
        vlan = -1;
        networkNames = Lists.newArrayList("default");
        netIndexes = Lists.newArrayList("-1");
    }
    VmRunType run = new VmRunType(rsvId, request.getUserData(), childToken.getAmount(), imgInfo, vmInfo,
            keyInfo, childToken.getInstanceIds(), macs, vlan, networkNames, netIndexes)
                    .regardingUserRequest(request);
    VmRunCallback cb = new VmRunCallback(run, childToken);
    if (!childToken.getAddresses().isEmpty()) {
        final String address = childToken.getAddresses().get(0);
        cb.then(new SuccessCallback<VmRunResponseType>() {
            @Override
            public void apply(VmRunResponseType response) {
                for (VmInfo vmInfo : response.getVms()) {//TODO: this will have some funny failure characteristics
                    try {
                        final Address addr = Addresses.getInstance().lookup(address);
                        final VmInstance vm = VmInstances.getInstance()
                                .lookup(childToken.getInstanceIds().get(0));
                        addr.assign(vmInfo.getInstanceId(), vmInfo.getNetParams().getIpAddress()).getCallback()
                                .dispatch(addr.getCluster());
                    } catch (NoSuchElementException ex) {
                        LOG.debug(ex, ex);
                    }
                }
            }
        });
    }
    return cb;
}

From source file:edu.harvard.med.screensaver.ui.screens.ScreenSearchResults.java

public List<TableColumn<Screen, ?>> buildScreenAdminColumns() {
    List<TableColumn<Screen, ?>> columns = Lists.newArrayList();

    columns.add(new EnumEntityColumn<Screen, ScreenDataSharingLevel>(
            RelationshipPath.from(Screen.class).toProperty("dataSharingLevel"), "Data Sharing Level",
            "The data sharing level", TableColumn.UNGROUPED, ScreenDataSharingLevel.values()) {
        @Override//from  w  w w .  j  ava2 s .  c o  m
        public ScreenDataSharingLevel getCellValue(Screen screen) {
            return screen.getDataSharingLevel();
        }
    });
    columns.get(columns.size() - 1).setAdministrative(false);
    columns.get(columns.size() - 1).setVisible(false);

    columns.add(new DateEntityColumn<Screen>(
            RelationshipPath.from(Screen.class).toProperty("dataPrivacyExpirationDate"),
            "Data Privacy Expiration Date", "The date on which the screen will become visible to level 1 users",
            TableColumn.UNGROUPED) {
        @Override
        public LocalDate getDate(Screen screen) {
            return screen.getDataPrivacyExpirationDate();
        }
    });
    columns.get(columns.size() - 1).setAdministrative(true);
    columns.get(columns.size() - 1).setVisible(false);

    columns.add(new DateEntityColumn<Screen>(Screen.labActivities.toProperty("dateOfActivity"),
            "Date of First Activity", "The date of the first lab activity performed for this screen",
            TableColumn.UNGROUPED) {
        @Override
        protected LocalDate getDate(Screen screen) {
            return screen.getLabActivities().isEmpty() ? null
                    : screen.getLabActivities().first().getDateOfActivity();
        }
    });
    columns.get(columns.size() - 1).setAdministrative(true);
    columns.get(columns.size() - 1).setVisible(false);

    columns.add(new DateEntityColumn<Screen>(Screen.labActivities.toProperty("dateOfActivity"),
            "Date Of Last Activity", "The date of the last lab activity performed for this screen",
            TableColumn.UNGROUPED) {
        @Override
        protected LocalDate getDate(Screen screen) {
            return screen.getLabActivities().isEmpty() ? null
                    : screen.getLabActivities().last().getDateOfActivity();
        }
    });
    columns.get(columns.size() - 1).setAdministrative(true);
    columns.get(columns.size() - 1).setVisible(false);

    if (!!!getApplicationProperties().isFacility(LincsScreensaverConstants.FACILITY_KEY)) {
        columns.add(new EnumEntityColumn<Screen, ScreenStatus>(Screen.statusItems.toProperty("status"),
                "Status", "The current status of the screen, e.g., 'Completed', 'Ongoing', 'Pending', etc.",
                TableColumn.UNGROUPED, ScreenStatus.values()) {
            @Override
            public ScreenStatus getCellValue(Screen screen) {
                SortedSet<StatusItem> statusItems = screen.getStatusItems();
                return statusItems.isEmpty() ? null : statusItems.last().getStatus();
            }
        });
        columns.get(columns.size() - 1).setAdministrative(true);

        columns.add(new DateEntityColumn<Screen>(Screen.statusItems.toProperty("statusDate"), "Status Date",
                "The date of the most recent change of status for the screen", TableColumn.UNGROUPED) {
            @Override
            protected LocalDate getDate(Screen screen) {
                SortedSet<StatusItem> statusItems = screen.getStatusItems();
                return statusItems.isEmpty() ? null : statusItems.last().getStatusDate();
            }
        });
        columns.get(columns.size() - 1).setAdministrative(true);
    }

    // TODO: should make this a vocab list, but need support for list-of-vocab column type
    columns.add(new TextSetEntityColumn<Screen>(Screen.fundingSupports.toProperty("value"), "Funding Supports",
            "The list of funding supports for the screen", TableColumn.UNGROUPED) {
        @Override
        public Set<String> getCellValue(Screen screen) {
            return Sets
                    .newHashSet(Iterables.transform(screen.getFundingSupports(), Functions.toStringFunction()));
        }
    });
    columns.get(columns.size() - 1).setAdministrative(true);
    columns.get(columns.size() - 1).setVisible(false);

    columns.add(new IntegerEntityColumn<Screen>(
            RelationshipPath.from(Screen.class).toProperty("screenedExperimentalWellCount"),
            "Experimental Wells Screened (Non-unique)",
            "The number of experimental library wells that have been screened (counting duplicate wells multiple times, ignoring replicates)",
            TableColumn.UNGROUPED) {
        @Override
        public Integer getCellValue(Screen screen) {
            return screen.getScreenedExperimentalWellCount();
        }
    });
    columns.get(columns.size() - 1).setAdministrative(true);
    columns.get(columns.size() - 1).setVisible(false);

    columns.add(new IntegerEntityColumn<Screen>(
            RelationshipPath.from(Screen.class).toProperty("screenedExperimentalWellCount"),
            "Experimental Wells Screened (Unique)",
            "The number of experimental library wells that have been screened (counting duplicate wells once, ignoring replicates)",
            TableColumn.UNGROUPED) {
        @Override
        public Integer getCellValue(Screen screen) {
            return screen.getUniqueScreenedExperimentalWellCount();
        }
    });
    columns.get(columns.size() - 1).setAdministrative(true);
    columns.get(columns.size() - 1).setVisible(false);

    columns.add(new IntegerEntityColumn<Screen>(
            RelationshipPath.from(Screen.class).toProperty("totalPlatedLabCherryPicks"),
            "Total Plated Cherry Picks",
            "The number of lab cherry picks that have been plated to date, for all cherry pick requests",
            TableColumn.UNGROUPED) {
        @Override
        public Integer getCellValue(Screen screen) {
            return screen.getTotalPlatedLabCherryPicks();
        }
    });
    columns.get(columns.size() - 1).setAdministrative(true);
    columns.get(columns.size() - 1).setVisible(false);

    columns.add(new TextEntityColumn<Screen>(RelationshipPath.from(Screen.class).toProperty("summary"),
            "Summary", "A summary of the screen", TableColumn.UNGROUPED) {
        @Override
        public String getCellValue(Screen screen) {
            return screen.getSummary();
        }
    });
    columns.get(columns.size() - 1).setAdministrative(true);
    columns.get(columns.size() - 1).setVisible(false);

    return columns;
}

From source file:com.eucalyptus.cluster.callback.reporting.CloudWatchHelper.java

private static <E extends Enum<E>> Map<String, String> metricsToUnitType(final Class<E> unitEnum) {
    return CollectionUtils.putAll(EnumSet.allOf(unitEnum), Maps.<String, String>newHashMap(),
            Functions.toStringFunction(), Functions.constant(unitEnum.getSimpleName()));
}

From source file:uk.ac.cam.cl.dtg.segue.dao.content.GitContentManager.java

@Override
public final Set<String> getTagsList(final String version) throws ContentManagerException {
    Validate.notBlank(version);//w  w  w. j av a 2s  .c  o  m

    List<Object> tagObjects = (List<Object>) searchProvider.getById(version, "metadata", "tags").getSource()
            .get("tags");

    return new HashSet<>(Lists.transform(tagObjects, Functions.toStringFunction()));
}

From source file:org.fao.geonet.api.groups.GroupsApi.java

@ApiOperation(value = "Remove a group", notes = "Remove a group by first removing sharing settings, link to users and "
        + "finally reindex all affected records.", authorizations = {
                @Authorization(value = "basicAuth") }, nickname = "deleteGroup")
@RequestMapping(value = "/{groupIdentifier}", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.DELETE)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
@PreAuthorize("hasRole('Administrator')")
@ApiResponses(value = { @ApiResponse(code = 204, message = "Group removed."),
        @ApiResponse(code = 404, message = ApiParams.API_RESPONSE_RESOURCE_NOT_FOUND),
        @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_ONLY_USER_ADMIN) })
@ResponseBody//from  w w w. j  a  va  2s .  c om
public void deleteGroup(@ApiParam(value = "Group identifier.") @PathVariable Integer groupIdentifier,
        @ApiParam(value = "Force removal even if records are assigned to that group.") @RequestParam(defaultValue = "false") boolean force,
        @ApiIgnore ServletRequest request) throws Exception {
    GroupRepository groupRepository = ApplicationContextHolder.get().getBean(GroupRepository.class);

    Group group = groupRepository.findOne(groupIdentifier);

    if (group != null) {
        OperationAllowedRepository operationAllowedRepo = ApplicationContextHolder.get()
                .getBean(OperationAllowedRepository.class);
        UserGroupRepository userGroupRepo = ApplicationContextHolder.get().getBean(UserGroupRepository.class);

        List<Integer> reindex = operationAllowedRepo
                .findAllIds(OperationAllowedSpecs.hasGroupId(groupIdentifier), OperationAllowedId_.metadataId);

        if (reindex.size() > 0 && force) {
            operationAllowedRepo.deleteAllByIdAttribute(OperationAllowedId_.groupId, groupIdentifier);

            //--- reindex affected metadata
            DataManager dm = ApplicationContextHolder.get().getBean(DataManager.class);
            dm.indexMetadata(Lists.transform(reindex, Functions.toStringFunction()));
        } else if (reindex.size() > 0 && !force) {
            throw new NotAllowedException(String.format(
                    "Group %s has privileges associated with %d record(s). Add 'force' parameter to remove it or remove privileges associated with that group first.",
                    group.getName(), reindex.size()));
        }

        final List<Integer> users = userGroupRepo.findUserIds(where(UserGroupSpecs.hasGroupId(group.getId())));
        if (users.size() > 0 && force) {
            userGroupRepo.deleteAllByIdAttribute(UserGroupId_.groupId, Arrays.asList(groupIdentifier));
        } else if (users.size() > 0 && !force) {
            throw new NotAllowedException(String.format(
                    "Group %s is associated with %d user(s). Add 'force' parameter to remove it or remove users associated with that group first.",
                    group.getName(), users.size()));
        }

        groupRepository.delete(groupIdentifier);

    } else {
        throw new ResourceNotFoundException(
                String.format(MSG_GROUP_WITH_IDENTIFIER_NOT_FOUND, groupIdentifier));
    }
}

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

/**
 * Generates a serialized version of the context.
 *//*from w  w w  .  ja v  a 2 s.  c  om*/
public Map<String, Object> serialize() {
    final Map<String, Object> context = new LinkedHashMap<>();
    final Map<String, TermDefinition> localContext = new LinkedHashMap<>();
    if (getBase() != null) {
        context.put(JsonLdKeyword.BASE.toString(), getBase().toString());
    }
    if (getVocab() != null) {
        context.put(JsonLdKeyword.VOCAB.toString(), getVocab());
    }
    for (Entry<String, TermDefinition> entry : definitions.entrySet()) {
        TermDefinition definition = entry.getValue();
        Object serializedDefinition = compactIri(definition.getTerm().toString(), localContext);
        if (!definition.getTypes().isEmpty() || definition.getContainer() != Container.UNKNOWN) {
            Map<String, Object> definitionMap = new LinkedHashMap<>(3);
            if (!entry.getKey().equals(serializedDefinition)) {
                definitionMap.put(JsonLdKeyword.ID.toString(), serializedDefinition);
            }
            if (definition.getTypes().size() == 1) {
                definitionMap.put(JsonLdKeyword.TYPE.toString(),
                        compactIri(Iterables.getOnlyElement(definition.getTypes()).toString(), localContext));
            } else if (!definition.getTypes().isEmpty()) {
                definitionMap.put(JsonLdKeyword.TYPE.toString(), FluentIterable.from(definition.getTypes())
                        .transform(Functions.toStringFunction()).transform(new Function<String, String>() {
                            @Override
                            public String apply(String input) {
                                return compactIri(input, localContext);
                            }
                        }).toList());
            }
            if (definition.getContainer() != Container.UNKNOWN) {
                definitionMap.put(JsonLdKeyword.CONTAINER.toString(), definition.getContainer().toString());
            }
            serializedDefinition = definitionMap;
        }
        context.put(entry.getKey(), serializedDefinition);
        localContext.put(entry.getKey(), definition);
    }
    return ImmutableMap.<String, Object>of(JsonLdKeyword.CONTEXT.toString(), context);
}

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

private void generateBuildWithBuckTarget(TargetNode<?> targetNode) throws IOException {
    final BuildTarget buildTarget = targetNode.getBuildTarget();

    String buckTargetProductName = getXcodeTargetName(buildTarget) + BUILD_WITH_BUCK_POSTFIX;

    PBXAggregateTarget buildWithBuckTarget = new PBXAggregateTarget(buckTargetProductName);
    buildWithBuckTarget.setProductName(buckTargetProductName);

    PBXShellScriptBuildPhase buildShellScriptBuildPhase = new PBXShellScriptBuildPhase();
    buildShellScriptBuildPhase.setShellScript(getBuildWithBuckShellScript(targetNode));
    buildWithBuckTarget.getBuildPhases().add(buildShellScriptBuildPhase);

    // Only add a shell script for fixing UUIDs if it is an AppleBundle
    if (targetNode.getType().equals(AppleBundleDescription.TYPE)) {
        PBXShellScriptBuildPhase fixUUIDShellScriptBuildPhase = new PBXShellScriptBuildPhase();
        fixUUIDShellScriptBuildPhase.setShellScript(getFixUUIDShellScript(targetNode));
        buildWithBuckTarget.getBuildPhases().add(fixUUIDShellScriptBuildPhase);

        PBXShellScriptBuildPhase codesignPhase = new PBXShellScriptBuildPhase();
        codesignPhase.setShellScript(getCodesignShellScript(targetNode));
        buildWithBuckTarget.getBuildPhases().add(codesignPhase);
    }/*  w  w  w  .ja  va2  s . c o  m*/

    TargetNode<CxxLibraryDescription.Arg> node = getAppleNativeNode(targetGraph, targetNode).get();
    ImmutableMap<String, ImmutableMap<String, String>> configs = getXcodeBuildConfigurationsForTargetNode(node,
            ImmutableMap.<String, String>of()).get();

    XCConfigurationList configurationList = new XCConfigurationList();
    PBXGroup group = project.getMainGroup()
            .getOrCreateDescendantGroupByPath(FluentIterable.from(buildTarget.getBasePath())
                    .transform(Functions.toStringFunction()).toList())
            .getOrCreateChildGroupByName(getXcodeTargetName(buildTarget));
    for (String configurationName : configs.keySet()) {
        XCBuildConfiguration configuration = configurationList.getBuildConfigurationsByName()
                .getUnchecked(configurationName);
        configuration.setBaseConfigurationReference(getConfigurationFileReference(group,
                getConfigurationNameToXcconfigPath(buildTarget).apply(configurationName)));

        NSDictionary inlineSettings = new NSDictionary();
        inlineSettings.put("HEADER_SEARCH_PATHS", "");
        inlineSettings.put("LIBRARY_SEARCH_PATHS", "");
        inlineSettings.put("FRAMEWORK_SEARCH_PATHS", "");
        configuration.setBuildSettings(inlineSettings);
    }

    buildWithBuckTarget.setBuildConfigurationList(configurationList);
    project.getTargets().add(buildWithBuckTarget);

    targetNodeToGeneratedProjectTargetBuilder.put(targetNode, buildWithBuckTarget);
}