Search in sources :

Example 1 with Repository

use of org.apache.sling.ide.transport.Repository in project sling by apache.

the class JcrNode method changePrimaryType.

void changePrimaryType(String newPrimaryType) {
    Repository repository = ServerUtil.getDefaultRepository(getProject());
    NodeTypeRegistry ntManager = (repository == null) ? null : repository.getNodeTypeRegistry();
    if (ntManager == null) {
        MessageDialog.openWarning(null, "Unable to change primary type", "Unable to change primary type since project " + getProject().getName() + " is not associated with a server or the server is not started.");
        return;
    }
    try {
        if (!ntManager.isAllowedPrimaryChildNodeType(getParent().getPrimaryType(), newPrimaryType)) {
            if (!MessageDialog.openQuestion(null, "Unable to change primary type", "Parent (type '" + getParent().getPrimaryType() + "')" + " does not accept child with primary type '" + newPrimaryType + "'. Change anyway?")) {
                return;
            }
        }
    } catch (RepositoryException e1) {
        MessageDialog.openWarning(null, "Unable to change primary type", "Exception occured while trying to " + "verify node types: " + e1);
        return;
    }
    String thisNodeType = getPrimaryType();
    final SerializationKind currentSk = getSerializationKind(thisNodeType);
    final SerializationKind newSk = getSerializationKind(newPrimaryType);
    if (currentSk.equals(newSk)) {
        if (newSk != SerializationKind.FOLDER) {
            // easiest - we should just be able to change the type in the .content.xml
            properties.doSetPropertyValue("jcr:primaryType", newPrimaryType);
        } else {
            if (thisNodeType.equals("nt:folder")) {
                // switching away from an nt:folder might require creating a .content.xml
                createVaultFile((IFolder) resource, ".content.xml", newPrimaryType);
            } else if (newPrimaryType.equals("nt:folder")) {
                // 1)
                if (domElement != null) {
                    MessageDialog.openWarning(null, "Unable to change primaryType", "Unable to change jcr:primaryType to nt:folder" + " since the node is contained in a .content.xml");
                    return;
                }
                // verify 2)
                if (!verifyNodeTypeChange(ntManager, newPrimaryType)) {
                    return;
                }
                if (!(resource instanceof IFolder)) {
                    MessageDialog.openWarning(null, "Unable to change primaryType", "Unable to change jcr:primaryType to nt:folder" + " as there is no underlying folder");
                    return;
                }
                IFolder folder = (IFolder) resource;
                // 3) delete the .content.xml
                IFile contentXml = folder.getFile(".content.xml");
                if (contentXml.exists()) {
                    try {
                        contentXml.delete(true, new NullProgressMonitor());
                    } catch (CoreException e) {
                        Logger logger = Activator.getDefault().getPluginLogger();
                        logger.error("Could not delete " + contentXml.getFullPath() + ", e=" + e, e);
                        MessageDialog.openError(null, "Could not delete file", "Could not delete " + contentXml.getFullPath() + ", " + e);
                    }
                }
            } else {
                properties.doSetPropertyValue("jcr:primaryType", newPrimaryType);
            }
        }
        return;
    }
    if (newSk == SerializationKind.FOLDER) {
        // switching to a folder
        if (currentSk == SerializationKind.FILE) {
            MessageDialog.openWarning(null, "Unable to change primary type", "Changing from a file to a folder type is currently not supported");
            return;
        }
        if (newPrimaryType.equals("nt:folder")) {
            // verify
            if (!verifyNodeTypeChange(ntManager, newPrimaryType)) {
                return;
            }
        }
        try {
            // create the new directory structure pointing to 'this'
            IFolder newFolder = getParent().prepareCreateFolderChild(getJcrPathName());
            if (!newPrimaryType.equals("nt:folder")) {
                // move any children from the existing 'this' to a new vault file
                createVaultFileWithContent(newFolder, ".content.xml", newPrimaryType, domElement);
            }
            // remove myself
            if (domElement != null) {
                domElement.remove();
                if (underlying != null) {
                    underlying.save();
                }
            }
            // add a pointer in the corresponding .content.xml to point to this (folder) child
            getParent().createDomChild(getJcrPathName(), null);
            if (newPrimaryType.equals("nt:folder")) {
                // delete the .content.xml
                if (properties != null && properties.getUnderlying() != null) {
                    IFile contentXml = properties.getUnderlying().file;
                    if (contentXml != null && contentXml.exists()) {
                        contentXml.delete(true, new NullProgressMonitor());
                    }
                }
            }
            ServerUtil.triggerIncrementalBuild(newFolder, null);
            return;
        } catch (CoreException e) {
            MessageDialog.openWarning(null, "Unable to change primaryType", "Exception occurred: " + e);
            Logger logger = Activator.getDefault().getPluginLogger();
            logger.error("Exception occurred", e);
            return;
        }
    } else if (newSk == SerializationKind.FILE) {
        MessageDialog.openWarning(null, "Unable to change primary type", "Changing to/from a file is currently not supported");
        return;
    } else {
        // otherwise we're going from a folder to partial-or-full
        if (domElement == null && (resource instanceof IFolder)) {
            createVaultFile((IFolder) resource, ".content.xml", newPrimaryType);
        } else {
            // set the "pointer"'s jcr:primaryType
            if (domElement.getAttributeMap().containsKey("jcr:primaryType")) {
                domElement.setAttribute("jcr:primaryType", newPrimaryType);
            } else {
                domElement.addAttribute("jcr:primaryType", newPrimaryType);
            }
            // then copy all the other attributes - plus children if there are nay
            Element propDomElement = properties.getDomElement();
            if (propDomElement != null) {
                List<Attribute> attributes = propDomElement.getAttributes();
                for (Iterator<Attribute> it = attributes.iterator(); it.hasNext(); ) {
                    Attribute anAttribute = it.next();
                    if (anAttribute.getName().startsWith("xmlns:")) {
                        continue;
                    }
                    if (anAttribute.getName().equals("jcr:primaryType")) {
                        continue;
                    }
                    if (domElement.getAttributeMap().containsKey(anAttribute.getName())) {
                        domElement.setAttribute(anAttribute.getName(), anAttribute.getValue());
                    } else {
                        domElement.addAttribute(anAttribute);
                    }
                }
                List<Element> c2 = propDomElement.getChildren();
                if (c2 != null && c2.size() != 0) {
                    domElement.addNodes(c2);
                }
            }
            if (properties.getUnderlying() != null && properties.getUnderlying().file != null) {
                try {
                    properties.getUnderlying().file.delete(true, new NullProgressMonitor());
                    // prune empty directories:
                    prune(properties.getUnderlying().file.getParent());
                } catch (CoreException e) {
                    MessageDialog.openError(null, "Unable to change primary type", "Could not delete vault file " + properties.getUnderlying().file + ": " + e);
                    Activator.getDefault().getPluginLogger().error("Error changing jcr:primaryType. Could not delete vault file " + properties.getUnderlying().file + ": " + e.getMessage(), e);
                    return;
                }
            }
            underlying.save();
        }
    }
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IFile(org.eclipse.core.resources.IFile) Attribute(de.pdark.decentxml.Attribute) Element(de.pdark.decentxml.Element) RepositoryException(org.apache.sling.ide.transport.RepositoryException) Logger(org.apache.sling.ide.log.Logger) Repository(org.apache.sling.ide.transport.Repository) CoreException(org.eclipse.core.runtime.CoreException) SerializationKind(org.apache.sling.ide.serialization.SerializationKind) Iterator(java.util.Iterator) NodeTypeRegistry(org.apache.sling.ide.transport.NodeTypeRegistry) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) IFolder(org.eclipse.core.resources.IFolder)

