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