f4a03ed47a6d84337dc6c2e9fc0f0cd14aaab887
[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 java.io.File;
20 import java.io.IOException;
21 import java.io.UncheckedIOException;
22 import java.nio.charset.StandardCharsets;
23 import java.nio.file.Files;
24 import java.nio.file.Path;
25 import java.nio.file.Paths;
26 import java.nio.file.StandardOpenOption;
27 import java.security.MessageDigest;
28 import java.security.NoSuchAlgorithmException;
29 import java.util.Arrays;
30 import java.util.HashMap;
31 import java.util.Iterator;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.concurrent.ForkJoinPool;
35 import java.util.concurrent.RecursiveTask;
36 import java.util.stream.Collectors;
37 import org.apache.maven.plugin.AbstractMojo;
38 import org.apache.maven.plugin.MojoExecutionException;
39 import org.apache.maven.plugin.MojoFailureException;
40 import org.apache.maven.plugins.annotations.LifecyclePhase;
41 import org.apache.maven.plugins.annotations.Mojo;
42 import org.apache.maven.plugins.annotations.Parameter;
43 import org.apache.maven.plugins.annotations.ResolutionScope;
44 import org.apache.maven.project.MavenProject;
45
46 @Mojo(name = "generate-signature", threadSafe = true, defaultPhase = LifecyclePhase.COMPILE,
47         requiresDependencyResolution = ResolutionScope.NONE)
48 public class SnapshotSignature extends AbstractMojo {
49
50     public static final String JAVA_EXT = ".java";
51     public static final String UNICORN = "unicorn";
52     public static final String CHECKSUM = "checksum";
53     public static final String DOT = ".";
54     public static final String SHA1 = "sha1";
55     public static final String COLON = ":";
56     public static final String ANY_EXT = "*";
57     public static final String SNAPSHOT = "SNAPSHOT";
58     public static final String JAR = "jar";
59
60     @Parameter
61     private File mainSourceLocation;
62     @Parameter
63     private File mainResourceLocation;
64     @Parameter(defaultValue = "${project}")
65     private MavenProject project;
66
67     @Override
68     public void execute() throws MojoExecutionException, MojoFailureException {
69         if (!JAR.equals(project.getPackaging())) {
70             return;
71         }
72         init();
73         long resourceChecksum = getChecksum(mainResourceLocation, ANY_EXT);
74         long mainChecksum = getChecksum(mainSourceLocation, JAVA_EXT);
75         byte[] sourceChecksum = calculateChecksum(mainChecksum, resourceChecksum).getBytes();
76         generateSignature(sourceChecksum);
77     }
78
79     private void init() {
80         if (mainSourceLocation == null) {
81             mainSourceLocation = Paths.get(project.getBuild().getSourceDirectory()).toFile();
82         }
83         if (mainResourceLocation == null) {
84             mainResourceLocation = Paths.get(project.getBuild().getResources().get(0).getDirectory()).toFile();
85         }
86     }
87
88     private long getChecksum(File file, String fileType) {
89         try {
90             return readSources(file, fileType).hashCode();
91         } catch (IOException e) {
92             throw new UncheckedIOException(e);
93         }
94     }
95
96     private Map<String, List<String>> readSources(File file, String fileType) throws IOException {
97         Map<String, List<String>> source = new HashMap<>();
98         if (file.exists()) {
99             List<File> list = Files.walk(Paths.get(file.getAbsolutePath()))
100                                    .filter(JAVA_EXT.equals(fileType) ? this::isRegularJavaFile : Files::isRegularFile)
101                                    .map(Path::toFile).collect(Collectors.toList());
102             source.putAll(ForkJoinPool.commonPool()
103                                       .invoke(new FileReadTask(list.toArray(new File[0]), file.getAbsolutePath())));
104         }
105         return source;
106     }
107
108     private boolean isRegularJavaFile(Path path) {
109         File file = path.toFile();
110         return file.isFile() && file.getName().endsWith(JAVA_EXT);
111     }
112
113     private class FileReadTask extends RecursiveTask<Map<String, List<String>>> {
114
115         private Map<String, List<String>> store = new HashMap<>();
116         File[] files;
117         String pathPrefix;
118         private static final int MAX_FILES = 10;
119
120         FileReadTask(File[] files, String pathPrefix) {
121             this.files = files;
122             this.pathPrefix = pathPrefix;
123         }
124
125         private List<String> getData(File file) throws IOException {
126             List<String> coll = Files.readAllLines(file.toPath(), StandardCharsets.ISO_8859_1);
127             if (file.getAbsolutePath().contains(File.separator + "generated-sources" + File.separator)) {
128                 Iterator<String> itr = coll.iterator();
129                 while (itr.hasNext()) {
130                     String s = itr.next();
131                     if (s == null || s.trim().startsWith("/") || s.trim().startsWith("*")) {
132                         itr.remove();
133                     }
134                 }
135             }
136             return coll;
137         }
138
139
140         @Override
141         protected Map<String, List<String>> compute() {
142             if (files.length > MAX_FILES) {
143                 FileReadTask task1 = new FileReadTask(Arrays.copyOfRange(files, 0, files.length / 2), pathPrefix);
144                 FileReadTask task2 =
145                         new FileReadTask(Arrays.copyOfRange(files, files.length / 2, files.length), pathPrefix);
146                 task1.fork();
147                 task2.fork();
148                 store.putAll(task1.join());
149                 store.putAll(task2.join());
150             } else {
151                 for (File toRead : files) {
152                     try {
153                         store.put(toRead.getAbsolutePath().substring(pathPrefix.length())
154                                         .replace(File.separatorChar, '.'), getData(toRead));
155                     } catch (IOException e) {
156                         throw new UncheckedIOException(e);
157                     }
158                 }
159             }
160
161             return store;
162         }
163     }
164
165     private void generateSignature(byte[] sourceChecksum) {
166         try {
167             Paths.get(project.getBuild().getOutputDirectory()).toFile().mkdirs();
168             Files.write(Paths.get(project.getBuild().getOutputDirectory(), UNICORN + DOT + CHECKSUM), sourceChecksum,
169                     StandardOpenOption.CREATE);
170         } catch (IOException e) {
171             throw new UncheckedIOException(e);
172         }
173     }
174
175     private String calculateChecksum(long mainChecksum, long resourceChecksum) throws MojoExecutionException {
176         try {
177             return getSourceChecksum(mainChecksum + COLON + resourceChecksum, SHA1);
178         } catch (NoSuchAlgorithmException e) {
179             throw new MojoExecutionException(e.getMessage(), e);
180         }
181     }
182
183     private String getSourceChecksum(String data, String hashType) throws NoSuchAlgorithmException {
184         MessageDigest md = MessageDigest.getInstance(hashType);
185         md.update(data.getBytes());
186         byte[] hashBytes = md.digest();
187
188         StringBuilder buffer = new StringBuilder();
189         for (byte hashByte : hashBytes) {
190             buffer.append(Integer.toString((hashByte & 0xff) + 0x100, 16).substring(1));
191         }
192         return buffer.toString();
193     }
194 }