Search in sources :

Example 46 with NodeTypeManager

use of javax.jcr.nodetype.NodeTypeManager in project jackrabbit-oak by apache.

the class RepositoryUpgrade method copy.

/**
     * Copies the full content from the source to the target repository.
     * <p>
     * The source repository <strong>must not be modified</strong> while
     * the copy operation is running to avoid an inconsistent copy.
     * <p>
     * Note that both the source and the target repository must be closed
     * during the copy operation as this method requires exclusive access
     * to the repositories.
     *
     * @param initializer optional extra repository initializer to use
     * @throws RepositoryException if the copy operation fails
     */
public void copy(RepositoryInitializer initializer) throws RepositoryException {
    if (checkLongNames) {
        assertNoLongNames();
    }
    RepositoryConfig config = source.getRepositoryConfig();
    logger.info("Copying repository content from {} to Oak", config.getHomeDir());
    try {
        NodeBuilder targetBuilder = target.getRoot().builder();
        if (VersionHistoryUtil.getVersionStorage(targetBuilder).exists() && !versionCopyConfiguration.skipOrphanedVersionsCopy()) {
            logger.warn("The version storage on destination already exists. Orphaned version histories will be skipped.");
            versionCopyConfiguration.setCopyOrphanedVersions(null);
        }
        final Root upgradeRoot = new UpgradeRoot(targetBuilder);
        String workspaceName = source.getRepositoryConfig().getDefaultWorkspaceName();
        SecurityProviderImpl security = new SecurityProviderImpl(mapSecurityConfig(config.getSecurityConfig()));
        if (skipInitialization) {
            logger.info("Skipping the repository initialization");
        } else {
            // init target repository first
            logger.info("Initializing initial repository content from {}", config.getHomeDir());
            new InitialContent().initialize(targetBuilder);
            if (initializer != null) {
                initializer.initialize(targetBuilder);
            }
            logger.debug("InitialContent completed from {}", config.getHomeDir());
            for (SecurityConfiguration sc : security.getConfigurations()) {
                RepositoryInitializer ri = sc.getRepositoryInitializer();
                ri.initialize(targetBuilder);
                logger.debug("Repository initializer '" + ri.getClass().getName() + "' completed", config.getHomeDir());
            }
            for (SecurityConfiguration sc : security.getConfigurations()) {
                WorkspaceInitializer wi = sc.getWorkspaceInitializer();
                wi.initialize(targetBuilder, workspaceName);
                logger.debug("Workspace initializer '" + wi.getClass().getName() + "' completed", config.getHomeDir());
            }
        }
        HashBiMap<String, String> uriToPrefix = HashBiMap.create();
        logger.info("Copying registered namespaces");
        copyNamespaces(targetBuilder, uriToPrefix);
        logger.debug("Namespace registration completed.");
        if (skipInitialization) {
            logger.info("Skipping registering node types and privileges");
        } else {
            logger.info("Copying registered node types");
            NodeTypeManager ntMgr = new ReadWriteNodeTypeManager() {

                @Override
                protected Tree getTypes() {
                    return upgradeRoot.getTree(NODE_TYPES_PATH);
                }

                @Nonnull
                @Override
                protected Root getWriteRoot() {
                    return upgradeRoot;
                }
            };
            copyNodeTypes(ntMgr, new ValueFactoryImpl(upgradeRoot, NamePathMapper.DEFAULT));
            logger.debug("Node type registration completed.");
            // migrate privileges
            logger.info("Copying registered privileges");
            PrivilegeConfiguration privilegeConfiguration = security.getConfiguration(PrivilegeConfiguration.class);
            copyCustomPrivileges(privilegeConfiguration.getPrivilegeManager(upgradeRoot, NamePathMapper.DEFAULT));
            logger.debug("Privilege registration completed.");
            // Triggers compilation of type information, which we need for
            // the type predicates used by the bulk  copy operations below.
            new TypeEditorProvider(false).getRootEditor(targetBuilder.getBaseState(), targetBuilder.getNodeState(), targetBuilder, null);
        }
        final NodeState reportingSourceRoot = ReportingNodeState.wrap(JackrabbitNodeState.createRootNodeState(source, workspaceName, targetBuilder.getNodeState(), uriToPrefix, copyBinariesByReference, skipOnError), new LoggingReporter(logger, "Migrating", LOG_NODE_COPY, -1));
        final NodeState sourceRoot;
        if (filterLongNames) {
            sourceRoot = NameFilteringNodeState.wrap(reportingSourceRoot);
        } else {
            sourceRoot = reportingSourceRoot;
        }
        final Stopwatch watch = Stopwatch.createStarted();
        logger.info("Copying workspace content");
        copyWorkspace(sourceRoot, targetBuilder, workspaceName);
        // on TarMK this does call triggers the actual copy
        targetBuilder.getNodeState();
        logger.info("Upgrading workspace content completed in {}s ({})", watch.elapsed(TimeUnit.SECONDS), watch);
        if (!versionCopyConfiguration.skipOrphanedVersionsCopy()) {
            logger.info("Copying version storage");
            watch.reset().start();
            copyVersionStorage(targetBuilder, getVersionStorage(sourceRoot), getVersionStorage(targetBuilder), versionCopyConfiguration);
            // on TarMK this does call triggers the actual copy
            targetBuilder.getNodeState();
            logger.info("Version storage copied in {}s ({})", watch.elapsed(TimeUnit.SECONDS), watch);
        } else {
            logger.info("Skipping the version storage as the copyOrphanedVersions is set to false");
        }
        watch.reset().start();
        logger.info("Applying default commit hooks");
        // TODO: default hooks?
        List<CommitHook> hooks = newArrayList();
        UserConfiguration userConf = security.getConfiguration(UserConfiguration.class);
        String groupsPath = userConf.getParameters().getConfigValue(UserConstants.PARAM_GROUP_PATH, UserConstants.DEFAULT_GROUP_PATH);
        String usersPath = userConf.getParameters().getConfigValue(UserConstants.PARAM_USER_PATH, UserConstants.DEFAULT_USER_PATH);
        // hooks specific to the upgrade, need to run first
        hooks.add(new EditorHook(new CompositeEditorProvider(new RestrictionEditorProvider(), new GroupEditorProvider(groupsPath), // copy referenced version histories
        new VersionableEditor.Provider(sourceRoot, workspaceName, versionCopyConfiguration), new SameNameSiblingsEditor.Provider(), AuthorizableFolderEditor.provider(groupsPath, usersPath))));
        // this editor works on the VersionableEditor output, so it can't be
        // a part of the same EditorHook
        hooks.add(new EditorHook(new VersionablePropertiesEditor.Provider()));
        // security-related hooks
        for (SecurityConfiguration sc : security.getConfigurations()) {
            hooks.addAll(sc.getCommitHooks(workspaceName));
        }
        if (customCommitHooks != null) {
            hooks.addAll(customCommitHooks);
        }
        // type validation, reference and indexing hooks
        hooks.add(new EditorHook(new CompositeEditorProvider(createTypeEditorProvider(), createIndexEditorProvider())));
        target.merge(targetBuilder, new LoggingCompositeHook(hooks, source, overrideEarlyShutdown()), CommitInfo.EMPTY);
        logger.info("Processing commit hooks completed in {}s ({})", watch.elapsed(TimeUnit.SECONDS), watch);
        logger.debug("Repository upgrade completed.");
    } catch (Exception e) {
        throw new RepositoryException("Failed to copy content", e);
    }
}
Also used : NodeTypeManager(javax.jcr.nodetype.NodeTypeManager) ReadWriteNodeTypeManager(org.apache.jackrabbit.oak.plugins.nodetype.write.ReadWriteNodeTypeManager) NameFilteringNodeState(org.apache.jackrabbit.oak.upgrade.nodestate.NameFilteringNodeState) ReportingNodeState(org.apache.jackrabbit.oak.upgrade.nodestate.report.ReportingNodeState) NodeState(org.apache.jackrabbit.oak.spi.state.NodeState) ValueFactoryImpl(org.apache.jackrabbit.oak.plugins.value.jcr.ValueFactoryImpl) Stopwatch(com.google.common.base.Stopwatch) LoggingReporter(org.apache.jackrabbit.oak.upgrade.nodestate.report.LoggingReporter) NodeBuilder(org.apache.jackrabbit.oak.spi.state.NodeBuilder) EditorHook(org.apache.jackrabbit.oak.spi.commit.EditorHook) VersionableEditor(org.apache.jackrabbit.oak.upgrade.version.VersionableEditor) SecurityProviderImpl(org.apache.jackrabbit.oak.security.SecurityProviderImpl) PrivilegeConfiguration(org.apache.jackrabbit.oak.spi.security.privilege.PrivilegeConfiguration) UserConfiguration(org.apache.jackrabbit.oak.spi.security.user.UserConfiguration) RepositoryConfig(org.apache.jackrabbit.core.config.RepositoryConfig) ReadWriteNodeTypeManager(org.apache.jackrabbit.oak.plugins.nodetype.write.ReadWriteNodeTypeManager) CompositeEditorProvider(org.apache.jackrabbit.oak.spi.commit.CompositeEditorProvider) RestrictionEditorProvider(org.apache.jackrabbit.oak.upgrade.security.RestrictionEditorProvider) Root(org.apache.jackrabbit.oak.api.Root) CommitHook(org.apache.jackrabbit.oak.spi.commit.CommitHook) RepositoryException(javax.jcr.RepositoryException) FileSystemException(org.apache.jackrabbit.core.fs.FileSystemException) IOException(java.io.IOException) CommitFailedException(org.apache.jackrabbit.oak.api.CommitFailedException) RepositoryException(javax.jcr.RepositoryException) NamespaceException(javax.jcr.NamespaceException) PropertyIndexEditorProvider(org.apache.jackrabbit.oak.plugins.index.property.PropertyIndexEditorProvider) EditorProvider(org.apache.jackrabbit.oak.spi.commit.EditorProvider) IndexEditorProvider(org.apache.jackrabbit.oak.plugins.index.IndexEditorProvider) CompositeEditorProvider(org.apache.jackrabbit.oak.spi.commit.CompositeEditorProvider) RestrictionEditorProvider(org.apache.jackrabbit.oak.upgrade.security.RestrictionEditorProvider) GroupEditorProvider(org.apache.jackrabbit.oak.upgrade.security.GroupEditorProvider) ReferenceEditorProvider(org.apache.jackrabbit.oak.plugins.index.reference.ReferenceEditorProvider) TypeEditorProvider(org.apache.jackrabbit.oak.plugins.nodetype.TypeEditorProvider) CompositeIndexEditorProvider(org.apache.jackrabbit.oak.plugins.index.CompositeIndexEditorProvider) InitialContent(org.apache.jackrabbit.oak.InitialContent) WorkspaceInitializer(org.apache.jackrabbit.oak.spi.lifecycle.WorkspaceInitializer) TypeEditorProvider(org.apache.jackrabbit.oak.plugins.nodetype.TypeEditorProvider) GroupEditorProvider(org.apache.jackrabbit.oak.upgrade.security.GroupEditorProvider) SecurityConfiguration(org.apache.jackrabbit.oak.spi.security.SecurityConfiguration) RepositoryInitializer(org.apache.jackrabbit.oak.spi.lifecycle.RepositoryInitializer)

