Example usage for com.google.common.collect ImmutableSet contains

List of usage examples for com.google.common.collect ImmutableSet contains

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableSet contains.

Prototype

boolean contains(Object o);

Source Link

Document

Returns true if this set contains the specified element.

Usage

From source file:io.prestosql.testing.LocalQueryRunner.java

private List<Driver> createDrivers(Session session, Plan plan, OutputFactory outputFactory,
        TaskContext taskContext) {//from ww w.ja  v a  2 s.c  o m
    if (printPlan) {
        System.out.println(PlanPrinter.textLogicalPlan(plan.getRoot(), plan.getTypes(),
                metadata.getFunctionRegistry(), plan.getStatsAndCosts(), session, 0, false));
    }

    SubPlan subplan = planFragmenter.createSubPlans(session, plan, true);
    if (!subplan.getChildren().isEmpty()) {
        throw new AssertionError("Expected subplan to have no children");
    }

    LocalExecutionPlanner executionPlanner = new LocalExecutionPlanner(metadata, sqlParser, Optional.empty(),
            pageSourceManager, indexManager, nodePartitioningManager, pageSinkManager, null, expressionCompiler,
            pageFunctionCompiler, joinFilterFunctionCompiler, new IndexJoinLookupStats(),
            this.taskManagerConfig, spillerFactory, singleStreamSpillerFactory, partitioningSpillerFactory,
            blockEncodingManager, new PagesIndex.TestingFactory(false), joinCompiler, new LookupJoinOperators(),
            new OrderingCompiler());

    // plan query
    StageExecutionDescriptor stageExecutionDescriptor = subplan.getFragment().getStageExecutionDescriptor();
    LocalExecutionPlan localExecutionPlan = executionPlanner.plan(taskContext, stageExecutionDescriptor,
            subplan.getFragment().getRoot(), subplan.getFragment().getPartitioningScheme().getOutputLayout(),
            plan.getTypes(), subplan.getFragment().getPartitionedSources(), outputFactory);

    // generate sources
    List<TaskSource> sources = new ArrayList<>();
    long sequenceId = 0;
    for (TableScanNode tableScan : findTableScanNodes(subplan.getFragment().getRoot())) {
        TableLayoutHandle layout = tableScan.getLayout().get();

        SplitSource splitSource = splitManager.getSplits(session, layout,
                stageExecutionDescriptor.isScanGroupedExecution(tableScan.getId()) ? GROUPED_SCHEDULING
                        : UNGROUPED_SCHEDULING);

        ImmutableSet.Builder<ScheduledSplit> scheduledSplits = ImmutableSet.builder();
        while (!splitSource.isFinished()) {
            for (Split split : getNextBatch(splitSource)) {
                scheduledSplits.add(new ScheduledSplit(sequenceId++, tableScan.getId(), split));
            }
        }

        sources.add(new TaskSource(tableScan.getId(), scheduledSplits.build(), true));
    }

    // create drivers
    List<Driver> drivers = new ArrayList<>();
    Map<PlanNodeId, DriverFactory> driverFactoriesBySource = new HashMap<>();
    for (DriverFactory driverFactory : localExecutionPlan.getDriverFactories()) {
        for (int i = 0; i < driverFactory.getDriverInstances().orElse(1); i++) {
            if (driverFactory.getSourceId().isPresent()) {
                checkState(
                        driverFactoriesBySource.put(driverFactory.getSourceId().get(), driverFactory) == null);
            } else {
                DriverContext driverContext = taskContext.addPipelineContext(driverFactory.getPipelineId(),
                        driverFactory.isInputDriver(), driverFactory.isOutputDriver(), false)
                        .addDriverContext();
                Driver driver = driverFactory.createDriver(driverContext);
                drivers.add(driver);
            }
        }
    }

    // add sources to the drivers
    ImmutableSet<PlanNodeId> partitionedSources = ImmutableSet
            .copyOf(subplan.getFragment().getPartitionedSources());
    for (TaskSource source : sources) {
        DriverFactory driverFactory = driverFactoriesBySource.get(source.getPlanNodeId());
        checkState(driverFactory != null);
        boolean partitioned = partitionedSources.contains(driverFactory.getSourceId().get());
        for (ScheduledSplit split : source.getSplits()) {
            DriverContext driverContext = taskContext.addPipelineContext(driverFactory.getPipelineId(),
                    driverFactory.isInputDriver(), driverFactory.isOutputDriver(), partitioned)
                    .addDriverContext();
            Driver driver = driverFactory.createDriver(driverContext);
            driver.updateSource(new TaskSource(split.getPlanNodeId(), ImmutableSet.of(split), true));
            drivers.add(driver);
        }
    }

    for (DriverFactory driverFactory : localExecutionPlan.getDriverFactories()) {
        driverFactory.noMoreDrivers();
    }

    return ImmutableList.copyOf(drivers);
}

From source file:forge.deck.DeckFormat.java

