Example usage for com.google.common.collect Collections2 transform

List of usage examples for com.google.common.collect Collections2 transform

Introduction

In this page you can find the example usage for com.google.common.collect Collections2 transform.

Prototype

public static <F, T> Collection<T> transform(Collection<F> fromCollection, Function<? super F, T> function) 

Source Link

Document

Returns a collection that applies function to each element of fromCollection .

Usage

From source file:org.jetbrains.kotlin.idea.framework.ui.FileUIUtils.java

@Nullable
public static Map<File, File> copyWithOverwriteDialog(@NotNull String messagesTitle,
        @NotNull Map<File, String> filesWithDestinations) {
    Set<String> fileNames = new HashSet<String>();
    Map<File, File> targetFiles = new LinkedHashMap<File, File>(filesWithDestinations.size());
    for (Map.Entry<File, String> sourceToDestination : filesWithDestinations.entrySet()) {
        File file = sourceToDestination.getKey();
        String destinationPath = sourceToDestination.getValue();

        String fileName = file.getName();

        if (!fileNames.add(fileName)) {
            throw new IllegalArgumentException("There are several files with the same name: " + fileName);
        }// w  w  w. j a  va  2 s .com

        targetFiles.put(file, new File(destinationPath, fileName));
    }

    Collection<Map.Entry<File, File>> existentFiles = Collections2.filter(targetFiles.entrySet(),
            new Predicate<Map.Entry<File, File>>() {
                @Override
                public boolean apply(@Nullable Map.Entry<File, File> sourceToTarget) {
                    assert sourceToTarget != null;
                    return sourceToTarget.getValue().exists();
                }
            });

    if (!existentFiles.isEmpty()) {
        String message;

        if (existentFiles.size() == 1) {
            File conflictingFile = existentFiles.iterator().next().getValue();
            message = String.format("File \"%s\" already exists in %s.\nDo you want to overwrite it?",
                    conflictingFile.getName(), conflictingFile.getParentFile().getAbsolutePath());
        } else {
            Collection<File> conflictFiles = Collections2.transform(existentFiles,
                    new Function<Map.Entry<File, File>, File>() {
                        @Override
                        public File apply(@Nullable Map.Entry<File, File> pair) {
                            assert pair != null;
                            return pair.getValue();
                        }
                    });
            message = String.format("Files already exist:\n%s\nDo you want to overwrite them?",
                    StringUtil.join(conflictFiles, "\n"));
        }

        int replaceIfExist = Messages.showYesNoDialog(null, message, messagesTitle + ". Replace File",
                "Overwrite", "Cancel", Messages.getWarningIcon());

        if (replaceIfExist != JOptionPane.YES_OPTION) {
            return null;
        }
    }

    for (Map.Entry<File, File> sourceToTarget : targetFiles.entrySet()) {
        try {
            String destinationPath = sourceToTarget.getValue().getParentFile().getAbsolutePath();
            if (!ProjectWizardUtil.createDirectoryIfNotExists("Destination folder", destinationPath, false)) {
                Messages.showErrorDialog(String.format("Error during folder creating '%s'", destinationPath),
                        messagesTitle + ". Error");
                return null;
            }

            FileUtil.copy(sourceToTarget.getKey(), sourceToTarget.getValue());
            LocalFileSystem.getInstance().refreshAndFindFileByIoFile(sourceToTarget.getValue());
        } catch (IOException e) {
            Messages.showErrorDialog("Error with copy file " + sourceToTarget.getKey().getName(),
                    messagesTitle + ". Error");
            return null;
        }
    }

    return targetFiles;
}

From source file:net.shibboleth.idp.saml.audit.impl.AssertionIDAuditExtractor.java

