re base code
[sdc.git] / openecomp-be / tools / compile-helper-plugin / src / main / java / org / openecomp / sdc / onboarding / BuildHelper.java
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 org.apache.maven.plugin.MojoFailureException;
20 import org.apache.maven.project.MavenProject;
21
22 import java.io.ByteArrayInputStream;
23 import java.io.File;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.ObjectInputStream;
27 import java.io.UncheckedIOException;
28 import java.net.URI;
29 import java.net.URISyntaxException;
30 import java.nio.charset.StandardCharsets;
31 import java.nio.file.Files;
32 import java.nio.file.Path;
33 import java.nio.file.Paths;
34 import java.security.MessageDigest;
35 import java.security.NoSuchAlgorithmException;
36 import java.util.Arrays;
37 import java.util.HashMap;
38 import java.util.Iterator;
39 import java.util.List;
40 import java.util.Map;
41 import java.util.Optional;
42 import java.util.concurrent.ForkJoinPool;
43 import java.util.concurrent.RecursiveTask;
44 import java.util.jar.JarEntry;
45 import java.util.jar.JarInputStream;
46 import java.util.stream.Collectors;
47
48 import static org.openecomp.sdc.onboarding.Constants.*;
49
50 class BuildHelper {
51
52
53     private static Map<String, String> store = new HashMap<>();
54
55     private BuildHelper() {
56         // donot remove.
57     }
58
59     static String getSnapshotSignature(File snapshotFile, String moduleCoordinate, String version) {
60         String key = moduleCoordinate + ":" + version;
61         String signature = store.get(key);
62         if (signature != null) {
63             return signature;
64         }
65         try {
66             signature = new String(fetchSnapshotSignature(snapshotFile, version));
67             if (version.equals(signature)) {
68                 signature = getSHA1For(snapshotFile, Paths.get(snapshotFile.getParentFile().getAbsolutePath(),
69                         moduleCoordinate.substring(moduleCoordinate.indexOf(':') + 1) + "-" + version + DOT + JAR + DOT
70                                 + SHA1).toFile());
71             }
72             store.put(key, signature);
73             return signature;
74         } catch (IOException | NoSuchAlgorithmException e) {
75             return version;
76         }
77
78     }
79
80     private static String getSHA1For(File file, File signatureFile) throws IOException, NoSuchAlgorithmException {
81         if (signatureFile.exists()) {
82             return new String(Files.readAllBytes(signatureFile.toPath()));
83         }
84         return getSourceChecksum(Files.readAllBytes(file.toPath()), SHA1);
85     }
86
87     static long getChecksum(File file, String fileType) {
88         try {
89             return readSources(file, fileType).hashCode();
90         } catch (IOException e) {
91             throw new UncheckedIOException(e);
92         }
93     }
94
95     static String getSourceChecksum(String data, String hashType) throws NoSuchAlgorithmException {
96         return getSourceChecksum(data.getBytes(), hashType);
97     }
98
99     static String getSourceChecksum(byte[] data, String hashType) throws NoSuchAlgorithmException {
100         MessageDigest md = MessageDigest.getInstance(hashType);
101         md.update(data);
102         byte[] hashBytes = md.digest();
103
104         StringBuilder buffer = new StringBuilder();
105         for (byte hashByte : hashBytes) {
106             buffer.append(Integer.toString((hashByte & 0xff) + 0x100, 16).substring(1));
107         }
108         return buffer.toString();
109     }
110
111
112     private static Map<String, List<String>> readSources(File file, String fileType) throws IOException {
113         Map<String, List<String>> source = new HashMap<>();
114         if (file.exists()) {
115             List<File> list = Files.walk(Paths.get(file.getAbsolutePath()))
116                                    .filter(JAVA_EXT.equals(fileType) ? BuildHelper::isRegularJavaFile :
117                                                    Files::isRegularFile).map(Path::toFile).collect(Collectors.toList());
118             source.putAll(ForkJoinPool.commonPool()
119                                       .invoke(new FileReadTask(list.toArray(new File[0]), file.getAbsolutePath())));
120         }
121         return source;
122     }
123
124     private static boolean isRegularJavaFile(Path path) {
125         File file = path.toFile();
126         return file.isFile() && file.getName().endsWith(JAVA_EXT);
127     }
128
129     private static class FileReadTask extends RecursiveTask<Map<String, List<String>>> {
130
131         private Map<String, List<String>> store = new HashMap<>();
132         File[] files;
133         String pathPrefix;
134         private static final int MAX_FILES = 10;
135
136         FileReadTask(File[] files, String pathPrefix) {
137             this.files = files;
138             this.pathPrefix = pathPrefix;
139         }
140
141         private static List<String> getData(File file) throws IOException {
142             List<String> coll = Files.readAllLines(file.toPath(), StandardCharsets.ISO_8859_1);
143             if (file.getAbsolutePath().contains(File.separator + "generated-sources" + File.separator)) {
144                 Iterator<String> itr = coll.iterator();
145                 while (itr.hasNext()) {
146                     String s = itr.next();
147                     if (s == null || s.trim().startsWith("/") || s.trim().startsWith("*")) {
148                         itr.remove();
149                     }
150                 }
151             }
152             return coll;
153         }
154
155
156         @Override
157         protected Map<String, List<String>> compute() {
158             if (files.length > MAX_FILES) {
159                 FileReadTask task1 = new FileReadTask(Arrays.copyOfRange(files, 0, files.length / 2), pathPrefix);
160                 FileReadTask task2 =
161                         new FileReadTask(Arrays.copyOfRange(files, files.length / 2, files.length), pathPrefix);
162                 task1.fork();
163                 task2.fork();
164                 store.putAll(task1.join());
165                 store.putAll(task2.join());
166             } else {
167                 for (File toRead : files) {
168                     try {
169                         store.put(toRead.getAbsolutePath().substring(pathPrefix.length())
170                                         .replace(File.separatorChar, '.'), getData(toRead));
171                     } catch (IOException e) {
172                         throw new UncheckedIOException(e);
173                     }
174                 }
175             }
176
177             return store;
178         }
179     }
180
181     static Optional<String> getArtifactPathInLocalRepo(String repoPath, MavenProject project, byte[] sourceChecksum)
182             throws MojoFailureException {
183         store.put(project.getGroupId() + COLON + project.getArtifactId() + COLON + project.getVersion(),
184                 new String(sourceChecksum));
185         URI uri = null;
186         try {
187             uri = new URI(repoPath + (project.getGroupId().replace('.', '/')) + '/' + project.getArtifactId() + '/'
188                                   + project.getVersion());
189         } catch (URISyntaxException e) {
190             throw new MojoFailureException(e.getMessage(), e);
191         }
192         File f = new File(uri);
193         File[] list = f.listFiles(t -> t.getName().equals(project.getArtifactId() + "-" + project.getVersion() + "."
194                                                                   + project.getPackaging()));
195         if (list != null && list.length > 0) {
196             try {
197                 if (Arrays.equals(sourceChecksum, fetchSnapshotSignature(list[0], project.getVersion()))) {
198                     return Optional.of(list[0].getAbsolutePath());
199                 }
200             } catch (IOException e) {
201                 throw new UncheckedIOException(e);
202             }
203         }
204         return Optional.empty();
205     }
206
207     private static byte[] fetchSnapshotSignature(File file, String version) throws IOException {
208         byte[] data = Files.readAllBytes(file.toPath());
209         try (ByteArrayInputStream bais = new ByteArrayInputStream(data);
210              JarInputStream jis = new JarInputStream(bais)) {
211             JarEntry entry = null;
212             while ((entry = jis.getNextJarEntry()) != null) {
213                 if (entry.getName().endsWith(UNICORN + DOT + CHECKSUM)) {
214                     byte[] sigStore = new byte[1024];
215                     return new String(sigStore, 0, jis.read(sigStore, 0, 1024)).getBytes();
216                 }
217             }
218         }
219         return version.getBytes();
220     }
221
222     static <T> Optional<T> readState(String fileName, Class<T> clazz) {
223         try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
224              ObjectInputStream ois = new ObjectInputStream(is)) {
225             return Optional.of(clazz.cast(ois.readObject()));
226         } catch (Exception ignored) {
227             return Optional.empty();
228         }
229     }
230
231 }