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.facebook.buck.core.build.engine.manifest.Manifest.java

/** Adds a new output file to the manifest. */
public void addEntry(FileHashCache fileHashCache, RuleKey key, SourcePathResolver resolver,
        ImmutableSet<SourcePath> universe, ImmutableSet<SourcePath> inputs) throws IOException {

    // Construct the input sub-paths that we care about.
    ImmutableSet<String> inputPaths = RichStream.from(inputs).map(sourcePathToManifestHeaderFunction(resolver))
            .toImmutableSet();/*from  w  ww .jav a2 s .co  m*/

    // Create a multimap from paths we care about to SourcePaths that maps to them.
    ImmutableListMultimap<String, SourcePath> sortedUniverse = index(universe,
            sourcePathToManifestHeaderFunction(resolver), inputPaths::contains);

    // Record the Entry.
    int index = 0;
    int[] hashIndices = new int[inputs.size()];
    for (String relativePath : inputPaths) {
        ImmutableList<SourcePath> paths = sortedUniverse.get(relativePath);
        Preconditions.checkState(!paths.isEmpty());
        hashIndices[index++] = addHash(relativePath, hashSourcePathGroup(fileHashCache, resolver, paths));
    }
    entries.add(new Pair<>(key, hashIndices));
}

From source file:com.google.devtools.build.buildjar.VanillaJavaBuilder.java

public VanillaJavaBuilderResult run(List<String> args) throws IOException {
    OptionsParser optionsParser;//from  ww  w  . j a v a2 s . c  om
    try {
        optionsParser = new OptionsParser(args);
    } catch (InvalidCommandLineException e) {
        return new VanillaJavaBuilderResult(false, e.getMessage());
    }
    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
    StringWriter output = new StringWriter();
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(diagnosticCollector, ENGLISH,
            UTF_8);
    setLocations(optionsParser, fileManager);
    ImmutableList<JavaFileObject> sources = getSources(optionsParser, fileManager);
    boolean ok;
    if (sources.isEmpty()) {
        ok = true;
    } else {
        CompilationTask task = javaCompiler.getTask(new PrintWriter(output, true), fileManager,
                diagnosticCollector, JavacOptions.removeBazelSpecificFlags(optionsParser.getJavacOpts()),
                ImmutableList.<String>of() /*classes*/, sources);
        setProcessors(optionsParser, fileManager, task);
        ok = task.call();
    }
    if (ok) {
        writeOutput(optionsParser);
    }
    writeGeneratedSourceOutput(optionsParser);
    // the jdeps output doesn't include any information about dependencies, but Bazel still expects
    // the file to be created
    if (optionsParser.getOutputDepsProtoFile() != null) {
        try (OutputStream os = Files.newOutputStream(Paths.get(optionsParser.getOutputDepsProtoFile()))) {
            Deps.Dependencies.newBuilder().setRuleLabel(optionsParser.getTargetLabel()).setSuccess(ok).build()
                    .writeTo(os);
        }
    }
    // TODO(cushon): support manifest protos & genjar
    if (optionsParser.getManifestProtoPath() != null) {
        try (OutputStream os = Files.newOutputStream(Paths.get(optionsParser.getManifestProtoPath()))) {
            Manifest.getDefaultInstance().writeTo(os);
        }
    }

    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnosticCollector.getDiagnostics()) {
        StringBuilder message = new StringBuilder();
        if (diagnostic.getSource() != null) {
            message.append(diagnostic.getSource().getName());
            if (diagnostic.getLineNumber() != -1) {
                message.append(':').append(diagnostic.getLineNumber());
            }
            message.append(": ");
        }
        message.append(diagnostic.getKind().toString().toLowerCase(ENGLISH));
        message.append(": ").append(diagnostic.getMessage(ENGLISH)).append(System.lineSeparator());
        output.write(message.toString());
    }
    return new VanillaJavaBuilderResult(ok, output.toString());
}

From source file:com.palantir.giraffe.file.UniformPath.java

private Path toRelativePath(FileSystem fs) {
    ImmutableList<String> segments = core.getPathSegments();
    if (segments.isEmpty()) {
        return fs.getPath("");
    } else {// w  w w  . ja v a  2s .  c  o m
        String first = segments.get(0);
        String[] more = segments.subList(1, segments.size()).toArray(new String[0]);
        return fs.getPath(first, more);
    }
}

From source file:com.facebook.buck.cxx.toolchain.elf.ElfVerDef.java

public ElfVerDef compact() {
    return new ElfVerDef(RichStream.from(MoreIterables.enumerate(this.entries)).map(vdp -> {
        int verdefIndex = vdp.getFirst();
        Verdef verdef = vdp.getSecond().getFirst();
        ImmutableList<Verdaux> verdauxes = vdp.getSecond().getSecond();
        return new Pair<>(
                new Verdef(verdef.vd_version, verdef.vd_flags, verdef.vd_ndx, verdauxes.size(), verdef.vd_hash,
                        verdauxes.isEmpty() ? 0 : Verdef.BYTES,
                        verdefIndex == entries.size() - 1 ? 0
                                : Verdef.BYTES + Verdaux.BYTES * verdauxes.size()),
                RichStream.from(MoreIterables.enumerate(verdauxes))
                        .map(vdxp -> new Verdaux(vdxp.getSecond().vda_name,
                                vdxp.getFirst() == verdauxes.size() - 1 ? 0 : Verdaux.BYTES))
                        .toImmutableList());
    }).toImmutableList());/*ww  w.  ja v  a2 s . co m*/
}

