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;
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;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.lang.reflect.Method;
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;
43 @Mojo(name = "init-artifact-helper", threadSafe = true, defaultPhase = LifecyclePhase.PRE_CLEAN,
44 requiresDependencyResolution = ResolutionScope.NONE)
45 public class InitializationHelperMojo extends AbstractMojo {
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 = ".";
53 @Parameter(defaultValue = "${session}")
54 private MavenSession session;
55 @Parameter(defaultValue = "${project}", readonly = true)
56 private MavenProject project;
58 private String groupId;
60 private String artifactId;
62 private String version;
64 private String excludePackaging;
66 private ArtifactHelper artifactHelper;
69 public void execute() throws MojoExecutionException, MojoFailureException {
70 if (System.getProperties().containsKey(UNICORN_INITIALIZED)) {
72 artifactHelper.shutDown(project);
73 } catch (IOException | ClassNotFoundException e) {
74 throw new MojoExecutionException("Unexpected Error Occured during shutdown activities", e);
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());
87 private String getResolvedVersion(List<ArtifactRepository> list, String artifactId) {
88 Pattern timestampPattern = Pattern.compile(".*<timestamp>(.*)</timestamp>.*");
89 Pattern buildNumberPattern = Pattern.compile(".*<buildNumber>(.*)</buildNumber>.*");
91 String timestamp = null;
92 String buildNumber = null;
93 for (ArtifactRepository repo : list) {
95 URL url = new URL(repo.getUrl() + (groupId.replace('.', '/')) + '/' + artifactId + '/' + version
96 + "/maven-metadata.xml");
98 new URL(repo.getUrl() + (groupId.replace('.', '/')) + '/' + artifactId + '/' + version + '/');
100 String content = artifactHelper.getContents(url);
101 Matcher m = timestampPattern.matcher(content);
103 timestamp = m.group(1);
105 m = buildNumberPattern.matcher(content);
107 buildNumber = m.group(1);
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;
117 } catch (IOException e) {
124 private String verifyBuildTimestamp(String buildNumber, String timestamp, URL fallbackUrl) throws IOException {
125 if (buildNumber == null) {
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);
133 String str = m.group(1);
134 if (!str.equals(timestamp)) {
141 private byte[] fetchContents(String repoUrl, String artifactId, String resolvedVersion) throws IOException {
142 File location = Paths.get(project.getBuild().getDirectory(), "build-data").toFile();
144 File file = new File(location, artifactId + "-" + (version.equals(resolvedVersion) ? version :
145 version.replace(SNAPSHOT, resolvedVersion)) + DOT
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);
153 byte[] data = Files.readAllBytes(file.toPath());
155 addJarToClasspath(file);
156 } catch (Exception e) {
157 getLog().error("Error while feeding the build-data into system.", e);
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);
171 private void setProperties(String proxyHostProperty, String proxyPortProperty, String nonProxyHostsProperty,
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()));
179 if (proxy.getNonProxyHosts() != null && !proxy.getNonProxyHosts().trim().isEmpty()) {
180 System.setProperty(nonProxyHostsProperty, proxy.getNonProxyHosts());
186 public void addJarToClasspath(File jar) throws MojoFailureException {
188 ClassLoader cl = ClassLoader.getSystemClassLoader();
189 Class<?> clazz = cl.getClass();
191 Method method = clazz.getSuperclass().getDeclaredMethod("addURL", new Class[] {URL.class});
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);