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