Example usage for com.google.common.collect ImmutableList isEmpty

List of usage examples for com.google.common.collect ImmutableList isEmpty

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableList isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this list contains no elements.

Usage

From source file:com.google.devtools.common.options.InvocationPolicyEnforcer.java

/**
 * Expand a single policy. If the policy is not about an expansion flag, this will simply return a
 * list with a single element, oneself. If the policy is for an expansion flag, the policy will
 * get split into multiple policies applying to each flag the original flag expands to.
 *
 * <p>None of the flagPolicies returned should be on expansion flags.
 *//*  w w w .j av  a  2 s .  c om*/
private static List<FlagPolicyWithContext> expandPolicy(FlagPolicyWithContext originalPolicy,
        OptionsParser parser, Level loglevel) throws OptionsParsingException {
    List<FlagPolicyWithContext> expandedPolicies = new ArrayList<>();

    boolean isExpansion = originalPolicy.description.isExpansion();
    ImmutableList<ParsedOptionDescription> subflags = parser.getExpansionValueDescriptions(
            originalPolicy.description.getOptionDefinition(), originalPolicy.origin);

    // If we have nothing to expand to, no need to do any further work.
    if (subflags.isEmpty()) {
        return ImmutableList.of(originalPolicy);
    }

    if (logger.isLoggable(loglevel)) {
        // Log the expansion. This is only really useful for understanding the invocation policy
        // itself.
        List<String> subflagNames = new ArrayList<>(subflags.size());
        for (ParsedOptionDescription subflag : subflags) {
            subflagNames.add("--" + subflag.getOptionDefinition().getOptionName());
        }

        logger.logp(loglevel, "InvocationPolicyEnforcer", "expandPolicy",
                String.format("Expanding %s on option %s to its %s: %s.",
                        originalPolicy.policy.getOperationCase(), originalPolicy.policy.getFlagName(),
                        isExpansion ? "expansions" : "implied flags", Joiner.on("; ").join(subflagNames)));
    }

    // Repeated flags are special, and could set multiple times in an expansion, with the user
    // expecting both values to be valid. Collect these separately.
    Multimap<OptionDescription, ParsedOptionDescription> repeatableSubflagsInSetValues = ArrayListMultimap
            .create();

    // Create a flag policy for the child that looks like the parent's policy "transferred" to its
    // child. Note that this only makes sense for SetValue, when setting an expansion flag, or
    // UseDefault, when preventing it from being set.
    for (ParsedOptionDescription currentSubflag : subflags) {
        OptionDescription subflagOptionDescription = parser
                .getOptionDescription(currentSubflag.getOptionDefinition().getOptionName());

        if (currentSubflag.getOptionDefinition().allowsMultiple()
                && originalPolicy.policy.getOperationCase().equals(OperationCase.SET_VALUE)) {
            repeatableSubflagsInSetValues.put(subflagOptionDescription, currentSubflag);
        } else {
            FlagPolicyWithContext subflagAsPolicy = getSingleValueSubflagAsPolicy(subflagOptionDescription,
                    currentSubflag, originalPolicy, isExpansion);
            // In case any of the expanded flags are themselves expansions, recurse.
            expandedPolicies.addAll(expandPolicy(subflagAsPolicy, parser, loglevel));
        }
    }

    // If there are any repeatable flag SetValues, deal with them together now.
    // Note that expansion flags have no value, and so cannot have multiple values either.
    // Skipping the recursion above is fine.
    for (OptionDescription repeatableFlag : repeatableSubflagsInSetValues.keySet()) {
        int numValues = repeatableSubflagsInSetValues.get(repeatableFlag).size();
        ArrayList<String> newValues = new ArrayList<>(numValues);
        ArrayList<OptionInstanceOrigin> origins = new ArrayList<>(numValues);
        for (ParsedOptionDescription setValue : repeatableSubflagsInSetValues.get(repeatableFlag)) {
            newValues.add(setValue.getUnconvertedValue());
            origins.add(setValue.getOrigin());
        }
        // These options come from expanding a single policy, so they have effectively the same
        // priority. They could have come from different expansions or implicit requirements in the
        // recursive resolving of the option list, so just pick the first one. Do collapse the source
        // strings though, in case there are different sources.
        OptionInstanceOrigin arbitraryFirstOptionOrigin = origins.get(0);
        OptionInstanceOrigin originOfSubflags = new OptionInstanceOrigin(
                arbitraryFirstOptionOrigin.getPriority(),
                origins.stream().map(OptionInstanceOrigin::getSource).distinct()
                        .collect(Collectors.joining(", ")),
                arbitraryFirstOptionOrigin.getImplicitDependent(),
                arbitraryFirstOptionOrigin.getExpandedFrom());
        expandedPolicies
                .add(getSetValueSubflagAsPolicy(repeatableFlag, newValues, originOfSubflags, originalPolicy));
    }

    // Don't add the original policy if it was an expansion flag, which have no value, but do add
    // it if there was either no expansion or if it was a valued flag with implicit requirements.
    if (!isExpansion) {
        expandedPolicies.add(originalPolicy);
    }

    return expandedPolicies;
}