Example 47 with NodeTypeManager

use of javax.jcr.nodetype.NodeTypeManager in project jackrabbit-oak by apache.

the class CompatibilityIssuesTest method testBinaryCoercion.

@Test
public void testBinaryCoercion() throws RepositoryException, IOException {
    Session session = getAdminSession();
    // node type with default child-node type of to nt:base
    String ntName = "binaryCoercionTest";
    NodeTypeManager ntm = session.getWorkspace().getNodeTypeManager();
    NodeTypeTemplate ntt = ntm.createNodeTypeTemplate();
    ntt.setName(ntName);
    PropertyDefinitionTemplate propertyWithType = ntm.createPropertyDefinitionTemplate();
    propertyWithType.setName("javaObject");
    propertyWithType.setRequiredType(PropertyType.STRING);
    PropertyDefinitionTemplate unnamed = ntm.createPropertyDefinitionTemplate();
    unnamed.setName("*");
    unnamed.setRequiredType(PropertyType.UNDEFINED);
    List<PropertyDefinition> properties = ntt.getPropertyDefinitionTemplates();
    properties.add(propertyWithType);
    properties.add(unnamed);
    ntm.registerNodeType(ntt, false);
    Node node = session.getRootNode().addNode("testNodeForBinary", ntName);
    ByteArrayOutputStream bos = serializeObject("testValue");
    node.setProperty("javaObject", session.getValueFactory().createBinary(new ByteArrayInputStream(bos.toByteArray())));
    Assert.assertTrue(IOUtils.contentEquals(new ByteArrayInputStream(bos.toByteArray()), node.getProperty("javaObject").getStream()));
}
Also used : NodeTypeManager(javax.jcr.nodetype.NodeTypeManager) NodeTypeTemplate(javax.jcr.nodetype.NodeTypeTemplate) PropertyDefinitionTemplate(javax.jcr.nodetype.PropertyDefinitionTemplate) ByteArrayInputStream(java.io.ByteArrayInputStream) Node(javax.jcr.Node) ByteArrayOutputStream(java.io.ByteArrayOutputStream) PropertyDefinition(javax.jcr.nodetype.PropertyDefinition) Session(javax.jcr.Session) Test(org.junit.Test)

