stataru8 commented on code in PR #317: URL: https://github.com/apache/camel-karaf/pull/317#discussion_r1625702729
########## tooling/camel-karaf-feature-maven-plugin/src/main/java/org/apache/camel/karaf/feature/maven/EnsureWrapBundleVersionMojo.java: ########## @@ -0,0 +1,319 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.karaf.feature.maven; + +import java.io.StringWriter; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.felix.utils.version.VersionCleaner; +import org.apache.karaf.features.internal.model.Bundle; +import org.apache.karaf.features.internal.model.Feature; +import org.apache.karaf.features.internal.model.Features; +import org.apache.karaf.features.internal.model.JaxbUtil; +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.osgi.framework.Version; + +@Mojo(name = "ensure-wrap-bundle-version", defaultPhase = LifecyclePhase.PROCESS_RESOURCES) +public class EnsureWrapBundleVersionMojo extends AbstractMojo { + + public static final String FILE_PROTOCOL = "file:"; + + public static final String WRAP_PROTOCOL = "wrap:mvn:"; + public static final String BUNDLE_VERSION = "Bundle-Version"; + public static final List<String> HEADERS_AFTER_BUNDLE_VEIRSION = Arrays.asList( + //"Bundle-Version", + "DynamicImport-Package", + "Export-Package", + "Export-Service", + "Fragment-Host", + "Import-Package", + "Import-Service", + "Provide-Capability", + "Require-Bundle", + "Require-Capability"); + + private static final String DEFAULT_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"; + private static final String LICENCE_HEADER = """ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +-->"""; + + @Parameter(property = "featuresFilePath", required = true) + private String featuresFilePath; + + @Parameter(property = "targetFeature", required = false) + private String targetFeature = null; + + public String getFeaturesFilePath() { + return featuresFilePath; + } + + public void setFeaturesFilePath(String featuresFilePath) { + this.featuresFilePath = featuresFilePath; + } + + public String getTargetFeature() { + return targetFeature; + } + + public void setTargetFeature(String targetFeature) { + this.targetFeature = targetFeature; + } + + @Override + public void execute() throws MojoExecutionException { + Features featuresData = JaxbUtil.unmarshal(getFeaturesFilePath(), false); + List<Feature> features = featuresData.getFeature(); + + if (getTargetFeature() != null) { + boolean featureFound = false; + for (Feature feature : features) { + // all the feature versions will be modified + if (getTargetFeature().equals(feature.getName())) { + featureFound = true; + processFeature(feature); + } + } + if (!featureFound) { + getLog().warn("Feature %s not found. File '%s' wasn't modified".formatted(getTargetFeature(), + getFeaturesFilePath())); + return; + } + } else { + processFeatures(features); + } + + marshal(featuresData); + } + + private void marshal(Features featuresData) throws MojoExecutionException { + try (StringWriter writer = new StringWriter()) { + JaxbUtil.marshal(featuresData, writer); + + String result = writer.toString().replace(DEFAULT_HEADER, LICENCE_HEADER); + + Path path = Paths.get(getFeaturesFilePath().replaceFirst(FILE_PROTOCOL, "")); + Files.writeString(path, result); + + getLog().info("File '%s' was successfully modified and saved".formatted(getFeaturesFilePath())); + } catch (Exception e) { + getLog().error("File '%s' was successfully modified but an error occurred while saving it" + .formatted(getFeaturesFilePath()), e); + throw new MojoExecutionException(e); + } + } + + private void processFeatures(List<Feature> features) { + for (Feature feature : features) { + processFeature(feature); + } + } + + private void processFeature(Feature feature) { + for (Bundle bundle : feature.getBundle()) { + String location = bundle.getLocation(); + if (location != null && location.startsWith(WRAP_PROTOCOL)) { + try { + bundle.setLocation(processLocation(location)); + } catch (Exception e) { + getLog().error("Bundle location '%s' was ignored: %s".formatted(location, e.getMessage()), e); + } + } + } + } + + String processLocation(String localtion) throws Exception { + int versionStartIndex = getVersionStartIndex(localtion); + int versionEndIndex = getVersionEndIndex(localtion, versionStartIndex); + + String rawVersion = getVersion(localtion, versionStartIndex, versionEndIndex); + String version = getValidVersion(localtion, rawVersion); + + String bundleVersionHeader = "%s=%s".formatted(BUNDLE_VERSION, version); + + if (localtion.contains(bundleVersionHeader)) { + return localtion; + } else if (localtion.contains(BUNDLE_VERSION)) { + return updateExistingVersion(localtion, bundleVersionHeader); + } + + String wrapProtocolOptions = localtion.substring(versionEndIndex + 1, localtion.length()); + StringBuilder sb = new StringBuilder(localtion); + + // insert before existing headers header + for (String header : HEADERS_AFTER_BUNDLE_VEIRSION) { + // add Bundle-Version before + if (localtion.contains(header)) { + int versionHeaderStartIndex = localtion.indexOf(header); + if (wrapProtocolOptions.contains("$")) { + // "amp;" is automatically added + return sb.insert(versionHeaderStartIndex, "%s&".formatted(bundleVersionHeader)).toString(); + } else { + // "amp;" is automatically added + return sb.insert(versionHeaderStartIndex, "$%s&".formatted(bundleVersionHeader)).toString(); + } + } + } + + // insert at the end + if (wrapProtocolOptions.contains("$")) { + // "amp;" is automatically added + return sb.insert(localtion.length(), "&%s".formatted(bundleVersionHeader)).toString(); + } else { + return sb.insert(localtion.length(), "$%s".formatted(bundleVersionHeader)).toString(); + } + } + + /** + * @param location + * @return artifact version first char index, inclusive + */ + int getVersionStartIndex(String location) { + char[] chars = location.toCharArray(); + + boolean artifactIdFound = false; + for (int i = 0; i < chars.length; i++) { + if ('/' == chars[i]) { + if (!artifactIdFound) { + artifactIdFound = true; + } else { + return i + 1; + } + } + } + + return -1; + } + + int getVersionEndIndex(String location) { + return getVersionEndIndex(location, getVersionStartIndex(location)); + } + + /** + * @param location + * @param versionStartIndex + * @return artifact version last char index, inclusive + */ + int getVersionEndIndex(String location, int versionStartIndex) { + char[] chars = location.toCharArray(); + + // start at + 1 to ignore the potential $ coming from version placeholder + for (int i = versionStartIndex + 1; i < chars.length; i++) { + if ('$' == chars[i]) { + return i - 1; + } + } + + return chars.length - 1; + } + + String getVersion(String Location) { + return getVersion(Location, getVersionStartIndex(Location), getVersionEndIndex(Location)); + } + + String getVersion(String location, int versionStartIndex, int versionEndIndex) { + return location.substring(versionStartIndex, versionEndIndex + 1); + } + + String getValidVersion(String location, String version) throws Exception { + if (version.charAt(0) == '$') { + throw new Exception("Maven version placeholder '%s' wasn't resolved".formatted(version)); + } + + try { + // Test if version will work in Karaf + new Version(version); + } catch (Exception e) { + + // TODO: only use cleanVersion if the artifact is non-osgi + String cleanVersion = VersionCleaner.clean(version); + try { + // Test if clean version will work in Karaf again! + new Version(cleanVersion); + + getLog().debug( + "Bundle location '%s' will be set with Bundle-Version '%s', the output of org.apache.felix.utils.version.VersionCleaner.clean(%s)" + .formatted(location, cleanVersion, version)); + return cleanVersion; + + } catch (Exception newException) { + throw new Exception("Version '%s' is not OSGi compliant".formatted(cleanVersion), newException); + } + } + return version; + } + + String updateExistingVersion(String location, String bundleVersioHeader) throws Exception { + int versionHeaderStartIndex = location.indexOf(BUNDLE_VERSION); + int versionHeaderEndIndex = getBundleVersionHeaderEndIndex(location, versionHeaderStartIndex); + + // BUNDLE_VERSION.length() + 1 will include '=' + String currentVersion = location.substring(versionHeaderStartIndex + BUNDLE_VERSION.length() + 1, + versionHeaderEndIndex + 1); + if (currentVersion.charAt(0) == '$' || !currentVersion.equals(getValidVersion(location, currentVersion))) { + String currentBundleVersionHeader = location.substring(versionHeaderStartIndex, versionHeaderEndIndex + 1); + + return location.replaceAll(Pattern.quote(currentBundleVersionHeader), + Matcher.quoteReplacement(bundleVersioHeader)); + } + + return location; + } + + /** + * @param location + * @param versionHeaderStartIndex Review Comment: you mean remove ? ``` * @param location * @param versionHeaderStartIndex ``` I would like to keep ``` * @return wrap protocol Bundle-Version header last char index, inclusive ``` -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: commits-unsubscr...@camel.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org