Search in sources :

Example 1 with Objects

use of java.util.Objects in project dropwizard by dropwizard.

the class DbRollbackCommand method run.

@Override
public void run(Namespace namespace, Liquibase liquibase) throws Exception {
    final String tag = namespace.getString("tag");
    final Integer count = namespace.getInt("count");
    final Date date = namespace.get("date");
    final Boolean dryRun = firstNonNull(namespace.getBoolean("dry-run"), false);
    final String context = getContext(namespace);
    if (Stream.of(tag, count, date).filter(Objects::nonNull).count() != 1) {
        throw new IllegalArgumentException("Must specify either a count, a tag, or a date.");
    }
    if (count != null) {
        if (dryRun) {
            liquibase.rollback(count, context, new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
        } else {
            liquibase.rollback(count, context);
        }
    } else if (tag != null) {
        if (dryRun) {
            liquibase.rollback(tag, context, new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
        } else {
            liquibase.rollback(tag, context);
        }
    } else {
        if (dryRun) {
            liquibase.rollback(date, context, new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
        } else {
            liquibase.rollback(date, context);
        }
    }
}
Also used : Objects(java.util.Objects) OutputStreamWriter(java.io.OutputStreamWriter) Date(java.util.Date)

Example 2 with Objects

use of java.util.Objects in project buck by facebook.

the class DefaultJavaLibrary method getBuildSteps.

/**
   * Building a java_library() rule entails compiling the .java files specified in the srcs
   * attribute. They are compiled into a directory under {@link BuckPaths#getScratchDir()}.
   */
@Override
public final ImmutableList<Step> getBuildSteps(BuildContext context, BuildableContext buildableContext) {
    ImmutableList.Builder<Step> steps = ImmutableList.builder();
    FluentIterable<JavaLibrary> declaredClasspathDeps = JavaLibraryClasspathProvider.getJavaLibraryDeps(getDepsForTransitiveClasspathEntries());
    // Always create the output directory, even if there are no .java files to compile because there
    // might be resources that need to be copied there.
    BuildTarget target = getBuildTarget();
    Path outputDirectory = getClassesDir(target, getProjectFilesystem());
    steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), outputDirectory));
    SuggestBuildRules suggestBuildRule = DefaultSuggestBuildRules.createSuggestBuildFunction(JAR_RESOLVER, context.getSourcePathResolver(), declaredClasspathDeps.toSet(), ImmutableSet.<JavaLibrary>builder().addAll(getTransitiveClasspathDeps()).add(this).build(), context.getActionGraph().getNodes());
    // We don't want to add these to the declared or transitive deps, since they're only used at
    // compile time.
    Collection<Path> provided = JavaLibraryClasspathProvider.getJavaLibraryDeps(providedDeps).transformAndConcat(JavaLibrary::getOutputClasspaths).filter(Objects::nonNull).transform(context.getSourcePathResolver()::getAbsolutePath).toSet();
    Iterable<Path> declaredClasspaths = declaredClasspathDeps.transformAndConcat(JavaLibrary::getOutputClasspaths).transform(context.getSourcePathResolver()::getAbsolutePath);
    // Only override the bootclasspath if this rule is supposed to compile Android code.
    ImmutableSortedSet<Path> declared = ImmutableSortedSet.<Path>naturalOrder().addAll(declaredClasspaths).addAll(additionalClasspathEntries.stream().map(e -> e.isLeft() ? context.getSourcePathResolver().getAbsolutePath(e.getLeft()) : checkIsAbsolute(e.getRight())).collect(MoreCollectors.toImmutableSet())).addAll(provided).build();
    // Make sure that this directory exists because ABI information will be written here.
    Step mkdir = new MakeCleanDirectoryStep(getProjectFilesystem(), getPathToAbiOutputDir());
    steps.add(mkdir);
    // If there are resources, then link them to the appropriate place in the classes directory.
    JavaPackageFinder finder = context.getJavaPackageFinder();
    if (resourcesRoot.isPresent()) {
        finder = new ResourcesRootPackageFinder(resourcesRoot.get(), finder);
    }
    steps.add(new CopyResourcesStep(getProjectFilesystem(), context.getSourcePathResolver(), ruleFinder, target, resources, outputDirectory, finder));
    steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), getOutputJarDirPath(target, getProjectFilesystem())));
    // into the built jar.
    if (!getJavaSrcs().isEmpty()) {
        ClassUsageFileWriter usedClassesFileWriter;
        if (trackClassUsage) {
            final Path usedClassesFilePath = getUsedClassesFilePath(getBuildTarget(), getProjectFilesystem());
            depFileOutputPath = getProjectFilesystem().getPathForRelativePath(usedClassesFilePath);
            usedClassesFileWriter = new DefaultClassUsageFileWriter(usedClassesFilePath);
            buildableContext.recordArtifact(usedClassesFilePath);
        } else {
            usedClassesFileWriter = NoOpClassUsageFileWriter.instance();
        }
        // This adds the javac command, along with any supporting commands.
        Path pathToSrcsList = BuildTargets.getGenPath(getProjectFilesystem(), getBuildTarget(), "__%s__srcs");
        steps.add(new MkdirStep(getProjectFilesystem(), pathToSrcsList.getParent()));
        Path scratchDir = BuildTargets.getGenPath(getProjectFilesystem(), target, "lib__%s____working_directory");
        steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), scratchDir));
        Optional<Path> workingDirectory = Optional.of(scratchDir);
        ImmutableSortedSet<Path> javaSrcs = getJavaSrcs().stream().map(context.getSourcePathResolver()::getRelativePath).collect(MoreCollectors.toImmutableSortedSet());
        compileStepFactory.createCompileToJarStep(context, javaSrcs, target, context.getSourcePathResolver(), ruleFinder, getProjectFilesystem(), declared, outputDirectory, workingDirectory, pathToSrcsList, Optional.of(suggestBuildRule), postprocessClassesCommands, ImmutableSortedSet.of(outputDirectory), /* mainClass */
        Optional.empty(), manifestFile.map(context.getSourcePathResolver()::getAbsolutePath), outputJar.get(), usedClassesFileWriter, /* output params */
        steps, buildableContext, classesToRemoveFromJar);
    }
    if (outputJar.isPresent()) {
        Path output = outputJar.get();
        // No source files, only resources
        if (getJavaSrcs().isEmpty()) {
            steps.add(new JarDirectoryStep(getProjectFilesystem(), output, ImmutableSortedSet.of(outputDirectory), /* mainClass */
            null, manifestFile.map(context.getSourcePathResolver()::getAbsolutePath).orElse(null), true, classesToRemoveFromJar));
        }
        buildableContext.recordArtifact(output);
    }
    JavaLibraryRules.addAccumulateClassNamesStep(this, buildableContext, context.getSourcePathResolver(), steps);
    return steps.build();
}
Also used : ArchiveMemberSourcePath(com.facebook.buck.rules.ArchiveMemberSourcePath) ClassPath(com.google.common.reflect.ClassPath) Path(java.nio.file.Path) SourcePath(com.facebook.buck.rules.SourcePath) ExplicitBuildTargetSourcePath(com.facebook.buck.rules.ExplicitBuildTargetSourcePath) ImmutableList(com.google.common.collect.ImmutableList) MkdirStep(com.facebook.buck.step.fs.MkdirStep) MkdirStep(com.facebook.buck.step.fs.MkdirStep) Step(com.facebook.buck.step.Step) MakeCleanDirectoryStep(com.facebook.buck.step.fs.MakeCleanDirectoryStep) JavaPackageFinder(com.facebook.buck.jvm.core.JavaPackageFinder) BuildTarget(com.facebook.buck.model.BuildTarget) Objects(java.util.Objects) MakeCleanDirectoryStep(com.facebook.buck.step.fs.MakeCleanDirectoryStep) SuggestBuildRules(com.facebook.buck.jvm.core.SuggestBuildRules)

