You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@jackrabbit.apache.org by tr...@apache.org on 2017/09/29 04:16:58 UTC
svn commit: r1810052 [2/3] - in /jackrabbit/commons/filevault/trunk: parent/
vault-core/ vault-core/src/main/java/org/apache/jackrabbit/vault/fs/io/
vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/
vault-core/src/main/java/org/apache/jac...
Added: jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/impl/ExecutionPlanBuilderImpl.java
URL: http://svn.apache.org/viewvc/jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/impl/ExecutionPlanBuilderImpl.java?rev=1810052&view=auto
==============================================================================
--- jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/impl/ExecutionPlanBuilderImpl.java (added)
+++ jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/impl/ExecutionPlanBuilderImpl.java Fri Sep 29 04:16:57 2017
@@ -0,0 +1,347 @@
+/*
+ * 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.jackrabbit.vault.packaging.registry.impl;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.annotation.Nonnull;
+import javax.jcr.Session;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.jackrabbit.vault.fs.api.ProgressTrackerListener;
+import org.apache.jackrabbit.vault.packaging.CyclicDependencyException;
+import org.apache.jackrabbit.vault.packaging.Dependency;
+import org.apache.jackrabbit.vault.packaging.DependencyException;
+import org.apache.jackrabbit.vault.packaging.NoSuchPackageException;
+import org.apache.jackrabbit.vault.packaging.PackageException;
+import org.apache.jackrabbit.vault.packaging.PackageId;
+import org.apache.jackrabbit.vault.packaging.registry.DependencyReport;
+import org.apache.jackrabbit.vault.packaging.registry.ExecutionPlan;
+import org.apache.jackrabbit.vault.packaging.registry.ExecutionPlanBuilder;
+import org.apache.jackrabbit.vault.packaging.registry.PackageTask;
+import org.apache.jackrabbit.vault.packaging.registry.PackageTaskBuilder;
+import org.apache.jackrabbit.vault.packaging.registry.RegisteredPackage;
+import org.apache.jackrabbit.vault.util.RejectingEntityResolver;
+import org.apache.jackrabbit.vault.util.xml.serialize.OutputFormat;
+import org.apache.jackrabbit.vault.util.xml.serialize.XMLSerializer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.AttributesImpl;
+
+/**
+ * {@code ExecutionPlanBuilderImpl}...
+ */
+public class ExecutionPlanBuilderImpl implements ExecutionPlanBuilder {
+
+ /**
+ * default logger
+ */
+ private static final Logger log = LoggerFactory.getLogger(ExecutionPlanBuilderImpl.class);
+
+ private final static String ATTR_VERSION = "version";
+ private static final String TAG_EXECUTION_PLAN = "executionPlan";
+ private static final String TAG_TASK = "task";
+ private static final String ATTR_CMD = "cmd";
+ private static final String ATTR_PACKAGE_ID = "packageId";
+
+ public static final double SUPPORTED_VERSION = 1.0;
+
+ protected double version = SUPPORTED_VERSION;
+
+ private final List<TaskBuilder> tasks = new LinkedList<TaskBuilder>();
+
+ private final JcrPackageRegistry registry;
+
+ private Session session;
+
+ private ProgressTrackerListener listener;
+
+ private ExecutionPlanImpl plan;
+
+ ExecutionPlanBuilderImpl(JcrPackageRegistry registry) {
+ this.registry = registry;
+ }
+
+ @Nonnull
+ @Override
+ public ExecutionPlanBuilder save(@Nonnull OutputStream out) throws IOException, PackageException {
+ validate();
+ try {
+ XMLSerializer ser = new XMLSerializer(out, new OutputFormat("xml", "UTF-8", true));
+ ser.startDocument();
+ AttributesImpl attrs = new AttributesImpl();
+ attrs.addAttribute(null, null, ATTR_VERSION, "CDATA", String.valueOf(version));
+ ser.startElement(null, null, TAG_EXECUTION_PLAN, attrs);
+
+ for (PackageTask task: plan.getTasks()) {
+ attrs = new AttributesImpl();
+ attrs.addAttribute(null, null, ATTR_CMD, "CDATA", task.getType().name().toLowerCase());
+ attrs.addAttribute(null, null, ATTR_PACKAGE_ID, "CDATA", task.getPackageId().toString());
+ ser.startElement(null, null, TAG_TASK, attrs);
+ ser.endElement(TAG_TASK);
+ }
+ ser.endElement(TAG_EXECUTION_PLAN);
+ ser.endDocument();
+ } catch (SAXException e) {
+ throw new IllegalStateException(e);
+ }
+ return this;
+ }
+
+ @Nonnull
+ @Override
+ public ExecutionPlanBuilder load(@Nonnull InputStream in) throws IOException {
+ tasks.clear();
+ try {
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ factory.setNamespaceAware(true);
+ DocumentBuilder builder = factory.newDocumentBuilder();
+ builder.setEntityResolver(new RejectingEntityResolver());
+ Document document = builder.parse(in);
+ Element doc = document.getDocumentElement();
+ if (!TAG_EXECUTION_PLAN.equals(doc.getNodeName())) {
+ throw new IOException("<" + TAG_EXECUTION_PLAN + "> expected.");
+ }
+ String v = doc.getAttribute(ATTR_VERSION);
+ if (v == null || "".equals(v)) {
+ v = "1.0";
+ }
+ version = Double.parseDouble(v);
+ if (version > SUPPORTED_VERSION) {
+ throw new IOException("version " + version + " not supported.");
+ }
+ read(doc);
+ } catch (ParserConfigurationException e) {
+ throw new IOException("Unable to create configuration XML parser", e);
+ } catch (SAXException e) {
+ throw new IOException("Configuration file syntax error.", e);
+ } finally {
+ IOUtils.closeQuietly(in);
+ }
+ return this;
+ }
+
+ private void read(Element elem) throws IOException {
+ NodeList nl = elem.getChildNodes();
+ for (int i=0; i<nl.getLength(); i++) {
+ Node child = nl.item(i);
+ if (child.getNodeType() == Node.ELEMENT_NODE) {
+ if (!TAG_TASK.equals(child.getNodeName())) {
+ throw new IOException("<" + TAG_TASK + "> expected.");
+ }
+ readTask((Element) child);
+ }
+ }
+ }
+
+ private void readTask(Element elem) throws IOException {
+ PackageTask.Type type = PackageTask.Type.valueOf(elem.getAttribute(ATTR_CMD).toUpperCase());
+ PackageId id = PackageId.fromString(elem.getAttribute(ATTR_PACKAGE_ID));
+ addTask().with(id).with(type);
+ }
+
+ @Nonnull
+ @Override
+ public PackageTaskBuilder addTask() {
+ TaskBuilder task = new TaskBuilder();
+ tasks.add(task);
+ plan = null; // invalidate potential plan
+ return task;
+ }
+
+ @Nonnull
+ @Override
+ public ExecutionPlanBuilder with(@Nonnull Session session) {
+ this.session = session;
+ return this;
+ }
+
+ @Nonnull
+ @Override
+ public ExecutionPlanBuilder with(@Nonnull ProgressTrackerListener listener) {
+ this.listener = listener;
+ return this;
+ }
+
+ @Nonnull
+ @Override
+ public ExecutionPlanBuilder validate() throws IOException, PackageException {
+ Map<PackageId, PackageTask> installTasks = new HashMap<PackageId, PackageTask>();
+ Map<PackageId, PackageTask> uninstallTasks = new HashMap<PackageId, PackageTask>();
+ Map<PackageId, PackageTask> removeTasks = new HashMap<PackageId, PackageTask>();
+ List<PackageTask> packageTasks = new ArrayList<PackageTask>(tasks.size());
+ for (TaskBuilder task: tasks) {
+ if (task.id == null || task.type == null) {
+ throw new PackageException("task builder must have package id and type defined.");
+ }
+ if (!registry.contains(task.id)) {
+ throw new NoSuchPackageException("No such package: " + task.id);
+ }
+ PackageTaskImpl pTask = new PackageTaskImpl(task.id, task.type);
+ // very simple task resolution: uninstall -> remove -> install/extract
+ switch (task.type) {
+ case INSTALL:
+ case EXTRACT:
+ installTasks.put(task.id, pTask);
+ break;
+ case UNINSTALL:
+ uninstallTasks.put(task.id, pTask);
+ break;
+ case REMOVE:
+ removeTasks.put(task.id, pTask);
+ break;
+ }
+ }
+
+ for (PackageId id: uninstallTasks.keySet().toArray(new PackageId[uninstallTasks.size()])) {
+ resolveUninstall(id, packageTasks, uninstallTasks, new HashSet<PackageId>());
+ }
+
+ // todo: validate remove
+ packageTasks.addAll(removeTasks.values());
+
+ for (PackageId id: installTasks.keySet().toArray(new PackageId[installTasks.size()])) {
+ resolveInstall(id, packageTasks, installTasks, new HashSet<PackageId>());
+ }
+
+ for (PackageTask task: packageTasks) {
+ log.info("- {}", task);
+ }
+
+ plan = new ExecutionPlanImpl(packageTasks);
+ return this;
+ }
+
+ private void resolveInstall(PackageId id, List<PackageTask> packageTasks, Map<PackageId, PackageTask> installTasks, Set<PackageId> resolved) throws IOException, PackageException {
+ if (resolved.contains(id)) {
+ throw new CyclicDependencyException("Package has cyclic dependencies: " + id);
+ }
+ resolved.add(id);
+ DependencyReport report = registry.analyzeDependencies(id, false);
+ if (report.getUnresolvedDependencies().length > 0) {
+ throw new DependencyException("Package has unresolved dependencies: " + Dependency.toString(report.getUnresolvedDependencies()));
+ }
+ for (PackageId depId: report.getResolvedDependencies()) {
+ // if the package task is already present, continue resolution
+ if (installTasks.get(depId) == PackageTaskImpl.MARKER) {
+ continue;
+ }
+ // if the package is already installed, continue resolution
+ try (RegisteredPackage pkg = registry.open(depId)) {
+ if (pkg == null || pkg.isInstalled()) {
+ continue;
+ }
+ }
+ resolveInstall(depId, packageTasks, installTasks, resolved);
+ }
+ PackageTask task = installTasks.get(id);
+ if (task == PackageTaskImpl.MARKER) {
+ // task was added during resolution
+ return;
+ }
+ if (task == null) {
+ // package is not registered in plan, but need to be installed due to dependency
+ task = new PackageTaskImpl(id, PackageTask.Type.INSTALL);
+ }
+ packageTasks.add(task);
+ // mark as processed
+ installTasks.put(id, PackageTaskImpl.MARKER);
+ }
+
+ private void resolveUninstall(PackageId id, List<PackageTask> packageTasks, Map<PackageId, PackageTask> uninstallTasks, Set<PackageId> resolved) throws IOException, PackageException {
+ if (resolved.contains(id)) {
+ throw new CyclicDependencyException("Package has cyclic dependencies: " + id);
+ }
+ resolved.add(id);
+ for (PackageId depId: registry.usage(id)) {
+ // if the package task is already present, continue resolution
+ if (uninstallTasks.get(depId) == PackageTaskImpl.MARKER) {
+ continue;
+ }
+ // if the package is already uninstalled, continue resolution
+ try (RegisteredPackage pkg = registry.open(depId)) {
+ if (pkg == null || !pkg.isInstalled()) {
+ continue;
+ }
+ }
+ resolveUninstall(depId, packageTasks, uninstallTasks, resolved);
+ }
+ PackageTask task = uninstallTasks.get(id);
+ if (task == PackageTaskImpl.MARKER) {
+ // task was added during resolution
+ return;
+ }
+ if (task == null) {
+ // package is not registered in plan, but need to be installed due to dependency
+ task = new PackageTaskImpl(id, PackageTask.Type.UNINSTALL);
+ }
+ packageTasks.add(task);
+ // mark as processed
+ uninstallTasks.put(id, PackageTaskImpl.MARKER);
+ }
+
+ @Nonnull
+ @Override
+ public ExecutionPlan execute() throws IOException, PackageException {
+ if (plan == null) {
+ validate();
+ }
+ // check if session is present or if no task needs it
+ if (session == null) {
+ for (PackageTask task: plan.getTasks()) {
+ if (task.getType() != PackageTask.Type.REMOVE) {
+ throw new PackageException("Session not set in builder, but " + task + " task requires it.");
+ }
+ }
+ }
+ return plan.with(registry).with(session).with(listener).execute();
+ }
+
+ private class TaskBuilder implements PackageTaskBuilder {
+ private PackageId id;
+ private PackageTask.Type type;
+
+ public PackageTaskBuilder with(@Nonnull PackageId id) {
+ this.id = id;
+ return this;
+ }
+
+ @Nonnull
+ @Override
+ public ExecutionPlanBuilder with(@Nonnull PackageTask.Type type) {
+ this.type = type;
+ return ExecutionPlanBuilderImpl.this;
+ }
+ }
+}
\ No newline at end of file
Added: jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/impl/ExecutionPlanImpl.java
URL: http://svn.apache.org/viewvc/jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/impl/ExecutionPlanImpl.java?rev=1810052&view=auto
==============================================================================
--- jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/impl/ExecutionPlanImpl.java (added)
+++ jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/impl/ExecutionPlanImpl.java Fri Sep 29 04:16:57 2017
@@ -0,0 +1,138 @@
+/*
+ * 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.jackrabbit.vault.packaging.registry.impl;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.annotation.Nonnull;
+import javax.jcr.Session;
+
+import org.apache.jackrabbit.vault.fs.api.ProgressTrackerListener;
+import org.apache.jackrabbit.vault.packaging.PackageException;
+import org.apache.jackrabbit.vault.packaging.registry.ExecutionPlan;
+import org.apache.jackrabbit.vault.packaging.registry.PackageRegistry;
+import org.apache.jackrabbit.vault.packaging.registry.PackageTask;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * {@code ExecutionPlanImpl}...
+ */
+public class ExecutionPlanImpl implements ExecutionPlan {
+
+ /**
+ * default logger
+ */
+ private static final Logger log = LoggerFactory.getLogger(ExecutionPlanImpl.class);
+
+ private List<PackageTask> tasks = new ArrayList<PackageTask>();
+
+ private String id;
+
+ private PackageRegistry registry;
+
+ private ProgressTrackerListener listener;
+
+ private Session session;
+
+ public ExecutionPlanImpl(List<PackageTask> tasks) {
+ this.tasks.addAll(tasks);
+ }
+
+ public List<PackageTask> getTasks() {
+ return tasks;
+ }
+
+ @Nonnull
+ @Override
+ public String getId() {
+ return id;
+ }
+
+ ExecutionPlanImpl setId(String id) {
+ this.id = id;
+ return this;
+ }
+
+ ExecutionPlanImpl with(PackageRegistry registry) {
+ this.registry = registry;
+ return this;
+ }
+
+ ExecutionPlanImpl with(Session session) {
+ this.session = session;
+ return this;
+ }
+
+ ExecutionPlanImpl with(ProgressTrackerListener listener) {
+ this.listener = listener;
+ return this;
+ }
+
+ PackageRegistry getRegistry() {
+ return registry;
+ }
+
+ ProgressTrackerListener getListener() {
+ return listener;
+ }
+
+ Session getSession() {
+ return session;
+ }
+
+ @Override
+ public boolean isExecuted() {
+ for (PackageTask task: tasks) {
+ if (task.getState() != PackageTask.State.COMPLETED && task.getState() != PackageTask.State.ERROR) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public boolean hasErrors() {
+ for (PackageTask task: tasks) {
+ if (task.getState() == PackageTask.State.ERROR) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Nonnull
+ public ExecutionPlan execute() throws IOException, PackageException {
+ if (isExecuted()) {
+ log.warn("executing plan that was already executed.");
+ return this;
+ }
+
+ for (PackageTask task: tasks) {
+ if (task instanceof PackageTaskImpl) {
+ ((PackageTaskImpl) task).execute(this);
+ } else {
+ throw new PackageException("task class " + task.getClass().getName() + " is not supported.");
+ }
+ }
+ return this;
+ }
+
+
+}
\ No newline at end of file
Copied: jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/impl/JcrPackageRegistry.java (from r1805059, jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/impl/JcrPackageManagerImpl.java)
URL: http://svn.apache.org/viewvc/jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/impl/JcrPackageRegistry.java?p2=jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/impl/JcrPackageRegistry.java&p1=jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/impl/JcrPackageManagerImpl.java&r1=1805059&r2=1810052&rev=1810052&view=diff
==============================================================================
--- jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/impl/JcrPackageManagerImpl.java (original)
+++ jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/impl/JcrPackageRegistry.java Fri Sep 29 04:16:57 2017
@@ -14,30 +14,25 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-package org.apache.jackrabbit.vault.packaging.impl;
+package org.apache.jackrabbit.vault.packaging.registry.impl;
import java.io.ByteArrayInputStream;
import java.io.File;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
-import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
+import java.util.UUID;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.jcr.Binary;
-import javax.jcr.ItemExistsException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
@@ -45,29 +40,31 @@ import javax.jcr.Session;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
-import org.apache.jackrabbit.vault.fs.api.ProgressTrackerListener;
-import org.apache.jackrabbit.vault.fs.api.WorkspaceFilter;
import org.apache.jackrabbit.vault.fs.config.MetaInf;
-import org.apache.jackrabbit.vault.fs.impl.ArchiveWrapper;
-import org.apache.jackrabbit.vault.fs.impl.SubPackageFilterArchive;
-import org.apache.jackrabbit.vault.fs.io.Archive;
-import org.apache.jackrabbit.vault.fs.io.ImportOptions;
import org.apache.jackrabbit.vault.fs.io.MemoryArchive;
-import org.apache.jackrabbit.vault.fs.io.ZipArchive;
-import org.apache.jackrabbit.vault.fs.io.ZipStreamArchive;
import org.apache.jackrabbit.vault.fs.spi.CNDReader;
import org.apache.jackrabbit.vault.fs.spi.NodeTypeInstaller;
import org.apache.jackrabbit.vault.fs.spi.ServiceProviderFactory;
import org.apache.jackrabbit.vault.packaging.Dependency;
-import org.apache.jackrabbit.vault.packaging.ExportOptions;
import org.apache.jackrabbit.vault.packaging.JcrPackage;
import org.apache.jackrabbit.vault.packaging.JcrPackageDefinition;
-import org.apache.jackrabbit.vault.packaging.JcrPackageManager;
+import org.apache.jackrabbit.vault.packaging.NoSuchPackageException;
import org.apache.jackrabbit.vault.packaging.PackageException;
+import org.apache.jackrabbit.vault.packaging.PackageExistsException;
import org.apache.jackrabbit.vault.packaging.PackageId;
import org.apache.jackrabbit.vault.packaging.VaultPackage;
import org.apache.jackrabbit.vault.packaging.Version;
import org.apache.jackrabbit.vault.packaging.events.PackageEvent;
+import org.apache.jackrabbit.vault.packaging.events.impl.PackageEventDispatcher;
+import org.apache.jackrabbit.vault.packaging.impl.JcrPackageDefinitionImpl;
+import org.apache.jackrabbit.vault.packaging.impl.JcrPackageImpl;
+import org.apache.jackrabbit.vault.packaging.impl.JcrPackageManagerImpl;
+import org.apache.jackrabbit.vault.packaging.impl.PackagePropertiesImpl;
+import org.apache.jackrabbit.vault.packaging.impl.ZipVaultPackage;
+import org.apache.jackrabbit.vault.packaging.registry.DependencyReport;
+import org.apache.jackrabbit.vault.packaging.registry.ExecutionPlanBuilder;
+import org.apache.jackrabbit.vault.packaging.registry.PackageRegistry;
+import org.apache.jackrabbit.vault.packaging.registry.RegisteredPackage;
import org.apache.jackrabbit.vault.util.InputStreamPump;
import org.apache.jackrabbit.vault.util.JcrConstants;
import org.apache.jackrabbit.vault.util.Text;
@@ -75,14 +72,14 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * Extends the {@code PackageManager} by JCR specific methods
+ * {@code JcrPackagePersistence}...
*/
-public class JcrPackageManagerImpl extends PackageManagerImpl implements JcrPackageManager {
+public class JcrPackageRegistry implements PackageRegistry {
/**
* default logger
*/
- private static final Logger log = LoggerFactory.getLogger(JcrPackageManagerImpl.class);
+ private static final Logger log = LoggerFactory.getLogger(JcrPackageRegistry.class);
/**
* name of node types resource
@@ -90,66 +87,147 @@ public class JcrPackageManagerImpl exten
private static final String DEFAULT_NODETYPES = "nodetypes.cnd";
/**
- * suggested folder types
- */
- private final static String[] FOLDER_TYPES = {"sling:Folder", "nt:folder", "nt:unstructured", null};
-
- /**
* root path for packages
*/
- final static String PACKAGE_ROOT_PATH = "/etc/packages";
+ public static final String PACKAGE_ROOT_PATH = "/etc/packages";
- /**
- * root path prefix for packages
- */
- public final static String PACKAGE_ROOT_PATH_PREFIX = "/etc/packages/";
+ public static final String PACKAGE_ROOT_PATH_PREFIX = "/etc/packages/";
/**
- * root path for packages
+ * suggested folder types
*/
- public final static String ARCHIVE_PACKAGE_ROOT_PATH = "/jcr_root/etc/packages";
+ private final static String[] FOLDER_TYPES = {"sling:Folder", "nt:folder", "nt:unstructured", null};
/**
* internal session
*/
private final Session session;
+ @Nullable
+ private PackageEventDispatcher dispatcher;
+
/**
* package root (/etc/packages)
*/
private Node packRoot;
- /**
- * Creates a new package manager using the given session.
- *
- * @param session repository session
- */
- public JcrPackageManagerImpl(Session session) {
+ public JcrPackageRegistry(Session session) {
this.session = session;
initNodeTypes();
}
+ @Nullable
+ PackageEventDispatcher getDispatcher() {
+ return dispatcher;
+ }
+
+ public void setDispatcher(@Nullable PackageEventDispatcher dispatcher) {
+ this.dispatcher = dispatcher;
+ }
+
+ public void dispatch(@Nonnull PackageEvent.Type type, @Nonnull PackageId id, @Nullable PackageId[] related) {
+ if (dispatcher == null) {
+ return;
+ }
+ dispatcher.dispatch(type, id, related);
+ }
+
+ /**
+ * Initializes vlt node types (might not be the correct location)
+ */
+ private void initNodeTypes() {
+ // check if node types are registered
+ try {
+ session.getWorkspace().getNodeTypeManager().getNodeType(JcrPackage.NT_VLT_PACKAGE);
+ // also check/register nodetypes needed for assembly
+ session.getWorkspace().getNodeTypeManager().getNodeType("vlt:HierarchyNode");
+ session.getWorkspace().getNodeTypeManager().getNodeType("vlt:FullCoverage");
+ return;
+ } catch (RepositoryException e) {
+ // ignore
+ }
+ try (InputStream in = JcrPackageManagerImpl.class.getResourceAsStream(DEFAULT_NODETYPES)){
+ if (in == null) {
+ throw new InternalError("Could not load " + DEFAULT_NODETYPES + " resource.");
+ }
+ NodeTypeInstaller installer = ServiceProviderFactory.getProvider().getDefaultNodeTypeInstaller(session);
+ CNDReader types = ServiceProviderFactory.getProvider().getCNDReader();
+ types.read(new InputStreamReader(in, "utf8"), DEFAULT_NODETYPES, null);
+ installer.install(null, types);
+ } catch (Throwable e) {
+ log.warn("Error while registering nodetypes. Package installation might not work correctly.", e);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Node getPackageRoot(boolean noCreate) throws RepositoryException {
+ if (packRoot == null) {
+ if (session.nodeExists(PACKAGE_ROOT_PATH)) {
+ packRoot = session.getNode(PACKAGE_ROOT_PATH);
+ } else if (noCreate) {
+ return null;
+ } else {
+ // assert that the session has no pending changes
+ if (session.hasPendingChanges()) {
+ throw new RepositoryException("Unwilling to create package root folder while session has transient changes.");
+ }
+ // try to create the missing intermediate nodes
+ String etcPath = Text.getRelativeParent(PACKAGE_ROOT_PATH, 1);
+ Node etc;
+ if (session.nodeExists(etcPath)) {
+ etc = session.getNode(etcPath);
+ } else {
+ etc = session.getRootNode().addNode(Text.getName(etcPath), JcrConstants.NT_FOLDER);
+ }
+ Node pack = etc.addNode(Text.getName(PACKAGE_ROOT_PATH), JcrConstants.NT_FOLDER);
+ try {
+ session.save();
+ } finally {
+ session.refresh(false);
+ }
+ packRoot = pack;
+ }
+ }
+ return packRoot;
+ }
+
+ @Nullable
+ @Override
+ public RegisteredPackage open(@Nonnull PackageId id) throws IOException {
+ try {
+ Node node = getPackageNode(id);
+ return node == null ? null : new JcrRegisteredPackage(open(node, false));
+ } catch (RepositoryException e) {
+ throw new IOException(e);
+ }
+ }
+
@Override
- public JcrPackage open(PackageId id) throws RepositoryException {
+ public boolean contains(@Nonnull PackageId id) throws IOException {
+ try {
+ return getPackageNode(id) != null;
+ } catch (RepositoryException e) {
+ throw new IOException(e);
+ }
+ }
+
+ @Nullable
+ private Node getPackageNode(@Nonnull PackageId id) throws RepositoryException {
String path = getInstallationPath(id);
String[] exts = new String[]{"", ".zip", ".jar"};
for (String ext: exts) {
if (session.nodeExists(path + ext)) {
- return open(session.getNode(path + ext));
+ return session.getNode(path + ext);
}
}
return null;
}
- @Override
- public JcrPackage open(Node node) throws RepositoryException {
- return open(node, false);
- }
-
/**
* {@inheritDoc}
*/
- @Override
public JcrPackage open(Node node, boolean allowInvalid) throws RepositoryException {
JcrPackage pack = new JcrPackageImpl(this, node);
if (pack.isValid()) {
@@ -167,69 +245,102 @@ public class JcrPackageManagerImpl exten
* {@inheritDoc}
*/
@Override
- public PackageId resolve(Dependency dependency, boolean onlyInstalled) throws RepositoryException {
- if (!getPackageRoot().hasNode(dependency.getGroup())) {
- return null;
- }
- Node groupNode = getPackageRoot().getNode(dependency.getGroup());
- NodeIterator iter = groupNode.getNodes();
- PackageId bestId = null;
- while (iter.hasNext()) {
- Node child = iter.nextNode();
- if (".snapshot".equals(child.getName())) {
- continue;
+ public PackageId resolve(Dependency dependency, boolean onlyInstalled) throws IOException {
+ try {
+ Node root = getPackageRoot(false);
+ if (!root.hasNode(dependency.getGroup())) {
+ return null;
}
- JcrPackageImpl pack = new JcrPackageImpl(this, child);
- if (pack.isValid()) {
- if (onlyInstalled && !pack.isInstalled()) {
+ Node groupNode = root.getNode(dependency.getGroup());
+ NodeIterator iter = groupNode.getNodes();
+ PackageId bestId = null;
+ while (iter.hasNext()) {
+ Node child = iter.nextNode();
+ if (".snapshot".equals(child.getName())) {
continue;
}
- PackageId id = pack.getDefinition().getId();
- if (dependency.matches(id)) {
- if (bestId == null || id.getVersion().compareTo(bestId.getVersion()) > 0) {
- bestId = id;
+ try (JcrPackageImpl pack = new JcrPackageImpl(this, child)) {
+ if (pack.isValid()) {
+ if (onlyInstalled && !pack.isInstalled()) {
+ continue;
+ }
+ PackageId id = pack.getDefinition().getId();
+ if (dependency.matches(id)) {
+ if (bestId == null || id.getVersion().compareTo(bestId.getVersion()) > 0) {
+ bestId = id;
+ }
+ }
}
}
}
-
+ return bestId;
+ } catch (RepositoryException e) {
+ throw new IOException(e);
}
- return bestId;
}
/**
* {@inheritDoc}
*/
+ @Nonnull
@Override
- public PackageId[] usage(PackageId id) throws RepositoryException {
+ public PackageId[] usage(PackageId id) throws IOException {
TreeSet<PackageId> usages = new TreeSet<PackageId>();
- for (JcrPackage p: listPackages()) {
- if (!p.isInstalled()) {
- continue;
- }
- for (Dependency dep: p.getDefinition().getDependencies()) {
- if (dep.matches(id)) {
- usages.add(p.getDefinition().getId());
- break;
+ for (PackageId pid: packages()) {
+ try (RegisteredPackage pkg = open(pid)) {
+ if (pkg == null || !pkg.isInstalled()) {
+ continue;
+ }
+ //noinspection resource
+ for (Dependency dep: pkg.getPackage().getDependencies()) {
+ if (dep.matches(id)) {
+ usages.add(pid);
+ break;
+ }
}
}
}
return usages.toArray(new PackageId[usages.size()]);
}
- /**
- * {@inheritDoc}
- */
+ @Nonnull
@Override
- public JcrPackage upload(InputStream in, boolean replace) throws RepositoryException, IOException {
- return upload(in, replace, false);
+ public DependencyReport analyzeDependencies(@Nonnull PackageId id, boolean onlyInstalled) throws IOException, NoSuchPackageException {
+ List<Dependency> unresolved = new LinkedList<Dependency>();
+ List<PackageId> resolved = new LinkedList<PackageId>();
+ try (RegisteredPackage pkg = open(id)) {
+ if (pkg == null) {
+ throw new NoSuchPackageException().setId(id);
+ }
+ //noinspection resource
+ for (Dependency dep : pkg.getPackage().getDependencies()) {
+ PackageId resolvedId = resolve(dep, onlyInstalled);
+ if (resolvedId == null) {
+ unresolved.add(dep);
+ } else {
+ resolved.add(resolvedId);
+ }
+ }
+ }
+
+ return new DependencyReportImpl(id, unresolved.toArray(new Dependency[unresolved.size()]),
+ resolved.toArray(new PackageId[resolved.size()])
+ );
}
- /**
- * {@inheritDoc}
- */
+ @Nonnull
@Override
- public JcrPackage upload(InputStream in, boolean replace, boolean strict)
- throws RepositoryException, IOException {
+ public PackageId register(@Nonnull InputStream in, boolean replace) throws IOException, PackageExistsException {
+ try (JcrPackage pkg = upload(in, replace)){
+ //noinspection resource
+ return pkg.getPackage().getId();
+ } catch (RepositoryException e) {
+ throw new IOException(e);
+ }
+ }
+
+ public JcrPackage upload(InputStream in, boolean replace)
+ throws RepositoryException, IOException, PackageExistsException {
MemoryArchive archive = new MemoryArchive(true);
InputStreamPump pump = new InputStreamPump(in , archive);
@@ -261,10 +372,10 @@ public class JcrPackageManagerImpl exten
// invalidate pid if path is unknown
if (pid == null) {
- bin.dispose();
- throw new IOException("Package does not contain a path specification or valid package id.");
+ pid = createRandomPid();
}
if (!pid.isValid()) {
+ bin.dispose();
throw new RepositoryException("Unable to create package. Illegal package name.");
}
@@ -279,25 +390,27 @@ public class JcrPackageManagerImpl exten
Calendar oldCreatedDate = null;
if (parent.hasNode(name)) {
- JcrPackage oldPackage = new JcrPackageImpl(this, parent.getNode(name));
- JcrPackageDefinitionImpl oldDef = (JcrPackageDefinitionImpl) oldPackage.getDefinition();
- if (oldDef != null) {
- state = oldDef.getState();
- oldCreatedDate = oldDef.getCreated();
+ try (JcrPackage oldPackage = new JcrPackageImpl(this, parent.getNode(name))) {
+ JcrPackageDefinitionImpl oldDef = (JcrPackageDefinitionImpl) oldPackage.getDefinition();
+ if (oldDef != null) {
+ state = oldDef.getState();
+ oldCreatedDate = oldDef.getCreated();
+ }
}
if (replace) {
parent.getNode(name).remove();
} else {
- throw new ItemExistsException("Package already exists: " + path);
+ throw new PackageExistsException("Package already exists: " + pid).setId(pid);
}
}
JcrPackage jcrPack = null;
try {
jcrPack = createNew(parent, pid, bin, archive);
JcrPackageDefinitionImpl def = (JcrPackageDefinitionImpl) jcrPack.getDefinition();
+ Calendar newCreateDate = def == null ? null : def.getCreated();
// only transfer the old package state to the new state in case both packages have the same create date
- if (state != null && oldCreatedDate != null && oldCreatedDate.compareTo(def.getCreated()) == 0) {
+ if (state != null && newCreateDate != null && oldCreatedDate != null && oldCreatedDate.compareTo(newCreateDate) == 0) {
def.setState(state);
}
dispatch(PackageEvent.Type.UPLOAD, pid, null);
@@ -312,68 +425,25 @@ public class JcrPackageManagerImpl exten
}
}
- /**
- * {@inheritDoc}
- */
@Nonnull
@Override
- public PackageId[] extract(@Nonnull Archive archive, @Nonnull ImportOptions options, boolean replace)
- throws RepositoryException, PackageException, IOException {
-
- SubPackageFilterArchive spfArchive = null;
- if (!options.isNonRecursive()) {
- spfArchive = new SubPackageFilterArchive(archive);
- archive = spfArchive;
- } else {
- archive = new ArchiveWrapper(archive);
- }
- ZipVaultPackage pkg = new ZipVaultPackage(archive, true);
-
- PackageId pid = pkg.getId();
- JcrPackage jcrPack = upload(pkg, replace, null);
- jcrPack = new JcrPackageImpl(this, jcrPack.getNode(), pkg);
- jcrPack.extract(options);
-
- Set<PackageId> ids = new HashSet<>();
- ids.add(pid);
-
- if (spfArchive != null) {
- for (Archive.Entry e: spfArchive.getSubPackageEntries()) {
- InputStream in = spfArchive.openInputStream(e);
- Archive subArchive = new ZipStreamArchive(in);
- PackageId[] subIds = extract(subArchive, options, replace);
- ids.addAll(Arrays.asList(subIds));
- subArchive.close();
- }
+ public PackageId register(@Nonnull File file, boolean replace) throws IOException, PackageExistsException {
+ ZipVaultPackage pack = new ZipVaultPackage(file, false, true);
+ try (JcrPackage pkg = upload(pack, replace)) {
+ //noinspection resource
+ return pkg.getPackage().getId();
+ } catch (RepositoryException e) {
+ throw new IOException(e);
}
-
- pkg.close();
- jcrPack.close();
- return ids.toArray(new PackageId[ids.size()]);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public JcrPackage upload(File file, boolean isTmpFile, boolean replace, String nameHint)
- throws RepositoryException, IOException {
- return upload(file, isTmpFile, replace, nameHint, false);
}
-
- /**
- * {@inheritDoc}
- */
+ @Nonnull
@Override
- public JcrPackage upload(File file, boolean isTmpFile, boolean replace, String nameHint, boolean strict)
- throws RepositoryException, IOException {
- ZipVaultPackage pack = new ZipVaultPackage(file, isTmpFile, strict);
- return upload(pack, replace, nameHint);
+ public PackageId registerExternal(@Nonnull File file, boolean replace) throws IOException, PackageExistsException {
+ throw new UnsupportedOperationException("linking files to repository persistence is not supported.");
}
- private JcrPackage upload(ZipVaultPackage pkg, boolean replace, String nameHint)
- throws RepositoryException, IOException {
+ public JcrPackage upload(ZipVaultPackage pkg, boolean replace) throws RepositoryException, IOException, PackageExistsException {
// open zip packages
if (pkg.getArchive().getJcrRoot() == null) {
@@ -386,10 +456,7 @@ public class JcrPackageManagerImpl exten
// invalidate pid if path is unknown
PackageId pid = pkg.getId();
if (pid == null) {
- if (nameHint == null || nameHint.length() == 0) {
- throw new IOException("Package does not contain a path specification and not name hint is given.");
- }
- pid = new PackageId(nameHint);
+ pid = createRandomPid();
}
if (!pid.isValid()) {
throw new RepositoryException("Unable to create package. Illegal package name.");
@@ -405,23 +472,24 @@ public class JcrPackageManagerImpl exten
JcrPackageDefinitionImpl.State state = null;
if (parent.hasNode(name)) {
- JcrPackage oldPackage = new JcrPackageImpl(this, parent.getNode(name));
- JcrPackageDefinitionImpl oldDef = (JcrPackageDefinitionImpl) oldPackage.getDefinition();
- if (oldDef != null) {
- state = oldDef.getState();
+ try (JcrPackage oldPackage = new JcrPackageImpl(this, parent.getNode(name))) {
+ JcrPackageDefinitionImpl oldDef = (JcrPackageDefinitionImpl) oldPackage.getDefinition();
+ if (oldDef != null) {
+ state = oldDef.getState();
+ }
}
if (replace) {
parent.getNode(name).remove();
} else {
- throw new ItemExistsException("Package already exists: " + path);
+ throw new PackageExistsException("Package already exists: " + pid).setId(pid);
}
}
JcrPackage jcrPack = null;
try {
jcrPack = createNew(parent, pid, pkg, false);
JcrPackageDefinitionImpl def = (JcrPackageDefinitionImpl) jcrPack.getDefinition();
- if (state != null) {
+ if (state != null && def != null) {
def.setState(state);
}
dispatch(PackageEvent.Type.UPLOAD, pid, null);
@@ -436,30 +504,46 @@ public class JcrPackageManagerImpl exten
}
/**
- * {@inheritDoc}
+ * yet another Convenience method to create intermediate nodes.
+ * @param path path to create
+ * @param autoSave if {@code true} all changes are automatically persisted
+ * @return the node
+ * @throws RepositoryException if an error occurrs
*/
- @Override
- public JcrPackage create(Node folder, String name)
- throws RepositoryException, IOException {
- if (folder == null) {
- folder = getPackageRoot();
+ public Node mkdir(String path, boolean autoSave) throws RepositoryException {
+ if (session.nodeExists(path)) {
+ return session.getNode(path);
}
- return createNew(folder, new PackageId(name), null, true);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public JcrPackage create(String group, String name)
- throws RepositoryException, IOException {
- return create(group, name, null);
+ String parentPath = Text.getRelativeParent(path, 1);
+ if (path == null || ("/".equals(path) && parentPath.equals(path))) {
+ throw new RepositoryException("could not crete intermediate nodes");
+ }
+ Node parent = mkdir(parentPath, autoSave);
+ Node node = null;
+ RepositoryException lastError = null;
+ for (int i=0; node == null && i<FOLDER_TYPES.length; i++) {
+ try {
+ node = parent.addNode(Text.getName(path), FOLDER_TYPES[i]);
+ } catch (RepositoryException e) {
+ lastError = e;
+ }
+ }
+ if (node == null) {
+ if (lastError != null) {
+ throw lastError;
+ } else {
+ throw new RepositoryException("Unable to create path: " + path);
+ }
+ }
+ if (autoSave) {
+ parent.getSession().save();
+ }
+ return node;
}
/**
* {@inheritDoc}
*/
- @Override
public JcrPackage create(String group, String name, String version)
throws RepositoryException, IOException {
// sanitize name
@@ -537,7 +621,7 @@ public class JcrPackageManagerImpl exten
* @since 3.1
*/
@Nonnull
- public JcrPackage createNew(@Nonnull Node parent, @Nonnull PackageId pid, @Nonnull Binary bin, @Nonnull MemoryArchive archive)
+ private JcrPackage createNew(@Nonnull Node parent, @Nonnull PackageId pid, @Nonnull Binary bin, @Nonnull MemoryArchive archive)
throws RepositoryException, IOException {
Node node = parent.addNode(Text.getName(getInstallationPath(pid) + ".zip"), JcrConstants.NT_FILE);
Node content = node.addNode(JcrConstants.JCR_CONTENT, JcrConstants.NT_RESOURCE);
@@ -556,35 +640,30 @@ public class JcrPackageManagerImpl exten
return new JcrPackageImpl(this, node);
}
-
- /**
- * {@inheritDoc}
- */
+ @SuppressWarnings("resource")
@Override
- public void remove(JcrPackage pack) throws RepositoryException {
- PackageId pid = pack.getDefinition().getId();
- JcrPackage snap = pack.getSnapshot();
- if (snap != null) {
- snap.getNode().remove();
+ public void remove(@Nonnull PackageId id) throws IOException, NoSuchPackageException {
+ JcrRegisteredPackage pkg = (JcrRegisteredPackage) open(id);
+ if (pkg == null) {
+ throw new NoSuchPackageException().setId(id);
}
- pack.getNode().remove();
- session.save();
- dispatch(PackageEvent.Type.REMOVE, pid, null);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public JcrPackage rename(JcrPackage pack, String group, String name)
- throws PackageException, RepositoryException {
- return rename(pack, group, name, null);
+ JcrPackage pack = pkg.getJcrPackage();
+ try {
+ JcrPackage snap = pack.getSnapshot();
+ if (snap != null) {
+ snap.getNode().remove();
+ }
+ pack.getNode().remove();
+ session.save();
+ } catch (RepositoryException e) {
+ throw new IOException(e);
+ }
+ dispatch(PackageEvent.Type.REMOVE, id, null);
}
/**
* {@inheritDoc}
*/
- @Override
public JcrPackage rename(JcrPackage pack, String group, String name, String version)
throws PackageException, RepositoryException {
if (!pack.isValid()) {
@@ -624,337 +703,50 @@ public class JcrPackageManagerImpl exten
session.save();
Node newNode = session.getNode(dstPath);
dispatch(PackageEvent.Type.RENAME, id, new PackageId[]{newId});
- return open(newNode);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void assemble(JcrPackage pack, ProgressTrackerListener listener)
- throws PackageException, RepositoryException, IOException {
- pack.verifyId(true, true);
- assemble(pack.getNode(), pack.getDefinition(), listener);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void assemble(Node packNode, JcrPackageDefinition definition,
- ProgressTrackerListener listener)
- throws PackageException, RepositoryException, IOException {
- Calendar now = Calendar.getInstance();
- JcrPackageDefinitionImpl def = (JcrPackageDefinitionImpl) definition;
- validateSubPackages(def);
- def.sealForAssembly(now, true);
-
- ExportOptions opts = new ExportOptions();
- opts.setMetaInf(def.getMetaInf());
- opts.setListener(listener);
- opts.setPostProcessor(def.getInjectProcessor());
-
- VaultPackage pack = assemble(packNode.getSession(), opts, (File) null);
- PackageId id = pack.getId();
-
- // update this content
- Node contentNode = packNode.getNode(JcrConstants.JCR_CONTENT);
- InputStream in;
- try {
- in = FileUtils.openInputStream(pack.getFile());
- } catch (IOException e) {
- throw new PackageException(e);
- }
- // stay jcr 1.0 compatible
- //noinspection deprecation
- contentNode.setProperty(JcrConstants.JCR_DATA, in);
- contentNode.setProperty(JcrConstants.JCR_LASTMODIFIED, now);
- contentNode.setProperty(JcrConstants.JCR_MIMETYPE, JcrPackage.MIME_TYPE);
- packNode.getSession().save();
- pack.close();
- dispatch(PackageEvent.Type.ASSEMBLE, id, null);
- }
-
- /**
- * {@inheritDoc}
- */
- private void validateSubPackages(JcrPackageDefinitionImpl def)
- throws RepositoryException, PackageException {
- List<JcrPackage> subs = listPackages(def.getMetaInf().getFilter());
- PackageId id = def.getId();
- for (JcrPackage p: subs) {
- // check if not include itself
- if (p.getDefinition().getId().equals(id)) {
- throw new PackageException("A package cannot include itself. Check filter definition.");
- }
- if (!p.isSealed()) {
- throw new PackageException("Only sealed (built) sub packages allowed: " + p.getDefinition().getId());
- }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void assemble(JcrPackageDefinition definition,
- ProgressTrackerListener listener, OutputStream out)
- throws IOException, RepositoryException, PackageException {
- JcrPackageDefinitionImpl def = (JcrPackageDefinitionImpl) definition;
- validateSubPackages(def);
- Calendar now = Calendar.getInstance();
- def.sealForAssembly(now, true);
-
- ExportOptions opts = new ExportOptions();
- opts.setMetaInf(def.getMetaInf());
- opts.setListener(listener);
- opts.setPostProcessor(def.getInjectProcessor());
-
- assemble(def.getNode().getSession(), opts, out);
+ return open(newNode, false);
}
- /**
- * {@inheritDoc}
- */
- @Override
- public void rewrap(JcrPackage pack, ProgressTrackerListener listener)
- throws PackageException, RepositoryException, IOException {
- VaultPackage src = ((JcrPackageImpl) pack).getPackage(true);
-
- Calendar now = Calendar.getInstance();
- pack.verifyId(true, false);
- JcrPackageDefinitionImpl def = (JcrPackageDefinitionImpl) pack.getDefinition();
- def.sealForRewrap(now, true);
-
- ExportOptions opts = new ExportOptions();
- opts.setMetaInf(def.getMetaInf());
- opts.setListener(listener);
- opts.setPostProcessor(def.getInjectProcessor());
-
- VaultPackage dst = rewrap(opts, src, (File) null);
-
- // update this content
- Node packNode = pack.getNode();
- Node contentNode = packNode.getNode(JcrConstants.JCR_CONTENT);
- InputStream in;
- try {
- in = FileUtils.openInputStream(dst.getFile());
- } catch (IOException e) {
- throw new PackageException(e);
- }
- // stay jcr 1.0 compatible
- //noinspection deprecation
- contentNode.setProperty(JcrConstants.JCR_DATA, in);
- contentNode.setProperty(JcrConstants.JCR_LASTMODIFIED, now);
- contentNode.setProperty(JcrConstants.JCR_MIMETYPE, JcrPackage.MIME_TYPE);
- packNode.getSession().save();
- dst.close();
- }
-
- /**
- * {@inheritDoc}
- */
+ @Nonnull
@Override
- public Node getPackageRoot() throws RepositoryException {
- return getPackageRoot(false);
- }
-
- /**
- * yet another Convenience method to create intermediate nodes.
- * @param path path to create
- * @param autoSave if {@code true} all changes are automatically persisted
- * @return the node
- * @throws RepositoryException if an error occurrs
- */
- protected Node mkdir(String path, boolean autoSave) throws RepositoryException {
- if (session.nodeExists(path)) {
- return session.getNode(path);
- }
- String parentPath = Text.getRelativeParent(path, 1);
- if (path == null || ("/".equals(path) && parentPath.equals(path))) {
- throw new RepositoryException("could not crete intermediate nodes");
- }
- Node parent = mkdir(parentPath, autoSave);
- Node node = null;
- RepositoryException lastError = null;
- for (int i=0; node == null && i<FOLDER_TYPES.length; i++) {
- try {
- node = parent.addNode(Text.getName(path), FOLDER_TYPES[i]);
- } catch (RepositoryException e) {
- lastError = e;
- }
- }
- if (node == null) {
- throw lastError;
- }
- if (autoSave) {
- parent.getSession().save();
- }
- return node;
- }
-
- /**
- * Initializes vlt node types (might not be the correct location)
- */
- private void initNodeTypes() {
- // check if node types are registered
+ public Set<PackageId> packages() throws IOException {
try {
- session.getWorkspace().getNodeTypeManager().getNodeType(JcrPackage.NT_VLT_PACKAGE);
- // also check/register nodetypes needed for assembly
- session.getWorkspace().getNodeTypeManager().getNodeType("vlt:HierarchyNode");
- session.getWorkspace().getNodeTypeManager().getNodeType("vlt:FullCoverage");
- return;
- } catch (RepositoryException e) {
- // ignore
- }
- InputStream in = null;
- try {
- in = getClass().getResourceAsStream(DEFAULT_NODETYPES);
- if (in == null) {
- throw new InternalError("Could not load " + DEFAULT_NODETYPES + " resource.");
- }
- NodeTypeInstaller installer = ServiceProviderFactory.getProvider().getDefaultNodeTypeInstaller(session);
- CNDReader types = ServiceProviderFactory.getProvider().getCNDReader();
- types.read(new InputStreamReader(in, "utf8"), DEFAULT_NODETYPES, null);
- installer.install(null, types);
- } catch (Throwable e) {
- log.warn("Error while registering nodetypes. Package installation might not work correctly.", e);
- } finally {
- IOUtils.closeQuietly(in);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Node getPackageRoot(boolean noCreate) throws RepositoryException {
- if (packRoot == null) {
- if (session.nodeExists(PACKAGE_ROOT_PATH)) {
- packRoot = session.getNode(PACKAGE_ROOT_PATH);
- } else if (noCreate) {
- return null;
- } else {
- // assert that the session has no pending changes
- if (session.hasPendingChanges()) {
- throw new RepositoryException("Unwilling to create package root folder while session has transient changes.");
- }
- // try to create the missing intermediate nodes
- String etcPath = Text.getRelativeParent(PACKAGE_ROOT_PATH, 1);
- Node etc;
- if (session.nodeExists(etcPath)) {
- etc = session.getNode(etcPath);
- } else {
- etc = session.getRootNode().addNode(Text.getName(etcPath), JcrConstants.NT_FOLDER);
- }
- Node pack = etc.addNode(Text.getName(PACKAGE_ROOT_PATH), JcrConstants.NT_FOLDER);
- try {
- session.save();
- } finally {
- session.refresh(false);
- }
- packRoot = pack;
+ Node pRoot = getPackageRoot(true);
+ if (pRoot == null) {
+ return Collections.emptySet();
}
- }
- return packRoot;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public List<JcrPackage> listPackages() throws RepositoryException {
- return listPackages(null);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public List<JcrPackage> listPackages(WorkspaceFilter filter) throws RepositoryException {
- Node root = getPackageRoot(true);
- if (root == null) {
- return Collections.emptyList();
- } else {
- List<JcrPackage> packages = new LinkedList<JcrPackage>();
- listPackages(root, packages, filter, false, false);
- Collections.sort(packages);
+ Set<PackageId> packages = new TreeSet<PackageId>();
+ listPackages(pRoot, packages);
return packages;
+ } catch (RepositoryException e) {
+ throw new IOException(e);
}
}
/**
- * {@inheritDoc}
- */
- @Override
- public List<JcrPackage> listPackages(String group, boolean built) throws RepositoryException {
- Node pRoot = getPackageRoot(true);
- if (pRoot == null) {
- return Collections.emptyList();
- }
- List<JcrPackage> packages = new LinkedList<JcrPackage>();
- if (group == null) {
- listPackages(pRoot, packages, null, built, false);
- } else {
- Node root = pRoot;
- if (group.length() > 0) {
- if (group.equals(pRoot.getPath())) {
- group = "";
- } else if (group.startsWith(pRoot.getPath() + "/")) {
- group = group.substring(pRoot.getPath().length() + 1);
- }
- if (group.startsWith("/")) {
- // don't scan outside /etc/packages
- return packages;
- } else if (group.length() > 0) {
- if (root.hasNode(group)) {
- root = root.getNode(group);
- } else {
- return packages;
- }
- }
- }
- listPackages(root, packages, null, built, true);
- }
- Collections.sort(packages);
- return packages;
- }
-
- /**
* internally adds the packages below {@code root} to the given list
* recursively.
*
* @param root root node
* @param packages list for the packages
- * @param filter optional filter to filter out packages
- * @param built if {@code true} only packages with size > 0 are returned
- * @param shallow if {@code true} don't recurs
* @throws RepositoryException if an error occurs
*/
- private void listPackages(Node root, List<JcrPackage> packages,
- WorkspaceFilter filter, boolean built, boolean shallow)
- throws RepositoryException {
- if (root != null) {
- for (NodeIterator iter = root.getNodes(); iter.hasNext();) {
- Node child = iter.nextNode();
- if (".snapshot".equals(child.getName())) {
- continue;
- }
- JcrPackageImpl pack = new JcrPackageImpl(this, child);
+ private void listPackages(Node root, Set<PackageId> packages) throws RepositoryException {
+ for (NodeIterator iter = root.getNodes(); iter.hasNext();) {
+ Node child = iter.nextNode();
+ if (".snapshot".equals(child.getName())) {
+ continue;
+ }
+ try (JcrPackageImpl pack = new JcrPackageImpl(this, child)) {
if (pack.isValid()) {
// skip packages with illegal names
JcrPackageDefinition jDef = pack.getDefinition();
- if (jDef != null && !jDef.getId().isValid()) {
+ if (jDef == null || !jDef.getId().isValid()) {
continue;
}
- if (filter == null || filter.contains(child.getPath())) {
- if (!built || pack.getSize() > 0) {
- packages.add(pack);
- }
- }
- } else if (child.hasNodes() && !shallow){
- listPackages(child, packages, filter, built, false);
+ packages.add(jDef.getId());
+ } else if (child.hasNodes()) {
+ listPackages(child, packages);
}
}
}
@@ -964,25 +756,35 @@ public class JcrPackageManagerImpl exten
* Returns the path of this package. please note that since 2.3 this also
* includes the version, but never the extension (.zip).
*
- * Note that the exact storage location is implementation detail and this method should only be used internally for
- * backward compatibility use cases.
- *
- * @param pid the package id
* @return the path of this package
+ * @since 2.2
*/
- public static String getInstallationPath(PackageId pid) {
+ public static String getInstallationPath(PackageId id) {
StringBuilder b = new StringBuilder(PACKAGE_ROOT_PATH_PREFIX);
- String group = pid.getGroup();
- if (group.length() > 0) {
- b.append(group);
+ if (id.getGroup().length() > 0) {
+ b.append(id.getGroup());
b.append("/");
}
- b.append(pid.getName());
- String version = pid.getVersion().toString();
- if (version.length() > 0) {
- b.append("-").append(version);
+ b.append(id.getName());
+ String v = id.getVersion().toString();
+ if (v.length() > 0) {
+ b.append("-").append(v);
}
return b.toString();
}
+ /**
+ * Creates a random package id for packages that lack one.
+ * @return a random package id.
+ */
+ private static PackageId createRandomPid() {
+ return new PackageId("temporary", "pack_" + UUID.randomUUID().toString(), (String) null);
+ }
+
+ @Nonnull
+ @Override
+ public ExecutionPlanBuilder createExecutionPlan() {
+ return new ExecutionPlanBuilderImpl(this);
+ }
+
}
\ No newline at end of file
Added: jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/impl/JcrRegisteredPackage.java
URL: http://svn.apache.org/viewvc/jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/impl/JcrRegisteredPackage.java?rev=1810052&view=auto
==============================================================================
--- jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/impl/JcrRegisteredPackage.java (added)
+++ jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/impl/JcrRegisteredPackage.java Fri Sep 29 04:16:57 2017
@@ -0,0 +1,99 @@
+/*
+ * 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.jackrabbit.vault.packaging.registry.impl;
+
+import java.io.IOException;
+import java.util.Calendar;
+
+import javax.annotation.CheckForNull;
+import javax.annotation.Nonnull;
+import javax.jcr.RepositoryException;
+
+import org.apache.jackrabbit.vault.packaging.JcrPackage;
+import org.apache.jackrabbit.vault.packaging.JcrPackageDefinition;
+import org.apache.jackrabbit.vault.packaging.PackageId;
+import org.apache.jackrabbit.vault.packaging.VaultPackage;
+import org.apache.jackrabbit.vault.packaging.registry.RegisteredPackage;
+
+/**
+ * {@code JcrRegisteredPackage}...
+ */
+public class JcrRegisteredPackage implements RegisteredPackage {
+
+ private JcrPackage pkg;
+
+ private VaultPackage vltPkg;
+
+ public JcrRegisteredPackage(JcrPackage pkg) throws IOException, RepositoryException {
+ this.pkg = pkg;
+ this.vltPkg = pkg.getPackage();
+ }
+
+ public JcrPackage getJcrPackage() {
+ return pkg;
+ }
+
+ @Nonnull
+ @Override
+ public PackageId getId() {
+ return vltPkg.getId();
+ }
+
+ @Nonnull
+ @Override
+ public VaultPackage getPackage() throws IOException {
+ return vltPkg;
+ }
+
+ @Override
+ public boolean isInstalled() {
+ try {
+ return pkg.isInstalled();
+ } catch (RepositoryException e) {
+ return false;
+ }
+ }
+
+ @Override
+ public long getSize() {
+ return pkg.getSize();
+ }
+
+ @CheckForNull
+ @Override
+ public Calendar getInstallationTime() {
+ try {
+ JcrPackageDefinition def = pkg.getDefinition();
+ return def == null ? null : def.getLastUnpacked();
+ } catch (RepositoryException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ @Override
+ public void close() {
+ vltPkg.close();
+ vltPkg = null;
+ pkg.close();
+ pkg = null;
+ }
+
+ @Override
+ public int compareTo(RegisteredPackage o) {
+ return getId().compareTo(o.getId());
+ }
+}
\ No newline at end of file
Added: jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/impl/PackageTaskImpl.java
URL: http://svn.apache.org/viewvc/jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/impl/PackageTaskImpl.java?rev=1810052&view=auto
==============================================================================
--- jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/impl/PackageTaskImpl.java (added)
+++ jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/impl/PackageTaskImpl.java Fri Sep 29 04:16:57 2017
@@ -0,0 +1,198 @@
+/*
+ * 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.jackrabbit.vault.packaging.registry.impl;
+
+import java.io.IOException;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import javax.jcr.RepositoryException;
+
+import org.apache.jackrabbit.vault.fs.io.ImportOptions;
+import org.apache.jackrabbit.vault.packaging.DependencyHandling;
+import org.apache.jackrabbit.vault.packaging.JcrPackage;
+import org.apache.jackrabbit.vault.packaging.NoSuchPackageException;
+import org.apache.jackrabbit.vault.packaging.PackageException;
+import org.apache.jackrabbit.vault.packaging.PackageId;
+import org.apache.jackrabbit.vault.packaging.registry.PackageTask;
+import org.apache.jackrabbit.vault.packaging.registry.RegisteredPackage;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * {@code PackageTaskImpl}...
+ */
+public class PackageTaskImpl implements PackageTask {
+
+ /**
+ * default logger
+ */
+ private static final Logger log = LoggerFactory.getLogger(PackageTaskImpl.class);
+
+ final static PackageTaskImpl MARKER = new PackageTaskImpl(new PackageId("", "" ,""), Type.INSTALL);
+
+ private final PackageId id;
+
+ private final Type type;
+
+ private State state = State.NEW;
+
+ private Throwable error;
+
+ PackageTaskImpl(@Nonnull PackageId id, @Nonnull Type type) {
+ this.id = id;
+ this.type = type;
+ }
+
+ @Nonnull
+ @Override
+ public PackageId getPackageId() {
+ return id;
+ }
+
+ @Nonnull
+ @Override
+ public Type getType() {
+ return type;
+ }
+
+ @Nonnull
+ @Override
+ public State getState() {
+ return state;
+ }
+
+ @Nullable
+ @Override
+ public Throwable getError() {
+ return error;
+ }
+
+ @Override
+ public String toString() {
+ return "PackageTaskImpl{" + "id=" + id +
+ ", type=" + type +
+ ", state=" + state +
+ '}';
+ }
+
+ void execute(ExecutionPlanImpl executionPlan) {
+ if (state != State.NEW) {
+ return;
+ }
+ state = State.RUNNING;
+ try {
+ switch (type) {
+ case INSTALL:
+ doInstall(executionPlan, false);
+ break;
+ case UNINSTALL:
+ doUninstall(executionPlan);
+ break;
+ case REMOVE:
+ doRemove(executionPlan);
+ break;
+ case EXTRACT:
+ doInstall(executionPlan, true);
+ break;
+ }
+ state = State.COMPLETED;
+ } catch (Exception e) {
+ log.info("error during package task {} on {}: {}", type, id, e.toString());
+ error = e;
+ state = State.ERROR;
+ }
+ }
+
+ /**
+ * Performs the removal.
+ * @param plan the execution plan
+ * @throws IOException if an I/O error occurs
+ * @throws PackageException if a package error occurs
+ */
+ private void doRemove(ExecutionPlanImpl plan) throws IOException, PackageException {
+ try (RegisteredPackage pkg = plan.getRegistry().open(id)) {
+ if (pkg == null) {
+ throw new NoSuchPackageException("No such package: " + id);
+ }
+ if (pkg.isInstalled()) {
+ throw new PackageException("refusing to remove installed package: " + id);
+ }
+ plan.getRegistry().remove(id);
+ }
+ }
+
+ /**
+ * Performs the uninstallation.
+ * @param plan the execution plan
+ * @throws IOException if an I/O error occurs
+ * @throws PackageException if a package error occurs
+ */
+ private void doUninstall(ExecutionPlanImpl plan) throws IOException, PackageException {
+ ImportOptions opts = new ImportOptions();
+ opts.setListener(plan.getListener());
+ // execution plan resolution already has resolved all dependencies, so there is no need to use best effort here.
+ opts.setDependencyHandling(DependencyHandling.STRICT);
+
+ try (RegisteredPackage pkg = plan.getRegistry().open(id)) {
+ if (pkg == null) {
+ throw new NoSuchPackageException("No such package: " + id);
+ }
+ if (!(pkg instanceof JcrRegisteredPackage)) {
+ throw new PackageException("non jcr packages not supported yet");
+ }
+ try (JcrPackage jcrPkg = ((JcrRegisteredPackage) pkg).getJcrPackage()){
+ jcrPkg.uninstall(opts);
+ } catch (RepositoryException e) {
+ throw new IOException(e);
+ }
+ }
+ }
+
+ /**
+ * Performs the installation.
+ * @param plan the execution plan
+ * @throws IOException if an I/O error occurs
+ * @throws PackageException if a package error occurs
+ */
+ private void doInstall(ExecutionPlanImpl plan, boolean extract) throws IOException, PackageException {
+ ImportOptions opts = new ImportOptions();
+ opts.setListener(plan.getListener());
+ // execution plan resolution already has resolved all dependencies, so there is no need to use best effort here.
+ opts.setDependencyHandling(DependencyHandling.STRICT);
+
+ try (RegisteredPackage pkg = plan.getRegistry().open(id)) {
+ if (pkg == null) {
+ throw new NoSuchPackageException("No such package: " + id);
+ }
+ if (!(pkg instanceof JcrRegisteredPackage)) {
+ throw new PackageException("non jcr packages not supported yet");
+ }
+ try (JcrPackage jcrPkg = ((JcrRegisteredPackage) pkg).getJcrPackage()){
+ if (extract) {
+ jcrPkg.extract(opts);
+ } else {
+ jcrPkg.install(opts);
+ }
+ } catch (RepositoryException e) {
+ throw new IOException(e);
+ }
+ }
+ }
+
+
+}
\ No newline at end of file
Copied: jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/package-info.java (from r1805059, jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/package-info.java)
URL: http://svn.apache.org/viewvc/jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/package-info.java?p2=jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/package-info.java&p1=jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/package-info.java&r1=1805059&r2=1810052&rev=1810052&view=diff
==============================================================================
--- jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/package-info.java (original)
+++ jackrabbit/commons/filevault/trunk/vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/registry/package-info.java Fri Sep 29 04:16:57 2017
@@ -14,8 +14,5 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-@Version("2.5.0")
-package org.apache.jackrabbit.vault.packaging;
-
-import org.osgi.annotation.versioning.Version;
\ No newline at end of file
+@org.osgi.annotation.versioning.Version("1.0.0")
+package org.apache.jackrabbit.vault.packaging.registry;
Modified: jackrabbit/commons/filevault/trunk/vault-core/src/test/java/org/apache/jackrabbit/vault/packaging/integration/TestArchiveExtraction.java
URL: http://svn.apache.org/viewvc/jackrabbit/commons/filevault/trunk/vault-core/src/test/java/org/apache/jackrabbit/vault/packaging/integration/TestArchiveExtraction.java?rev=1810052&r1=1810051&r2=1810052&view=diff
==============================================================================
--- jackrabbit/commons/filevault/trunk/vault-core/src/test/java/org/apache/jackrabbit/vault/packaging/integration/TestArchiveExtraction.java (original)
+++ jackrabbit/commons/filevault/trunk/vault-core/src/test/java/org/apache/jackrabbit/vault/packaging/integration/TestArchiveExtraction.java Fri Sep 29 04:16:57 2017
@@ -121,6 +121,8 @@ public class TestArchiveExtraction exten
fail("extract w/o replace should fail.");
} catch (ItemExistsException e) {
// expected
+ } catch (PackageException e) {
+ // expected
}
}