From source file:org.apache.flink.streaming.connectors.elasticsearch2.ElasticsearchSink.java

/**
 * Initializes the connection to Elasticsearch by creating a
 * {@link org.elasticsearch.client.transport.TransportClient}.
 *//*from www  .j  a v a2s. co  m*/
@Override
public void open(Configuration configuration) {
    List<TransportAddress> transportNodes;
    transportNodes = new ArrayList<>(transportAddresses.size());
    for (InetSocketAddress address : transportAddresses) {
        transportNodes.add(new InetSocketTransportAddress(address));
    }

    Settings settings = Settings.settingsBuilder().put(userConfig).build();

    TransportClient transportClient = TransportClient.builder().settings(settings).build();
    for (TransportAddress transport : transportNodes) {
        transportClient.addTransportAddress(transport);
    }

    // verify that we actually are connected to a cluster
    ImmutableList<DiscoveryNode> nodes = ImmutableList.copyOf(transportClient.connectedNodes());
    if (nodes.isEmpty()) {
        throw new RuntimeException("Client is not connected to any Elasticsearch nodes!");
    }

    client = transportClient;

    if (LOG.isInfoEnabled()) {
        LOG.info("Created Elasticsearch TransportClient {}", client);
    }

    BulkProcessor.Builder bulkProcessorBuilder = BulkProcessor.builder(client, new BulkProcessor.Listener() {
        @Override
        public void beforeBulk(long executionId, BulkRequest request) {

        }

        @Override
        public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
            if (response.hasFailures()) {
                for (BulkItemResponse itemResp : response.getItems()) {
                    if (itemResp.isFailed()) {
                        LOG.error("Failed to index document in Elasticsearch: " + itemResp.getFailureMessage());
                        failureThrowable.compareAndSet(null,
                                new RuntimeException(itemResp.getFailureMessage()));
                    }
                }
                hasFailure.set(true);
            }
        }

        @Override
        public void afterBulk(long executionId, BulkRequest request, Throwable failure) {
            LOG.error(failure.getMessage());
            failureThrowable.compareAndSet(null, failure);
            hasFailure.set(true);
        }
    });

    // This makes flush() blocking
    bulkProcessorBuilder.setConcurrentRequests(0);

    ParameterTool params = ParameterTool.fromMap(userConfig);

    if (params.has(CONFIG_KEY_BULK_FLUSH_MAX_ACTIONS)) {
        bulkProcessorBuilder.setBulkActions(params.getInt(CONFIG_KEY_BULK_FLUSH_MAX_ACTIONS));
    }

    if (params.has(CONFIG_KEY_BULK_FLUSH_MAX_SIZE_MB)) {
        bulkProcessorBuilder.setBulkSize(
                new ByteSizeValue(params.getInt(CONFIG_KEY_BULK_FLUSH_MAX_SIZE_MB), ByteSizeUnit.MB));
    }

    if (params.has(CONFIG_KEY_BULK_FLUSH_INTERVAL_MS)) {
        bulkProcessorBuilder
                .setFlushInterval(TimeValue.timeValueMillis(params.getInt(CONFIG_KEY_BULK_FLUSH_INTERVAL_MS)));
    }

    bulkProcessor = bulkProcessorBuilder.build();
    requestIndexer = new BulkProcessorIndexer(bulkProcessor);
}

From source file:com.squareup.wire.schema.MessageType.java

@Override
Type retainAll(Schema schema, MarkSet markSet) {
    ImmutableList.Builder<Type> retainedNestedTypesBuilder = ImmutableList.builder();
    for (Type nestedType : nestedTypes) {
        Type retainedNestedType = nestedType.retainAll(schema, markSet);
        if (retainedNestedType != null) {
            retainedNestedTypesBuilder.add(retainedNestedType);
        }/*from  w ww  . j  ava 2  s.  c  o  m*/
    }

    // If this type is not retained, and none of its nested types are retained, prune it.
    ImmutableList<Type> retainedNestedTypes = retainedNestedTypesBuilder.build();
    if (!markSet.contains(protoType) && retainedNestedTypes.isEmpty()) {
        return null;
    }

    ImmutableList.Builder<OneOf> retainedOneOfsBuilder = ImmutableList.builder();
    for (OneOf oneOf : oneOfs) {
        OneOf retainedOneOf = oneOf.retainAll(schema, markSet, protoType);
        if (retainedOneOf != null) {
            retainedOneOfsBuilder.add(retainedOneOf);
        }
    }
    ImmutableList<OneOf> retainedOneOfs = retainedOneOfsBuilder.build();

    return new MessageType(protoType, location, documentation, name,
            Field.retainAll(schema, markSet, protoType, declaredFields),
            Field.retainAll(schema, markSet, protoType, extensionFields), retainedOneOfs, retainedNestedTypes,
            extensionsList, reserveds, options.retainAll(schema, markSet));
}

