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.plugin.logging.Log;
52 import org.apache.maven.project.MavenProject;
56 private static Log logger;
58 private static Map<String, String> store = new HashMap<>();
60 private BuildHelper() {
64 static void setLogger(Log log) {
68 static String getSnapshotSignature(File snapshotFile, String moduleCoordinate, String version) {
69 String key = moduleCoordinate + ":" + version;
70 String signature = store.get(key);
71 if (signature != null) {
75 signature = new String(fetchSnapshotSignature(snapshotFile, version));
76 store.put(key, signature);
78 } catch (IOException ioe) {
85 static long getChecksum(File file, String fileType) {
87 return readSources(file, fileType).hashCode();
88 } catch (IOException e) {
89 throw new UncheckedIOException(e);
93 static String getSourceChecksum(String data, String hashType) throws NoSuchAlgorithmException {
94 MessageDigest md = MessageDigest.getInstance(hashType);
95 md.update(data.getBytes());
96 byte[] hashBytes = md.digest();
98 StringBuilder buffer = new StringBuilder();
99 for (byte hashByte : hashBytes) {
100 buffer.append(Integer.toString((hashByte & 0xff) + 0x100, 16).substring(1));
102 return buffer.toString();
106 private static Map<String, List<String>> readSources(File file, String fileType) throws IOException {
107 Map<String, List<String>> source = new HashMap<>();
109 List<File> list = Files.walk(Paths.get(file.getAbsolutePath()))
110 .filter(JAVA_EXT.equals(fileType) ? BuildHelper::isRegularJavaFile :
111 Files::isRegularFile).map(Path::toFile).collect(Collectors.toList());
112 source.putAll(ForkJoinPool.commonPool()
113 .invoke(new FileReadTask(list.toArray(new File[0]), file.getAbsolutePath())));
118 private static boolean isRegularJavaFile(Path path) {
119 File file = path.toFile();
120 return file.isFile() && file.getName().endsWith(JAVA_EXT);
123 private static class FileReadTask extends RecursiveTask<Map<String, List<String>>> {
125 private Map<String, List<String>> store = new HashMap<>();
128 private static final int MAX_FILES = 10;
130 FileReadTask(File[] files, String pathPrefix) {
132 this.pathPrefix = pathPrefix;
135 private static List<String> getData(File file) throws IOException {
136 List<String> coll = Files.readAllLines(file.toPath(), StandardCharsets.ISO_8859_1);
137 if (file.getAbsolutePath().contains(File.separator + "generated-sources" + File.separator)) {
138 Iterator<String> itr = coll.iterator();
139 while (itr.hasNext()) {
140 String s = itr.next();
141 if (s == null || s.trim().startsWith("/") || s.trim().startsWith("*")) {
151 protected Map<String, List<String>> compute() {
152 if (files.length > MAX_FILES) {
153 FileReadTask task1 = new FileReadTask(Arrays.copyOfRange(files, 0, files.length / 2), pathPrefix);
155 new FileReadTask(Arrays.copyOfRange(files, files.length / 2, files.length), pathPrefix);
158 store.putAll(task1.join());
159 store.putAll(task2.join());
161 for (File toRead : files) {
163 store.put(toRead.getAbsolutePath().substring(pathPrefix.length())
164 .replace(File.separatorChar, '.'), getData(toRead));
165 } catch (IOException e) {
166 throw new UncheckedIOException(e);
175 static Optional<String> getArtifactPathInLocalRepo(String repoPath, MavenProject project, byte[] sourceChecksum)
176 throws MojoFailureException {
177 store.put(project.getGroupId() + COLON + project.getArtifactId() + COLON + project.getVersion(),
178 new String(sourceChecksum));
181 uri = new URI(repoPath + (project.getGroupId().replace('.', '/')) + '/' + project.getArtifactId() + '/'
182 + project.getVersion());
183 } catch (URISyntaxException e) {
184 throw new MojoFailureException(e.getMessage(), e);
186 File f = new File(uri);
187 File[] list = f.listFiles(t -> t.getName().equals(project.getArtifactId() + "-" + project.getVersion() + "."
188 + project.getPackaging()));
189 if (list != null && list.length > 0) {
191 if (Arrays.equals(sourceChecksum, fetchSnapshotSignature(list[0], project.getVersion()))) {
192 return Optional.of(list[0].getAbsolutePath());
194 } catch (IOException e) {
195 throw new UncheckedIOException(e);
198 return Optional.empty();
201 private static byte[] fetchSnapshotSignature(File file, String version) throws IOException {
202 byte[] data = Files.readAllBytes(file.toPath());
203 try (ByteArrayInputStream bais = new ByteArrayInputStream(data);
204 JarInputStream jis = new JarInputStream(bais)) {
205 JarEntry entry = null;
206 while ((entry = jis.getNextJarEntry()) != null) {
207 if (entry.getName().equals(UNICORN + DOT + CHECKSUM)) {
208 byte[] sigStore = new byte[1024];
209 return new String(sigStore, 0, jis.read(sigStore, 0, 1024)).getBytes();
213 return version.getBytes();
216 static <T> Optional<T> readState(String fileName, Class<T> clazz) {
217 try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
218 ObjectInputStream ois = new ObjectInputStream(is)) {
219 return Optional.of(clazz.cast(ois.readObject()));
220 } catch (Exception ignored) {
221 logger.debug(ignored);
222 return Optional.empty();