/** {@inheritDoc} */
@Override//from   w  ww . ja v a  2 s  .c  om
@Nullable
public Collection<String> apply(@Nullable final ProfileRequestContext input) {
    SAMLObject message = responseLookupStrategy.apply(input);
    if (message != null) {

        // Step down into ArtifactResponses.
        if (message instanceof ArtifactResponse) {
            message = ((ArtifactResponse) message).getMessage();
        }

        if (message instanceof org.opensaml.saml.saml2.core.Response) {

            final List<org.opensaml.saml.saml2.core.Assertion> assertions = ((org.opensaml.saml.saml2.core.Response) message)
                    .getAssertions();
            if (!assertions.isEmpty()) {
                return Collections2.transform(assertions,
                        new Function<org.opensaml.saml.saml2.core.Assertion, String>() {
                            public String apply(org.opensaml.saml.saml2.core.Assertion input) {
                                return input.getID();
                            }
                        });
            }

        } else if (message instanceof org.opensaml.saml.saml1.core.Response) {

            final List<org.opensaml.saml.saml1.core.Assertion> assertions = ((org.opensaml.saml.saml1.core.Response) message)
                    .getAssertions();
            if (!assertions.isEmpty()) {
                return Collections2.transform(assertions,
                        new Function<org.opensaml.saml.saml1.core.Assertion, String>() {
                            public String apply(org.opensaml.saml.saml1.core.Assertion input) {
                                return input.getID();
                            }
                        });
            }

        } else if (message instanceof org.opensaml.saml.saml2.core.Assertion) {
            return Collections.singletonList(((org.opensaml.saml.saml2.core.Assertion) message).getID());
        } else if (message instanceof org.opensaml.saml.saml1.core.Assertion) {
            return Collections.singletonList(((org.opensaml.saml.saml1.core.Assertion) message).getID());
        }
    }

    return Collections.emptyList();
}

From source file:com.offbytwo.jenkins.model.Job.java

/**
 * Trigger a parameterized build/*  w  ww .j av  a  2s.c o m*/
 *
 * @param params
 *            the job parameters
 * @param crumbFlag
 *            determines whether crumb flag is used
 * @throws IOException
 */
public QueueReference build(Map<String, String> params, boolean crumbFlag) throws IOException {
    String qs = join(Collections2.transform(params.entrySet(), new MapEntryToQueryStringPair()), "&");
    ExtractHeader location = client.post(url + "buildWithParameters?" + qs, null, ExtractHeader.class,
            crumbFlag);
    return new QueueReference(location.getLocation());
}

From source file:gov.nih.nci.caintegrator.web.transfer.AuthorizationTrees.java

private void handleAnnotationFieldDescriptors(StudyConfiguration studyConfig,
        final AuthorizedStudyElementsGroup authGroup) {
    for (final AnnotationFieldDescriptor descriptor : studyConfig.getStudy().getAuthorizedFieldDescriptors()) {
        TreeNode node = new TreeNode(descriptor.getId(), descriptor.getDisplayName(), false);
        Set<String> permissibleValues = PermissibleValueUtil
                .getDisplayPermissibleValue(descriptor.getPermissibleValues());
        node.getChildren().addAll(Collections2.transform(permissibleValues, new Function<String, TreeNode>() {
            @Override//from w w w . ja  v a 2  s .  c  om
            public TreeNode apply(String value) {
                TreeNode node = new TreeNode(null, value, isSelected(descriptor, value, authGroup));
                return node;
            }
        }));
        fieldDescriptors.add(node);
    }
}

From source file:org.apache.beam.sdk.options.PipelineOptionsValidator.java

/**
 * Validates that the passed {@link PipelineOptions} conforms to all the validation criteria from
 * the passed in interface.//  w ww.j  av a  2 s.  com
 *
 * <p>Note that the interface requested must conform to the validation criteria specified on
 * {@link PipelineOptions#as(Class)}.
 *
 * @param klass The interface to fetch validation criteria from.
 * @param options The {@link PipelineOptions} to validate.
 * @return The type
 */