From source file:com.facebook.buck.cxx.toolchain.elf.ElfVerNeed.java

public ElfVerNeed compact() {
    return new ElfVerNeed(RichStream.from(MoreIterables.enumerate(this.entries)).map(vnp -> {
        int verneedIndex = vnp.getFirst();
        ElfVerNeed.Verneed verneed = vnp.getSecond().getFirst();
        ImmutableList<ElfVerNeed.Vernaux> vernauxes = vnp.getSecond().getSecond();
        return new Pair<>(
                new ElfVerNeed.Verneed(verneed.vn_version, vernauxes.size(), verneed.vn_file,
                        vernauxes.isEmpty() ? 0 : ElfVerNeed.Verneed.BYTES,
                        verneedIndex == entries.size() - 1 ? 0
                                : ElfVerNeed.Verneed.BYTES + ElfVerNeed.Vernaux.BYTES * vernauxes.size()),
                RichStream.from(MoreIterables.enumerate(vernauxes))
                        .map(vnxp -> new ElfVerNeed.Vernaux(vnxp.getSecond().vna_hash,
                                vnxp.getSecond().vna_flags, vnxp.getSecond().vna_other,
                                vnxp.getSecond().vna_name,
                                vnxp.getFirst() == vernauxes.size() - 1 ? 0 : ElfVerNeed.Vernaux.BYTES))
                        .toImmutableList());
    }).toImmutableList());/*from  ww  w .j a  v a2s . c om*/
}

From source file:org.apache.james.transport.mailets.RecipientRewriteTableProcessor.java

public void processMail(Mail mail) throws MessagingException {
    ImmutableList<RrtExecutionResult> mappingDatas = toMappingDatas(mail);

    ImmutableList<MailAddress> newRecipients = getRecipientsByCondition(mappingDatas, recipientWithoutError);

    ImmutableList<MailAddress> errorMailAddresses = getRecipientsByCondition(mappingDatas, recipientWithError);

    if (!errorMailAddresses.isEmpty()) {
        mailetContext.sendMail(mail.getSender(), errorMailAddresses, mail.getMessage(), Mail.ERROR);
    }//from  w  w  w  .ja  va 2  s .c o m

    if (newRecipients.isEmpty()) {
        mail.setState(Mail.GHOST);
    }

    mail.setRecipients(newRecipients);
}

From source file:google.registry.tools.CreateOrUpdateTldCommand.java

private void checkReservedListValidityForTld(String tld, Set<String> reservedListNames) {
    ImmutableList.Builder<String> builder = new ImmutableList.Builder<>();
    for (String reservedListName : reservedListNames) {
        if (!reservedListName.startsWith("common_") && !reservedListName.startsWith(tld + "_")) {
            builder.add(reservedListName);
        }//from  w  w  w.  j a  va2  s .  c  o  m
    }
    ImmutableList<String> invalidNames = builder.build();
    if (!invalidNames.isEmpty()) {
        String errMsg = String.format("The reserved list(s) %s cannot be applied to the tld %s",
                Joiner.on(", ").join(invalidNames), tld);
        if (overrideReservedListRules) {
            System.err.println("Error overriden: " + errMsg);
        } else {
            throw new IllegalArgumentException(errMsg);
        }
    }
}

From source file:ratpack.session.clientside.internal.ClientSideSessionStore.java

private ByteBuf deserialize(ImmutableList<Cookie> sessionCookies) throws Exception {
    if (sessionCookies.isEmpty()) {
        return Unpooled.EMPTY_BUFFER;
    }/*from  ww w  .j  a  va2s.co m*/

    StringBuilder sessionCookie = new StringBuilder();
    for (Cookie cookie : sessionCookies) {
        sessionCookie.append(cookie.value());
    }
    String[] parts = sessionCookie.toString().split(SESSION_SEPARATOR);
    if (parts.length != 2) {
        return Unpooled.buffer(0, 0);
    }
    ByteBuf payload = null;
    ByteBuf digest = null;
    ByteBuf expectedDigest = null;
    ByteBuf decryptedPayload = null;
    try {
        payload = fromBase64(bufferAllocator, parts[0]);
        digest = fromBase64(bufferAllocator, parts[1]);
        expectedDigest = signer.sign(payload, bufferAllocator);
        if (ByteBufUtil.equals(digest, expectedDigest)) {
            decryptedPayload = crypto.decrypt(payload.resetReaderIndex(), bufferAllocator);
        } else {
            decryptedPayload = Unpooled.buffer(0, 0);
        }
    } finally {
        if (payload != null) {
            payload.touch().release();
        }
        if (digest != null) {
            digest.release();
        }
        if (expectedDigest != null) {
            expectedDigest.release();
        }
    }
    return decryptedPayload.touch();
}