681e5f71bd20b69fffe3338358f7cc89a6fcd1e0
[sdc.git] /
1 /*
2  * Copyright © 2018 European Support Limited
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package org.openecomp.sdc.onboarding;
18
19 import static org.openecomp.sdc.onboarding.Constants.JAVA_EXT;
20 import static org.openecomp.sdc.onboarding.Constants.UNICORN;
21
22 import java.io.File;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.ObjectInputStream;
26 import java.io.UncheckedIOException;
27 import java.net.URI;
28 import java.net.URISyntaxException;
29 import java.nio.charset.StandardCharsets;
30 import java.nio.file.Files;
31 import java.nio.file.Path;
32 import java.nio.file.Paths;
33 import java.security.MessageDigest;
34 import java.security.NoSuchAlgorithmException;
35 import java.util.Arrays;
36 import java.util.HashMap;
37 import java.util.Iterator;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.Optional;
41 import java.util.concurrent.ForkJoinPool;
42 import java.util.concurrent.RecursiveTask;
43 import java.util.stream.Collectors;
44 import org.apache.maven.plugin.MojoFailureException;
45 import org.apache.maven.project.MavenProject;
46
47 class BuildHelper {
48
49     private BuildHelper() {
50         // donot remove.
51     }
52
53     static long getChecksum(File file, String fileType) {
54         try {
55             return readSources(file, fileType).hashCode();
56         } catch (IOException e) {
57             throw new UncheckedIOException(e);
58         }
59     }
60
61     static String getSourceChecksum(String data, String hashType) throws NoSuchAlgorithmException {
62         MessageDigest md = MessageDigest.getInstance(hashType);
63         md.update(data.getBytes());
64         byte[] hashBytes = md.digest();
65
66         StringBuilder buffer = new StringBuilder();
67         for (byte hashByte : hashBytes) {
68             buffer.append(Integer.toString((hashByte & 0xff) + 0x100, 16).substring(1));
69         }
70         return buffer.toString();
71     }
72
73
74     private static Map<String, List<String>> readSources(File file, String fileType) throws IOException {
75         Map<String, List<String>> source = new HashMap<>();
76         if (file.exists()) {
77             List<File> list = Files.walk(Paths.get(file.getAbsolutePath()))
78                                    .filter(JAVA_EXT.equals(fileType) ? BuildHelper::isRegularJavaFile :
79                                                    Files::isRegularFile).map(p -> p.toFile())
80                                    .collect(Collectors.toList());
81             source.putAll(ForkJoinPool.commonPool()
82                                       .invoke(new FileReadTask(list.toArray(new File[0]), file.getAbsolutePath())));
83         }
84         return source;
85     }
86
87     private static boolean isRegularJavaFile(Path path) {
88         File file = path.toFile();
89         return file.isFile() && file.getName().endsWith(JAVA_EXT);
90     }
91
92     private static class FileReadTask extends RecursiveTask<Map<String, List<String>>> {
93
94         private Map<String, List<String>> store = new HashMap<>();
95         File[] files;
96         String pathPrefix;
97         private static final int MAX_FILES = 10;
98
99         FileReadTask(File[] files, String pathPrefix) {
100             this.files = files;
101             this.pathPrefix = pathPrefix;
102         }
103
104         private static List<String> getData(File file) throws IOException {
105             List<String> coll = Files.readAllLines(file.toPath(), StandardCharsets.ISO_8859_1);
106             if (file.getAbsolutePath().contains(File.separator + "generated-sources" + File.separator)) {
107                 Iterator<String> itr = coll.iterator();
108                 while (itr.hasNext()) {
109                     String s = itr.next();
110                     if (s == null || s.trim().startsWith("/") || s.trim().startsWith("*")) {
111                         itr.remove();
112                     }
113                 }
114             }
115             return coll;
116         }
117
118
119         @Override
120         protected Map<String, List<String>> compute() {
121             if (files.length > MAX_FILES) {
122                 FileReadTask task1 = new FileReadTask(Arrays.copyOfRange(files, 0, files.length / 2), pathPrefix);
123                 FileReadTask task2 =
124                         new FileReadTask(Arrays.copyOfRange(files, files.length / 2, files.length), pathPrefix);
125                 task1.fork();
126                 task2.fork();
127                 store.putAll(task1.join());
128                 store.putAll(task2.join());
129             } else {
130                 for (File toRead : files) {
131                     try {
132                         store.put(toRead.getAbsolutePath().substring(pathPrefix.length())
133                                         .replace(File.separatorChar, '.'), getData(toRead));
134                     } catch (IOException e) {
135                         throw new UncheckedIOException(e);
136                     }
137                 }
138             }
139
140             return store;
141         }
142     }
143
144     static Optional<String> getArtifactPathInLocalRepo(String repoPath, MavenProject project, byte[] sourceChecksum)
145             throws MojoFailureException {
146
147         URI uri = null;
148         try {
149             uri = new URI(repoPath + (project.getGroupId().replace('.', '/')) + '/' + project.getArtifactId() + '/'
150                                   + project.getVersion());
151         } catch (URISyntaxException e) {
152             throw new MojoFailureException(e.getMessage(), e);
153         }
154         File f = new File(uri);
155         File[] list = f.listFiles(t -> t.getName().equals(project.getArtifactId() + "-" + project.getVersion() + "."
156                                                                   + project.getPackaging()));
157         if (list != null && list.length > 0) {
158             File checksumFile = new File(list[0].getParentFile(), project.getBuild().getFinalName() + "." + UNICORN);
159             try {
160                 if (checksumFile.exists() && Arrays.equals(sourceChecksum, Files.readAllBytes(checksumFile.toPath()))) {
161                     return Optional.of(list[0].getAbsolutePath());
162                 }
163             } catch (IOException e) {
164                 throw new UncheckedIOException(e);
165             }
166         }
167         return Optional.empty();
168     }
169
170     static <T> Optional<T> readState(String fileName, Class<T> clazz) {
171         try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
172              ObjectInputStream ois = new ObjectInputStream(is)) {
173             return Optional.of(clazz.cast(ois.readObject()));
174         } catch (Exception ignored) {
175             //ignore. it is taken care.
176             return Optional.empty();
177         }
178     }
179
180 }