From source file:com.google.devtools.build.lib.rules.java.ProguardHelper.java

/**
 * Creates an action to run Proguard over the given {@code programJar} with various other given
 * inputs to produce {@code proguardOutputJar}.  If requested explicitly, or implicitly with
 * --java_optimization_mode, the action also produces a mapping file (which shows what methods and
 * classes in the output Jar correspond to which methods and classes in the input).  The "pair"
 * returned by this method indicates whether a mapping is being produced.
 *
 * <p>See the Proguard manual for the meaning of the various artifacts in play.
 *
 * @param proguard Proguard executable to use
 * @param proguardSpecs Proguard specification files to pass to Proguard
 * @param proguardMapping optional mapping file for Proguard to apply
 * @param libraryJars any other Jar files that the {@code programJar} will run against
 * @param mappingRequested whether to ask Proguard to output a mapping file (a mapping will be
 *        produced anyway if --java_optimization_mode includes obfuscation)
 * @param optimizationPasses if not null specifies to break proguard up into multiple passes with
 *        the given number of optimization passes.
 *//*from  ww w.  j  a v  a  2  s. co m*/
public static ProguardOutput createProguardAction(RuleContext ruleContext, FilesToRunProvider proguard,
        Artifact programJar, ImmutableList<Artifact> proguardSpecs, @Nullable Artifact proguardSeeds,
        @Nullable Artifact proguardUsage, @Nullable Artifact proguardMapping, Iterable<Artifact> libraryJars,
        Artifact proguardOutputJar, JavaSemantics semantics, @Nullable Integer optimizationPasses)
        throws InterruptedException {
    JavaOptimizationMode optMode = getJavaOptimizationMode(ruleContext);
    Preconditions.checkArgument(optMode != JavaOptimizationMode.NOOP);
    Preconditions.checkArgument(optMode != JavaOptimizationMode.LEGACY || !proguardSpecs.isEmpty());

    ProguardOutput output = getProguardOutputs(proguardOutputJar, proguardSeeds, proguardUsage, ruleContext,
            semantics);

    if (optimizationPasses == null) {
        // Run proguard as a single step.
        Builder builder = makeBuilder(proguard, programJar, proguardSpecs, proguardMapping, libraryJars,
                output.getOutputJar(), output.getMapping(), output.getProtoMapping(), output.getSeeds(),
                output.getUsage(), output.getConstantStringObfuscatedMapping(), output.getConfig())
                        .setProgressMessage("Trimming binary with Proguard").addOutput(proguardOutputJar);

        ruleContext.registerAction(builder.build(ruleContext));
    } else {
        // Optimization passes have been specified, so run proguard in multiple phases.
        Artifact lastStageOutput = getProguardTempArtifact(ruleContext, optMode.name().toLowerCase(),
                "proguard_preoptimization.jar");
        ruleContext.registerAction(makeBuilder(proguard, programJar, proguardSpecs, proguardMapping,
                libraryJars, output.getOutputJar(), /* proguardOutputMap */ null,
                /* proguardOutputProtoMap */ null, output.getSeeds(), // ProGuard only prints seeds during INITIAL and NORMAL runtypes.
                /* proguardUsage */ null, /* constantStringObfuscatedMapping */ null,
                /* proguardConfigOutput */ null)
                        .setProgressMessage("Trimming binary with Proguard: Verification/Shrinking Pass")
                        .addArgument("-runtype INITIAL").addArgument("-nextstageoutput")
                        .addOutputArgument(lastStageOutput).build(ruleContext));

        for (int i = 0; i < optimizationPasses; i++) {
            Artifact optimizationOutput = getProguardTempArtifact(ruleContext, optMode.name().toLowerCase(),
                    "proguard_optimization_" + (i + 1) + ".jar");
            ruleContext.registerAction(makeBuilder(proguard, programJar, proguardSpecs, proguardMapping,
                    libraryJars, output.getOutputJar(), /* proguardOutputMap */ null,
                    /* proguardOutputProtoMap */ null, /* proguardSeeds */ null, /* proguardUsage */ null,
                    /* constantStringObfuscatedMapping */ null, /* proguardConfigOutput */ null)
                            .setProgressMessage("Trimming binary with Proguard: Optimization Pass " + (i + 1))
                            .addArgument("-runtype OPTIMIZATION").addArgument("-laststageoutput")
                            .addInputArgument(lastStageOutput).addArgument("-nextstageoutput")
                            .addOutputArgument(optimizationOutput).build(ruleContext));
            lastStageOutput = optimizationOutput;
        }

        Builder builder = makeBuilder(proguard, programJar, proguardSpecs, proguardMapping, libraryJars,
                output.getOutputJar(), output.getMapping(), output.getProtoMapping(), /* proguardSeeds */ null, // runtype FINAL does not produce seeds.
                output.getUsage(), output.getConstantStringObfuscatedMapping(), output.getConfig())
                        .setProgressMessage("Trimming binary with Proguard: Obfuscation and Final Output Pass")
                        .addArgument("-runtype FINAL").addArgument("-laststageoutput")
                        .addInputArgument(lastStageOutput).addOutput(proguardOutputJar);

        ruleContext.registerAction(builder.build(ruleContext));
    }

    return output;
}

