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();
    }
  }
  /** {@inheritDoc} */
  public void watchDocument(Node documentNode, String userName, int notifyType) throws Exception {
    Session session = documentNode.getSession();
    Value newWatcher = session.getValueFactory().createValue(userName);
    if (!documentNode.isNodeType(EXO_WATCHABLE_MIXIN)) {
      documentNode.addMixin(EXO_WATCHABLE_MIXIN);
      if (notifyType == NOTIFICATION_BY_EMAIL) {
        documentNode.setProperty(EMAIL_WATCHERS_PROP, new Value[] {newWatcher});
        documentNode.save();
        session.save();
        EmailNotifyListener listener = new EmailNotifyListener(documentNode);
        observeNode(documentNode, listener);
      }
      session.save();
    } else {
      List<Value> watcherList = new ArrayList<Value>();
      if (notifyType == NOTIFICATION_BY_EMAIL) {
        if (documentNode.hasProperty(EMAIL_WATCHERS_PROP)) {
          for (Value watcher : documentNode.getProperty(EMAIL_WATCHERS_PROP).getValues()) {
            watcherList.add(watcher);
          }
          watcherList.add(newWatcher);
        }

        documentNode.setProperty(
            EMAIL_WATCHERS_PROP, watcherList.toArray(new Value[watcherList.size()]));
        documentNode.save();
      }
      session.save();
    }
  }
Beispiel #3
0
  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();
  }
