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.rtoth.boilerplate.GetTestMethodsDialog.java

@Nullable
@Override/*w  w  w .  jav a2 s. c  o  m*/
protected JComponent createCenterPanel() {
    // inf rows, 1 column
    // TODO: Lately the cards are showing up squished..
    final JPanel methodSelection = new JPanel(new GridBagLayout());
    final JPanel parameterRuleCards = new JPanel(new CardLayout());
    parameterRuleCards.add(new JLabel("Select a method to configure."), EMPTY_CARD_ID);

    int rowIndex = 0;
    for (Map.Entry<JCheckBox, PsiMethod> methodEntry : availableMethods.entrySet()) {
        final PsiMethod method = methodEntry.getValue();
        final String methodSignature = getPresentableMethodSignature(method);
        final JCheckBox methodCheckBox = methodEntry.getKey();
        final JButton methodConfigureButton = new JButton("->");
        methodConfigureButton.setEnabled(false);

        GridBagConstraints constraints = new GridBagConstraints();
        constraints.gridx = 0;
        constraints.gridy = rowIndex;
        constraints.anchor = GridBagConstraints.LINE_START;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        methodSelection.add(methodCheckBox, constraints);
        constraints.gridx = 1;
        constraints.gridy = rowIndex;
        constraints.anchor = GridBagConstraints.LINE_END;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        methodSelection.add(methodConfigureButton, constraints);

        // TODO: Better layout here.
        JPanel card = new JPanel(new GridLayout(0, 1));
        ImmutableList<ParameterRule> rules = parameterRules.get(method);
        if (!rules.isEmpty()) {
            for (ParameterRule rule : rules) {
                card.add(rule.getUiComponent());
            }
        } else {
            card.add(NO_CONFIGURABLE_PARAMETERS);
        }
        parameterRuleCards.add(card, methodSignature);

        methodCheckBox.addChangeListener(e -> {
            // Enable/disable the parameter configuration button based on whether this method
            // is selected (checked)
            methodConfigureButton.setEnabled(methodCheckBox.isSelected());

            // If this method is now selected, and the card view is empty, show the current method's
            // card.
            if (methodCheckBox.isSelected() && selectedCardId.equals(EMPTY_CARD_ID)) {
                CardLayout cardLayout = (CardLayout) parameterRuleCards.getLayout();
                cardLayout.show(parameterRuleCards, methodSignature);
                selectedCardId = methodSignature;
            }
            // If this method is no longer selected, and this method's card was displayed, make sure
            // we set the card view back to empty
            else if (!methodCheckBox.isSelected() && selectedCardId.equals(methodSignature)) {
                CardLayout cardLayout = (CardLayout) parameterRuleCards.getLayout();
                cardLayout.show(parameterRuleCards, EMPTY_CARD_ID);
                selectedCardId = EMPTY_CARD_ID;
            }
        });

        methodConfigureButton.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
                CardLayout cardLayout = (CardLayout) parameterRuleCards.getLayout();
                cardLayout.show(parameterRuleCards, methodSignature);
                selectedCardId = methodSignature;
            }

            @Override
            public void focusLost(FocusEvent e) {
                // Do nothing
            }
        });
        rowIndex++;
    }

    // TODO: Add "show card" method
    CardLayout cardLayout = (CardLayout) parameterRuleCards.getLayout();
    cardLayout.show(parameterRuleCards, EMPTY_CARD_ID);
    selectedCardId = EMPTY_CARD_ID;

    return new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, methodSelection, parameterRuleCards);
}

From source file:org.gradle.integtests.fixtures.executer.LogContent.java

private LogContent(ImmutableList<String> lines, boolean definitelyNoDebugPrefix, LogContent rawContent) {
    this.lines = lines;
    this.rawContent = rawContent == null ? this : rawContent;
    this.definitelyNoDebugPrefix = definitelyNoDebugPrefix || lines.isEmpty();
}

From source file:io.codis.jodis.RoundRobinJedisPool.java

@Override
public Jedis getResource() {
    ImmutableList<PooledObject> pools = this.pools;
    if (pools.isEmpty()) {
        throw new JedisException("Proxy list empty");
    }// w  w  w  .j a v a2s  . c om
    for (;;) {
        int current = nextIdx.get();
        int next = current >= pools.size() - 1 ? 0 : current + 1;
        if (nextIdx.compareAndSet(current, next)) {
            return pools.get(next).getResource();
        }
    }
}

From source file:com.facebook.buck.core.config.BuckConfig.java

