/** * Test {@link javax.jcr.lock.Lock#isLockOwningSession()} * * @throws RepositoryException If an execption occurs. */ public void testIsLockOwningSession() throws RepositoryException { assertTrue("Session must be lock owner", lock.isLockOwningSession()); assertTrue("Session must be lock owner", lockedNode.getLock().isLockOwningSession()); assertTrue( "Session must be lock owner", lockMgr.getLock(lockedNode.getPath()).isLockOwningSession()); Session otherSession = getHelper().getReadOnlySession(); try { Lock lck = otherSession.getNode(lockedNode.getPath()).getLock(); assertFalse("Session must not be lock owner", lck.isLockOwningSession()); Lock lck2 = getLockManager(otherSession).getLock(lockedNode.getPath()); assertFalse("Session must not be lock owner", lck2.isLockOwningSession()); } finally { otherSession.logout(); } Session otherAdmin = getHelper().getSuperuserSession(); try { Lock lck = otherAdmin.getNode(lockedNode.getPath()).getLock(); assertFalse( "Other Session for the same userID must not be lock owner", lck.isLockOwningSession()); Lock lck2 = getLockManager(otherAdmin).getLock(lockedNode.getPath()); assertFalse( "Other Session for the same userID must not be lock owner", lck2.isLockOwningSession()); } finally { otherAdmin.logout(); } }
@Test public void shouldAllowDataPersistedInOneSessionBeAccessibleInOtherSessions() throws Exception { startRepository(); Session session = getRepository().login(getTestCredentials()); assertThat(session, is(notNullValue())); assertThat(session.getRootNode(), is(notNullValue())); // Create a child node ... Node node = session.getRootNode().addNode("testnode", "nt:unstructured"); assertThat(node, is(notNullValue())); assertThat(node.getName(), is("testnode")); assertThat(node.getPath(), is("/testnode")); // Save and close the session ... session.save(); session.logout(); for (int i = 0; i != 3; ++i) { // Create another session ... session = getRepository().login(getTestCredentials()); assertThat(session, is(notNullValue())); assertThat(session.getRootNode(), is(notNullValue())); // Look for the child node ... node = session.getRootNode().getNode("testnode"); assertThat(node, is(notNullValue())); assertThat(node.getName(), is("testnode")); assertThat(node.getPath(), is("/testnode")); // Close the session ... session.logout(); } }
/** Test locks are released when session logs out */ public void testImplicitUnlock() throws RepositoryException, NotExecutableException { Session other = getHelper().getReadWriteSession(); try { Node testNode = (Node) other.getItem(testRootNode.getPath()); Node lockedNode = testNode.addNode(nodeName1, testNodeType); other.save(); assertLockable(lockedNode); Lock lock = getLockManager(other) .lock( lockedNode.getPath(), isDeep(), isSessionScoped(), getTimeoutHint(), getLockOwner()); other.logout(); assertFalse(lock.isLive()); } finally { if (other.isLive()) { other.logout(); } } }
/** Releases the sessions aquired in {@link #setUp()}. */ protected void tearDown() throws Exception { if (sessionW2 != null) { sessionW2.logout(); sessionW2 = null; } if (session != null) { session.logout(); session = null; } super.tearDown(); }
/** * This method will re-observer all nodes that have been ever observed with all repositories. * * @throws Exception */ private void reInitObserver() throws Exception { RepositoryEntry repo = repoService_.getCurrentRepository().getConfiguration(); ManageableRepository repository = repoService_.getCurrentRepository(); String[] workspaceNames = repository.getWorkspaceNames(); for (String workspace : workspaceNames) { Session session = repository.getSystemSession(workspace); QueryManager queryManager = null; try { queryManager = session.getWorkspace().getQueryManager(); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", e); } } if (queryManager == null) { session.logout(); continue; } try { Query query = queryManager.createQuery(WATCHABLE_MIXIN_QUERY, Query.XPATH); QueryResult queryResult = query.execute(); for (NodeIterator iter = queryResult.getNodes(); iter.hasNext(); ) { Node observedNode = iter.nextNode(); EmailNotifyListener emailNotifyListener = new EmailNotifyListener(observedNode); ObservationManager manager = session.getWorkspace().getObservationManager(); List<String> list = getDocumentNodeTypes(observedNode); String[] observedNodeTypeNames = list.toArray(new String[list.size()]); manager.addEventListener( emailNotifyListener, Event.PROPERTY_CHANGED, observedNode.getPath(), true, null, observedNodeTypeNames, false); } session.logout(); } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn( "==>>> Cannot init observer for node: " + e.getLocalizedMessage() + " in '" + repo.getName() + "' repository"); } if (LOG.isErrorEnabled()) { LOG.error("Unexpected error", e); } } } }
/* * (non-Javadoc) * @see com.stratelia.webactiv.util.document.model.jcr.impl.JcrDocumentService# getUpdatedDocument * (com.stratelia.webactiv.util.document.model.DocumentVersion, java.lang.String) */ public void getUpdatedDocument(DocumentVersion document) { Session session = null; try { session = BasicDaoFactory.getSystemSession(); jcrDocumentDao.updateDocument(session, document); session.save(); } catch (RepositoryException ex) { SilverTrace.error("document", "JcrDocumentServiceImpl", "document.jcr.create.exception", ex); throw new VersioningRuntimeException( "JcrDocumentServiceImpl", SilverpeasRuntimeException.ERROR, "document.jcr.create.exception", ex); } catch (IOException ex) { SilverTrace.error("document", "JcrDocumentServiceImpl", "document.jcr.create.exception", ex); throw new VersioningRuntimeException( "JcrDocumentServiceImpl", SilverpeasRuntimeException.ERROR, "document.jcr.create.exception", ex); } finally { if (session != null) { session.logout(); } } }
@Test public void testGetCompounds() throws Exception { Session session = getSession(); final Set<String> compounds = HippoNodeUtils.getCompounds(session); assertTrue(compounds.size() == 0); session.logout(); }
public static void main(String[] argv) { // Create and start the engine ... ModeShapeEngine engine = new ModeShapeEngine(); engine.start(); // Load the configuration for a repository via the classloader (can also use path to a file)... Repository repository = null; String repositoryName = null; try { URL url = ModeShapeExample.class.getClassLoader().getResource("my-repository-config.json"); RepositoryConfiguration config = RepositoryConfiguration.read(url); // We could change the name of the repository programmatically ... // config = config.withName("Some Other Repository"); // Verify the configuration for the repository ... Problems problems = config.validate(); if (problems.hasErrors()) { System.err.println("Problems starting the engine."); System.err.println(problems); System.exit(-1); } // Deploy the repository ... repository = engine.deploy(config); repositoryName = config.getName(); } catch (Throwable e) { e.printStackTrace(); System.exit(-1); return; } Session session = null; try { // Get the repository repository = engine.getRepository(repositoryName); // Create a session ... session = repository.login("default"); // Get the root node ... Node root = session.getRootNode(); assert root != null; System.out.println( "Found the root node in the \"" + session.getWorkspace().getName() + "\" workspace"); } catch (RepositoryException e) { e.printStackTrace(); } finally { if (session != null) session.logout(); System.out.println("Shutting down engine ..."); try { engine.shutdown().get(); System.out.println("Success!"); } catch (Exception e) { e.printStackTrace(); } } }
/** * The main entry point of the example application. * * @param args command line arguments (ignored) * @throws Exception if an error occurs */ public static void main(String[] args) throws Exception { Repository repository = new TransientRepository(); Session session = repository.login(new SimpleCredentials("admin", "admin".toCharArray())); try { Node root = session.getRootNode(); // Import the XML file unless already imported if (!root.hasNode("importxml")) { System.out.print("Importing xml... "); // Create an unstructured node under which to import the XML Node node = root.addNode("importxml", "nt:unstructured"); // Import the file "test.xml" under the created node FileInputStream xml = new FileInputStream("test.xml"); session.importXML(node.getPath(), xml, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW); xml.close(); session.save(); System.out.println("done."); } // output the repository content dump(root); } finally { session.logout(); } }
private void persistBinaryContent(JcrRepository repository) throws RepositoryException, IOException { assertNotNull(repository); long minimumBinarySize = repository.getConfiguration().getBinaryStorage().getMinimumBinarySizeInBytes(); long binarySize = minimumBinarySize + 1; Session session = repository.login(); InputStream binaryValueStream = null; try { byte[] content = new byte[(int) binarySize]; new Random().nextBytes(content); JCR_TOOLS.uploadFile(session, "folder/file", new ByteArrayInputStream(content)); session.save(); Node nodeWithBinaryContent = session.getNode("/folder/file/jcr:content"); Binary binaryValue = nodeWithBinaryContent.getProperty("jcr:data").getBinary(); binaryValueStream = binaryValue.getStream(); byte[] retrievedContent = IoUtil.readBytes(binaryValueStream); assertArrayEquals(content, retrievedContent); } finally { if (binaryValueStream != null) { binaryValueStream.close(); } session.logout(); } }
private boolean removeNode(String path) { Resource templateResource = resourceResolver.getResource(path); if (templateResource != null) { Node nodeToDelete = templateResource.adaptTo(Node.class); if (nodeToDelete != null) { try { nodeToDelete.remove(); TemplateUtils.saveNode(nodeToDelete); session.save(); return true; } catch (VersionException ex) { java.util.logging.Logger.getLogger(TemplateManagerDeleteServlet.class.getName()) .log(Level.SEVERE, null, ex); } catch (LockException ex) { java.util.logging.Logger.getLogger(TemplateManagerDeleteServlet.class.getName()) .log(Level.SEVERE, null, ex); } catch (ConstraintViolationException ex) { java.util.logging.Logger.getLogger(TemplateManagerDeleteServlet.class.getName()) .log(Level.SEVERE, null, ex); } catch (AccessDeniedException ex) { java.util.logging.Logger.getLogger(TemplateManagerDeleteServlet.class.getName()) .log(Level.SEVERE, null, ex); } catch (RepositoryException ex) { java.util.logging.Logger.getLogger(TemplateManagerDeleteServlet.class.getName()) .log(Level.SEVERE, null, ex); } finally { session.logout(); } } } return false; }
/** {@inheritDoc} */ public void onEvent(EventIterator eventIterator) { // waiting for Event.PROPERTY_ADDED, Event.PROPERTY_REMOVED, // Event.PROPERTY_CHANGED Session session = null; try { while (eventIterator.hasNext()) { Event event = eventIterator.nextEvent(); String path = event.getPath(); if (path.endsWith("/jcr:data")) { // jcr:data removed 'exo:groovyResourceContainer' then unbind resource if (event.getType() == Event.PROPERTY_REMOVED) { unloadScript(path.substring(0, path.lastIndexOf('/'))); } else if (event.getType() == Event.PROPERTY_ADDED || event.getType() == Event.PROPERTY_CHANGED) { if (session == null) { session = repository.getSystemSession(workspaceName); } Node node = session.getItem(path).getParent(); if (node.getProperty("exo:autoload").getBoolean()) loadScript(node); } } } } catch (Exception e) { LOG.error("Process event failed. ", e); } finally { if (session != null) { session.logout(); } } }
/** * The full set of version histories in the version storage, though stored in a single location in * the repository, must be reflected in each workspace as a subtree below the node * /jcr:system/jcr:versionStorage. Entire subtree must be identical across all workspaces and is * protected. */ public void testVersionStorageIdenticalAcrossAllWorkspaces() throws RepositoryException { // The superuser session for the second workspace Session superuserW2 = getHelper().getSuperuserSession(workspaceName); try { // check path to version storage assertTrue( "Version strorage must be reflected as a subtree below the node '" + versionStoragePath + "'", superuserW2.getRootNode().hasNode(versionStoragePath)); // check if subnodes in versionStorage are protected try { // try to create a version node Node versionStorageNodeW2 = superuserW2.getRootNode().getNode(versionStoragePath); versionStorageNodeW2.addNode(nodeName1, ntVersion); fail("It should not be possible to add a subnode/version in version storage."); } catch (ConstraintViolationException e) { // success } } finally { superuserW2.logout(); } }
public String getHomePageLogoURI() { SessionProvider sProvider = SessionProvider.createSystemProvider(); Node rootNode = null; Node publicApplicationNode = null; String pathImageNode = null; Node ImageNode = null; Session session = null; try { publicApplicationNode = nodeCreator.getPublicApplicationNode(sProvider); session = publicApplicationNode.getSession(); rootNode = session.getRootNode(); Node logosNode = rootNode.getNode(path); if (logosNode.hasNode(logo_name)) { ImageNode = logosNode.getNode(logo_name); pathImageNode = ImageNode.getPath() + "?" + System.currentTimeMillis(); } } catch (Exception e) { LOG.error("Can not get path of Logo : default LOGO will be used" + e.getMessage(), e); return null; } finally { if (session != null) session.logout(); if (sProvider != null) sProvider.close(); } return pathImageNode; }
protected void activate(final ComponentContext ctx) { if (TMP_DIR != null) { File tmpDir = new File(TMP_DIR); fontsDir = new File(tmpDir, "fonts." + UUID.randomUUID()); fontsDir.mkdir(); fontsDir.deleteOnExit(); Session session = null; try { session = repo.loginAdministrative(repo.getDefaultWorkspace()); if (session.nodeExists(FONT_CONFIG)) { configFile = createFile(session.getNode(FONT_CONFIG)); } if (session.nodeExists(FONT_CONFIG_FONTS)) { Node fonts = session.getNode(FONT_CONFIG_FONTS); NodeIterator children = fonts.getNodes(); while (children.hasNext()) { createFile((Node) children.next()); } } } catch (RepositoryException e) { logger.error("Failed exporting FOP font data.", e); } finally { if (session != null) { session.logout(); } } } }
public void testRestoreSNS() throws RepositoryException { Session session = getHelper().getSuperuserSession(); // - Create a node 'a' with nodetype nt:unstructured // (defining it's childnodes to show OPV Version behaviour) Node node = session.getRootNode().addNode("RestoreSameNameSiblingTest"); try { // - Create a child node 'b' node.addNode("test"); // - Make 'a' versionable (add mixin mix:versionable) node.addMixin(mixVersionable); session.save(); // - Checkin/Checkout 'a' Version version = node.checkin(); node.checkout(); assertEquals(1, node.getNodes("test").getSize()); // - Restore any version of 'a' node.restore(version, true); assertEquals(1, node.getNodes("test").getSize()); } finally { node.remove(); session.save(); session.logout(); } }
/** A LockException is thrown if a lock prevents the copy. */ public void testMoveNodesLocked() throws RepositoryException { // we assume repository supports locking String dstAbsPath = node2.getPath() + "/" + node1.getName(); // get other session Session otherSession = helper.getReadWriteSession(); try { // get lock target node in destination wsp through other session Node lockTarget = (Node) otherSession.getItem(node2.getPath()); // add mixin "lockable" to be able to lock the node if (!lockTarget.getPrimaryNodeType().isNodeType(mixLockable)) { lockTarget.addMixin(mixLockable); lockTarget.getParent().save(); } // lock dst parent node using other session lockTarget.lock(true, true); try { workspace.move(node1.getPath(), dstAbsPath); fail("LockException was expected."); } catch (LockException e) { // successful } finally { lockTarget.unlock(); } } finally { otherSession.logout(); } }
private URI addDatastreamNode( final String pid, final String dsPath, final MediaType contentType, final InputStream requestBodyStream, final Session session) throws RepositoryException, IOException { Long oldObjectSize = getObjectSize(session.getNode(getObjectJcrNodePath(pid))); logger.debug("Attempting to add datastream node at path: " + dsPath); try { boolean created = session.nodeExists(dsPath); createDatastreamNode(session, dsPath, contentType.toString(), requestBodyStream); session.save(); if (created) { /* * we save before updating the repo size because the act of * persisting session state creates new system-curated nodes and * properties which contribute to the footprint of this resource */ updateRepositorySize( getObjectSize(session.getNode(getObjectJcrNodePath(pid))) - oldObjectSize, session); // now we save again to persist the repo size session.save(); } } finally { session.logout(); } logger.debug("Finished adding datastream node at path: " + dsPath); return uriInfo.getAbsolutePath(); }
@Override protected void internalStore(Mail mail) throws MessagingException, IOException { try { Session session = login(); try { String name = Text.escapeIllegalJcrChars(mail.getName()); final String xpath = "/jcr:root/" + MAIL_PATH + "//element(" + name + ",james:mail)"; QueryManager manager = session.getWorkspace().getQueryManager(); @SuppressWarnings("deprecation") Query query = manager.createQuery(xpath, Query.XPATH); NodeIterator iterator = query.execute().getNodes(); if (iterator.hasNext()) { while (iterator.hasNext()) { setMail(iterator.nextNode(), mail); } } else { Node parent = session.getRootNode().getNode(MAIL_PATH); Node node = parent.addNode(name, "james:mail"); Node resource = node.addNode("jcr:content", "nt:resource"); resource.setProperty("jcr:mimeType", "message/rfc822"); setMail(node, mail); } session.save(); logger.info("Mail " + mail.getName() + " stored in repository"); } finally { session.logout(); } } catch (IOException e) { throw new MessagingException("Unable to store message: " + mail.getName(), e); } catch (RepositoryException e) { throw new MessagingException("Unable to store message: " + mail.getName(), e); } }
public Mail retrieve(String key) throws MessagingException { try { Session session = login(); try { String name = toSafeName(key); QueryManager manager = session.getWorkspace().getQueryManager(); @SuppressWarnings("deprecation") Query query = manager.createQuery( "/jcr:root/" + MAIL_PATH + "//element(" + name + ",james:mail)", Query.XPATH); NodeIterator iterator = query.execute().getNodes(); if (iterator.hasNext()) { return getMail(iterator.nextNode()); } else { return null; } } finally { session.logout(); } } catch (IOException e) { throw new MessagingException("Unable to retrieve message: " + key, e); } catch (RepositoryException e) { throw new MessagingException("Unable to retrieve message: " + key, e); } }
@Override protected void internalRemove(String key) throws MessagingException { try { Session session = login(); try { String name = ISO9075.encode(Text.escapeIllegalJcrChars(key)); QueryManager manager = session.getWorkspace().getQueryManager(); @SuppressWarnings("deprecation") Query query = manager.createQuery( "/jcr:root/" + MAIL_PATH + "//element(" + name + ",james:mail)", Query.XPATH); NodeIterator nodes = query.execute().getNodes(); if (nodes.hasNext()) { while (nodes.hasNext()) { nodes.nextNode().remove(); } session.save(); logger.info("Mail " + key + " removed from repository"); } else { logger.warn("Mail " + key + " not found"); } } finally { session.logout(); } } catch (RepositoryException e) { throw new MessagingException("Unable to remove message: " + key, e); } }
public void initDefaultUsers() { Session session = null; try { session = repository.loginAdministrative(null); UserManager userManager = AccessControlUtil.getUserManager(session); // Apply default user properties from JSON files. Pattern fileNamePattern = Pattern.compile("/users/|\\.json"); @SuppressWarnings("rawtypes") Enumeration entriesEnum = bundle.findEntries("users", "*.json", true); while (entriesEnum.hasMoreElements()) { Object entry = entriesEnum.nextElement(); URL jsonUrl = new URL(entry.toString()); String jsonFileName = jsonUrl.getFile(); String authorizableId = fileNamePattern.matcher(jsonFileName).replaceAll(""); Authorizable authorizable = userManager.getAuthorizable(authorizableId); if (authorizable != null) { applyJsonToAuthorizable(jsonUrl, authorizable, session); LOGGER.info("Initialized default authorizable {}", authorizableId); } else { LOGGER.warn("Configured default authorizable {} not found", authorizableId); } } } catch (RepositoryException e) { LOGGER.error("Could not configure default authorizables", e); } catch (IOException e) { LOGGER.error("Could not configure default authorizables", e); } finally { if (session != null) { session.logout(); } } }
/** * This will prepare <code>jcrPath</code> to have a storage node for the unique id. Call this * method on initialization time when no concurrent access will hapen. */ public void initializePath(String jcrPath) throws IDException { jcrPath = removeJCRPrefix(jcrPath); Session session; try { session = login(); Item item = session.getItem(jcrPath); if (!item.isNode()) { throw new IDException("Path '" + jcrPath + "' is a property (should be a node)"); } else { // check if it has a subnode containing a unique id Node parent = (Node) item; if (!parent.hasNode(ID_NODE)) { // create the id node if it does not exist yet parent.addNode(ID_NODE, ID_NODE_TYPE); session.save(); } } session.logout(); } catch (LoginException e) { throw new IDException("Login to repository failed.", e); } catch (PathNotFoundException e) { throw new IDException("Repository path does not exist: " + jcrPath, e); } catch (RepositoryException e) { throw new IDException("Cannot lookup repository path: " + jcrPath, e); } }
/** * Gets the spell suggestion. * * @param checkingWord the checking word * @param manageableRepository the manageable repository * @return the spell suggestion * @throws Exception the exception */ private String getSpellSuggestion(String checkingWord, ManageableRepository manageableRepository) throws Exception { // Retrieve spell suggestion in special way to avoid access denied exception String suggestion = null; Session session = null; try { session = manageableRepository.getSystemSession( manageableRepository.getConfiguration().getDefaultWorkspaceName()); QueryManager queryManager = session.getWorkspace().getQueryManager(); Query query = queryManager.createQuery( "SELECT rep:spellcheck() FROM nt:base WHERE jcr:path like '/' AND SPELLCHECK('" + checkingWord + "')", Query.SQL); RowIterator rows = query.execute().getRows(); Value value = rows.nextRow().getValue("rep:spellcheck()"); if (value != null) { suggestion = value.getString(); } } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } finally { if (session != null) session.logout(); } return suggestion; }
/** * Modify an existing datastream's content * * @param pathList * @param requestContentType Content-Type header * @param requestBodyStream Binary blob * @return 201 Created * @throws RepositoryException * @throws InvalidChecksumException */ @PUT @Timed public Response modifyContent( @PathParam("path") final List<PathSegment> pathList, @QueryParam("checksum") final String checksum, @HeaderParam("Content-Disposition") final String contentDisposition, @HeaderParam("Content-Type") final MediaType requestContentType, @ContentLocation final InputStream requestBodyStream, @Context final Request request, @Context final HttpServletResponse servletResponse) throws RepositoryException, InvalidChecksumException, URISyntaxException, ParseException { try { final String path = toPath(pathList); final MediaType contentType = getSimpleContentType(requestContentType); if (nodeService.exists(session, path)) { final Datastream ds = datastreamService.getDatastream(session, path); evaluateRequestPreconditions(request, ds); } LOGGER.debug("create Datastream {}", path); final URI checksumURI = checksumURI(checksum); final String originalFileName = originalFileName(contentDisposition); final Datastream datastream = datastreamService.createDatastream( session, path, contentType.toString(), originalFileName, requestBodyStream, checksumURI); final boolean isNew = datastream.isNew(); session.save(); versionService.nodeUpdated(datastream.getNode()); ResponseBuilder builder; if (isNew) { final HttpIdentifierTranslator subjects = new HttpIdentifierTranslator(session, FedoraNodes.class, uriInfo); builder = created(new URI(subjects.getSubject(datastream.getContentNode().getPath()).getURI())); } else { builder = noContent(); } addCacheControlHeaders(servletResponse, datastream); return builder.build(); } finally { session.logout(); } }
public void testLogin() throws RepositoryException { SimpleCredentials good = new SimpleCredentials("superuser", "".toCharArray()); try { Session session = repository.login(good, getWorkspace()); assertNotNull(session); session.logout(); } catch (LoginException e) { fail("Failed to login."); } try { Session session = repository.login(good, null); session.logout(); } catch (NoSuchWorkspaceException e) { fail("Failed to detect default workspace"); } }
/** Releases the session aquired in {@link #setUp()}. */ protected void tearDown() throws Exception { if (session != null) { session.logout(); session = null; } property = null; super.tearDown(); }
@Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { final Session session = createAdminSession(); try { String statusFilter = req.getParameter("status"); if (statusFilter == null) { // By default, only approved posts are returned. statusFilter = RelatedUgcNodeIndexerExtension.FIELD_STATE_APPROVED; } final List<Post> mltPosts = RelatedSearchUtil.getRelatedPosts( getResourceResolver(session), req.getParameter("q"), statusFilter, req.getParameter("resource-type"), req.getParameter("component-path"), MLT_FIELDS, Integer.valueOf(req.getParameter("max-results")), MIN_TERM_FREQ, MIN_DOC_FREQ); if (mltPosts == null) { return; } final JSONObject json = new JSONObject(); JSONObject match; final List<JSONObject> matches = new ArrayList<JSONObject>(); for (final Post p : mltPosts) { match = new JSONObject(); match.put("subject", xssProtectionService.protectFromXSS(p.getSubject())); match.put("replyCount", p.getRepliesCount()); match.put("url", p.getUrl()); match.put("id", p.getId()); match.put("created", p.getCreated()); match.put("createdBy", xssProtectionService.protectFromXSS(p.getCreatedBy().getFullName())); matches.add(match); } json.put("mlt", matches); resp.setContentType("application/json"); resp.getWriter().write(json.toString()); } catch (final Exception e) { throw new ServletException(e); } finally { if (session != null) { session.logout(); } } }
/** * Create a link to a file. There is no need to call a session.save, the change is persistent. * * @param fileNode The node that represents the file. This node has to be retrieved via the normal * user his {@link Session session}. If the userID equals {@link UserConstants.ANON_USERID} an * AccessDeniedException will be thrown. * @param linkPath The absolute path in JCR where the link should be placed. * @param slingRepository The {@link SlingRepository} to use to login as an administrative. * @return The newly created node. * @throws AccessDeniedException When the user is anonymous. * @throws RepositoryException Something else went wrong. */ public static boolean createLink(Node fileNode, String linkPath, SlingRepository slingRepository) throws AccessDeniedException, RepositoryException { Session session = fileNode.getSession(); String userId = session.getUserID(); if (UserConstants.ANON_USERID.equals(userId)) { throw new AccessDeniedException(); } boolean hasMixin = JcrUtils.hasMixin(fileNode, REQUIRED_MIXIN) && fileNode.canAddMixin(REQUIRED_MIXIN); // If the fileNode doesn't have the required referenceable mixin, we need to set it. if (!hasMixin) { // The required mixin is not on the node. // Set it. Session adminSession = null; try { adminSession = slingRepository.loginAdministrative(null); // Grab the node via the adminSession String path = fileNode.getPath(); Node adminFileNode = (Node) adminSession.getItem(path); if (!hasMixin) { adminFileNode.addMixin(REQUIRED_MIXIN); } if (adminSession.hasPendingChanges()) { adminSession.save(); } } finally { if (adminSession != null) { adminSession.logout(); } } } // Now that the file is referenceable, it has a uuid. // Use it for the link. // Grab the (updated) node via the user's session id. fileNode = (Node) session.getItem(fileNode.getPath()); // Create the link Node linkNode = JcrUtils.deepGetOrCreateNode(session, linkPath); if (!"sling:Folder".equals(linkNode.getPrimaryNodeType().getName())) { // sling folder allows single and multiple properties, no need for the mixin. if (linkNode.canAddMixin(REQUIRED_MIXIN)) { linkNode.addMixin(REQUIRED_MIXIN); } } linkNode.setProperty(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, RT_SAKAI_LINK); linkNode.setProperty(SAKAI_LINK, fileNode.getIdentifier()); // Save link. if (session.hasPendingChanges()) { session.save(); } return true; }
private List<Node> getLastEditedNode(String noOfItem, String showGadgetWs) throws Exception { if (showGadgetWs != null && showGadgetWs.length() > 0) { show_gadget = Boolean.parseBoolean(showGadgetWs); } ArrayList<Node> lstNode = new ArrayList<Node>(); StringBuffer bf = new StringBuffer(1024); List<String> lstNodeType = templateService.getDocumentTemplates(); if (lstNodeType != null) { for (String nodeType : lstNodeType) { bf.append("(") .append(JCR_PRIMARYTYPE) .append("=") .append("'") .append(nodeType) .append("'") .append(")") .append(" OR "); } } if (bf.length() == 1) return null; bf.delete(bf.lastIndexOf("OR") - 1, bf.length()); if (noOfItem == null || noOfItem.trim().length() == 0) noOfItem = String.valueOf(NO_PER_PAGE); String queryStatement = StringUtils.replace(QUERY_STATEMENT, "$0", NT_BASE); queryStatement = StringUtils.replace(queryStatement, "$1", bf.toString()); queryStatement = StringUtils.replace(queryStatement, "$2", DATE_MODIFIED); ManageableRepository manageableRepository = repositoryService.getCurrentRepository(); try { String[] workspaces = manageableRepository.getWorkspaceNames(); List<String> lstWorkspace = new ArrayList<String>(); // Arrays.asList() return fixed size list; lstWorkspace.addAll(Arrays.asList(workspaces)); if (!show_gadget && lstWorkspace.contains(GADGET)) { lstWorkspace.remove(GADGET); } SessionProvider provider = WCMCoreUtils.createAnonimProvider(); QueryImpl query = null; Session session = null; QueryResult queryResult = null; QueryManager queryManager = null; for (String workspace : lstWorkspace) { session = provider.getSession(workspace, manageableRepository); queryManager = session.getWorkspace().getQueryManager(); query = (QueryImpl) queryManager.createQuery(queryStatement, Query.SQL); query.setLimit(Integer.parseInt(noOfItem)); query.setOffset(0); queryResult = query.execute(); puttoList(lstNode, queryResult.getNodes()); session.logout(); } } catch (RepositoryException e) { if (LOG.isErrorEnabled()) { LOG.error("Exception when execute SQL " + queryStatement, e); } } return lstNode; }