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:org.apache.hadoop.hdfs.server.namenode.JournalSet.java

/**
 * Return a manifest of what finalized edit logs are available. All available
 * edit logs are returned starting from the transaction id passed. If
 * 'fromTxId' falls in the middle of a log, that log is returned as well.
 * //from ww w. j  av  a  2  s.com
 * @param fromTxId Starting transaction id to read the logs.
 * @return RemoteEditLogManifest object.
 */
public synchronized RemoteEditLogManifest getEditLogManifest(long fromTxId) {
    // Collect RemoteEditLogs available from each FileJournalManager
    List<RemoteEditLog> allLogs = Lists.newArrayList();
    for (JournalAndStream j : journals) {
        if (j.getManager() instanceof FileJournalManager) {
            FileJournalManager fjm = (FileJournalManager) j.getManager();
            try {
                allLogs.addAll(fjm.getRemoteEditLogs(fromTxId, false));
            } catch (Throwable t) {
                LOG.warn("Cannot list edit logs in " + fjm, t);
            }
        }
    }

    // Group logs by their starting txid
    ImmutableListMultimap<Long, RemoteEditLog> logsByStartTxId = Multimaps.index(allLogs,
            RemoteEditLog.GET_START_TXID);
    long curStartTxId = fromTxId;

    List<RemoteEditLog> logs = Lists.newArrayList();
    while (true) {
        ImmutableList<RemoteEditLog> logGroup = logsByStartTxId.get(curStartTxId);
        if (logGroup.isEmpty()) {
            // we have a gap in logs - for example because we recovered some old
            // storage directory with ancient logs. Clear out any logs we've
            // accumulated so far, and then skip to the next segment of logs
            // after the gap.
            SortedSet<Long> startTxIds = Sets.newTreeSet(logsByStartTxId.keySet());
            startTxIds = startTxIds.tailSet(curStartTxId);
            if (startTxIds.isEmpty()) {
                break;
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found gap in logs at " + curStartTxId + ": "
                            + "not returning previous logs in manifest.");
                }
                logs.clear();
                curStartTxId = startTxIds.first();
                continue;
            }
        }

        // Find the one that extends the farthest forward
        RemoteEditLog bestLog = Collections.max(logGroup);
        logs.add(bestLog);
        // And then start looking from after that point
        curStartTxId = bestLog.getEndTxId() + 1;
    }
    RemoteEditLogManifest ret = new RemoteEditLogManifest(logs);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Generated manifest for logs since " + fromTxId + ":" + ret);
    }
    return ret;
}

From source file:com.facebook.buck.artifact_cache.AbstractAsynchronousCache.java

