8d1941169e020261eb5a02399ec2b6f1215b8693
[sdc.git] /
1 /*
2  * Copyright © 2018 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on a "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.sdc.onboarding;
18
19 import static org.openecomp.sdc.onboarding.Constants.CHECKSUM;
20 import static org.openecomp.sdc.onboarding.Constants.COLON;
21 import static org.openecomp.sdc.onboarding.Constants.DOT;
22 import static org.openecomp.sdc.onboarding.Constants.JAR;
23 import static org.openecomp.sdc.onboarding.Constants.JAVA_EXT;
24 import static org.openecomp.sdc.onboarding.Constants.SHA1;
25 import static org.openecomp.sdc.onboarding.Constants.UNICORN;
26
27 import java.io.ByteArrayInputStream;
28 import java.io.File;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.ObjectInputStream;
32 import java.io.UncheckedIOException;
33 import java.net.URI;
34 import java.net.URISyntaxException;
35 import java.nio.charset.StandardCharsets;
36 import java.nio.file.Files;
37 import java.nio.file.Path;
38 import java.nio.file.Paths;
39 import java.security.MessageDigest;
40 import java.security.NoSuchAlgorithmException;
41 import java.util.Arrays;
42 import java.util.HashMap;
43 import java.util.List;
44 import java.util.Map;
45 import java.util.Optional;
46 import java.util.concurrent.ForkJoinPool;
47 import java.util.concurrent.RecursiveTask;
48 import java.util.jar.JarEntry;
49 import java.util.jar.JarInputStream;
50 import java.util.logging.Level;
51 import java.util.logging.Logger;
52 import java.util.stream.Stream;
53 import org.apache.maven.plugin.MojoFailureException;
54 import org.apache.maven.project.MavenProject;
55
56 class BuildHelper {
57
58
59     private static final Map<String, String> STORE = new HashMap<>();
60     private static final Logger LOG = Logger.getAnonymousLogger();
61
62     private BuildHelper() {
63         // do not remove.
64     }
65
66     static String getSnapshotSignature(File snapshotFile, String moduleCoordinate, String version) {
67         String key = moduleCoordinate + ":" + version;
68         String signature = STORE.get(key);
69         if (signature != null) {
70             return signature;
71         }
72         try {
73             signature = new String(fetchSnapshotSignature(snapshotFile, version));
74             if (version.equals(signature)) {
75                 signature = getSha1For(snapshotFile, Paths.get(snapshotFile.getParentFile().getAbsolutePath(),
76                         moduleCoordinate.substring(moduleCoordinate.indexOf(':') + 1) + "-" + version + DOT + JAR + DOT
77                                 + SHA1).toFile());
78             }
79             STORE.put(key, signature);
80             return signature;
81         } catch (IOException | NoSuchAlgorithmException e) {
82             LOG.log(Level.FINE, e.getMessage(), e);
83             return version;
84         }
85
86     }
87
88     private static String getSha1For(File file, File signatureFile) throws IOException, NoSuchAlgorithmException {
89         if (signatureFile.exists()) {
90             return new String(Files.readAllBytes(signatureFile.toPath()));
91         }
92         return getSourceChecksum(Files.readAllBytes(file.toPath()), SHA1);
93     }
94
95     static long getChecksum(File file, String fileType) {
96         try {
97             return readSources(file, fileType).hashCode();
98         } catch (IOException e) {
99             throw new UncheckedIOException(e);
100         }
101     }
102
103     static String getSourceChecksum(String data, String hashType) throws NoSuchAlgorithmException {
104         return getSourceChecksum(data.getBytes(), hashType);
105     }
106
107     static String getSourceChecksum(byte[] data, String hashType) throws NoSuchAlgorithmException {
108         MessageDigest md = MessageDigest.getInstance(hashType);
109         md.update(data);
110         byte[] hashBytes = md.digest();
111
112         StringBuilder buffer = new StringBuilder();
113         for (byte hashByte : hashBytes) {
114             buffer.append(Integer.toString((hashByte & 0xff) + 0x100, 16).substring(1));
115         }
116         return buffer.toString();
117     }
118
119
120     private static Map<String, List<String>> readSources(File file, String fileType) throws IOException {
121         Map<String, List<String>> source = new HashMap<>();
122
123         if (!file.exists()) {
124             return source;
125         }
126
127         try (Stream<Path> pathStream = Files.walk(Paths.get(file.getAbsolutePath()))) {
128             File[] selectedFiles = pathStream.filter(
129                     JAVA_EXT.equals(fileType) ? BuildHelper::isRegularJavaFile : Files::isRegularFile)
130                                            .map(Path::toFile).toArray(File[]::new);
131             source.putAll(ForkJoinPool.commonPool()
132                                   .invoke(new FileReadTask(selectedFiles, file.getAbsolutePath())));
133             return source;
134         }
135     }
136
137     private static boolean isRegularJavaFile(Path path) {
138         File file = path.toFile();
139         return file.isFile() && file.getName().endsWith(JAVA_EXT);
140     }
141
142     private static class FileReadTask extends RecursiveTask<Map<String, List<String>>> {
143
144         private final Map<String, List<String>> store = new HashMap<>();
145         final File[] files;
146         final String pathPrefix;
147         private static final int MAX_FILES = 10;
148
149         FileReadTask(File[] files, String pathPrefix) {
150             this.files = files;
151             this.pathPrefix = pathPrefix;
152         }
153
154         private static List<String> getData(File file) throws IOException {
155             List<String> coll = Files.readAllLines(file.toPath(), StandardCharsets.ISO_8859_1);
156             if (file.getAbsolutePath().contains(File.separator + "generated-sources" + File.separator)) {
157                 coll.removeIf(s -> s == null || s.trim().startsWith("/") || s.trim().startsWith("*"));
158             }
159             return coll;
160         }
161
162
163         @Override
164         protected Map<String, List<String>> compute() {
165             if (files.length > MAX_FILES) {
166                 FileReadTask task1 = new FileReadTask(Arrays.copyOfRange(files, 0, files.length / 2), pathPrefix);
167                 FileReadTask task2 =
168                         new FileReadTask(Arrays.copyOfRange(files, files.length / 2, files.length), pathPrefix);
169                 task1.fork();
170                 task2.fork();
171                 store.putAll(task1.join());
172                 store.putAll(task2.join());
173             } else {
174                 for (File toRead : files) {
175                     try {
176                         store.put(toRead.getAbsolutePath().substring(pathPrefix.length())
177                                         .replace(File.separatorChar, '.'), getData(toRead));
178                     } catch (IOException e) {
179                         throw new UncheckedIOException(e);
180                     }
181                 }
182             }
183
184             return store;
185         }
186     }
187
188     static Optional<String> getArtifactPathInLocalRepo(String repoPath, MavenProject project, byte[] sourceChecksum)
189             throws MojoFailureException {
190         STORE.put(project.getGroupId() + COLON + project.getArtifactId() + COLON + project.getVersion(),
191                 new String(sourceChecksum));
192         URI uri;
193         try {
194             uri = new URI(repoPath + (project.getGroupId().replace('.', '/')) + '/' + project.getArtifactId() + '/'
195                                   + project.getVersion());
196         } catch (URISyntaxException e) {
197             throw new MojoFailureException(e.getMessage(), e);
198         }
199         File f = new File(uri);
200         File[] list = f.listFiles(t -> t.getName().equals(project.getArtifactId() + "-" + project.getVersion() + "."
201                                                                   + project.getPackaging()));
202         if (list != null && list.length > 0) {
203             try {
204                 if (Arrays.equals(sourceChecksum, fetchSnapshotSignature(list[0], project.getVersion()))) {
205                     return Optional.of(list[0].getAbsolutePath());
206                 }
207             } catch (IOException e) {
208                 throw new UncheckedIOException(e);
209             }
210         }
211         return Optional.empty();
212     }
213
214     private static byte[] fetchSnapshotSignature(File file, String version) throws IOException {
215
216         byte[] data = Files.readAllBytes(file.toPath());
217         try (ByteArrayInputStream byteInputStream = new ByteArrayInputStream(data);
218                 JarInputStream jarInputStream = new JarInputStream(byteInputStream)) {
219
220             JarEntry entry;
221             while ((entry = jarInputStream.getNextJarEntry()) != null) {
222                 if (entry.getName().endsWith(UNICORN + DOT + CHECKSUM)) {
223                     byte[] sigStore = new byte[1024];
224                     return new String(sigStore, 0, jarInputStream.read(sigStore, 0, 1024)).getBytes();
225                 }
226             }
227         }
228         return version.getBytes();
229     }
230
231     static <T> Optional<T> readState(String fileName, Class<T> clazz) {
232
233         try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
234                 ObjectInputStream ois = new ObjectInputStream(is)) {
235             return Optional.of(clazz.cast(ois.readObject()));
236         } catch (Exception e) {
237             LOG.log(Level.FINE, e.getMessage(), e);
238             return Optional.empty();
239         }
240     }
241
242 }