View Javadoc
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  
22  import java.io.File;
23  import java.io.IOException;
24  import java.util.Collection;
25  import java.util.LinkedHashSet;
26  import java.util.Set;
27  
28  import org.jetbrains.annotations.NotNull;
29  
30  import com.google.common.hash.HashCode;
31  import com.google.common.hash.Hashing;
32  import com.google.common.io.Files;
33  
34  import io.wcm.devops.conga.generator.util.FileUtil;
35  
36  /**
37   * Describes an installable file with a set of run modes and (lazily evaluated) hash code.
38   */
39  public abstract class AbstractInstallableFile implements InstallableFile {
40  
41    private final File file;
42    private final Set<String> variants;
43    private HashCode hashCode;
44  
45    protected AbstractInstallableFile(File file, Collection<String> variants) {
46      this.file = file;
47      this.variants = new LinkedHashSet<>(variants);
48    }
49  
50    @Override
51    @NotNull
52    public File getFile() {
53      return file;
54    }
55  
56    @Override
57    @NotNull
58    public Set<String> getVariants() {
59      return variants;
60    }
61  
62    @Override
63    @NotNull
64    public HashCode getHashCode() {
65      if (this.hashCode == null) {
66        this.hashCode = getHashCode(file);
67      }
68      return this.hashCode;
69    }
70  
71    @Override
72    public String toString() {
73      return file.toString();
74    }
75  
76    private static HashCode getHashCode(File file) {
77      try {
78        return Files.asByteSource(file).hash(Hashing.sha256());
79      }
80      catch (IOException ex) {
81        throw new IllegalArgumentException("Unable to get hashcode for " + FileUtil.getCanonicalPath(file), ex);
82      }
83    }
84  
85  }