public String getDeckConformanceProblem(Deck deck) {
    if (deck == null) {
        return "is not selected";
    }/*from  ww w . ja  v  a  2 s . c  om*/

    int deckSize = deck.getMain().countAll();

    int min = getMainRange().getMinimum();
    int max = getMainRange().getMaximum();

    // TODO "Your minimum deck size is reduced by five."
    // Adjust minimum base on number of Advantageous Proclamation or similar cards

    if (deckSize < min) {
        return String.format("should have at least %d cards", min);
    }

    if (deckSize > max) {
        return String.format("should have no more than %d cards", max);
    }

    if (hasCommander()) { //Must contain exactly 1 legendary Commander and a sideboard of 10 or zero cards.
        final CardPool cmd = deck.get(DeckSection.Commander);
        if (cmd == null || cmd.isEmpty()) {
            return "is missing a commander";
        }
        if (!isLegalCommander(cmd.get(0).getRules())) {
            return "has an illegal commander";
        }

        final ColorSet cmdCI = cmd.get(0).getRules().getColorIdentity();
        final List<PaperCard> erroneousCI = new ArrayList<PaperCard>();

        for (final Entry<PaperCard, Integer> cp : deck.get(DeckSection.Main)) {
            if (!cp.getKey().getRules().getColorIdentity().hasNoColorsExcept(cmdCI.getColor())) {
                erroneousCI.add(cp.getKey());
            }
        }
        if (deck.has(DeckSection.Sideboard)) {
            for (final Entry<PaperCard, Integer> cp : deck.get(DeckSection.Sideboard)) {
                if (!cp.getKey().getRules().getColorIdentity().hasNoColorsExcept(cmdCI.getColor())) {
                    erroneousCI.add(cp.getKey());
                }
            }
        }

        if (erroneousCI.size() > 0) {
            StringBuilder sb = new StringBuilder(
                    "contains one or more cards that do not match the commanders color identity:");

            for (PaperCard cp : erroneousCI) {
                sb.append("\n").append(cp.getName());
            }

            return sb.toString();
        }
    }

    if (cardPoolFilter != null) {
        final List<PaperCard> erroneousCI = new ArrayList<PaperCard>();
        for (final Entry<PaperCard, Integer> cp : deck.getAllCardsInASinglePool()) {
            if (!cardPoolFilter.apply(cp.getKey().getRules())) {
                erroneousCI.add(cp.getKey());
            }
        }
        if (erroneousCI.size() > 0) {
            final StringBuilder sb = new StringBuilder("contains the following illegal cards:\n");

            for (final PaperCard cp : erroneousCI) {
                sb.append("\n").append(cp.getName());
            }

            return sb.toString();
        }
    }

    final int maxCopies = getMaxCardCopies();
    if (maxCopies < Integer.MAX_VALUE) {
        //Must contain no more than 4 of the same card
        //shared among the main deck and sideboard, except
        //basic lands, Shadowborn Apostle and Relentless Rats

        final CardPool allCards = deck.getAllCardsInASinglePool(hasCommander());
        final ImmutableSet<String> limitExceptions = ImmutableSet.of("Relentless Rats", "Shadowborn Apostle");

        // should group all cards by name, so that different editions of same card are really counted as the same card
        for (final Entry<String, Integer> cp : Aggregates.groupSumBy(allCards, PaperCard.FN_GET_NAME)) {
            final IPaperCard simpleCard = StaticData.instance().getCommonCards().getCard(cp.getKey());
            if (simpleCard == null) {
                return String.format("contains the nonexisting card %s", cp.getKey());
            }

            final boolean canHaveMultiple = simpleCard.getRules().getType().isBasicLand()
                    || limitExceptions.contains(cp.getKey());
            if (!canHaveMultiple && cp.getValue() > maxCopies) {
                return String.format("must not contain more than %d copies of the card %s", maxCopies,
                        cp.getKey());
            }
        }
    }

    // The sideboard must contain either 0 or 15 cards
    int sideboardSize = deck.has(DeckSection.Sideboard) ? deck.get(DeckSection.Sideboard).countAll() : 0;
    Range<Integer> sbRange = getSideRange();
    if (sbRange != null && sideboardSize > 0 && !sbRange.contains(sideboardSize)) {
        return sbRange.getMinimum() == sbRange.getMaximum()
                ? String.format("must have a sideboard of %d cards or no sideboard at all",
                        sbRange.getMaximum())
                : String.format("must have a sideboard of %d to %d cards or no sideboard at all",
                        sbRange.getMinimum(), sbRange.getMaximum());
    }

    return null;
}

From source file:com.facebook.buck.features.haskell.HaskellDescriptionUtils.java

/**
 * Create a Haskell compile rule that compiles all the given haskell sources in one step and pulls
 * interface files from all transitive haskell dependencies.
 *//*from www . ja  va 2 s  .c o  m*/