public ImmutableList<BuildTarget> getFullyQualifiedBuildTargets(String section, String key,
        TargetConfiguration targetConfiguration) {
    ImmutableList<String> buildTargets = getListWithoutComments(section, key);
    if (buildTargets.isEmpty()) {
        return ImmutableList.of();
    }//from www.ja va2  s. co  m
    return buildTargets.stream()
            .map(buildTarget -> getBuildTargetForFullyQualifiedTarget(buildTarget, targetConfiguration))
            .collect(ImmutableList.toImmutableList());
}

From source file:com.facebook.buck.go.GoCompile.java

@Override
public ImmutableList<Step> getBuildSteps(BuildContext context, BuildableContext buildableContext) {

    buildableContext.recordArtifact(output);

    ImmutableList.Builder<Path> compileSrcListBuilder = ImmutableList.builder();
    ImmutableList.Builder<Path> headerSrcListBuilder = ImmutableList.builder();
    ImmutableList.Builder<Path> asmSrcListBuilder = ImmutableList.builder();
    for (SourcePath path : srcs) {
        Path srcPath = getResolver().getAbsolutePath(path);
        String extension = MorePaths.getFileExtension(srcPath).toLowerCase();
        if (extension.equals("s")) {
            asmSrcListBuilder.add(srcPath);
        } else if (extension.equals("go")) {
            compileSrcListBuilder.add(srcPath);
        } else {//www . j  a va 2s .  c  o m
            headerSrcListBuilder.add(srcPath);
        }
    }

    ImmutableList<Path> compileSrcs = compileSrcListBuilder.build();
    ImmutableList<Path> headerSrcs = headerSrcListBuilder.build();
    ImmutableList<Path> asmSrcs = asmSrcListBuilder.build();

    ImmutableList.Builder<Step> steps = ImmutableList.builder();
    steps.add(new MkdirStep(getProjectFilesystem(), output.getParent()));

    Optional<Path> asmHeaderPath;

    if (!asmSrcs.isEmpty()) {
        asmHeaderPath = Optional.of(BuildTargets.getScratchPath(getProjectFilesystem(), getBuildTarget(),
                "%s/" + getBuildTarget().getShortName() + "__asm_hdr").resolve("go_asm.h"));

        steps.add(new MkdirStep(getProjectFilesystem(), asmHeaderPath.get().getParent()));
    } else {
        asmHeaderPath = Optional.empty();
    }

    boolean allowExternalReferences = !asmSrcs.isEmpty();

    if (compileSrcs.isEmpty()) {
        steps.add(new TouchStep(getProjectFilesystem(), output));
    } else {
        steps.add(new GoCompileStep(getProjectFilesystem().getRootPath(), compiler.getEnvironment(),
                compiler.getCommandPrefix(getResolver()), compilerFlags, packageName, compileSrcs,
                importPathMap, ImmutableList.of(symlinkTree.getRoot()), asmHeaderPath, allowExternalReferences,
                platform, output));
    }

    if (!asmSrcs.isEmpty()) {
        Path asmIncludeDir = BuildTargets.getScratchPath(getProjectFilesystem(), getBuildTarget(),
                "%s/" + getBuildTarget().getShortName() + "__asm_includes");
        steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), asmIncludeDir));

        if (!headerSrcs.isEmpty()) {
            // TODO(mikekap): Allow header-map style input.
            for (Path header : FluentIterable.from(headerSrcs).append(asmSrcs)) {
                steps.add(new SymlinkFileStep(getProjectFilesystem(), header,
                        asmIncludeDir.resolve(header.getFileName()), /* useAbsolutePaths */ true));
            }
        }

        Path asmOutputDir = BuildTargets.getScratchPath(getProjectFilesystem(), getBuildTarget(),
                "%s/" + getBuildTarget().getShortName() + "__asm_compile");
        steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), asmOutputDir));

        ImmutableList.Builder<Path> asmOutputs = ImmutableList.builder();
        for (Path asmSrc : asmSrcs) {
            Path outputPath = asmOutputDir
                    .resolve(asmSrc.getFileName().toString().replaceAll("\\.[sS]$", ".o"));
            steps.add(new GoAssembleStep(getProjectFilesystem().getRootPath(), assembler.getEnvironment(),
                    assembler.getCommandPrefix(getResolver()), assemblerFlags, asmSrc,
                    ImmutableList.<Path>builder().addAll(assemblerIncludeDirs)
                            .add(asmHeaderPath.get().getParent()).add(asmIncludeDir).build(),
                    platform, outputPath));
            asmOutputs.add(outputPath);
        }

        steps.add(new GoPackStep(getProjectFilesystem().getRootPath(), packer.getEnvironment(),
                packer.getCommandPrefix(getResolver()), GoPackStep.Operation.APPEND, asmOutputs.build(),
                output));
    }

    return steps.build();
}

From source file:com.facebook.buck.versions.QueryTargetTranslator.java

