features;
71 |
72 | /**
73 | * Flag to indicate whether to delete old runtime files.
74 | */
75 | @Parameter(defaultValue = "true")
76 | private boolean deleteOldRuntimeFiles = true;
77 |
78 |
79 | @Parameter(defaultValue = "${project}")
80 | private MavenProject project;
81 |
82 | @Component
83 | private EquinoxLauncher launcher;
84 |
85 | @Component
86 | private MavenSession session;
87 |
88 | @Parameter(defaultValue = "standalone")
89 | private DirectorRuntimeType directorRuntime;
90 |
91 | @Component
92 | private StandaloneDirectorRuntimeFactory standaloneDirectorFactory;
93 |
94 | /**
95 | * Kill the forked test process after a certain number of seconds. If set to 0, wait forever for
96 | * the process, never timing out.
97 | */
98 | @Parameter(defaultValue = "${p2.timeout}")
99 | private int forkedProcessTimeoutInSeconds;
100 |
101 | private File runtimeLocation;
102 |
103 | /**
104 | * Overridden method of AbstractMojo class. This is picked up by the maven runtime for execution.
105 | *
106 | * @throws MojoExecutionException throws when any runtime exception occurs. i.e: fail to read write file, fail to
107 | * parse a configuration xml
108 | * @throws MojoFailureException throws when the tool breaks for any configuration issues
109 | */
110 | public void execute() throws MojoExecutionException, MojoFailureException {
111 | this.runtimeLocation = new BuildOutputDirectory(this.project.getBuild().getDirectory()).getChild("director");
112 | setDirectorRuntime();
113 | FeatureInstaller installer = constructFeatureInstaller();
114 | installer.install();
115 | }
116 |
117 | /**
118 | * Constructs the FeatureInstaller object.
119 | * @return FeatureInstaller
120 | */
121 | private FeatureInstaller constructFeatureInstaller() {
122 | FeatureInstallResourceBundle resourceBundle = new FeatureInstallResourceBundle();
123 | resourceBundle.setDestination(this.destination);
124 | resourceBundle.setProfile(this.runtime == null ? P2Constants.DEFAULT_PROFILE_ID : this.runtime);
125 | resourceBundle.setRepository(this.repositoryURL);
126 | resourceBundle.setFeatures(this.features);
127 | resourceBundle.setDeleteOldProfileFiles(this.deleteOldRuntimeFiles);
128 | resourceBundle.setProject(this.project);
129 | resourceBundle.setLauncher(this.launcher);
130 | resourceBundle.setForkedProcessTimeoutInSeconds(this.forkedProcessTimeoutInSeconds);
131 | resourceBundle.setLog(getLog());
132 | resourceBundle.setRuntimeLocation(this.runtimeLocation);
133 | return new FeatureInstaller(resourceBundle);
134 | }
135 |
136 | /**
137 | * Runtime in which the director application is executed.
138 | * standalone (default) - to create and use a stand-alone installation of the director application. This option is
139 | * needed if the product to be installed includes artifacts with meta-requirements (e.g. to a non-standard
140 | * touchpoint action).
141 | *
142 | * @throws MojoFailureException
143 | * @throws MojoExecutionException
144 | */
145 | private void setDirectorRuntime() throws MojoFailureException, MojoExecutionException {
146 | switch (directorRuntime) {
147 | case standalone:
148 | standaloneDirectorFactory.createStandaloneDirector(this.runtimeLocation,
149 | this.session.getLocalRepository(), this.forkedProcessTimeoutInSeconds);
150 | return;
151 | default:
152 | throw new MojoFailureException("Unsupported value for attribute 'directorRuntime': \"" +
153 | directorRuntime + "\"");
154 | }
155 | }
156 | }
157 |
--------------------------------------------------------------------------------
/carbon-feature-plugin/src/main/java/org/wso2/maven/p2/utils/BundleUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
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 an "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.wso2.maven.p2.utils;
18 |
19 | import java.util.regex.Matcher;
20 | import java.util.regex.Pattern;
21 |
22 | /**
23 | * Utility class composed of utility methods pertaining to a Bundles.
24 | *
25 | * @since 2.0.0
26 | */
27 | public class BundleUtils {
28 |
29 | private static final Pattern OSGI_VERSION_PATTERN = Pattern.compile("[0-9]+\\.[0-9]+\\.[0-9]+(\\.[0-9A-Za-z_-]+)?");
30 | private static final Pattern ONLY_NUMBERS = Pattern.compile("[0-9]+");
31 |
32 | /**
33 | * Returns the OSGI version for the given artifact version.
34 | *
35 | * @param version artifact version
36 | * @return OSGI version
37 | */
38 | public static String getOSGIVersion(String version) {
39 | // This method is taken from org.apache.maven.shared.osgi.DefaultMaven2OsgiConverter to get the OSGI version
40 | // from a give version artifact version.
41 | String osgiVersion;
42 |
43 | // Matcher m = P_VERSION.matcher(version);
44 | // if (m.matches()) {
45 | // osgiVersion = m.group(1) + "." + m.group(3);
46 | // }
47 |
48 | /* TODO need a regexp guru here */
49 |
50 | Matcher m;
51 |
52 | /* if it's already OSGi compliant don't touch it */
53 | m = OSGI_VERSION_PATTERN.matcher(version);
54 | if (m.matches()) {
55 | return version;
56 | }
57 |
58 | osgiVersion = version;
59 |
60 | /* check for dated snapshot versions with only major or major and minor */
61 | Pattern datedSnapshotPattern =
62 | Pattern.compile("([0-9])(\\.([0-9]))?(\\.([0-9]))?\\-([0-9]{8}\\.[0-9]{6}\\-[0-9]*)");
63 | m = datedSnapshotPattern.matcher(osgiVersion);
64 | if (m.matches()) {
65 | String major = m.group(1);
66 | String minor = (m.group(3) != null) ? m.group(3) : "0";
67 | String service = (m.group(5) != null) ? m.group(5) : "0";
68 | String qualifier = m.group(6).replaceAll("-", "_").replaceAll("\\.", "_");
69 | osgiVersion = major + "." + minor + "." + service + "." + qualifier;
70 | }
71 |
72 | /* else transform first - to . and others to _ */
73 | osgiVersion = osgiVersion.replaceFirst("-", "\\.");
74 | osgiVersion = osgiVersion.replaceAll("-", "_");
75 | m = OSGI_VERSION_PATTERN.matcher(osgiVersion);
76 | if (m.matches()) {
77 | return osgiVersion;
78 | }
79 |
80 | /* remove dots in the middle of the qualifier */
81 | Pattern dotsInQualifierPattern = Pattern.compile("([0-9])(\\.[0-9])?\\.([0-9A-Za-z_-]+)\\.([0-9A-Za-z_-]+)");
82 | m = dotsInQualifierPattern.matcher(osgiVersion);
83 | if (m.matches()) {
84 | String s1 = m.group(1);
85 | String s2 = m.group(2);
86 | String s3 = m.group(3);
87 | String s4 = m.group(4);
88 |
89 | Matcher qualifierMatcher = ONLY_NUMBERS.matcher(s3);
90 | /*
91 | * if last portion before dot is only numbers then it's not in the middle of the
92 | * qualifier
93 | */
94 | if (!qualifierMatcher.matches()) {
95 | osgiVersion = s1 + s2 + "." + s3 + "_" + s4;
96 | }
97 | }
98 |
99 | /* convert
100 | * 1.string -> 1.0.0.string
101 | * 1.2.string -> 1.2.0.string
102 | * 1 -> 1.0.0
103 | * 1.1 -> 1.1.0
104 | */
105 | //Pattern NEED_TO_FILL_ZEROS = Pattern.compile( "([0-9])(\\.([0-9]))?\\.([0-9A-Za-z_-]+)" );
106 | Pattern needToFillZerosPattern = Pattern.compile("([0-9])(\\.([0-9]))?(\\.([0-9A-Za-z_-]+))?");
107 | m = needToFillZerosPattern.matcher(osgiVersion);
108 | if (m.matches()) {
109 | String major = m.group(1);
110 | String minor = m.group(3);
111 | String service = null;
112 | String qualifier = m.group(5);
113 |
114 | /* if there's no qualifier just fill with 0s */
115 | if (qualifier == null) {
116 | osgiVersion = getOSGIVersion(major, minor, null, null);
117 | } else {
118 | /* if last portion is only numbers then it's not a qualifier */
119 | Matcher qualifierMatcher = ONLY_NUMBERS.matcher(qualifier);
120 | if (qualifierMatcher.matches()) {
121 | if (minor == null) {
122 | minor = qualifier;
123 | } else {
124 | service = qualifier;
125 | }
126 | osgiVersion = getOSGIVersion(major, minor, service, null);
127 | } else {
128 | osgiVersion = getOSGIVersion(major, minor, null, qualifier);
129 | }
130 | }
131 | }
132 |
133 | m = OSGI_VERSION_PATTERN.matcher(osgiVersion);
134 | /* if still its not OSGi version then add everything as qualifier */
135 | if (!m.matches()) {
136 | String major = "0";
137 | String minor = "0";
138 | String service = "0";
139 | String qualifier = osgiVersion.replaceAll("\\.", "_");
140 | osgiVersion = major + "." + minor + "." + service + "." + qualifier;
141 | }
142 |
143 | return osgiVersion;
144 | }
145 |
146 | private static String getOSGIVersion(String major, String minor, String service, String qualifier) {
147 | StringBuilder sb = new StringBuilder();
148 | sb.append(major != null ? major : "0");
149 | sb.append('.');
150 | sb.append(minor != null ? minor : "0");
151 | sb.append('.');
152 | sb.append(service != null ? service : "0");
153 | if (qualifier != null) {
154 | sb.append('.');
155 | sb.append(qualifier);
156 | }
157 | return sb.toString();
158 | }
159 |
160 | }
161 |
--------------------------------------------------------------------------------
/carbon-feature-plugin/src/main/java/org/wso2/maven/p2/feature/install/FeatureInstallResourceBundle.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
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 an "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.wso2.maven.p2.feature.install;
18 |
19 | import org.apache.maven.plugin.logging.Log;
20 | import org.apache.maven.project.MavenProject;
21 | import org.eclipse.sisu.equinox.launching.EquinoxLauncher;
22 |
23 | import java.io.File;
24 | import java.net.URL;
25 | import java.util.List;
26 |
27 | /**
28 | * Bean class containing all the parameters entered to the mojo through plugin configuration.
29 | *
30 | * The purpose of this class is to make any configuration property accessible from any class by simply passing this
31 | * bean as a parameter.
32 | *
33 | * @since 2.0.0
34 | */
35 | public class FeatureInstallResourceBundle {
36 |
37 | private String destination;
38 | private String profile;
39 | private URL repository;
40 | private List features;
41 | private boolean deleteOldProfileFiles;
42 | private MavenProject project;
43 | private EquinoxLauncher launcher;
44 | private File runtimeLocation;
45 | private int forkedProcessTimeoutInSeconds;
46 | private Log log;
47 |
48 | /**
49 | * Returns the destination of the profile to install features.
50 | *
51 | * @return {@code String}
52 | */
53 | public String getDestination() {
54 | return destination;
55 | }
56 |
57 | /**
58 | * Sets the destination of the profile to install features.
59 | *
60 | * @param destination {@code String}
61 | */
62 | public void setDestination(String destination) {
63 | this.destination = destination;
64 | }
65 |
66 | /**
67 | * Returns the name of the profile that the features will be installed.
68 | *
69 | * @return {@code String}
70 | */
71 | public String getProfile() {
72 | return profile;
73 | }
74 |
75 | /**
76 | * Sets the name of the profile that the features will be installed.
77 | *
78 | * @param profile {@code String}
79 | */
80 | public void setProfile(String profile) {
81 | this.profile = profile;
82 | }
83 |
84 | /**
85 | * Returns the repository url where the features taken from.
86 | *
87 | * @return {@link URL}
88 | */
89 | public URL getRepository() {
90 | return repository;
91 | }
92 |
93 | /**
94 | * Sets the repository url where the features taken from.
95 | *
96 | * @param repository {@link URL}
97 | */
98 | public void setRepository(URL repository) {
99 | this.repository = repository;
100 | }
101 |
102 | /**
103 | * Returns the features list to be installed.
104 | *
105 | * @return {@code List}
106 | */
107 | public List getFeatures() {
108 | return features;
109 | }
110 |
111 | /**
112 | * Sets the features list to be installed.
113 | *
114 | * @param features {@code List}
115 | */
116 | public void setFeatures(List features) {
117 | this.features = features;
118 | }
119 |
120 | /**
121 | * Returns a boolean which specifies whether the old profile files should be deleted or not.
122 | *
123 | * @return {@code boolean}
124 | */
125 | public boolean isDeleteOldProfileFiles() {
126 | return deleteOldProfileFiles;
127 | }
128 |
129 | /**
130 | * Specify whether old profile files should be deleted or not.
131 | *
132 | * @param deleteOldProfileFiles {@code boolean}
133 | */
134 | public void setDeleteOldProfileFiles(boolean deleteOldProfileFiles) {
135 | this.deleteOldProfileFiles = deleteOldProfileFiles;
136 | }
137 |
138 | /**
139 | * Returns the maven project injected by the maven runtime.
140 | *
141 | * @return {@link MavenProject}
142 | */
143 | public MavenProject getProject() {
144 | return project;
145 | }
146 |
147 | /**
148 | * Sets the maven project injected by the maven runtime.
149 | *
150 | * @param project {@link MavenProject}
151 | */
152 | public void setProject(MavenProject project) {
153 | this.project = project;
154 | }
155 |
156 | /**
157 | * Returns the EquinoxLauncher injected by the maven runtime.
158 | *
159 | * @return {@link EquinoxLauncher}
160 | */
161 | public EquinoxLauncher getLauncher() {
162 | return launcher;
163 | }
164 |
165 | /**
166 | * Sets the EquinoxLauncher injected by the maven runtime.
167 | *
168 | * @param launcher {@link EquinoxLauncher}
169 | */
170 | public void setLauncher(EquinoxLauncher launcher) {
171 | this.launcher = launcher;
172 | }
173 |
174 | /**
175 | * Returns the forkedProcessTimeout in seconds.
176 | * @return {@code int}
177 | */
178 | public int getForkedProcessTimeoutInSeconds() {
179 | return forkedProcessTimeoutInSeconds;
180 | }
181 |
182 | /**
183 | * Sets the forkedProcessTimeout in seconds.
184 | * @param forkedProcessTimeoutInSeconds {@code int}
185 | */
186 | public void setForkedProcessTimeoutInSeconds(int forkedProcessTimeoutInSeconds) {
187 | this.forkedProcessTimeoutInSeconds = forkedProcessTimeoutInSeconds;
188 | }
189 |
190 | /**
191 | * Returns the Log.
192 | *
193 | * @return {@link Log}
194 | */
195 | public Log getLog() {
196 | return log;
197 | }
198 |
199 | /**
200 | * Sets the Log.
201 | *
202 | * @param log {@link Log}
203 | */
204 | public void setLog(Log log) {
205 | this.log = log;
206 | }
207 |
208 | /**
209 | * Returns the Runtime Location.
210 | *
211 | * @return {@link File}
212 | */
213 | public File getRuntimeLocation() {
214 | return runtimeLocation;
215 | }
216 |
217 | /**
218 | * Sets the Runtime Location.
219 | *
220 | * @param runtimeLocation {@link File}
221 | */
222 | public void setRuntimeLocation(File runtimeLocation) {
223 | this.runtimeLocation = runtimeLocation;
224 | }
225 | }
226 |
--------------------------------------------------------------------------------
/carbon-feature-plugin/src/main/java/org/wso2/maven/p2/beans/CarbonArtifact.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
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 an "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.wso2.maven.p2.beans;
18 |
19 | import org.apache.maven.artifact.Artifact;
20 |
21 | /**
22 | * Bean class representing CarbonArtifacts.
23 | *
24 | * This class is extended by all the Bean classes which represent any artifact created from the carbon feature plugin.
25 | *
26 | *
27 | * @since 2.0.0
28 | */
29 | public class CarbonArtifact {
30 | private String groupId;
31 | private String artifactId;
32 | private String version;
33 | private String symbolicName;
34 | private String type;
35 | private String bundleVersion;
36 | private Artifact artifact;
37 | private String compatibility = "compatible";
38 |
39 | /**
40 | * Returns the maven group id for the carbon artifact.
41 | *
42 | * @return String
43 | */
44 | public String getGroupId() {
45 | return groupId;
46 | }
47 |
48 | /**
49 | * Sets the maven group id for the carbon artifact.
50 | *
51 | * @param groupId String
52 | */
53 | public void setGroupId(String groupId) {
54 | this.groupId = groupId;
55 | }
56 |
57 | /**
58 | * Returns the maven artifact id for the carbon artifact.
59 | *
60 | * @return String
61 | */
62 | public String getArtifactId() {
63 | return artifactId;
64 | }
65 |
66 | /**
67 | * Sets the maven artifact id for the carbon artifact.
68 | *
69 | * @param artifactId String
70 | */
71 | public void setArtifactId(String artifactId) {
72 | this.artifactId = artifactId;
73 | }
74 |
75 | /**
76 | * Returns the maven version for this artifact.
77 | *
78 | * Important: This is not the OSGI version
79 | *
80 | *
81 | * @return String
82 | */
83 | public String getVersion() {
84 | return version;
85 | }
86 |
87 | /**
88 | * Sets the maven version for this artifact.
89 | *
90 | * Important: This is not the OSGI version
91 | *
92 | *
93 | * @param version String
94 | */
95 | public void setVersion(String version) {
96 | this.version = version;
97 | }
98 |
99 | /**
100 | * Returns the actual maven artifact represented by this carbon artifact.
101 | *
102 | * @return org.apache.maven.artifact object
103 | */
104 | public Artifact getArtifact() {
105 | return artifact;
106 | }
107 |
108 | /**
109 | * Sets the actual maven artifact represented by this carbon artifact.
110 | *
111 | * @param artifact org.apache.maven.artifact object
112 | */
113 | public void setArtifact(Artifact artifact) {
114 | this.artifact = artifact;
115 | }
116 |
117 | /**
118 | * Returns the OSGI symbolic name which is in the manifest file of the artifact represented by this
119 | * carbon artifact. This is applicable only if the represented carbon artifact is an OSGI bundle.
120 | *
121 | * @return String symbolic name
122 | */
123 | public String getSymbolicName() {
124 | return symbolicName;
125 | }
126 |
127 | /**
128 | * Sets the OSGI symbolic name which is in the manifest file of the artifact represented by this
129 | * carbon artifact. This is applicable only if the represented carbon artifact is an OSGI bundle.
130 | *
131 | * @param symbolicName String
132 | */
133 | public void setSymbolicName(String symbolicName) {
134 | this.symbolicName = symbolicName;
135 | }
136 |
137 | /**
138 | * Returns the file type of the actual artifact represented by this carbon artifact.
139 | * i.e: Jar, Zip
140 | *
141 | * @return String file extension
142 | */
143 | public String getType() {
144 | return type;
145 | }
146 |
147 | /**
148 | * Sets the file type(extension) of the actual artifact represented by this carbon artifact.
149 | *
150 | * @param type String
151 | */
152 | public void setType(String type) {
153 | this.type = type;
154 | }
155 |
156 | /**
157 | * Returns the OSGI bundle version of the actual artifact represented by this carbon artifact.
158 | * This is applicable only if the carbon artifact represent an OSGI bundle.
159 | *
160 | * @return String
161 | */
162 | public String getBundleVersion() {
163 | return bundleVersion;
164 | }
165 |
166 | /**
167 | * Sets the OSGI bundle version of the actual artifact represented by this carbon artifact.
168 | * This is applicable only if the carbon artifact represent an OSGI bundle.
169 | *
170 | * @param bundleVersion String
171 | */
172 | public void setBundleVersion(String bundleVersion) {
173 | this.bundleVersion = bundleVersion;
174 | }
175 |
176 | /**
177 | * Returns the compatibility type of this CarbonArtifact.
178 | * Permitted values are;
179 | *
180 | * - perfect
181 | * - equivalent
182 | * - compatible
183 | * - greaterOrEqual
184 | * - patch
185 | * - optional
186 | *
187 | *
188 | * @return String compatibility
189 | */
190 | public String getCompatibility() {
191 | return compatibility;
192 | }
193 |
194 | /*
195 | * Though there is no usage for this method from the code, do not delete this as this is used by maven
196 | * context to inject match.
197 | *
198 | */
199 | public void setCompatibility(String compatibility) {
200 | this.compatibility = compatibility;
201 | }
202 |
203 | /**
204 | * Util method which will copy some of the properties of this parent class into it's sub classes.
205 | *
206 | * @param item target Subclass of CarbonArtifact object which needs to copy fields of this object.
207 | * @param SubClass of CarbonArtifact
208 | */
209 | public void copyTo(T item) {
210 | item.setArtifact(this.artifact);
211 | item.setVersion(this.version);
212 | item.setArtifactId(this.artifactId);
213 | item.setBundleVersion(this.bundleVersion);
214 | item.setGroupId(this.groupId);
215 | item.setSymbolicName(this.symbolicName);
216 | item.setType(this.type);
217 | }
218 | }
219 |
--------------------------------------------------------------------------------
/carbon-feature-plugin/src/main/java/org/wso2/maven/p2/utils/ProductFileUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
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 an "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.wso2.maven.p2.utils;
18 |
19 | import org.apache.maven.artifact.Artifact;
20 | import org.apache.maven.plugin.MojoExecutionException;
21 | import org.apache.maven.project.MavenProject;
22 | import org.wso2.maven.p2.beans.product.Configurations;
23 | import org.wso2.maven.p2.beans.product.Product;
24 | import org.wso2.maven.p2.beans.product.config.ProductConfig;
25 | import org.wso2.maven.p2.beans.product.config.ProductFileConfig;
26 |
27 | import java.io.File;
28 | import java.io.IOException;
29 | import java.io.StringWriter;
30 | import java.nio.charset.Charset;
31 | import java.nio.file.Files;
32 | import java.nio.file.Paths;
33 | import javax.xml.bind.JAXBContext;
34 | import javax.xml.bind.JAXBException;
35 | import javax.xml.bind.Marshaller;
36 |
37 | /**
38 | * Utility class for helper functions in generating and reading a product file at build-time.
39 | *
40 | * This class is to be used by publish-product and generate-runtime maven goals.
41 | *
42 | * @since 3.1.0
43 | */
44 | public class ProductFileUtils {
45 |
46 | /**
47 | * Write Product bean as an XML to a product file.
48 | *
49 | * @param productFileConfig productFileConfig bean as read from project pom.
50 | * @param mavenProject mavenProject bean as read from project pom.
51 | * @throws JAXBException Is thrown if an error occurs in writing configurations into a string.
52 | * @throws MojoExecutionException Is thrown if maven project is not been able to be read.
53 | * @throws IOException Is thrown if an error occurs in writing configurations into a product file.
54 | */
55 | public static void generateProductFile(ProductFileConfig productFileConfig, MavenProject mavenProject) throws
56 | JAXBException, MojoExecutionException, IOException {
57 | // validating version and featureConfig values captured from project pom
58 | ProductConfig validatedProductConfig = ProductFileUtils.validateProductConfig(productFileConfig.
59 | getProductConfig(), mavenProject);
60 |
61 | // populating a product instance with validated values for writing to a product file
62 | Product product = new Product();
63 |
64 | product.setName(validatedProductConfig.getName());
65 | product.setUid(validatedProductConfig.getUid());
66 | product.setId(validatedProductConfig.getId());
67 | product.setApplication(validatedProductConfig.getApplication());
68 | product.setVersion(validateProductVersion(validatedProductConfig.getVersion()));
69 | product.setIncludeLaunchers(validatedProductConfig.getIncludeLaunchers());
70 | product.setConfigIni(validatedProductConfig.getConfigIni());
71 | product.setLauncher(validatedProductConfig.getLauncher());
72 | product.setConfigurations(new Configurations(validatedProductConfig.getPluginConfig(), validatedProductConfig
73 | .getPropertyConfig()));
74 |
75 | // writing to a product file
76 | StringWriter stringWriter = new StringWriter();
77 | stringWriter.append("").append(System
79 | .lineSeparator()).append("").append(System.lineSeparator());
81 |
82 | JAXBContext jaxbContext = JAXBContext.newInstance(Product.class);
83 | Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
84 |
85 | jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
86 | jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
87 | jaxbMarshaller.marshal(product, stringWriter);
88 |
89 | Files.write(Paths.get(ProductFileUtils.getProductFilePath(mavenProject)), stringWriter.toString()
90 | .getBytes(Charset.forName(P2Constants.DEFAULT_ENCODING)));
91 | }
92 |
93 | /**
94 | * Get path to dynamically generated product file.
95 | *
96 | * @param mavenProject bean as read from project pom.
97 | * @return String Path to dynamically generated product file.
98 | * @throws MojoExecutionException Is thrown if maven project is not been able to be read.
99 | */
100 | public static String getProductFilePath(MavenProject mavenProject) throws MojoExecutionException {
101 | if (mavenProject == null) {
102 | throw new MojoExecutionException("Unable to read maven project for finding project path.");
103 | } else {
104 | return mavenProject.getBasedir().getAbsolutePath() + File.separator + P2Constants.ProductFile
105 | .TARGET_DIRECTORY + File.separator + P2Constants.ProductFile.NAME;
106 | }
107 | }
108 |
109 | private static ProductConfig validateProductConfig(ProductConfig productConfig, MavenProject mavenProject) throws
110 | MojoExecutionException {
111 | if (productConfig.getVersion() == null) {
112 | productConfig.setVersion(ProductFileUtils.getDependencyVersion(mavenProject, P2Constants.ProductFile
113 | .Product.OSGI_RUNTIME_FEATURE));
114 | }
115 | return productConfig;
116 | }
117 |
118 | private static String validateProductVersion(String version) {
119 | if (version != null && !version.isEmpty() && version.contains(P2Constants.ProductFile.Feature
120 | .VERSION_CHAR_REPLACED)) {
121 | version = version.replaceAll(P2Constants.ProductFile.Feature.VERSION_CHAR_REPLACED, P2Constants
122 | .ProductFile.Feature.VERSION_CHAR_REPLACEMENT);
123 | }
124 | return version;
125 | }
126 |
127 | private static String getDependencyVersion(MavenProject mavenProject, String dependency) throws
128 | MojoExecutionException {
129 | if (mavenProject == null) {
130 | throw new MojoExecutionException("Unable to read maven project for finding dependencies.");
131 | } else if (dependency == null || dependency.isEmpty()) {
132 | throw new MojoExecutionException("Unable to find version for invalid dependency value.");
133 | } else {
134 | Artifact selectedArtifact = mavenProject.getDependencyArtifacts()
135 | .stream()
136 | .filter(artifact -> artifact.getArtifactId().contains(dependency))
137 | .findFirst()
138 | .orElseThrow(() -> new MojoExecutionException("Unable to find version as there seems to be " +
139 | "no pom based configuration for the provided dependency."));
140 |
141 | String dependencyVersion = selectedArtifact.getBaseVersion();
142 | if (dependencyVersion == null || dependencyVersion.isEmpty()) {
143 | throw new MojoExecutionException("Unable to find version for the provided dependency.");
144 | }
145 | return dependencyVersion;
146 | }
147 | }
148 | }
149 |
--------------------------------------------------------------------------------
/carbon-feature-plugin/src/main/java/org/wso2/maven/p2/feature/install/FeatureInstaller.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
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 an "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.wso2.maven.p2.feature.install;
18 |
19 | import org.apache.maven.plugin.MojoExecutionException;
20 | import org.apache.maven.plugin.MojoFailureException;
21 | import org.apache.maven.plugin.logging.Log;
22 | import org.wso2.maven.p2.utils.FileManagementUtil;
23 | import org.wso2.maven.p2.utils.P2Constants;
24 | import org.wso2.maven.p2.utils.StandaloneManager;
25 |
26 | import java.io.File;
27 | import java.io.FileOutputStream;
28 | import java.io.IOException;
29 | import java.io.OutputStreamWriter;
30 | import java.io.PrintWriter;
31 | import java.io.Writer;
32 | import java.nio.file.Paths;
33 |
34 | /**
35 | * FeatureInstaller takes parameters from the pom.xml and generates the profile.
36 | *
37 | * @since 2.0.0
38 | */
39 | public class FeatureInstaller {
40 |
41 | private final FeatureInstallResourceBundle resourceBundle;
42 | private final String destination;
43 |
44 | private Log log;
45 |
46 | /**
47 | * ProfileGenerator constructor taking ProfileResourceBundle as a parameter.
48 | *
49 | * @param resourceBundle ProfileResourceBundle
50 | */
51 | public FeatureInstaller(FeatureInstallResourceBundle resourceBundle) {
52 | this.resourceBundle = resourceBundle;
53 | this.log = resourceBundle.getLog();
54 | this.destination = resourceBundle.getDestination();
55 | }
56 |
57 | /**
58 | * Performs the installation operation.
59 | *
60 | * @throws MojoExecutionException throws when any runtime exception occurs. i.e: fail to read write file, fail to
61 | * install any given feature.
62 | * @throws MojoFailureException throws when the tool breaks for any configuration issues
63 | */
64 | public void install() throws MojoExecutionException, MojoFailureException {
65 | try {
66 | writeEclipseIni();
67 | installFeatures();
68 | updateProfileConfigIni();
69 | deleteOldProfiles();
70 | } catch (IOException e) {
71 | throw new MojoExecutionException(e.getMessage(), e);
72 | }
73 | }
74 |
75 | /**
76 | * Updating profile's config.ini p2.data.area property using relative path.
77 | */
78 | private void updateProfileConfigIni() {
79 | File profileConfigIni = FileManagementUtil.getProfileConfigIniFile(destination, resourceBundle.getProfile());
80 | FileManagementUtil.changeConfigIniProperty(profileConfigIni, "eclipse.p2.data.area", P2Constants.P2_DIRECTORY,
81 | resourceBundle.getLog());
82 | }
83 |
84 | /**
85 | * Calls the P2ApplicationLauncher and install the features.
86 | *
87 | * @throws MojoFailureException throws when the director application fail to install any given feature.
88 | */
89 | private void installFeatures() throws MojoFailureException {
90 | this.log.info("Running Equinox P2 Director Application");
91 | StandaloneManager launcher = new StandaloneManager(resourceBundle.getLauncher());
92 | launcher.setRuntimeLocation(resourceBundle.getRuntimeLocation());
93 | launcher.addArgumentsToInstallFeatures(resourceBundle.getRepository().toExternalForm(), destination,
94 | resourceBundle.getProfile());
95 | launcher.performAction(extractIUsToInstall(), resourceBundle.getForkedProcessTimeoutInSeconds());
96 | }
97 |
98 | /**
99 | * Generate the formatted string representation of features from the features passed in through the pom.xml. This
100 | * formatted string is passed into P2ApplicationLauncher to generate the profile.
101 | *
102 | * @return formatted string to pass into P2ApplicationLauncher
103 | */
104 | private String extractIUsToInstall() {
105 | StringBuilder installIUs = new StringBuilder();
106 | resourceBundle.getFeatures().forEach(feature ->
107 | installIUs.append(feature.getId().trim()).append("/").append(feature.getVersion().trim()).append(","));
108 |
109 | return installIUs.toString();
110 | }
111 |
112 | /**
113 | * Delete old profile files located at ${destination}/p2/org.eclipse.equinox.p2.engine/profileRegistry.
114 | *
115 | * @throws IOException throws when fail to delete old profile files
116 | */
117 | private void deleteOldProfiles() throws IOException {
118 | //In not specified to delete, then return the method.
119 | if (!resourceBundle.isDeleteOldProfileFiles()) {
120 | return;
121 | }
122 | String destination = resourceBundle.getDestination();
123 | if (!destination.endsWith("/")) {
124 | destination = destination + "/";
125 | resourceBundle.setDestination(destination);
126 | }
127 | String profileFolderName = resourceBundle.getDestination() +
128 | "p2/org.eclipse.equinox.p2.engine/profileRegistry/" + resourceBundle.getProfile() + ".profile";
129 |
130 | File profileFolder = new File(profileFolderName);
131 | if (profileFolder.isDirectory()) {
132 | String[] profileFileList = profileFolder.list((dir, name) -> name.endsWith(".profile"));
133 |
134 | //deleting old profile files
135 | if (profileFileList != null) {
136 | for (int i = 0; i < (profileFileList.length - 1); i++) {
137 | File profileFile = new File(profileFolderName, profileFileList[i]);
138 | if (profileFile.exists() && !profileFile.delete()) {
139 | throw new IOException("Failed to delete old profile file: " +
140 | profileFile.getAbsolutePath());
141 | }
142 | }
143 | }
144 |
145 | }
146 | }
147 |
148 | /**
149 | * Truncate and write the eclipse.ini file with the new profile location.
150 | *
151 | * @throws IOException throws when fail to eclipse.ini file/fail to delete old files.
152 | */
153 | private void writeEclipseIni() throws IOException {
154 | String profileLocation = resourceBundle.getDestination() + File.separator + resourceBundle.getProfile();
155 |
156 | File eclipseIni = Paths.get(profileLocation, "eclipse.ini").toFile();
157 | if (eclipseIni.exists()) {
158 | updateFile(eclipseIni, profileLocation);
159 | }
160 | }
161 |
162 | /**
163 | * Update eclipse.ini.
164 | *
165 | * @param file File object
166 | * @param profileLocation location of the profile directory
167 | * @throws IOException throws if fail to update the file
168 | */
169 | private void updateFile(File file, String profileLocation) throws IOException {
170 | if (file.exists()) {
171 | if (!file.delete()) {
172 | throw new IOException("Failed to delete " + file.getAbsolutePath());
173 | }
174 | }
175 | this.log.info("Updating " + file.getName());
176 | try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), P2Constants.DEFAULT_ENCODING);
177 | PrintWriter pw = new PrintWriter(writer)) {
178 | pw.write("-install\n");
179 | pw.write(profileLocation);
180 | pw.flush();
181 | } catch (IOException e) {
182 | this.log.debug("Error while writing to file " + file.getName(), e);
183 | }
184 | }
185 | }
186 |
--------------------------------------------------------------------------------
/carbon-feature-plugin/src/main/java/org/wso2/maven/p2/utils/P2Utils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
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 an "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 | package org.wso2.maven.p2.utils;
17 |
18 | import org.apache.maven.plugin.MojoExecutionException;
19 | import org.apache.maven.project.MavenProject;
20 | import org.w3c.dom.Document;
21 | import org.w3c.dom.Element;
22 | import org.wso2.maven.p2.repository.CatFeature;
23 | import org.wso2.maven.p2.repository.Category;
24 |
25 | import java.io.BufferedReader;
26 | import java.io.File;
27 | import java.io.FileInputStream;
28 | import java.io.IOException;
29 | import java.io.InputStreamReader;
30 | import java.util.ArrayList;
31 | import java.util.HashMap;
32 | import java.util.List;
33 | import java.util.Map;
34 | import java.util.regex.Pattern;
35 | import javax.xml.parsers.DocumentBuilder;
36 | import javax.xml.parsers.DocumentBuilderFactory;
37 | import javax.xml.parsers.ParserConfigurationException;
38 | import javax.xml.transform.OutputKeys;
39 | import javax.xml.transform.Transformer;
40 | import javax.xml.transform.TransformerConfigurationException;
41 | import javax.xml.transform.TransformerException;
42 | import javax.xml.transform.TransformerFactory;
43 | import javax.xml.transform.dom.DOMSource;
44 | import javax.xml.transform.stream.StreamResult;
45 |
46 |
47 | /**
48 | * The class contains operations related to Categories, which is out of the scope for current set of tasks. Thus
49 | * the refactoring is done for a minimum for the moment.
50 | *
51 | * @since 2.0.0
52 | */
53 | public class P2Utils {
54 | private static String[] matchList = new String[]{"perfect", "equivalent", "compatible", "greaterOrEqual", "patch",
55 | "optional"};
56 |
57 | /**
58 | * Traverse the given p2Inf file, find the last index of the property entries in the file and returns. This us
59 | * used when updating the p2inf with new properties.
60 | *
61 | * @param p2InfFile p2Inf Flie object
62 | * @return last index of the properties
63 | * @throws IOException throws if unable to read the p2Inf file
64 | */
65 | public static int getLastIndexOfProperties(File p2InfFile) throws IOException {
66 | int min = -1;
67 | if (p2InfFile.exists()) {
68 |
69 | try (InputStreamReader reader = new InputStreamReader(new FileInputStream(p2InfFile),
70 | P2Constants.DEFAULT_ENCODING);
71 | BufferedReader in = new BufferedReader(reader)) {
72 | String line;
73 | while ((line = in.readLine()) != null) {
74 | String[] split = line.split("=");
75 | String[] split2 = split[0].split(Pattern.quote("."));
76 | if (split2[0].equalsIgnoreCase("properties")) {
77 | int index = Integer.parseInt(split2[1]);
78 | if (index > min) {
79 | min = index;
80 | }
81 | }
82 | }
83 | }
84 | }
85 | return min;
86 | }
87 |
88 | public static boolean isMatchString(String matchStr) {
89 | for (String match : matchList) {
90 | if (matchStr.equalsIgnoreCase(match)) {
91 | return true;
92 | }
93 | }
94 | return false;
95 | }
96 |
97 | /**
98 | * Takes a match string and returns the correct matching string correspond to it.
99 | *
100 | * @param matchStr matching string
101 | * @return the correct matching rule corresponds to the given matching string
102 | */
103 | public static String getMatchRule(String matchStr) {
104 | if (isPatch(matchStr)) {
105 | return "perfect";
106 | }
107 | for (String match : matchList) {
108 | if (matchStr.equalsIgnoreCase(match)) {
109 | return match;
110 | }
111 | }
112 | return null;
113 | }
114 |
115 | /**
116 | * Returns whether the given matching string matches the patch matching rule.
117 | *
118 | * @param matchStr matching string to check
119 | * @return whether the given matching rule matches with patch matching rule
120 | */
121 | public static boolean isPatch(String matchStr) {
122 | return matchStr.equalsIgnoreCase("patch");
123 | }
124 |
125 | /**
126 | * Create the category file.
127 | *
128 | * @param project Maven project
129 | * @param categories categories list
130 | * @param categoryFile category file
131 | * @throws ParserConfigurationException throws if fail to generate a manifest document
132 | * @throws TransformerException throws when fail to transform the category file
133 | * @throws MojoExecutionException throws if fail to process features
134 | */
135 | public static void createCategoryFile(MavenProject project, List categories, File categoryFile)
136 | throws ParserConfigurationException, TransformerException, MojoExecutionException {
137 |
138 | Map featureCategories = new HashMap();
139 |
140 | Document doc = getManifestDocument();
141 | Element rootElement = doc.getDocumentElement();
142 |
143 | if (rootElement == null) {
144 | rootElement = doc.createElement("site");
145 | doc.appendChild(rootElement);
146 | }
147 |
148 | for (Object object : categories) {
149 | if (object instanceof Category) {
150 | Category cat = (Category) object;
151 | Element categoryDef = doc.createElement("category-def");
152 | categoryDef.setAttribute("name", cat.getId());
153 | categoryDef.setAttribute("label", cat.getLabel());
154 | rootElement.appendChild(categoryDef);
155 | Element descriptionElement = doc.createElement("description");
156 | descriptionElement.setTextContent(cat.getDescription());
157 | categoryDef.appendChild(descriptionElement);
158 | ArrayList processedFeatures = cat.getProcessedFeatures(project);
159 | for (CatFeature feature : processedFeatures) {
160 | if (!featureCategories.containsKey(feature.getId() + feature.getVersion())) {
161 | ArrayList list = new ArrayList();
162 | featureCategories.put((feature.getId() + feature.getVersion()), list);
163 | list.add(feature);
164 | }
165 | ArrayList list = (ArrayList) featureCategories.get(feature.getId() + feature.getVersion());
166 | list.add(cat.getId());
167 | }
168 | }
169 | }
170 |
171 | for (Object object : featureCategories.entrySet()) {
172 | if (object instanceof List) {
173 | List list = (List) object;
174 | CatFeature feature = (CatFeature) list.get(0);
175 | list.remove(0);
176 |
177 | Element featureDef = doc.createElement("feature");
178 | featureDef.setAttribute("id", feature.getId());
179 | featureDef.setAttribute("version", BundleUtils.getOSGIVersion(feature.getVersion()));
180 | for (Object catId : list) {
181 | Element category = doc.createElement("category");
182 | category.setAttribute("name", catId.toString());
183 | featureDef.appendChild(category);
184 | }
185 | rootElement.appendChild(featureDef);
186 | }
187 | }
188 |
189 | try {
190 | TransformerFactory transformerFactory = TransformerFactory.newInstance();
191 | Transformer transformer;
192 | transformer = transformerFactory.newTransformer();
193 | DOMSource source = new DOMSource(doc);
194 | StreamResult result = new StreamResult(categoryFile);
195 | transformer.setOutputProperty(OutputKeys.INDENT, "yes");
196 | transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
197 | transformer.transform(source, result);
198 | } catch (TransformerConfigurationException e) {
199 | throw new TransformerConfigurationException("Unable to create feature manifest", e);
200 | } catch (TransformerException e) {
201 | throw new TransformerException("Unable to create feature manifest", e);
202 | }
203 | }
204 |
205 | /**
206 | * Returns a blank document.
207 | *
208 | * @return org.w3c.dom.Document object
209 | * @throws ParserConfigurationException throws when fail to build a new xml document
210 | */
211 | public static Document getManifestDocument() throws ParserConfigurationException {
212 | DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
213 | DocumentBuilder documentBuilder;
214 | documentBuilder = documentBuilderFactory.newDocumentBuilder();
215 | return documentBuilder.newDocument();
216 | }
217 | }
218 |
--------------------------------------------------------------------------------
/carbon-feature-plugin/src/main/java/org/wso2/maven/p2/utils/P2ApplicationLaunchManager.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
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 an "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.wso2.maven.p2.utils;
18 |
19 | import org.apache.maven.plugin.MojoFailureException;
20 | import org.eclipse.sisu.equinox.launching.internal.P2ApplicationLauncher;
21 |
22 | import java.io.File;
23 | import java.io.IOException;
24 | import java.net.URL;
25 | import java.nio.file.Paths;
26 |
27 | /**
28 | * Wrapper class containing P2ApplicationLauncher which makes configuring the P2ApplicationLauncher easier.
29 | *
30 | * @since 2.0.0
31 | */
32 | public class P2ApplicationLaunchManager {
33 |
34 | private final P2ApplicationLauncher launcher;
35 |
36 | /**
37 | * The constructor which initializes this class. This class wraps the P2ApplicationLauncher and expose a set
38 | * of simple, easy to use methods to configure the P2ApplicationLauncher.
39 | *
40 | * @param launcher P2ApplicationLauncher which will be wrapped by this wrapper class
41 | */
42 | public P2ApplicationLaunchManager(P2ApplicationLauncher launcher) {
43 | this.launcher = launcher;
44 | }
45 |
46 | /**
47 | * Sets the working directory of P2Applilcation launcher instance.
48 | *
49 | * @param workingDir File object pointing the directory
50 | */
51 | public void setWorkingDirectory(File workingDir) {
52 | this.launcher.setWorkingDirectory(workingDir);
53 | }
54 |
55 | /**
56 | * Sets the application name.
57 | *
58 | * @param applicationName name of the application
59 | */
60 | public void setApplicationName(String applicationName) {
61 | this.launcher.setApplicationName(applicationName);
62 | }
63 |
64 | /**
65 | * Sets the P2ApplicationLauncher's arguments to install features.
66 | *
67 | * @param repositoryLocation a comma separated list of metadata repository(or artifact repository as in p2 both
68 | * metadata and artifacts resides in the same repo) URLs where the software to be
69 | * installed can be found.
70 | * @param installIUs a comma separated list of IUs to install. Each entry in the list is in the form
71 | * {@code [ '/' ]}. If you are looking to install a feature, the identifier
72 | * of the feature has to be suffixed with ".feature.group".
73 | * @param destination the path of a folder in which the targeted product is located.
74 | * @param profile the profile id containing the description of the targeted product. This ID is
75 | * defined by the eclipse.p2.profile property contained in the config.ini of the
76 | * targeted product.
77 | */
78 | public void addArgumentsToInstallFeatures(String repositoryLocation,
79 | String installIUs, String destination, String profile) {
80 |
81 | launcher.addArguments(
82 | "-metadataRepository", repositoryLocation,
83 | "-artifactRepository", repositoryLocation,
84 | "-profileProperties", "org.eclipse.update.install.features=true",
85 | "-installIU", installIUs,
86 | "-bundlepool", Paths.get(destination, "lib").toString(),
87 | //to support shared installation in carbon
88 | "-shared", Paths.get(destination, "lib", "p2").toString(),
89 | //target is set to a separate directory per Profile
90 | "-destination", Paths.get(destination, profile).toString(),
91 | "-profile", profile,
92 | "-roaming");
93 | }
94 |
95 | /**
96 | * Sets the P2ApplicationLauncher's arguments to uninstall features.
97 | *
98 | * @param uninstallIUs a comma separated list of IUs to uninstall. Each entry in the list is in the form
99 | * {@code [ '/' ]}. If you are looking to uninstall a feature, the identifier
100 | * of the feature has to be suffixed with ".feature.group".
101 | * @param destination the path of a folder in which the targeted product is located
102 | * @param profile the profile id containing the description of the targeted product
103 | */
104 | public void addArgumentsToUnInstallFeatures(String uninstallIUs, String destination,
105 | String profile) {
106 | launcher.addArguments(
107 | "-profileProperties", "org.eclipse.update.install.features=false",
108 | // a comma separated list of IUs to uninstall. Each entry in the list is in the form
109 | // [ '/' ]
110 | "-uninstallIU", uninstallIUs,
111 | // the location of where the plug-ins and features will be stored. This value is only taken into account
112 | // when a new profile is created. For an application where all the bundles are located into the
113 | // plugins/ folder of the destination, set it to
114 | // to support shared installation in carbon
115 | "-shared", Paths.get(destination, "lib", "p2").toString(),
116 | "-destination", Paths.get(destination, profile).toString(),
117 | "-profile", profile
118 | );
119 | }
120 |
121 | /**
122 | * Sets the P2ApplicationLauncher's arguments to generate P2 repository. For this scenario both metadata repository
123 | * and artifact repository are same.
124 | *
125 | * @param sourceDir the location of the update site
126 | * @param metadataRepoLocation the URI to the metadata repository where the installable units should be published
127 | * @param repositoryName name of the artifact repository where the artifacts should be published
128 | */
129 | public void addRepoGenerationArguments(String sourceDir, String metadataRepoLocation,
130 | String repositoryName) {
131 | launcher.addArguments("-source", sourceDir,
132 | "-metadataRepository", metadataRepoLocation,
133 | "-metadataRepositoryName", repositoryName,
134 | "-artifactRepository", metadataRepoLocation,
135 | "-artifactRepositoryName", repositoryName,
136 | "-publishArtifacts",
137 | "-publishArtifactRepository",
138 | "-compress",
139 | "-append");
140 | }
141 |
142 | /**
143 | * Sets the P2ApplicationLauncher's arguments and configure it to categorizing a set of Installable Units in a given
144 | * repository.
145 | *
146 | * @param metadataRepositoryLocation a comma separated list of metadata repository URLs where the software to be
147 | * installed can be found.
148 | * @param categoryDefinitionFile The category file which drives the categorization of installable units in the
149 | * repository
150 | */
151 | public void addUpdateRepoWithCategoryArguments(String metadataRepositoryLocation, String categoryDefinitionFile) {
152 | launcher.addArguments("-metadataRepository", metadataRepositoryLocation,
153 | "-categoryDefinition", categoryDefinitionFile,
154 | "-categoryQualifier",
155 | "-compress",
156 | "-append");
157 |
158 | }
159 |
160 | /**
161 | * Sets the P2ApplicationLauncher's arguments and configure it to publish a give product.
162 | *
163 | * @param repositoryURL the URL to the metadata repository where the product should be published
164 | * @param productConfigurationFile File object pointing the .product file
165 | * @param executable location of the equinox executable jar
166 | * @throws IOException throws when unable to get the canonical path from the product configuration file
167 | */
168 | public void addPublishProductArguments(URL repositoryURL, File productConfigurationFile, String executable)
169 | throws IOException {
170 | launcher.addArguments(
171 | "-metadataRepository", repositoryURL.toString(),
172 | "-artifactRepository", repositoryURL.toString(),
173 | "-productFile", productConfigurationFile.getCanonicalPath(),
174 | "-executables", executable,
175 | "-publishArtifacts",
176 | "-configs", "gtk.linux.x86",
177 | "-flavor", "tooling",
178 | "-append");
179 |
180 | }
181 |
182 | /**
183 | * Sets the P2ApplicationLauncher's arguments and configure it to generate a profile.
184 | *
185 | * @param repositoryURL the URL to the metadata repository where the product should be published
186 | * @param id product id taken from .product file
187 | * @param profile name of the new profile
188 | * @param targetPath location of the components directory of the carbon distribution
189 | */
190 | public void addGenerateProfileArguments(URL repositoryURL, String id, String profile, URL targetPath) {
191 | launcher.addArguments(
192 | "-metadataRepository", repositoryURL.toExternalForm(),
193 | "-artifactRepository", repositoryURL.toExternalForm(),
194 | "-installIU", id,
195 | "-profileProperties", "org.eclipse.update.install.features=true",
196 | "-profile", profile,
197 | "-bundlepool", targetPath.toExternalForm() + File.separator + "lib",
198 | //to support shared installation in carbon
199 | "-shared", targetPath.toExternalForm() + File.separator + "lib" + File.separator + "p2",
200 | //target is set to a separate directory per Profile
201 | "-destination", targetPath.toExternalForm() + File.separator + profile,
202 | "-p2.os", "linux",
203 | "-p2.ws", "gtk",
204 | "-p2.arch", "x86",
205 | "-roaming"
206 | );
207 | }
208 |
209 | /**
210 | * Generate/update the repository.
211 | *
212 | * @param forkedProcessTimeoutInSeconds int
213 | * @throws MojoFailureException throws when unable to perform the p2 activity
214 | */
215 | public void performAction(int forkedProcessTimeoutInSeconds) throws MojoFailureException {
216 | int result = launcher.execute(forkedProcessTimeoutInSeconds);
217 | if (result != 0) {
218 | throw new MojoFailureException("P2 publisher return code was " + result);
219 | }
220 | }
221 |
222 | }
223 |
--------------------------------------------------------------------------------
/carbon-feature-plugin/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
204 |
--------------------------------------------------------------------------------
/carbon-feature-plugin/src/main/java/org/wso2/maven/p2/utils/FileManagementUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
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 an "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 | package org.wso2.maven.p2.utils;
17 |
18 | import org.apache.maven.plugin.logging.Log;
19 |
20 | import java.io.BufferedInputStream;
21 | import java.io.BufferedOutputStream;
22 | import java.io.File;
23 | import java.io.FileInputStream;
24 | import java.io.FileOutputStream;
25 | import java.io.IOException;
26 | import java.io.InputStream;
27 | import java.io.OutputStream;
28 | import java.nio.file.Paths;
29 | import java.util.Properties;
30 | import java.util.zip.ZipEntry;
31 | import java.util.zip.ZipInputStream;
32 | import java.util.zip.ZipOutputStream;
33 |
34 | /**
35 | * Util class which handle file manipulation operations.
36 | *
37 | * @since 2.0.0
38 | */
39 | public class FileManagementUtil {
40 | private static final int BUFFER = 2048;
41 |
42 |
43 | /**
44 | * For a given location and the profile, returns the File object represented by config.ini.
45 | *
46 | * @param destination path pointing the [carbon product]/wso2 folder
47 | * @param profile name of the profile
48 | * @return the config.ini file for the Profile
49 | */
50 | public static File getProfileConfigIniFile(String destination, String profile) {
51 | return Paths.get(destination, profile, "configuration", "config.ini").toFile();
52 | }
53 |
54 | /**
55 | * Updated the given config.ini file with a given key value pair.
56 | *
57 | * @param configIniFile File object representing the config.ini
58 | * @param propKey property key
59 | * @param value property value
60 | * @param log Logger to log any warnings
61 | */
62 | public static void changeConfigIniProperty(File configIniFile, String propKey, String value, Log log) {
63 | Properties prop = new Properties();
64 |
65 | try (InputStream inputStream = new FileInputStream(configIniFile)) {
66 | prop.load(inputStream);
67 | prop.setProperty(propKey, value);
68 | try (OutputStream outputStream = new FileOutputStream(configIniFile)) {
69 | prop.store(outputStream, null);
70 | }
71 | } catch (IOException e) {
72 | log.warn("Error occurred while updating " + configIniFile.getName(), e);
73 | }
74 | }
75 |
76 | /**
77 | * Zip a give folder to a give output zip file.
78 | *
79 | * @param srcFolder source folder
80 | * @param destZipFile path to the output zip file
81 | * @param log Logger to log any warnings
82 | */
83 | public static void zipFolder(String srcFolder, String destZipFile, Log log) {
84 | try (FileOutputStream fileWriter = new FileOutputStream(destZipFile);
85 | ZipOutputStream zip = new ZipOutputStream(fileWriter)) {
86 | addFolderContentsToZip(srcFolder, zip, log);
87 | } catch (IOException e) {
88 | log.warn("Error occurred while archiving " + srcFolder, e);
89 | }
90 |
91 |
92 | }
93 |
94 | /**
95 | * Add a given folder/file into the given {@link ZipOutputStream}.
96 | *
97 | * @param path {@code String} Location inside the ZipOutputStream
98 | * @param srcFile {@code String} folder/file to be added into ZipOutputStream
99 | * @param zip {@link ZipOutputStream} zip output stream
100 | * @param log {@link Log}
101 | */
102 | private static void addToZip(String path, String srcFile, ZipOutputStream zip, Log log) {
103 | File folder = new File(srcFile);
104 | if (folder.isDirectory()) {
105 | addFolderToZip(path, srcFile, zip, log);
106 | } else {
107 | // Transfer bytes from in to out
108 | byte[] buf = new byte[1024];
109 | int len;
110 | try (FileInputStream inputStream = new FileInputStream(srcFile)) {
111 | if (path.trim().equals("")) {
112 | zip.putNextEntry(new ZipEntry(folder.getName()));
113 | } else {
114 | zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
115 | }
116 | while ((len = inputStream.read(buf)) > 0) {
117 | zip.write(buf, 0, len);
118 | }
119 | } catch (IOException e) {
120 | log.warn("Error occurred while archiving " + srcFile, e);
121 | }
122 | }
123 | }
124 |
125 | /**
126 | * Add root level content of a folder to the given {@link ZipOutputStream}.
127 | *
128 | * @param srcFolder {@code String} location of the folder to be included into the ZipOutputStream
129 | * @param zip {@link ZipOutputStream}
130 | * @param log {@link Log}
131 | */
132 | private static void addFolderContentsToZip(String srcFolder, ZipOutputStream zip, Log log) {
133 | File folder = new File(srcFolder);
134 | String fileList[] = folder.list();
135 | if (fileList != null) {
136 | try {
137 | int i = 0;
138 | while (true) {
139 | if (fileList.length == i) {
140 | break;
141 | }
142 | if (new File(folder, fileList[i]).isDirectory()) {
143 | zip.putNextEntry(new ZipEntry(fileList[i] + "/"));
144 | zip.closeEntry();
145 | }
146 | addToZip("", srcFolder + "/" + fileList[i], zip, log);
147 | i++;
148 | }
149 | } catch (IOException e) {
150 | log.warn("Error occurred while archiving " + srcFolder, e);
151 | }
152 | }
153 | }
154 |
155 | /**
156 | * Add non root level folders into a given {@link ZipOutputStream}.
157 | * @param path {@code String}
158 | * @param srcFolder {@code String}
159 | * @param zip {@link ZipOutputStream}
160 | * @param log {@link Log}
161 | */
162 | private static void addFolderToZip(String path, String srcFolder, ZipOutputStream zip, Log log) {
163 | File folder = new File(srcFolder);
164 | String fileList[] = folder.list();
165 | if (fileList != null) {
166 | try {
167 | int i = 0;
168 | while (true) {
169 | if (fileList.length == i) {
170 | break;
171 | }
172 | String newPath = folder.getName();
173 | if (!path.equalsIgnoreCase("")) {
174 | newPath = path + "/" + newPath;
175 | }
176 | if (new File(folder, fileList[i]).isDirectory()) {
177 | zip.putNextEntry(new ZipEntry(newPath + "/" + fileList[i] + "/"));
178 | zip.closeEntry();
179 | }
180 | addToZip(newPath, srcFolder + "/" + fileList[i], zip, log);
181 | i++;
182 | }
183 | } catch (IOException e) {
184 | log.warn("Error occurred while archiving " + srcFolder, e);
185 | }
186 | }
187 | }
188 |
189 | /**
190 | * Delete a given directory.
191 | *
192 | * @param dir directory to be deleted
193 | * @throws IOException throws when fail to delete a given directory
194 | */
195 | public static void deleteDirectories(File dir) throws IOException {
196 | File[] children = dir.listFiles();
197 |
198 | if (children != null) {
199 | for (File child : children) {
200 | if (child != null) {
201 | String[] childrenOfChild = child.list();
202 | if (childrenOfChild != null) {
203 | if (childrenOfChild.length > 0) {
204 | deleteDirectories(child);
205 | } else {
206 | if (!child.delete()) {
207 | throw new IOException("Failed to delete " + child.getAbsolutePath());
208 | }
209 | }
210 | } else {
211 | if (!child.delete()) {
212 | throw new IOException("Failed to delete " + child.getAbsolutePath());
213 | }
214 | }
215 | }
216 | }
217 | if (!dir.delete()) {
218 | throw new IOException("Failed to delete " + dir.getAbsolutePath());
219 | }
220 | }
221 | }
222 |
223 | /**
224 | * Copies all files under srcDir to dstDir. If dstDir does not exist, it will be created.
225 | *
226 | * @param srcDir source directory
227 | * @param dstDir destination directory
228 | * @throws IOException throws when fail to create the directory structure when copying files
229 | */
230 | public static void copyDirectory(File srcDir, File dstDir) throws IOException {
231 | if (srcDir.isDirectory()) {
232 | if (!dstDir.exists()) {
233 | if (!dstDir.mkdirs()) {
234 | throw new IOException("Failed to create directory " + dstDir.getAbsolutePath());
235 | }
236 | }
237 |
238 | String[] children = srcDir.list();
239 | if (children != null) {
240 | for (String child : children) {
241 | copyDirectory(new File(srcDir, child), new File(dstDir, child));
242 | }
243 | }
244 | } else {
245 | copy(srcDir, dstDir);
246 | }
247 | }
248 |
249 | /**
250 | * Copies src file to dst file. If the dst file does not exist, it is created.
251 | *
252 | * @param src source file
253 | * @param dst destination file
254 | * @throws IOException throws when fail to copy a given file
255 | */
256 | public static void copy(File src, File dst) throws IOException {
257 | if (dst.getParentFile() != null && !dst.getParentFile().exists()) {
258 | if (!dst.getParentFile().mkdirs()) {
259 | throw new IOException("Failed to create " + dst.getAbsolutePath());
260 | }
261 | }
262 |
263 | try (InputStream in = new FileInputStream(src);
264 | OutputStream out = new FileOutputStream(dst)) {
265 | // Transfer bytes from in to out
266 | byte[] buf = new byte[1024];
267 | int len;
268 | while ((len = in.read(buf)) > 0) {
269 | out.write(buf, 0, len);
270 | }
271 | }
272 | }
273 |
274 | /**
275 | * Unzip a given archive to a given destination.
276 | *
277 | * @param archiveFile archive file to be unzipped
278 | * @param destination location to put the unzipped file
279 | * @throws IOException throws when fail to create the directory structure when unzipping a file.
280 | */
281 | public static void unzip(File archiveFile, File destination) throws IOException {
282 |
283 | try (FileInputStream fis = new FileInputStream(archiveFile);
284 | ZipInputStream zis = new
285 | ZipInputStream(new BufferedInputStream(fis))) {
286 | ZipEntry entry;
287 |
288 | while ((entry = zis.getNextEntry()) != null) {
289 | int count;
290 | byte data[] = new byte[BUFFER];
291 | File file = new File(destination, entry.getName());
292 | if (entry.getName().endsWith("/")) {
293 | if (!file.exists() && !file.mkdirs()) {
294 | throw new IOException("Failed to create directories at " + file.getAbsolutePath());
295 | }
296 | continue;
297 | }
298 | if (file.getParentFile() != null && !file.getParentFile().exists()) {
299 | if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
300 | throw new IOException("Failed to create directories at " + file.getAbsolutePath());
301 | }
302 | }
303 | try (FileOutputStream fos = new FileOutputStream(file);
304 | BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
305 | while ((count = zis.read(data, 0, BUFFER)) != -1) {
306 | dest.write(data, 0, count);
307 | }
308 | }
309 | }
310 | }
311 | }
312 | }
313 |
--------------------------------------------------------------------------------