Beispiel #4
0
  /**
   * 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;
  }
  @Override
  public void removeMessageAfterSent() throws Exception {
    final boolean stats =
        NotificationContextFactory.getInstance().getStatistics().isStatisticsEnabled();
    boolean created = NotificationSessionManager.createSystemProvider();
    SessionProvider sProvider = NotificationSessionManager.getSessionProvider();

    try {
      Node notificationHome = getNotificationHomeNode(sProvider, workspace);
      Session session = notificationHome.getSession();
      // remove all
      Set<String> listPaths = removeByCallBack.get(REMOVE_ALL);
      removeByCallBack.remove(REMOVE_ALL);
      if (listPaths != null && listPaths.size() > 0) {
        for (String nodePath : listPaths) {
          try {
            session.getItem(nodePath).remove();
            // record entity delete here
            if (stats) {
              NotificationContextFactory.getInstance()
                  .getStatisticsCollector()
                  .deleteEntity(NTF_MESSAGE);
            }

            LOG.debug("Remove NotificationMessage " + nodePath);
          } catch (Exception e) {
            LOG.warn(
                "Failed to remove node of NotificationMessage " + nodePath + "\n" + e.getMessage());
            LOG.debug("Remove NotificationMessage " + nodePath, e);
          }
        }
        session.save();
      }

      listPaths = removeByCallBack.get(REMOVE_DAILY);
      if (listPaths != null && listPaths.size() > 0) {
        for (String nodePath : listPaths) {
          try {
            Item item = session.getItem(nodePath);
            if (item.isNode()) {
              Node node = (Node) item;
              node.setProperty(NTF_SEND_TO_DAILY, new String[] {""});
            }
            LOG.debug("Remove SendToDaily property " + nodePath);
          } catch (Exception e) {
            LOG.warn(
                "Failed to remove SendToDaily property of " + nodePath + "\n" + e.getMessage());
            LOG.debug("Remove SendToDaily property " + nodePath, e);
          }
        }
        session.save();
      }
    } catch (Exception e) {
      LOG.warn("Failed to remove message after sent email notification", e);
    } finally {
      NotificationSessionManager.closeSessionProvider(created);
    }
  }
  public void afterSuite() throws Exception {
    for (int i = 0; i < NODE_COUNT; i++) {
      root.getNode("node" + i).remove();
      session.save();
    }

    root.remove();
    session.save();
  }
  /**
   * Creates the node strucure is it not already created
   *
   * @throws ServletException if error
   */
  private void createNodeStructure() throws ServletException {

    try {

      Node rootNode = session.getRootNode();
      Node admin = null;

      // creates the root node of the system if not already created
      if (!rootNode.hasNode("blogRoot")) {
        Node blogRoot = rootNode.addNode("blogRoot", "nt:folder");

        // Adding the admin user
        admin = blogRoot.addNode("admin", "blog:user");
        admin.setProperty("blog:nickname", "admin");
        admin.setProperty("blog:email", "*****@*****.**");
        admin.setProperty("blog:password", "admin");
        session.save();

        // Adding the guest user
        Node guest = blogRoot.addNode("guest", "blog:user");
        guest.setProperty("blog:nickname", "guest");

        // These properties will never be used by the system
        guest.setProperty("blog:email", "*****@*****.**");
        guest.setProperty("blog:password", "guest");
      }

      // Created the library node if not already created
      if (!rootNode.hasNode("library")) {
        rootNode.addNode("library", "nt:folder");
      }

      if (!rootNode.hasNode("wiki")) {
        Node wiki = rootNode.addNode("wiki", "nt:folder");
        Node frontPage = wiki.addNode("frontPage", "wiki:wikiPage");

        frontPage.setProperty("wiki:title", "Front Page");
        frontPage.setProperty("wiki:content", "Type the content here");
        frontPage.setProperty("wiki:savedBy", admin.getUUID());
      }

      session.save();

      log("JACKRABBIT-JCR-DEMO: Node Structure created ...");

    } catch (RepositoryException e) {
      throw new ServletException("Failed to create node structure ", e);
    }
  }
  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;
  }
  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();
    }
  }
 /*
  * (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();
     }
   }
 }
Beispiel #11
0
  /**
   * Create an anonymous DS with a newly minted name and content from request body
   *
   * @param pathList
   * @throws RepositoryException
   */
  @POST
  public Response create(
      @PathParam("path") final List<PathSegment> pathList,
      @QueryParam("checksumType") final String checksumType,
      @QueryParam("checksum") final String checksum,
      @HeaderParam("Content-Type") final MediaType requestContentType,
      final InputStream requestBodyStream)
      throws IOException, InvalidChecksumException, RepositoryException {
    final MediaType contentType =
        requestContentType != null ? requestContentType : APPLICATION_OCTET_STREAM_TYPE;

    String path = toPath(pathList);
    if (path.endsWith("/fcr:new")) {
      logger.debug("Creating a new unnamed object");
      final String dsid = pidMinter.mintPid();
      path = path.replaceFirst("\\/fcr\\:new$", "/" + dsid);
    }

    logger.debug("create Datastream {}", path);
    final Session session = getAuthenticatedSession();
    try {
      datastreamService.createDatastreamNode(
          session, path, contentType.toString(), requestBodyStream, checksumType, checksum);
    } finally {
      session.save();
    }
    return created(uriInfo.getBaseUriBuilder().path("/rest" + path).build()).build();
  }
  /**
   * 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();
    }
  }
  @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();
    }
  }
 @Override
 protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
     throws ServletException, IOException {
   String paramUser = request.getParameter(SiteService.SiteEvent.USER);
   logger.info("Request to add user " + paramUser);
   String paramGroup = "";
   try {
     Node requestedNode = request.getResource().adaptTo(Node.class);
     Value[] authorizables = requestedNode.getProperty("sakai:authorizables").getValues();
     paramGroup = authorizables[1].getString();
     request.setAttribute(JoinRequestConstants.PARAM_SITENODE, requestedNode);
     Session session = slingRepository.loginAdministrative(null);
     UserManager userManager = AccessControlUtil.getUserManager(session);
     Authorizable userAuth = userManager.getAuthorizable(paramUser);
     Group groupAuth = (Group) userManager.getAuthorizable(paramGroup);
     if (siteJoinIsAuthorized(request)) {
       groupAuth.addMember(userAuth);
       logger.info(paramUser + " added as member of group " + paramGroup);
     } else {
       response.sendError(403, "Not authorized to add member to site.");
     }
     if (session.hasPendingChanges()) {
       session.save();
     }
   } catch (Exception e) {
     response.sendError(500, e.getMessage());
   }
 }
 private Node createEmptyCache(HtmlLibrary library, String root, Session session) {
   Node node = null;
   // this.lock.writeLock().lock();
   try {
     Node swap =
         JcrUtils.getOrCreateByPath(
             root,
             JcrResourceConstants.NT_SLING_FOLDER,
             JcrResourceConstants.NT_SLING_FOLDER,
             session,
             true);
     node = swap.addNode(getLibraryName(library), JcrConstants.NT_FILE);
     swap = node.addNode(JcrConstants.JCR_CONTENT, JcrConstants.NT_RESOURCE);
     swap.setProperty(JcrConstants.JCR_LASTMODIFIED, 0L);
     swap.setProperty(JcrConstants.JCR_MIMETYPE, library.getType().contentType);
     swap.setProperty(
         JcrConstants.JCR_DATA,
         session.getValueFactory().createBinary(new ByteArrayInputStream(new byte[0])));
     session.save();
     // this.lock.writeLock().unlock();
   } catch (RepositoryException re) {
     log.debug(re.getMessage());
   }
   return node;
 }
 private Node populateCache(HtmlLibrary library, String root, Session session) {
   Node cacheNode = null;
   try {
     String libPath = (new StringBuilder(CACHE_PATH).append(library.getPath(false))).toString();
     Node src = JcrUtils.getNodeIfExists(libPath, session);
     cacheNode = session.getNode(root);
     if (null != src) {
       // this.lock.readLock().lock();
       // produced closure compiled src
       String compiled = compile(library, this.optimization, JcrUtils.readFile(src));
       // this.lock.readLock().unlock();
       // this.lock.writeLock().lock();
       //
       JcrUtils.putFile(
           cacheNode.getParent(),
           getLibraryName(library),
           library.getType().contentType,
           IOUtils.toInputStream(compiled, "UTF-8"));
       session.save();
       // this.lock.writeLock().unlock();
     }
   } catch (RepositoryException re) {
     log.debug(re.getMessage());
   } catch (IOException ioe) {
     log.debug(ioe.getMessage());
   }
   return cacheNode;
 }
 @Test
 public void addObjectNew() throws Exception {
   store.addObject(new FedoraObject().pid("test:new-object"));
   Assert.assertTrue(jcr.nodeExists("/ca/88/test_new-object"));
   jcr.removeItem("/ca/88/test_new-object");
   jcr.save();
 }
  /** 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();
      }
    }
  }
 @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);
   }
 }
  @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);
    }
  }
  /** Test if the removeExisting-flag removes an existing node in case of uuid conflict. */
  public void testWorkspaceRestoreWithRemoveExistingJcr2()
      throws NotExecutableException, RepositoryException {
    // create version for parentNode of childNode
    superuser
        .getWorkspace()
        .clone(
            workspaceName, wVersionableChildNode.getPath(), wVersionableChildNode.getPath(), false);
    Version parentV =
        versionableNode
            .getSession()
            .getWorkspace()
            .getVersionManager()
            .checkin(versionableNode.getPath());

    // move child node in order to produce the uuid conflict
    String newChildPath = wVersionableNode2.getPath() + "/" + wVersionableChildNode.getName();
    wSuperuser.move(wVersionableChildNode.getPath(), newChildPath);
    wSuperuser.save();

    // restore the parent with removeExisting == true >> moved child node
    // must be removed.
    wSuperuser.getWorkspace().getVersionManager().restore(new Version[] {parentV}, true);
    if (wSuperuser.itemExists(newChildPath)) {
      fail(
          "Workspace.restore(Version[], boolean) with the boolean flag set to true, must remove the existing node in case of Uuid conflict.");
    }
  }
  /**
   * 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);
    }
  }
  /**
   * Tests if restoring the <code>Version</code> of an existing node throws an <code>
   * ItemExistsException</code> if removeExisting is set to FALSE.
   */
  public void testWorkspaceRestoreWithUUIDConflictJcr2()
      throws RepositoryException, NotExecutableException {
    try {
      // Verify that nodes used for the test are indeed versionable
      NodeDefinition nd = wVersionableNode.getDefinition();
      if (nd.getOnParentVersion() != OnParentVersionAction.COPY
          && nd.getOnParentVersion() != OnParentVersionAction.VERSION) {
        throw new NotExecutableException("Nodes must be versionable in order to run this test.");
      }

      VersionManager versionManager =
          wVersionableNode.getSession().getWorkspace().getVersionManager();
      String path = wVersionableNode.getPath();
      Version v = versionManager.checkin(path);
      versionManager.checkout(path);
      wSuperuser.move(
          wVersionableChildNode.getPath(),
          wVersionableNode2.getPath() + "/" + wVersionableChildNode.getName());
      wSuperuser.save();
      wSuperuser.getWorkspace().getVersionManager().restore(new Version[] {v}, false);

      fail(
          "Node.restore( Version, boolean ): An ItemExistsException must be thrown if the node to be restored already exsits and removeExisting was set to false.");
    } catch (ItemExistsException e) {
      // success
    }
  }
