Search in sources :

Example 1 with UpdateResult

use of org.apache.sling.installer.api.UpdateResult in project sling by apache.

the class UpdateHandlerTest method testSimpleUpdate.

@Test
public void testSimpleUpdate() throws Exception {
    final UpdateHandlerImpl up = new UpdateHandlerImpl();
    final Dictionary<String, Object> dict = new Hashtable<String, Object>();
    dict.put(UpdateHandler.PROPERTY_SCHEMES, TYPE);
    this.serviceRegistrations.add(this.bundleContext.registerService(UpdateHandler.class, up, dict));
    final Dictionary<String, Object> data = new Hashtable<String, Object>();
    data.put("foo", "bar");
    final InstallableResource ir = new InstallableResource("/resource/a." + TYPE, null, data, null, InstallableResource.TYPE_PROPERTIES, null);
    final Barrier b = this.getInstallerListenerBarrier();
    this.installer.registerResources(TYPE, new InstallableResource[] { ir });
    b.block();
    b.reg.unregister();
    assertNotNull("Resource should be installed: " + installed, installed.get(TYPE) + ":a");
    final Dictionary<String, Object> newData = new Hashtable<String, Object>();
    data.put("bar", "foo");
    this.resourceChangeListener.resourceAddedOrUpdated(TYPE, "a", null, newData, null);
    final UpdateResult ur = up.waitForUpdate();
    assertNotNull(ur);
    assertEquals(TYPE + ":/resource/b/a." + TYPE, ur.getURL());
    this.resourceChangeListener.resourceRemoved(TYPE, "a");
    final UpdateResult r2 = up.waitForUpdate();
    assertNotNull(r2);
    assertEquals(TYPE + ":/resource/b/a." + TYPE, r2.getURL());
}
Also used : UpdateHandler(org.apache.sling.installer.api.UpdateHandler) Hashtable(java.util.Hashtable) InstallableResource(org.apache.sling.installer.api.InstallableResource) CyclicBarrier(java.util.concurrent.CyclicBarrier) UpdateResult(org.apache.sling.installer.api.UpdateResult) Test(org.junit.Test)

Example 2 with UpdateResult

use of org.apache.sling.installer.api.UpdateResult in project sling by apache.

the class FileInstaller method handleUpdate.

/**
     * Internal implementation of update handling
     */
private UpdateResult handleUpdate(final String resourceType, final String id, final String url, final InputStream is, final Dictionary<String, Object> dict, final Map<String, Object> attributes) {
    if (!this.writeBack) {
        return null;
    }
    // we only handle add/update of configs for now
    if (!resourceType.equals(InstallableResource.TYPE_CONFIG)) {
        return null;
    }
    try {
        final String path;
        final String prefix;
        if (url != null) {
            // update
            final int pos = url.indexOf(':');
            final String oldPath = url.substring(pos + 1);
            prefix = url.substring(0, pos);
            // ensure extension 'config'
            if (!oldPath.endsWith(".config")) {
                final File file = new File(oldPath);
                if (file.exists()) {
                    file.delete();
                }
                final int lastDot = oldPath.lastIndexOf('.');
                final int lastSlash = oldPath.lastIndexOf('/');
                if (lastDot <= lastSlash) {
                    path = oldPath + ".config";
                } else {
                    path = oldPath.substring(0, lastDot) + ".config";
                }
            } else {
                path = oldPath;
            }
            logger.debug("Update of {} at {}", resourceType, path);
        } else {
            // add
            final FileMonitor first = this.monitors.get(0);
            path = first.getRoot().getAbsolutePath() + '/' + id + ".config";
            prefix = first.getListener().getScheme();
            logger.debug("Add of {} at {}", resourceType, path);
        }
        final File file = new File(path);
        file.getParentFile().mkdirs();
        final FileOutputStream fos = new FileOutputStream(file);
        try {
            fos.write("# Configuration created by Apache Sling File Installer\n".getBytes("UTF-8"));
            ConfigurationHandler.write(fos, dict);
        } finally {
            try {
                fos.close();
            } catch (final IOException ignore) {
            }
        }
        final UpdateResult result = new UpdateResult(prefix + ':' + path);
        result.setResourceIsMoved(true);
        return result;
    } catch (final IOException e) {
        logger.error("Unable to add/update resource " + resourceType + ':' + id, e);
        return null;
    }
}
Also used : FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) File(java.io.File) UpdateResult(org.apache.sling.installer.api.UpdateResult)

