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.List;
45 import java.util.Optional;
46 import java.util.concurrent.ForkJoinPool;
47 import java.util.concurrent.RecursiveTask;
48 import java.util.jar.JarEntry;
49 import java.util.jar.JarInputStream;
50 import java.util.logging.Level;
51 import java.util.logging.Logger;
52 import java.util.stream.Stream;
53 import org.apache.maven.plugin.MojoFailureException;
54 import org.apache.maven.project.MavenProject;
59 private static final Map<String, String> STORE = new HashMap<>();
60 private static final Logger LOG = Logger.getAnonymousLogger();
62 private BuildHelper() {
66 static String getSnapshotSignature(File snapshotFile, String moduleCoordinate, String version) {
67 String key = moduleCoordinate + ":" + version;
68 String signature = STORE.get(key);
69 if (signature != null) {
73 signature = new String(fetchSnapshotSignature(snapshotFile, version));
74 if (version.equals(signature)) {
75 signature = getSha1For(snapshotFile, Paths.get(snapshotFile.getParentFile().getAbsolutePath(),
76 moduleCoordinate.substring(moduleCoordinate.indexOf(':') + 1) + "-" + version + DOT + JAR + DOT
79 STORE.put(key, signature);
81 } catch (IOException | NoSuchAlgorithmException e) {
82 LOG.log(Level.FINE, e.getMessage(), e);
88 private static String getSha1For(File file, File signatureFile) throws IOException, NoSuchAlgorithmException {
89 if (signatureFile.exists()) {
90 return new String(Files.readAllBytes(signatureFile.toPath()));
92 return getSourceChecksum(Files.readAllBytes(file.toPath()), SHA1);
95 static long getChecksum(File file, String fileType) {
97 return readSources(file, fileType).hashCode();
98 } catch (IOException e) {
99 throw new UncheckedIOException(e);
103 static String getSourceChecksum(String data, String hashType) throws NoSuchAlgorithmException {
104 return getSourceChecksum(data.getBytes(), hashType);
107 static String getSourceChecksum(byte[] data, String hashType) throws NoSuchAlgorithmException {
108 MessageDigest md = MessageDigest.getInstance(hashType);
110 byte[] hashBytes = md.digest();
112 StringBuilder buffer = new StringBuilder();
113 for (byte hashByte : hashBytes) {
114 buffer.append(Integer.toString((hashByte & 0xff) + 0x100, 16).substring(1));
116 return buffer.toString();
120 private static Map<String, List<String>> readSources(File file, String fileType) throws IOException {
121 Map<String, List<String>> source = new HashMap<>();
123 if (!file.exists()) {
127 try (Stream<Path> pathStream = Files.walk(Paths.get(file.getAbsolutePath()))) {
128 File[] selectedFiles = pathStream.filter(
129 JAVA_EXT.equals(fileType) ? BuildHelper::isRegularJavaFile : Files::isRegularFile)
130 .map(Path::toFile).toArray(File[]::new);
131 source.putAll(ForkJoinPool.commonPool()
132 .invoke(new FileReadTask(selectedFiles, file.getAbsolutePath())));
137 private static boolean isRegularJavaFile(Path path) {
138 File file = path.toFile();
139 return file.isFile() && file.getName().endsWith(JAVA_EXT);
142 private static class FileReadTask extends RecursiveTask<Map<String, List<String>>> {
144 private final Map<String, List<String>> store = new HashMap<>();
146 final String pathPrefix;
147 private static final int MAX_FILES = 10;
149 FileReadTask(File[] files, String pathPrefix) {
151 this.pathPrefix = pathPrefix;
154 private static List<String> getData(File file) throws IOException {
155 List<String> coll = Files.readAllLines(file.toPath(), StandardCharsets.ISO_8859_1);
156 if (file.getAbsolutePath().contains(File.separator + "generated-sources" + File.separator)) {
157 coll.removeIf(s -> s == null || s.trim().startsWith("/") || s.trim().startsWith("*"));
164 protected Map<String, List<String>> compute() {
165 if (files.length > MAX_FILES) {
166 FileReadTask task1 = new FileReadTask(Arrays.copyOfRange(files, 0, files.length / 2), pathPrefix);
168 new FileReadTask(Arrays.copyOfRange(files, files.length / 2, files.length), pathPrefix);
171 store.putAll(task1.join());
172 store.putAll(task2.join());
174 for (File toRead : files) {
176 store.put(toRead.getAbsolutePath().substring(pathPrefix.length())
177 .replace(File.separatorChar, '.'), getData(toRead));
178 } catch (IOException e) {
179 throw new UncheckedIOException(e);
188 static Optional<String> getArtifactPathInLocalRepo(String repoPath, MavenProject project, byte[] sourceChecksum)
189 throws MojoFailureException {
190 STORE.put(project.getGroupId() + COLON + project.getArtifactId() + COLON + project.getVersion(),
191 new String(sourceChecksum));
194 uri = new URI(repoPath + (project.getGroupId().replace('.', '/')) + '/' + project.getArtifactId() + '/'
195 + project.getVersion());
196 } catch (URISyntaxException e) {
197 throw new MojoFailureException(e.getMessage(), e);
199 File f = new File(uri);
200 File[] list = f.listFiles(t -> t.getName().equals(project.getArtifactId() + "-" + project.getVersion() + "."
201 + project.getPackaging()));
202 if (list != null && list.length > 0) {
204 if (Arrays.equals(sourceChecksum, fetchSnapshotSignature(list[0], project.getVersion()))) {
205 return Optional.of(list[0].getAbsolutePath());
207 } catch (IOException e) {
208 throw new UncheckedIOException(e);
211 return Optional.empty();
214 private static byte[] fetchSnapshotSignature(File file, String version) throws IOException {
216 byte[] data = Files.readAllBytes(file.toPath());
217 try (ByteArrayInputStream byteInputStream = new ByteArrayInputStream(data);
218 JarInputStream jarInputStream = new JarInputStream(byteInputStream)) {
221 while ((entry = jarInputStream.getNextJarEntry()) != null) {
222 if (entry.getName().endsWith(UNICORN + DOT + CHECKSUM)) {
223 byte[] sigStore = new byte[1024];
224 return new String(sigStore, 0, jarInputStream.read(sigStore, 0, 1024)).getBytes();
228 return version.getBytes();
231 static <T> Optional<T> readState(String fileName, Class<T> clazz) {
233 try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
234 ObjectInputStream ois = new ObjectInputStream(is)) {
235 return Optional.of(clazz.cast(ois.readObject()));
236 } catch (Exception e) {
237 LOG.log(Level.FINE, e.getMessage(), e);
238 return Optional.empty();