Example 2 with Repository

use of org.apache.sling.ide.transport.Repository in project sling by apache.

the class JcrNode method validateDrop.

public IStatus validateDrop(int operation, TransferData transferType) {
    Repository repository = ServerUtil.getDefaultRepository(getProject());
    NodeTypeRegistry ntManager = (repository == null) ? null : repository.getNodeTypeRegistry();
    if (ntManager == null) {
        return new Status(IStatus.CANCEL, Activator.PLUGIN_ID, 1, "Cannot drop element here because corresponding server is not started! (Needed to determine node types)", null);
    }
    // let's support plain files first
    try {
        if (getPrimaryType().equals("nt:file")) {
            // hard-code the most prominent case: cannot drop onto a file
            return new Status(IStatus.CANCEL, Activator.PLUGIN_ID, 1, "Cannot drop element onto nt:file", null);
        }
        if (ntManager.isAllowedPrimaryChildNodeType(getPrimaryType(), "nt:file")) {
            return Status.OK_STATUS;
        } else {
            return Status.CANCEL_STATUS;
        }
    } catch (RepositoryException e) {
        Activator.getDefault().getPluginLogger().error("validateDrop: Got Exception while " + "verifying nodeType: " + e, e);
        return Status.CANCEL_STATUS;
    }
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) Repository(org.apache.sling.ide.transport.Repository) NodeTypeRegistry(org.apache.sling.ide.transport.NodeTypeRegistry) RepositoryException(org.apache.sling.ide.transport.RepositoryException)

Example 3 with Repository

use of org.apache.sling.ide.transport.Repository in project sling by apache.

the class JcrNode method pasteFromClipboard.