@Override
public final ListenableFuture<Void> store(ImmutableList<Pair<ArtifactInfo, BorrowablePath>> artifacts) {
    if (!getCacheReadMode().isWritable()) {
        return Futures.immediateFuture(null);
    }/*from ww  w . ja  v  a2 s . c  om*/

    ImmutableList.Builder<Pair<ArtifactInfo, Path>> matchedArtifactsBuilder = ImmutableList
            .builderWithExpectedSize(artifacts.size());
    ImmutableList.Builder<Long> artifactSizesInBytesBuilder = ImmutableList
            .builderWithExpectedSize(artifacts.size());

    for (int i = 0; i < artifacts.size(); i++) {
        BorrowablePath output = artifacts.get(i).getSecond();
        ArtifactInfo info = artifacts.get(i).getFirst();
        long artifactSizeBytes = getFileSize(output.getPath());
        if (artifactExceedsMaximumSize(artifactSizeBytes)) {
            LOG.info("Artifact too big so not storing it in the %s cache. file=[%s] buildTarget=[%s]", name,
                    output.getPath(), info.getBuildTarget());
            continue;
        }

        Path tmp;
        try {
            tmp = getPathForArtifact(output);
        } catch (IOException e) {
            LOG.error(e, "Failed to store artifact in temp file: " + output.getPath());
            continue;
        }

        matchedArtifactsBuilder.add(new Pair<>(info, tmp));
        artifactSizesInBytesBuilder.add(artifactSizeBytes);
    }

    ImmutableList<Pair<ArtifactInfo, Path>> matchedArtifacts = matchedArtifactsBuilder.build();

    if (matchedArtifacts.isEmpty()) {
        return Futures.immediateFuture(null);
    }

    ImmutableList<Long> artifactSizesInBytes = artifactSizesInBytesBuilder.build();

    ImmutableList.Builder<StoreEvents> eventsBuilder = ImmutableList
            .builderWithExpectedSize(artifactSizesInBytes.size());
    for (int i = 0; i < artifactSizesInBytes.size(); i++) {
        eventsBuilder.add(
                eventListener.storeScheduled(matchedArtifacts.get(i).getFirst(), artifactSizesInBytes.get(i)));
    }

    ImmutableList<StoreEvents> events = eventsBuilder.build();

    return storeExecutorService.submit(() -> {
        for (int i = 0; i < matchedArtifacts.size(); i++) {
            StoreEvents.StoreRequestEvents requestEvents = events.get(i).started();
            try {
                StoreResult result = storeImpl(matchedArtifacts.get(i).getFirst(),
                        matchedArtifacts.get(i).getSecond());
                requestEvents.finished(result);
            } catch (IOException e) {
                String msg = String.format("store(%s): %s: %s",
                        matchedArtifacts.get(i).getFirst().getRuleKeys(), e.getClass().getName(),
                        e.getMessage());
                requestEvents.failed(e, msg);
                throw new RuntimeException(e);
            }
        }

        return null;
    });
}

From source file:com.facebook.buck.features.apple.project.NewNativeTargetProjectMutator.java

private void addSourcePathToSourcesBuildPhase(SourceWithFlags sourceWithFlags, PBXGroup sourcesGroup,
        PBXSourcesBuildPhase sourcesBuildPhase) {
    SourceTreePath sourceTreePath = new SourceTreePath(PBXReference.SourceTree.SOURCE_ROOT,
            pathRelativizer.outputDirToRootRelative(sourcePathResolver.apply(sourceWithFlags.getSourcePath())),
            Optional.empty());/* w w  w .  j  a  v  a  2s.co m*/
    PBXFileReference fileReference = sourcesGroup.getOrCreateFileReferenceBySourceTreePath(sourceTreePath);
    PBXBuildFile buildFile = new PBXBuildFile(fileReference);
    sourcesBuildPhase.getFiles().add(buildFile);

    ImmutableList<String> customLangPreprocessorFlags = ImmutableList.of();
    Optional<CxxSource.Type> sourceType = CxxSource.Type
            .fromExtension(Files.getFileExtension(sourceTreePath.toString()));
    if (sourceType.isPresent() && langPreprocessorFlags.containsKey(sourceType.get())) {
        customLangPreprocessorFlags = langPreprocessorFlags.get(sourceType.get());
    }

    ImmutableList<String> customFlags = ImmutableList
            .copyOf(Iterables.concat(customLangPreprocessorFlags, sourceWithFlags.getFlags()));
    if (!customFlags.isEmpty()) {
        NSDictionary settings = new NSDictionary();
        settings.put("COMPILER_FLAGS", Joiner.on(' ').join(customFlags));
        buildFile.setSettings(Optional.of(settings));
    }
    LOG.verbose("Added source path %s to group %s, flags %s, PBXFileReference %s", sourceWithFlags,
            sourcesGroup.getName(), customFlags, fileReference);
}

From source file:com.spectralogic.dsbrowser.gui.components.localfiletreetable.LocalFileTreeTablePresenter.java

