javax.jcr.Session Java Examples

The following examples show how to use javax.jcr.Session. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Importer.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
private void registerPrivileges(Session session) throws IOException, RepositoryException {
    PrivilegeDefinitions privileges = archive.getMetaInf().getPrivileges();
    if (privileges != null && !privileges.getDefinitions().isEmpty()) {
        PrivilegeInstaller installer = ServiceProviderFactory.getProvider().getDefaultPrivilegeInstaller(session);
        try {
            log.debug("Registering privileges...");
            installer.install(tracker, privileges);
        } catch (RepositoryException e) {
            if (opts.isStrict()) {
                throw e;
            }
            track(e, "Packaged privileges");
        }
    } else {
        log.debug("No privileges provided.");
    }
}
 
Example #2
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Override
public void removeProject(RepositorySession session, String repositoryId, String namespace, String projectId)
        throws MetadataRepositoryException {
    final Session jcrSession = getSession(session);
    try {
        Node root = jcrSession.getRootNode();
        String namespacePath = getNamespacePath(repositoryId, namespace);

        if (root.hasNode(namespacePath)) {
            Iterator<Node> nodeIterator = JcrUtils.getChildNodes(root.getNode(namespacePath)).iterator();
            while (nodeIterator.hasNext()) {
                Node node = nodeIterator.next();
                if (node.isNodeType(org.apache.archiva.metadata.repository.jcr.JcrConstants.PROJECT_MIXIN_TYPE) && projectId.equals(node.getName())) {
                    node.remove();
                }
            }

        }
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException(e.getMessage(), e);
    }

}
 
Example #3
Source File: PackageServiceImpl.java    From publick-sling-blog with Apache License 2.0 6 votes vote down vote up
/**
 * Delete package from the JCR.
 *
 * @param request The current request.
 * @param groupName The name of the package group to install
 * @param packageName The name of the package to install
 * @param version The version of the package to install
 * @return true if package was installed successfully
 */
public boolean deletePackage(final SlingHttpServletRequest request, final String groupName, final String packageName, final String version) {
    Session session = request.getResourceResolver().adaptTo(Session.class);
    boolean result;

    final JcrPackageManager packageManager = packaging.getPackageManager(session);
    final PackageId packageId = new PackageId(groupName, packageName, version);

    try {
        final JcrPackage jcrPackage = packageManager.open(packageId);
        packageManager.remove(jcrPackage);

        result = true;
    } catch (RepositoryException e) {
        LOGGER.error("Could not remove package", e);
        result = false;
    }

    return result;
}
 
Example #4
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Override
public List<ArtifactMetadata> getArtifacts(RepositorySession session, String repositoryId)
        throws MetadataRepositoryException {
    final Session jcrSession = getSession(session);
    List<ArtifactMetadata> artifacts;

    String q = getArtifactQuery(repositoryId).toString();

    try {
        Query query = jcrSession.getWorkspace().getQueryManager().createQuery(q, Query.JCR_SQL2);
        QueryResult result = query.execute();

        artifacts = new ArrayList<>();
        for (Node n : JcrUtils.getNodes(result)) {
            if (n.isNodeType(ARTIFACT_NODE_TYPE)) {
                artifacts.add(getArtifactFromNode(repositoryId, n));
            }
        }
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException(e.getMessage(), e);
    }
    return artifacts;
}
 
Example #5
Source File: Sync.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
private void register(VltContext ctx, Session s, Boolean enable) throws RepositoryException {
    Config cfg = new Config(s);
    if (!cfg.load(ctx)) {
        ctx.getStdout().println("No sync-service configured at " + CFG_NODE_PATH);
        return;
    }
    for (String path: cfg.roots) {
        // need to check canonical path
        try {
            File f = new File(path).getCanonicalFile();
            if (f.equals(localDir)) {
                ctx.getStdout().println("Directory is already synced: " + localDir.getAbsolutePath());
                return;
            }
        } catch (IOException e) {
            // ignore
        }
    }
    cfg.roots.add(localDir.getAbsolutePath());
    if (enable != null) {
        cfg.enabled = enable;
    }
    cfg.save(ctx);
    ctx.getStdout().println("Added new sync directory: " + localDir.getAbsolutePath());
}
 