/**
     * Paste from the clipboard to this (container) node.
     * <p>
     * Copyright Note: The code of this method was ported from eclipse'
     * PasteAction, which due to visibility restrictions was not reusable.
     * <p>
     * @param clipboard
     */
public void pasteFromClipboard(Clipboard clipboard) {
    if (!canBePastedTo(clipboard)) {
        // should not occur due to 'canBePastedTo' check done by 
        // corresponding action - checking here nevertheless
        MessageDialog.openInformation(null, "Cannot paste", "No applicable node (type) for pasting found.");
        return;
    }
    Repository repository = ServerUtil.getDefaultRepository(getProject());
    NodeTypeRegistry ntManager = (repository == null) ? null : repository.getNodeTypeRegistry();
    if (ntManager == null) {
        MessageDialog.openWarning(null, "Cannot paste", "Cannot paste if corresponding server is not started");
        return;
    }
    // try the resource transfer
    IResource[] resourceData = (IResource[]) clipboard.getContents(ResourceTransfer.getInstance());
    if (resourceData != null && resourceData.length > 0) {
        if (resourceData[0].getType() == IResource.PROJECT) {
            // do not support project pasting onto a jcr node
            MessageDialog.openInformation(null, "Cannot paste project(s)", "Pasting of a project onto a (JCR) node is not possible");
            return;
        } else {
            CopyFilesAndFoldersOperation operation = new CopyFilesAndFoldersOperation(null);
            operation.copyResources(resourceData, getDropContainer());
        }
        return;
    }
    // try the file transfer
    String[] fileData = (String[]) clipboard.getContents(FileTransfer.getInstance());
    if (fileData != null) {
        CopyFilesAndFoldersOperation operation = new CopyFilesAndFoldersOperation(null);
        operation.copyFiles(fileData, getDropContainer());
        return;
    }
    // then try the text transfer
    String text = (String) clipboard.getContents(TextTransfer.getInstance());
    if ((text != null) && (this.domElement != null)) {
        try {
            Document document = TolerantXMLParser.parse(text, "pasted from clipboard");
            this.domElement.addNode(document.getRootElement());
            this.underlying.save();
        } catch (IOException e) {
            MessageDialog.openError(null, "Could not paste from clipboard", "Exception encountered while pasting from clipboard: " + e);
            Activator.getDefault().getPluginLogger().error("Error pasting from clipboard: " + e, e);
        }
    }
}
Also used : Repository(org.apache.sling.ide.transport.Repository) NodeTypeRegistry(org.apache.sling.ide.transport.NodeTypeRegistry) IOException(java.io.IOException) Document(de.pdark.decentxml.Document) CopyFilesAndFoldersOperation(org.eclipse.ui.actions.CopyFilesAndFoldersOperation) IResource(org.eclipse.core.resources.IResource)

Example 4 with Repository

use of org.apache.sling.ide.transport.Repository in project sling by apache.

the class JcrNode method canBePastedTo.

public boolean canBePastedTo(Clipboard clipboard) {
    Repository repository = ServerUtil.getDefaultRepository(getProject());
    NodeTypeRegistry ntManager = (repository == null) ? null : repository.getNodeTypeRegistry();
    IResource[] resourceData = (IResource[]) clipboard.getContents(ResourceTransfer.getInstance());
    if (resourceData != null) {
        IContainer container = getDropContainer();
        return container != null;
    }
    String[] fileData = (String[]) clipboard.getContents(FileTransfer.getInstance());
    if (fileData != null) {
        IContainer container = getDropContainer();
        return container != null;
    }
    String text = (String) clipboard.getContents(TextTransfer.getInstance());
    if (text != null) {
        return (domElement != null);
    }
    return false;
}
Also used : Repository(org.apache.sling.ide.transport.Repository) NodeTypeRegistry(org.apache.sling.ide.transport.NodeTypeRegistry) IContainer(org.eclipse.core.resources.IContainer) IResource(org.eclipse.core.resources.IResource)

Example 5 with Repository

use of org.apache.sling.ide.transport.Repository in project sling by apache.

the class SlingLaunchpadBehaviour method publishContentModule.