private static HaskellCompileRule createCompileRule(BuildTarget target, ProjectFilesystem projectFilesystem,
        BuildRuleParams baseParams, ActionGraphBuilder graphBuilder, SourcePathRuleFinder ruleFinder,
        ImmutableSet<BuildRule> deps, HaskellPlatform platform, Linker.LinkableDepType depType,
        boolean hsProfile, Optional<String> main, Optional<HaskellPackageInfo> packageInfo,
        ImmutableList<String> flags, HaskellSources sources) {

    CxxPlatform cxxPlatform = platform.getCxxPlatform();

    Map<BuildTarget, ImmutableList<String>> depFlags = new TreeMap<>();
    Map<BuildTarget, ImmutableList<SourcePath>> depIncludes = new TreeMap<>();
    ImmutableSortedMap.Builder<String, HaskellPackage> exposedPackagesBuilder = ImmutableSortedMap
            .naturalOrder();
    ImmutableSortedMap.Builder<String, HaskellPackage> packagesBuilder = ImmutableSortedMap.naturalOrder();
    new AbstractBreadthFirstTraversal<BuildRule>(deps) {
        private final ImmutableSet<BuildRule> empty = ImmutableSet.of();

        @Override
        public Iterable<BuildRule> visit(BuildRule rule) {
            Iterable<BuildRule> ruleDeps = empty;
            if (rule instanceof HaskellCompileDep) {
                HaskellCompileDep haskellCompileDep = (HaskellCompileDep) rule;
                ruleDeps = haskellCompileDep.getCompileDeps(platform);
                HaskellCompileInput compileInput = haskellCompileDep.getCompileInput(platform, depType,
                        hsProfile);
                depFlags.put(rule.getBuildTarget(), compileInput.getFlags());
                depIncludes.put(rule.getBuildTarget(), compileInput.getIncludes());

                // We add packages from first-order deps as expose modules, and transitively included
                // packages as hidden ones.
                boolean firstOrderDep = deps.contains(rule);
                for (HaskellPackage pkg : compileInput.getPackages()) {
                    if (firstOrderDep) {
                        exposedPackagesBuilder.put(pkg.getInfo().getIdentifier(), pkg);
                    } else {
                        packagesBuilder.put(pkg.getInfo().getIdentifier(), pkg);
                    }
                }
            }
            return ruleDeps;
        }
    }.start();

    Collection<CxxPreprocessorInput> cxxPreprocessorInputs = CxxPreprocessables
            .getTransitiveCxxPreprocessorInput(cxxPlatform, graphBuilder, deps);
    ExplicitCxxToolFlags.Builder toolFlagsBuilder = CxxToolFlags.explicitBuilder();
    PreprocessorFlags.Builder ppFlagsBuilder = PreprocessorFlags.builder();
    toolFlagsBuilder.setPlatformFlags(
            StringArg.from(CxxSourceTypes.getPlatformPreprocessFlags(cxxPlatform, CxxSource.Type.C)));
    for (CxxPreprocessorInput input : cxxPreprocessorInputs) {
        ppFlagsBuilder.addAllIncludes(input.getIncludes());
        ppFlagsBuilder.addAllFrameworkPaths(input.getFrameworks());
        toolFlagsBuilder.addAllRuleFlags(input.getPreprocessorFlags().get(CxxSource.Type.C));
    }
    ppFlagsBuilder.setOtherFlags(toolFlagsBuilder.build());
    PreprocessorFlags ppFlags = ppFlagsBuilder.build();

    ImmutableList<String> compileFlags = ImmutableList.<String>builder().addAll(platform.getCompilerFlags())
            .addAll(flags).addAll(Iterables.concat(depFlags.values())).build();

    ImmutableList<SourcePath> includes = ImmutableList.copyOf(Iterables.concat(depIncludes.values()));

    ImmutableSortedMap<String, HaskellPackage> exposedPackages = exposedPackagesBuilder.build();
    ImmutableSortedMap<String, HaskellPackage> packages = packagesBuilder.build();

    return HaskellCompileRule.from(target, projectFilesystem, baseParams, ruleFinder,
            platform.getCompiler().resolve(graphBuilder), platform.getHaskellVersion(), compileFlags, ppFlags,
            cxxPlatform, depType == Linker.LinkableDepType.STATIC ? PicType.PDC : PicType.PIC, hsProfile, main,
            packageInfo, includes, exposedPackages, packages, sources,
            CxxSourceTypes.getPreprocessor(cxxPlatform, CxxSource.Type.C).resolve(graphBuilder));
}

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

public ImmutableMap<String, NSObject> getMergeableEntitlements() {
    final ImmutableSet<String> excludedKeys = ImmutableSet.of(
            "com.apple.developer.icloud-container-development-container-identifiers",
            "com.apple.developer.icloud-container-environment",
            "com.apple.developer.icloud-container-identifiers", "com.apple.developer.icloud-services",
            "com.apple.developer.restricted-resource-mode",
            "com.apple.developer.ubiquity-container-identifiers",
            "com.apple.developer.ubiquity-kvstore-identifier", "inter-app-audio", "com.apple.developer.homekit",
            "com.apple.developer.healthkit", "com.apple.developer.in-app-payments", "com.apple.developer.maps",
            "com.apple.external-accessory.wireless-configuration");

    ImmutableMap<String, NSObject> allEntitlements = getEntitlements();
    ImmutableMap.Builder<String, NSObject> filteredEntitlementsBuilder = ImmutableMap.builder();
    for (String key : allEntitlements.keySet()) {
        if (!excludedKeys.contains(key)) {
            filteredEntitlementsBuilder.put(key, allEntitlements.get(key));
        }//from   w  ww .j ava2  s . c o m
    }
    return filteredEntitlementsBuilder.build();
}

From source file:com.google.devtools.build.lib.flags.InvocationPolicyEnforcer.java

/**
 * Applies this OptionsPolicyEnforcer's policy to the given OptionsParser.
 *
 * @param parser The OptionsParser to enforce policy on.
 * @param command The current blaze command, for flag policies that apply to only specific
 *     commands. Such policies will be enforced only if they contain this command or a command
 *     they inherit from//from   w  ww  .  jav  a 2s.  co m
 * @throws OptionsParsingException if any flag policy is invalid.
 */