Example #6
Source File: Activator.java    From aem-password-reset with Apache License 2.0 6 votes vote down vote up
@Activate
public void start(ActivatorConfiguration config) {
    String[] authorizableIds = config.pwdreset_authorizables();

    Session session = null;
    try {
        ResourceResolver resolver = resolverFactory.getAdministrativeResourceResolver(null);

        UserManager userManager = resolver.adaptTo(UserManager.class);
        session = resolver.adaptTo(Session.class);

        for (String authorizable : authorizableIds) {
            try {
                Authorizable user = userManager.getAuthorizable(authorizable);
                if (user != null) {
                    ((User) user).changePassword(authorizable);
                    if (!userManager.isAutoSave()) {
                        session.save();
                    }
                    log.info("Changed the password for {}", authorizable);
                } else {
                    log.error("Could not find authorizable {}", authorizable);
                }
            } catch (RepositoryException repEx) {
                log.error("Could not change password for {}", authorizable, repEx);
            }
        }
    } catch (LoginException loginEx) {
        log.error("Could not login to the repository", loginEx);
    } finally {
        if(session != null) {
            session.logout();
        }
    }
}
 
Example #7
Source File: JcrSysViewTransformer.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
JcrSysViewTransformer(Node node, String existingPath) throws RepositoryException, SAXException {
    Session session = node.getSession();
    parent = node;
    handler = session.getImportContentHandler(
            node.getPath(),
            existingPath != null
                    ? ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING
                    : ImportUUIDBehavior.IMPORT_UUID_COLLISION_REMOVE_EXISTING
    );
    // first define the current namespaces
    String[] prefixes = session.getNamespacePrefixes();
    handler.startDocument();
    for (String prefix: prefixes) {
        handler.startPrefixMapping(prefix, session.getNamespaceURI(prefix));
    }

    this.existingPath = existingPath;
    if (existingPath != null) {
        // check if there is an existing node with the name
        recovery = new ChildNodeStash(session).excludeName("rep:cache");
        recovery.stashChildren(existingPath);
    }
    excludeNode("rep:cache");
}
 
Example #8
Source File: JackrabbitSessionFactory.java    From mycollab with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected void registerNodeTypes() throws Exception {
    if (!ObjectUtils.isEmpty(nodeDefinitions)) {

        Session session = getBareSession();
        Workspace ws = session.getWorkspace();

        NodeTypeManagerImpl jackrabbitNodeTypeManager = (NodeTypeManagerImpl) ws.getNodeTypeManager();

        boolean debug = LOG.isDebugEnabled();
        for (int i = 0; i < nodeDefinitions.length; i++) {
            Resource resource = nodeDefinitions[i];
            if (debug) {
                LOG.debug("adding node type definitions from " + resource.getDescription());
            }
            try {
                //                    ws.getNodeTypeManager().registerNodeType(ntd, allowUpdate)
                jackrabbitNodeTypeManager.registerNodeTypes(resource.getInputStream(), contentType);
            } catch (RepositoryException ex) {
                LOG.error("Error registering nodetypes ", ex.getCause());
            }
        }
        session.logout();
    }
}
 
Example #9
Source File: PackageManagerImpl.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public VaultPackage assemble(Session s, ExportOptions opts, File file)
        throws IOException, RepositoryException {
    OutputStream out = null;
    boolean isTmp = false;
    boolean success = false;
    try {
        if (file == null) {
            file = File.createTempFile("filevault", ".zip");
            isTmp = true;
        }
        out = FileUtils.openOutputStream(file);
        assemble(s, opts, out);
        IOUtils.closeQuietly(out);
        success = true;
        return new ZipVaultPackage(file, isTmp);
    } finally {
        IOUtils.closeQuietly(out);
        if (isTmp && !success) {
            FileUtils.deleteQuietly(file);
        }
    }
}
 
Example #10
Source File: JcrTemplate.java    From mycollab with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @see org.springframework.extensions.jcr.JcrOperations#dump(javax.jcr.Node)
 */
@Override
public String dump(final Node node) {

    return execute(new JcrCallback<String>() {
        /**
         * @see JcrCallback#doInJcr(javax.jcr.Session)
         */
        @Override
        public String doInJcr(Session session) throws RepositoryException {
            Node nd = node;

            if (nd == null)
                nd = session.getRootNode();

            return dumpNode(nd);
        }

    }, true);

}
 
Example #11
Source File: JCRBuilder.java    From jackalope with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the requested node.
 *
 * @param session Session to be associated with the new node
 * @return the Node
 */
