Search in sources :

Example 1 with Logger

use of org.apache.sling.ide.log.Logger 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 Logger

use of org.apache.sling.ide.log.Logger in project sling by apache.

the class JcrNode method canCreateChild.

public boolean canCreateChild() {
    try {
        final IProject project = getProject();
        final Filter filter = ProjectUtil.loadFilter(project);
        final String relativeFilePath = getJcrPath();
        //            }
        if (filter == null) {
            Activator.getDefault().getPluginLogger().error("No filter.xml found for " + project);
            return true;
        } else {
            final FilterResult result = filter.filter(relativeFilePath);
            return result == FilterResult.ALLOW;
        }
    } catch (CoreException e) {
        Logger logger = Activator.getDefault().getPluginLogger();
        logger.error("Could not verify child node allowance: " + this, e);
        return false;
    }
}
Also used : CoreException(org.eclipse.core.runtime.CoreException) IActionFilter(org.eclipse.ui.IActionFilter) Filter(org.apache.sling.ide.filter.Filter) FilterResult(org.apache.sling.ide.filter.FilterResult) Logger(org.apache.sling.ide.log.Logger) IProject(org.eclipse.core.resources.IProject)

Example 3 with Logger

use of org.apache.sling.ide.log.Logger in project sling by apache.

the class IgnoreMissingGrammarXmlValidator method doValidate.

/** Call the original private method named validate with the same parameters from {@link AbstractNestedValidator} through reflection.
     * 
     * @param file
     * @param inputstream
     * @param result
     * @param reporter
     * @param context */
private void doValidate(IFile file, InputStream inputstream, ValidationResult result, IReporter reporter, NestedValidatorContext context) {
    try {
        Method method = AbstractNestedValidator.class.getDeclaredMethod("validate", IFile.class, InputStream.class, ValidationResult.class, IReporter.class, NestedValidatorContext.class);
        method.setAccessible(true);
        method.invoke(this, file, inputstream, result, reporter, context);
    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
        Logger logger = Activator.getDefault().getPluginLogger();
        logger.error("Failed calling validate method on AbstractNestedValidator, probably WTP version is incompatible.", e);
    }
}
Also used : Method(java.lang.reflect.Method) Logger(org.apache.sling.ide.log.Logger) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 4 with Logger

use of org.apache.sling.ide.log.Logger in project sling by apache.

the class ServiceComponentHeaderValidator method findMissingScrDescriptors.

/**
     * Finds missing SCR descriptor files referenced in the manifest
     * 
     * <p>
     * Only acts if the Manifest is located under the project's output directory at
     * </p>
     * 
     * @param manifest the location of the manifest to parse for the Service-Component header
     * @return a list of missing files, empty if no problems are found
     * @throws CoreException any errors
     */
public List<IFile> findMissingScrDescriptors(IFile manifest) throws CoreException {
    IProject project = manifest.getProject();
    Logger pluginLogger = Activator.getDefault().getPluginLogger();
    IJavaProject javaProject = ProjectHelper.asJavaProject(project);
    IFolder outputFolder = (IFolder) project.getWorkspace().getRoot().findMember(javaProject.getOutputLocation());
    if (!outputFolder.getFullPath().isPrefixOf(manifest.getFullPath())) {
        pluginLogger.trace("Ignoring manifest found at {0} since it is not under the output directory at {1}", manifest.getFullPath(), outputFolder.getFullPath());
        return Collections.emptyList();
    }
    List<IFile> missingDescriptors = new ArrayList<>();
    try (InputStream contents = manifest.getContents()) {
        Manifest mf = new Manifest(contents);
        String serviceComponentHeader = mf.getMainAttributes().getValue("Service-Component");
        if (serviceComponentHeader != null) {
            String[] entries = serviceComponentHeader.split(",");
            for (String entry : entries) {
                entry = entry.trim();
                if (entry.contains("*")) {
                    pluginLogger.trace("Ignoring wildcard Service-Component entry {0}", entry);
                    continue;
                }
                IFile descriptor = outputFolder.getFile(entry);
                if (descriptor.exists()) {
                    pluginLogger.trace("Found matching resource for Service-Component entry {0}", entry);
                    continue;
                }
                missingDescriptors.add(descriptor);
                pluginLogger.trace("Raising error for missing DS descriptor entry {0}", entry);
            }
        }
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Unable to access " + manifest.getFullPath(), e));
    }
    return missingDescriptors;
}
Also used : Status(org.eclipse.core.runtime.Status) IStatus(org.eclipse.core.runtime.IStatus) IFile(org.eclipse.core.resources.IFile) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Logger(org.apache.sling.ide.log.Logger) Manifest(java.util.jar.Manifest) IProject(org.eclipse.core.resources.IProject) IJavaProject(org.eclipse.jdt.core.IJavaProject) CoreException(org.eclipse.core.runtime.CoreException) IFolder(org.eclipse.core.resources.IFolder)

