Example usage for com.google.common.collect Sets union

List of usage examples for com.google.common.collect Sets union

Introduction

In this page you can find the example usage for com.google.common.collect Sets union.

Prototype

public static <E> SetView<E> union(final Set<? extends E> set1, final Set<? extends E> set2) 

Source Link

Document

Returns an unmodifiable view of the union of two sets.

Usage

From source file:com.opengamma.strata.function.calculation.credit.AbstractCdsFunction.java

@Override
public FunctionRequirements requirements(CdsTrade trade) {
    Cds cds = trade.getProduct();/*  w  w  w .j  av a  2  s  .c  om*/

    Currency notionalCurrency = cds.getFeeLeg().getPeriodicPayments().getNotional().getCurrency();
    Currency feeCurrency = cds.getFeeLeg().getUpfrontFee().getCurrency();

    Set<MarketDataKey<?>> rateCurveKeys = ImmutableSet.of(IsdaYieldCurveInputsKey.of(notionalCurrency),
            IsdaYieldCurveInputsKey.of(feeCurrency));

    Set<Currency> currencies = ImmutableSet.of(notionalCurrency, feeCurrency);
    ReferenceInformation referenceInformation = cds.getReferenceInformation();
    ReferenceInformationType cdsType = referenceInformation.getType();
    // TODO the only real difference between single name and index trades is how the credit curves are keyed and the
    // TODO application of an index factor. We have two switch statements currently to handle this
    // TODO we should be able to handle that a bit more gracefully, but there seems little point in duplicating
    // TODO all of the calculation functions and the entire trade model when the vast majority of behavior is common
    if (cdsType == ReferenceInformationType.SINGLE_NAME) {
        SingleNameReferenceInformation singleNameReferenceInformation = (SingleNameReferenceInformation) referenceInformation;

        Set<MarketDataKey<?>> keys = ImmutableSet.of(
                IsdaSingleNameCreditCurveInputsKey.of(singleNameReferenceInformation),
                IsdaSingleNameRecoveryRateKey.of(singleNameReferenceInformation));

        return FunctionRequirements.builder().singleValueRequirements(Sets.union(rateCurveKeys, keys))
                .outputCurrencies(currencies).build();
    } else if (cdsType == ReferenceInformationType.INDEX) {
        IndexReferenceInformation indexReferenceInformation = (IndexReferenceInformation) referenceInformation;

        Set<MarketDataKey<?>> keys = ImmutableSet.of(
                IsdaIndexCreditCurveInputsKey.of(indexReferenceInformation),
                IsdaIndexRecoveryRateKey.of(indexReferenceInformation));

        return FunctionRequirements.builder().singleValueRequirements(Sets.union(rateCurveKeys, keys))
                .outputCurrencies(currencies).build();
    } else {
        throw new IllegalArgumentException("Unknown ReferenceInformationType " + cdsType);
    }
}

From source file:org.obm.push.backend.FolderSnapshotService.java

public CollectionId createSnapshotAddingFolder(UserDataRequest udr, FolderSyncKey outgoingSyncKey,
        FolderSnapshot knownSnapshot, BackendFolder backendFolder) throws Exception {
    int nextId = knownSnapshot.getNextId();

    CollectionId collectionId = CollectionId.of(nextId++);

    Set<Folder> knownFolders = knownSnapshot.getFolders();

    Set<Folder> newFolders = Sets.union(knownFolders,
            ImmutableSet.of(Folder.from(backendFolder, collectionId)));

    FolderSnapshot snapshot = FolderSnapshot.nextId(nextId).folders(newFolders);
    folderSnapshotDao.create(udr.getUser(), udr.getDevice(), outgoingSyncKey, snapshot);

    return collectionId;
}

From source file:com.kixeye.chassis.transport.websocket.WebSocketMessageMappingRegistry.java

/**
 * Gets all the action methods for action.
 * /* w  w  w  . j a  v  a  2  s  . com*/
 * @param action
 * @return
 */
public Set<WebSocketAction> getActionMethods(String action) {
    return Sets.union((Set<WebSocketAction>) actions.get(action),
            (Set<WebSocketAction>) actions.get(WILDCARD_ACTION));
}

From source file:org.eclipse.sirius.diagram.ui.internal.refresh.diagram.DDiagramCanonicalSynchronizer.java