@Override
public Optional<Query> translateTargets(CellPathResolver cellPathResolver, String targetBaseName,
        TargetNodeTranslator translator, Query query) {

    // Extract all build targets from the original query string.
    ImmutableList<BuildTarget> targets;
    try {//  w w  w  . ja va2s. c  om
        targets = QueryUtils.extractBuildTargets(cellPathResolver, targetBaseName, query)
                .collect(ImmutableList.toImmutableList());
    } catch (QueryException e) {
        throw new RuntimeException("Error parsing/executing query from deps", e);
    }

    // If there's no targets, bail early.
    if (targets.isEmpty()) {
        return Optional.empty();
    }

    // A pattern matching all of the build targets in the query string.
    Pattern targetsPattern = Pattern.compile(
            targets.stream().map(Object::toString).map(Pattern::quote).collect(Collectors.joining("|")));

    // Build a new query string from the original by translating all build targets.
    String queryString = query.getQuery();
    Matcher matcher = targetsPattern.matcher(queryString);
    StringBuilder builder = new StringBuilder();
    int lastEnd = 0;
    while (matcher.find()) {
        builder.append(queryString, lastEnd, matcher.start());
        BuildTarget target = unconfiguredBuildTargetFactory
                .createForBaseName(cellPathResolver, targetBaseName, matcher.group())
                .configure(query.getTargetConfiguration());
        Optional<BuildTarget> translated = translator.translate(cellPathResolver, targetBaseName, target);
        builder.append(translated.orElse(target).getFullyQualifiedName());
        lastEnd = matcher.end();
    }
    builder.append(queryString, lastEnd, queryString.length());
    String newQuery = builder.toString();

    return queryString.equals(newQuery) ? Optional.empty()
            : Optional.of(Query.of(newQuery, query.getTargetConfiguration(), query.getBaseName(),
                    query.getResolvedQuery()));
}

From source file:com.facebook.buck.util.ProcessExecutorParams.java

private ProcessExecutorParams(ImmutableList<String> command, Optional<File> directory,
        Optional<Map<String, String>> environment, Optional<ProcessBuilder.Redirect> redirectInput,
        Optional<ProcessBuilder.Redirect> redirectOutput, Optional<ProcessBuilder.Redirect> redirectError) {
    this.command = command;
    Preconditions.checkArgument(!command.isEmpty());
    this.directory = directory;
    this.environment = environment;
    this.redirectInput = redirectInput;
    this.redirectOutput = redirectOutput;
    this.redirectError = redirectError;
}

From source file:com.facebook.buck.core.graph.transformation.executor.impl.ToposortDepsAwareWorker.java

@Override
protected boolean eval(ToposortBasedDepsAwareTask<T> task) throws InterruptedException {
    if (!task.compareAndSetStatus(ToposortBasedDepsAwareTask.TaskStatus.SCHEDULED,
            ToposortBasedDepsAwareTask.TaskStatus.STARTED)) {
        return false;
    }/*from   w w  w. ja  v a2  s  .c om*/

    ImmutableSet<? extends ToposortBasedDepsAwareTask<T>> prereqs;
    try {
        prereqs = task.getPrereqs();
    } catch (Exception e) {
        task.getFuture().completeExceptionally(e);
        return true;
    }

    ImmutableList<ToposortBasedDepsAwareTask<T>> notDoneTasks;
    try {
        notDoneTasks = checkTasksReadyOrReschedule(prereqs);
    } catch (ExecutionException e) {
        completeWithException(task, e.getCause());
        return true;
    }

    if (!notDoneTasks.isEmpty()) {
        notDoneTasks.forEach(depTask -> depTask.registerDependant(task));
        // I1. task becomes NOT_SCHEDULED only when all its deps are registered
        Verify.verify(task.compareAndSetStatus(TaskStatus.STARTED, TaskStatus.NOT_SCHEDULED));

        if (task.numOutStandingDependencies.get() != 0
                || !task.compareAndSetStatus(TaskStatus.NOT_SCHEDULED, TaskStatus.STARTED)) {
            return true;
        }
    }

    ImmutableSet<? extends ToposortBasedDepsAwareTask<T>> deps;
    try {
        deps = task.getDependencies();
    } catch (Exception e) {
        task.getFuture().completeExceptionally(e);
        return true;
    }

    try {
        notDoneTasks = checkTasksReadyOrReschedule(deps);
    } catch (ExecutionException e) {
        completeWithException(task, e.getCause());
        return true;
    }

    if (!notDoneTasks.isEmpty()) {
        notDoneTasks.forEach(depTask -> depTask.registerDependant(task));
        // I1. task becomes NOT_SCHEDULED only when all its deps are registered
        Verify.verify(task.compareAndSetStatus(TaskStatus.STARTED, TaskStatus.NOT_SCHEDULED));

        if (task.numOutStandingDependencies.get() != 0
                || !task.compareAndSetStatus(TaskStatus.NOT_SCHEDULED, TaskStatus.STARTED)) {
            return true;
        }
    }

    task.call();
    ImmutableList<ToposortBasedDepsAwareTask<T>> toReschedule = task.reportCompletionToDependents();

    for (ToposortBasedDepsAwareTask<T> taskToSchedule : toReschedule) {
        if (taskToSchedule.compareAndSetStatus(TaskStatus.NOT_SCHEDULED, TaskStatus.SCHEDULED)) {
            // at this point, we know that all its deps have been registered, which means its
            // numOutStandingDependencies can only decrease (see I1)
            if (taskToSchedule.numOutStandingDependencies.get() != 0) {
                // the task may have been incorrectly returned one of its dependents were not done
                // registering dependents before the completion of this task. Check the task count again
                // and don't reschedule if it still has dependents left.
                Verify.verify(
                        taskToSchedule.compareAndSetStatus(TaskStatus.SCHEDULED, TaskStatus.NOT_SCHEDULED));
                // before setting the taskToSchedule back to NOT_SCHEDULED, its possible that its
                // dependents have been completed, but got blocked from scheduling it due to this task
                // having set its status. Now that its unblocked, we should recheck its
                // numOuStandingDependencies.
                if (taskToSchedule.numOutStandingDependencies.get() != 0) {
                    continue;
                }
                if (!taskToSchedule.compareAndSetStatus(TaskStatus.NOT_SCHEDULED, TaskStatus.SCHEDULED)) {
                    continue;
                }
            }
            sharedQueue.putFirst(taskToSchedule);
        }
    }
    return true;
}

