Java Code Examples for javax.jcr.Session#getNode()

The following examples show how to use javax.jcr.Session#getNode() . 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: DefaultWorkspaceFilter.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void dumpCoverage(Session session, ProgressTrackerListener listener, boolean skipJcrContent)
        throws RepositoryException {
    ProgressTracker tracker = new ProgressTracker(listener);
    // get common ancestor
    Tree<PathFilterSet> tree = new Tree<PathFilterSet>();
    for (PathFilterSet set: nodesFilterSets) {
        tree.put(set.getRoot(), set);
    }
    String rootPath = tree.getRootPath();
    javax.jcr.Node rootNode;
    if (session.nodeExists(rootPath)) {
        rootNode = session.getNode(rootPath);
    } else if (session.nodeExists("/")) {
        log.warn("Common ancestor {} not found. Using root node", rootPath);
        rootNode = session.getRootNode();
        rootPath = "/";
    } else {
        throw new PathNotFoundException("Common ancestor " + rootPath+ " not found.");
    }
    log.debug("Starting coverage dump at {} (skipJcrContent={})", rootPath, skipJcrContent);
    dumpCoverage(rootNode, tracker, skipJcrContent);
}
 
Example 2
Source File: Debug.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
public void run(VltContext ctx) throws VltException {
    VltDirectory root = new VltDirectory(ctx, localDir);
    // mount fs at the top most directory
    if (root.isControlled()) {
        ctx.setFsRoot(root);
    }
    Session s = ctx.getFileSystem(ctx.getMountpoint()).getAggregateManager().getSession();
    byte[] buf = new byte[0x5000];
    try {
        Node tmp = s.getNode("/tmp");
        tmp.setProperty("test_binary", new ByteArrayInputStream(buf));
        tmp.setProperty("test_binary", new ByteArrayInputStream(buf));
        s.save();
    } catch (RepositoryException e) {
        log.error("Failed", e);
    }
    ctx.printMessage("done.");
}
 
Example 3
Source File: CheckPermissions.java    From APM with Apache License 2.0 5 votes vote down vote up
private List<String> getAllSubpaths(Session session, final String path) throws RepositoryException, LoginException {
  List<String> subPaths = new ArrayList<>();
  Node node = session.getNode(path);
  subPaths.addAll(crawl(node));

  return subPaths;
}
 
Example 4
Source File: ScriptStorageImpl.java    From APM with Apache License 2.0 5 votes vote down vote up
private Script saveScript(FileDescriptor descriptor, LaunchMetadata launchMetadata, boolean overwrite,
    ResourceResolver resolver) {
  Script result = null;
  try {
    final Session session = resolver.adaptTo(Session.class);
    final ValueFactory valueFactory = session.getValueFactory();
    final Binary binary = valueFactory.createBinary(descriptor.getInputStream());
    final Node saveNode = session.getNode(descriptor.getPath());

    final Node fileNode, contentNode;
    if (overwrite && saveNode.hasNode(descriptor.getName())) {
      fileNode = saveNode.getNode(descriptor.getName());
      contentNode = fileNode.getNode(JcrConstants.JCR_CONTENT);
    } else {
      fileNode = saveNode.addNode(generateFileName(descriptor.getName(), saveNode), JcrConstants.NT_FILE);
      contentNode = fileNode.addNode(JcrConstants.JCR_CONTENT, JcrConstants.NT_RESOURCE);
    }

    contentNode.setProperty(JcrConstants.JCR_DATA, binary);
    contentNode.setProperty(JcrConstants.JCR_ENCODING, SCRIPT_ENCODING.name());
    fileNode.addMixin(ScriptNode.APM_SCRIPT);
    fileNode.setProperty(ScriptNode.APM_LAUNCH_ENABLED, launchMetadata.isExecutionEnabled());
    setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_MODE, launchMetadata.getLaunchMode());
    setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_ENVIRONMENT, launchMetadata.getLaunchEnvironment());
    setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_HOOK, launchMetadata.getExecutionHook());
    setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_SCHEDULE, launchMetadata.getExecutionSchedule());
    removeProperty(fileNode, ScriptNode.APM_LAST_EXECUTED);
    JcrUtils.setLastModified(fileNode, Calendar.getInstance());
    session.save();
    result = scriptFinder.find(fileNode.getPath(), resolver);
  } catch (RepositoryException e) {
    LOG.error(e.getMessage(), e);
  }
  return result;
}
 
