You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by kw...@apache.org on 2022/08/11 11:40:39 UTC
[sling-maven-plugin] branch master updated: SLING-11522 update Maven plugins, dependencies and parent (#6)
This is an automated email from the ASF dual-hosted git repository.
kwin pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-maven-plugin.git
The following commit(s) were added to refs/heads/master by this push:
new 0d526a8 SLING-11522 update Maven plugins, dependencies and parent (#6)
0d526a8 is described below
commit 0d526a8d11a39364356bfd40dd7365bd2d83d3e2
Author: Konrad Windszus <kw...@apache.org>
AuthorDate: Thu Aug 11 13:40:35 2022 +0200
SLING-11522 update Maven plugins, dependencies and parent (#6)
Switch to Maven Resolver/Eclipse Aether API introduced with Maven 3.3.1
use newest Fluido skin
fix SCM info for all modules
add sanity checks on responses of the different deployment servlets
add IT leveraging sling-starter
---
parent/pom.xml | 13 +-
{sling-maven-plugin => parent}/src/site/site.xml | 26 +-
pom.xml | 7 -
sling-maven-plugin/pom.xml | 285 ++++++++++++---------
.../src/it/install-test/invoker.properties | 23 ++
sling-maven-plugin/src/it/install-test/pom.xml | 92 +++++++
.../java/org/apache/sling/dummy/HelloWorld.java | 23 ++
.../bundlesupport/AbstractBundleDeployMojo.java | 63 ++---
.../bundlesupport/AbstractBundleInstallMojo.java | 44 ++--
...ostMojo.java => AbstractBundleRequestMojo.java} | 116 ++++++---
.../maven/bundlesupport/AbstractFsMountMojo.java | 75 +++---
.../maven/bundlesupport/BundleInstallFileMojo.java | 114 ++++-----
.../maven/bundlesupport/BundleInstallMojo.java | 41 +--
.../maven/bundlesupport/BundleUninstallMojo.java | 46 ++--
.../sling/maven/bundlesupport/FsMountMojo.java | 112 ++++----
.../sling/maven/bundlesupport/FsUnMountMojo.java | 12 +-
.../maven/bundlesupport/deploy/DeployContext.java | 8 +-
.../maven/bundlesupport/deploy/DeployMethod.java | 6 +-
.../deploy/method/FelixPostDeployMethod.java | 130 +++++-----
.../deploy/method/IntermediateUrisExtractor.java | 10 +-
.../deploy/method/SlingPostDeployMethod.java | 127 ++++-----
.../method/{MkColMethod.java => WebDavMkCol.java} | 17 +-
.../deploy/method/WebDavPutDeployMethod.java | 194 +++++++-------
.../fsresource/FileVaultXmlMounter.java | 9 +-
.../bundlesupport/fsresource/FsMountHelper.java | 119 ++++-----
.../fsresource/SlingInitialContentMounter.java | 9 +-
.../src/site/markdown/bundle-installation.md | 29 +++
sling-maven-plugin/src/site/markdown/index.md | 4 +-
sling-maven-plugin/src/site/site.xml | 17 +-
.../method/IntermediateUrisExtractorTest.java | 19 +-
.../deploy/method/SlingPostDeployMethodTest.java | 41 +++
31 files changed, 1013 insertions(+), 818 deletions(-)
diff --git a/parent/pom.xml b/parent/pom.xml
index f73b1d6..abba75c 100644
--- a/parent/pom.xml
+++ b/parent/pom.xml
@@ -17,13 +17,13 @@
specific language governing permissions and limitations
under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" child.project.url.inherit.append.path="false">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.sling</groupId>
<artifactId>sling</artifactId>
- <version>41</version>
+ <version>49</version>
<relativePath />
</parent>
@@ -33,10 +33,17 @@
<name>Apache Sling Maven Plugin Parent</name>
+ <!-- using adjusted inheritance rules: https://issues.apache.org/jira/browse/MNG-6059 -->
+ <scm child.scm.connection.inherit.append.path="false" child.scm.developerConnection.inherit.append.path="false" child.scm.url.inherit.append.path="false">
+ <connection>scm:git:https://gitbox.apache.org/repos/asf/sling-maven-plugin.git</connection>
+ <developerConnection>scm:git:https://gitbox.apache.org/repos/asf/sling-maven-plugin.git</developerConnection>
+ <url>https://github.com/apache/sling-maven-plugin</url>
+ <tag>HEAD</tag>
+ </scm>
+
<build>
<pluginManagement>
<plugins>
-
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
diff --git a/sling-maven-plugin/src/site/site.xml b/parent/src/site/site.xml
similarity index 61%
copy from sling-maven-plugin/src/site/site.xml
copy to parent/src/site/site.xml
index cdfb1e8..0ba3fda 100644
--- a/sling-maven-plugin/src/site/site.xml
+++ b/parent/src/site/site.xml
@@ -19,25 +19,13 @@ specific language governing permissions and limitations
under the License.
-->
-<project>
- <skin>
- <groupId>org.apache.maven.skins</groupId>
- <artifactId>maven-fluido-skin</artifactId>
- <version>1.9</version>
- </skin>
+<project xmlns="http://maven.apache.org/DECORATION/1.8.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/DECORATION/1.8.0 http://maven.apache.org/xsd/decoration-1.8.0.xsd">
<body>
- <menu name="Overview">
- <item name="Introduction" href="index.html"/>
- <item name="Goals" href="plugin-info.html"/>
- </menu>
- <menu ref="reports"/>
+ <!-- repeat the items from parent due to https://issues.apache.org/jira/browse/MSITE-910 -->
+ <breadcrumbs>
+ <item name="Apache Sling" href="https://sling.apache.org/"/>
+ <item name="Maven Plugins" href="https://sling.apache.org/components/"/>
+ </breadcrumbs>
</body>
- <custom>
- <fluidoSkin>
- <gitHub>
- <projectId>apache/sling-maven-plugin</projectId>
- <ribbonOrientation>right</ribbonOrientation>
- </gitHub>
- </fluidoSkin>
- </custom>
</project>
diff --git a/pom.xml b/pom.xml
index 89cf69c..5e777df 100644
--- a/pom.xml
+++ b/pom.xml
@@ -33,13 +33,6 @@
<name>Apache Sling Maven Plugin Reactor</name>
- <scm>
- <connection>scm:git:https://gitbox.apache.org/repos/asf/sling-maven-plugin.git</connection>
- <developerConnection>scm:git:https://gitbox.apache.org/repos/asf/sling-maven-plugin.git</developerConnection>
- <url>https://gitbox.apache.org/repos/asf?p=sling-maven-plugin.git</url>
- <tag>HEAD</tag>
- </scm>
-
<modules>
<module>parent</module>
<module>sling-maven-plugin</module>
diff --git a/sling-maven-plugin/pom.xml b/sling-maven-plugin/pom.xml
index fe8e523..fbc5f69 100644
--- a/sling-maven-plugin/pom.xml
+++ b/sling-maven-plugin/pom.xml
@@ -1,23 +1,24 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
- 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
+ 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
+ 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.
+ 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.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
@@ -38,31 +39,24 @@
<url>https://sling.apache.org/components/sling-maven-plugin/</url>
<prerequisites>
- <maven>3.0.4</maven> <!-- still support older maven version than required in parent pom -->
+ <maven>${mavenVersion}</maven>
</prerequisites>
<properties>
<maven.site.path>${project.artifactId}-archives/${project.artifactId}-LATEST</maven.site.path>
+ <github.project.id>apache/sling-maven-plugin</github.project.id>
+ <sling.java.version>8</sling.java.version>
+ <mavenVersion>3.3.1</mavenVersion><!-- minimum target Maven version this plugin is compatible with -->
+ <asmVersion>9.3</asmVersion>
+ <maven.compiler.target>${sling.java.version}</maven.compiler.target><!-- also set target next to release due to https://issues.apache.org/jira/browse/MPLUGIN-404 -->
</properties>
<build>
- <pluginManagement>
- <plugins>
- <plugin>
- <artifactId>maven-site-plugin</artifactId>
- <version>3.9.1</version>
- </plugin>
- <plugin>
- <artifactId>maven-project-info-reports-plugin</artifactId>
- <version>3.1.1</version>
- </plugin>
- </plugins>
- </pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-plugin-plugin</artifactId>
- <executions>
+ <executions>
<execution>
<id>default-descriptor</id>
<phase>process-classes</phase>
@@ -92,6 +86,86 @@
</excludes>
</configuration>
</plugin>
+ <!-- reserve network ports for the integration tests -->
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>build-helper-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>reserve-network-port</id>
+ <goals>
+ <goal>reserve-network-port</goal>
+ </goals>
+ <phase>pre-integration-test</phase>
+ <configuration>
+ <portNames>
+ <portName>starter-its.http.port</portName>
+ </portNames>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <!-- launch the Sling instances to test; only oak-tar -->
+ <plugin>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>feature-launcher-maven-plugin</artifactId>
+ <version>0.1.2</version>
+ <configuration>
+ <launches>
+ <launch>
+ <id>sling-starter-oak-tar</id>
+ <!-- Include the feature previously aggregated -->
+ <feature>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.starter</artifactId>
+ <version>12</version>
+ <classifier>oak_tar</classifier>
+ <type>slingosgifeature</type>
+ </feature>
+ <launcherArguments>
+ <frameworkProperties>
+ <org.osgi.service.http.port>${starter-its.http.port}</org.osgi.service.http.port>
+ </frameworkProperties>
+ </launcherArguments>
+ <startTimeoutSeconds>${starter-its.startTimeoutSeconds}</startTimeoutSeconds>
+ </launch>
+ </launches>
+ </configuration>
+ <executions>
+ <execution>
+ <goals>
+ <goal>start</goal>
+ <goal>stop</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-invoker-plugin</artifactId>
+ <configuration>
+ <cloneProjectsTo>${project.build.directory}/it</cloneProjectsTo>
+ <pomIncludes>
+ <pomInclude>**/pom.xml</pomInclude>
+ </pomIncludes>
+ <postBuildHookScript>verify</postBuildHookScript>
+ <localRepositoryPath>${project.build.directory}/it-repo</localRepositoryPath>
+ <properties>
+ <sling.url>http://localhost:${starter-its.http.port}</sling.url>
+ </properties>
+ <streamLogsOnFailures>true</streamLogsOnFailures>
+ </configuration>
+ <executions>
+ <execution>
+ <id>integration-test</id>
+ <goals>
+ <goal>install</goal>
+ <goal>integration-test</goal>
+ <goal>verify</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
</plugins>
</build>
@@ -105,7 +179,7 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<configuration>
- <!-- No javadocs -->
+ <!-- No javadocs -->
<excludePackageNames>
org.apache.sling
</excludePackageNames>
@@ -116,58 +190,39 @@
<dependencies>
<dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- <version>3.6</version>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>commons-httpclient</groupId>
- <artifactId>commons-httpclient</artifactId>
- <version>3.1</version>
+ <groupId>org.apache.httpcomponents.client5</groupId>
+ <artifactId>httpclient5</artifactId>
+ <version>5.1.3</version>
<scope>compile</scope>
</dependency>
<dependency>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- <version>1.0.4</version>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ <version>3.12.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
- <version>2.5</version>
+ <version>2.11.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.jcr.contentparser</artifactId>
- <version>1.2.4</version>
+ <version>1.2.8</version>
<scope>compile</scope>
- <exclusions>
- <exclusion>
- <groupId>org.apache.geronimo.specs</groupId>
- <artifactId>geronimo-json_1.0_spec</artifactId>
- </exclusion>
- </exclusions>
</dependency>
- <!-- Stick with json 1.0 specs until the plugin can be updated to Java 8 - json_1.1 spec requires Java 8 (SLING-7644) -->
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
- <artifactId>geronimo-json_1.0_spec</artifactId>
- <version>1.0-alpha-1</version>
+ <artifactId>geronimo-json_1.1_spec</artifactId>
+ <version>1.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.johnzon</groupId>
<artifactId>johnzon-core</artifactId>
- <version>1.0.0</version>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.jackrabbit.vault</groupId>
- <artifactId>org.apache.jackrabbit.vault</artifactId>
- <version>3.4.6</version>
+ <version>1.2.16</version>
<scope>compile</scope>
</dependency>
<dependency>
@@ -179,39 +234,38 @@
<groupId>org.osgi</groupId>
<artifactId>org.osgi.framework</artifactId>
<version>1.8.0</version>
+ <scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.commons.osgi</artifactId>
- <version>2.4.0</version>
- </dependency>
- <dependency>
- <groupId>org.apache.maven</groupId>
- <artifactId>maven-plugin-api</artifactId>
- <version>3.0.4</version>
+ <version>2.4.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
- <artifactId>maven-artifact</artifactId>
- <version>3.0.4</version>
- <scope>compile</scope>
+ <artifactId>maven-plugin-api</artifactId>
+ <version>${mavenVersion}</version>
+ <scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
- <artifactId>maven-compat</artifactId>
- <version>3.0.4</version>
- <scope>compile</scope>
+ <artifactId>maven-core</artifactId>
+ <version>${mavenVersion}</version>
+ <scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
- <artifactId>maven-archiver</artifactId>
- <version>2.6</version>
+ <artifactId>maven-artifact</artifactId>
+ <version>${mavenVersion}</version>
+ <scope>provided</scope>
</dependency>
+ <!-- use for evaluating Adapter annotations -->
<dependency>
<groupId>net.sf.scannotation</groupId>
<artifactId>scannotation</artifactId>
<version>1.0.2</version>
+ <scope>compile</scope>
<exclusions>
<exclusion>
<groupId>javassist</groupId>
@@ -223,30 +277,33 @@
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.18.2-GA</version>
+ <scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>adapter-annotations</artifactId>
<version>1.0.0</version>
+ <scope>compile</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.ow2.asm/asm -->
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
- <version>9.0</version>
+ <version>${asmVersion}</version>
+ <scope>compile</scope>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm-commons</artifactId>
- <version>9.0</version>
+ <version>${asmVersion}</version>
+ <scope>compile</scope>
</dependency>
-
+
<dependency>
<groupId>org.apache.maven.plugin-tools</groupId>
<artifactId>maven-plugin-annotations</artifactId>
- <version>3.4</version>
<scope>provided</scope>
- </dependency>
+ </dependency>
<dependency>
<groupId>org.sonatype.plexus</groupId>
<artifactId>plexus-build-api</artifactId>
@@ -259,14 +316,8 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- <version>15.0</version>
- <scope>test</scope>
- </dependency>
</dependencies>
-
+
<profiles>
<!-- This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself. -->
<profile>
@@ -279,37 +330,37 @@
<build>
<pluginManagement>
<plugins>
- <plugin>
- <groupId>org.eclipse.m2e</groupId>
- <artifactId>lifecycle-mapping</artifactId>
- <version>1.0.0</version>
- <configuration>
- <lifecycleMappingMetadata>
- <pluginExecutions>
- <pluginExecution>
- <pluginExecutionFilter>
- <groupId>
- org.apache.maven.plugins
- </groupId>
- <artifactId>
- maven-plugin-plugin
- </artifactId>
- <versionRange>
- [3.4,)
- </versionRange>
- <goals>
- <goal>descriptor</goal>
- <goal>helpmojo</goal>
- </goals>
- </pluginExecutionFilter>
- <action>
- <ignore />
- </action>
- </pluginExecution>
- </pluginExecutions>
- </lifecycleMappingMetadata>
- </configuration>
- </plugin>
+ <plugin>
+ <groupId>org.eclipse.m2e</groupId>
+ <artifactId>lifecycle-mapping</artifactId>
+ <version>1.0.0</version>
+ <configuration>
+ <lifecycleMappingMetadata>
+ <pluginExecutions>
+ <pluginExecution>
+ <pluginExecutionFilter>
+ <groupId>
+ org.apache.maven.plugins
+ </groupId>
+ <artifactId>
+ maven-plugin-plugin
+ </artifactId>
+ <versionRange>
+ [3.4,)
+ </versionRange>
+ <goals>
+ <goal>descriptor</goal>
+ <goal>helpmojo</goal>
+ </goals>
+ </pluginExecutionFilter>
+ <action>
+ <ignore/>
+ </action>
+ </pluginExecution>
+ </pluginExecutions>
+ </lifecycleMappingMetadata>
+ </configuration>
+ </plugin>
</plugins>
</pluginManagement>
</build>
diff --git a/sling-maven-plugin/src/it/install-test/invoker.properties b/sling-maven-plugin/src/it/install-test/invoker.properties
new file mode 100644
index 0000000..3c0aaa5
--- /dev/null
+++ b/sling-maven-plugin/src/it/install-test/invoker.properties
@@ -0,0 +1,23 @@
+# 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.
+
+invoker.goals=install -Dsling.urlSuffix=/system/console
+invoker.goals.2=install -Dsling.deploy.method=WebDAV -Dsling.urlSuffix=/dav/default/apps/sling-it
+invoker.goals.3=install -Dsling.deploy.method=SlingPostServlet -Dsling.urlSuffix=/apps/sling-it
+# invalid URL must lead to build failure
+invoker.goals.4=install -Dsling.urlSuffix=/system/console2
+invoker.buildResult.4=failure
\ No newline at end of file
diff --git a/sling-maven-plugin/src/it/install-test/pom.xml b/sling-maven-plugin/src/it/install-test/pom.xml
new file mode 100644
index 0000000..513a40a
--- /dev/null
+++ b/sling-maven-plugin/src/it/install-test/pom.xml
@@ -0,0 +1,92 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+ 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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+
+ <groupId>org.apache.sling</groupId>
+ <artifactId>example-bundle</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+
+ <properties>
+ <maven.compiler.source>1.8</maven.compiler.source>
+ <maven.compiler.target>1.8</maven.compiler.target>
+ </properties>
+ <build>
+ <pluginManagement>
+ <plugins>
+ <plugin>
+ <artifactId>maven-resources-plugin</artifactId>
+ <version>3.3.0</version>
+ </plugin>
+ <plugin>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>3.10.1</version>
+ </plugin>
+ <plugin>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <version>2.22.1</version>
+ </plugin>
+ <plugin>
+ <artifactId>maven-install-plugin</artifactId>
+ <version>3.0.1</version>
+ </plugin>
+ </plugins>
+ </pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>biz.aQute.bnd</groupId>
+ <artifactId>bnd-maven-plugin</artifactId>
+ <version>6.3.1</version>
+ <extensions>true</extensions>
+ <executions>
+ <execution>
+ <id>jar</id>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>@project.groupId@</groupId>
+ <artifactId>@project.artifactId@</artifactId>
+ <version>@project.version@</version>
+ <executions>
+ <execution>
+ <id>bundle-install</id>
+ <goals>
+ <goal>install</goal>
+ </goals>
+ </execution>
+ <execution>
+ <id>bundle-uninstall</id>
+ <goals>
+ <goal>uninstall</goal>
+ </goals>
+ <phase>install</phase>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+
+</project>
diff --git a/sling-maven-plugin/src/it/install-test/src/main/java/org/apache/sling/dummy/HelloWorld.java b/sling-maven-plugin/src/it/install-test/src/main/java/org/apache/sling/dummy/HelloWorld.java
new file mode 100644
index 0000000..9ac824e
--- /dev/null
+++ b/sling-maven-plugin/src/it/install-test/src/main/java/org/apache/sling/dummy/HelloWorld.java
@@ -0,0 +1,23 @@
+/*
+ * 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.sling.dummy;
+
+public class HelloWorld {
+ public static void main(String[] args) {
+ System.out.println("Hello World!");
+ }
+}
\ No newline at end of file
diff --git a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/AbstractBundleDeployMojo.java b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/AbstractBundleDeployMojo.java
index bdff661..52baa64 100644
--- a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/AbstractBundleDeployMojo.java
+++ b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/AbstractBundleDeployMojo.java
@@ -29,19 +29,15 @@ import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.Deflater;
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.HttpStatus;
-import org.apache.commons.httpclient.methods.PostMethod;
-import org.apache.commons.httpclient.methods.multipart.FilePart;
-import org.apache.commons.httpclient.methods.multipart.FilePartSource;
-import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
-import org.apache.commons.httpclient.methods.multipart.Part;
-import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.io.IOUtils;
+import org.apache.hc.client5.http.classic.methods.HttpPost;
+import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
+import org.apache.hc.client5.http.impl.classic.BasicHttpClientResponseHandler;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Parameter;
-abstract class AbstractBundleDeployMojo extends AbstractBundlePostMojo {
+abstract class AbstractBundleDeployMojo extends AbstractBundleRequestMojo {
/**
* The URL to the OSGi Bundle repository to which the bundle is posted, e.g.
@@ -93,42 +89,27 @@ abstract class AbstractBundleDeployMojo extends AbstractBundlePostMojo {
getLog().info(
"Deploying Bundle " + bundleName + "(" + jarFile + ") to " + obr);
- this.post(this.obr, jarFile);
- }
-
- private void post(String targetURL, File file)
- throws MojoExecutionException {
-
- PostMethod filePost = new PostMethod(targetURL);
- try {
- Part[] parts = {
- new FilePart(file.getName(), new FilePartSource(file.getName(),
- file)), new StringPart("_noredir_", "_noredir_") };
- filePost.setRequestEntity(new MultipartRequestEntity(parts,
- filePost.getParams()));
- HttpClient client = new HttpClient();
- client.getHttpConnectionManager().getParams().setConnectionTimeout(
- 5000);
- int status = client.executeMethod(filePost);
- if (status == HttpStatus.SC_OK) {
- getLog().info("Bundle deployed");
- } else {
- String msg = "Deployment failed, cause: "
- + HttpStatus.getStatusText(status);
- if (failOnError) {
- throw new MojoExecutionException(msg);
- } else {
- getLog().error(msg);
- }
- }
- } catch (Exception ex) {
- throw new MojoExecutionException("Deployment on " + targetURL
+ try (CloseableHttpClient httpClient = getHttpClient()) {
+ this.post(httpClient, this.obr, jarFile);
+ getLog().info("Bundle deployed");
+ }
+ catch (IOException ex) {
+ throw new MojoExecutionException("Deployment on " + this.obr
+ " failed, cause: " + ex.getMessage(), ex);
- } finally {
- filePost.releaseConnection();
}
}
+ private void post(CloseableHttpClient httpClient, String targetURL, File file)
+ throws IOException {
+ HttpPost filePost = new HttpPost(targetURL);
+ MultipartEntityBuilder builder = MultipartEntityBuilder.create();
+ builder.addTextBody("_noredir_", "_noredir_");
+ builder.addBinaryBody(file.getName(), file);
+ filePost.setEntity(builder.build());
+ String response = httpClient.execute(filePost, new BasicHttpClientResponseHandler());
+ getLog().debug("Received response: " + response);
+ }
+
/**
* Change the version in jar
* @param file File
diff --git a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/AbstractBundleInstallMojo.java b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/AbstractBundleInstallMojo.java
index dc20552..40ea058 100644
--- a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/AbstractBundleInstallMojo.java
+++ b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/AbstractBundleInstallMojo.java
@@ -19,7 +19,10 @@
package org.apache.sling.maven.bundlesupport;
import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
@@ -27,7 +30,7 @@ import org.apache.sling.maven.bundlesupport.deploy.BundleDeploymentMethod;
import org.apache.sling.maven.bundlesupport.deploy.DeployContext;
import org.apache.sling.maven.bundlesupport.fsresource.SlingInitialContentMounter;
-abstract class AbstractBundleInstallMojo extends AbstractBundlePostMojo {
+abstract class AbstractBundleInstallMojo extends AbstractBundleRequestMojo {
/**
* If a PUT via WebDAV should be used instead of the standard POST to the
@@ -54,6 +57,7 @@ abstract class AbstractBundleInstallMojo extends AbstractBundlePostMojo {
* </ol>
*
* This has precedence over the deprecated parameter {@link #usePut}.
+ * If nothing is set the default is either {@code WebConsole} or {@code WebDAV} (when {@link #usePut} is {@code true}).
*/
@Parameter(property="sling.deploy.method", required = false)
protected BundleDeploymentMethod deploymentMethod;
@@ -103,19 +107,17 @@ abstract class AbstractBundleInstallMojo extends AbstractBundlePostMojo {
super();
}
- protected abstract String getBundleFileName() throws MojoExecutionException;
+ protected abstract File getBundleFileName() throws MojoExecutionException;
@Override
public void execute() throws MojoExecutionException {
// get the file to upload
- String bundleFileName = getBundleFileName();
+ File bundleFile = getBundleFileName();
// only upload if packaging as an osgi-bundle
- File bundleFile = new File(bundleFileName);
-
- if(!bundleFile.exists()) {
- getLog().info(bundleFile + " does not exist, no uploading");
+ if (!bundleFile.exists()) {
+ getLog().info(bundleFile + " does not exist, not uploading");
return;
}
@@ -125,29 +127,39 @@ abstract class AbstractBundleInstallMojo extends AbstractBundlePostMojo {
return;
}
- String targetURL = getTargetURL();
+ URI targetURL = getTargetURL();
BundleDeploymentMethod deploymentMethod = getDeploymentMethod();
getLog().info(
"Installing Bundle " + bundleName + "(" + bundleFile + ") to "
- + targetURL + " via " + deploymentMethod);
+ + targetURL + " via " + deploymentMethod + "...");
- deploymentMethod.execute().deploy(targetURL, bundleFile, bundleName, new DeployContext()
+ try (CloseableHttpClient httpClient = getHttpClient()){
+ deploymentMethod.execute().deploy(targetURL, bundleFile, bundleName, new DeployContext()
.log(getLog())
- .httpClient(getHttpClient())
+ .httpClient(httpClient)
.failOnError(failOnError)
.bundleStartLevel(bundleStartLevel)
.bundleStart(bundleStart)
.mimeType(mimeType)
.refreshPackages(refreshPackages));
-
- if ( mountByFS ) {
- configure(getConsoleTargetURL(), bundleFile);
+ getLog().info("Bundle installed successfully");
+ if ( mountByFS ) {
+ configure(httpClient, getConsoleTargetURL(), bundleFile);
+ }
+ } catch (IOException e) {
+ String msg = "Installation failed, cause: "
+ + e.getMessage();
+ if (failOnError) {
+ throw new MojoExecutionException(msg, e);
+ } else {
+ getLog().error(msg, e);
+ }
}
}
- protected void configure(final String targetURL, final File file) throws MojoExecutionException {
- new SlingInitialContentMounter(getLog(), getHttpClient(), project).mount(targetURL, file);
+ protected void configure(CloseableHttpClient httpClient, final URI targetURL, final File file) throws MojoExecutionException {
+ new SlingInitialContentMounter(getLog(), httpClient, project).mount(targetURL, file);
}
/**
diff --git a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/AbstractBundlePostMojo.java b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/AbstractBundleRequestMojo.java
similarity index 54%
rename from sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/AbstractBundlePostMojo.java
rename to sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/AbstractBundleRequestMojo.java
index eb05238..d92083f 100644
--- a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/AbstractBundlePostMojo.java
+++ b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/AbstractBundleRequestMojo.java
@@ -20,35 +20,46 @@ package org.apache.sling.maven.bundlesupport;
import java.io.File;
import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
-import org.apache.commons.httpclient.Credentials;
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.UsernamePasswordCredentials;
-import org.apache.commons.httpclient.auth.AuthScope;
-import org.apache.commons.lang3.StringUtils;
+import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
+import org.apache.hc.client5.http.config.RequestConfig;
+import org.apache.hc.client5.http.impl.auth.BasicScheme;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
+import org.apache.hc.client5.http.impl.classic.HttpClients;
+import org.apache.hc.client5.http.protocol.HttpClientContext;
+import org.apache.hc.core5.http.EntityDetails;
+import org.apache.hc.core5.http.HttpException;
+import org.apache.hc.core5.http.HttpHost;
+import org.apache.hc.core5.http.HttpRequest;
+import org.apache.hc.core5.http.HttpRequestInterceptor;
+import org.apache.hc.core5.http.protocol.HttpContext;
+import org.apache.hc.core5.util.Timeout;
import org.apache.maven.plugin.AbstractMojo;
+import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugins.annotations.Parameter;
-abstract class AbstractBundlePostMojo extends AbstractMojo {
+abstract class AbstractBundleRequestMojo extends AbstractMojo {
/**
* The URL of the running Sling instance.
*
* <p>The default is only useful for <strong>WebConsole</strong> deployment.</p>
*
- * <p>For <strong>WebDAV</strong> deployment it is recommended to include the Sling Simple WebDAV servlet root, for instance <a href="http://localhost:8080/dav/default/libs/sling/install">http://localhost:8080/dav/default/libs/sling/install</a>. Omitting the {@code dav/default} segment can lead to conflicts with other servlets.</p>
+ * <p>For <strong>WebDAV</strong> deployment it is recommended to include the <a href="https://sling.apache.org/documentation/development/repository-based-development.html#separate-uri-space-webdav">Sling Simple WebDAV servlet root</a>, for instance <a href="http://localhost:8080/dav/default/libs/sling/install">http://localhost:8080/dav/default/libs/sling/install</a>. Omitting the {@code dav/default} segment can lead to conflicts with other servlets.</p>
*/
@Parameter(property="sling.url", defaultValue="http://localhost:8080/system/console", required = true)
- protected String slingUrl;
+ protected URI slingUrl;
/**
* The WebConsole URL of the running Sling instance. This is required for file system provider operations.
* If not configured the value of slingUrl is used.
*/
@Parameter(property="sling.console.url")
- protected String slingConsoleUrl;
+ protected URI slingConsoleUrl;
/**
* An optional url suffix which will be appended to the <code>sling.url</code>
@@ -144,42 +155,85 @@ abstract class AbstractBundlePostMojo extends AbstractMojo {
}
/**
- * @return Returns the combination of <code>sling.url</code> and <code>sling.urlSuffix</code>.
+ * @return Returns the combination of <code>sling.url</code> and <code>sling.urlSuffix</code>. Always ends with "/".
*/
- protected String getTargetURL() {
- String targetURL = slingUrl;
+ protected URI getTargetURL() {
+ final URI targetURL;
if (slingUrlSuffix != null) {
- targetURL += slingUrlSuffix;
+ targetURL = slingUrl.resolve(slingUrlSuffix);
+ } else {
+ targetURL = slingUrl;
}
- return targetURL;
+ return addTrailingSlash(targetURL);
}
/**
- * @return Returns the combination of <code>sling.console.url</code> and <code>sling.urlSuffix</code>.
+ * @return Returns the combination of <code>sling.console.url</code> and <code>sling.urlSuffix</code>. Always ends with "/".
*/
- protected String getConsoleTargetURL() {
- String targetURL = StringUtils.defaultString(slingConsoleUrl, slingUrl);
+ protected URI getConsoleTargetURL() {
+ URI targetURL = slingConsoleUrl != null ? slingConsoleUrl : slingUrl;
if (slingUrlSuffix != null) {
- targetURL += slingUrlSuffix;
+ targetURL = targetURL.resolve(slingUrlSuffix);
+ }
+ return addTrailingSlash(targetURL);
+ }
+
+ public static URI addTrailingSlash(URI targetURL) {
+ if (!targetURL.getPath().endsWith("/")) {
+ String path = targetURL.getPath()+"/";
+ try {
+ return new URI(targetURL.getScheme(), targetURL.getUserInfo(), targetURL.getHost(), targetURL.getPort(), path, targetURL.getQuery(), targetURL.getFragment());
+ } catch (URISyntaxException e) {
+ throw new IllegalStateException("Could not create new URI from existing one", e); // should never happen
+ }
+ } else {
+ return targetURL;
}
- return targetURL;
}
/**
* @return Get the http client
*/
- protected HttpClient getHttpClient() {
- final HttpClient client = new HttpClient();
- client.getHttpConnectionManager().getParams().setConnectionTimeout(
- 5000);
-
- // authentication stuff
- client.getParams().setAuthenticationPreemptive(true);
- Credentials defaultcreds = new UsernamePasswordCredentials(user,
- password);
- client.getState().setCredentials(AuthScope.ANY, defaultcreds);
-
- return client;
+ protected CloseableHttpClient getHttpClient() {
+ // Generate Basic scheme object
+ final BasicScheme basicAuth = new BasicScheme();
+ basicAuth.initPreemptive(new UsernamePasswordCredentials(user, password.toCharArray()));
+
+ // restrict to the Sling URL only
+ final HttpHost target = new HttpHost(getTargetURL().getScheme(), getTargetURL().getHost(), getTargetURL().getPort());
+
+ RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(Timeout.ofSeconds(5)).build();
+
+ return HttpClients.custom()
+ .setDefaultRequestConfig(requestConfig)
+ .addRequestInterceptorFirst(new PreemptiveBasicAuthInterceptor(basicAuth, target, getLog()))
+ .build();
}
+
+ private static final class PreemptiveBasicAuthInterceptor implements HttpRequestInterceptor {
+
+ private final BasicScheme basicAuth;
+ private final HttpHost targetHost;
+ private final Log log;
+
+ public PreemptiveBasicAuthInterceptor(BasicScheme basicAuth, HttpHost targetHost, Log log) {
+ super();
+ this.basicAuth = basicAuth;
+ this.targetHost = targetHost;
+ this.log = log;
+ }
+
+ @Override
+ public void process(HttpRequest request, EntityDetails entity, HttpContext context) throws HttpException, IOException {
+ if (!(context instanceof HttpClientContext)) {
+ throw new IllegalStateException("This interceptor only supports HttpClientContext but context is of type " + context.getClass());
+ }
+ HttpClientContext httpClientContext = (HttpClientContext)context;
+
+ log.debug("Adding preemptive authentication to request for target host " + targetHost);
+ // as the AuthExchange object is already retrieved by the client when the interceptor kicks in, it needs to modify the existing object
+ httpClientContext.getAuthExchange(targetHost).select(basicAuth);
+ }
+ }
}
diff --git a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/AbstractFsMountMojo.java b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/AbstractFsMountMojo.java
index 7d53418..af58bd1 100644
--- a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/AbstractFsMountMojo.java
+++ b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/AbstractFsMountMojo.java
@@ -24,9 +24,12 @@ import static org.apache.jackrabbit.vault.util.Constants.ROOT_DIR;
import static org.apache.jackrabbit.vault.util.Constants.VAULT_DIR;
import java.io.File;
+import java.io.IOException;
+import java.net.URI;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
@@ -36,7 +39,7 @@ import org.apache.maven.project.MavenProject;
/**
* Manages OSGi configurations for File System Resource provider.
*/
-abstract class AbstractFsMountMojo extends AbstractBundlePostMojo {
+abstract class AbstractFsMountMojo extends AbstractBundleRequestMojo {
/**
* The name of the generated JAR file.
@@ -76,38 +79,40 @@ abstract class AbstractFsMountMojo extends AbstractBundlePostMojo {
return;
}
- String targetUrl = getConsoleTargetURL();
-
- // ensure required bundles are installed
- ensureBundlesInstalled(targetUrl);
-
- // check for Sling-Initial-Content
- File bundleFile = new File(bundleFileName);
- if (bundleFile.exists()) {
- configureSlingInitialContent(targetUrl, bundleFile);
- return;
- }
-
- // try to detect filevault layout
- File jcrRootFile;
- File filterXmlFile;
- if (fileVaultJcrRootFile != null) {
- jcrRootFile = fileVaultJcrRootFile;
- }
- else {
- jcrRootFile = detectJcrRootFile();
- }
- if (fileVaultFilterXmlFile != null) {
- filterXmlFile = fileVaultFilterXmlFile;
- }
- else {
- filterXmlFile = detectFilterXmlFile();
- }
- if (jcrRootFile != null && jcrRootFile.exists() && filterXmlFile != null && filterXmlFile.exists()) {
- configureFileVaultXml(targetUrl, jcrRootFile, filterXmlFile);
- return;
+ URI targetUrl = getConsoleTargetURL();
+ try (CloseableHttpClient httpClient = getHttpClient()) {
+ // ensure required bundles are installed
+ ensureBundlesInstalled(httpClient, targetUrl);
+
+ // check for Sling-Initial-Content
+ File bundleFile = new File(bundleFileName);
+ if (bundleFile.exists()) {
+ configureSlingInitialContent(httpClient, targetUrl, bundleFile);
+ return;
+ }
+
+ // try to detect filevault layout
+ File jcrRootFile;
+ File filterXmlFile;
+ if (fileVaultJcrRootFile != null) {
+ jcrRootFile = fileVaultJcrRootFile;
+ }
+ else {
+ jcrRootFile = detectJcrRootFile();
+ }
+ if (fileVaultFilterXmlFile != null) {
+ filterXmlFile = fileVaultFilterXmlFile;
+ }
+ else {
+ filterXmlFile = detectFilterXmlFile();
+ }
+ if (jcrRootFile != null && jcrRootFile.exists() && filterXmlFile != null && filterXmlFile.exists()) {
+ configureFileVaultXml(httpClient, targetUrl, jcrRootFile, filterXmlFile);
+ return;
+ }
+ } catch (IOException e) {
+ getLog().error("Could not close underlying HTTP client" + e.getMessage(), e);
}
-
getLog().info("No Bundle with initial content or FileVault content package found - skipping.");
}
@@ -158,13 +163,13 @@ abstract class AbstractFsMountMojo extends AbstractBundlePostMojo {
return null;
}
- protected abstract void configureSlingInitialContent(final String targetUrl, final File bundleFile)
+ protected abstract void configureSlingInitialContent(CloseableHttpClient httpClient, final URI targetUrl, final File bundleFile)
throws MojoExecutionException;
- protected abstract void configureFileVaultXml(final String targetUrl, final File jcrRootFile, final File filterXmlFile)
+ protected abstract void configureFileVaultXml(CloseableHttpClient httpClient, final URI targetUrl, final File jcrRootFile, final File filterXmlFile)
throws MojoExecutionException;
- protected abstract void ensureBundlesInstalled(final String targetUrl)
+ protected abstract void ensureBundlesInstalled(CloseableHttpClient httpClient, final URI targetUrl)
throws MojoExecutionException;
}
\ No newline at end of file
diff --git a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/BundleInstallFileMojo.java b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/BundleInstallFileMojo.java
index 2f33de2..5cde07d 100644
--- a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/BundleInstallFileMojo.java
+++ b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/BundleInstallFileMojo.java
@@ -17,33 +17,44 @@
package org.apache.sling.maven.bundlesupport;
+import java.io.File;
import java.util.ArrayList;
import java.util.List;
-import org.apache.maven.artifact.Artifact;
-import org.apache.maven.artifact.repository.ArtifactRepository;
-import org.apache.maven.artifact.repository.ArtifactRepositoryFactory;
-import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy;
-import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
-import org.apache.maven.artifact.resolver.AbstractArtifactResolutionException;
-import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.plexus.util.StringUtils;
+import org.eclipse.aether.RepositorySystem;
+import org.eclipse.aether.RepositorySystemSession;
+import org.eclipse.aether.artifact.DefaultArtifact;
+import org.eclipse.aether.repository.RemoteRepository;
+import org.eclipse.aether.repository.RepositoryPolicy;
+import org.eclipse.aether.resolution.ArtifactRequest;
+import org.eclipse.aether.resolution.ArtifactResolutionException;
+import org.eclipse.aether.resolution.ArtifactResult;
/**
- * Install an OSGi bundle to a running Sling instance.
+ * Install an OSGi bundle from a given file path or Maven coordinates (resolved from the repository) to a running Sling instance.
+ * One of the following parameter sets must be set to determine the bundle to install:
+ * <ul>
+ * <li>{@link #bundleFileName}</li>
+ * <li>{@link #groupId}, {@link #artifactId}, {@link #version}, {@link #packaging} and optionally {@link #classifier}</li>
+ * <li>{@link #artifact}</li>
+ * </ul>
+ *
+ * To install a bundle which has been built from the current Maven project rather use goal <a href="install-mojo.html">install</a>.
+ * For details refer to <a href="bundle-installation.html">Bundle Installation</a>.
*/
@Mojo(name = "install-file", requiresProject = false)
public class BundleInstallFileMojo extends AbstractBundleInstallMojo {
/**
- * The name of the generated JAR file.
+ * The path of the bundle file to install.
*/
@Parameter(property="sling.file")
- private String bundleFileName;
+ private File bundleFileName;
/**
* The groupId of the artifact to install
@@ -76,45 +87,23 @@ public class BundleInstallFileMojo extends AbstractBundleInstallMojo {
private String classifier;
/**
- * A string of the form groupId:artifactId:version[:packaging[:classifier]].
+ * A string of the form {@code groupId:artifactId:version[:packaging[:classifier]]}.
*/
@Parameter(property="sling.artifact")
private String artifact;
- @Parameter(property="project.remoteArtifactRepositories", required = true, readonly = true)
- private List pomRemoteRepositories;
-
- /**
- * The id of the repository from which we'll download the artifact
- */
- @Parameter(property = "sling.repoId", defaultValue = "temp")
- private String repositoryId = "temp";
-
- /**
- * The url of the repository from which we'll download the artifact
- */
- @Parameter(property = "sling.repoUrl")
- private String repositoryUrl;
-
- @SuppressWarnings("deprecation")
@Component
- private org.apache.maven.artifact.factory.ArtifactFactory artifactFactory;
+ private RepositorySystem repoSystem;
- @Component
- private ArtifactResolver artifactResolver;
-
- @Component
- private ArtifactRepositoryFactory artifactRepositoryFactory;
+ @Parameter( defaultValue = "${repositorySystemSession}", readonly = true, required = true )
+ private RepositorySystemSession repoSession;
- @Component(hint="default")
- private ArtifactRepositoryLayout repositoryLayout;
-
- @Parameter(property="localRepository", readonly = true)
- private ArtifactRepository localRepository;
+ @Parameter( defaultValue = "${project.remoteProjectRepositories}", readonly = true, required = true )
+ private List<RemoteRepository> repositories;
@Override
- protected String getBundleFileName() throws MojoExecutionException {
- String fileName = bundleFileName;
+ protected File getBundleFileName() throws MojoExecutionException {
+ File fileName = bundleFileName;
if (fileName == null) {
fileName = resolveBundleFileFromArtifact();
@@ -126,8 +115,7 @@ public class BundleInstallFileMojo extends AbstractBundleInstallMojo {
return fileName;
}
- @SuppressWarnings({ "rawtypes", "unchecked", "deprecation" })
- private String resolveBundleFileFromArtifact() throws MojoExecutionException {
+ private File resolveBundleFileFromArtifact() throws MojoExecutionException {
if (artifactId == null && artifact == null) {
return null;
}
@@ -145,31 +133,31 @@ public class BundleInstallFileMojo extends AbstractBundleInstallMojo {
if (tokens.length == 5)
classifier = tokens[4];
}
- Artifact packageArtifact = artifactFactory.createArtifactWithClassifier(groupId, artifactId, version, packaging, classifier);
-
- if (pomRemoteRepositories == null) {
- pomRemoteRepositories = new ArrayList();
- }
-
- List repoList = new ArrayList(pomRemoteRepositories);
-
- if (repositoryUrl != null) {
- ArtifactRepositoryPolicy policy =
- new ArtifactRepositoryPolicy( true, ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS,
- ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN );
- ArtifactRepository remoteRepo = artifactRepositoryFactory.createArtifactRepository(repositoryId, repositoryUrl,
- repositoryLayout, policy, policy);
- repoList.add(remoteRepo);
- }
+ File resolvedArtifactFile = resolveArtifact(new DefaultArtifact(groupId, artifactId, classifier, packaging, version));
+ getLog().info("Resolved artifact to " + resolvedArtifactFile.getAbsolutePath());
+ return resolvedArtifactFile;
+ }
+ protected File resolveArtifact(org.eclipse.aether.artifact.Artifact artifact) throws MojoExecutionException {
+ ArtifactRequest req = new ArtifactRequest(artifact, getRemoteRepositoriesWithUpdatePolicy(repositories, RepositoryPolicy.UPDATE_POLICY_ALWAYS), null);
+ ArtifactResult resolutionResult;
try {
- artifactResolver.resolve(packageArtifact, repoList, localRepository);
- getLog().info("Resolved artifact to " + packageArtifact.getFile().getAbsolutePath());
- } catch (AbstractArtifactResolutionException e) {
- throw new MojoExecutionException("Couldn't download artifact: " + e.getMessage(), e);
+ resolutionResult = repoSystem.resolveArtifact(repoSession, req);
+ return resolutionResult.getArtifact().getFile();
+ } catch (ArtifactResolutionException e) {
+ throw new MojoExecutionException("Artifact " + artifact + " could not be resolved.", e);
}
+ }
- return packageArtifact.getFile().getAbsolutePath();
+ private List<RemoteRepository> getRemoteRepositoriesWithUpdatePolicy(List<RemoteRepository> repositories, String updatePolicy) {
+ List<RemoteRepository> newRepositories = new ArrayList<>();
+ for (RemoteRepository repo : repositories) {
+ RemoteRepository.Builder builder = new RemoteRepository.Builder(repo);
+ RepositoryPolicy newPolicy = new RepositoryPolicy(repo.getPolicy(false).isEnabled(), updatePolicy, repo.getPolicy(false).getChecksumPolicy());
+ builder.setPolicy(newPolicy);
+ newRepositories.add(builder.build());
+ }
+ return newRepositories;
}
}
\ No newline at end of file
diff --git a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/BundleInstallMojo.java b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/BundleInstallMojo.java
index 6c5d5db..6ecc098 100644
--- a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/BundleInstallMojo.java
+++ b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/BundleInstallMojo.java
@@ -17,57 +17,32 @@
package org.apache.sling.maven.bundlesupport;
+import java.io.File;
+
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;
/**
- * Install an OSGi bundle to a running Sling instance.
- * The plugin places an HTTP POST request to
- * <a href="http://felix.apache.org/documentation/subprojects/apache-felix-web-console/web-console-restful-api.html#post-requests">Felix Web Console</a>.
- * It's also possible to HTTP PUT instead of POST leveraging the <a href="http://sling.apache.org/documentation/development/repository-based-development.html">WebDAV bundle from Sling</a>.
- * Since version 2.1.8 you can also leverage the the <a href="http://sling.apache.org/documentation/bundles/manipulating-content-the-slingpostservlet-servlets-post.html">Sling POST servlet</a>
- * for that The chosen method depends on the parameter {@link #deploymentMethod}.
- * <br>
- * <p><strong>Intermediate Node Creation</strong></p>
- * <p>
- * For all <code>deploymentMethod</code>s except WebDAV the bundle is not directly deployed within the OSGi container,
- * but rather being uploaded to the JCR and from there on being picked up by the
- * <a href="https://sling.apache.org/documentation/bundles/jcr-installer-provider.html">JCR Installer Provider</a> asynchronously, which takes care
- * of deploying it in the OSGi container. For both other deployment methods, intermediate nodes (i.e. inexisting parent nodes)
- * are automatically created. The primary type of those intermediate nodes depend on the deployment method.
- * </p>
- * <ul>
- * <li>
- * WebDAV, uses the configured collection node type, by default <code>sling:Folder</code>
- * (see also <a href="https://sling.apache.org/documentation/development/repository-based-development.html">WebDAV Configuration</a>)</li>
- * <li>
- * SlingPostServlet, uses internally <code>ResourceResolverFactory.create(...)</code> without setting any <code>jcr:primaryType</code>.
- * Therefore the <code>JcrResourceProviderFactory</code> will call <code>Node.addNode(String relPath)</code> which determines a fitting
- * node type automatically, depending on the parents node type definition (see <a href="https://docs.adobe.com/docs/en/spec/jsr170/javadocs/jcr-2.0/javax/jcr/Node.html#addNode(java.lang.String)">Javadoc</a>).
- * So in most of the cases this should be a <code>sling:Folder</code>, as this is the first allowed child node definition in <code>sling:Folder</code>.
- * This only may differ, if your existing parent node is not of type <code>sling:Folder</code> itself.
- * </li>
- * </ul>
+ * Install a local OSGi bundle file to a running Sling instance.
+ * For details refer to <a href="bundle-installation.html">Bundle Installation</a>.
*/
@Mojo(name = "install", defaultPhase = LifecyclePhase.INSTALL)
public class BundleInstallMojo extends AbstractBundleInstallMojo {
/**
* Whether to skip this step even though it has been configured in the
- * project to be executed. This property may be set by the
- * <code>sling.install.skip</code> comparable to the <code>maven.test.skip</code>
- * property to prevent running the unit tests.
+ * project to be executed.
*/
@Parameter(property = "sling.install.skip", defaultValue = "false", required = true)
private boolean skip;
/**
- * The name of the generated JAR file.
+ * The path of the bundle file to install.
*/
@Parameter(property = "sling.file", defaultValue = "${project.build.directory}/${project.build.finalName}.jar", required = true)
- private String bundleFileName;
+ private File bundleFileName;
@Override
public void execute() throws MojoExecutionException {
@@ -81,7 +56,7 @@ public class BundleInstallMojo extends AbstractBundleInstallMojo {
}
@Override
- protected String getBundleFileName() {
+ protected File getBundleFileName() {
return bundleFileName;
}
}
\ No newline at end of file
diff --git a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/BundleUninstallMojo.java b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/BundleUninstallMojo.java
index d6dc19e..f550e5d 100644
--- a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/BundleUninstallMojo.java
+++ b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/BundleUninstallMojo.java
@@ -19,7 +19,10 @@
package org.apache.sling.maven.bundlesupport;
import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
@@ -43,10 +46,10 @@ public class BundleUninstallMojo extends AbstractBundleInstallMojo {
* The name of the generated JAR file.
*/
@Parameter(property = "sling.file", defaultValue = "${project.build.directory}/${project.build.finalName}.jar")
- private String bundleFileName;
+ private File bundleFileName;
@Override
- protected String getBundleFileName() {
+ protected File getBundleFileName() {
return bundleFileName;
}
@@ -55,33 +58,44 @@ public class BundleUninstallMojo extends AbstractBundleInstallMojo {
*/
@Override
public void execute() throws MojoExecutionException {
- // only upload if packaging as an osgi-bundle
- final File bundleFile = new File(bundleFileName);
+ // only uninstall if packaging as an osgi-bundle
+ final File bundleFile = getBundleFileName();
final String bundleName = getBundleSymbolicName(bundleFile);
if (bundleName == null) {
getLog().info(bundleFile + " is not an OSGi Bundle, not uploading");
return;
}
- String targetURL = getTargetURL();
+ URI targetURL = getTargetURL();
BundleDeploymentMethod deployMethod = getDeploymentMethod();
- getLog().info(
- "Unistalling Bundle " + bundleName + " from "
- + targetURL + " via " + deployMethod);
- configure(targetURL, bundleFile);
- deployMethod.execute().undeploy(targetURL, bundleFile, bundleName, new DeployContext()
- .log(getLog())
- .httpClient(getHttpClient())
- .failOnError(failOnError)
- .mimeType(mimeType));
+ try (CloseableHttpClient httpClient = getHttpClient()){
+ configure(httpClient, targetURL, bundleFile);
+ getLog().info(
+ "Uninstalling Bundle " + bundleName + " from "
+ + targetURL + " via " + deployMethod + "...");
+ deployMethod.execute().undeploy(targetURL, bundleFile, bundleName, new DeployContext()
+ .log(getLog())
+ .httpClient(httpClient)
+ .failOnError(failOnError)
+ .mimeType(mimeType));
+ getLog().info("Bundle uninstalled successfully!");
+ } catch (IOException e) {
+ String msg = "Uninstall from " + targetURL
+ + " failed, cause: " + e.getMessage();
+ if (failOnError) {
+ throw new MojoExecutionException(msg, e);
+ } else {
+ getLog().error(msg, e);
+ }
+ }
}
@Override
- protected void configure(final String targetURL, final File file) throws MojoExecutionException {
- new SlingInitialContentMounter(getLog(), getHttpClient(), project).unmount(targetURL, file);
+ protected void configure(CloseableHttpClient httpClient, final URI targetURL, final File file) throws MojoExecutionException {
+ new SlingInitialContentMounter(getLog(), httpClient, project).unmount(targetURL, file);
}
}
\ No newline at end of file
diff --git a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/FsMountMojo.java b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/FsMountMojo.java
index de8478e..9547e14 100644
--- a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/FsMountMojo.java
+++ b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/FsMountMojo.java
@@ -19,8 +19,7 @@ package org.apache.sling.maven.bundlesupport;
import java.io.File;
import java.io.IOException;
-import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
+import java.net.URI;
import java.util.ArrayList;
import java.util.List;
@@ -28,10 +27,10 @@ import javax.json.JsonArray;
import javax.json.JsonException;
import javax.json.JsonObject;
-import org.apache.commons.httpclient.HttpException;
-import org.apache.commons.httpclient.methods.GetMethod;
-import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.client5.http.impl.classic.BasicHttpClientResponseHandler;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolutionRequest;
@@ -164,17 +163,17 @@ public class FsMountMojo extends AbstractFsMountMojo {
}
@Override
- protected void configureSlingInitialContent(final String targetUrl, final File bundleFile) throws MojoExecutionException {
+ protected void configureSlingInitialContent(CloseableHttpClient httpClient, final URI targetUrl, final File bundleFile) throws MojoExecutionException {
new SlingInitialContentMounter(getLog(), getHttpClient(), project).mount(targetUrl, bundleFile);
}
@Override
- protected void configureFileVaultXml(String targetUrl, File jcrRootFile, File filterXmlFile) throws MojoExecutionException {
- new FileVaultXmlMounter(getLog(), getHttpClient(), project).mount(targetUrl, jcrRootFile, filterXmlFile);
+ protected void configureFileVaultXml(CloseableHttpClient httpClient, URI targetUrl, File jcrRootFile, File filterXmlFile) throws MojoExecutionException {
+ new FileVaultXmlMounter(getLog(), httpClient, project).mount(targetUrl, jcrRootFile, filterXmlFile);
}
@Override
- protected void ensureBundlesInstalled(String targetUrl) throws MojoExecutionException {
+ protected void ensureBundlesInstalled(CloseableHttpClient httpClient,URI targetUrl) throws MojoExecutionException {
if (!deployFsResourceBundle) {
return;
}
@@ -194,43 +193,52 @@ public class FsMountMojo extends AbstractFsMountMojo {
}
for (BundlePrerequisite bundlePrerequisite : deployFsResourceBundlePrerequisites) {
- if (isBundlePrerequisitesPreconditionsMet(bundlePrerequisite, targetUrl)) {
+ if (isBundlePrerequisitesPreconditionsMet(httpClient, bundlePrerequisite, targetUrl)) {
for (Bundle bundle : bundlePrerequisite.getBundles()) {
- deployBundle(bundle, targetUrl);
+ deployBundle(httpClient, bundle, targetUrl);
}
break;
}
}
}
- private void deployBundle(Bundle bundle, String targetUrl) throws MojoExecutionException {
- if (isBundleInstalled(bundle, targetUrl)) {
- getLog().debug("Bundle " + bundle.getSymbolicName() + " " + bundle.getOsgiVersion() + " (or higher) already installed.");
- return;
+ private void deployBundle(CloseableHttpClient httpClient, Bundle bundle, URI targetUrl) throws MojoExecutionException {
+ try {
+ if (isBundleInstalled(httpClient, bundle, targetUrl)) {
+ getLog().debug("Bundle " + bundle.getSymbolicName() + " " + bundle.getOsgiVersion() + " (or higher) already installed.");
+ return;
+ }
+
+ getLog().info("Installing Bundle " + bundle.getSymbolicName() + " " + bundle.getOsgiVersion() + " to "
+ + targetUrl + " via " + deploymentMethod);
+
+ File file = getArtifactFile(bundle, "jar");
+ deploymentMethod.execute().deploy(targetUrl, file, bundle.getSymbolicName(), new DeployContext()
+ .log(getLog())
+ .httpClient(httpClient)
+ .failOnError(failOnError));
+ } catch(IOException e) {
+ throw new MojoExecutionException("Error deploying bundle " + bundle + " to " + targetUrl + ": " + e.getMessage(), e);
}
-
- getLog().info("Installing Bundle " + bundle.getSymbolicName() + " " + bundle.getOsgiVersion() + " to "
- + targetUrl + " via " + deploymentMethod);
-
- File file = getArtifactFile(bundle, "jar");
- deploymentMethod.execute().deploy(targetUrl, file, bundle.getSymbolicName(), new DeployContext()
- .log(getLog())
- .httpClient(getHttpClient())
- .failOnError(failOnError));
}
- private boolean isBundlePrerequisitesPreconditionsMet(BundlePrerequisite bundlePrerequisite, String targetUrl) throws MojoExecutionException {
+ private boolean isBundlePrerequisitesPreconditionsMet(CloseableHttpClient httpClient, BundlePrerequisite bundlePrerequisite, URI targetUrl) throws MojoExecutionException {
for (Bundle precondition : bundlePrerequisite.getPreconditions()) {
- if (!isBundleInstalled(precondition, targetUrl)) {
- getLog().debug("Bundle " + precondition.getSymbolicName() + " " + precondition.getOsgiVersion() + " (or higher) is not installed.");
- return false;
+ try {
+ if (!isBundleInstalled(httpClient, precondition, targetUrl)) {
+ getLog().debug("Bundle " + precondition.getSymbolicName() + " " + precondition.getOsgiVersion() + " (or higher) is not installed.");
+ return false;
+ }
+ } catch (IOException e) {
+ throw new MojoExecutionException("Reading bundle data for bundle " + precondition
+ + " failed, cause: " + e.getMessage(), e);
}
}
return true;
}
- private boolean isBundleInstalled(Bundle bundle, String targetUrl) throws MojoExecutionException {
- String installedVersionString = getBundleInstalledVersion(bundle.getSymbolicName(), targetUrl);
+ private boolean isBundleInstalled(CloseableHttpClient httpClient, Bundle bundle, URI targetUrl) throws IOException {
+ String installedVersionString = getBundleInstalledVersion(httpClient, bundle.getSymbolicName(), targetUrl);
if (StringUtils.isBlank(installedVersionString)) {
return false;
}
@@ -241,46 +249,28 @@ public class FsMountMojo extends AbstractFsMountMojo {
/**
* Get version of fsresource bundle that is installed in the instance.
+ * @param httpClient the http client to use
* @param targetUrl Target URL
* @return Version number or null if non installed
* @throws MojoExecutionException
*/
- private String getBundleInstalledVersion(final String bundleSymbolicName, final String targetUrl) throws MojoExecutionException {
- final String getUrl = targetUrl + "/bundles/" + bundleSymbolicName + ".json";
- final GetMethod get = new GetMethod(getUrl);
+ private String getBundleInstalledVersion(CloseableHttpClient httpClient, final String bundleSymbolicName, final URI targetUrl) throws IOException {
+ final URI getUrl = targetUrl.resolve( "/bundles/" + bundleSymbolicName + ".json");
+ final HttpGet get = new HttpGet(getUrl);
+ final String jsonText = httpClient.execute(get, new BasicHttpClientResponseHandler());
try {
- final int status = getHttpClient().executeMethod(get);
- if ( status == 200 ) {
- final String jsonText;
- try (InputStream jsonResponse = get.getResponseBodyAsStream()) {
- jsonText = IOUtils.toString(jsonResponse, StandardCharsets.UTF_8);
- }
- try {
- JsonObject response = JsonSupport.parseObject(jsonText);
- JsonArray data = response.getJsonArray("data");
- if (data.size() > 0) {
- JsonObject bundleData = data.getJsonObject(0);
- return bundleData.getString("version");
- }
-
- } catch (JsonException ex) {
- throw new MojoExecutionException("Reading bundle data from " + getUrl
- + " failed, cause: " + ex.getMessage(), ex);
- }
+ JsonObject response = JsonSupport.parseObject(jsonText);
+ JsonArray data = response.getJsonArray("data");
+ if (!data.isEmpty()) {
+ JsonObject bundleData = data.getJsonObject(0);
+ return bundleData.getString("version");
}
- }
- catch (HttpException ex) {
- throw new MojoExecutionException("Reading bundle data from " + getUrl
- + " failed, cause: " + ex.getMessage(), ex);
- }
- catch (IOException ex) {
- throw new MojoExecutionException("Reading bundle data from " + getUrl
+
+ } catch (JsonException ex) {
+ throw new IOException("Reading bundle data from " + getUrl
+ " failed, cause: " + ex.getMessage(), ex);
}
- finally {
- get.releaseConnection();
- }
// no version detected, bundle is not installed
return null;
}
diff --git a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/FsUnMountMojo.java b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/FsUnMountMojo.java
index 43bc967..0e7ee0c 100644
--- a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/FsUnMountMojo.java
+++ b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/FsUnMountMojo.java
@@ -18,7 +18,9 @@
package org.apache.sling.maven.bundlesupport;
import java.io.File;
+import java.net.URI;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.sling.maven.bundlesupport.fsresource.FileVaultXmlMounter;
@@ -33,17 +35,17 @@ import org.apache.sling.maven.bundlesupport.fsresource.SlingInitialContentMounte
public class FsUnMountMojo extends AbstractFsMountMojo {
@Override
- protected void configureSlingInitialContent(final String targetUrl, final File bundleFile) throws MojoExecutionException {
- new SlingInitialContentMounter(getLog(), getHttpClient(), project).unmount(targetUrl, bundleFile);
+ protected void configureSlingInitialContent(CloseableHttpClient httpClient, final URI targetUrl, final File bundleFile) throws MojoExecutionException {
+ new SlingInitialContentMounter(getLog(), httpClient, project).unmount(targetUrl, bundleFile);
}
@Override
- protected void configureFileVaultXml(String targetUrl, File jcrRootFile, File filterXmlFile) throws MojoExecutionException {
- new FileVaultXmlMounter(getLog(), getHttpClient(), project).unmount(targetUrl, jcrRootFile, filterXmlFile);
+ protected void configureFileVaultXml(CloseableHttpClient httpClient, URI targetUrl, File jcrRootFile, File filterXmlFile) throws MojoExecutionException {
+ new FileVaultXmlMounter(getLog(), httpClient, project).unmount(targetUrl, jcrRootFile, filterXmlFile);
}
@Override
- protected void ensureBundlesInstalled(String targetUrl) throws MojoExecutionException {
+ protected void ensureBundlesInstalled(CloseableHttpClient httpClient, URI targetUrl) throws MojoExecutionException {
// nothing to do on uninstall
}
diff --git a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/DeployContext.java b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/DeployContext.java
index a622d58..9f9ca6e 100644
--- a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/DeployContext.java
+++ b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/DeployContext.java
@@ -18,13 +18,13 @@
*/
package org.apache.sling.maven.bundlesupport.deploy;
-import org.apache.commons.httpclient.HttpClient;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.maven.plugin.logging.Log;
public final class DeployContext {
private Log log;
- private HttpClient httpClient;
+ private CloseableHttpClient httpClient;
private boolean failOnError = true;
private String bundleStartLevel = "20";
private boolean bundleStart = true;
@@ -38,10 +38,10 @@ public final class DeployContext {
this.log = log;
return this;
}
- public HttpClient getHttpClient() {
+ public CloseableHttpClient getHttpClient() {
return httpClient;
}
- public DeployContext httpClient(HttpClient httpClient) {
+ public DeployContext httpClient(CloseableHttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
diff --git a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/DeployMethod.java b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/DeployMethod.java
index cdf3454..31a8689 100644
--- a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/DeployMethod.java
+++ b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/DeployMethod.java
@@ -19,6 +19,8 @@
package org.apache.sling.maven.bundlesupport.deploy;
import java.io.File;
+import java.io.IOException;
+import java.net.URI;
import org.apache.maven.plugin.MojoExecutionException;
@@ -35,7 +37,7 @@ public interface DeployMethod {
* @param context Deploy context parameters
* @throws MojoExecutionException Mojo execution execution
*/
- void deploy(String targetURL, File file, String bundleSymbolicName, DeployContext context) throws MojoExecutionException;
+ void deploy(URI targetURL, File file, String bundleSymbolicName, DeployContext context) throws IOException;
/**
* Undeploy/uninstall a bundle on a Sling instance.
@@ -45,6 +47,6 @@ public interface DeployMethod {
* @param context Deploy context parameters
* @throws MojoExecutionException Mojo execution execution
*/
- void undeploy(String targetURL, File file, String bundleSymbolicName, DeployContext context) throws MojoExecutionException;
+ void undeploy(URI targetURL, File file, String bundleSymbolicName, DeployContext context) throws IOException;
}
diff --git a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/method/FelixPostDeployMethod.java b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/method/FelixPostDeployMethod.java
index b47ac8a..bda2b89 100644
--- a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/method/FelixPostDeployMethod.java
+++ b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/method/FelixPostDeployMethod.java
@@ -19,93 +19,79 @@
package org.apache.sling.maven.bundlesupport.deploy.method;
import java.io.File;
+import java.io.IOException;
+import java.net.URI;
import java.util.ArrayList;
import java.util.List;
-import org.apache.commons.httpclient.HttpStatus;
-import org.apache.commons.httpclient.methods.PostMethod;
-import org.apache.commons.httpclient.methods.multipart.FilePart;
-import org.apache.commons.httpclient.methods.multipart.FilePartSource;
-import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
-import org.apache.commons.httpclient.methods.multipart.Part;
-import org.apache.commons.httpclient.methods.multipart.StringPart;
-import org.apache.maven.plugin.MojoExecutionException;
+import javax.json.JsonException;
+import javax.json.JsonObject;
+
+import org.apache.hc.client5.http.classic.methods.HttpPost;
+import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
+import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
+import org.apache.hc.client5.http.impl.classic.BasicHttpClientResponseHandler;
+import org.apache.hc.core5.http.NameValuePair;
+import org.apache.hc.core5.http.message.BasicNameValuePair;
+import org.apache.sling.maven.bundlesupport.JsonSupport;
import org.apache.sling.maven.bundlesupport.deploy.DeployContext;
import org.apache.sling.maven.bundlesupport.deploy.DeployMethod;
+/**
+ * Un-/Installs bundles via the <a href="https://felix.apache.org/documentation/subprojects/apache-felix-web-console/web-console-restful-api.html#post-requests">
+ * ReST service provided by the Felix Web Console</a>
+ *
+ */
public class FelixPostDeployMethod implements DeployMethod {
@Override
- public void deploy(String targetURL, File file, String bundleSymbolicName, DeployContext context) throws MojoExecutionException {
-
- // append pseudo path after root URL to not get redirected for nothing
- final PostMethod filePost = new PostMethod(targetURL + "/install");
-
- try {
- // set referrer
- filePost.setRequestHeader("referer", "about:blank");
-
- List<Part> partList = new ArrayList<Part>();
- partList.add(new StringPart("action", "install"));
- partList.add(new StringPart("_noredir_", "_noredir_"));
- partList.add(new FilePart("bundlefile", new FilePartSource(
- file.getName(), file)));
- partList.add(new StringPart("bundlestartlevel", context.getBundleStartLevel()));
-
- if (context.isBundleStart()) {
- partList.add(new StringPart("bundlestart", "start"));
- }
-
- if (context.isRefreshPackages()) {
- partList.add(new StringPart("refreshPackages", "true"));
- }
-
- Part[] parts = partList.toArray(new Part[partList.size()]);
-
- filePost.setRequestEntity(new MultipartRequestEntity(parts,
- filePost.getParams()));
-
- int status = context.getHttpClient().executeMethod(filePost);
- if (status == HttpStatus.SC_OK) {
- context.getLog().info("Bundle installed");
- } else {
- String msg = "Installation failed, cause: "
- + HttpStatus.getStatusText(status);
- if (context.isFailOnError()) {
- throw new MojoExecutionException(msg);
- } else {
- context.getLog().error(msg);
- }
- }
- } catch (Exception ex) {
- throw new MojoExecutionException("Installation on " + targetURL
- + " failed, cause: " + ex.getMessage(), ex);
- } finally {
- filePost.releaseConnection();
+ public void deploy(URI targetURL, File file, String bundleSymbolicName, DeployContext context) throws IOException {
+
+ // append pseudo path after root URL to not get redirected
+ // https://github.com/apache/felix-dev/blob/8e35c940a95c91f3fee09c537dbaf9665e5d027e/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/BundlesServlet.java#L338
+ URI postUrl = targetURL.resolve("install");
+ final HttpPost filePost = new HttpPost(postUrl);
+
+ // set referrer
+ filePost.setHeader("referer", "about:blank");
+ MultipartEntityBuilder builder = MultipartEntityBuilder.create();
+ builder.addTextBody("action", "install");
+ builder.addTextBody("_noredir_", "_noredir_");
+ builder.addTextBody("bundlestartlevel", context.getBundleStartLevel());
+ if (context.isBundleStart()) {
+ builder.addTextBody("bundlestart", "start");
+ }
+ if (context.isRefreshPackages()) {
+ builder.addTextBody("refreshPackages", "true");
+ }
+ builder.addBinaryBody("bundlefile", file);
+ filePost.setEntity(builder.build());
+ String response = context.getHttpClient().execute(filePost, new BasicHttpClientResponseHandler());
+ // sanity check on response (has really the right servlet answered?)
+ // must be empty in this case (https://github.com/apache/felix-dev/blob/8e35c940a95c91f3fee09c537dbaf9665e5d027e/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/BundlesServlet.java#L340)
+ if (!response.isEmpty()) {
+ throw new IOException("Unexpected response received from " + postUrl + ". Maybe wrong endpoint? Must be empty but was: " + response);
}
}
@Override
- public void undeploy(String targetURL, File file, String bundleSymbolicName, DeployContext context) throws MojoExecutionException {
- final PostMethod post = new PostMethod(targetURL + "/bundles/" + bundleSymbolicName);
- post.addParameter("action", "uninstall");
-
+ public void undeploy(URI targetURL, File file, String bundleSymbolicName, DeployContext context) throws IOException {
+ URI postUrl = targetURL.resolve("bundles/" + bundleSymbolicName);
+ final HttpPost post = new HttpPost(postUrl);
+ List<NameValuePair> params = new ArrayList<>();
+ params.add(new BasicNameValuePair("action", "uninstall"));
+ post.setEntity(new UrlEncodedFormEntity(params));
+ String response = context.getHttpClient().execute(post, new BasicHttpClientResponseHandler());
+ // sanity check on response (has really the right servlet answered?)
+ // must be JSON (https://github.com/apache/felix-dev/blob/8e35c940a95c91f3fee09c537dbaf9665e5d027e/webconsole/src/main/java/org/apache/felix/webconsole/internal/core/BundlesServlet.java#L420_
try {
-
- int status = context.getHttpClient().executeMethod(post);
- if (status == HttpStatus.SC_OK) {
- context.getLog().info("Bundle uninstalled");
- } else {
- context.getLog().error(
- "Uninstall failed, cause: "
- + HttpStatus.getStatusText(status));
- }
- } catch (Exception ex) {
- throw new MojoExecutionException("Uninstall from " + targetURL
- + " failed, cause: " + ex.getMessage(), ex);
- } finally {
- post.releaseConnection();
+ JsonObject jsonObject = JsonSupport.parseObject(response);
+ // must contain boolean
+ jsonObject.getBoolean("fragment");
+ } catch (JsonException|ClassCastException|NullPointerException e) {
+ throw new IOException("Unexpected response received from " + postUrl + ". Maybe wrong endpoint? Must be valid JSON but was: " + response);
}
+ context.getLog().debug("Received response from " + postUrl + ": " + response);
}
}
diff --git a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/method/IntermediateUrisExtractor.java b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/method/IntermediateUrisExtractor.java
index 3ec1e4d..eb2f81d 100644
--- a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/method/IntermediateUrisExtractor.java
+++ b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/method/IntermediateUrisExtractor.java
@@ -33,7 +33,7 @@ final class IntermediateUrisExtractor {
* Extracts a list of intermediate paths from an URL.
*
* <p>For instance, <tt>http://localhost:8080/apps/slingshot/install</tt> would have the following intermediate
- * paths:
+ * URIs:
* <ol>
* <li>http://localhost:8080/apps</li>
* <li>http://localhost:8080/apps/slingshot</li>
@@ -44,13 +44,11 @@ final class IntermediateUrisExtractor {
* @param url the url to extract paths from
* @return the intermediate paths, possibly empty
*/
- public static List<String> extractIntermediateUris(String url) {
+ public static List<URI> extractIntermediateUris(URI uri) {
- List<String> paths = new ArrayList<String>();
+ List<URI> paths = new ArrayList<>();
- URI uri = URI.create(url);
String path = uri.getPath();
-
StringBuilder accu = new StringBuilder();
for ( String segment : path.split("/") ) {
@@ -63,7 +61,7 @@ final class IntermediateUrisExtractor {
// don't add the root segment ( / )
if ( segment.length() != 0 ) {
- paths.add(0, uri.resolve(accu.toString()).toString());
+ paths.add(0, uri.resolve(accu.toString()));
}
}
diff --git a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/method/SlingPostDeployMethod.java b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/method/SlingPostDeployMethod.java
index 8b7ba95..d60ed9f 100644
--- a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/method/SlingPostDeployMethod.java
+++ b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/method/SlingPostDeployMethod.java
@@ -21,94 +21,57 @@ package org.apache.sling.maven.bundlesupport.deploy.method;
import static org.apache.sling.maven.bundlesupport.JsonSupport.JSON_MIME_TYPE;
import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.List;
-import org.apache.commons.httpclient.HttpStatus;
-import org.apache.commons.httpclient.methods.PostMethod;
-import org.apache.commons.httpclient.methods.multipart.FilePart;
-import org.apache.commons.httpclient.methods.multipart.FilePartSource;
-import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
-import org.apache.commons.httpclient.methods.multipart.Part;
-import org.apache.commons.httpclient.methods.multipart.StringPart;
-import org.apache.maven.plugin.MojoExecutionException;
+import org.apache.hc.client5.http.classic.methods.HttpPost;
+import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
+import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
+import org.apache.hc.client5.http.impl.classic.BasicHttpClientResponseHandler;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.NameValuePair;
+import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.sling.maven.bundlesupport.deploy.DeployContext;
import org.apache.sling.maven.bundlesupport.deploy.DeployMethod;
public class SlingPostDeployMethod implements DeployMethod {
@Override
- public void deploy(String targetURL, File file, String bundleSymbolicName, DeployContext context) throws MojoExecutionException {
+ public void deploy(URI targetURL, File file, String bundleSymbolicName, DeployContext context) throws IOException {
/* truncate off trailing slash as this has special behaviorisms in
* the SlingPostServlet around created node name conventions */
- if (targetURL.endsWith("/")) {
- targetURL = targetURL.substring(0, targetURL.length()-1);
- }
+ targetURL = stripTrailingSlash(targetURL);
+
// append pseudo path after root URL to not get redirected for nothing
- final PostMethod filePost = new PostMethod(targetURL);
-
- try {
-
- Part[] parts = new Part[2];
- // Add content type to force the configured mimeType value
- parts[0] = new FilePart("*", new FilePartSource(
- file.getName(), file), context.getMimeType(), null);
- // Add TypeHint to have jar be uploaded as file (not as resource)
- parts[1] = new StringPart("*@TypeHint", "nt:file");
-
- /* Request JSON response from Sling instead of standard HTML, to
- * reduce the payload size (if the PostServlet supports it). */
- filePost.setRequestHeader("Accept", JSON_MIME_TYPE);
- filePost.setRequestEntity(new MultipartRequestEntity(parts,
- filePost.getParams()));
+ final HttpPost filePost = new HttpPost(targetURL);
- int status = context.getHttpClient().executeMethod(filePost);
- // SlingPostServlet may return 200 or 201 on creation, accept both
- if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED) {
- context.getLog().info("Bundle installed");
- } else {
- String msg = "Installation failed, cause: "
- + HttpStatus.getStatusText(status);
- if (context.isFailOnError()) {
- throw new MojoExecutionException(msg);
- } else {
- context.getLog().error(msg);
- }
- }
- } catch (Exception ex) {
- throw new MojoExecutionException("Installation on " + targetURL
- + " failed, cause: " + ex.getMessage(), ex);
- } finally {
- filePost.releaseConnection();
- }
+ /* Request JSON response from Sling instead of standard HTML, to
+ * reduce the payload size (if the PostServlet supports it). */
+ filePost.setHeader("Accept", JSON_MIME_TYPE);
+ MultipartEntityBuilder builder = MultipartEntityBuilder.create();
+ builder.addTextBody("*@TypeHint", "nt:file");
+ builder.addBinaryBody("*", file, ContentType.create(context.getMimeType()), file.getName());
+ filePost.setEntity(builder.build());
+
+ String response = context.getHttpClient().execute(filePost, new BasicHttpClientResponseHandler());
+ context.getLog().debug("Received response: " + response);
}
@Override
- public void undeploy(String targetURL, File file, String bundleSymbolicName, DeployContext context) throws MojoExecutionException {
- final PostMethod post = new PostMethod(getURLWithFilename(targetURL, file.getName()));
-
- try {
- // Add SlingPostServlet operation flag for deleting the content
- Part[] parts = new Part[1];
- parts[0] = new StringPart(":operation", "delete");
- post.setRequestEntity(new MultipartRequestEntity(parts,
- post.getParams()));
+ public void undeploy(URI targetURL, File file, String bundleSymbolicName, DeployContext context) throws IOException {
+ final HttpPost post = new HttpPost(getURLWithFilename(targetURL, file.getName()));
- // Request JSON response from Sling instead of standard HTML
- post.setRequestHeader("Accept", JSON_MIME_TYPE);
-
- int status = context.getHttpClient().executeMethod(post);
- if (status == HttpStatus.SC_OK) {
- context.getLog().info("Bundle uninstalled");
- } else {
- context.getLog().error(
- "Uninstall failed, cause: "
- + HttpStatus.getStatusText(status));
- }
- } catch (Exception ex) {
- throw new MojoExecutionException("Uninstall from " + targetURL
- + " failed, cause: " + ex.getMessage(), ex);
- } finally {
- post.releaseConnection();
- }
+ List<NameValuePair> params = new ArrayList<>();
+ // Request JSON response from Sling instead of standard HTML
+ post.setHeader("Accept", JSON_MIME_TYPE);
+ params.add(new BasicNameValuePair(":operation", "delete"));
+ post.setEntity(new UrlEncodedFormEntity(params));
+
+ String response = context.getHttpClient().execute(post, new BasicHttpClientResponseHandler());
+ context.getLog().debug("Received response: " + response);
}
/**
@@ -116,8 +79,20 @@ public class SlingPostDeployMethod implements DeployMethod {
* @param targetURL the original requested targetURL to append fileName to
* @param fileName the name of the file to append to the targetURL.
*/
- private String getURLWithFilename(String targetURL, String fileName) {
- return targetURL + (targetURL.endsWith("/") ? "" : "/") + fileName;
+ static URI getURLWithFilename(URI targetURL, String fileName) {
+ return targetURL.resolve(fileName);
+ }
+
+ static URI stripTrailingSlash(URI targetURL) {
+ if (targetURL.getPath().endsWith("/")) {
+ String path = targetURL.getPath().substring(0, targetURL.getPath().length()-1);
+ try {
+ return new URI(targetURL.getScheme(), targetURL.getUserInfo(), targetURL.getHost(), targetURL.getPort(), path, targetURL.getQuery(), targetURL.getFragment());
+ } catch (URISyntaxException e) {
+ throw new IllegalStateException("Could not create new URI from existing one", e); // should never happen
+ }
+ } else {
+ return targetURL;
+ }
}
-
}
diff --git a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/method/MkColMethod.java b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/method/WebDavMkCol.java
similarity index 80%
rename from sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/method/MkColMethod.java
rename to sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/method/WebDavMkCol.java
index 6063053..3b7ecdf 100644
--- a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/method/MkColMethod.java
+++ b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/method/WebDavMkCol.java
@@ -16,7 +16,9 @@
*/
package org.apache.sling.maven.bundlesupport.deploy.method;
-import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
+import java.net.URI;
+
+import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
/**
* Implements the WebDAV MKCOL method
@@ -24,20 +26,17 @@ import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
* @see <a href="http://www.webdav.org/specs/rfc4918.html#METHOD_MKCOL">RFC 4918, $9.3</a>
*
*/
-final class MkColMethod extends EntityEnclosingMethod {
+final class WebDavMkCol extends HttpUriRequestBase {
+
+ private static final long serialVersionUID = -8206740913450995038L;
/**
* Constructor specifying a URI.
*
* @param uri either an absolute or relative URI
*/
- public MkColMethod(String uri) {
- super(uri);
- }
-
- @Override
- public String getName() {
- return "MKCOL";
+ public WebDavMkCol(URI uri) {
+ super("MKCOL", uri);
}
}
diff --git a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/method/WebDavPutDeployMethod.java b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/method/WebDavPutDeployMethod.java
index ab9bb40..0c82476 100644
--- a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/method/WebDavPutDeployMethod.java
+++ b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/deploy/method/WebDavPutDeployMethod.java
@@ -20,129 +20,131 @@ package org.apache.sling.maven.bundlesupport.deploy.method;
import java.io.File;
import java.io.IOException;
+import java.net.URI;
+import java.util.Arrays;
import java.util.List;
-import org.apache.commons.httpclient.HttpException;
-import org.apache.commons.httpclient.HttpStatus;
-import org.apache.commons.httpclient.methods.DeleteMethod;
-import org.apache.commons.httpclient.methods.FileRequestEntity;
-import org.apache.commons.httpclient.methods.HeadMethod;
-import org.apache.commons.httpclient.methods.PutMethod;
-import org.apache.maven.plugin.MojoExecutionException;
+import org.apache.hc.client5.http.HttpResponseException;
+import org.apache.hc.client5.http.classic.methods.HttpDelete;
+import org.apache.hc.client5.http.classic.methods.HttpHead;
+import org.apache.hc.client5.http.classic.methods.HttpPut;
+import org.apache.hc.client5.http.impl.classic.BasicHttpClientResponseHandler;
+import org.apache.hc.core5.http.ClassicHttpResponse;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.HttpEntity;
+import org.apache.hc.core5.http.HttpException;
+import org.apache.hc.core5.http.HttpStatus;
+import org.apache.hc.core5.http.io.HttpClientResponseHandler;
+import org.apache.hc.core5.http.io.entity.EntityUtils;
+import org.apache.hc.core5.http.io.entity.FileEntity;
import org.apache.sling.maven.bundlesupport.deploy.DeployContext;
import org.apache.sling.maven.bundlesupport.deploy.DeployMethod;
public class WebDavPutDeployMethod implements DeployMethod {
@Override
- public void deploy(String targetURL, File file, String bundleSymbolicName, DeployContext context) throws MojoExecutionException {
- boolean success = false;
- int status;
-
+ public void deploy(URI targetURL, File file, String bundleSymbolicName, DeployContext context) throws IOException {
try {
- status = performPut(targetURL, file, context);
- if (status >= 200 && status < 300) {
- success = true;
- } else if (status == HttpStatus.SC_CONFLICT) {
-
+ performPut(targetURL, file, context);
+ } catch (HttpResponseException e) {
+ if (e.getStatusCode() == HttpStatus.SC_CONFLICT) {
context.getLog().debug("Bundle not installed due missing parent folders. Attempting to create parent structure.");
createIntermediaryPaths(targetURL, context);
context.getLog().debug("Re-attempting bundle install after creating parent folders.");
- status = performPut(targetURL, file, context);
- if (status >= 200 && status < 300) {
- success = true;
- }
- }
-
- if (!success) {
- String msg = "Installation failed, cause: "
- + HttpStatus.getStatusText(status);
- if (context.isFailOnError()) {
- throw new MojoExecutionException(msg);
- } else {
- context.getLog().error(msg);
- }
+ performPut(targetURL, file, context);
}
- } catch (Exception ex) {
- throw new MojoExecutionException("Installation on " + targetURL
- + " failed, cause: " + ex.getMessage(), ex);
}
}
@Override
- public void undeploy(String targetURL, File file, String bundleSymbolicName, DeployContext context) throws MojoExecutionException {
- final DeleteMethod delete = new DeleteMethod(getURLWithFilename(targetURL, file.getName()));
+ public void undeploy(URI targetURL, File file, String bundleSymbolicName, DeployContext context) throws IOException {
+ final HttpDelete delete = new HttpDelete(SlingPostDeployMethod.getURLWithFilename(targetURL, file.getName()));
+ // sanity check on response
+ // must answer 204 (no content)
+ // https://github.com/apache/jackrabbit/blob/88490006e6bdba0b0ad52d209b1bfa040477c2ec/jackrabbit-webdav/src/main/java/org/apache/jackrabbit/webdav/server/AbstractWebdavServlet.java#L763
+ Integer status = context.getHttpClient().execute(delete, new ResponseCodeEnforcingResponseHandler(HttpStatus.SC_NO_CONTENT));
+ context.getLog().debug("Received status code " + status);
+ }
- try {
+ private void performPut(URI targetURL, File file, DeployContext context) throws IOException {
+ HttpPut filePut = new HttpPut(SlingPostDeployMethod.getURLWithFilename(targetURL, file.getName()));
+ filePut.setEntity(new FileEntity(file, ContentType.create(context.getMimeType())));
+ // sanity check on response (has really the right servlet answered?)
+ // check status code, must be either 201 (created) for new resources or 204 (no content) for updated existing resources
+ // https://github.com/apache/jackrabbit/blob/88490006e6bdba0b0ad52d209b1bfa040477c2ec/jackrabbit-webdav/src/main/java/org/apache/jackrabbit/webdav/server/AbstractWebdavServlet.java#L707
+ Integer status = context.getHttpClient().execute(filePut, new ResponseCodeEnforcingResponseHandler(HttpStatus.SC_NO_CONTENT, HttpStatus.SC_CREATED));
+ context.getLog().debug("Received status code " + status);
+ }
- int status = context.getHttpClient().executeMethod(delete);
- if (status >= 200 && status < 300) {
- context.getLog().info("Bundle uninstalled");
- } else {
- context.getLog().error(
- "Uninstall failed, cause: "
- + HttpStatus.getStatusText(status));
- }
- } catch (Exception ex) {
- throw new MojoExecutionException("Uninstall from " + targetURL
- + " failed, cause: " + ex.getMessage(), ex);
- } finally {
- delete.releaseConnection();
- }
+ private void performHead(URI uri, DeployContext context) throws IOException {
+ HttpHead head = new HttpHead(uri);
+ context.getHttpClient().execute(head, new BasicHttpClientResponseHandler());
+ // this never returns a body
}
- private int performPut(String targetURL, File file, DeployContext context) throws HttpException, IOException {
- PutMethod filePut = new PutMethod(getURLWithFilename(targetURL, file.getName()));
- try {
- filePut.setRequestEntity(new FileRequestEntity(file, context.getMimeType()));
- return context.getHttpClient().executeMethod(filePut);
- } finally {
- filePut.releaseConnection();
+ private static final class ResponseCodeEnforcingResponseHandler implements HttpClientResponseHandler<Integer> {
+
+ private final List<Integer> allowedCodes;
+ public ResponseCodeEnforcingResponseHandler(Integer... allowedCodes) {
+ this.allowedCodes = Arrays.asList(allowedCodes);
}
- }
- private int performHead(String uri, DeployContext context) throws HttpException, IOException {
- HeadMethod head = new HeadMethod(uri);
- try {
- return context.getHttpClient().executeMethod(head);
- } finally {
- head.releaseConnection();
+ @Override
+ public Integer handleResponse(ClassicHttpResponse response) throws HttpException, IOException {
+ final HttpEntity entity = response.getEntity();
+ EntityUtils.consume(entity);
+ if (allowedCodes.contains(response.getCode())) {
+ throw new HttpResponseException(response.getCode(), response.getReasonPhrase());
+ }
+ return null;
}
+
}
- private int performMkCol(String uri, DeployContext context) throws IOException {
- MkColMethod mkCol = new MkColMethod(uri);
- try {
- return context.getHttpClient().executeMethod(mkCol);
- } finally {
- mkCol.releaseConnection();
- }
+ private void performMkCol(URI uri, DeployContext context) throws IOException {
+ WebDavMkCol mkCol = new WebDavMkCol(uri);
+ String response = context.getHttpClient().execute(mkCol, new BasicHttpClientResponseHandler());
+ context.getLog().info("Received response: " + response);
+ // must be 201 (created)
+ // https://github.com/apache/jackrabbit/blob/88490006e6bdba0b0ad52d209b1bfa040477c2ec/jackrabbit-webdav/src/main/java/org/apache/jackrabbit/webdav/server/AbstractWebdavServlet.java#L746
+
}
- private void createIntermediaryPaths(String targetURL, DeployContext context) throws HttpException, IOException, MojoExecutionException {
+ private void createIntermediaryPaths(URI targetURL, DeployContext context) throws IOException {
// extract all intermediate URIs (longest one first)
- List<String> intermediateUris = IntermediateUrisExtractor.extractIntermediateUris(targetURL);
+ List<URI> intermediateUris = IntermediateUrisExtractor.extractIntermediateUris(targetURL);
// 1. go up to the node in the repository which exists already (HEAD request towards the root node)
- String existingIntermediateUri = null;
+ URI existingIntermediateUri = null;
// go through all intermediate URIs (longest first)
- for (String intermediateUri : intermediateUris) {
+ for (URI intermediateUri : intermediateUris) {
// until one is existing
- int result = performHead(intermediateUri, context);
- // if the result is 200 (in case the default get servlet allows returning index files) or 403 (in case the default get servlet does no allow returning index files)
- // we assume that the intermediate node exists already
- if (result == HttpStatus.SC_OK || result == HttpStatus.SC_FORBIDDEN) {
- existingIntermediateUri = intermediateUri;
- break;
- } else if (result != HttpStatus.SC_NOT_FOUND) {
- throw new MojoExecutionException("Failed getting intermediate path at " + intermediateUri + "."
- + " Reason: " + HttpStatus.getStatusText(result));
+ try {
+ try {
+ performHead(intermediateUri, context);
+ // if the result is 200 (in case the default get servlet allows returning index files)
+ existingIntermediateUri = intermediateUri;
+ break;
+ } catch (HttpResponseException e) {
+ // or 403 (in case the default get servlet does no allow returning index files)
+ if (e.getStatusCode() == HttpStatus.SC_FORBIDDEN) {
+ // we assume that the intermediate node exists already
+ existingIntermediateUri = intermediateUri;
+ break;
+ } else if (e.getStatusCode() != HttpStatus.SC_NOT_FOUND) {
+ throw e;
+ }
+ }
+ }
+ catch (IOException e) {
+ throw new IOException("Failed getting intermediate path at " + intermediateUri + "."
+ + " Reason: " + e.getMessage(), e);
}
}
if (existingIntermediateUri == null) {
- throw new MojoExecutionException(
+ throw new IOException(
"Could not find any intermediate path up until the root of " + targetURL + ".");
}
@@ -155,25 +157,15 @@ public class WebDavPutDeployMethod implements DeployMethod {
for (int index = startOfInexistingIntermediateUri - 1; index >= 0; index--) {
// use MKCOL to create the intermediate paths
- String intermediateUri = intermediateUris.get(index);
- int result = performMkCol(intermediateUri, context);
- if (result == HttpStatus.SC_CREATED || result == HttpStatus.SC_OK) {
+ URI intermediateUri = intermediateUris.get(index);
+ try {
+ performMkCol(intermediateUri, context);
context.getLog().debug("Intermediate path at " + intermediateUri + " successfully created");
- continue;
- } else {
- throw new MojoExecutionException("Failed creating intermediate path at '" + intermediateUri + "'."
- + " Reason: " + HttpStatus.getStatusText(result));
+ } catch (IOException e) {
+ throw new IOException("Failed creating intermediate path at '" + intermediateUri + "'."
+ + " Reason: " + e.getMessage());
}
}
}
- /**
- * Returns the URL with the filename appended to it.
- * @param targetURL the original requested targetURL to append fileName to
- * @param fileName the name of the file to append to the targetURL.
- */
- private String getURLWithFilename(String targetURL, String fileName) {
- return targetURL + (targetURL.endsWith("/") ? "" : "/") + fileName;
- }
-
}
diff --git a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/fsresource/FileVaultXmlMounter.java b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/fsresource/FileVaultXmlMounter.java
index d61685f..e1c5cd3 100644
--- a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/fsresource/FileVaultXmlMounter.java
+++ b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/fsresource/FileVaultXmlMounter.java
@@ -20,11 +20,12 @@ package org.apache.sling.maven.bundlesupport.fsresource;
import java.io.File;
import java.io.IOException;
+import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-import org.apache.commons.httpclient.HttpClient;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.jackrabbit.vault.fs.api.PathFilterSet;
import org.apache.jackrabbit.vault.fs.api.WorkspaceFilter;
import org.apache.jackrabbit.vault.fs.config.ConfigurationException;
@@ -41,7 +42,7 @@ public final class FileVaultXmlMounter {
private final Log log;
private final FsMountHelper helper;
- public FileVaultXmlMounter(Log log, HttpClient httpClient, MavenProject project) {
+ public FileVaultXmlMounter(Log log, CloseableHttpClient httpClient, MavenProject project) {
this.log = log;
this.helper = new FsMountHelper(log, httpClient, project);
}
@@ -53,7 +54,7 @@ public final class FileVaultXmlMounter {
* @param filterXmlFile FileVault Filter XML file
* @throws MojoExecutionException Exception
*/
- public void mount(final String targetUrl, final File jcrRootFile, final File filterXmlFile) throws MojoExecutionException {
+ public void mount(final URI targetUrl, final File jcrRootFile, final File filterXmlFile) throws MojoExecutionException {
log.info("Trying to configure file system provider...");
// create config for each path defined in filter
@@ -79,7 +80,7 @@ public final class FileVaultXmlMounter {
* @param filterXmlFile FileVault Filter XML file
* @throws MojoExecutionException Exception
*/
- public void unmount(final String targetUrl, final File jcrRootFile, final File filterXmlFile) throws MojoExecutionException {
+ public void unmount(final URI targetUrl, final File jcrRootFile, final File filterXmlFile) throws MojoExecutionException {
log.info("Removing file system provider configurations...");
// remove all current configs for this project
diff --git a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/fsresource/FsMountHelper.java b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/fsresource/FsMountHelper.java
index 5cb25f0..d9412b8 100644
--- a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/fsresource/FsMountHelper.java
+++ b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/fsresource/FsMountHelper.java
@@ -19,24 +19,29 @@
package org.apache.sling.maven.bundlesupport.fsresource;
import java.io.IOException;
-import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
+import java.net.URI;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
+import java.util.List;
import java.util.Map;
import javax.json.JsonArray;
import javax.json.JsonException;
import javax.json.JsonObject;
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.HttpException;
-import org.apache.commons.httpclient.HttpStatus;
-import org.apache.commons.httpclient.methods.GetMethod;
-import org.apache.commons.httpclient.methods.PostMethod;
-import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.client5.http.classic.methods.HttpPost;
+import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
+import org.apache.hc.client5.http.impl.classic.BasicHttpClientResponseHandler;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
+import org.apache.hc.core5.http.NameValuePair;
+import org.apache.hc.core5.http.ProtocolException;
+import org.apache.hc.core5.http.io.entity.EntityUtils;
+import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
@@ -60,10 +65,10 @@ final class FsMountHelper {
private static final String PROPERTY_FILEVAULT_FILTER_XML = "provider.filevault.filterxml.path";
private final Log log;
- private final HttpClient httpClient;
+ private final CloseableHttpClient httpClient;
private final MavenProject project;
- public FsMountHelper(Log log, HttpClient httpClient, MavenProject project) {
+ public FsMountHelper(Log log, CloseableHttpClient httpClient, MavenProject project) {
this.log = log;
this.httpClient = httpClient;
this.project = project;
@@ -72,7 +77,7 @@ final class FsMountHelper {
/**
* Adds as set of new configurations and removes old ones.
*/
- public void addConfigurations(final String targetUrl, Collection<FsResourceConfiguration> cfgs) throws MojoExecutionException {
+ public void addConfigurations(final URI targetUrl, Collection<FsResourceConfiguration> cfgs) throws MojoExecutionException {
final Map<String,FsResourceConfiguration> oldConfigs = getCurrentConfigurations(targetUrl);
for (FsResourceConfiguration cfg : cfgs) {
@@ -111,36 +116,27 @@ final class FsMountHelper {
/**
* Add a new configuration for the file system provider
*/
- private void addConfiguration(final String targetUrl, FsResourceConfiguration cfg) throws MojoExecutionException {
- final String postUrl = targetUrl + "/configMgr/" + FS_FACTORY;
- final PostMethod post = new PostMethod(postUrl);
- post.addParameter("apply", "true");
- post.addParameter("factoryPid", FS_FACTORY);
- post.addParameter("pid", "[Temporary PID replaced by real PID upon save]");
+ private void addConfiguration(final URI targetUrl, FsResourceConfiguration cfg) throws MojoExecutionException {
+ final URI postUrl = targetUrl.resolve("/configMgr/" + FS_FACTORY);
+ final HttpPost post = new HttpPost(postUrl);
+ List<NameValuePair> params = new ArrayList<>();
+ params.add(new BasicNameValuePair("apply", "true"));
+ params.add(new BasicNameValuePair("factoryPid", FS_FACTORY));
+ params.add(new BasicNameValuePair("pid", "[Temporary PID replaced by real PID upon save]"));
Map<String,String> props = toMap(cfg);
for (Map.Entry<String,String> entry : props.entrySet()) {
- post.addParameter(entry.getKey(), entry.getValue());
+ params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
- post.addParameter("propertylist", StringUtils.join(props.keySet(), ","));
+ params.add(new BasicNameValuePair("propertylist", StringUtils.join(props.keySet(), ",")));
+ post.setEntity(new UrlEncodedFormEntity(params));
+
try {
- final int status = httpClient.executeMethod(post);
- // we get a moved temporarily back from the configMgr plugin
- if (status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_OK) {
- log.info("Configuration created.");
- }
- else {
- log.error("Configuration on " + postUrl + " failed, cause: " + HttpStatus.getStatusText(status));
- }
- }
- catch (HttpException ex) {
- throw new MojoExecutionException("Configuration on " + postUrl + " failed, cause: " + ex.getMessage(), ex);
+ String response = httpClient.execute(post, new BasicHttpClientResponseHandler());
+ log.debug("Configuration created: " + response);
}
catch (IOException ex) {
throw new MojoExecutionException("Configuration on " + postUrl + " failed, cause: " + ex.getMessage(), ex);
}
- finally {
- post.releaseConnection();
- }
}
private Map<String,String> toMap(FsResourceConfiguration cfg) {
@@ -168,7 +164,7 @@ final class FsMountHelper {
/**
* Remove all configurations contained in the given config map.
*/
- public void removeConfigurations(final String targetUrl, Map<String,FsResourceConfiguration> configs) throws MojoExecutionException {
+ public void removeConfigurations(final URI targetUrl, Map<String,FsResourceConfiguration> configs) throws MojoExecutionException {
for (Map.Entry<String,FsResourceConfiguration> current : configs.entrySet()) {
log.debug("Removing configuration for " + current.getValue());
// remove old config
@@ -179,32 +175,23 @@ final class FsMountHelper {
/**
* Remove configuration.
*/
- private void removeConfiguration(final String targetUrl, final String pid) throws MojoExecutionException {
- final String postUrl = targetUrl + "/configMgr/" + pid;
- final PostMethod post = new PostMethod(postUrl);
- post.addParameter("apply", "true");
- post.addParameter("delete", "true");
+ private void removeConfiguration(final URI targetUrl, final String pid) throws MojoExecutionException {
+ final URI postUrl = targetUrl.resolve("/configMgr/" + pid);
+ final HttpPost post = new HttpPost(postUrl);
+ List<NameValuePair> params = new ArrayList<>();
+ params.add(new BasicNameValuePair("apply", "true"));
+ params.add(new BasicNameValuePair("delete", "true"));
+ post.setEntity(new UrlEncodedFormEntity(params));
+
try {
- final int status = httpClient.executeMethod(post);
+ String response = httpClient.execute(post, new BasicHttpClientResponseHandler());
// we get a moved temporarily back from the configMgr plugin
- if (status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_OK) {
- log.debug("Configuration removed.");
- }
- else {
- log.error("Removing configuration failed, cause: "+ HttpStatus.getStatusText(status));
- }
- }
- catch (HttpException ex) {
- throw new MojoExecutionException("Removing configuration at " + postUrl
- + " failed, cause: " + ex.getMessage(), ex);
+ log.debug("Configuration removed: " + response);
}
catch (IOException ex) {
throw new MojoExecutionException("Removing configuration at " + postUrl
+ " failed, cause: " + ex.getMessage(), ex);
}
- finally {
- post.releaseConnection();
- }
}
/**
@@ -213,16 +200,16 @@ final class FsMountHelper {
* @return A map (may be empty) with the pids as keys and the configurations as values
* @throws MojoExecutionException
*/
- public Map<String,FsResourceConfiguration> getCurrentConfigurations(final String targetUrl) throws MojoExecutionException {
+ public Map<String,FsResourceConfiguration> getCurrentConfigurations(final URI targetUrl) throws MojoExecutionException {
log.debug("Getting current file provider configurations.");
final Map<String,FsResourceConfiguration> result = new HashMap<>();
- final String getUrl = targetUrl + "/configMgr/(service.factoryPid=" + FS_FACTORY + ").json";
- final GetMethod get = new GetMethod(getUrl);
+ final URI getUrl = targetUrl.resolve("/configMgr/(service.factoryPid=" + FS_FACTORY + ").json");
+ final HttpGet get = new HttpGet(getUrl);
- try {
- final int status = httpClient.executeMethod(get);
+ try (CloseableHttpResponse response = httpClient.execute(get)) {
+ final int status = response.getCode();
if ( status == 200 ) {
- String contentType = get.getResponseHeader(HEADER_CONTENT_TYPE).getValue();
+ String contentType = response.getHeader(HEADER_CONTENT_TYPE).getValue();
int pos = contentType.indexOf(';');
if ( pos != -1 ) {
contentType = contentType.substring(0, pos);
@@ -233,10 +220,7 @@ final class FsMountHelper {
"the initial content through file system provider configs. " +
"Either upgrade the web console or disable this feature.");
}
- final String jsonText;
- try (InputStream jsonResponse = get.getResponseBodyAsStream()) {
- jsonText = IOUtils.toString(jsonResponse, StandardCharsets.UTF_8);
- }
+ final String jsonText = EntityUtils.toString(response.getEntity());
try {
JsonArray array = JsonSupport.parseArray(jsonText);
for(int i=0; i<array.size(); i++) {
@@ -268,17 +252,10 @@ final class FsMountHelper {
}
}
}
- catch (HttpException ex) {
+ catch (IOException | ProtocolException ex) {
throw new MojoExecutionException("Reading configuration from " + getUrl
+ " failed, cause: " + ex.getMessage(), ex);
}
- catch (IOException ex) {
- throw new MojoExecutionException("Reading configuration from " + getUrl
- + " failed, cause: " + ex.getMessage(), ex);
- }
- finally {
- get.releaseConnection();
- }
return result;
}
diff --git a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/fsresource/SlingInitialContentMounter.java b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/fsresource/SlingInitialContentMounter.java
index c613cfc..8963146 100644
--- a/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/fsresource/SlingInitialContentMounter.java
+++ b/sling-maven-plugin/src/main/java/org/apache/sling/maven/bundlesupport/fsresource/SlingInitialContentMounter.java
@@ -20,6 +20,7 @@ package org.apache.sling.maven.bundlesupport.fsresource;
import java.io.File;
import java.io.IOException;
+import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@@ -27,8 +28,8 @@ import java.util.Map;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
-import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.lang3.StringUtils;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;
@@ -48,7 +49,7 @@ public final class SlingInitialContentMounter {
private final MavenProject project;
private final FsMountHelper helper;
- public SlingInitialContentMounter(Log log, HttpClient httpClient, MavenProject project) {
+ public SlingInitialContentMounter(Log log, CloseableHttpClient httpClient, MavenProject project) {
this.log = log;
this.project = project;
this.helper = new FsMountHelper(log, httpClient, project);
@@ -60,7 +61,7 @@ public final class SlingInitialContentMounter {
* @param bundleFile The artifact (bundle)
* @throws MojoExecutionException Exception
*/
- public void mount(final String targetUrl, final File bundleFile) throws MojoExecutionException {
+ public void mount(final URI targetUrl, final File bundleFile) throws MojoExecutionException {
// first, let's get the manifest and see if initial content is configured
ManifestHeader header = null;
try {
@@ -163,7 +164,7 @@ public final class SlingInitialContentMounter {
* @param bundleFile The artifact (bundle)
* @throws MojoExecutionException Exception
*/
- public void unmount(final String targetUrl, final File bundleFile) throws MojoExecutionException {
+ public void unmount(final URI targetUrl, final File bundleFile) throws MojoExecutionException {
log.info("Removing file system provider configurations...");
// remove all current configs for this project
diff --git a/sling-maven-plugin/src/site/markdown/bundle-installation.md b/sling-maven-plugin/src/site/markdown/bundle-installation.md
new file mode 100644
index 0000000..9dcd3ff
--- /dev/null
+++ b/sling-maven-plugin/src/site/markdown/bundle-installation.md
@@ -0,0 +1,29 @@
+# Bundle Installation
+
+## Deploy/Upload/Install
+
+There are three different installation approaches supported by the plugin
+
+### Felix Web Console
+
+The plugin by default places an *HTTP POST* request to the [Felix Web Console](https://felix.apache.org/documentation/subprojects/apache-felix-web-console/web-console-restful-api.html#post-requests). This will achieve both upload and installation of the bundle in one request *synchronously*.
+
+### WebDAV PUT
+
+It's also possible to use *HTTP PUT* instead of POST leveraging the [WebDAV bundle from Sling](https://sling.apache.org/documentation/development/repository-based-development.html). This will create a new Sling resource containing the OSGi bundle in the underlying repository.
+From there it needs to be picked up by the [JCR Installer](https://sling.apache.org/documentation/bundles/jcr-installer-provider.html) to be actually installed in the OSGi container. The latter happens *asynchronously*. It is important that the bundle resource is uploaded to a location of the repository which is actually watched by the JCR installer (by default only resources below a resource called `install`).
+
+### Sling POST Servlet
+
+Since version 2.1.8 you can also leverage the [Sling POST servlet](https://sling.apache.org/documentation/bundles/manipulating-content-the-slingpostservlet-servlets-post.html) for uploading the bundle to the repository. The subsequent installation is being performed *asynchronously* by the JCR Installer (similar to the WebDAV PUT approach).
+
+## Intermediate Resources
+
+For both WebDAV PUT and Sling POST servlet installation, intermediate resources (i.e. non-existing parent resources)
+are automatically created. The primary type of those intermediate nodes depend on the deployment method (only applicable if the JCR resource provider is used)
+
+- **WebDAV PUT**, uses the configured collection node type, by default `sling:Folder` (see also [WebDAV Configuration](https://sling.apache.org/documentation/development/repository-based-development.html))
+- **Sling POST Servlet**, uses internally `ResourceResolverFactory.create(...)` without setting any `jcr:primaryType`. Therefore the `JcrResourceProviderFactory` will call `Node.addNode(String relPath)` which determines a suitable
+node type automatically, depending on the parent's node type definition (see [JCR Node Javadoc](https://s.apache.org/jcr-2.0-javadoc/javax/jcr/Node.html#addNode(java.lang.String))).
+
+In most of the cases the intermediate node is of type `sling:Folder`, as this is the first allowed child node definition for node type `sling:Folder`. This may only differ if your existing parent node is not of type `sling:Folder` itself.
diff --git a/sling-maven-plugin/src/site/markdown/index.md b/sling-maven-plugin/src/site/markdown/index.md
index 8fba41b..8daf15b 100644
--- a/sling-maven-plugin/src/site/markdown/index.md
+++ b/sling-maven-plugin/src/site/markdown/index.md
@@ -1,6 +1,8 @@
Sling Maven Plugin
==================
-The Sling Maven Plugin provides a number of goals which may be of help while developing bundles for Sling. To run the plugin you need at least Maven 3.x and JDK 1.7 or higher.
+The Sling Maven Plugin provides a number of goals which may be of help while developing bundles for Sling.
See [Goals](plugin-info.html) for a list of supported goals.
+
+Details about the different approaches for installing bundles are explained in [Bundle Installation](bundle-installation.html).
diff --git a/sling-maven-plugin/src/site/site.xml b/sling-maven-plugin/src/site/site.xml
index cdfb1e8..99a3240 100644
--- a/sling-maven-plugin/src/site/site.xml
+++ b/sling-maven-plugin/src/site/site.xml
@@ -19,25 +19,14 @@ specific language governing permissions and limitations
under the License.
-->
-<project>
- <skin>
- <groupId>org.apache.maven.skins</groupId>
- <artifactId>maven-fluido-skin</artifactId>
- <version>1.9</version>
- </skin>
+<project xmlns="http://maven.apache.org/DECORATION/1.8.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/DECORATION/1.8.0 http://maven.apache.org/xsd/decoration-1.8.0.xsd">
<body>
<menu name="Overview">
<item name="Introduction" href="index.html"/>
+ <item name="Bundle Installation" href="bundle-installation.html"/>
<item name="Goals" href="plugin-info.html"/>
</menu>
<menu ref="reports"/>
</body>
- <custom>
- <fluidoSkin>
- <gitHub>
- <projectId>apache/sling-maven-plugin</projectId>
- <ribbonOrientation>right</ribbonOrientation>
- </gitHub>
- </fluidoSkin>
- </custom>
</project>
diff --git a/sling-maven-plugin/src/test/java/org/apache/sling/maven/bundlesupport/deploy/method/IntermediateUrisExtractorTest.java b/sling-maven-plugin/src/test/java/org/apache/sling/maven/bundlesupport/deploy/method/IntermediateUrisExtractorTest.java
index a099836..f679192 100644
--- a/sling-maven-plugin/src/test/java/org/apache/sling/maven/bundlesupport/deploy/method/IntermediateUrisExtractorTest.java
+++ b/sling-maven-plugin/src/test/java/org/apache/sling/maven/bundlesupport/deploy/method/IntermediateUrisExtractorTest.java
@@ -19,6 +19,7 @@ package org.apache.sling.maven.bundlesupport.deploy.method;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
+import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@@ -31,13 +32,14 @@ public class IntermediateUrisExtractorTest {
public void extractPaths() {
doTest("http://localhost:8080/apps/slingshot/install",
- Arrays.asList("http://localhost:8080/apps/slingshot/install", "http://localhost:8080/apps/slingshot", "http://localhost:8080/apps" ));
+ Arrays.asList(
+ URI.create("http://localhost:8080/apps/slingshot/install"),
+ URI.create("http://localhost:8080/apps/slingshot"),
+ URI.create("http://localhost:8080/apps" )));
}
- private void doTest(String input, List<String> expectedOutput) {
-
- List<String> paths = IntermediateUrisExtractor.extractIntermediateUris(input);
-
+ private void doTest(String input, List<URI> expectedOutput) {
+ List<URI> paths = IntermediateUrisExtractor.extractIntermediateUris(URI.create(input));
assertThat(paths, equalTo(expectedOutput));
}
@@ -45,13 +47,16 @@ public class IntermediateUrisExtractorTest {
public void extractPaths_trailingSlash() {
doTest("http://localhost:8080/apps/slingshot/install/",
- Arrays.asList("http://localhost:8080/apps/slingshot/install", "http://localhost:8080/apps/slingshot", "http://localhost:8080/apps" ));
+ Arrays.asList(
+ URI.create("http://localhost:8080/apps/slingshot/install"),
+ URI.create("http://localhost:8080/apps/slingshot"),
+ URI.create("http://localhost:8080/apps") ));
}
@Test
public void extractPaths_empty() {
- doTest("http://localhost:8080", Collections.<String> emptyList());
+ doTest("http://localhost:8080", Collections.<URI> emptyList());
}
}
diff --git a/sling-maven-plugin/src/test/java/org/apache/sling/maven/bundlesupport/deploy/method/SlingPostDeployMethodTest.java b/sling-maven-plugin/src/test/java/org/apache/sling/maven/bundlesupport/deploy/method/SlingPostDeployMethodTest.java
new file mode 100644
index 0000000..fa70886
--- /dev/null
+++ b/sling-maven-plugin/src/test/java/org/apache/sling/maven/bundlesupport/deploy/method/SlingPostDeployMethodTest.java
@@ -0,0 +1,41 @@
+/*
+ * 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.sling.maven.bundlesupport.deploy.method;
+
+import static org.junit.Assert.*;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import org.junit.Test;
+
+public class SlingPostDeployMethodTest {
+
+ @Test
+ public void testGetURLWithFilename() throws URISyntaxException {
+ // all URLs are given with trailing slash
+ assertEquals(new URI("http://localhost:5602/test/filename"), SlingPostDeployMethod.getURLWithFilename(new URI("http://localhost:5602/test/"), "filename"));
+ assertEquals(new URI("http://localhost:5602/filename"), SlingPostDeployMethod.getURLWithFilename(new URI("http://localhost:5602/"), "filename"));
+ }
+
+ @Test
+ public void testStripTrailingSlash() throws URISyntaxException {
+ assertEquals(new URI("http://localhost"), SlingPostDeployMethod.stripTrailingSlash(new URI("http://localhost")));
+ assertEquals(new URI("http://localhost"), SlingPostDeployMethod.stripTrailingSlash(new URI("http://localhost/")));
+ assertEquals(new URI("http://user:pw@localhost:5602/test?key=value#fragment"), SlingPostDeployMethod.stripTrailingSlash(new URI("http://user:pw@localhost:5602/test/?key=value#fragment")));
+ }
+}