Example 5 with Logger

use of org.apache.sling.ide.log.Logger in project sling by apache.

the class ResourceChangeCommandFactory method findSerializationDataFromCoveringParent.

/**
     * Tries to find serialization data from a resource in a covering parent
     * 
     * <p>
     * If the serialization resource is null, it's valid to look for a serialization resource higher in the filesystem,
     * given that the found serialization resource covers this resource
     * 
     * @param changedResource the resource which has changed
     * @param syncDirectory the content sync directory for the resource's project
     * @param resourceLocation the resource location relative to the sync directory
     * @param serializationFilePath the location
     * @return a <tt>ResourceProxy</tt> if there is a covering parent, or null is there is not
     * @throws CoreException
     * @throws IOException
     */
private ResourceProxy findSerializationDataFromCoveringParent(IResource changedResource, IFolder syncDirectory, String resourceLocation, IPath serializationFilePath) throws CoreException, IOException {
    // TODO - this too should be abstracted in the service layer, rather than in the Eclipse-specific code
    Logger logger = Activator.getDefault().getPluginLogger();
    logger.trace("Found plain nt:folder candidate at {0}, trying to find a covering resource for it", changedResource.getProjectRelativePath());
    // don't use isRoot() to prevent infinite loop when the final path is '//'
    while (serializationFilePath.segmentCount() != 0) {
        serializationFilePath = serializationFilePath.removeLastSegments(1);
        IFolder folderWithPossibleSerializationFile = syncDirectory.getFolder(serializationFilePath);
        if (folderWithPossibleSerializationFile == null) {
            logger.trace("No folder found at {0}, moving up to the next level", serializationFilePath);
            continue;
        }
        // it's safe to use a specific SerializationKind since this scenario is only valid for METADATA_PARTIAL
        // coverage
        String possibleSerializationFilePath = serializationManager.getSerializationFilePath(((IFolder) folderWithPossibleSerializationFile).getLocation().toOSString(), SerializationKind.METADATA_PARTIAL);
        logger.trace("Looking for serialization data in {0}", possibleSerializationFilePath);
        if (serializationManager.isSerializationFile(possibleSerializationFilePath)) {
            IPath parentSerializationFilePath = Path.fromOSString(possibleSerializationFilePath).makeRelativeTo(syncDirectory.getLocation());
            IFile possibleSerializationFile = syncDirectory.getFile(parentSerializationFilePath);
            if (!possibleSerializationFile.exists()) {
                logger.trace("Potential serialization data file {0} does not exist, moving up to the next level", possibleSerializationFile.getFullPath());
                continue;
            }
            ResourceProxy serializationData;
            try (InputStream contents = possibleSerializationFile.getContents()) {
                serializationData = serializationManager.readSerializationData(parentSerializationFilePath.toPortableString(), contents);
            }
            String repositoryPath = serializationManager.getRepositoryPath(resourceLocation);
            String potentialPath = serializationData.getPath();
            boolean covered = serializationData.covers(repositoryPath);
            logger.trace("Found possible serialization data at {0}. Resource :{1} ; our resource: {2}. Covered: {3}", parentSerializationFilePath, potentialPath, repositoryPath, covered);
            // another resource
            if (covered) {
                return serializationData.getChild(repositoryPath);
            }
            break;
        }
    }
    return null;
}
Also used : IFile(org.eclipse.core.resources.IFile) IPath(org.eclipse.core.runtime.IPath) InputStream(java.io.InputStream) Logger(org.apache.sling.ide.log.Logger) ResourceProxy(org.apache.sling.ide.transport.ResourceProxy) IFolder(org.eclipse.core.resources.IFolder)

Aggregations

Logger (org.apache.sling.ide.log.Logger)11 CoreException (org.eclipse.core.runtime.CoreException)5 ArrayList (java.util.ArrayList)3 IFile (org.eclipse.core.resources.IFile)3 IFolder (org.eclipse.core.resources.IFolder)3 IPath (org.eclipse.core.runtime.IPath)3 IStatus (org.eclipse.core.runtime.IStatus)3 Status (org.eclipse.core.runtime.Status)3 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 Repository (org.apache.sling.ide.transport.Repository)2 IProject (org.eclipse.core.resources.IProject)2 IModuleResource (org.eclipse.wst.server.core.model.IModuleResource)2 Attribute (de.pdark.decentxml.Attribute)1 Element (de.pdark.decentxml.Element)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 HashSet (java.util.HashSet)1 Hashtable (java.util.Hashtable)1 Iterator (java.util.Iterator)1