Search in sources :

Example 21 with NodeTypeManager

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

the class NodeTypeUtils method createNodeType.

/**
 * Creates a node type with the given properties.
 *
 * @param session the session
 * @param name the name
 * @param properties the properties
 * @param superTypes the super types
 * @param childrenTypes the children types
 * @param baseType the base type
 * @param isMixin the is mixin
 * @return the string
 * @throws RepositoryException the repository exception
 */
@SuppressWarnings("unchecked")
public static String createNodeType(Session session, String name, String[] properties, int[] propTypes, String[] superTypes, String[] childrenTypes, String baseType, boolean isMixin) throws RepositoryException {
    NodeTypeManager ntm = session.getWorkspace().getNodeTypeManager();
    NodeTypeTemplate ntt = ntm.createNodeTypeTemplate();
    if (baseType != null) {
        NodeTypeDefinition ntd = ntm.getNodeType(baseType);
        ntt = ntm.createNodeTypeTemplate(ntd);
    }
    if ((superTypes != null) && (superTypes.length != 0)) {
        ntt.setDeclaredSuperTypeNames(superTypes);
    }
    ntt.setOrderableChildNodes(false);
    ntt.setName(name);
    if (properties != null) {
        for (int count = 0; count < properties.length; count++) {
            ntt.getPropertyDefinitionTemplates().add(createPropertyDefTemplate(ntm, properties[count], propTypes[count]));
        }
    }
    if (childrenTypes != null) {
        ntt.getNodeDefinitionTemplates().add(createNodeDefTemplate(ntm, childrenTypes));
    }
    ntt.setMixin(isMixin);
    ntm.registerNodeType(ntt, true);
    return ntt.getName();
}
Also used : NodeTypeManager(javax.jcr.nodetype.NodeTypeManager) NodeTypeTemplate(javax.jcr.nodetype.NodeTypeTemplate) NodeTypeDefinition(javax.jcr.nodetype.NodeTypeDefinition)

Example 22 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();
        SecurityProvider security = SecurityProviderBuilder.newBuilder().with(mapSecurityConfig(config.getSecurityConfig())).build();
        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.wrapRoot(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);
        removeVersions();
        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.plugins.migration.report.ReportingNodeState) FilteringNodeState(org.apache.jackrabbit.oak.plugins.migration.FilteringNodeState) 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.plugins.migration.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) 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) SecurityProvider(org.apache.jackrabbit.oak.spi.security.SecurityProvider) 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) SecurityProvider(org.apache.jackrabbit.oak.spi.security.SecurityProvider) SecurityConfiguration(org.apache.jackrabbit.oak.spi.security.SecurityConfiguration) RepositoryInitializer(org.apache.jackrabbit.oak.spi.lifecycle.RepositoryInitializer)

Example 23 with NodeTypeManager

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

the class GQL method collectNodeTypes.

/**
 * Resolves and collects all node types that match <code>ntName</code>.
 *
 * @param ntName the name of a node type (optionally without prefix).
 * @throws RepositoryException if an error occurs while reading from the
 *                             node type manager.
 */
private void collectNodeTypes(String ntName) throws RepositoryException {
    NodeTypeManager ntMgr = session.getWorkspace().getNodeTypeManager();
    String[] resolvedNames = resolveNodeTypeName(ntName);
    // now resolve node type hierarchy
    for (String resolvedName : resolvedNames) {
        try {
            NodeType base = ntMgr.getNodeType(resolvedName);
            if (base.isMixin()) {
                // search for nodes where jcr:mixinTypes is set to this mixin
                addTypeConstraint(new MixinComparision(resolvedName));
            } else {
                // search for nodes where jcr:primaryType is set to this type
                addTypeConstraint(new PrimaryTypeComparision(resolvedName));
            }
            // now search for all node types that are derived from base
            NodeTypeIterator allTypes = ntMgr.getAllNodeTypes();
            while (allTypes.hasNext()) {
                NodeType nt = allTypes.nextNodeType();
                NodeType[] superTypes = nt.getSupertypes();
                if (Arrays.asList(superTypes).contains(base)) {
                    if (nt.isMixin()) {
                        addTypeConstraint(new MixinComparision(nt.getName()));
                    } else {
                        addTypeConstraint(new PrimaryTypeComparision(nt.getName()));
                    }
                }
            }
        } catch (NoSuchNodeTypeException e) {
            // add anyway -> will not match anything
            addTypeConstraint(new PrimaryTypeComparision(resolvedName));
        }
    }
}
Also used : NodeTypeManager(javax.jcr.nodetype.NodeTypeManager) NodeType(javax.jcr.nodetype.NodeType) NodeTypeIterator(javax.jcr.nodetype.NodeTypeIterator) NoSuchNodeTypeException(javax.jcr.nodetype.NoSuchNodeTypeException)

