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 org.apache.maven.plugin.MojoFailureException;
20 import org.apache.maven.project.MavenProject;
22 import java.io.ByteArrayInputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.ObjectInputStream;
27 import java.io.UncheckedIOException;
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;
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;
48 import static org.openecomp.sdc.onboarding.Constants.*;
53 private static Map<String, String> store = new HashMap<>();
55 private BuildHelper() {
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) {
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
72 store.put(key, signature);
74 } catch (IOException | NoSuchAlgorithmException e) {
80 private static String getSHA1For(File file, File signatureFile) throws IOException, NoSuchAlgorithmException {
81 if (signatureFile.exists()) {
82 return new String(Files.readAllBytes(signatureFile.toPath()));
84 return getSourceChecksum(Files.readAllBytes(file.toPath()), SHA1);
87 static long getChecksum(File file, String fileType) {
89 return readSources(file, fileType).hashCode();
90 } catch (IOException e) {
91 throw new UncheckedIOException(e);
95 static String getSourceChecksum(String data, String hashType) throws NoSuchAlgorithmException {
96 return getSourceChecksum(data.getBytes(), hashType);
99 static String getSourceChecksum(byte[] data, String hashType) throws NoSuchAlgorithmException {
100 MessageDigest md = MessageDigest.getInstance(hashType);
102 byte[] hashBytes = md.digest();
104 StringBuilder buffer = new StringBuilder();
105 for (byte hashByte : hashBytes) {
106 buffer.append(Integer.toString((hashByte & 0xff) + 0x100, 16).substring(1));
108 return buffer.toString();
112 private static Map<String, List<String>> readSources(File file, String fileType) throws IOException {
113 Map<String, List<String>> source = new HashMap<>();
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())));
124 private static boolean isRegularJavaFile(Path path) {
125 File file = path.toFile();
126 return file.isFile() && file.getName().endsWith(JAVA_EXT);
129 private static class FileReadTask extends RecursiveTask<Map<String, List<String>>> {
131 private Map<String, List<String>> store = new HashMap<>();
134 private static final int MAX_FILES = 10;
136 FileReadTask(File[] files, String pathPrefix) {
138 this.pathPrefix = pathPrefix;
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("*")) {
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);
161 new FileReadTask(Arrays.copyOfRange(files, files.length / 2, files.length), pathPrefix);
164 store.putAll(task1.join());
165 store.putAll(task2.join());
167 for (File toRead : files) {
169 store.put(toRead.getAbsolutePath().substring(pathPrefix.length())
170 .replace(File.separatorChar, '.'), getData(toRead));
171 } catch (IOException e) {
172 throw new UncheckedIOException(e);
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));
187 uri = new URI(repoPath + (project.getGroupId().replace('.', '/')) + '/' + project.getArtifactId() + '/'
188 + project.getVersion());
189 } catch (URISyntaxException e) {
190 throw new MojoFailureException(e.getMessage(), e);
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) {
197 if (Arrays.equals(sourceChecksum, fetchSnapshotSignature(list[0], project.getVersion()))) {
198 return Optional.of(list[0].getAbsolutePath());
200 } catch (IOException e) {
201 throw new UncheckedIOException(e);
204 return Optional.empty();
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();
219 return version.getBytes();
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();