Example 48 with NodeTypeManager

use of javax.jcr.nodetype.NodeTypeManager in project sling by apache.

the class NodeTypeConfigurationPrinter method printConfiguration.

/**
     * {@inheritDoc}
     */
public void printConfiguration(PrintWriter pw, String mode) {
    if (slingRepository != null) {
        Session session = null;
        try {
            session = slingRepository.loginAdministrative(null);
            NodeTypeManager ntm = session.getWorkspace().getNodeTypeManager();
            NodeTypeIterator it = ntm.getAllNodeTypes();
            List<NodeType> sortedTypes = sortTypes(it);
            for (NodeType nt : sortedTypes) {
                pw.printf("[%s]", nt.getName());
                printSuperTypes(pw, nt);
                if (nt.hasOrderableChildNodes()) {
                    pw.print(" orderable");
                }
                if (nt.isMixin()) {
                    pw.print(" mixin");
                }
                linebreak(pw, mode);
                for (PropertyDefinition prop : nt.getPropertyDefinitions()) {
                    if (prop.getDeclaringNodeType() == nt) {
                        startBold(pw, mode);
                    }
                    pw.printf("- %s", prop.getName());
                    printDefaultValues(pw, prop);
                    if (prop.getName().equals(nt.getPrimaryItemName())) {
                        pw.print(" primary");
                    }
                    if (prop.isMandatory()) {
                        pw.print(" mandatory");
                    }
                    if (prop.isAutoCreated()) {
                        pw.print(" autocreated");
                    }
                    if (prop.isProtected()) {
                        pw.print(" protected");
                    }
                    if (prop.isMultiple()) {
                        pw.print(" multiple");
                    }
                    pw.printf(" %s", OnParentVersionAction.nameFromValue(prop.getOnParentVersion()));
                    printConstraints(pw, prop);
                    if (prop.getDeclaringNodeType() == nt) {
                        stopBold(pw, mode);
                    }
                    linebreak(pw, mode);
                }
                for (NodeDefinition child : nt.getChildNodeDefinitions()) {
                    if (child.getDeclaringNodeType() == nt) {
                        startBold(pw, mode);
                    }
                    pw.printf("+ %s", child.getName());
                    printRequiredChildTypes(pw, child);
                    if (child.getDefaultPrimaryType() != null) {
                        pw.printf(" = %s", child.getDefaultPrimaryType().getName());
                    }
                    if (child.isMandatory()) {
                        pw.print(" mandatory");
                    }
                    if (child.isAutoCreated()) {
                        pw.print(" autocreated");
                    }
                    if (child.isProtected()) {
                        pw.print(" protected");
                    }
                    if (child.allowsSameNameSiblings()) {
                        pw.print(" multiple");
                    }
                    pw.printf(" %s", OnParentVersionAction.nameFromValue(child.getOnParentVersion()));
                    if (child.getDeclaringNodeType() == nt) {
                        stopBold(pw, mode);
                    }
                    linebreak(pw, mode);
                }
                linebreak(pw, mode);
            }
        } catch (RepositoryException e) {
            pw.println("Unable to output namespace mappings.");
            e.printStackTrace(pw);
        } finally {
            if (session != null) {
                session.logout();
            }
        }
    } else {
        pw.println("SlingRepository is not available.");
    }
}
Also used : NodeTypeManager(javax.jcr.nodetype.NodeTypeManager) NodeType(javax.jcr.nodetype.NodeType) NodeDefinition(javax.jcr.nodetype.NodeDefinition) NodeTypeIterator(javax.jcr.nodetype.NodeTypeIterator) RepositoryException(javax.jcr.RepositoryException) PropertyDefinition(javax.jcr.nodetype.PropertyDefinition) Session(javax.jcr.Session)