Example 24 with NodeTypeManager

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

the class GQL method resolvePropertyName.

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

Example 25 with NodeTypeManager

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

the class GQL method resolveNodeTypeName.

/**
 * Resolves the given <code>ntName</code> and returns all node type names
 * where the local name matches <code>ntName</code>.
 *
 * @param ntName the name of a node type (optionally without prefix).
 * @return the matching node type names.
 * @throws RepositoryException if an error occurs while reading from the
 *                             node type manager.
 */
private String[] resolveNodeTypeName(String ntName) throws RepositoryException {
    String[] names;
    if (isPrefixed(ntName)) {
        names = new String[] { ntName };
    } else {
        if (ntNames == null) {
            NodeTypeManager ntMgr = session.getWorkspace().getNodeTypeManager();
            ntNames = new HashMap<String, String[]>();
            NodeTypeIterator it = ntMgr.getAllNodeTypes();
            while (it.hasNext()) {
                String name = it.nextNodeType().getName();
                String localName = name;
                int idx = name.indexOf(':');
                if (idx != -1) {
                    localName = name.substring(idx + 1);
                }
                String[] nts = ntNames.get(localName);
                if (nts == null) {
                    nts = new String[] { name };
                } else {
                    String[] tmp = new String[nts.length + 1];
                    System.arraycopy(nts, 0, tmp, 0, nts.length);
                    tmp[nts.length] = name;
                    nts = tmp;
                }
                ntNames.put(localName, nts);
            }
        }
        names = ntNames.get(ntName);
        if (names == null) {
            names = new String[] { ntName };
        }
    }
    return names;
}
Also used : NodeTypeManager(javax.jcr.nodetype.NodeTypeManager) NodeTypeIterator(javax.jcr.nodetype.NodeTypeIterator)

Aggregations

NodeTypeManager (javax.jcr.nodetype.NodeTypeManager)103 NodeType (javax.jcr.nodetype.NodeType)47 Node (javax.jcr.Node)38 Session (javax.jcr.Session)35 NodeTypeTemplate (javax.jcr.nodetype.NodeTypeTemplate)31 NodeTypeIterator (javax.jcr.nodetype.NodeTypeIterator)29 Test (org.junit.Test)25 RepositoryException (javax.jcr.RepositoryException)18 ByteArrayInputStream (java.io.ByteArrayInputStream)15 PropertyDefinition (javax.jcr.nodetype.PropertyDefinition)15 ConstraintViolationException (javax.jcr.nodetype.ConstraintViolationException)14 NotExecutableException (org.apache.jackrabbit.test.NotExecutableException)11 ArrayList (java.util.ArrayList)10 Workspace (javax.jcr.Workspace)10 InputStream (java.io.InputStream)9 NodeDefinition (javax.jcr.nodetype.NodeDefinition)9 PropertyDefinitionTemplate (javax.jcr.nodetype.PropertyDefinitionTemplate)9 InputStreamReader (java.io.InputStreamReader)8 NamespaceRegistry (javax.jcr.NamespaceRegistry)8 Value (javax.jcr.Value)8