Example 3 with Objects

use of java.util.Objects in project buck by facebook.

the class ProjectFilesystem method extractIgnorePaths.

private static ImmutableSet<PathOrGlobMatcher> extractIgnorePaths(final Path root, Config config, final BuckPaths buckPaths) {
    ImmutableSet.Builder<PathOrGlobMatcher> builder = ImmutableSet.builder();
    builder.add(new PathOrGlobMatcher(root, ".idea"));
    final String projectKey = "project";
    final String ignoreKey = "ignore";
    String buckdDirProperty = System.getProperty(BUCK_BUCKD_DIR_KEY, ".buckd");
    if (!Strings.isNullOrEmpty(buckdDirProperty)) {
        builder.add(new PathOrGlobMatcher(root, buckdDirProperty));
    }
    Path cacheDir = getCacheDir(root, config.getValue("cache", "dir"), buckPaths);
    builder.add(new PathOrGlobMatcher(cacheDir));
    builder.addAll(FluentIterable.from(config.getListWithoutComments(projectKey, ignoreKey)).transform(new Function<String, PathOrGlobMatcher>() {

        @Nullable
        @Override
        public PathOrGlobMatcher apply(String input) {
            // walks, so return null
            if (buckPaths.getBuckOut().toString().equals(input)) {
                //root.getFileSystem().getPathMatcher("glob:**");
                return null;
            }
            if (GLOB_CHARS.matcher(input).find()) {
                return new PathOrGlobMatcher(root.getFileSystem().getPathMatcher("glob:" + input), input);
            }
            return new PathOrGlobMatcher(root, input);
        }
    }).filter(Objects::nonNull).toList());
    return builder.build();
}
Also used : Path(java.nio.file.Path) Function(com.google.common.base.Function) ImmutableSet(com.google.common.collect.ImmutableSet) Objects(java.util.Objects)

