2 * Copyright © 2018 European Support Limited
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.openecomp.sdc.onboarding;
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;
27 import java.io.ByteArrayInputStream;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.ObjectInputStream;
32 import java.io.UncheckedIOException;
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;
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;
58 private static Map<String, String> store = new HashMap<>();
60 private BuildHelper() {
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) {
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
77 store.put(key, signature);
79 } catch (IOException | NoSuchAlgorithmException e) {
85 private static String getSHA1For(File file, File signatureFile) throws IOException, NoSuchAlgorithmException {
86 if (signatureFile.exists()) {
87 return new String(Files.readAllBytes(signatureFile.toPath()));
89 return getSourceChecksum(Files.readAllBytes(file.toPath()), SHA1);
92 static long getChecksum(File file, String fileType) {
94 return readSources(file, fileType).hashCode();
95 } catch (IOException e) {
96 throw new UncheckedIOException(e);
100 static String getSourceChecksum(String data, String hashType) throws NoSuchAlgorithmException {
101 return getSourceChecksum(data.getBytes(), hashType);
104 static String getSourceChecksum(byte[] data, String hashType) throws NoSuchAlgorithmException {
105 MessageDigest md = MessageDigest.getInstance(hashType);
107 byte[] hashBytes = md.digest();
109 StringBuilder buffer = new StringBuilder();
110 for (byte hashByte : hashBytes) {
111 buffer.append(Integer.toString((hashByte & 0xff) + 0x100, 16).substring(1));
113 return buffer.toString();
117 private static Map<String, List<String>> readSources(File file, String fileType) throws IOException {
118 Map<String, List<String>> source = new HashMap<>();
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())));
129 private static boolean isRegularJavaFile(Path path) {
130 File file = path.toFile();
131 return file.isFile() && file.getName().endsWith(JAVA_EXT);
134 private static class FileReadTask extends RecursiveTask<Map<String, List<String>>> {
136 private Map<String, List<String>> store = new HashMap<>();
139 private static final int MAX_FILES = 10;
141 FileReadTask(File[] files, String pathPrefix) {
143 this.pathPrefix = pathPrefix;
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("*")) {
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);
166 new FileReadTask(Arrays.copyOfRange(files, files.length / 2, files.length), pathPrefix);
169 store.putAll(task1.join());
170 store.putAll(task2.join());
172 for (File toRead : files) {
174 store.put(toRead.getAbsolutePath().substring(pathPrefix.length())
175 .replace(File.separatorChar, '.'), getData(toRead));
176 } catch (IOException e) {
177 throw new UncheckedIOException(e);
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));
192 uri = new URI(repoPath + (project.getGroupId().replace('.', '/')) + '/' + project.getArtifactId() + '/'
193 + project.getVersion());
194 } catch (URISyntaxException e) {
195 throw new MojoFailureException(e.getMessage(), e);
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) {
202 if (Arrays.equals(sourceChecksum, fetchSnapshotSignature(list[0], project.getVersion()))) {
203 return Optional.of(list[0].getAbsolutePath());
205 } catch (IOException e) {
206 throw new UncheckedIOException(e);
209 return Optional.empty();
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();
224 return version.getBytes();
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();