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.JAVA_EXT;
23 import static org.openecomp.sdc.onboarding.Constants.UNICORN;
25 import java.io.ByteArrayInputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.ObjectInputStream;
30 import java.io.UncheckedIOException;
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;
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;
56 private static Map<String, String> store = new HashMap<>();
58 private BuildHelper() {
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) {
69 signature = new String(fetchSnapshotSignature(snapshotFile, version));
70 store.put(key, signature);
72 } catch (IOException ioe) {
78 static long getChecksum(File file, String fileType) {
80 return readSources(file, fileType).hashCode();
81 } catch (IOException e) {
82 throw new UncheckedIOException(e);
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();
91 StringBuilder buffer = new StringBuilder();
92 for (byte hashByte : hashBytes) {
93 buffer.append(Integer.toString((hashByte & 0xff) + 0x100, 16).substring(1));
95 return buffer.toString();
99 private static Map<String, List<String>> readSources(File file, String fileType) throws IOException {
100 Map<String, List<String>> source = new HashMap<>();
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())));
111 private static boolean isRegularJavaFile(Path path) {
112 File file = path.toFile();
113 return file.isFile() && file.getName().endsWith(JAVA_EXT);
116 private static class FileReadTask extends RecursiveTask<Map<String, List<String>>> {
118 private Map<String, List<String>> store = new HashMap<>();
121 private static final int MAX_FILES = 10;
123 FileReadTask(File[] files, String pathPrefix) {
125 this.pathPrefix = pathPrefix;
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("*")) {
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);
148 new FileReadTask(Arrays.copyOfRange(files, files.length / 2, files.length), pathPrefix);
151 store.putAll(task1.join());
152 store.putAll(task2.join());
154 for (File toRead : files) {
156 store.put(toRead.getAbsolutePath().substring(pathPrefix.length())
157 .replace(File.separatorChar, '.'), getData(toRead));
158 } catch (IOException e) {
159 throw new UncheckedIOException(e);
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));
174 uri = new URI(repoPath + (project.getGroupId().replace('.', '/')) + '/' + project.getArtifactId() + '/'
175 + project.getVersion());
176 } catch (URISyntaxException e) {
177 throw new MojoFailureException(e.getMessage(), e);
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) {
184 if (Arrays.equals(sourceChecksum, fetchSnapshotSignature(list[0], project.getVersion()))) {
185 return Optional.of(list[0].getAbsolutePath());
187 } catch (IOException e) {
188 throw new UncheckedIOException(e);
191 return Optional.empty();
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();
206 return version.getBytes();
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();