Example 4 with Objects

use of java.util.Objects in project buck by facebook.

the class Resolver method getNewerVersionFile.

/**
   * @return {@link Path} to the file in {@code project} with filename consistent with the given
   * {@link Artifact}, but with a newer version. If no such file exists, {@link Optional#empty} is
   * returned. If multiple such files are present one with the newest version will be returned.
   */
@VisibleForTesting
Optional<Path> getNewerVersionFile(final Artifact artifactToDownload, Path project) throws IOException {
    final Version artifactToDownloadVersion;
    try {
        artifactToDownloadVersion = versionScheme.parseVersion(artifactToDownload.getVersion());
    } catch (InvalidVersionSpecificationException e) {
        throw new RuntimeException(e);
    }
    final Pattern versionExtractor = Pattern.compile(String.format(ARTIFACT_FILE_NAME_REGEX_FORMAT, artifactToDownload.getArtifactId(), VERSION_REGEX_GROUP, artifactToDownload.getExtension()));
    Iterable<Version> versionsPresent = FluentIterable.from(Files.newDirectoryStream(project)).transform(new Function<Path, Version>() {

        @Nullable
        @Override
        public Version apply(Path input) {
            Matcher matcher = versionExtractor.matcher(input.getFileName().toString());
            if (matcher.matches()) {
                try {
                    return versionScheme.parseVersion(matcher.group(1));
                } catch (InvalidVersionSpecificationException e) {
                    throw new RuntimeException(e);
                }
            } else {
                return null;
            }
        }
    }).filter(Objects::nonNull);
    List<Version> newestPresent = Ordering.natural().greatestOf(versionsPresent, 1);
    if (newestPresent.isEmpty() || newestPresent.get(0).compareTo(artifactToDownloadVersion) <= 0) {
        return Optional.empty();
    } else {
        return Optional.of(project.resolve(String.format(ARTIFACT_FILE_NAME_FORMAT, artifactToDownload.getArtifactId(), newestPresent.get(0).toString(), artifactToDownload.getExtension())));
    }
}
Also used : Path(java.nio.file.Path) Pattern(java.util.regex.Pattern) Function(com.google.common.base.Function) InvalidVersionSpecificationException(org.eclipse.aether.version.InvalidVersionSpecificationException) Version(org.eclipse.aether.version.Version) Matcher(java.util.regex.Matcher) Objects(java.util.Objects) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 5 with Objects

use of java.util.Objects in project buck by facebook.

the class PreDexMerge method addStepsForSplitDex.