Example 3 with UpdateResult

use of org.apache.sling.installer.api.UpdateResult in project sling by apache.

the class FileInstaller method handleRemoval.

/**
     * @see org.apache.sling.installer.api.UpdateHandler#handleRemoval(java.lang.String, java.lang.String, java.lang.String)
     */
public UpdateResult handleRemoval(final String resourceType, final String id, final String url) {
    if (!this.writeBack) {
        return null;
    }
    final int pos = url.indexOf(':');
    final String path = url.substring(pos + 1);
    // remove
    logger.debug("Removal of {}", path);
    final File file = new File(path);
    if (file.exists()) {
        file.delete();
    }
    return new UpdateResult(url);
}
Also used : File(java.io.File) UpdateResult(org.apache.sling.installer.api.UpdateResult)

Example 4 with UpdateResult

use of org.apache.sling.installer.api.UpdateResult in project sling by apache.

the class JcrInstaller method handleUpdate.

/**
     * Internal implementation of update handling
     */
private UpdateResult handleUpdate(final String resourceType, final String id, final String url, final InputStream is, final Dictionary<String, Object> dict, final Map<String, Object> attributes) {
    // get configuration
    final InstallerConfig cfg = this.getConfiguration();
    if (cfg == null || !cfg.isWriteBack()) {
        return null;
    }
    // we only handle add/update of configs for now
    if (!resourceType.equals(InstallableResource.TYPE_CONFIG)) {
        return null;
    }
    Session session = null;
    try {
        session = repository.loginService(/* subservice name */
        null, repository.getDefaultWorkspace());
        final String path;
        boolean resourceIsMoved = true;
        if (url != null) {
            // update
            final int pos = url.indexOf(':');
            final String oldPath = url.substring(pos + 1);
            // calculate the new node path
            final String nodePath;
            if (url.startsWith(URL_SCHEME + ':')) {
                nodePath = getPathWithHighestPrio(cfg, oldPath);
            } else {
                final int lastSlash = url.lastIndexOf('/');
                final int lastPos = url.lastIndexOf('.');
                final String name;
                if (lastSlash == -1 || lastPos < lastSlash) {
                    name = id;
                } else {
                    name = url.substring(lastSlash + 1, lastPos);
                }
                nodePath = getPathWithHighestPrio(cfg, cfg.getNewConfigPath() + name + ".config");
            }
            // ensure extension 'config'
            if (!nodePath.endsWith(".config")) {
                if (session.itemExists(nodePath)) {
                    session.getItem(nodePath).remove();
                }
                path = nodePath + ".config";
            } else {
                path = nodePath;
            }
            resourceIsMoved = nodePath.equals(oldPath);
            logger.debug("Update of {} at {}", resourceType, path);
        } else {
            // add
            final String name;
            if (attributes != null && attributes.get(InstallableResource.RESOURCE_URI_HINT) != null) {
                name = (String) attributes.get(InstallableResource.RESOURCE_URI_HINT);
            } else {
                name = id;
            }
            path = cfg.getNewConfigPath() + name + ".config";
            logger.debug("Add of {} at {}", resourceType, path);
        }
        // write to a byte array stream
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.write("# Configuration created by Apache Sling JCR Installer\n".getBytes("UTF-8"));
        ConfigurationHandler.write(baos, dict);
        baos.close();
        // get or create file node
        JcrUtil.createPath(session, path, NT_FILE);
        // get or create resource node
        final Node dataNode = JcrUtil.createPath(session, path + "/jcr:content", NT_RESOURCE);
        dataNode.setProperty(PROP_DATA, new ByteArrayInputStream(baos.toByteArray()));
        dataNode.setProperty(PROP_MODIFIED, Calendar.getInstance());
        dataNode.setProperty(PROP_ENC, ENCODING);
        dataNode.setProperty(PROP_MIME, MIME_TXT);
        session.save();
        final UpdateResult result = new UpdateResult(JcrInstaller.URL_SCHEME + ':' + path);
        // priority
        final int lastSlash = path.lastIndexOf('/');
        final String parentPath = path.substring(0, lastSlash);
        result.setPriority(cfg.getFolderNameFilter().getPriority(parentPath));
        result.setResourceIsMoved(resourceIsMoved);
        return result;
    } catch (final RepositoryException re) {
        logger.error("Unable to add/update resource " + resourceType + ':' + id, re);
        return null;
    } catch (final IOException e) {
        logger.error("Unable to add/update resource " + resourceType + ':' + id, e);
        return null;
    } finally {
        if (session != null) {
            session.logout();
        }
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) Node(javax.jcr.Node) RepositoryException(javax.jcr.RepositoryException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) UpdateResult(org.apache.sling.installer.api.UpdateResult) Session(javax.jcr.Session)

Example 5 with UpdateResult

use of org.apache.sling.installer.api.UpdateResult in project sling by apache.

the class OsgiInstallerImpl method internalResourceAddedOrUpdated.

/**
     * Handle external addition or update of a resource
     * @see org.apache.sling.installer.api.ResourceChangeListener#resourceAddedOrUpdated(java.lang.String, java.lang.String, java.io.InputStream, java.util.Dictionary, Map)
     */
private void internalResourceAddedOrUpdated(final String resourceType, final String entityId, final ResourceData data, final Dictionary<String, Object> dict, final Map<String, Object> attributes) {
    final String key = resourceType + ':' + entityId;
    final boolean persistChange = (attributes != null ? PropertiesUtil.toBoolean(attributes.get(ResourceChangeListener.RESOURCE_PERSIST), true) : true);
    try {
        boolean compactAndSave = false;
        boolean done = false;
        synchronized (this.resourcesLock) {
            final EntityResourceList erl = this.persistentList.getEntityResourceList(key);
            logger.debug("Added or updated {} : {}", key, erl);
            // we first check for update
            if (erl != null && erl.getFirstResource() != null) {
                // check digest for dictionaries
                final TaskResource tr = erl.getFirstResource();
                if (dict != null) {
                    final String digest = FileDataStore.computeDigest(dict);
                    if (tr.getDigest().equals(digest)) {
                        if (tr.getState() == ResourceState.INSTALLED) {
                            logger.debug("Resource did not change {}", key);
                        } else if (tr.getState() == ResourceState.INSTALL || tr.getState() == ResourceState.IGNORED) {
                            erl.setForceFinishState(ResourceState.INSTALLED, null);
                            compactAndSave = true;
                        }
                        done = true;
                    }
                }
                final UpdateHandler handler;
                if (!done && persistChange) {
                    handler = this.findHandler(tr.getScheme());
                    if (handler == null) {
                        logger.debug("No handler found to handle update of resource with scheme {}", tr.getScheme());
                    }
                } else {
                    handler = null;
                }
                if (!done && handler == null) {
                    compactAndSave = this.handleExternalUpdateWithoutWriteBack(erl);
                    done = true;
                }
                if (!done) {
                    final InputStream localIS = data.getInputStream();
                    try {
                        final UpdateResult result = (localIS == null ? handler.handleUpdate(resourceType, entityId, tr.getURL(), data.getDictionary(), attributes) : handler.handleUpdate(resourceType, entityId, tr.getURL(), localIS, attributes));
                        if (result != null) {
                            if (!result.getURL().equals(tr.getURL()) && !result.getResourceIsMoved()) {
                                // resource has been added!
                                final InternalResource internalResource = new InternalResource(result.getScheme(), result.getResourceId(), null, data.getDictionary(), (data.getDictionary() != null ? InstallableResource.TYPE_PROPERTIES : InstallableResource.TYPE_FILE), data.getDigest(result.getURL(), result.getDigest()), result.getPriority(), data.getDataFile(), null);
                                final RegisteredResource rr = this.persistentList.addOrUpdate(internalResource);
                                final TransformationResult transRes = new TransformationResult();
                                // use the old entity id
                                final int pos = erl.getResourceId().indexOf(':');
                                transRes.setId(erl.getResourceId().substring(pos + 1));
                                transRes.setResourceType(resourceType);
                                if (attributes != null) {
                                    transRes.setAttributes(attributes);
                                }
                                this.persistentList.transform(rr, new TransformationResult[] { transRes });
                                final EntityResourceList newGroup = this.persistentList.getEntityResourceList(key);
                                newGroup.setFinishState(ResourceState.INSTALLED, null);
                                newGroup.compact();
                            } else {
                                // resource has been updated or moved
                                ((RegisteredResourceImpl) tr).update(data.getDataFile(), data.getDictionary(), data.getDigest(result.getURL(), result.getDigest()), result.getPriority(), result.getURL());
                                erl.setForceFinishState(ResourceState.INSTALLED, null);
                            }
                            compactAndSave = true;
                        } else {
                            // handler does not persist
                            compactAndSave = this.handleExternalUpdateWithoutWriteBack(erl);
                        }
                    } finally {
                        if (localIS != null) {
                            // always close the input stream!
                            try {
                                localIS.close();
                            } catch (final IOException ignore) {
                            // ignore
                            }
                        }
                    }
                    done = true;
                }
            }
            if (!done) {
                // create
                final List<UpdateHandler> handlerList = this.updateHandlerTracker.getSortedServices();
                for (final UpdateHandler handler : handlerList) {
                    final InputStream localIS = data.getInputStream();
                    try {
                        final UpdateResult result = (localIS == null ? handler.handleUpdate(resourceType, entityId, null, data.getDictionary(), attributes) : handler.handleUpdate(resourceType, entityId, null, localIS, attributes));
                        if (result != null) {
                            final InternalResource internalResource = new InternalResource(result.getScheme(), result.getResourceId(), null, data.getDictionary(), (data.getDictionary() != null ? InstallableResource.TYPE_PROPERTIES : InstallableResource.TYPE_FILE), data.getDigest(result.getURL(), result.getDigest()), result.getPriority(), data.getDataFile(), null);
                            final RegisteredResource rr = this.persistentList.addOrUpdate(internalResource);
                            final TransformationResult transRes = new TransformationResult();
                            transRes.setId(entityId);
                            transRes.setResourceType(resourceType);
                            if (attributes != null) {
                                transRes.setAttributes(attributes);
                            }
                            this.persistentList.transform(rr, new TransformationResult[] { transRes });
                            final EntityResourceList newGroup = this.persistentList.getEntityResourceList(key);
                            newGroup.setFinishState(ResourceState.INSTALLED);
                            newGroup.compact();
                            compactAndSave = true;
                            done = true;
                            break;
                        }
                    } finally {
                        if (localIS != null) {
                            // always close the input stream!
                            try {
                                localIS.close();
                            } catch (final IOException ignore) {
                            // ignore
                            }
                        }
                    }
                }
                if (!done) {
                    logger.debug("No handler found to handle creation of resource {}", key);
                }
            }
            if (compactAndSave) {
                if (erl != null) {
                    erl.compact();
                }
                this.persistentList.save();
            }
        }
    } catch (final IOException ioe) {
        logger.error("Unable to handle resource add or update of " + key, ioe);
    }
}
Also used : UpdateHandler(org.apache.sling.installer.api.UpdateHandler) TaskResource(org.apache.sling.installer.api.tasks.TaskResource) InputStream(java.io.InputStream) RegisteredResource(org.apache.sling.installer.api.tasks.RegisteredResource) IOException(java.io.IOException) TransformationResult(org.apache.sling.installer.api.tasks.TransformationResult) UpdateResult(org.apache.sling.installer.api.UpdateResult)

Aggregations

UpdateResult (org.apache.sling.installer.api.UpdateResult)6 IOException (java.io.IOException)3 File (java.io.File)2 RepositoryException (javax.jcr.RepositoryException)2 Session (javax.jcr.Session)2 UpdateHandler (org.apache.sling.installer.api.UpdateHandler)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 FileOutputStream (java.io.FileOutputStream)1 InputStream (java.io.InputStream)1 Hashtable (java.util.Hashtable)1 CyclicBarrier (java.util.concurrent.CyclicBarrier)1 Node (javax.jcr.Node)1 InstallableResource (org.apache.sling.installer.api.InstallableResource)1 RegisteredResource (org.apache.sling.installer.api.tasks.RegisteredResource)1 TaskResource (org.apache.sling.installer.api.tasks.TaskResource)1 TransformationResult (org.apache.sling.installer.api.tasks.TransformationResult)1 Test (org.junit.Test)1