From source file:com.android.build.gradle.internal.transforms.InstantRunTransform.java

protected void wrapUpOutputs(File classes2Folder, File classes3Folder) throws IOException {

    // the transform can set the verifier status to failure in some corner cases, in that
    // case, make sure we delete our classes.3
    if (!transformScope.getInstantRunBuildContext().hasPassedVerification()) {
        FileUtils.cleanOutputDir(classes3Folder);
        return;//from w ww. j a  v a 2 s  .c  o  m
    }
    // otherwise, generate the patch file and add it to the list of files to process next.
    ImmutableList<String> generatedClassNames = generatedClasses3Names.build();
    if (!generatedClassNames.isEmpty()) {
        writePatchFileContents(generatedClassNames, classes3Folder,
                transformScope.getInstantRunBuildContext().getBuildId());
    }
}

From source file:org.apache.james.core.builder.MimeMessageBuilder.java

public MimeMessage build() throws MessagingException {
    Preconditions.checkState(!(text.isPresent() && content.isPresent()),
            "Can not get at the same time a text and a content");
    MimeMessage mimeMessage = new MimeMessage(Session.getInstance(new Properties()));
    if (text.isPresent()) {
        mimeMessage.setContent(text.get(), textContentType.orElse(DEFAULT_TEXT_PLAIN_UTF8_TYPE));
    }//  www. ja va  2 s. co m
    if (content.isPresent()) {
        mimeMessage.setContent(content.get());
    }
    if (sender.isPresent()) {
        mimeMessage.setSender(sender.get());
    }
    if (subject.isPresent()) {
        mimeMessage.setSubject(subject.get());
    }
    ImmutableList<InternetAddress> fromAddresses = from.build();
    if (!fromAddresses.isEmpty()) {
        mimeMessage.addFrom(fromAddresses.toArray(new InternetAddress[fromAddresses.size()]));
    }
    List<InternetAddress> toAddresses = to.build();
    if (!toAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.TO,
                toAddresses.toArray(new InternetAddress[toAddresses.size()]));
    }
    List<InternetAddress> ccAddresses = cc.build();
    if (!ccAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.CC,
                ccAddresses.toArray(new InternetAddress[ccAddresses.size()]));
    }
    List<InternetAddress> bccAddresses = bcc.build();
    if (!bccAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.BCC,
                bccAddresses.toArray(new InternetAddress[bccAddresses.size()]));
    }

    MimeMessage wrappedMessage = MimeMessageWrapper.wrap(mimeMessage);

    List<Header> headerList = headers.build();
    for (Header header : headerList) {
        if (header.name.equals("Message-ID") || header.name.equals("Date")) {
            wrappedMessage.setHeader(header.name, header.value);
        } else {
            wrappedMessage.addHeader(header.name, header.value);
        }
    }
    wrappedMessage.saveChanges();

    return wrappedMessage;
}