42f3166ad6a7978aef9be5832c1e1c34035378df
[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.BufferedInputStream;
23 import java.io.File;
24 import java.io.FileInputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.ObjectInputStream;
28 import java.io.UncheckedIOException;
29 import java.net.URI;
30 import java.net.URISyntaxException;
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.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         StringBuffer buffer = new StringBuffer();
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, String> readSources(File file, String fileType) throws IOException {
75         Map<String, 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 String getData(File file, byte[] buffer) {
93         try (FileInputStream fis = new FileInputStream(file);
94              BufferedInputStream bis = new BufferedInputStream(fis, 64 * 1024)) {
95             bis.read(buffer, 0, ((int) file.length()));
96             if (file.getAbsolutePath().contains(File.separator + "generated-sources" + File.separator)) {
97                 StringBuffer sb = new StringBuffer();
98                 List<String> coll = Files.readAllLines(file.toPath());
99                 for (String s : coll) {
100                     if (s != null && !s.trim().startsWith("/") && !s.trim().startsWith("*")) {
101                         sb.append(s);
102                     }
103                 }
104                 return sb.toString();
105             }
106         } catch (IOException ioe) {
107             throw new UncheckedIOException(ioe);
108         }
109         return new String(buffer, 0, ((int) file.length()));
110     }
111
112
113     private static class FileReadTask extends RecursiveTask<Map<String, String>> {
114
115         Map<String, String> store = new HashMap<>();
116         private byte[] buffer = new byte[1024 * 1024];
117         File[] files;
118         String pathPrefix;
119         private final int MAX_FILES = 10;
120
121         FileReadTask(File[] files, String pathPrefix) {
122             this.files = files;
123             this.pathPrefix = pathPrefix;
124         }
125
126         @Override
127         protected Map<String, String> compute() {
128             if (files.length > MAX_FILES) {
129                 FileReadTask task1 = new FileReadTask(Arrays.copyOfRange(files, 0, files.length / 2), pathPrefix);
130                 FileReadTask task2 =
131                         new FileReadTask(Arrays.copyOfRange(files, files.length / 2, files.length), pathPrefix);
132                 task1.fork();
133                 task2.fork();
134                 store.putAll(task1.join());
135                 store.putAll(task2.join());
136             } else {
137                 for (File toRead : files) {
138                     store.put(toRead.getAbsolutePath().substring(pathPrefix.length()), getData(toRead, buffer));
139                 }
140             }
141
142             return store;
143         }
144     }
145
146     static Optional<String> getArtifactPathInLocalRepo(String repoPath, MavenProject project, byte[] sourceChecksum)
147             throws MojoFailureException {
148
149         URI uri = null;
150         try {
151             uri = new URI(repoPath + (project.getGroupId().replace('.', '/')) + '/' + project.getArtifactId() + '/'
152                                   + project.getVersion());
153         } catch (URISyntaxException e) {
154             throw new MojoFailureException(e.getMessage());
155         }
156         File f = new File(uri);
157         File[] list = f.listFiles(t -> t.getName().equals(project.getArtifactId() + "-" + project.getVersion() + "."
158                                                                   + project.getPackaging()));
159         if (list != null && list.length > 0) {
160             File checksumFile = new File(list[0].getParentFile(), project.getBuild().getFinalName() + "." + UNICORN);
161             try {
162                 if (checksumFile.exists() && Arrays.equals(sourceChecksum, Files.readAllBytes(checksumFile.toPath()))) {
163                     return Optional.of(list[0].getAbsolutePath());
164                 }
165             } catch (IOException e) {
166                 throw new UncheckedIOException(e);
167             }
168         }
169         return Optional.empty();
170     }
171
172     static <T> Optional<T> readState(String fileName, Class<T> clazz) {
173         try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
174              ObjectInputStream ois = new ObjectInputStream(is)) {
175             return Optional.of(clazz.cast(ois.readObject()));
176         } catch (Exception ignored) {
177             //ignore. it is taken care.
178             return Optional.empty();
179         }
180     }
181
182 }