private void refreshSemantic() {
    if (gmfDiagram != null && gmfDiagram.getElement() != null) {
        final Set<View> createdNodeViews = Sets.newLinkedHashSet();
        createdNodeViews.addAll(refreshSemanticChildren(gmfDiagram, gmfDiagram.getElement()));
        for (final Object object : gmfDiagram.getChildren()) {
            createdNodeViews.addAll(refreshSemantic((View) object));
        }/*from www .jav  a2s. c  o  m*/

        final Set<Edge> createdConnectionViews = Sets.newLinkedHashSet();
        createdConnectionViews.addAll(refreshConnections(gmfDiagram));

        Set<View> createdViews = Sets.union(createdNodeViews, createdConnectionViews);

        manageCreatedViewsLayout(createdViews);

        manageCollapse(createdNodeViews);

        manageRegions();
    }
}

From source file:org.fenixedu.treasury.domain.document.CreditEntry.java

public static Stream<? extends CreditEntry> find(final TreasuryEvent treasuryEvent) {
    return DebitEntry.find(treasuryEvent).map(d -> d.getCreditEntriesSet()).reduce((a, b) -> Sets.union(a, b))
            .orElse(Sets.newHashSet()).stream();
}

From source file:io.bazel.rules.closure.webfiles.WebfilesValidatorProgram.java