private ImmutableList<kotlin.Pair<String, Path>> getLocalFilesToPut() {
    final ObservableList<TreeItem<FileTreeModel>> currentLocalSelection = treeTable.getSelectionModel()
            .getSelectedItems();// w  ww  .  j a  va  2s.  co m
    final ImmutableList<kotlin.Pair<String, Path>> files = currentLocalSelection.stream()
            .filter(Objects::nonNull).map(TreeItem::getValue).filter(Objects::nonNull)
            .map(i -> new kotlin.Pair<>(i.getName(), i.getPath())).collect(GuavaCollectors.immutableList());
    if (files.isEmpty()) {
        ds3Common.getDs3TreeTableView().refresh();
        return null;
    }
    return files;
}

From source file:org.geogit.storage.Neo4JGraphDatabase.java

/**
 * Adds a commit to the database with the given parents. If a commit with the same id already
 * exists, it will not be inserted.//from   w w w  . ja v a 2s.  co  m
 * 
 * @param commitId the commit id to insert
 * @param parentIds the commit ids of the commit's parents
 * @return true if the commit id was inserted, false otherwise
 */
@Override
public boolean put(ObjectId commitId, ImmutableList<ObjectId> parentIds) {
    Transaction tx = graphDB.beginTx();

    Node commitNode = null;
    try {
        // See if it already exists
        commitNode = getOrAddNode(commitId);

        if (parentIds.isEmpty()) {
            if (!commitNode.getRelationships(Direction.OUTGOING, CommitRelationshipTypes.TOROOT).iterator()
                    .hasNext()) {
                // Attach this node to the root node
                commitNode.createRelationshipTo(graphDB.getNodeById(0), CommitRelationshipTypes.TOROOT);
            }
        }

        if (!commitNode.getRelationships(Direction.OUTGOING, CommitRelationshipTypes.PARENT).iterator()
                .hasNext()) {
            // Don't make relationships if they have been created already
            for (ObjectId parent : parentIds) {
                Node parentNode = getOrAddNode(parent);
                commitNode.createRelationshipTo(parentNode, CommitRelationshipTypes.PARENT);
            }
        }

        tx.success();
    } catch (Exception e) {
        tx.failure();
        throw Throwables.propagate(e);
    } finally {
        tx.finish();
    }

    return true;
}

From source file:com.facebook.buck.jvm.java.JavacToJarStepFactory.java

@Override
public void createCompileToJarStep(BuildContext context, ImmutableSortedSet<Path> sourceFilePaths,
        BuildTarget invokingRule, SourcePathResolver resolver, SourcePathRuleFinder ruleFinder,
        ProjectFilesystem filesystem, ImmutableSortedSet<Path> declaredClasspathEntries, Path outputDirectory,
        Optional<Path> workingDirectory, Path pathToSrcsList, Optional<SuggestBuildRules> suggestBuildRules,
        ImmutableList<String> postprocessClassesCommands, ImmutableSortedSet<Path> entriesToJar,
        Optional<String> mainClass, Optional<Path> manifestFile, Path outputJar,
        ClassUsageFileWriter usedClassesFileWriter,
        /* output params */
        ImmutableList.Builder<Step> steps, BuildableContext buildableContext,
        ImmutableSet<Pattern> classesToRemoveFromJar) {

    String spoolMode = javacOptions.getSpoolMode().name();
    // In order to use direct spooling to the Jar:
    // (1) It must be enabled through a .buckconfig.
    // (2) The target must have 0 postprocessing steps.
    // (3) Tha compile API must be JSR 199.
    boolean isSpoolingToJarEnabled = postprocessClassesCommands.isEmpty()
            && javacOptions.getSpoolMode() == AbstractJavacOptions.SpoolMode.DIRECT_TO_JAR
            && javacOptions.getJavac() instanceof Jsr199Javac;

    LOG.info("Target: %s SpoolMode: %s Expected SpoolMode: %s Postprocessing steps: %s",
            invokingRule.getBaseName(),// w w  w.  jav a 2 s  .co m
            (isSpoolingToJarEnabled) ? (SpoolMode.DIRECT_TO_JAR) : (SpoolMode.INTERMEDIATE_TO_DISK), spoolMode,
            postprocessClassesCommands.toString());

    if (isSpoolingToJarEnabled) {
        final JavacOptions buildTimeOptions = amender.amend(javacOptions, context);
        // Javac requires that the root directory for generated sources already exists.
        addAnnotationGenFolderStep(buildTimeOptions, filesystem, steps, buildableContext);

        steps.add(new JavacDirectToJarStep(sourceFilePaths, invokingRule, resolver, ruleFinder, filesystem,
                declaredClasspathEntries, buildTimeOptions, outputDirectory, workingDirectory, pathToSrcsList,
                suggestBuildRules, entriesToJar, mainClass, manifestFile, outputJar, usedClassesFileWriter));
    } else {
        super.createCompileToJarStep(context, sourceFilePaths, invokingRule, resolver, ruleFinder, filesystem,
                declaredClasspathEntries, outputDirectory, workingDirectory, pathToSrcsList, suggestBuildRules,
                postprocessClassesCommands, entriesToJar, mainClass, manifestFile, outputJar,
                usedClassesFileWriter, steps, buildableContext, javacOptions.getClassesToRemoveFromJar());
    }
}