Beispiel #24
0
  @Override
  public void deleteDirectory(long companyId, long repositoryId, String dirName)
      throws PortalException {

    Session session = null;

    try {
      session = JCRFactoryUtil.createSession();

      Node rootNode = getRootNode(session, companyId);

      Node repositoryNode = getFolderNode(rootNode, repositoryId);

      Node dirNode = repositoryNode.getNode(dirName);

      dirNode.remove();

      session.save();
    } catch (PathNotFoundException pnfe) {
      throw new NoSuchDirectoryException(dirName);
    } catch (RepositoryException re) {
      String message = GetterUtil.getString(re.getMessage());

      if (message.contains("failed to resolve path")) {
        throw new NoSuchDirectoryException(dirName);
      } else {
        throw new PortalException(re);
      }
    } finally {
      JCRFactoryUtil.closeSession(session);
    }
  }
Beispiel #25
0
  /**
   * 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();
    }
  }
Beispiel #26
0
  @Override
  public void updateFile(
      long companyId, long repositoryId, String fileName, String versionLabel, InputStream is)
      throws PortalException, SystemException {

    Session session = null;

    try {
      session = JCRFactoryUtil.createSession();

      Workspace workspace = session.getWorkspace();

      VersionManager versionManager = workspace.getVersionManager();

      Node rootNode = getRootNode(session, companyId);

      Node repositoryNode = getFolderNode(rootNode, repositoryId);

      if (fileName.contains(StringPool.SLASH)) {
        String path = fileName.substring(0, fileName.lastIndexOf(StringPool.SLASH));

        fileName = fileName.substring(path.length() + 1);

        repositoryNode = getFolderNode(repositoryNode, path);
      }

      Node fileNode = repositoryNode.getNode(fileName);

      Node contentNode = fileNode.getNode(JCRConstants.JCR_CONTENT);

      versionManager.checkout(contentNode.getPath());

      contentNode.setProperty(JCRConstants.JCR_MIME_TYPE, "text/plain");

      ValueFactory valueFactory = session.getValueFactory();

      Binary binary = valueFactory.createBinary(is);

      contentNode.setProperty(JCRConstants.JCR_DATA, binary);

      contentNode.setProperty(JCRConstants.JCR_LAST_MODIFIED, Calendar.getInstance());

      session.save();

      Version version = versionManager.checkin(contentNode.getPath());

      VersionHistory versionHistory = versionManager.getVersionHistory(contentNode.getPath());

      versionHistory.addVersionLabel(
          version.getName(), versionLabel, PropsValues.DL_STORE_JCR_MOVE_VERSION_LABELS);
    } catch (PathNotFoundException pnfe) {
      throw new NoSuchFileException(
          "{fileName=" + fileName + ", versionLabel=" + versionLabel + "}");
    } catch (RepositoryException re) {
      throw new SystemException(re);
    } finally {
      JCRFactoryUtil.closeSession(session);
    }
  }
 /** {@inheritDoc} */
 public void removeTemplate(
     String portletName, String category, String templateName, SessionProvider sessionProvider)
     throws Exception {
   Node templateNode = getTemplateByName(portletName, category, templateName, sessionProvider);
   Session session = templateNode.getSession();
   templateNode.remove();
   session.save();
 }