public void enforce(OptionsParser parser, @Nullable String command) throws OptionsParsingException {
    if (invocationPolicy == null || invocationPolicy.getFlagPoliciesCount() == 0) {
        return;
    }

    ImmutableSet<String> commandAndParentCommands = command == null ? ImmutableSet.<String>of()
            : CommandNameCache.CommandNameCacheInstance.INSTANCE.get(command);
    for (FlagPolicy flagPolicy : invocationPolicy.getFlagPoliciesList()) {
        String flagName = flagPolicy.getFlagName();

        // Skip the flag policy if it doesn't apply to this command. If the commands list is empty,
        // then the policy applies to all commands.
        if (!flagPolicy.getCommandsList().isEmpty() && !commandAndParentCommands.isEmpty()) {
            boolean flagApplies = false;
            for (String policyCommand : flagPolicy.getCommandsList()) {
                if (commandAndParentCommands.contains(policyCommand)) {
                    flagApplies = true;
                    break;
                }
            }
            if (!flagApplies) {
                continue;
            }
        }

        OptionValueDescription valueDescription;
        try {
            valueDescription = parser.getOptionValueDescription(flagName);
        } catch (IllegalArgumentException e) {
            // This flag doesn't exist. We are deliberately lenient if the flag policy has a flag
            // we don't know about. This is for better future proofing so that as new flags are added,
            // new policies can use the new flags without worrying about older versions of Bazel.
            log.info(String.format("Flag '%s' specified by invocation policy does not exist", flagName));
            continue;
        }

        OptionDescription optionDescription = parser.getOptionDescription(flagName);
        // getOptionDescription() will return null if the option does not exist, however
        // getOptionValueDescription() above would have thrown an IllegalArgumentException if that
        // were the case.
        Verify.verifyNotNull(optionDescription);

        switch (flagPolicy.getOperationCase()) {
        case SET_VALUE:
            applySetValueOperation(parser, flagPolicy, flagName, valueDescription, optionDescription);
            break;

        case USE_DEFAULT:
            applyUseDefaultOperation(parser, "UseDefault", flagName);
            break;

        case ALLOW_VALUES:
            AllowValues allowValues = flagPolicy.getAllowValues();
            FilterValueOperation.ALLOW_VALUE_OPERATION.apply(parser, allowValues.getAllowedValuesList(),
                    allowValues.hasNewValue() ? allowValues.getNewValue() : null, allowValues.hasUseDefault(),
                    flagName, valueDescription, optionDescription);
            break;

        case DISALLOW_VALUES:
            DisallowValues disallowValues = flagPolicy.getDisallowValues();
            FilterValueOperation.DISALLOW_VALUE_OPERATION.apply(parser,
                    disallowValues.getDisallowedValuesList(),
                    disallowValues.hasNewValue() ? disallowValues.getNewValue() : null,
                    disallowValues.hasUseDefault(), flagName, valueDescription, optionDescription);
            break;

        case OPERATION_NOT_SET:
            throw new OptionsParsingException(
                    String.format("Flag policy for flag '%s' does not " + "have an operation", flagName));

        default:
            log.warning(String.format("Unknown operation '%s' from invocation policy for flag '%s'",
                    flagPolicy.getOperationCase(), flagName));
            break;
        }
    }
}

From source file:com.facebook.buck.features.haskell.HaskellDescriptionUtils.java

/**
 * Create a Haskell link rule that links the given inputs to a executable or shared library and
 * pulls in transitive native linkable deps from the given dep roots.
 *//*from  w w w  .jav  a  2  s.c o m*/
