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