From source file:com.tinspx.util.net.Requests.java

/**
 * Combines the supplied redirect handlers. The first handler to indicate
 * a redirect is necessary will be used to apply the redirect. Only one
 * of the handlers will be used for any given redirect.
 *///from w  w w.j  av  a2s  .c o m
public static RedirectHandler chain(Iterable<? extends RedirectHandler> handlers) {
    final ImmutableList<RedirectHandler> redirectHandlers = ImmutableList
            .copyOf(CollectUtils.checkAllNotNull(handlers));
    checkArgument(!redirectHandlers.isEmpty(), "no handler provided");
    return new RedirectHandler() {
        @Override
        public boolean shouldRedirect(Response response) {
            if (response == null) {
                return false;
            }
            for (RedirectHandler handler : redirectHandlers) {
                if (handler.shouldRedirect(response)) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public Request apply(Request request) {
            if (request == null) {
                return null;
            }
            final Response cause = request.cause().get();
            for (RedirectHandler handler : redirectHandlers) {
                if (handler.shouldRedirect(cause)) {
                    return handler.apply(request);
                }
            }
            return null;
        }
    };
}

From source file:com.liveramp.megadesk.recipes.queue.Queue.java

@Override
protected VALUE internalRead(ImmutableList<VALUE> transfer) {
    if (transfer.isEmpty()) {
        return null;
    } else {//from   w  ww  . java  2 s  . c  o m
        return transfer.get(0);
    }
}

From source file:com.google.template.soy.jbcsrc.restricted.BytecodeUtils.java

private static Expression doShortCircuitingLogicalOperator(
        final ImmutableList<? extends Expression> expressions, final boolean isOrOperator) {
    checkArgument(!expressions.isEmpty());
    for (Expression expr : expressions) {
        expr.checkAssignableTo(Type.BOOLEAN_TYPE);
    }//  ww  w. j a  va  2s.c o  m
    if (expressions.size() == 1) {
        return expressions.get(0);
    }

    return new Expression(Type.BOOLEAN_TYPE,
            Expression.areAllCheap(expressions) ? Features.of(Feature.CHEAP) : Features.of()) {
        @Override
        protected void doGen(CodeBuilder adapter) {
            Label end = new Label();
            Label shortCircuit = new Label();
            for (int i = 0; i < expressions.size(); i++) {
                Expression expr = expressions.get(i);
                expr.gen(adapter);
                if (i == expressions.size() - 1) {
                    // if we are the last one, just goto end. Whatever the result of the last expression is
                    // determines the result of the whole expression (when all prior tests fail).
                    adapter.goTo(end);
                } else {
                    adapter.ifZCmp(isOrOperator ? Opcodes.IFNE : Opcodes.IFEQ, shortCircuit);
                }
            }
            adapter.mark(shortCircuit);
            adapter.pushBoolean(isOrOperator); // default for || is true && is false
            adapter.mark(end);
        }
    };
}

From source file:org.eclipse.milo.opcua.sdk.client.session.SessionFsmFactory.java

@SuppressWarnings("Duplicates")
private static CompletableFuture<Unit> transferSubscriptions(FsmContext<State, Event> ctx, OpcUaClient client,
        OpcUaSession session) {//w ww .j a va  2  s .c  om

    UaStackClient stackClient = client.getStackClient();
    OpcUaSubscriptionManager subscriptionManager = client.getSubscriptionManager();
    ImmutableList<UaSubscription> subscriptions = subscriptionManager.getSubscriptions();

    if (subscriptions.isEmpty()) {
        return completedFuture(Unit.VALUE);
    }

    CompletableFuture<Unit> transferFuture = new CompletableFuture<>();

    UInteger[] subscriptionIdsArray = subscriptions.stream().map(UaSubscription::getSubscriptionId)
            .toArray(UInteger[]::new);

    TransferSubscriptionsRequest request = new TransferSubscriptionsRequest(
            client.newRequestHeader(session.getAuthenticationToken()), subscriptionIdsArray, true);

    LOGGER.debug("[{}] Sending TransferSubscriptionsRequest...", ctx.getInstanceId());

    stackClient.sendRequest(request).thenApply(TransferSubscriptionsResponse.class::cast)
            .whenComplete((tsr, ex) -> {
                if (tsr != null) {
                    List<TransferResult> results = l(tsr.getResults());

                    LOGGER.debug("[{}] TransferSubscriptions supported: {}", ctx.getInstanceId(),
                            tsr.getResponseHeader().getServiceResult());

                    if (LOGGER.isDebugEnabled()) {
                        try {
                            Stream<UInteger> subscriptionIds = subscriptions.stream()
                                    .map(UaSubscription::getSubscriptionId);
                            Stream<StatusCode> statusCodes = results.stream()
                                    .map(TransferResult::getStatusCode);

                            //noinspection UnstableApiUsage
                            String[] ss = Streams
                                    .zip(subscriptionIds, statusCodes,
                                            (i, s) -> String
                                                    .format("id=%s/%s", i,
                                                            StatusCodes.lookup(s.getValue()).map(sa -> sa[0])
                                                                    .orElse(s.toString())))
                                    .toArray(String[]::new);

                            LOGGER.debug("[{}] TransferSubscriptions results: {}", ctx.getInstanceId(),
                                    Arrays.toString(ss));
                        } catch (Throwable t) {
                            LOGGER.error("[{}] error logging TransferSubscription results", ctx.getInstanceId(),
                                    t);
                        }
                    }

                    client.getConfig().getExecutor().execute(() -> {
                        for (int i = 0; i < results.size(); i++) {
                            TransferResult result = results.get(i);

                            if (!result.getStatusCode().isGood()) {
                                UaSubscription subscription = subscriptions.get(i);

                                subscriptionManager.transferFailed(subscription.getSubscriptionId(),
                                        result.getStatusCode());
                            }
                        }
                    });

                    transferFuture.complete(Unit.VALUE);
                } else {
                    StatusCode statusCode = UaException.extract(ex).map(UaException::getStatusCode)
                            .orElse(StatusCode.BAD);

                    // Bad_ServiceUnsupported is the correct response when transfers aren't supported but
                    // server implementations tend to interpret the spec in their own unique way...
                    if (statusCode.getValue() == StatusCodes.Bad_NotImplemented
                            || statusCode.getValue() == StatusCodes.Bad_NotSupported
                            || statusCode.getValue() == StatusCodes.Bad_OutOfService
                            || statusCode.getValue() == StatusCodes.Bad_ServiceUnsupported) {

                        LOGGER.debug("[{}] TransferSubscriptions not supported: {}", ctx.getInstanceId(),
                                statusCode);

                        client.getConfig().getExecutor().execute(() -> {
                            // transferFailed() will remove the subscription, but that is okay
                            // because the list from getSubscriptions() above is a copy.
                            for (UaSubscription subscription : subscriptions) {
                                subscriptionManager.transferFailed(subscription.getSubscriptionId(),
                                        statusCode);
                            }
                        });

                        transferFuture.complete(Unit.VALUE);
                    } else {
                        transferFuture.completeExceptionally(ex);
                    }
                }
            });

    return transferFuture;
}

From source file:com.liveramp.megadesk.recipes.queue.PopOne.java

@Override
public Void run(Context context) throws Exception {
    ImmutableList<VALUE> list = context.read(this.list);
    if (!list.isEmpty()) {
        ImmutableList<VALUE> newList = list.subList(1, list.size());
        context.write(this.list, newList);
    }/*from  w w w.j  a  v a 2 s .  c o  m*/
    if (context.read(this.list).isEmpty()) {
        context.write(this.frozen, false);
    }
    return null;
}

From source file:org.apache.james.backends.es.ClientProviderImpl.java

private ClientProviderImpl(ImmutableList<Host> hosts) {
    Preconditions.checkArgument(!hosts.isEmpty(), "You should provide at least one host");
    this.hosts = hosts;
}

From source file:com.facebook.buck.rules.coercer.ZeroArgMacroTypeCoercer.java

@Override
public M coerce(CellPathResolver cellRoots, ProjectFilesystem filesystem, Path pathRelativeToProjectRoot,
        TargetConfiguration targetConfiguration, ImmutableList<String> args) throws CoerceFailedException {
    if (!args.isEmpty()) {
        throw new CoerceFailedException(String.format("expected zero arguments (found %d)", args.size()));
    }/*  w w  w. jav a 2  s .  co m*/
    return val;
}

From source file:org.jclouds.cloudsigma2.compute.functions.TemplateOptionsToStatementWithoutPublicKey.java

@Override
public Statement apply(TemplateOptions options) {
    ImmutableList.Builder<Statement> builder = ImmutableList.builder();
    if (options.getRunScript() != null) {
        builder.add(options.getRunScript());
    }/*from   w ww  .ja  v  a  2s.co m*/
    if (options.getPrivateKey() != null) {
        builder.add(new InstallRSAPrivateKey(options.getPrivateKey()));
    }

    ImmutableList<Statement> bootstrap = builder.build();
    if (bootstrap.isEmpty()) {
        return null;
    }

    if (options.getTaskName() == null && !(options.getRunScript() instanceof InitScript)) {
        options.nameTask("bootstrap");
    }
    return bootstrap.size() == 1 ? bootstrap.get(0) : new StatementList(bootstrap);
}