private int run(Iterable<String> args) throws IOException {
    Webfiles target = null;/*from   ww  w.  j  av a 2  s .c o m*/
    List<Webfiles> directDeps = new ArrayList<>();
    final List<Path> transitiveDeps = new ArrayList<>();
    Iterator<String> flags = args.iterator();
    Set<String> suppress = new HashSet<>();
    while (flags.hasNext()) {
        String flag = flags.next();
        switch (flag) {
        case "--dummy":
            Files.write(fs.getPath(flags.next()), new byte[0]);
            break;
        case "--target":
            target = loadWebfilesPbtxt(fs.getPath(flags.next()));
            break;
        case "--direct_dep":
            directDeps.add(loadWebfilesPbtxt(fs.getPath(flags.next())));
            break;
        case "--transitive_dep":
            transitiveDeps.add(fs.getPath(flags.next()));
            break;
        case "--suppress":
            suppress.add(flags.next());
            break;
        default:
            throw new RuntimeException("Unexpected flag: " + flag);
        }
    }
    if (target == null) {
        output.println(ERROR_PREFIX + "Missing --target flag");
        return 1;
    }
    Multimap<String, String> errors = validator.validate(target, directDeps,
            Suppliers.memoize(new Supplier<ImmutableList<Webfiles>>() {
                @Override
                public ImmutableList<Webfiles> get() {
                    ImmutableList.Builder<Webfiles> builder = new ImmutableList.Builder<>();
                    for (Path path : transitiveDeps) {
                        try {
                            builder.add(loadWebfilesPbtxt(path));
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    return builder.build();
                }
            }));
    Set<String> superfluous = Sets.difference(suppress, Sets.union(errors.keySet(), NEVER_SUPERFLUOUS));
    if (!superfluous.isEmpty()) {
        errors.put(SUPERFLUOUS_SUPPRESS_ERROR, "Superfluous suppress codes: " + joinWords(superfluous));
    }
    return displayErrors(suppress, errors);
}

From source file:org.onosproject.net.link.impl.LinkManager.java

@Override
public Set<Link> getDeviceLinks(DeviceId deviceId) {
    checkPermission(LINK_READ);//from   w  w  w .  j  a va2 s . c o m
    checkNotNull(deviceId, DEVICE_ID_NULL);
    return Sets.union(store.getDeviceEgressLinks(deviceId), store.getDeviceIngressLinks(deviceId));
}

From source file:com.mmounirou.spotirss.spotify.tracks.XTracks.java

public Set<String> getAllArtists() {
    return Sets.union(m_artists, m_artistsInTrackName);
}

From source file:org.opennms.netmgt.bsm.service.model.graph.internal.GraphAlgorithms.java

public static Set<GraphEdge> calculateImpacting(BusinessServiceGraph graph, GraphVertex parent) {
    // Grab all of the child edges
    List<GraphEdge> childEdges = graph.getOutEdges(parent).stream().collect(Collectors.toList());

    // Generate the power set of all the child edges
    Set<Set<GraphEdge>> powerSet = generatePowerSet(childEdges);

    // Sort the subsets in the power set by size
    List<Set<GraphEdge>> subsetsInAscendingSize = powerSet.stream().sorted((a, b) -> a.size() - b.size())
            .collect(Collectors.toList());

    // Simulate replacing the mapped severity off all the edges
    // in a given subset with the minimal severity.
    // If the resulting  reduced value is less than the current value, we'll deem this
    // particular subset as "impacting".
    // Once we find an impacting subset, only continue the simulation with other
    // subsets of that same size, since any larger subset may contain those
    // edges along with other non-impacting edges.
    List<Set<GraphEdge>> impactingSubsets = Lists.newArrayList();
    for (Set<GraphEdge> subSet : subsetsInAscendingSize) {
        if (impactingSubsets.size() > 0 && subSet.size() > impactingSubsets.iterator().next().size()) {
            // We already found one more more smaller impacting subsets, we're done
            break;
        }//from   w  w w .  java2 s  . com

        // Gather the statuses for all of the child edges
        Map<GraphEdge, Status> edgesWithStatus = childEdges.stream()
                .collect(Collectors.toMap(Function.identity(), e -> e.getStatus()));

        // Now replace the status for the edges in the current subset with minimum severity
        for (GraphEdge edge : subSet) {
            edgesWithStatus.put(edge, DefaultBusinessServiceStateMachine.MIN_SEVERITY);
        }

        // Weigh and reduce the statuses
        List<Status> statuses = DefaultBusinessServiceStateMachine.weighStatuses(edgesWithStatus);
        Status reducedStatus = parent.getReductionFunction().reduce(statuses)
                .orElse(DefaultBusinessServiceStateMachine.MIN_SEVERITY);

        // Did replacing the status of the edges in the current subset affect the status?
        if (reducedStatus.isLessThan(parent.getStatus())) {
            impactingSubsets.add(subSet);
        }
    }

    // Gather the edges in all of the impacting subsets by taking the union of these
    Set<GraphEdge> union = Collections.emptySet();
    for (Set<GraphEdge> impactingSubset : impactingSubsets) {
        union = Sets.union(union, impactingSubset);
    }
    return union;
}

From source file:ezbake.groups.cli.commands.user.GetUserAuthorizations.java

private static Set<Long> getAuthorizations(EzGroupsGraphImpl graph, BaseVertex.VertexType userType,
        String userId, List<String> appFilterChain) throws GroupQueryException, UserNotFoundException {
    Set<Long> auths = Sets.newHashSet();

    // Only get auths if the user exists
    User user;// ww  w .  jav  a  2  s.co  m
    try {
        user = graph.getUser(userType, userId);
        if (!user.isActive()) {
            return auths; // just don't get groups
        }
    } catch (UserNotFoundException | InvalidVertexTypeException e) {
        return auths; // just don't get groups
    }

    // Add the user's own index
    auths.add(user.getIndex());

    // This can sometimes be null
    if (appFilterChain == null) {
        appFilterChain = Collections.emptyList();
    }

    // These are the groups the user has on their own
    Set<Group> userGroups = getUserGroups(graph, userType, userId, false, false);
    logger.debug("Initial user groups: {}", userGroups);

    // These are the groups the apps always include, even if the user doesn't have access
    List<Set<Group>> appsGroups = getAuthorizationsForApps(graph, appFilterChain, false);
    Set<Long> appsFilter = Sets.newHashSet(); // This is the intersection of all app auths
    Set<Long> groupsAppsAlwaysInclude = Sets.newTreeSet(); // This is all the groups the apps include anyways
    for (Set<Group> appGroup : appsGroups) {
        Set<Long> indices = Sets.newTreeSet();
        for (Group group : appGroup) {
            indices.add(group.getIndex());
            if (group.isRequireOnlyApp()) {
                groupsAppsAlwaysInclude.add(group.getIndex());
            }
        }
        appsFilter.retainAll(indices);
    }
    logger.debug("Apps filter: {}", appsFilter);

    if (userType == BaseVertex.VertexType.USER) {
        // Split groups into 2 sets - those that users always have (even if app doesn't) and those that users only have if app has too
        Set<Long> groupsUserHasRegardless = Sets.newHashSet(auths);
        Set<Long> groupsDependingOnApp = Sets.newHashSet();
        for (Group g : userGroups) {
            if (g.isRequireOnlyUser()) {
                groupsUserHasRegardless.add(g.getIndex());
            } else {
                groupsDependingOnApp.add(g.getIndex());
            }
        }

        // Filter the groups that depend on the app
        if (!groupsDependingOnApp.isEmpty()) {
            logger.debug("Groups depending on app: {}", groupsDependingOnApp);
            groupsDependingOnApp = Sets.intersection(groupsDependingOnApp, appsFilter);
        }

        logger.debug("Groups user has regardless: {}", groupsUserHasRegardless);
        // Now union the sets to get the users final list
        auths = Sets.union(groupsUserHasRegardless, groupsDependingOnApp);
    } else if (userType == BaseVertex.VertexType.APP_USER) {
        // What to do here?
        Set<Long> appAuths = Sets.newHashSet(auths);
        for (Group g : userGroups) {
            appAuths.add(g.getIndex());
        }
        auths = appAuths;
    }

    logger.debug("User auths before union: {}", auths);
    return Sets.union(auths, groupsAppsAlwaysInclude);
}