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

The following examples show how to use javax.jcr.Session#save() . 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: 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 2
Source File: PurRepositoryTestingUtils.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
/**
 * Create a {@linkplain JcrCallback} for setting up ACL management in test repository
 * 
 * @return acl management callback
 */
static JcrCallback setAclManagementCallback() {
  return new JcrCallback() {
    @Override
    public Object doInJcr( Session session ) throws IOException, RepositoryException {
      PentahoJcrConstants pentahoJcrConstants = new PentahoJcrConstants( session );
      Workspace workspace = session.getWorkspace();
      PrivilegeManager privilegeManager = ( (JackrabbitWorkspace) workspace ).getPrivilegeManager();
      try {
        privilegeManager.getPrivilege( pentahoJcrConstants.getPHO_ACLMANAGEMENT_PRIVILEGE() );
      } catch ( AccessControlException ace ) {
        privilegeManager.registerPrivilege( pentahoJcrConstants.getPHO_ACLMANAGEMENT_PRIVILEGE(), false,
            new String[0] );
      }
      session.save();
      return null;
    }
  };
}
 
Example 3
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 4
Source File: CommentServiceImpl.java    From publick-sling-blog with Apache License 2.0 6 votes vote down vote up
/**
 * Edit comment and mark it as author edited.
 *
 * @param request The current request to get session and Resource Resolver
 * @param id The comment UUID
 * @param text The comment text
 * @return true if the operation was successful
 */
public boolean editComment(final SlingHttpServletRequest request, final String id, String text) {
    boolean result = false;

    try {
        Session session = request.getResourceResolver().adaptTo(Session.class);
        Node node = session.getNodeByIdentifier(id);

        if (node != null) {
            JcrResourceUtil.setProperty(node, PublickConstants.COMMENT_PROPERTY_COMMENT, text);
            JcrResourceUtil.setProperty(node, PublickConstants.COMMENT_PROPERTY_EDITED, true);
            session.save();
            result = true;
        }
    } catch (RepositoryException e) {
        LOGGER.error("Could not update comment from JCR", e);
    }

    return result;
}
 
Example 5
Source File: CommentServiceImpl.java    From publick-sling-blog with Apache License 2.0 6 votes vote down vote up
/**
 * Delete comment by setting it's display property to false.
 *
 * @param request The current request to get session and Resource Resolver
 * @param id The comment UUID
 * @return true if the operation was successful
 */
public boolean deleteComment(final SlingHttpServletRequest request, final String id) {
    boolean result = false;

    try {
        Session session = request.getResourceResolver().adaptTo(Session.class); 
        Node node = session.getNodeByIdentifier(id);

        if (node != null) {
            JcrResourceUtil.setProperty(node, PublickConstants.COMMENT_PROPERTY_DISPLAY, false);
            session.save();
            result = true;
        }
    } catch (RepositoryException e) {
        LOGGER.error("Could not delete comment from JCR", e);
    }

    return result;
}
 
Example 6
Source File: HistoryImpl.java    From APM with Apache License 2.0 6 votes vote down vote up
private HistoryEntry createHistoryEntry(ResourceResolver resolver, Script script, ExecutionMode mode,
    HistoryEntryWriter historyEntryWriter, boolean remote) {
  try {
    Session session = resolver.adaptTo(Session.class);

    Node scriptHistoryNode = createScriptHistoryNode(script, session);
    Node historyEntryNode = createHistoryEntryNode(scriptHistoryNode, script, mode, remote);
    historyEntryNode.setProperty(HistoryEntryImpl.SCRIPT_CONTENT_PATH, versionService.getVersionPath(script));
    writeProperties(resolver, historyEntryNode, historyEntryWriter);

    session.save();
    resolver.commit();
    return resolver.getResource(historyEntryNode.getPath()).adaptTo(HistoryEntryImpl.class);
  } catch (PersistenceException | RepositoryException e) {
    LOG.error("Issues with saving to repository while logging script execution", e);
    return null;
  }
}
 
Example 7
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 8
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 9
Source File: PackageServiceImpl.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
/**
 * Create a JCR package and store it under /etc/packages/group_name/package_name-version.zip.
 * {@link org.apache.sling.distribution.serialization.impl.vlt.JcrVaultDistributionPackageBuilder#createPackageForAdd}
 *
 * @param request The Sling HTTP servlet request
 * @param groupName The name of the package group
 * @param packageName The name of the package
 * @param version The version of the package
 * @param paths The JCR paths to include in the package
 * @return true  the saved JCR Package
 */
public JcrPackage createPackage(final SlingHttpServletRequest request, final String groupName,
        final String packageName, final String version, final String[] paths) {

    Session session = null;
    VaultPackage vaultPackage = null;
    JcrPackage savedPackage = null;

    File tempDirectory = VltUtils.getTempFolder(settingsService.getTemporaryDirectory());

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

        WorkspaceFilter filter = VltUtils.createFilter(paths, true);
        ExportOptions opts = VltUtils.getExportOptions(filter, paths, groupName, packageName, version);

        vaultPackage = VltUtils.createPackage(packaging.getPackageManager(), session, opts, tempDirectory);

        savedPackage = uploadPackage(session, vaultPackage);

        session.save();
    } catch (Exception e) {
        VltUtils.deletePackage(vaultPackage);
    }

    return savedPackage;
}
 