Example 49 with NodeTypeManager

use of javax.jcr.nodetype.NodeTypeManager in project sling by apache.

the class NodeTypeDefinitionScanner method registerNodeTypes.

/**
     * Registers node types found in classpath in JCR repository.
     * @param session Session
     * @param nodeTypeResources List of classpath resource URLs pointing to node type definitions
     */
private void registerNodeTypes(Session session, List<String> nodeTypeResources) throws RepositoryException {
    ClassLoader classLoader = getClass().getClassLoader();
    Workspace workspace = session.getWorkspace();
    NodeTypeManager nodeTypeManager = workspace.getNodeTypeManager();
    NamespaceRegistry namespaceRegistry = workspace.getNamespaceRegistry();
    ValueFactory valueFactory = session.getValueFactory();
    // try registering node types multiple times because the exact order is not known
    int iteration = 0;
    List<String> remainingNodeTypeResources = new ArrayList<String>(nodeTypeResources);
    while (!remainingNodeTypeResources.isEmpty()) {
        registerNodeTypesAndRemoveSucceeds(remainingNodeTypeResources, classLoader, nodeTypeManager, namespaceRegistry, valueFactory, false);
        iteration++;
        if (iteration >= MAX_ITERATIONS) {
            break;
        }
    }
    if (!remainingNodeTypeResources.isEmpty()) {
        registerNodeTypesAndRemoveSucceeds(remainingNodeTypeResources, classLoader, nodeTypeManager, namespaceRegistry, valueFactory, true);
    }
}
Also used : NodeTypeManager(javax.jcr.nodetype.NodeTypeManager) NamespaceRegistry(javax.jcr.NamespaceRegistry) ArrayList(java.util.ArrayList) ValueFactory(javax.jcr.ValueFactory) Workspace(javax.jcr.Workspace)

