AbstractInstallableFile.java

  1. /*
  2.  * #%L
  3.  * wcm.io
  4.  * %%
  5.  * Copyright (C) 2022 wcm.io
  6.  * %%
  7.  * Licensed under the Apache License, Version 2.0 (the "License");
  8.  * you may not use this file except in compliance with the License.
  9.  * You may obtain a copy of the License at
  10.  *
  11.  *      http://www.apache.org/licenses/LICENSE-2.0
  12.  *
  13.  * Unless required by applicable law or agreed to in writing, software
  14.  * distributed under the License is distributed on an "AS IS" BASIS,
  15.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16.  * See the License for the specific language governing permissions and
  17.  * limitations under the License.
  18.  * #L%
  19.  */
  20. package io.wcm.devops.conga.plugins.aem.maven.model;

  21. import java.io.File;
  22. import java.io.IOException;
  23. import java.util.Collection;
  24. import java.util.LinkedHashSet;
  25. import java.util.Set;

  26. import org.jetbrains.annotations.NotNull;

  27. import com.google.common.hash.HashCode;
  28. import com.google.common.hash.Hashing;
  29. import com.google.common.io.Files;

  30. import io.wcm.devops.conga.generator.util.FileUtil;

  31. /**
  32.  * Describes an installable file with a set of run modes and (lazily evaluated) hash code.
  33.  */
  34. public abstract class AbstractInstallableFile implements InstallableFile {

  35.   private final File file;
  36.   private final Set<String> variants;
  37.   private HashCode hashCode;

  38.   protected AbstractInstallableFile(File file, Collection<String> variants) {
  39.     this.file = file;
  40.     this.variants = new LinkedHashSet<>(variants);
  41.   }

  42.   @Override
  43.   @NotNull
  44.   public File getFile() {
  45.     return file;
  46.   }

  47.   @Override
  48.   @NotNull
  49.   public Set<String> getVariants() {
  50.     return variants;
  51.   }

  52.   @Override
  53.   @NotNull
  54.   public HashCode getHashCode() {
  55.     if (this.hashCode == null) {
  56.       this.hashCode = getHashCode(file);
  57.     }
  58.     return this.hashCode;
  59.   }

  60.   @Override
  61.   public String toString() {
  62.     return file.toString();
  63.   }

  64.   private static HashCode getHashCode(File file) {
  65.     try {
  66.       return Files.asByteSource(file).hash(Hashing.sha256());
  67.     }
  68.     catch (IOException ex) {
  69.       throw new IllegalArgumentException("Unable to get hashcode for " + FileUtil.getCanonicalPath(file), ex);
  70.     }
  71.   }

  72. }