Example 5
Source File: SyncHandler.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
private SyncResult syncToDisk(Session session) throws RepositoryException, IOException {
    SyncResult res = new SyncResult();
    for (String path: preparedJcrChanges) {
        boolean recursive = path.endsWith("/");
        if (recursive) {
            path = path.substring(0, path.length() - 1);
        }
        if (!contains(path)) {
            log.debug("**** rejected. filter does not include {}", path);
            continue;
        }
        File file = getFileForJcrPath(path);
        log.debug("**** about sync jcr:/{} -> file://{}", path, file.getAbsolutePath());
        Node node;
        Node parentNode;
        if (session.nodeExists(path)) {
            node = session.getNode(path);
            parentNode = node.getParent();
        } else {
            node = null;
            String parentPath = Text.getRelativeParent(path, 1);
            parentNode = session.nodeExists(parentPath)
                    ? session.getNode(parentPath)
                    : null;
        }
        TreeSync tree = createTreeSync(SyncMode.JCR2FS);
        res.merge(tree.syncSingle(parentNode, node, file, recursive));
    }
    return res;
}
 
Example 6
Source File: SyncHandler.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
private void syncToJcr(Session session, SyncResult res) throws RepositoryException, IOException {
    for (String filePath: pendingFsChanges.keySet()) {
        if (res.getByFsPath(filePath) != null) {
            log.debug("ignoring change triggered by previous JCR->FS update. {}", filePath);
            return;
        }
        File file = pendingFsChanges.get(filePath);
        String path = getJcrPathForFile(file);
        log.debug("**** about sync file:/{} -> jcr://{}", file.getAbsolutePath(), path);
        if (!contains(path)) {
            log.debug("**** rejected. filter does not include {}", path);
            continue;
        }
        Node node;
        Node parentNode;
        if (session.nodeExists(path)) {
            node = session.getNode(path);
            parentNode = node.getParent();
        } else {
            node = null;
            String parentPath = Text.getRelativeParent(path, 1);
            parentNode = session.nodeExists(parentPath)
                    ? session.getNode(parentPath)
                    : null;
        }
        TreeSync tree = createTreeSync(SyncMode.FS2JCR);
        tree.setSyncMode(SyncMode.FS2JCR);
        res.merge(tree.syncSingle(parentNode, node, file, false));
    }
}
 
Example 7
Source File: AggregateManagerImpl.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new artifact manager that is rooted at the given node.
 *
 * @param config fs config
 * @param wspFilter the workspace filter
 * @param mountpoint the address of the mountpoint
 * @param session the repository session
 * @return an artifact manager
 * @throws RepositoryException if an error occurs.
 */
public static AggregateManager mount(VaultFsConfig config,
                                     WorkspaceFilter wspFilter,
                                     RepositoryAddress mountpoint,
                                     Session session)
        throws RepositoryException {
    if (config == null) {
        config = getDefaultConfig();
    }
    if (wspFilter == null) {
        wspFilter = getDefaultWorkspaceFilter();
    }
    Node rootNode = session.getNode(mountpoint.getPath());
    return new AggregateManagerImpl(config, wspFilter, mountpoint, rootNode, false);
}
 
Example 8
Source File: CatalogDataResourceProviderManagerImpl.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
/**
 * Handle resource events to add or remove virtual catalog data registrations.
 */
