2 * Copyright © 2018 European Support Limited
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.openecomp.sdc.onboarding.util;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.lang.reflect.Method;
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;
42 @Mojo(name = "init-artifact-helper", threadSafe = true, defaultPhase = LifecyclePhase.PRE_CLEAN,
43 requiresDependencyResolution = ResolutionScope.NONE)
44 public class InitializationHelperMojo extends AbstractMojo {
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 = ".";
52 @Parameter(defaultValue = "${session}")
53 private MavenSession session;
54 @Parameter(defaultValue = "${project}", readonly = true)
55 private MavenProject project;
57 private String groupId;
59 private String artifactId;
61 private String version;
63 private String excludePackaging;
65 private ArtifactHelper artifactHelper;
68 public void execute() throws MojoExecutionException, MojoFailureException {
69 if (System.getProperties().containsKey(UNICORN_INITIALIZED)) {
71 artifactHelper.shutDown(project);
72 } catch (IOException | ClassNotFoundException e) {
73 throw new MojoExecutionException("Unexpected Error Occured during shutdown activities", e);
77 artifactHelper.init(groupId + ":" + artifactId);
78 artifactHelper.deleteAll(artifactHelper.getUnicornMetaLocation());
79 String resolvedVersion =
80 getResolvedVersion(artifactHelper.getRepositories(version.contains(SNAPSHOT)), artifactId);
81 getLog().info(resolvedVersion.equals(version) ? "Unicorn Initialization Failed!!!" :
82 "Unicorn Initialization Completed Successfully!!!");
83 System.getProperties().setProperty(UNICORN_INITIALIZED, Boolean.TRUE.toString());
86 private String getResolvedVersion(List<ArtifactRepository> list, String artifactId) {
87 Pattern timestampPattern = Pattern.compile(".*<timestamp>(.*)</timestamp>.*");
88 Pattern buildNumberPattern = Pattern.compile(".*<buildNumber>(.*)</buildNumber>.*");
90 String timestamp = null;
91 String buildNumber = null;
92 for (ArtifactRepository repo : list) {
94 URL url = new URL(repo.getUrl() + (groupId.replace('.', '/')) + '/' + artifactId + '/' + version
95 + "/maven-metadata.xml");
97 new URL(repo.getUrl() + (groupId.replace('.', '/')) + '/' + artifactId + '/' + version + '/');
99 String content = artifactHelper.getContents(url);
100 Matcher m = timestampPattern.matcher(content);
102 timestamp = m.group(1);
104 m = buildNumberPattern.matcher(content);
106 buildNumber = m.group(1);
108 timestamp = verifyBuildTimestamp(buildNumber, timestamp, fallbackUrl);
109 if (timestamp != null && buildNumber != null) {
110 byte[] data = fetchContents(repo.getUrl(), artifactId, timestamp + "-" + buildNumber);
111 artifactHelper.store(artifactId, data);
112 getLog().info(artifactId + " Version to be copied is " + timestamp + "-" + buildNumber);
113 ArtifactHelper.setSnapshotBuildNumber(Integer.parseInt(buildNumber));
114 return timestamp + "-" + buildNumber;
116 } catch (IOException e) {
123 private String verifyBuildTimestamp(String buildNumber, String timestamp, URL fallbackUrl) throws IOException {
124 if (buildNumber == null) {
127 String buildPage = artifactHelper.getContents(fallbackUrl);
128 Pattern verifyPattern = Pattern.compile(
129 ".*" + artifactId + "-" + version.replace(SNAPSHOT, "") + "(.*)" + "-" + buildNumber + ".jar</a>.*");
130 Matcher m = verifyPattern.matcher(buildPage);
132 String str = m.group(1);
133 if (!str.equals(timestamp)) {
140 private byte[] fetchContents(String repoUrl, String artifactId, String resolvedVersion) throws IOException {
141 File location = Paths.get(project.getBuild().getDirectory(), "build-data").toFile();
143 File file = new File(location, artifactId + "-" + (version.equals(resolvedVersion) ? version :
144 version.replace(SNAPSHOT, resolvedVersion)) + DOT
146 URL path = new URL(repoUrl + (groupId.replace('.', '/')) + '/' + artifactId + '/' + version + '/' + artifactId
147 + "-" + (version.equals(resolvedVersion) ? version :
148 version.replace(SNAPSHOT, resolvedVersion)) + DOT + "jar");
149 try (InputStream is = path.openStream()) {
150 Files.copy(is, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
152 byte[] data = Files.readAllBytes(file.toPath());
154 addJarToClasspath(file);
155 } catch (Exception e) {
156 getLog().error("Error while feeding the build-data into system.", e);
162 private void setProxy(URL url) {
163 if (url.getProtocol().equalsIgnoreCase(HTTP)) {
164 setProperties("http.proxyHost", "http.proxyPort", "http.nonProxyHosts", HTTP);
165 } else if (url.getProtocol().equalsIgnoreCase(HTTPS)) {
166 setProperties("https.proxyHost", "https.proxyPort", "https.nonProxyHosts", HTTPS);
170 private void setProperties(String proxyHostProperty, String proxyPortProperty, String nonProxyHostsProperty,
172 for (Proxy proxy : session.getSettings().getProxies()) {
173 if (proxy.isActive() && proxy.getProtocol().equalsIgnoreCase(protocol)) {
174 if (proxy.getHost() != null && !proxy.getHost().trim().isEmpty()) {
175 System.setProperty(proxyHostProperty, proxy.getHost());
176 System.setProperty(proxyPortProperty, String.valueOf(proxy.getPort()));
178 if (proxy.getNonProxyHosts() != null && !proxy.getNonProxyHosts().trim().isEmpty()) {
179 System.setProperty(nonProxyHostsProperty, proxy.getNonProxyHosts());
185 public void addJarToClasspath(File jar) throws MojoFailureException {
187 ClassLoader cl = ClassLoader.getSystemClassLoader();
188 Class<?> clazz = cl.getClass();
190 Method method = clazz.getSuperclass().getDeclaredMethod("addURL", new Class[] {URL.class});
192 method.setAccessible(true);
193 method.invoke(cl, new Object[] {jar.toURI().toURL()});
194 } catch (Exception e) {
195 throw new MojoFailureException("Problem while loadig build-data", e);