public static <T extends PipelineOptions> T validate(Class<T> klass, PipelineOptions options) {
    checkNotNull(klass);
    checkNotNull(options);
    checkArgument(Proxy.isProxyClass(options.getClass()));
    checkArgument(Proxy.getInvocationHandler(options) instanceof ProxyInvocationHandler);

    // Ensure the methods for T are registered on the ProxyInvocationHandler
    T asClassOptions = options.as(klass);

    ProxyInvocationHandler handler = (ProxyInvocationHandler) Proxy.getInvocationHandler(asClassOptions);

    SortedSetMultimap<String, Method> requiredGroups = TreeMultimap.create(Ordering.natural(),
            PipelineOptionsFactory.MethodNameComparator.INSTANCE);
    for (Method method : ReflectHelpers.getClosureOfMethodsOnInterface(klass)) {
        Required requiredAnnotation = method.getAnnotation(Validation.Required.class);
        if (requiredAnnotation != null) {
            if (requiredAnnotation.groups().length > 0) {
                for (String requiredGroup : requiredAnnotation.groups()) {
                    requiredGroups.put(requiredGroup, method);
                }
            } else {
                checkArgument(handler.invoke(asClassOptions, method, null) != null,
                        "Missing required value for [%s, \"%s\"]. ", method, getDescription(method));
            }
        }
    }

    for (String requiredGroup : requiredGroups.keySet()) {
        if (!verifyGroup(handler, asClassOptions, requiredGroups.get(requiredGroup))) {
            throw new IllegalArgumentException("Missing required value for group [" + requiredGroup
                    + "]. At least one of the following properties "
                    + Collections2.transform(requiredGroups.get(requiredGroup), ReflectHelpers.METHOD_FORMATTER)
                    + " required. Run with --help=" + klass.getSimpleName() + " for more information.");
        }
    }

    return asClassOptions;
}

From source file:org.opendaylight.controller.netconf.cli.reader.impl.ListEntryReader.java

@Override
public List<Node<?>> readWithContext(final ListSchemaNode listNode) throws IOException, ReadingException {
    console.formatLn("Submit child nodes for list entry: %s, %s", listNode.getQName().getLocalName(),
            Collections2.transform(listNode.getChildNodes(), new Function<DataSchemaNode, String>() {
                @Override//  ww  w  . j a  v a  2s .  c  o  m
                public String apply(final DataSchemaNode input) {
                    return input.getQName().getLocalName();
                }
            }));

    final String listName = listNode.getQName().getLocalName();
    final CompositeNodeBuilder<ImmutableCompositeNode> compositeNodeBuilder = ImmutableCompositeNode.builder();
    compositeNodeBuilder.setQName(listNode.getQName());

    final SeparatedNodes separatedChildNodes = SeparatedNodes.separateNodes(listNode, getReadConfigNode());

    final List<Node<?>> nodes = readKeys(separatedChildNodes.getKeyNodes());
    nodes.addAll(readMandatoryNotKeys(separatedChildNodes.getMandatoryNotKey()));
    if (!separatedChildNodes.getOthers().isEmpty()) {
        final Optional<Boolean> readNodesWhichAreNotKey = new DecisionReader().read(console,
                "Add non-key, non-mandatory nodes to list %s? [Y|N]", listName);
        if (readNodesWhichAreNotKey.isPresent() && readNodesWhichAreNotKey.get()) {
            nodes.addAll(readNotKeys(separatedChildNodes.getOthers()));
        }
    }

    if (!nodes.isEmpty()) {
        compositeNodeBuilder.addAll(nodes);
        return Collections.<Node<?>>singletonList(compositeNodeBuilder.toInstance());
    } else {
        return Collections.emptyList();
    }
}

From source file:ru.crazyproger.plugins.webtoper.nls.codeinsight.NlsCompletionContributor.java

@NotNull
public static Collection<NlsFileImpl> getNlsFiles(Project project) {
    Collection<VirtualFile> files = getNlsVirtualFiles(project);
    if (files.isEmpty())
        return Collections.emptyList();
    final PsiManager psiManager = PsiManager.getInstance(project);
    Collection<NlsFileImpl> nlsFiles = Collections2.transform(files, new Function<VirtualFile, NlsFileImpl>() {
        @Override//www . j  a va 2 s  .  co m
        public NlsFileImpl apply(@Nullable VirtualFile virtualFile) {
            if (virtualFile != null) {
                return (NlsFileImpl) psiManager.findFile(virtualFile);
            }
            return null;
        }
    });
    return Collections2.filter(nlsFiles, Predicates.notNull());
}

From source file:com.netflix.paas.cassandra.discovery.EurekaAstyanaxHostSupplier.java

