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)) {
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());
81 private String getResolvedVersion(List<ArtifactRepository> list, String artifactId) {
82 Pattern timestampPattern = Pattern.compile(".*<timestamp>(.*)</timestamp>.*");
83 Pattern buildNumberPattern = Pattern.compile(".*<buildNumber>(.*)</buildNumber>.*");
85 String timestamp = null;
86 String buildNumber = null;
87 for (ArtifactRepository repo : list) {
89 URL url = new URL(repo.getUrl() + (groupId.replace('.', '/')) + '/' + artifactId + '/' + version
90 + "/maven-metadata.xml");
92 new URL(repo.getUrl() + (groupId.replace('.', '/')) + '/' + artifactId + '/' + version + '/');
94 String content = artifactHelper.getContents(url);
95 Matcher m = timestampPattern.matcher(content);
97 timestamp = m.group(1);
99 m = buildNumberPattern.matcher(content);
101 buildNumber = m.group(1);
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;
111 } catch (IOException e) {
118 private String verifyBuildTimestamp(String buildNumber, String timestamp, URL fallbackUrl) throws IOException {
119 if (buildNumber == null) {
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);
127 String str = m.group(1);
128 if (!str.equals(timestamp)) {
135 private byte[] fetchContents(String repoUrl, String artifactId, String resolvedVersion) throws IOException {
136 File location = Paths.get(project.getBuild().getDirectory(), "build-data").toFile();
138 File file = new File(location, artifactId + "-" + (version.equals(resolvedVersion) ? version :
139 version.replace(SNAPSHOT, resolvedVersion)) + DOT
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);
147 byte[] data = Files.readAllBytes(file.toPath());
149 addJarToClasspath(file);
150 } catch (Exception e) {
151 getLog().error("Error while feeding the build-data into system.", e);
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);
165 private void setProperties(String proxyHostProperty, String proxyPortProperty, String nonProxyHostsProperty,
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()));
173 if (proxy.getNonProxyHosts() != null && !proxy.getNonProxyHosts().trim().isEmpty()) {
174 System.setProperty(nonProxyHostsProperty, proxy.getNonProxyHosts());
180 public void addJarToClasspath(File jar) throws MojoFailureException {
182 ClassLoader cl = ClassLoader.getSystemClassLoader();
183 Class<?> clazz = cl.getClass();
185 Method method = clazz.getSuperclass().getDeclaredMethod("addURL", new Class[] {URL.class});
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);