public static HaskellLinkRule createLinkRule(BuildTarget target, ProjectFilesystem projectFilesystem,
        BuildRuleParams baseParams, ActionGraphBuilder graphBuilder, SourcePathRuleFinder ruleFinder,
        HaskellPlatform platform, Linker.LinkType linkType, ImmutableList<Arg> linkerFlags,
        Iterable<Arg> linkerInputs, Iterable<? extends NativeLinkable> deps,
        ImmutableSet<BuildTarget> linkWholeDeps, Linker.LinkableDepType depType, Path outputPath,
        Optional<String> soname, boolean hsProfile) {

    Tool linker = platform.getLinker().resolve(graphBuilder);

    ImmutableList.Builder<Arg> linkerArgsBuilder = ImmutableList.builder();
    ImmutableList.Builder<Arg> argsBuilder = ImmutableList.builder();

    // Add the base flags from the `.buckconfig` first.
    argsBuilder.addAll(StringArg.from(platform.getLinkerFlags()));

    // Pass in the appropriate flags to link a shared library.
    if (linkType.equals(Linker.LinkType.SHARED)) {
        argsBuilder.addAll(StringArg.from("-shared", "-dynamic"));
        soname.ifPresent(
                name -> argsBuilder.addAll(StringArg.from(MoreIterables.zipAndConcat(Iterables.cycle("-optl"),
                        platform.getCxxPlatform().getLd().resolve(graphBuilder).soname(name)))));
    }

    // Add in extra flags passed into this function.
    argsBuilder.addAll(linkerFlags);

    // We pass in the linker inputs and all native linkable deps by prefixing with `-optl` so that
    // the args go straight to the linker, and preserve their order.
    linkerArgsBuilder.addAll(linkerInputs);
    for (NativeLinkable nativeLinkable : NativeLinkables.getNativeLinkables(platform.getCxxPlatform(),
            graphBuilder, deps, depType)) {
        NativeLinkable.Linkage link = nativeLinkable.getPreferredLinkage(platform.getCxxPlatform(),
                graphBuilder);
        NativeLinkableInput input = nativeLinkable.getNativeLinkableInput(platform.getCxxPlatform(),
                NativeLinkables.getLinkStyle(link, depType),
                linkWholeDeps.contains(nativeLinkable.getBuildTarget()), graphBuilder);
        linkerArgsBuilder.addAll(input.getArgs());
    }

    // Since we use `-optl` to pass all linker inputs directly to the linker, the haskell linker
    // will complain about not having any input files.  So, create a dummy archive with an empty
    // module and pass that in normally to work around this.
    BuildTarget emptyModuleTarget = target.withAppendedFlavors(InternalFlavor.of("empty-module"));
    WriteFile emptyModule = graphBuilder
            .addToIndex(new WriteFile(emptyModuleTarget, projectFilesystem, "module Unused where",
                    BuildTargetPaths.getGenPath(projectFilesystem, emptyModuleTarget, "%s/Unused.hs"),
                    /* executable */ false));
    HaskellCompileRule emptyCompiledModule = graphBuilder.addToIndex(createCompileRule(
            target.withAppendedFlavors(InternalFlavor.of("empty-compiled-module")), projectFilesystem,
            baseParams, graphBuilder, ruleFinder,
            // TODO(agallagher): We shouldn't need any deps to compile an empty module, but ghc
            // implicitly tries to load the prelude and in some setups this is provided via a
            // Buck dependency.
            RichStream.from(deps).filter(BuildRule.class).toImmutableSortedSet(Ordering.natural()), platform,
            depType, hsProfile, Optional.empty(), Optional.empty(), ImmutableList.of(),
            HaskellSources.builder().putModuleMap("Unused", emptyModule.getSourcePathToOutput()).build()));
    BuildTarget emptyArchiveTarget = target.withAppendedFlavors(InternalFlavor.of("empty-archive"));
    Archive emptyArchive = graphBuilder.addToIndex(Archive.from(emptyArchiveTarget, projectFilesystem,
            graphBuilder, ruleFinder, platform.getCxxPlatform(),
            BuildTargetPaths.getGenPath(projectFilesystem, emptyArchiveTarget, "%s/libempty.a"),
            emptyCompiledModule.getObjects(), /* cacheable */ true));
    argsBuilder.add(SourcePathArg.of(emptyArchive.getSourcePathToOutput()));

    ImmutableList<Arg> args = argsBuilder.build();
    ImmutableList<Arg> linkerArgs = linkerArgsBuilder.build();

    return graphBuilder.addToIndex(new HaskellLinkRule(target, projectFilesystem, baseParams
            .withDeclaredDeps(ImmutableSortedSet.<BuildRule>naturalOrder()
                    .addAll(BuildableSupport.getDepsCollection(linker, ruleFinder))
                    .addAll(Stream.of(args, linkerArgs).flatMap(Collection::stream)
                            .flatMap(arg -> BuildableSupport.getDeps(arg, ruleFinder)).iterator())
                    .build())
            .withoutExtraDeps(), linker, outputPath, args, linkerArgs, platform.shouldCacheLinks()));
}

From source file:com.google.devtools.build.lib.analysis.DependencyResolver.java

/** Resolves the dependencies for all implicit attributes in this rule. */
private void resolveImplicitAttributes(RuleResolver depResolver) throws InterruptedException {
    // Since the attributes that come from aspects do not appear in attributeMap, we have to get
    // their values from somewhere else. This incidentally means that aspects attributes are not
    // configurable. It would be nice if that wasn't the case, but we'd have to revamp how
    // attribute mapping works, which is a large chunk of work.
    Rule rule = depResolver.rule;/*  w  w w . ja v a2 s  . c  o  m*/
    Label ruleLabel = rule.getLabel();
    ConfiguredAttributeMapper attributeMap = depResolver.attributeMap;
    ImmutableSet<String> mappedAttributes = ImmutableSet.copyOf(attributeMap.getAttributeNames());
    for (AttributeAndOwner attributeAndOwner : depResolver.attributes) {
        Attribute attribute = attributeAndOwner.attribute;
        if (!attribute.isImplicit() || !attribute.getCondition().apply(attributeMap)) {
            continue;
        }

        if (attribute.getType() == BuildType.LABEL) {
            Label label = mappedAttributes.contains(attribute.getName())
                    ? attributeMap.get(attribute.getName(), BuildType.LABEL)
                    : BuildType.LABEL.cast(attribute.getDefaultValue(rule));

            if (label != null) {
                label = ruleLabel.resolveRepositoryRelative(label);
                depResolver.resolveDep(attributeAndOwner, label);
            }
        } else if (attribute.getType() == BuildType.LABEL_LIST) {
            List<Label> labelList;
            if (mappedAttributes.contains(attribute.getName())) {
                labelList = new ArrayList<>();
                for (Label label : attributeMap.get(attribute.getName(), BuildType.LABEL_LIST)) {
                    labelList.add(label);
                }
            } else {
                labelList = BuildType.LABEL_LIST.cast(attribute.getDefaultValue(rule));
            }
            for (Label label : labelList) {
                depResolver.resolveDep(attributeAndOwner, ruleLabel.resolveRepositoryRelative(label));
            }
        }
    }
}

From source file:it.unibz.inf.ontop.owlrefplatform.core.translator.SparqlAlgebraToDatalogTranslator.java

