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