From source file:org.kiji.schema.KijiURI.java

/**
 * Formats the full KijiURI up to the column.
 *
 * @param preserveOrdering Whether to preserve ordering.
 * @return Representation of this KijiURI up to the table.
 *///from  w  w  w. j a  v a2  s.co  m
private String toStringCol(boolean preserveOrdering) {
    String columnField;
    ImmutableList<KijiColumnName> columns = preserveOrdering ? mColumnNames : mColumnNamesNormalized;
    if (columns.isEmpty()) {
        columnField = UNSET_URI_STRING;
    } else {
        ImmutableList.Builder<String> builder = ImmutableList.builder();
        for (KijiColumnName column : columns) {
            builder.add(column.getName());
        }
        ImmutableList<String> strColumns = builder.build();
        if (strColumns.size() == 1) {
            columnField = strColumns.get(0);
        } else {
            columnField = Joiner.on(",").join(strColumns);
        }
    }

    try {
        // SCHEMA-6. URI Encode column names using RFC-2396.
        final URI columnsEncoded = new URI(KIJI_SCHEME, columnField, null);
        return String.format("%s%s/", toStringTable(preserveOrdering),
                columnsEncoded.getRawSchemeSpecificPart());
    } catch (URISyntaxException e) {
        throw new KijiURIException(e.getMessage());
    }
}

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

/**
 * Creates an action to run Proguard to <i>output</i> the given {@code deployJar} artifact
 * if --java_optimization_mode calls for it from an assumed input artifact
 * {@link JavaSemantics#JAVA_BINARY_MERGED_JAR}.  Returns the artifacts that Proguard will
 * generate or {@code null} if Proguard isn't used.
 *
 * <p>If this method returns artifacts then {@link DeployArchiveBuilder} needs to write the
 * assumed input artifact (instead of the conventional deploy.jar, which now Proguard writes).
 * Do not use this method for binary rules that themselves declare {@link #PROGUARD_SPECS}
 * attributes, which as of includes 1/2016 {@code android_binary} and {@code android_test}.
 *///ww w  .  j  av  a2  s.  c  o  m