private void addStepsForSplitDex(ImmutableList.Builder<Step> steps, BuildableContext buildableContext) {
    // Collect all of the DexWithClasses objects to use for merging.
    ImmutableMultimap.Builder<APKModule, DexWithClasses> dexFilesToMergeBuilder = ImmutableMultimap.builder();
    dexFilesToMergeBuilder.putAll(FluentIterable.from(preDexDeps.entries()).transform(input -> new AbstractMap.SimpleEntry<>(input.getKey(), DexWithClasses.TO_DEX_WITH_CLASSES.apply(input.getValue()))).filter(input -> input.getValue() != null).toSet());
    final SplitDexPaths paths = new SplitDexPaths();
    final ImmutableSet.Builder<Path> secondaryDexDirectories = ImmutableSet.builder();
    if (dexSplitMode.getDexStore() == DexStore.RAW) {
        // Raw classes*.dex files go in the top-level of the APK.
        secondaryDexDirectories.add(paths.jarfilesSubdir);
    } else {
        // Otherwise, we want to include the metadata and jars as assets.
        secondaryDexDirectories.add(paths.metadataDir);
        secondaryDexDirectories.add(paths.jarfilesDir);
    }
    //always add additional dex stores and metadata as assets
    secondaryDexDirectories.add(paths.additionalJarfilesDir);
    // Do not clear existing directory which might contain secondary dex files that are not
    // re-merged (since their contents did not change).
    steps.add(new MkdirStep(getProjectFilesystem(), paths.jarfilesSubdir));
    steps.add(new MkdirStep(getProjectFilesystem(), paths.additionalJarfilesSubdir));
    steps.add(new MkdirStep(getProjectFilesystem(), paths.successDir));
    steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), paths.metadataSubdir));
    steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), paths.scratchDir));
    buildableContext.addMetadata(SECONDARY_DEX_DIRECTORIES_KEY, secondaryDexDirectories.build().stream().map(Object::toString).collect(MoreCollectors.toImmutableList()));
    buildableContext.recordArtifact(primaryDexPath);
    buildableContext.recordArtifact(paths.jarfilesSubdir);
    buildableContext.recordArtifact(paths.metadataSubdir);
    buildableContext.recordArtifact(paths.successDir);
    buildableContext.recordArtifact(paths.additionalJarfilesSubdir);
    PreDexedFilesSorter preDexedFilesSorter = new PreDexedFilesSorter(Optional.ofNullable(DexWithClasses.TO_DEX_WITH_CLASSES.apply(dexForUberRDotJava)), dexFilesToMergeBuilder.build(), dexSplitMode.getPrimaryDexPatterns(), apkModuleGraph, paths.scratchDir, // to set the dex weight limit during pre-dex merging.
    dexSplitMode.getLinearAllocHardLimit(), dexSplitMode.getDexStore(), paths.jarfilesSubdir, paths.additionalJarfilesSubdir);
    final ImmutableMap<String, PreDexedFilesSorter.Result> sortResults = preDexedFilesSorter.sortIntoPrimaryAndSecondaryDexes(getProjectFilesystem(), steps);
    PreDexedFilesSorter.Result rootApkModuleResult = sortResults.get(APKModuleGraph.ROOT_APKMODULE_NAME);
    if (rootApkModuleResult == null) {
        throw new HumanReadableException("No classes found in primary or secondary dexes");
    }
    Multimap<Path, Path> aggregatedOutputToInputs = HashMultimap.create();
    ImmutableMap.Builder<Path, Sha1HashCode> dexInputHashesBuilder = ImmutableMap.builder();
    for (PreDexedFilesSorter.Result result : sortResults.values()) {
        if (!result.apkModule.equals(apkModuleGraph.getRootAPKModule())) {
            Path dexOutputPath = paths.additionalJarfilesSubdir.resolve(result.apkModule.getName());
            steps.add(new MkdirStep(getProjectFilesystem(), dexOutputPath));
        }
        aggregatedOutputToInputs.putAll(result.secondaryOutputToInputs);
        dexInputHashesBuilder.putAll(result.dexInputHashes);
    }
    final ImmutableMap<Path, Sha1HashCode> dexInputHashes = dexInputHashesBuilder.build();
    steps.add(new SmartDexingStep(getProjectFilesystem(), primaryDexPath, Suppliers.ofInstance(rootApkModuleResult.primaryDexInputs), Optional.of(paths.jarfilesSubdir), Optional.of(Suppliers.ofInstance(aggregatedOutputToInputs)), () -> dexInputHashes, paths.successDir, DX_MERGE_OPTIONS, dxExecutorService, xzCompressionLevel, dxMaxHeapSize));
    // Record the primary dex SHA1 so exopackage apks can use it to compute their ABI keys.
    // Single dex apks cannot be exopackages, so they will never need ABI keys.
    steps.add(new RecordFileSha1Step(getProjectFilesystem(), primaryDexPath, PRIMARY_DEX_HASH_KEY, buildableContext));
    for (PreDexedFilesSorter.Result result : sortResults.values()) {
        if (!result.apkModule.equals(apkModuleGraph.getRootAPKModule())) {
            Path dexMetadataOutputPath = paths.additionalJarfilesSubdir.resolve(result.apkModule.getName()).resolve("metadata.txt");
            addMetadataWriteStep(result, steps, dexMetadataOutputPath);
        }
    }
    addMetadataWriteStep(rootApkModuleResult, steps, paths.metadataFile);
}
Also used : Iterables(com.google.common.collect.Iterables) Step(com.facebook.buck.step.Step) SourcePath(com.facebook.buck.rules.SourcePath) Multimap(com.google.common.collect.Multimap) BuildOutput(com.facebook.buck.android.PreDexMerge.BuildOutput) MkdirStep(com.facebook.buck.step.fs.MkdirStep) AbstractExecutionStep(com.facebook.buck.step.AbstractExecutionStep) ExecutionContext(com.facebook.buck.step.ExecutionContext) HashMultimap(com.google.common.collect.HashMultimap) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) FluentIterable(com.google.common.collect.FluentIterable) Map(java.util.Map) Suppliers(com.google.common.base.Suppliers) BuildOutputInitializer(com.facebook.buck.rules.BuildOutputInitializer) ImmutableMultimap(com.google.common.collect.ImmutableMultimap) BuildRuleParams(com.facebook.buck.rules.BuildRuleParams) Path(java.nio.file.Path) EnumSet(java.util.EnumSet) Nullable(javax.annotation.Nullable) MoreCollectors(com.facebook.buck.util.MoreCollectors) Function(com.google.common.base.Function) ImmutableSet(com.google.common.collect.ImmutableSet) AddToRuleKey(com.facebook.buck.rules.AddToRuleKey) MakeCleanDirectoryStep(com.facebook.buck.step.fs.MakeCleanDirectoryStep) ImmutableMap(com.google.common.collect.ImmutableMap) InitializableFromDisk(com.facebook.buck.rules.InitializableFromDisk) BuildableContext(com.facebook.buck.rules.BuildableContext) IOException(java.io.IOException) HumanReadableException(com.facebook.buck.util.HumanReadableException) OnDiskBuildInfo(com.facebook.buck.rules.OnDiskBuildInfo) AbstractBuildRule(com.facebook.buck.rules.AbstractBuildRule) Objects(java.util.Objects) AbstractMap(java.util.AbstractMap) List(java.util.List) Paths(java.nio.file.Paths) RecordFileSha1Step(com.facebook.buck.rules.RecordFileSha1Step) Sha1HashCode(com.facebook.buck.util.sha1.Sha1HashCode) BuildContext(com.facebook.buck.rules.BuildContext) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) BuildTargets(com.facebook.buck.model.BuildTargets) StepExecutionResult(com.facebook.buck.step.StepExecutionResult) Collections(java.util.Collections) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) MkdirStep(com.facebook.buck.step.fs.MkdirStep) StepExecutionResult(com.facebook.buck.step.StepExecutionResult) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMultimap(com.google.common.collect.ImmutableMultimap) RecordFileSha1Step(com.facebook.buck.rules.RecordFileSha1Step) SourcePath(com.facebook.buck.rules.SourcePath) Path(java.nio.file.Path) ImmutableMap(com.google.common.collect.ImmutableMap) HumanReadableException(com.facebook.buck.util.HumanReadableException) Sha1HashCode(com.facebook.buck.util.sha1.Sha1HashCode) MakeCleanDirectoryStep(com.facebook.buck.step.fs.MakeCleanDirectoryStep)

Aggregations

Objects (java.util.Objects)55 List (java.util.List)29 Map (java.util.Map)24 Collectors (java.util.stream.Collectors)22 ArrayList (java.util.ArrayList)20 Set (java.util.Set)19 Optional (java.util.Optional)16 IOException (java.io.IOException)15 HashMap (java.util.HashMap)14 Collections (java.util.Collections)13 HashSet (java.util.HashSet)10 ImmutableSet (com.google.common.collect.ImmutableSet)9 Result (ddf.catalog.data.Result)9 Stream (java.util.stream.Stream)9 Metacard (ddf.catalog.data.Metacard)8 TimeUnit (java.util.concurrent.TimeUnit)8 LoggerFactory (org.slf4j.LoggerFactory)8 QueryImpl (ddf.catalog.operation.impl.QueryImpl)7 Path (java.nio.file.Path)7 Logger (org.slf4j.Logger)7