protected NodeImpl build(Session session) {
    try {
        NodeImpl node = new NodeImpl((SessionImpl)session, getName());
        if (!Strings.isNullOrEmpty(nodeTypeName))
            node.setPrimaryType(nodeTypeName);
        for (ItemBuilder builder : childBuilders)
            builder.build(node);
        node.getSession().save();
        return node;
    }
    catch (RepositoryException re) {
        throw new SlingRepositoryException(re);
    }
}
 
Example #12
Source File: JcrTemplate.java    From mycollab with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @see org.springframework.extensions.jcr.JcrOperations#setNamespacePrefix(java.lang.String,
 *      java.lang.String)
 */
@Override
public void setNamespacePrefix(final String prefix, final String uri) {
    execute(new JcrCallbackWithoutResult() {
        /**
         * @see org.springframework.extensions.jcr.JcrCallbackWithoutResult#doInJcrwithoutResult(javax.jcr.Session)
         */
        @Override
        protected void doInJcrWithoutResult(Session session) throws RepositoryException {
            session.setNamespacePrefix(prefix, uri);
        }
    }, true);
}
 
Example #13
Source File: SystemFilter.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
/**
 * Prevent unauthorables from accessing Sling's user admin.
 *
 * @param request The Sling HTTP Servlet Request.
 * @param response The Sling HTTP Servlet Response.
 * @param chain The Filter Chain to continue processin the response.
 */
@Override
public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain chain) throws IOException, ServletException {

    // Since this is a Sling Filter, the request and response objects are guaranteed
    // to be of types SlingHttpServletRequest and SlingHttpServletResponse.
    final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest)request;
    final SlingHttpServletResponse slingResponse = (SlingHttpServletResponse)response;
    final String path = slingRequest.getPathInfo().toLowerCase();
    final String method = slingRequest.getMethod();

    response.setCharacterEncoding(CharEncoding.UTF_8);

    if ("POST".equals(method) && path.startsWith("/system")) {
        if (userService != null) {
            final boolean allow = userService.isAuthorable(slingRequest.getResourceResolver().adaptTo(Session.class));

            if (allow) {
                chain.doFilter(request, response);
            } else {
                slingResponse.sendError(SlingHttpServletResponse.SC_FORBIDDEN);
            }
        } else {
            slingResponse.sendError(SlingHttpServletResponse.SC_FORBIDDEN);
        }
    } else {
        chain.doFilter(request, response);
    }
}
 
Example #14
Source File: Activator.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
/**
 * Create user groups for authors and testers.
 *
 * @param bundleContext The bundle context provided by the component.
 */
private void createGroups(BundleContext bundleContext){
    ServiceReference SlingRepositoryFactoryReference = bundleContext.getServiceReference(SlingRepository.class.getName());
    SlingRepository repository = (SlingRepository)bundleContext.getService(SlingRepositoryFactoryReference);

    Session session = null;

    if (repository != null) {
        try {
            session = repository.loginAdministrative(null);

            if (session != null && session instanceof JackrabbitSession) {
                UserManager userManager = ((JackrabbitSession)session).getUserManager();
                ValueFactory valueFactory = session.getValueFactory();

                Authorizable authors = userManager.getAuthorizable(PublickConstants.GROUP_ID_AUTHORS);

                if (authors == null) {
                    authors = userManager.createGroup(PublickConstants.GROUP_ID_AUTHORS);
                    authors.setProperty(GROUP_DISPLAY_NAME, valueFactory.createValue(PublickConstants.GROUP_DISPLAY_AUTHORS));
                }

                Authorizable testers = userManager.getAuthorizable(PublickConstants.GROUP_ID_TESTERS);

                if (testers == null) {
                    testers = userManager.createGroup(PublickConstants.GROUP_ID_TESTERS);
                    testers.setProperty(GROUP_DISPLAY_NAME, valueFactory.createValue(PublickConstants.GROUP_DISPLAY_TESTERS));
                }
            }
        } catch (RepositoryException e) {
            LOGGER.error("Could not get session", e);
        } finally {
            if (session != null && session.isLive()) {
                session.logout();
                session = null;
            }
        }
    }
}
 