private void publishContentModule(int kind, int deltaKind, IModule[] module, IProgressMonitor monitor) throws CoreException, SerializationException, IOException {
    Logger logger = Activator.getDefault().getPluginLogger();
    Repository repository = ServerUtil.getConnectedRepository(getServer(), monitor);
    if (repository == null) {
        throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Unable to find a repository for server " + getServer()));
    }
    Batcher batcher = Activator.getDefault().getBatcherFactory().createBatcher();
    // TODO it would be more efficient to have a module -> filter mapping
    // it would be simpler to implement this in SlingContentModuleAdapter, but
    // the behaviour for resources being filtered out is deletion, and that
    // would be an incorrect ( or at least suprising ) behaviour at development time
    List<IModuleResource> addedOrUpdatedResources = new ArrayList<>();
    IModuleResource[] allResources = getResources(module);
    Set<IPath> handledPaths = new HashSet<>();
    switch(deltaKind) {
        case ServerBehaviourDelegate.CHANGED:
            for (IModuleResourceDelta resourceDelta : getPublishedResourceDelta(module)) {
                StringBuilder deltaTrace = new StringBuilder();
                deltaTrace.append("- processing delta kind ");
                switch(resourceDelta.getKind()) {
                    case IModuleResourceDelta.ADDED:
                        deltaTrace.append("ADDED ");
                        break;
                    case IModuleResourceDelta.CHANGED:
                        deltaTrace.append("CHANGED ");
                        break;
                    case IModuleResourceDelta.NO_CHANGE:
                        deltaTrace.append("NO_CHANGE ");
                        break;
                    case IModuleResourceDelta.REMOVED:
                        deltaTrace.append("REMOVED ");
                        break;
                    default:
                        deltaTrace.append("UNKNOWN - ").append(resourceDelta.getKind());
                }
                deltaTrace.append("for resource ").append(resourceDelta.getModuleResource());
                logger.trace(deltaTrace.toString());
                switch(resourceDelta.getKind()) {
                    case IModuleResourceDelta.ADDED:
                    case IModuleResourceDelta.CHANGED:
                    case // TODO is this needed?
                    IModuleResourceDelta.NO_CHANGE:
                        Command<?> command = addFileCommand(repository, resourceDelta.getModuleResource());
                        if (command != null) {
                            ensureParentIsPublished(resourceDelta.getModuleResource(), repository, allResources, handledPaths, batcher);
                            addedOrUpdatedResources.add(resourceDelta.getModuleResource());
                        }
                        enqueue(batcher, command);
                        break;
                    case IModuleResourceDelta.REMOVED:
                        enqueue(batcher, removeFileCommand(repository, resourceDelta.getModuleResource()));
                        break;
                }
            }
            break;
        case ServerBehaviourDelegate.ADDED:
        case // TODO is this correct ?
        ServerBehaviourDelegate.NO_CHANGE:
            for (IModuleResource resource : getResources(module)) {
                Command<?> command = addFileCommand(repository, resource);
                enqueue(batcher, command);
                if (command != null) {
                    addedOrUpdatedResources.add(resource);
                }
            }
            break;
        case ServerBehaviourDelegate.REMOVED:
            for (IModuleResource resource : getResources(module)) {
                enqueue(batcher, removeFileCommand(repository, resource));
            }
            break;
    }
    // reorder the child nodes at the end, when all create/update/deletes have been processed
    for (IModuleResource resource : addedOrUpdatedResources) {
        enqueue(batcher, reorderChildNodesCommand(repository, resource));
    }
    execute(batcher);
    // set state to published
    super.publishModule(kind, deltaKind, module, monitor);
    setModulePublishState(module, IServer.PUBLISH_STATE_NONE);
//        setServerPublishState(IServer.PUBLISH_STATE_NONE);
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) IModuleResource(org.eclipse.wst.server.core.model.IModuleResource) IPath(org.eclipse.core.runtime.IPath) ArrayList(java.util.ArrayList) IModuleResourceDelta(org.eclipse.wst.server.core.model.IModuleResourceDelta) Logger(org.apache.sling.ide.log.Logger) Repository(org.apache.sling.ide.transport.Repository) CoreException(org.eclipse.core.runtime.CoreException) Batcher(org.apache.sling.ide.transport.Batcher) HashSet(java.util.HashSet)

Aggregations

Repository (org.apache.sling.ide.transport.Repository)10 NodeTypeRegistry (org.apache.sling.ide.transport.NodeTypeRegistry)7 RepositoryException (org.apache.sling.ide.transport.RepositoryException)5 CoreException (org.eclipse.core.runtime.CoreException)3 IStatus (org.eclipse.core.runtime.IStatus)3 Status (org.eclipse.core.runtime.Status)3 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 Logger (org.apache.sling.ide.log.Logger)2 IResource (org.eclipse.core.resources.IResource)2 Attribute (de.pdark.decentxml.Attribute)1 Document (de.pdark.decentxml.Document)1 Element (de.pdark.decentxml.Element)1 URISyntaxException (java.net.URISyntaxException)1 HashSet (java.util.HashSet)1 Iterator (java.util.Iterator)1 LinkedList (java.util.LinkedList)1 List (java.util.List)1 NodeType (javax.jcr.nodetype.NodeType)1 EmbeddedArtifactLocator (org.apache.sling.ide.artifacts.EmbeddedArtifactLocator)1