Example usage for com.google.common.base Preconditions checkNotNull

List of usage examples for com.google.common.base Preconditions checkNotNull

Introduction

In this page you can find the example usage for com.google.common.base Preconditions checkNotNull.

Prototype

public static <T> T checkNotNull(T reference) 

Source Link

Document

Ensures that an object reference passed as a parameter to the calling method is not null.

Usage

From source file:com.google.devtools.build.android.ideinfo.PackageParser.java

public static void main(String[] args) throws Exception {
    PackageParserOptions options = parseArgs(args);
    Preconditions.checkNotNull(options.outputManifest);

    try {/* w w w . j a v  a2  s  . c om*/
        PackageParser parser = new PackageParser(PackageParserIoProvider.INSTANCE);
        Map<ArtifactLocation, String> outputMap = parser.parsePackageStrings(options.sources);
        parser.writeManifest(outputMap, options.outputManifest);
    } catch (Throwable e) {
        logger.log(Level.SEVERE, "Error parsing package strings", e);
        System.exit(1);
    }
    System.exit(0);
}

From source file:com.google.devtools.build.android.AndroidResourceValidatorAction.java

public static void main(String[] args) throws Exception {
    final Stopwatch timer = Stopwatch.createStarted();
    OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class, AaptConfigOptions.class);
    optionsParser.parseAndExitUponError(args);
    AaptConfigOptions aaptConfigOptions = optionsParser.getOptions(AaptConfigOptions.class);
    Options options = optionsParser.getOptions(Options.class);

    final AndroidResourceProcessor resourceProcessor = new AndroidResourceProcessor(stdLogger);
    VariantType packageType = VariantType.LIBRARY;

    Preconditions.checkNotNull(options.rOutput);
    Preconditions.checkNotNull(options.srcJarOutput);
    try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("resource_validator_tmp")) {
        Path tmp = scopedTmp.getPath();
        Path expandedOut = tmp.resolve("tmp-expanded");
        Path resources = expandedOut.resolve("res");
        Path assets = expandedOut.resolve("assets");
        Path generatedSources = tmp.resolve("generated_resources");
        Path dummyManifest = tmp.resolve("manifest-aapt-dummy/AndroidManifest.xml");

        unpackZip(options.mergedResources, expandedOut);
        logger.fine(String.format("unpacked zip at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        // We need to make the manifest aapt safe (w.r.t., placeholders). For now, just stub it out.
        resourceProcessor.writeDummyManifestForAapt(dummyManifest, options.packageForR);

        resourceProcessor.runAapt(aaptConfigOptions.aapt, aaptConfigOptions.androidJar,
                aaptConfigOptions.buildToolsVersion, packageType, aaptConfigOptions.debug, options.packageForR,
                new FlagAaptOptions(aaptConfigOptions), aaptConfigOptions.resourceConfigs,
                ImmutableList.<String>of(), dummyManifest, resources, assets, generatedSources,
                null, /* packageOut */
                null, /* proguardOut */
                null, /* mainDexProguardOut */
                null /* publicResourcesOut */);
        logger.fine(String.format("aapt finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        resourceProcessor.copyRToOutput(generatedSources, options.rOutput, VariantType.LIBRARY == packageType);

        resourceProcessor.createSrcJar(generatedSources, options.srcJarOutput,
                VariantType.LIBRARY == packageType);
    } catch (Exception e) {
        logger.log(java.util.logging.Level.SEVERE, "Unexpected", e);
        throw e;//from w  ww.ja va2  s . co m
    } finally {
        resourceProcessor.shutdown();
    }
    logger.fine(String.format("Resources merged in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
}

From source file:com.google.devtools.build.android.RClassGeneratorAction.java

public static void main(String[] args) throws Exception {
    final Stopwatch timer = Stopwatch.createStarted();
    OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class);
    if (args.length == 1 && args[0].startsWith("@")) {
        args = Files.readAllLines(Paths.get(args[0].substring(1)), StandardCharsets.UTF_8)
                .toArray(new String[0]);
    }//from  w ww  . j  a va  2 s  .c  o  m

    optionsParser.parseAndExitUponError(args);
    Options options = optionsParser.getOptions(Options.class);
    Preconditions.checkNotNull(options.classJarOutput);
    final AndroidResourceProcessor resourceProcessor = new AndroidResourceProcessor(STD_LOGGER);
    try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("android_res_compile_tmp")) {
        Path tmp = scopedTmp.getPath();
        Path classOutPath = tmp.resolve("compiled_classes");

        LOGGER.fine(String.format("Setup finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
        List<SymbolFileProvider> libraries = new ArrayList<>();
        for (DependencySymbolFileProvider library : options.libraries) {
            libraries.add(library);
        }
        // Note that we need to write the R class for the main binary (so proceed even if there
        // are no libraries).
        if (options.primaryRTxt != null) {
            String appPackageName = options.packageForR;
            if (appPackageName == null) {
                appPackageName = VariantConfiguration.getManifestPackage(options.primaryManifest.toFile());
            }
            Multimap<String, SymbolLoader> libSymbolMap = ArrayListMultimap.create();
            SymbolLoader fullSymbolValues = resourceProcessor.loadResourceSymbolTable(libraries, appPackageName,
                    options.primaryRTxt, libSymbolMap);
            LOGGER.fine(String.format("Load symbols finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
            // For now, assuming not used for libraries and setting final access for fields.
            if (fullSymbolValues != null) {
                resourceProcessor.writePackageRClasses(libSymbolMap, fullSymbolValues, appPackageName,
                        classOutPath, true /* finalFields */);
                LOGGER.fine(String.format("Finished R.class at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
            }
        } else {
            Files.createDirectories(classOutPath);
        }
        // We write .class files to temp, then jar them up after (we create a dummy jar, even if
        // there are no class files).
        resourceProcessor.createClassJar(classOutPath, options.classJarOutput);
        LOGGER.fine(String.format("createClassJar finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
    } finally {
        resourceProcessor.shutdown();
    }
    LOGGER.fine(String.format("Compile action done in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
}

From source file:com.google.devtools.build.android.CompileLibraryResourcesAction.java

public static void main(String[] args) throws Exception {
    OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class);
    optionsParser.enableParamsFileSupport(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault()));
    optionsParser.parseAndExitUponError(args);

    Options options = optionsParser.getOptions(Options.class);

    Preconditions.checkNotNull(options.resources);
    Preconditions.checkNotNull(options.output);
    Preconditions.checkNotNull(options.aapt2);

    final ListeningExecutorService defaultService = ExecutorServiceCloser.createDefaultService();
    try (Closeable serviceCloser = ExecutorServiceCloser.createWith(defaultService);
            ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("android_resources_tmp")) {
        final Path tmp = scopedTmp.getPath();
        final Path databindingResourcesRoot = Files
                .createDirectories(tmp.resolve("android_data_binding_resources"));
        final Path compiledResources = Files.createDirectories(tmp.resolve("compiled"));

        final ResourceCompiler compiler = ResourceCompiler.create(defaultService, compiledResources,
                options.aapt2, options.buildToolsVersion);
        options.resources.toData(options.manifest)
                .processDataBindings(options.dataBindingInfoOut, options.packagePath, databindingResourcesRoot)
                .compile(compiler, compiledResources).copyResourcesZipTo(options.output);
    }//from  w  ww.ja  va2s.  c o m
}

From source file:com.google.devtools.build.android.AndroidResourceMergingAction.java

public static void main(String[] args) throws Exception {
    final Stopwatch timer = Stopwatch.createStarted();
    OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class, AaptConfigOptions.class);
    optionsParser.parseAndExitUponError(args);
    AaptConfigOptions aaptConfigOptions = optionsParser.getOptions(AaptConfigOptions.class);
    Options options = optionsParser.getOptions(Options.class);

    final AndroidResourceProcessor resourceProcessor = new AndroidResourceProcessor(stdLogger);

    Preconditions.checkNotNull(options.primaryData);
    Preconditions.checkNotNull(options.primaryManifest);
    Preconditions.checkNotNull(options.classJarOutput);

    try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("android_resource_merge_tmp")) {
        Path tmp = scopedTmp.getPath();
        Path mergedAssets = tmp.resolve("merged_assets");
        Path mergedResources = tmp.resolve("merged_resources");
        Path generatedSources = tmp.resolve("generated_resources");
        Path processedManifest = tmp.resolve("manifest-processed/AndroidManifest.xml");

        logger.fine(String.format("Setup finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        VariantType packageType = VariantType.LIBRARY;
        AndroidResourceClassWriter resourceClassWriter = AndroidResourceClassWriter.createWith(
                aaptConfigOptions.androidJar, generatedSources, Strings.nullToEmpty(options.packageForR));
        resourceClassWriter.setIncludeClassFile(true);
        resourceClassWriter.setIncludeJavaFile(false);

        final MergedAndroidData mergedData = resourceProcessor.mergeData(options.primaryData,
                options.primaryManifest, options.directData, options.transitiveData, mergedResources,
                mergedAssets, new StubPngCruncher(), packageType, options.symbolsBinOut, resourceClassWriter);

        logger.fine(String.format("Merging finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        // Until enough users with manifest placeholders migrate to the new manifest merger,
        // we need to replace ${applicationId} and ${packageName} with options.packageForR to make
        // the manifests compatible with the old manifest merger.
        if (options.manifestOutput != null) {
            MergedAndroidData processedData = resourceProcessor.processManifest(packageType,
                    options.packageForR, null, /* applicationId */
                    -1, /* versionCode */
                    null, /* versionName */
                    mergedData, processedManifest);
            resourceProcessor.copyManifestToOutput(processedData, options.manifestOutput);
        }/*from w w w.j  a v a 2  s .  c  om*/

        resourceProcessor.createClassJar(generatedSources, options.classJarOutput);

        logger.fine(String.format("Create classJar finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        if (options.resourcesOutput != null) {
            // For now, try compressing the library resources that we pass to the validator. This takes
            // extra CPU resources to pack and unpack (~2x), but can reduce the zip size (~4x).
            resourceProcessor.createResourcesZip(mergedData.getResourceDir(), mergedData.getAssetDir(),
                    options.resourcesOutput, true /* compress */);
            logger.fine(String.format("Create resources.zip finished at %sms",
                    timer.elapsed(TimeUnit.MILLISECONDS)));
        }
    } catch (MergingException e) {
        logger.log(Level.SEVERE, "Error during merging resources", e);
        throw e;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Unexpected", e);
        throw e;
    } finally {
        resourceProcessor.shutdown();
    }
    logger.fine(String.format("Resources merged in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
}

From source file:com.google.devtools.build.android.ValidateAndLinkResourcesAction.java

public static void main(String[] args) throws Exception {
    final OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class, Aapt2ConfigOptions.class);
    optionsParser.enableParamsFileSupport(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault()));
    optionsParser.parse(args);//from   ww w  . j  a va2s  .c  o  m

    Options options = optionsParser.getOptions(Options.class);
    final Aapt2ConfigOptions aapt2Options = optionsParser.getOptions(Aapt2ConfigOptions.class);
    final Profiler profiler = LoggingProfiler.createAndStart("manifest");

    try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("android_resources_tmp")) {
        CompiledResources resources =
                // TODO(b/64570523): Remove when the flags are standardized.
                Optional.ofNullable(options.resources)
                        .orElseGet(() -> CompiledResources.from(Preconditions.checkNotNull(options.compiled),
                                Preconditions.checkNotNull(options.manifest)))
                        // We need to make the manifest aapt safe (w.r.t., placeholders). For now, just stub
                        // it out.
                        .processManifest(manifest -> AndroidManifestProcessor.writeDummyManifestForAapt(
                                scopedTmp.getPath().resolve("manifest-aapt-dummy/AndroidManifest.xml"),
                                options.packageForR));
        profiler.recordEndOf("manifest").startTask("link");
        ResourceLinker.create(aapt2Options.aapt2, scopedTmp.getPath()).profileUsing(profiler)
                .dependencies(Optional.ofNullable(options.deprecatedLibraries).orElse(options.libraries))
                .include(
                        options.compiledDeps.stream().map(CompiledResources::from).collect(Collectors.toList()))
                .buildVersion(aapt2Options.buildToolsVersion).linkStatically(resources)
                .copyLibraryTo(options.staticLibraryOut).copySourceJarTo(options.sourceJarOut)
                .copyRTxtTo(options.rTxtOut);
        profiler.recordEndOf("link");
    }
}

From source file:org.apache.mahout.knn.tools.TrainNewsGroupsKMeansLogisticRegression.java

public static void main(String[] args) throws IOException, ParseException {
    Options options = new Options();
    options.addOption("i", "input", true,
            "Path to the input folder containing the training set's" + " sequence files.");
    options.addOption("o", "output", true, "Base path to the output file. The name will be "
            + "appended with a suffix for each type of training.");
    options.addOption("a", "actual", false, "If set, runs the training with the actual cluster "
            + "assignments and outputs the model to the output path with a -actual suffix.");
    options.addOption("b", "ballkmeans", false, "If set, runs the training with the ball k-means "
            + "cluster assignments and outputs the model to the output path with a -ballkmeans suffix.");
    options.addOption("s", "streamingkmeans", false,
            "If set, runs the training with the "
                    + "streaming k-means cluster assignments and outputs the model to the output path with a "
                    + "-streamingkmeans suffix.");
    options.addOption("c", "centroids", true, "Path to the centroids seqfile");

    CommandLine cmd = (new PosixParser()).parse(options, args);

    String inputPath = cmd.getOptionValue("input");
    Preconditions.checkNotNull(inputPath);

    String outputBase = cmd.getOptionValue("output");
    Preconditions.checkNotNull(outputBase);

    String centroidsPath = cmd.getOptionValue("centroids");
    Preconditions.checkNotNull(centroidsPath);

    Configuration conf = new Configuration();
    SequenceFileDirIterable<Text, VectorWritable> inputIterable = new SequenceFileDirIterable<Text, VectorWritable>(
            new Path(inputPath), PathType.LIST, conf);

    PrintStream clusterIdOut = new PrintStream(new FileOutputStream("cluster-ids.csv"));
    clusterIdOut.printf("clusterName, clusterId\n");
    int clusterId = 0;
    Map<String, Integer> clusterNamesToIds = Maps.newHashMapWithExpectedSize(NUM_CLASSES);
    for (Pair<Text, VectorWritable> pair : inputIterable) {
        String clusterName = pair.getFirst().toString();
        if (!clusterNamesToIds.containsKey(clusterName)) {
            clusterIdOut.printf("%s, %d\n", clusterName, clusterId);
            clusterNamesToIds.put(clusterName, clusterId++);
        }/*from   w  ww. java2  s.c  o m*/
    }
    clusterIdOut.close();

    if (cmd.hasOption("actual")) {
        System.out.printf("\nActual clusters models\n");
        System.out.printf("----------------------\n");
        long start = System.currentTimeMillis();
        trainActual(inputIterable, outputBase, clusterNamesToIds);
        long end = System.currentTimeMillis();
        System.out.printf("Trained models for actual clusters. Took %d ms\n", end - start);
    }

    if (cmd.hasOption("ballkmeans") || cmd.hasOption("streamingkmeans")) {
        SequenceFileValueIterable<CentroidWritable> centroidIterable = new SequenceFileValueIterable<CentroidWritable>(
                new Path(centroidsPath), conf);
        List<Centroid> centroids = Lists
                .newArrayList(CreateCentroids.getCentroidsFromCentroidWritableIterable(centroidIterable));

        if (cmd.hasOption("ballkmeans")) {
            System.out.printf("\nBall k-means clusters models\n");
            System.out.printf("----------------------------\n");
            long start = System.currentTimeMillis();
            trainComputed(inputIterable, outputBase, "ballkmeans", clusterNamesToIds,
                    new Pair<Integer, Iterable<Centroid>>(NUM_FEATURES_BKM, centroids));
            long end = System.currentTimeMillis();
            System.out.printf("Trained models for ballkmeans clusters. Took %d ms\n", end - start);
        }

        if (cmd.hasOption("streamingkmeans")) {
            System.out.printf("\nStreaming k-means clusters models\n");
            System.out.printf("---------------------------------\n");
            long start = System.currentTimeMillis();
            trainComputed(inputIterable, outputBase, "streamingkmeans", clusterNamesToIds,
                    new Pair<Integer, Iterable<Centroid>>(centroids.size(), centroids));
            long end = System.currentTimeMillis();
            System.out.printf("Trained models for streamingkmeans clusters. Took %d ms\n", end - start);
        }
    }
}

From source file:com.linkedin.pinot.common.utils.SchemaUtils.java

/**
 * An example on how to use this utility class.
 *//*w  w  w.  j  a v  a2 s  . c  o  m*/
public static void main(String[] args) {
    Schema schema = new Schema.SchemaBuilder().setSchemaName("testSchema")
            .addSingleValueDimension("dimension", FieldSpec.DataType.DOUBLE)
            .addMetric("metric", FieldSpec.DataType.INT).addTime("time", TimeUnit.DAYS, FieldSpec.DataType.INT)
            .build();
    System.out.println(postSchema("localhost", 8100, schema));
    Schema fetchedSchema = getSchema("localhost", 8100, "testSchema");
    Preconditions.checkNotNull(fetchedSchema);
    System.out.println(fetchedSchema);
    System.out.println(equalsIgnoreVersion(schema, fetchedSchema));
    System.out.println(deleteSchema("localhost", 8100, "testSchema"));
}

From source file:com.enonic.cms.core.SiteBasePathResolver.java

public static SiteBasePath resolveSiteBasePath(HttpServletRequest httpRequest, SiteKey sitekey) {
    Preconditions.checkNotNull(httpRequest);
    Preconditions.checkNotNull(sitekey);

    SiteBasePath siteBasePath;//ww w.jav  a 2 s  . co  m

    if (isInDebugMode()) {
        Path adminPath = new Path(DeploymentPathResolver.getAdminDeploymentPath(httpRequest));
        siteBasePath = new AdminSiteDebugBasePath(adminPath, sitekey);
    } else if (isInPreviewMode(httpRequest)) {
        Path adminPath = new Path(DeploymentPathResolver.getAdminDeploymentPath(httpRequest));
        siteBasePath = new AdminSitePreviewBasePath(adminPath, sitekey);
    } else {
        Path sitePrefixPath = new Path(DeploymentPathResolver.getSiteDeploymentPath(httpRequest));
        siteBasePath = new PortalSiteBasePath(sitePrefixPath, sitekey);
    }

    return siteBasePath;
}

From source file:works.chatterbox.hooks.ircchannels.channels.modes.Mode.java

static Mode fromString(@NotNull final String string) {
    Preconditions.checkNotNull(string);
    Preconditions.checkArgument(string.length() > 0, "Zero-length (or smaller) string given");
    final char modeChar = string.charAt(0);
    final Mode mode = IRCChannelsAPI.getInstance().getModesAPI().getModes().getMode(modeChar);
    Preconditions.checkState(mode != null, "No mode for " + modeChar);
    if (mode.getArgumentLength() > 0) {
        Preconditions.checkState(string.length() > 2, "No arguments for mode requiring arguments");
        final String[] args = string.substring(2).split(" ");
        Preconditions.checkState(args.length == mode.getArgumentLength(),
                "Invalid number of arguments. Expected " + mode.getArgumentLength() + ", received "
                        + args.length);//from  w  w w  . j  a v a 2s.c o  m
        final List<String> arguments = Arrays.stream(args).collect(Collectors.toList());
        //noinspection unchecked
        mode.setArguments(arguments);
    }
    return mode;
}