Example #15
Source File: CmdImport.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
protected void doExecute(VaultFsConsoleExecutionContext ctx, CommandLine cl) throws Exception {
    String localPath = (String) cl.getValue(argLocalPath);
    String jcrPath = (String) cl.getValue(argJcrPath);
    boolean verbose = cl.hasOption(OPT_VERBOSE);
    /*
    List excludeList = cl.getValues(optExclude);
    String[] excludes = Constants.EMPTY_STRING_ARRAY;
    if (excludeList != null && excludeList.size() > 0) {
        excludes = (String[]) excludeList.toArray(new String[excludeList.size()]);
    }
    */
    File localFile = ctx.getVaultFsApp().getPlatformFile(localPath, false);
    VaultFile vaultFile = ctx.getVaultFsApp().getVaultFile(jcrPath, true);
    VaultFsApp.log.info("Importing {} to {}", localFile.getCanonicalPath(), vaultFile.getPath());
    Archive archive;
    if (localFile.isFile()) {
        archive = new ZipArchive(localFile);
    } else {
        archive = new FileArchive(localFile);
    }
    Importer importer = new Importer();
    if (verbose) {
        importer.getOptions().setListener(new DefaultProgressListener());
    }

    Session s = vaultFile.getFileSystem().getAggregateManager().getSession();
    importer.run(archive, s, vaultFile.getPath());
    VaultFsApp.log.info("Importing done.");
}
 
Example #16
Source File: ResourceResolverImpl.java    From jackalope with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <AdapterType> AdapterType adaptTo(Class<AdapterType> type) {
    if (type.equals(Session.class)) return (AdapterType)session;
    if (type.equals(PageManager.class)) return (AdapterType)new PageManagerImpl(this);
    else return null;
}
 
Example #17
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 5 votes vote down vote up
private void updateProject(Session jcrSession, String repositoryId, String namespace, String projectId)
        throws MetadataRepositoryException {
    updateNamespace(jcrSession, repositoryId, namespace);

    try {
        getOrAddProjectNode(jcrSession, repositoryId, namespace, projectId);
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException(e.getMessage(), e);
    }
}
 
Example #18
Source File: CatalogDataResourceProviderManagerImpl.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
private String getJcrStringProperty(String pNodePath, String pPropertName) {
    String absolutePropertyPath = pNodePath + "/" + pPropertName;
    Session session = resolver.adaptTo(Session.class);
    try {
        if (!session.itemExists(absolutePropertyPath)) {
            return null;
        }
        return session.getProperty(absolutePropertyPath)
            .getString();
    } catch (RepositoryException ex) {
        return null;
    }
}
 
Example #19
Source File: JcrTemplate.java    From mycollab with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @see org.springframework.extensions.jcr.JcrOperations#refresh(boolean)
 */
@Override
public void refresh(final boolean keepChanges) {
    execute(new JcrCallbackWithoutResult() {
        /**
         * @see org.springframework.extensions.jcr.JcrCallbackWithoutResult#doInJcrwithoutResult(javax.jcr.Session)
         */
        @Override
        protected void doInJcrWithoutResult(Session session) throws RepositoryException {
            session.refresh(keepChanges);
        }
    }, true);
}
 
Example #20
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Override
public void removeTimestampedArtifact(RepositorySession session, ArtifactMetadata artifactMetadata, String baseVersion)
        throws MetadataRepositoryException {
    final Session jcrSession = getSession(session);
    String repositoryId = artifactMetadata.getRepositoryId();

    try {
        Node root = jcrSession.getRootNode();
        String path =
                getProjectVersionPath(repositoryId, artifactMetadata.getNamespace(), artifactMetadata.getProject(),
                        baseVersion);

        if (root.hasNode(path)) {
            Node node = root.getNode(path);

            for (Node n : JcrUtils.getChildNodes(node)) {
                if (n.isNodeType(ARTIFACT_NODE_TYPE)) {
                    if (n.hasProperty("version")) {
                        String version = n.getProperty("version").getString();
                        if (StringUtils.equals(version, artifactMetadata.getVersion())) {
                            n.remove();
                        }
                    }

                }
            }
        }
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException(e.getMessage(), e);
    }


}
 
Example #21
Source File: JcrPackageRegistry.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
public JcrPackageRegistry(@NotNull Session session, @Nullable AbstractPackageRegistry.SecurityConfig securityConfig, @Nullable String... roots) {
    super(securityConfig);
    this.session = session;
    if (roots == null || roots.length == 0) {
        packRootPaths = new String[]{DEFAULT_PACKAGE_ROOT_PATH};
    } else {
        packRootPaths = roots;
    }
    packRoots = new Node[packRootPaths.length];
    initNodeTypes();
}
 