@Override
public Supplier<List<Host>> getSupplier(final String clusterName) {
    return new Supplier<List<Host>>() {

        @Override/* ww w.j a v a 2 s .  c  o  m*/
        public List<Host> get() {
            Application app = eurekaClient.getApplication(clusterName.toUpperCase());
            List<Host> hosts = Lists.newArrayList();
            if (app == null) {
                LOG.warn("Cluster '{}' not found in eureka", new Object[] { clusterName });
            } else {
                List<InstanceInfo> ins = app.getInstances();
                if (ins != null && !ins.isEmpty()) {
                    hosts = Lists.newArrayList(
                            Collections2.transform(Collections2.filter(ins, new Predicate<InstanceInfo>() {
                                @Override
                                public boolean apply(InstanceInfo input) {
                                    return input.getStatus() == InstanceInfo.InstanceStatus.UP;
                                }
                            }), new Function<InstanceInfo, Host>() {
                                @Override
                                public Host apply(InstanceInfo info) {
                                    String[] parts = StringUtils
                                            .split(StringUtils.split(info.getHostName(), ".")[0], '-');

                                    Host host = new Host(info.getHostName(), info.getPort())
                                            .addAlternateIpAddress(StringUtils.join(
                                                    new String[] { parts[1], parts[2], parts[3], parts[4] },
                                                    "."))
                                            .addAlternateIpAddress(info.getIPAddr()).setId(info.getId());

                                    try {
                                        if (info.getDataCenterInfo() instanceof AmazonInfo) {
                                            AmazonInfo amazonInfo = (AmazonInfo) info.getDataCenterInfo();
                                            host.setRack(amazonInfo.get(MetaDataKey.availabilityZone));
                                        }
                                    } catch (Throwable t) {
                                        LOG.error("Error getting rack for host " + host.getName(), t);
                                    }

                                    return host;
                                }
                            }));
                } else {
                    LOG.warn("Cluster '{}' found in eureka but has no instances", new Object[] { clusterName });
                }
            }
            return hosts;
        }
    };
}

From source file:eu.esdihumboldt.hale.io.jdbc.constraints.factory.SQLArrayFactory.java

@Override
public Value store(SQLArray constraint, TypeReferenceBuilder typeIndex) throws Exception {
    ValueProperties props = new ValueProperties();

    if (constraint.isArray()) {
        // store element class
        Class<?> elementType = constraint.getElementType();
        if (elementType != null) {
            props.put(NAME_ELEMENT_CLASS, Value.of(elementType.getName()));
        }//from ww w .  j  a v  a 2 s  .c  om

        // store element database type name
        String typeName = constraint.getElementTypeName();
        if (typeName != null) {
            props.put(NAME_ELEMENT_TYPE_NAME, Value.of(typeName));
        }

        // store dimension
        props.put(NAME_DIMENSION, Value.of(constraint.getDimension()));

        // store array dimension sizes
        List<Integer> sizes = constraint.getSizes();
        if (sizes != null && !sizes.isEmpty()) {
            ValueList sizeList = new ValueList(Collections2.transform(sizes, new Function<Integer, Value>() {

                @Override
                public Value apply(Integer input) {
                    return Value.of(input);
                }
            }));
            props.put(NAME_SIZES, Value.complex(sizeList));
        }

        return props.toValue();
    } else {
        return null;
    }
}

From source file:org.batoo.jpa.core.impl.criteria.CriteriaUpdateImpl.java

/**
 * {@inheritDoc}//from   w  w w.  j a v a 2s .c o  m
 * 
 */
@Override
public String generateSql() {
    final String update = Joiner.on(",").join(Collections2.transform(this.updates.entrySet(),
            new Function<Entry<AbstractPath<?>, AbstractExpression<?>>, String>() {

                @Override
                public String apply(Entry<AbstractPath<?>, AbstractExpression<?>> input) {
                    return "\t" + input.getKey().getSqlRestrictionFragments(CriteriaUpdateImpl.this)[0] + " = "
                            + input.getValue().getSqlRestrictionFragments(CriteriaUpdateImpl.this)[0];
                }
            }));

    final String sqlRestriction = this.generateSqlRestriction();

    return "UPDATE " + this.getRoot().generateSqlFrom(this) + " SET\n" + update + //
            (StringUtils.isNotBlank(sqlRestriction) ? "\nWHERE " + sqlRestriction : "");
}