@Nullable
public ProguardOutput applyProguardIfRequested(RuleContext ruleContext, Artifact deployJar,
        ImmutableList<Artifact> bootclasspath, String mainClassName, JavaSemantics semantics)
        throws InterruptedException {
    JavaOptimizationMode optMode = getJavaOptimizationMode(ruleContext);
    if (optMode == JavaOptimizationMode.NOOP || optMode == JavaOptimizationMode.LEGACY) {
        // For simplicity do nothing in LEGACY mode
        return null;
    }

    Preconditions.checkArgument(!bootclasspath.isEmpty(), "Bootclasspath should not be empty");
    FilesToRunProvider proguard = findProguard(ruleContext);
    if (proguard == null) {
        ruleContext.ruleError("--proguard_top required for --java_optimization_mode=" + optMode);
        return null;
    }

    ImmutableList<Artifact> proguardSpecs = collectProguardSpecs(ruleContext, bootclasspath, mainClassName);
    Artifact singleJar = ruleContext.getImplicitOutputArtifact(JavaSemantics.JAVA_BINARY_MERGED_JAR);
    return createProguardAction(ruleContext, proguard, singleJar, proguardSpecs,
            /* proguardSeeds */ (Artifact) null, /* proguardUsage */ (Artifact) null,
            /* proguardMapping */ (Artifact) null, bootclasspath, deployJar, semantics,
            /* optimizationPases */ 3);
}

From source file:org.richfaces.component.behavior.ClientValidatorImpl.java

@Override
public void broadcast(BehaviorEvent event) throws AbortProcessingException {
    // Add message components to re-render list ( if any )
    FacesContext facesContext = FacesContext.getCurrentInstance();
    PartialViewContext partialViewContext = facesContext.getPartialViewContext();
    if (partialViewContext.isAjaxRequest()) {
        UIComponent component = event.getComponent();
        if (component instanceof EditableValueHolder) {
            String clientId = component.getClientId(facesContext);
            final ImmutableList<Message> messages = ImmutableList
                    .copyOf(Iterators.transform(facesContext.getMessages(clientId), MESSAGES_TRANSFORMER));

            JavaScriptService javaScriptService = ServiceTracker.getService(JavaScriptService.class);
            javaScriptService.addPageReadyScript(facesContext, new MessageUpdateScript(clientId, messages));

            if (messages.isEmpty()) {
                final String onvalid = getOnvalid();
                if (onvalid != null && !"".equals(onvalid.trim())) {
                    javaScriptService.addPageReadyScript(facesContext,
                            new AnonymousFunctionCall().addToBody(onvalid));
                }//from w  w  w .j  av a  2  s .co  m
            } else {
                final String oninvalid = getOninvalid();
                if (oninvalid != null && !"".equals(oninvalid.trim())) {
                    javaScriptService.addPageReadyScript(facesContext, new AnonymousFunctionCall("messages")
                            .addParameterValue(ScriptUtils.toScript(messages)).addToBody(oninvalid));
                }
            }
        }
    }
    super.broadcast(event);
}

From source file:com.moz.fiji.schema.FijiURI.java

/**
 * Formats the full FijiURI up to the column.
 *
 * @param preserveOrdering Whether to preserve ordering.
 * @return Representation of this FijiURI up to the table.
 *///from www. j a v  a2s  . co m
private String toStringCol(boolean preserveOrdering) {
    String columnField;
    ImmutableList<FijiColumnName> columns = preserveOrdering ? mColumnNames : mColumnNamesNormalized;
    if (columns.isEmpty()) {
        columnField = UNSET_URI_STRING;
    } else {
        ImmutableList.Builder<String> builder = ImmutableList.builder();
        for (FijiColumnName column : columns) {
            builder.add(column.getName());
        }
        ImmutableList<String> strColumns = builder.build();
        if (strColumns.size() == 1) {
            columnField = strColumns.get(0);
        } else {
            columnField = Joiner.on(",").join(strColumns);
        }
    }

    try {
        // SCHEMA-6. URI Encode column names using RFC-2396.
        final URI columnsEncoded = new URI(FIJI_SCHEME, columnField, null);
        return String.format("%s%s/", toStringTable(preserveOrdering),
                columnsEncoded.getRawSchemeSpecificPart());
    } catch (URISyntaxException e) {
        throw new FijiURIException(e.getMessage());
    }
}