public void onEvent(EventIterator events) {
    try {
        // collect all actions to be performed for this event

        final Map<String, Boolean> actions = new HashMap<>();
        boolean nodeAdded = false;
        boolean nodeRemoved = false;
        while (events.hasNext()) {
            final Event event = events.nextEvent();
            final String path = event.getPath();
            final int eventType = event.getType();
            if (eventType == Event.NODE_ADDED) {
                nodeAdded = true;
                Session session = resolver.adaptTo(Session.class);
                final Node node = session.getNode(path);
                if (node != null && node.isNodeType(JcrResourceConstants.NT_SLING_FOLDER) && node.hasProperty(
                    CatalogDataResourceProviderFactory.PROPERTY_FACTORY_ID) || node.hasProperty(CONF_ROOT)) {
                    actions.put(path, true);
                }
            } else if (eventType == Event.NODE_REMOVED && providers.containsKey(path)) {
                nodeRemoved = true;
                actions.put(path, false);
            } else if ((eventType == Event.PROPERTY_CHANGED || eventType == Event.PROPERTY_ADDED || eventType == Event.PROPERTY_REMOVED)
                && isRelevantPath(path)) {
                // narrow down the properties to be watched.
                // force re-registering
                nodeAdded = true;
                nodeRemoved = true;
            }
        }

        for (Map.Entry<String, Boolean> action : actions.entrySet()) {
            if (action.getValue()) {
                final Resource rootResource = resolver.getResource(action.getKey());
                if (rootResource != null) {
                    registerDataRoot(rootResource);
                }
            } else {
                final ResourceProvider provider = providers.remove(action.getKey());
                if (provider != null) {
                    unregisterService(provider);
                }
            }
        }

        if (nodeAdded && nodeRemoved) {
            // maybe a virtual catalog was moved, re-register all virtual catalogs
            // (existing ones will be skipped)
            registerDataRoots();
        }
    } catch (RepositoryException e) {
        log.error("Unexpected repository exception during event processing.", e);
    }
}
 
Example 9
Source File: ScriptDownloadServlet.java    From APM with Apache License 2.0 4 votes vote down vote up
@Override
protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
		throws ServletException, IOException {
	String fileName = request.getParameter("filename");
	String filePath = request.getParameter("filepath");

	String mode = request.getParameter("mode");

	try {
		final ResourceResolver resourceResolver = request.getResourceResolver();
		final Session session = resourceResolver.adaptTo(Session.class);

		if (!("view").equals(mode)) {
			response.setContentType("application/octet-stream"); // Your content type
			response.setHeader("Content-Disposition",
					"attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
		}

		String path = StringUtils.replace(filePath, "_jcr_content", "jcr:content");

		Node jcrContent = session.getNode(path + "/jcr:content");

		InputStream input = jcrContent.getProperty("jcr:data").getBinary().getStream();

		session.save();
		int read;
		byte[] bytes = new byte[BYTES_DOWNLOAD];
		OutputStream os = response.getOutputStream();

		while ((read = input.read(bytes)) != -1) {
			os.write(bytes, 0, read);
		}
		input.close();
		os.flush();
		os.close();

	} catch (RepositoryException e) {
		LOGGER.error(e.getMessage(), e);
		response.sendRedirect("/etc/cqsm.html");
		// response.sendError(500);
	}
}
 
Example 10
Source File: Importer.java    From jackrabbit-filevault with Apache License 2.0 4 votes vote down vote up
public Node getParentNode(Session s) throws RepositoryException {
    String parentPath = emptyPathToRoot(Text.getRelativeParent(path, 1));
    return s.nodeExists(parentPath)
            ? s.getNode(parentPath)
            : null;
}
 
Example 11
Source File: Importer.java    From jackrabbit-filevault with Apache License 2.0 4 votes vote down vote up
public Node getNode(Session s) throws RepositoryException {
    String p = emptyPathToRoot(path);
    return s.nodeExists(p)
            ? s.getNode(p)
            : null;
}