Example 10
Source File: SyncHandler.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
public void sync(Session session) throws RepositoryException, IOException {
    updateConfig();
    updateFilter();
    if (filter == null) {
        log.info("No filter present or configured in {}. Not syncing.", fileRoot.getAbsolutePath());
        observer.checkAndNotify();
        return;
    }

    log.debug("Starting sync cycle for {}.", this);
    if (cfg.isDisabled()) {
        log.debug("Syncing is disabled in {}.", fileRoot.getAbsolutePath());
        // flush changes
        observer.checkAndNotify();
        pendingFsChanges.clear();
        return;
    }
    // check if full sync is requested
    SyncMode syncOnce = cfg.getSyncOnce();
    if (syncOnce != null) {
        cfg.setSyncOnce(null);
        try {
            cfg.save();
        } catch (IOException e) {
            log.error("Error while saving config", e);
        }
        log.info("Sync Once requested: {}", syncOnce);
        syncTree(session, syncOnce);
    } else {
        SyncResult res = syncToDisk(session);
        log.debug("Scanning filesystem for changes {}", this);
        observer.checkAndNotify();
        syncToJcr(session, res);
        // todo: maybe save after each import?
        session.save();
        res.dump();
    }
    log.debug("Sync cycle completed for {}", this);
}
 
Example 11
Source File: NodeTypeAggregator.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ImportInfo remove(Node node, boolean recursive, boolean trySave) throws RepositoryException {
    ImportInfo info = new ImportInfoImpl();
    info.onDeleted(node.getPath());
    Session s = node.getSession();
    node.remove();
    if (trySave) {
        s.save();
    }
    return info;
}
 
Example 12
Source File: FileAggregator.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ImportInfo remove(Node node, boolean recursive, boolean trySave)
        throws RepositoryException {
    ImportInfo info = new ImportInfoImpl();
    info.onDeleted(node.getPath());
    Session s = node.getSession();
    node.remove();
    if (trySave) {
        s.save();
    }
    return info;
}
 
Example 13
Source File: Importer.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
public void applyMemberships(Session session) {
    if (memberships.isEmpty()) {
        return;
    }
    if (opts.isDryRun()) {
        track("Dry run: Would apply merged group memberships...", "");
    } else {
        track("Applying merged group memberships...", "");
    }
    for (String id: memberships.keySet()) {
        String[] members = memberships.get(id);
        String authPath = userManagement.getAuthorizablePath(session, id);
        if (authPath != null) {
            if (!opts.isDryRun()) {
                userManagement.addMembers(session, id, members);
            }
            track("U", String.format("%s", authPath));
        }
    }
    try {
        session.save();
    } catch (RepositoryException e) {
        log.error("Error while updating memberships.", e);
        try {
            session.refresh(false);
        } catch (RepositoryException e1) {
            // ignore
        }
    }
    memberships.clear();
}
 
Example 14
Source File: WebdavProviderTestCase.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
private static void importFiles(final File repoDirectory, final File sourceDir) throws Exception {
    final TransientRepository repository = getTransientRepository(repoDirectory);
    try {
        final Session session = getSession(repository);
        importFiles(session.getRootNode(), sourceDir);
        session.save();
        session.logout();
    } finally {
        repository.shutdown();
    }
}
 
Example 15
Source File: Webdav4ProviderTestCase.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
private static void importFiles(final File repoDirectory, final File sourceDir) throws Exception {
    final TransientRepository repository = getTransientRepository(repoDirectory);
    try {
        final Session session = getSession(repository);
        importFiles(session.getRootNode(), sourceDir);
        session.save();
        session.logout();
    } finally {
        repository.shutdown();
    }
}
 
Example 16
Source File: ProductBindingCreator.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
private void deleteJcrNode(Resource res) {
    Session session = resolver.adaptTo(Session.class);
    try {
        session.removeItem(res.getPath());
        session.save();
    } catch (RepositoryException e) {
        LOG.error(e.getMessage(), e);
    }

}
 
Example 17
Source File: SessionSavingPolicyImpl.java    From APM with Apache License 2.0 4 votes vote down vote up
public void save(Session session, SessionSavingMode sessionSavingMode) throws RepositoryException {
	if (mode != sessionSavingMode) {
		return;
	}
	session.save();
}
 
Example 18
Source File: AutoSave.java    From jackrabbit-filevault with Apache License 2.0 4 votes vote down vote up
/**
 * saves the changes under the given node and resets the counter
 * @param session the session to save. can be {@code null}
 * @throws RepositoryException if an error occurs.
 */
public void save(@Nullable Session session) throws RepositoryException {
    if (threshold == Integer.MAX_VALUE) {
        log.trace("Save disabled.");
        return;
    }
    int diff = numModified - lastSave;
    log.debug("Threshold of {} reached. {} approx {} transient changes. {} unresolved", new Object[]{
            threshold,
            dryRun ? "dry run, reverting" : "saving",
            diff,
            missingMandatory.size()
    });
    if (tracker != null) {
        if (dryRun) {
            tracker.track("reverting approx " + diff + " nodes... (dry run)", "");
        } else {
            tracker.track("saving approx " + diff + " nodes...", "");
        }
    }
    if (session != null) {
        if (debugFailEach > 0 && debugSaveCount > 0 && debugSaveCount%debugFailEach == 0) {
            String msg = String.format("Debugging provoked failure after %s saves.", debugSaveCount);
            log.error(msg);
            throw new RepositoryException(msg);
        }

        if (dryRun) {
            session.refresh(false);
        } else {
            try {
                session.save();
                debugSaveCount++;
            } catch (RepositoryException e) {
                log.error("error during auto save - retrying after refresh...");
                session.refresh(true);
                session.save();
                debugSaveCount++;
            }
        }
    }
    lastSave = numModified;
}
 
Example 19
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);
	}
}