/**
 *
 * @param expr expression/*from  w  w  w.j a v a 2  s.  c o m*/
 * @param variables the set of variables that can occur in the expression
 *                  (the rest will be replaced with NULL)
 * @return term
 */

private Term getExpression(ValueExpr expr, ImmutableSet<Variable> variables) {

    // PrimaryExpression ::= BrackettedExpression | BuiltInCall | iriOrFunction |
    //                          RDFLiteral | NumericLiteral | BooleanLiteral | Var
    // iriOrFunction ::= iri ArgList?

    if (expr instanceof Var) {
        Var v = (Var) expr;
        Variable var = ofac.getVariable(v.getName());
        return variables.contains(var) ? var : OBDAVocabulary.NULL;
    } else if (expr instanceof ValueConstant) {
        Value v = ((ValueConstant) expr).getValue();
        if (v instanceof Literal)
            return getTermForLiteral((Literal) v);
        else if (v instanceof URI)
            return getTermForIri((URI) v, true);

        throw new RuntimeException("The value " + v + " is not supported yet!");
    } else if (expr instanceof Bound) {
        // BOUND (Sec 17.4.1.1)
        // xsd:boolean  BOUND (variable var)
        Var v = ((Bound) expr).getArg();
        Variable var = ofac.getVariable(v.getName());
        return variables.contains(var) ? ofac.getFunctionIsNotNull(var) : ofac.getBooleanConstant(false);
    } else if (expr instanceof UnaryValueOperator) {
        Term term = getExpression(((UnaryValueOperator) expr).getArg(), variables);

        if (expr instanceof Not) {
            return ofac.getFunctionNOT(term);
        } else if (expr instanceof IsLiteral) {
            return ofac.getFunction(ExpressionOperation.IS_LITERAL, term);
        } else if (expr instanceof IsURI) {
            return ofac.getFunction(ExpressionOperation.IS_IRI, term);
        } else if (expr instanceof Str) {
            return ofac.getFunction(ExpressionOperation.SPARQL_STR, term);
        } else if (expr instanceof Datatype) {
            return ofac.getFunction(ExpressionOperation.SPARQL_DATATYPE, term);
        } else if (expr instanceof IsBNode) {
            return ofac.getFunction(ExpressionOperation.IS_BLANK, term);
        } else if (expr instanceof Lang) {
            ValueExpr arg = ((UnaryValueOperator) expr).getArg();
            if (arg instanceof Var)
                return ofac.getFunction(ExpressionOperation.SPARQL_LANG, term);
            else
                throw new RuntimeException("A variable or a value is expected in " + expr);
        }
        // other subclasses
        // IRIFunction: IRI (Sec 17.4.2.8) for constructing IRIs
        // IsNumeric:  isNumeric (Sec 17.4.2.4) for checking whether the argument is a numeric value
        // AggregateOperatorBase: Avg, Min, Max, etc.
        // Like:  ??
        // IsResource: ??
        // LocalName: ??
        // Namespace: ??
        // Label: ??
    } else if (expr instanceof BinaryValueOperator) {
        BinaryValueOperator bexpr = (BinaryValueOperator) expr;
        Term term1 = getExpression(bexpr.getLeftArg(), variables);
        Term term2 = getExpression(bexpr.getRightArg(), variables);

        if (expr instanceof And) {
            return ofac.getFunctionAND(term1, term2);
        } else if (expr instanceof Or) {
            return ofac.getFunctionOR(term1, term2);
        } else if (expr instanceof SameTerm) {
            // sameTerm (Sec 17.4.1.8)
            // ROMAN (28 June 2016): strictly speaking it's not equality
            return ofac.getFunctionEQ(term1, term2);
        } else if (expr instanceof Regex) {
            // REGEX (Sec 17.4.3.14)
            // xsd:boolean  REGEX (string literal text, simple literal pattern)
            // xsd:boolean  REGEX (string literal text, simple literal pattern, simple literal flags)
            Regex reg = (Regex) expr;
            Term term3 = (reg.getFlagsArg() != null) ? getExpression(reg.getFlagsArg(), variables)
                    : OBDAVocabulary.NULL;
            return ofac.getFunction(ExpressionOperation.REGEX, term1, term2, term3);
        } else if (expr instanceof Compare) {
            ExpressionOperation p = RelationalOperations.get(((Compare) expr).getOperator());
            return ofac.getFunction(p, term1, term2);
        } else if (expr instanceof MathExpr) {
            ExpressionOperation p = NumericalOperations.get(((MathExpr) expr).getOperator());
            return ofac.getFunction(p, term1, term2);
        } else if (expr instanceof LangMatches) {
            if (term2 instanceof Function) {
                Function f = (Function) term2;
                if (f.isDataTypeFunction()) {
                    Term functionTerm = f.getTerm(0);
                    if (functionTerm instanceof Constant) {
                        Constant c = (Constant) functionTerm;
                        term2 = ofac.getFunction(f.getFunctionSymbol(),
                                ofac.getConstantLiteral(c.getValue().toLowerCase(), c.getType()));
                    }
                }
            }
            return ofac.getLANGMATCHESFunction(term1, term2);
        }
    } else if (expr instanceof FunctionCall) {
        FunctionCall f = (FunctionCall) expr;

        int arity = f.getArgs().size();
        List<Term> terms = new ArrayList<>(arity);
        for (ValueExpr a : f.getArgs())
            terms.add(getExpression(a, variables));

        OperationPredicate p = XPathFunctions.get(f.getURI());
        if (p != null) {
            if (arity != p.getArity())
                throw new UnsupportedOperationException("Wrong number of arguments (found " + terms.size()
                        + ", only " + p.getArity() + "supported) for SPARQL " + f.getURI() + "function");

            return ofac.getFunction(p, terms);
        }

        // these are all special cases with **variable** number of arguments

        switch (f.getURI()) {
        // CONCAT (Sec 17.4.3.12)
        // string literal  CONCAT(string literal ltrl1 ... string literal ltrln)
        case "http://www.w3.org/2005/xpath-functions#concat":
            if (arity < 1)
                throw new UnsupportedOperationException("Wrong number of arguments (found " + terms.size()
                        + ", at least 1) for SPARQL function CONCAT");

            Term concat = terms.get(0);
            for (int i = 1; i < arity; i++) // .get(i) is OK because it's based on an array
                concat = ofac.getFunction(ExpressionOperation.CONCAT, concat, terms.get(i));
            return concat;

        // REPLACE (Sec 17.4.3.15)
        //string literal  REPLACE (string literal arg, simple literal pattern, simple literal replacement )
        //string literal  REPLACE (string literal arg, simple literal pattern, simple literal replacement,  simple literal flags)
        case "http://www.w3.org/2005/xpath-functions#replace":
            // TODO: the fourth argument is flags (see http://www.w3.org/TR/xpath-functions/#flags)
            Term flags;
            if (arity == 3)
                flags = ofac.getConstantLiteral("");
            else if (arity == 4)
                flags = terms.get(3);
            else
                throw new UnsupportedOperationException("Wrong number of arguments (found " + terms.size()
                        + ", only 3 or 4 supported) for SPARQL function REPLACE");

            return ofac.getFunction(ExpressionOperation.REPLACE, terms.get(0), terms.get(1), terms.get(2),
                    flags);

        // SUBSTR (Sec 17.4.3.3)
        // string literal  SUBSTR(string literal source, xsd:integer startingLoc)
        // string literal  SUBSTR(string literal source, xsd:integer startingLoc, xsd:integer length)
        case "http://www.w3.org/2005/xpath-functions#substring":
            if (arity == 2)
                return ofac.getFunction(ExpressionOperation.SUBSTR2, terms.get(0), terms.get(1));
            else if (arity == 3)
                return ofac.getFunction(ExpressionOperation.SUBSTR3, terms.get(0), terms.get(1), terms.get(2));

            throw new UnsupportedOperationException("Wrong number of arguments (found " + terms.size()
                    + ", only 2 or 3 supported) for SPARQL function SUBSTRING");

        default:
            throw new RuntimeException("Function " + f.getURI() + " is not supported yet!");
        }
    }
    // other subclasses
    // SubQueryValueOperator
    // If
    // BNodeGenerator
    // NAryValueOperator (ListMemberOperator and Coalesce)
    throw new RuntimeException("The expression " + expr + " is not supported yet!");
}