Beispiel #28
0
 @Test
 public void testCreatedObject() throws RepositoryException {
   containerService.findOrCreate(session, "/testObject");
   session.save();
   session.logout();
   session = repo.login();
   final Container obj = containerService.findOrCreate(session, "/testObject");
   assertNotNull("Couldn't find object!", obj);
 }
  public void setRoleBindings(
      Session session, ITenant tenant, String runtimeRoleName, List<String> logicalRoleNames)
      throws NamespaceException, RepositoryException {
    if (tenant == null) {
      tenant = JcrTenantUtils.getTenant(runtimeRoleName, false);
      runtimeRoleName = getPrincipalName(runtimeRoleName);
    }

    if (!TenantUtils.isAccessibleTenant(tenant)) {
      throw new NotFoundException("Tenant " + tenant.getId() + " not found");
    }

    PentahoJcrConstants pentahoJcrConstants = new PentahoJcrConstants(session);
    final String phoNsPrefix =
        session.getNamespacePrefix(PentahoJcrConstants.PHO_NS) + ":"; // $NON-NLS-1$
    final String onlyPentahoPattern = phoNsPrefix + "*"; // $NON-NLS-1$
    Node runtimeRolesFolderNode = getRuntimeRolesFolderNode(session, tenant);
    NodeIterator runtimeRoleNodes = runtimeRolesFolderNode.getNodes(onlyPentahoPattern);
    int i = 0;
    while (runtimeRoleNodes.hasNext()) {
      runtimeRoleNodes.nextNode();
      i++;
    }
    if (i == 0) {
      // no bindings setup yet; install bootstrap bindings; bootstrapRoleBindings will now no longer
      // be
      // consulted
      for (Map.Entry<String, List<String>> entry : bootstrapRoleBindings.entrySet()) {
        JcrRoleAuthorizationPolicyUtils.internalSetBindings(
            pentahoJcrConstants,
            runtimeRolesFolderNode,
            entry.getKey(),
            entry.getValue(),
            phoNsPrefix);
      }
    }
    if (!isImmutable(runtimeRoleName)) {
      JcrRoleAuthorizationPolicyUtils.internalSetBindings(
          pentahoJcrConstants,
          runtimeRolesFolderNode,
          runtimeRoleName,
          logicalRoleNames,
          phoNsPrefix);
    } else {
      throw new RuntimeException(
          Messages.getInstance()
              .getString(
                  "JcrRoleAuthorizationPolicyRoleBindingDao.ERROR_0001_ATTEMPT_MOD_IMMUTABLE",
                  runtimeRoleName)); //$NON-NLS-1$
    }
    session.save();
    Assert.isTrue(NodeHelper.hasNode(runtimeRolesFolderNode, phoNsPrefix, runtimeRoleName));

    // update cache
    String roleId = tenantedRoleNameUtils.getPrincipleId(tenant, runtimeRoleName);
    cacheManager.putInRegionCache(LOGICAL_ROLE_BINDINGS_REGION, roleId, logicalRoleNames);
  }
