6fa9b0e365835e7a659d4f63bc799935027e9cd4
[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.util;
18
19 import java.io.File;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.lang.reflect.Method;
23 import java.net.URL;
24 import java.nio.file.Files;
25 import java.nio.file.Paths;
26 import java.nio.file.StandardCopyOption;
27 import java.util.List;
28 import java.util.regex.Matcher;
29 import java.util.regex.Pattern;
30 import org.apache.maven.artifact.repository.ArtifactRepository;
31 import org.apache.maven.execution.MavenSession;
32 import org.apache.maven.plugin.AbstractMojo;
33 import org.apache.maven.plugin.MojoExecutionException;
34 import org.apache.maven.plugin.MojoFailureException;
35 import org.apache.maven.plugins.annotations.LifecyclePhase;
36 import org.apache.maven.plugins.annotations.Mojo;
37 import org.apache.maven.plugins.annotations.Parameter;
38 import org.apache.maven.plugins.annotations.ResolutionScope;
39 import org.apache.maven.project.MavenProject;
40 import org.apache.maven.settings.Proxy;
41
42 @Mojo(name = "init-artifact-helper", threadSafe = true, defaultPhase = LifecyclePhase.PRE_CLEAN,
43         requiresDependencyResolution = ResolutionScope.NONE)
44 public class InitializationHelperMojo extends AbstractMojo {
45
46     private static final String UNICORN_INITIALIZED = "unicorn_initialized";
47     private static final String HTTP = "http";
48     private static final String HTTPS = "https";
49     private static final String SNAPSHOT = "SNAPSHOT";
50     private static final String DOT = ".";
51
52     @Parameter(defaultValue = "${session}")
53     private MavenSession session;
54     @Parameter(defaultValue = "${project}", readonly = true)
55     private MavenProject project;
56     @Parameter
57     private String groupId;
58     @Parameter
59     private String artifactId;
60     @Parameter
61     private String version;
62     @Parameter
63     private String excludePackaging;
64     @Parameter
65     private ArtifactHelper artifactHelper;
66
67     @Override
68     public void execute() throws MojoExecutionException, MojoFailureException {
69         if (System.getProperties().containsKey(UNICORN_INITIALIZED)) {
70             return;
71         }
72         artifactHelper.init(groupId + ":" + artifactId);
73         artifactHelper.deleteAll(artifactHelper.getUnicornMetaLocation());
74         String resolvedVersion =
75                 getResolvedVersion(artifactHelper.getRepositories(version.contains(SNAPSHOT)), artifactId);
76         getLog().info(resolvedVersion.equals(version) ? "Unicorn Initialization Failed!!!" :
77                               "Unicorn Initialization Completed Successfully!!!");
78         System.getProperties().setProperty(UNICORN_INITIALIZED, Boolean.TRUE.toString());
79     }
80
81     private String getResolvedVersion(List<ArtifactRepository> list, String artifactId) {
82         Pattern timestampPattern = Pattern.compile(".*<timestamp>(.*)</timestamp>.*");
83         Pattern buildNumberPattern = Pattern.compile(".*<buildNumber>(.*)</buildNumber>.*");
84
85         String timestamp = null;
86         String buildNumber = null;
87         for (ArtifactRepository repo : list) {
88             try {
89                 URL url = new URL(repo.getUrl() + (groupId.replace('.', '/')) + '/' + artifactId + '/' + version
90                                           + "/maven-metadata.xml");
91                 URL fallbackUrl =
92                         new URL(repo.getUrl() + (groupId.replace('.', '/')) + '/' + artifactId + '/' + version + '/');
93                 setProxy(url);
94                 String content = artifactHelper.getContents(url);
95                 Matcher m = timestampPattern.matcher(content);
96                 if (m.find()) {
97                     timestamp = m.group(1);
98                 }
99                 m = buildNumberPattern.matcher(content);
100                 if (m.find()) {
101                     buildNumber = m.group(1);
102                 }
103                 timestamp = verifyBuildTimestamp(buildNumber, timestamp, fallbackUrl);
104                 if (timestamp != null && buildNumber != null) {
105                     byte[] data = fetchContents(repo.getUrl(), artifactId, timestamp + "-" + buildNumber);
106                     artifactHelper.store(artifactId, data);
107                     getLog().info(artifactId + " Version to be copied is " + timestamp + "-" + buildNumber);
108                     artifactHelper.setSnapshotBuildNumber(Integer.parseInt(buildNumber));
109                     return timestamp + "-" + buildNumber;
110                 }
111             } catch (IOException e) {
112                 getLog().debug(e);
113             }
114         }
115         return version;
116     }
117
118     private String verifyBuildTimestamp(String buildNumber, String timestamp, URL fallbackUrl) throws IOException {
119         if (buildNumber == null) {
120             return timestamp;
121         }
122         String buildPage = artifactHelper.getContents(fallbackUrl);
123         Pattern verifyPattern = Pattern.compile(
124                 ".*" + artifactId + "-" + version.replace(SNAPSHOT, "") + "(.*)" + "-" + buildNumber + ".jar</a>.*");
125         Matcher m = verifyPattern.matcher(buildPage);
126         if (m.find()) {
127             String str = m.group(1);
128             if (!str.equals(timestamp)) {
129                 return str;
130             }
131         }
132         return timestamp;
133     }
134
135     private byte[] fetchContents(String repoUrl, String artifactId, String resolvedVersion) throws IOException {
136         File location = Paths.get(project.getBuild().getDirectory(), "build-data").toFile();
137         location.mkdirs();
138         File file = new File(location, artifactId + "-" + (version.equals(resolvedVersion) ? version :
139                                                                    version.replace(SNAPSHOT, resolvedVersion)) + DOT
140                                                + "jar");
141         URL path = new URL(repoUrl + (groupId.replace('.', '/')) + '/' + artifactId + '/' + version + '/' + artifactId
142                                    + "-" + (version.equals(resolvedVersion) ? version :
143                                                     version.replace(SNAPSHOT, resolvedVersion)) + DOT + "jar");
144         try (InputStream is = path.openStream()) {
145             Files.copy(is, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
146         }
147         byte[] data = Files.readAllBytes(file.toPath());
148         try {
149             addJarToClasspath(file);
150         } catch (Exception e) {
151             getLog().error("Error while feeding the build-data into system.", e);
152         }
153
154         return data;
155     }
156
157     private void setProxy(URL url) {
158         if (url.getProtocol().equalsIgnoreCase(HTTP)) {
159             setProperties("http.proxyHost", "http.proxyPort", "http.nonProxyHosts", HTTP);
160         } else if (url.getProtocol().equalsIgnoreCase(HTTPS)) {
161             setProperties("https.proxyHost", "https.proxyPort", "https.nonProxyHosts", HTTPS);
162         }
163     }
164
165     private void setProperties(String proxyHostProperty, String proxyPortProperty, String nonProxyHostsProperty,
166             String protocol) {
167         for (Proxy proxy : session.getSettings().getProxies()) {
168             if (proxy.isActive() && proxy.getProtocol().equalsIgnoreCase(protocol)) {
169                 if (proxy.getHost() != null && !proxy.getHost().trim().isEmpty()) {
170                     System.setProperty(proxyHostProperty, proxy.getHost());
171                     System.setProperty(proxyPortProperty, String.valueOf(proxy.getPort()));
172                 }
173                 if (proxy.getNonProxyHosts() != null && !proxy.getNonProxyHosts().trim().isEmpty()) {
174                     System.setProperty(nonProxyHostsProperty, proxy.getNonProxyHosts());
175                 }
176             }
177         }
178     }
179
180     public void addJarToClasspath(File jar) throws MojoFailureException {
181         try {
182             ClassLoader cl = ClassLoader.getSystemClassLoader();
183             Class<?> clazz = cl.getClass();
184
185             Method method = clazz.getSuperclass().getDeclaredMethod("addURL", new Class[] {URL.class});
186
187             method.setAccessible(true);
188             method.invoke(cl, new Object[] {jar.toURI().toURL()});
189         } catch (Exception e) {
190             throw new MojoFailureException("Problem while loadig build-data", e);
191         }
192     }
193
194 }