From source file:com.facebook.buck.android.AndroidTransitiveDependencyGraph.java

/**
 * @param uberRDotJava that may have produced {@code R.class} files that need to be dexed.
 *//*  w w w  .  ja v a  2  s.  c  om*/
public AndroidDexTransitiveDependencies findDexDependencies(
        ImmutableList<HasAndroidResourceDeps> androidResourceDeps,
        final ImmutableSet<JavaLibrary> buildRulesToExcludeFromDex, final UberRDotJava uberRDotJava) {
    // These are paths that will be dex'ed. They may be either directories of compiled .class files,
    // or paths to compiled JAR files.
    final ImmutableSet.Builder<Path> pathsToDexBuilder = ImmutableSet.builder();

    // Paths to the classfiles to not dex.
    final ImmutableSet.Builder<Path> noDxPathsBuilder = ImmutableSet.builder();

    // These are paths to third-party jars that may contain resources that must be included in the
    // final APK.
    final ImmutableSet.Builder<Path> pathsToThirdPartyJarsBuilder = ImmutableSet.builder();

    AndroidResourceDetails details = findAndroidResourceDetails(androidResourceDeps);

    // Update pathsToDex.
    final ImmutableSetMultimap<JavaLibrary, Path> classpath = Classpaths
            .getClasspathEntries(rulesToTraverseForTransitiveDeps);
    for (Map.Entry<JavaLibrary, Path> entry : classpath.entries()) {
        if (!buildRulesToExcludeFromDex.contains(entry.getKey())) {
            pathsToDexBuilder.add(entry.getValue());
        } else {
            noDxPathsBuilder.add(entry.getValue());
        }
    }
    // Include the directory of compiled R.java files on the classpath.
    final ImmutableSet<String> rDotJavaPackages = details.rDotJavaPackages;
    if (!rDotJavaPackages.isEmpty()) {
        Path pathToCompiledRDotJavaFiles = uberRDotJava.getPathToCompiledRDotJavaFiles();
        pathsToDexBuilder.add(pathToCompiledRDotJavaFiles);
    }

    ImmutableSet<Path> noDxPaths = noDxPathsBuilder.build();

    // Filter out the classpath entries to exclude from dex'ing, if appropriate
    Set<Path> classpathEntries = Sets.difference(pathsToDexBuilder.build(), noDxPaths);

    Supplier<Map<String, HashCode>> classNamesToHashesSupplier = Suppliers
            .memoize(new Supplier<Map<String, HashCode>>() {
                @Override
                public Map<String, HashCode> get() {
                    ImmutableMap.Builder<String, HashCode> builder = ImmutableMap.builder();
                    for (JavaLibrary javaLibrary : classpath.keySet()) {
                        if (!buildRulesToExcludeFromDex.contains(javaLibrary)) {
                            builder.putAll(javaLibrary.getClassNamesToHashes());
                        }
                    }
                    if (!rDotJavaPackages.isEmpty()) {
                        builder.putAll(uberRDotJava.getClassNamesToHashes());
                    }
                    return builder.build();
                }
            });

    // Visit all of the transitive dependencies to populate the above collections.
    new AbstractDependencyVisitor(rulesToTraverseForTransitiveDeps) {
        @Override
        public ImmutableSet<BuildRule> visit(BuildRule rule) {
            // We need to include the transitive closure of the compiled .class files when dex'ing, as
            // well as the third-party jars that they depend on.
            // Update pathsToThirdPartyJars.
            if (rule.getBuildable() instanceof PrebuiltJar) {
                PrebuiltJar prebuiltJar = (PrebuiltJar) rule.getBuildable();
                pathsToThirdPartyJarsBuilder.add(prebuiltJar.getBinaryJar());
            }
            return maybeVisitAllDeps(rule, rule.getProperties().is(LIBRARY));
        }
    }.start();

    // Classpath entries that should be excluded from dexing should also be excluded from
    // pathsToThirdPartyJars because their resources should not end up in main APK. If they do,
    // the pre-dexed library may try to load a resource from the main APK rather than from within
    // the pre-dexed library (even though the resource is available in both locations). This
    // causes a significant performance regression, as the resource may take more than one second
    // longer to load.
    Set<Path> pathsToThirdPartyJars = Sets.difference(pathsToThirdPartyJarsBuilder.build(), noDxPaths);

    return new AndroidDexTransitiveDependencies(classpathEntries, pathsToThirdPartyJars, noDxPaths,
            classNamesToHashesSupplier);
}