Beispiel #30
0
  @Override
  public void addFile(long companyId, long repositoryId, String fileName, InputStream is)
      throws PortalException, SystemException {

    Session session = null;

    try {
      session = JCRFactoryUtil.createSession();

      Workspace workspace = session.getWorkspace();

      VersionManager versionManager = workspace.getVersionManager();

      Node rootNode = getRootNode(session, companyId);

      Node repositoryNode = getFolderNode(rootNode, repositoryId);

      if (fileName.contains(StringPool.SLASH)) {
        String path = fileName.substring(0, fileName.lastIndexOf(StringPool.SLASH));

        fileName = fileName.substring(path.length() + 1);

        repositoryNode = getFolderNode(repositoryNode, path);
      }

      if (repositoryNode.hasNode(fileName)) {
        throw new DuplicateFileException(fileName);
      } else {
        Node fileNode = repositoryNode.addNode(fileName, JCRConstants.NT_FILE);

        Node contentNode = fileNode.addNode(JCRConstants.JCR_CONTENT, JCRConstants.NT_RESOURCE);

        contentNode.addMixin(JCRConstants.MIX_VERSIONABLE);
        contentNode.setProperty(JCRConstants.JCR_MIME_TYPE, "text/plain");

        ValueFactory valueFactory = session.getValueFactory();

        Binary binary = valueFactory.createBinary(is);

        contentNode.setProperty(JCRConstants.JCR_DATA, binary);

        contentNode.setProperty(JCRConstants.JCR_LAST_MODIFIED, Calendar.getInstance());

        session.save();

        Version version = versionManager.checkin(contentNode.getPath());

        VersionHistory versionHistory = versionManager.getVersionHistory(contentNode.getPath());

        versionHistory.addVersionLabel(version.getName(), VERSION_DEFAULT, false);
      }
    } catch (RepositoryException re) {
      throw new SystemException(re);
    } finally {
      JCRFactoryUtil.closeSession(session);
    }
  }