Example 50 with NodeTypeManager

use of javax.jcr.nodetype.NodeTypeManager in project jackrabbit by apache.

the class GQL method resolveChildNodeName.

/**
     * Resolves the given node name. If the name has a prefix then the name
     * is returned immediately as is. Otherwise the node type manager is
     * searched for a node definition that defines a named child node with
     * a local name that matches the provided <code>name</code>. If such a match
     * is found the name of the node definition is returned.
     *
     * @param name the name of a node (optionally without a prefix).
     * @return the resolved node name.
     * @throws RepositoryException if an error occurs while reading from the
     *                             node type manager.
     */
private String resolveChildNodeName(String name) throws RepositoryException {
    if (isPrefixed(name)) {
        return name;
    }
    if (childNodeNames == null) {
        childNodeNames = new HashMap<String, String>();
        NodeTypeManager ntMgr = session.getWorkspace().getNodeTypeManager();
        NodeTypeIterator it = ntMgr.getAllNodeTypes();
        while (it.hasNext()) {
            NodeType nt = it.nextNodeType();
            NodeDefinition[] defs = nt.getDeclaredChildNodeDefinitions();
            for (NodeDefinition def : defs) {
                String cnn = def.getName();
                if (!cnn.equals("*")) {
                    String localName = cnn;
                    int idx = cnn.indexOf(':');
                    if (idx != -1) {
                        localName = cnn.substring(idx + 1);
                    }
                    childNodeNames.put(localName, cnn);
                }
            }
        }
    }
    String cnn = childNodeNames.get(name);
    if (cnn != null) {
        return cnn;
    } else {
        return name;
    }
}
Also used : NodeTypeManager(javax.jcr.nodetype.NodeTypeManager) NodeType(javax.jcr.nodetype.NodeType) NodeDefinition(javax.jcr.nodetype.NodeDefinition) NodeTypeIterator(javax.jcr.nodetype.NodeTypeIterator)

Aggregations

NodeTypeManager (javax.jcr.nodetype.NodeTypeManager)93 NodeType (javax.jcr.nodetype.NodeType)41 Node (javax.jcr.Node)32 Session (javax.jcr.Session)30 NodeTypeTemplate (javax.jcr.nodetype.NodeTypeTemplate)29 NodeTypeIterator (javax.jcr.nodetype.NodeTypeIterator)27 Test (org.junit.Test)24 ConstraintViolationException (javax.jcr.nodetype.ConstraintViolationException)14 PropertyDefinition (javax.jcr.nodetype.PropertyDefinition)14 RepositoryException (javax.jcr.RepositoryException)13 ByteArrayInputStream (java.io.ByteArrayInputStream)12 NotExecutableException (org.apache.jackrabbit.test.NotExecutableException)11 ArrayList (java.util.ArrayList)8 Workspace (javax.jcr.Workspace)8 NoSuchNodeTypeException (javax.jcr.nodetype.NoSuchNodeTypeException)8 NodeDefinition (javax.jcr.nodetype.NodeDefinition)8 PropertyDefinitionTemplate (javax.jcr.nodetype.PropertyDefinitionTemplate)8 NodeDefinitionTemplate (javax.jcr.nodetype.NodeDefinitionTemplate)7 AbstractRepositoryTest (org.apache.jackrabbit.oak.jcr.AbstractRepositoryTest)7 InputStream (java.io.InputStream)6