From source file:com.siemens.sw360.portal.portlets.admin.UserPortlet.java

@Override
public void doView(RenderRequest request, RenderResponse response) throws IOException, PortletException {

    List<com.siemens.sw360.datahandler.thrift.users.User> missingUsers = new ArrayList<>();
    List<com.siemens.sw360.datahandler.thrift.users.User> backEndUsers;

    List<User> liferayUsers;
    List<User> liferayUsers2;
    try {/*from w ww. j  a va2  s .  c om*/
        liferayUsers2 = UserLocalServiceUtil.getUsers(QueryUtil.ALL_POS, QueryUtil.ALL_POS);
    } catch (SystemException e) {
        log.error("Could not get user List from liferay", e);
        liferayUsers2 = Collections.emptyList();
    }
    liferayUsers = FluentIterable.from(liferayUsers2).filter(new Predicate<User>() {
        @Override
        public boolean apply(User liferayUser) {

            String firstName = liferayUser.getFirstName();
            String lastName = liferayUser.getLastName();
            String emailAddress = liferayUser.getEmailAddress();
            List<Organization> organizations;
            try {
                organizations = liferayUser.getOrganizations();
            } catch (PortalException | SystemException e) {
                return false;
            }

            String department = "";

            if (organizations != null && organizations.size() > 0) {
                department = organizations.get(0).getName();
            }

            String userGroup = "";

            List<Role> roles;
            try {
                roles = liferayUser.getRoles();
            } catch (SystemException e) {
                return false;
            }
            List<String> roleNames = new ArrayList<>();

            for (Role role : roles) {
                roleNames.add(role.getName());
            }

            for (UserGroup group : UserGroup.values()) {
                String roleConstantFromUserGroup = getRoleConstantFromUserGroup(group);
                if (roleNames.contains(roleConstantFromUserGroup)) {
                    userGroup = group.toString();
                    break;
                }
            }

            String gid = liferayUser.getOpenId();
            String passwordHash = liferayUser.getPassword();

            return !(isNullOrEmpty(firstName) || isNullOrEmpty(lastName) || isNullOrEmpty(emailAddress)
                    || isNullOrEmpty(department) || isNullOrEmpty(userGroup) || isNullOrEmpty(gid)
                    || isNullOrEmpty(passwordHash));
        }
    }).toList();

    try {
        UserService.Iface client = thriftClients.makeUserClient();
        backEndUsers = CommonUtils.nullToEmptyList(client.searchUsers(null));
    } catch (TException e) {
        log.error("Problem with user client", e);
        backEndUsers = Collections.emptyList();
    }

    if (backEndUsers.size() > 0) {

        final ImmutableSet<String> lifeRayMails = FluentIterable.from(liferayUsers)
                .transform(new Function<User, String>() {
                    @Override
                    public String apply(User input) {
                        return input.getEmailAddress();
                    }
                }).toSet();

        missingUsers = FluentIterable.from(backEndUsers)
                .filter(new Predicate<com.siemens.sw360.datahandler.thrift.users.User>() {
                    @Override
                    public boolean apply(com.siemens.sw360.datahandler.thrift.users.User input) {
                        return !lifeRayMails.contains(input.getEmail());
                    }
                }).toList();

    }

    request.setAttribute(PortalConstants.USER_LIST, liferayUsers);
    request.setAttribute(PortalConstants.MISSING_USER_LIST, missingUsers);

    // Proceed with page rendering
    super.doView(request, response);
}