Example #22
Source File: LongSessionService.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
private void registerObservation() {
    final Session session = getSession();
    if (session != null) {
        try {
            session.getWorkspace().getObservationManager().addEventListener(this, 63, "/", true, null, null, true);
        } catch (RepositoryException x) {
        }
    }
}
 
Example #23
Source File: SessionLogoutFive.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
public void five() {
    Session session = null; // Noncompliant
    try {
        session = repository.loginAdministrative(null);
    } catch (RepositoryException e) {
        e.printStackTrace();
    } finally {
        if (session != null && session.isLive()) {
            //	session.logout();
        }
    }
}
 
Example #24
Source File: LongResourceResolverEvenListenerError.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
@Deactivate
public void deactivate(final Map<String, String> config) throws RepositoryException {
    try {
        final Session session = resolver.adaptTo(Session.class);
    } finally {
    }
}
 
Example #25
Source File: AdministrativeAccessUsageCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
public Session getSession(String workspace) {
    Session session = null;
    try {
        session = repository.loginAdministrative(workspace); // Noncompliant {{Method 'loginAdministrative' is deprecated. Use 'loginService' instead.}}
    } catch (RepositoryException e) {
        //
    }
    return session;
}
 
Example #26
Source File: SessionLogoutEight.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
private Session createAdminSession() {
    Session result = null;
    try {
        result = repository.loginAdministrative(null);
    } catch (RepositoryException e) {
        e.printStackTrace();
    }
    return result;
}
 
Example #27
Source File: JcrTemplate.java    From mycollab with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @see org.springframework.extensions.jcr.JcrOperations#save()
 */
@Override
public void save() {
    execute(new JcrCallbackWithoutResult() {
        /**
         * @see org.springframework.extensions.jcr.JcrCallbackWithoutResult#doInJcrwithoutResult(javax.jcr.Session)
         */
        @Override
        protected void doInJcrWithoutResult(Session session) throws RepositoryException {
            session.save();
        }
    }, true);
}
 
Example #28
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Override
public void addMetadataFacet(RepositorySession session, String repositoryId, MetadataFacet metadataFacet)
        throws MetadataRepositoryException {
    final Session jcrSession = getSession(session);
    try {
        Node repo = getOrAddRepositoryNode(jcrSession, repositoryId);
        Node facets = JcrUtils.getOrAddNode(repo, "facets", FACETS_FOLDER_TYPE);

        String id = metadataFacet.getFacetId();
        Node facetNode = JcrUtils.getOrAddNode(facets, id, FACET_ID_CONTAINER_TYPE);
        if (!facetNode.hasProperty("id")) {
            facetNode.setProperty("id", id);
        }

        Node facetInstance = getOrAddNodeByPath(facetNode, metadataFacet.getName(), FACET_NODE_TYPE, true);
        if (!facetInstance.hasProperty("archiva:facetId")) {
            facetInstance.setProperty("archiva:facetId", id);
            facetInstance.setProperty("archiva:name", metadataFacet.getName());
        }

        for (Map.Entry<String, String> entry : metadataFacet.toProperties().entrySet()) {
            facetInstance.setProperty(entry.getKey(), entry.getValue());
        }
        session.save();
    } catch (RepositoryException | MetadataSessionException e) {
        throw new MetadataRepositoryException(e.getMessage(), e);
    }
}
 
Example #29
Source File: ScriptStorageImpl.java    From APM with Apache License 2.0 5 votes vote down vote up
@Override
public void remove(final Script script, ResourceResolver resolver) throws RepositoryException {
  scriptManager.getEventManager().trigger(Event.BEFORE_REMOVE, script);
  final Session session = resolver.adaptTo(Session.class);
  final String path = script.getPath();
  if (path != null) {
    session.removeItem(path);
    session.save();
  }
}
 
Example #30
Source File: JackrabbitACLImporter.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
private JackrabbitACLImporter(Session session, String path, AccessControlHandling aclHandling)
        throws RepositoryException {
    if (aclHandling == AccessControlHandling.CLEAR || aclHandling == AccessControlHandling.IGNORE) {
        throw new RepositoryException("Error while reading access control content: unsupported AccessControlHandling: " + aclHandling);
    }
    this.accessControlledPath = path;
    this.session = (JackrabbitSession) session;
    this.acMgr = this.session.getAccessControlManager();
    this.pMgr = this.session.getPrincipalManager();
    this.aclHandling = aclHandling;
    this.states.push(State.INITIAL);
}