/**
   * Registors the custome node types for the jackrabbit-jcr-demo application from a given CND file.
   * Location of the CND file is given as an initial parameter
   *
   * @throws ServletException is thrown when registration not possible.
   */
  private void registerCustomNodeTypes() throws ServletException {

    // location of the CND file is kept as a servelt init parameter in the web.xml
    String cndPath = getInitParameter("cnd.path");
    String ocmPath = getInitParameter("ocm.path");

    try {

      Workspace ws = session.getWorkspace();

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

      // Registors the custom node types and namespaces
      InputStream inputStream = getServletContext().getResourceAsStream(cndPath);
      ntTypeMgr.registerNodeTypes(inputStream, JackrabbitNodeTypeManager.TEXT_X_JCR_CND, true);

      InputStream nodeTypeStream = getServletContext().getResourceAsStream(ocmPath);
      ntTypeMgr.registerNodeTypes(nodeTypeStream, JackrabbitNodeTypeManager.TEXT_XML, true);

      // Register a namespace to be used with in the program
      // ex. for a username "nandana" we can use demo:nandana
      NamespaceRegistryImpl nsReg =
          (NamespaceRegistryImpl) session.getWorkspace().getNamespaceRegistry();
      nsReg.safeRegisterNamespace("demo", "http://code.google.com/p/jackrabbit-jcr-demo");
      nsReg.safeRegisterNamespace("ocm", "http://jackrabbit.apache.org/ocm");

      log("JACKRABBIT-JCR-DEMO: Custom Node types registered  ...");

    } catch (RepositoryException e) {
      throw new ServletException("Failed to registor node types", e);
    } catch (IOException e) {
      throw new ServletException("Error occured while accessing the file" + cndPath, e);
    }
  }
  /** TODO: Not fully implemented SEE: DirectSearchModule.getKeywordMapLive() */
  public static synchronized void refreshUserDocKeywords(Session session)
      throws RepositoryException {
    log.info("refreshUserDocKeywords({})", session);
    String statement = "/jcr:root/" + Repository.ROOT + "/element(*,okm:document)";

    try {
      Workspace workspace = session.getWorkspace();
      QueryManager queryManager = workspace.getQueryManager();
      Query query = queryManager.createQuery(statement, Query.XPATH);
      javax.jcr.query.QueryResult qResult = query.execute();
      Map<String, Set<String>> userDocKeywords = new HashMap<String, Set<String>>();

      for (NodeIterator nit = qResult.getNodes(); nit.hasNext(); ) {
        Node docNode = nit.nextNode();
        Value[] keywords = docNode.getProperty(Property.KEYWORDS).getValues();
        Set<String> keywordSet = new HashSet<String>();

        for (int i = 0; i < keywords.length; i++) {
          keywordSet.add(keywords[i].getString());
        }

        userDocKeywords.put(docNode.getUUID(), keywordSet);
      }

      // userDocumentKeywordsMgr.put(session.getUserID(), userDocKeywords);
    } catch (javax.jcr.RepositoryException e) {
      log.error(e.getMessage(), e);
      throw new RepositoryException(e.getMessage(), e);
    }

    log.info("refreshUserDocKeywords: void");
  }
Esempio n. 3
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);
    }
  }
Esempio n. 4
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);
    }
  }
  /**
   * This method registers the listener <code> org.apache.jackrabbit.demo.blog.model.AlertManager
   * </code> with the default workspace. This listener listens to events of adding new comments to
   * blog entries.
   *
   * @throws RepositoryException if an error occur in the repository
   */
  private void registerListeners() throws RepositoryException {

    Workspace ws = session.getWorkspace();
    ObservationManager observationMgr = ws.getObservationManager();
    AlertManager alertMgr = new AlertManager(repository);
    observationMgr.addEventListener(
        alertMgr, Event.NODE_ADDED, "/blogRoot", true, null, null, false);

    log("JACKRABBIT-JCR-DEMO: Listeners registered ...");
  }
Esempio n. 6
0
  /** Get keyword map */
  private Map<String, Integer> getKeywordMapLive(String token, List<String> filter)
      throws RepositoryException, DatabaseException {
    log.debug("getKeywordMapLive({}, {})", token, filter);
    String statement =
        "/jcr:root//*[@jcr:primaryType eq 'okm:document' or @jcr:primaryType eq 'okm:mail' or @jcr:primaryType eq 'okm:folder']";
    HashMap<String, Integer> cloud = new HashMap<String, Integer>();
    Session session = null;

    try {
      if (token == null) {
        session = JCRUtils.getSession();
      } else {
        session = JcrSessionManager.getInstance().get(token);
      }

      Workspace workspace = session.getWorkspace();
      QueryManager queryManager = workspace.getQueryManager();
      Query query = queryManager.createQuery(statement, Query.XPATH);
      javax.jcr.query.QueryResult qResult = query.execute();

      for (NodeIterator nit = qResult.getNodes(); nit.hasNext(); ) {
        Node doc = nit.nextNode();
        Value[] keywordsValue = doc.getProperty(com.openkm.bean.Property.KEYWORDS).getValues();
        ArrayList<String> keywordCollection = new ArrayList<String>();

        for (int i = 0; i < keywordsValue.length; i++) {
          keywordCollection.add(keywordsValue[i].getString());
        }

        if (filter != null && keywordCollection.containsAll(filter)) {
          for (Iterator<String> it = keywordCollection.iterator(); it.hasNext(); ) {
            String keyword = it.next();

            if (!filter.contains(keyword)) {
              Integer occurs = cloud.get(keyword) != null ? cloud.get(keyword) : 0;
              cloud.put(keyword, occurs + 1);
            }
          }
        }
      }
    } catch (javax.jcr.RepositoryException e) {
      log.error(e.getMessage(), e);
      throw new RepositoryException(e.getMessage(), e);
    } finally {
      if (token == null) JCRUtils.logout(session);
    }

    log.debug("getKeywordMapLive: {}", cloud);
    return cloud;
  }
  @Before
  public void setup() throws RepositoryException {
    initMocks(this);

    when(mockSession.getWorkspace()).thenReturn(mockWorkspace);
    when(mockWorkspace.getNamespaceRegistry()).thenReturn(mockNamespaceRegistry);
    when(mockNamespaceRegistry.getPrefixes()).thenReturn(new String[] {});

    testData.session(mockSession);
    testData.topic(createURI("test:subject"));
    testData.concat(
        new Triple(
            createURI("test:subject"), createURI("test:predicate"), createLiteral("test:object")));
    testData.concat(
        new Triple(
            createURI("test:subject"),
            createURI(getRDFNamespaceForJcrNamespace(JCR_NAMESPACE) + "primaryType"),
            createLiteral("nt:file")));

    testData2.session(mockSession);
    testData2.topic(createURI("test:subject2"));
    testData2.concat(
        new Triple(
            createURI("test:subject2"),
            createURI(getRDFNamespaceForJcrNamespace(JCR_NAMESPACE) + "mixinTypes"),
            createLiteral("childOf:ntFile")));
    final UriInfo info = Mockito.mock(UriInfo.class);
    setField(testProvider, "uriInfo", info);
  }
 @Before
 public void setUp() throws RepositoryException {
   initMocks(this);
   testProvider.registerMimeTypes();
   when(mockSession.getWorkspace()).thenReturn(mockWorkspace);
   when(mockWorkspace.getNamespaceRegistry()).thenReturn(mockNamespaceRegistry);
   when(mockNamespaceRegistry.getPrefixes()).thenReturn(new String[] {});
 }
  @Test
  public void testGet()
      throws VersionException, UnsupportedRepositoryOperationException, InvalidItemStateException,
          LockException, RepositoryException, IOException, ServletException {
    SlingHttpServletRequest request = createNiceMock(SlingHttpServletRequest.class);
    SlingHttpServletResponse response = createNiceMock(SlingHttpServletResponse.class);
    Resource resource = createNiceMock(Resource.class);
    Node node = createNiceMock(Node.class);
    Version version = createNiceMock(Version.class);
    PropertyIterator propertyIterator = createNiceMock(PropertyIterator.class);
    VersionHistory versionHistory = createNiceMock(VersionHistory.class);
    VersionIterator versionIterator = createNiceMock(VersionIterator.class);
    Node versionNode = createNiceMock(Node.class);
    Session session = createNiceMock(Session.class);
    Workspace workspace = createNiceMock(Workspace.class);
    VersionManager versionManager = createNiceMock(VersionManager.class);

    EasyMock.expect(request.getResource()).andReturn(resource).anyTimes();
    EasyMock.expect(resource.adaptTo(Node.class)).andReturn(node).anyTimes();
    PrintWriter pw = new PrintWriter(new ByteArrayOutputStream());
    EasyMock.expect(response.getWriter()).andReturn(pw).anyTimes();

    EasyMock.expect(node.getSession()).andReturn(session);
    EasyMock.expect(session.getWorkspace()).andReturn(workspace);
    EasyMock.expect(workspace.getVersionManager()).andReturn(versionManager);
    EasyMock.expect(versionManager.getVersionHistory("/foo")).andReturn(versionHistory);
    EasyMock.expect(node.getPath()).andReturn("/foo").anyTimes();
    EasyMock.expect(versionHistory.getAllVersions()).andReturn(versionIterator);
    EasyMock.expect(versionIterator.getSize()).andReturn(2L);
    EasyMock.expect(versionIterator.hasNext()).andReturn(true);
    EasyMock.expect(versionIterator.nextVersion()).andReturn(version);
    EasyMock.expect(versionIterator.hasNext()).andReturn(true);
    EasyMock.expect(versionIterator.nextVersion()).andReturn(version);

    EasyMock.expect(version.getName()).andReturn("NameVersioNode").anyTimes();
    EasyMock.expect(version.getNode(JcrConstants.JCR_FROZENNODE)).andReturn(versionNode).anyTimes();
    EasyMock.expect(version.getProperties()).andReturn(propertyIterator).anyTimes();
    EasyMock.expect(propertyIterator.hasNext()).andReturn(false).anyTimes();

    replay();

    listVersionsServlet.doGet(request, response);
    verify();
  }
Esempio n. 10
0
  @Override
  public void deleteFile(long companyId, long repositoryId, String fileName, String versionLabel)
      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);

      Node fileNode = repositoryNode.getNode(fileName);

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

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

      if (!versionHistory.hasVersionLabel(versionLabel)) {
        throw new NoSuchFileException(
            "{fileName=" + fileName + ", versionLabel=" + versionLabel + "}");
      }

      Version version = versionHistory.getVersionByLabel(versionLabel);

      versionManager.restore(version.getPredecessors()[0], true);

      versionHistory.removeVersion(version.getName());

      session.save();
    } catch (PathNotFoundException pnfe) {
      throw new NoSuchFileException(
          "{fileName=" + fileName + ", versionLabel=" + versionLabel + "}");
    } catch (RepositoryException re) {
      throw new SystemException(re);
    } finally {
      JCRFactoryUtil.closeSession(session);
    }
  }
Esempio n. 11
0
  /**
   * {@inheritDoc}
   *
   * @see
   *     org.modeshape.graph.request.processor.RequestProcessor#process(org.modeshape.graph.request.CopyBranchRequest)
   */
  @Override
  public void process(CopyBranchRequest request) {
    if (request == null) return;
    try {
      String fromWorkspaceName = request.fromWorkspace();
      String intoWorkspaceName = request.intoWorkspace();
      boolean sameWorkspace = fromWorkspaceName.equals(intoWorkspaceName);
      Workspace fromWorkspace = workspaceFor(fromWorkspaceName);
      Workspace intoWorkspace = sameWorkspace ? fromWorkspace : workspaceFor(intoWorkspaceName);
      Node sourceNode = fromWorkspace.node(request.from());
      Node targetNode = fromWorkspace.node(request.into());
      Location fromLocation = fromWorkspace.locationFor(sourceNode);

      // Calculate the source and destination paths ...
      String srcAbsPath = sourceNode.getPath();
      String destAbsPath = targetNode.getPath();
      String copyName =
          request.desiredName() != null
              ? intoWorkspace.stringFor(request.desiredName())
              : sourceNode.getName();
      destAbsPath += '/' + copyName;

      // Perform the copy ...
      javax.jcr.Workspace workspace = intoWorkspace.session().getWorkspace();
      if (sameWorkspace) {
        workspace.copy(srcAbsPath, destAbsPath);
      } else {
        workspace.copy(fromWorkspaceName, srcAbsPath, destAbsPath);
      }

      // Find the actual location of the result of the node ...
      Node last = null;
      for (NodeIterator iter = targetNode.getNodes(copyName); iter.hasNext(); ) {
        last = iter.nextNode();
      }
      Location intoLocation = intoWorkspace.locationFor(last);
      request.setActualLocations(fromLocation, intoLocation);
    } catch (Throwable e) {
      request.setError(e);
    }
  }
Esempio n. 12
0
  protected Node getFileContentNode(
      Session session, long companyId, long repositoryId, String fileName, String versionLabel)
      throws PortalException, SystemException {

    Node contentNode = null;

    try {
      Workspace workspace = session.getWorkspace();

      VersionManager versionManager = workspace.getVersionManager();

      Node rootNode = getRootNode(session, companyId);

      Node repositoryNode = getFolderNode(rootNode, repositoryId);

      Node fileNode = repositoryNode.getNode(fileName);

      contentNode = fileNode.getNode(JCRConstants.JCR_CONTENT);

      if (Validator.isNotNull(versionLabel)) {
        VersionHistory versionHistory = versionManager.getVersionHistory(contentNode.getPath());

        if (!versionHistory.hasVersionLabel(versionLabel)) {
          throw new NoSuchFileException(
              "{fileName=" + fileName + ", versionLabel=" + versionLabel + "}");
        }

        Version version = versionHistory.getVersionByLabel(versionLabel);

        contentNode = version.getNode(JCRConstants.JCR_FROZEN_NODE);
      }
    } catch (PathNotFoundException pnfe) {
      throw new NoSuchFileException(
          "{fileName=" + fileName + ", versionLabel=" + versionLabel + "}");
    } catch (RepositoryException re) {
      throw new SystemException(re);
    }

    return contentNode;
  }
 @Override
 public void endDocument() throws SAXException {
   delegatee.endDocument();
   try {
     workspace.importXML(parentAbsPath, new FileInputStream(tmpFile), uuidBehavior);
   } catch (IOException e) {
     throw new SAXException(e);
   } catch (RepositoryException e) {
     throw new SAXException(e);
   } finally {
     tmpFile.delete();
   }
 }
Esempio n. 14
0
 public static boolean registerNodeType(
     Session session, String systemId, Reader reader, boolean reregisterExisting)
     throws IOException, RepositoryException {
   try {
     Workspace wsp = session.getWorkspace();
     CndImporter.registerNodeTypes(
         reader,
         systemId,
         wsp.getNodeTypeManager(),
         wsp.getNamespaceRegistry(),
         session.getValueFactory(),
         reregisterExisting);
   } catch (RepositoryException re) {
     if (isReRegisterBuiltinNodeType(re)) {
       log.debug("Attempt to re-register built-in node type, RepositoryException ignored", re);
     } else {
       throw re;
     }
   } catch (ParseException e) {
     throw new IOException("Unable to parse CND Input: " + e.getMessage());
   }
   return true;
 }
Esempio n. 15
0
  public ResultSet findByStatementPaginated(
      String token, String statement, String type, int offset, int limit)
      throws RepositoryException, DatabaseException {
    log.debug(
        "findByStatement({}, {}, {}, {}, {})",
        new Object[] {token, statement, type, offset, limit});
    ResultSet rs = new ResultSet();
    Session session = null;

    try {
      if (token == null) {
        session = JCRUtils.getSession();
      } else {
        session = JcrSessionManager.getInstance().get(token);
      }

      if (statement != null && !statement.equals("")) {
        Workspace workspace = session.getWorkspace();
        QueryManager queryManager = workspace.getQueryManager();
        Query query = queryManager.createQuery(statement, type);
        rs = executeQuery(session, query, offset, limit);
      }

      // Activity log
      UserActivity.log(
          session.getUserID(), "FIND_BY_STATEMENT", null, null, type + ", " + statement);
    } catch (javax.jcr.RepositoryException e) {
      log.error(e.getMessage(), e);
      throw new RepositoryException(e.getMessage(), e);
    } finally {
      if (token == null) JCRUtils.logout(session);
    }

    log.debug("findByStatement: {}", rs);
    return rs;
  }
Esempio n. 16
0
  @SuppressWarnings("unchecked")
  @Test
  public void test()
      throws ServletException, IOException, UnsupportedRepositoryOperationException,
          RepositoryException {
    SlingHttpServletRequest request = createNiceMock(SlingHttpServletRequest.class);
    SlingHttpServletResponse response = createNiceMock(SlingHttpServletResponse.class);
    RequestPathInfo requestPathInfo = createNiceMock(RequestPathInfo.class);
    Resource resource = createNiceMock(Resource.class);
    Node node = createNiceMock(Node.class);
    VersionHistory versionHistory = createNiceMock(VersionHistory.class);
    Version version = createNiceMock(Version.class);
    Node frozenNode = createNiceMock(Node.class);
    Property resourceTypeProperty = createNiceMock(Property.class);
    Capture<Resource> capturedResource = new Capture<Resource>();
    RequestDispatcher requestDispatcher = createNiceMock(RequestDispatcher.class);
    Capture<ServletRequest> capturedRequest = new Capture<ServletRequest>();
    Capture<ServletResponse> capturedResponse = new Capture<ServletResponse>();
    VersionManager versionManager = createNiceMock(VersionManager.class);
    Session session = createNiceMock(Session.class);
    Workspace workspace = createNiceMock(Workspace.class);

    EasyMock.expect(request.getRequestPathInfo()).andReturn(requestPathInfo);
    EasyMock.expect(requestPathInfo.getSelectorString()).andReturn("version.,1.1,.tidy.json");
    EasyMock.expect(request.getResource()).andReturn(resource);
    EasyMock.expect(resource.adaptTo(Node.class)).andReturn(node);
    EasyMock.expect(node.getPath()).andReturn("/foo");
    EasyMock.expect(node.getSession()).andReturn(session);
    EasyMock.expect(session.getWorkspace()).andReturn(workspace);
    EasyMock.expect(workspace.getVersionManager()).andReturn(versionManager);
    EasyMock.expect(versionManager.getVersionHistory("/foo")).andReturn(versionHistory);
    EasyMock.expect(versionHistory.getVersion("1.1")).andReturn(version);
    EasyMock.expect(version.getNode(JcrConstants.JCR_FROZENNODE)).andReturn(frozenNode);
    EasyMock.expect(frozenNode.getPath()).andReturn("/testnode");
    EasyMock.expect(frozenNode.hasProperty(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY))
        .andReturn(true);
    EasyMock.expect(frozenNode.getProperty(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY))
        .andReturn(resourceTypeProperty);
    EasyMock.expect(resourceTypeProperty.getString()).andReturn("sakai/testing");
    EasyMock.expect(frozenNode.hasProperty(JcrResourceConstants.SLING_RESOURCE_SUPER_TYPE_PROPERTY))
        .andReturn(true);
    EasyMock.expect(frozenNode.getProperty(JcrResourceConstants.SLING_RESOURCE_SUPER_TYPE_PROPERTY))
        .andReturn(resourceTypeProperty);
    EasyMock.expect(resourceTypeProperty.getString()).andReturn("sakai/super-type-testing");
    EasyMock.expect(request.getRequestDispatcher(EasyMock.capture(capturedResource)))
        .andReturn(requestDispatcher);
    requestDispatcher.forward(
        EasyMock.capture(capturedRequest), EasyMock.capture(capturedResponse));
    EasyMock.expectLastCall();

    replay();
    getVersionServlet.doGet(request, response);

    Assert.assertTrue(capturedRequest.hasCaptured());
    Assert.assertTrue(capturedResource.hasCaptured());
    Assert.assertTrue(capturedResponse.hasCaptured());

    Resource cresource = capturedResource.getValue();

    Node capturedNode = cresource.adaptTo(Node.class);
    Assert.assertEquals(capturedNode, frozenNode);

    Map<String, String> map = cresource.adaptTo(Map.class);
    Assert.assertNotNull(map);

    verify();
  }
Esempio n. 17
0
  public void updateFile(long companyId, long repositoryId, String fileName, String newFileName)
      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);

      Node newFileNode = repositoryNode.addNode(newFileName, JCRConstants.NT_FILE);

      Node newContentNode = newFileNode.addNode(JCRConstants.JCR_CONTENT, JCRConstants.NT_RESOURCE);

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

      String[] versionLabels = versionHistory.getVersionLabels();

      for (int i = (versionLabels.length - 1); i >= 0; i--) {
        Version version = versionHistory.getVersionByLabel(versionLabels[i]);

        Node frozenContentNode = version.getNode(JCRConstants.JCR_FROZEN_NODE);

        if (i == (versionLabels.length - 1)) {
          newContentNode.addMixin(JCRConstants.MIX_VERSIONABLE);
        } else {
          versionManager.checkout(newContentNode.getPath());
        }

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

        copyBinaryProperty(frozenContentNode, newContentNode, JCRConstants.JCR_DATA);

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

        session.save();

        Version newVersion = versionManager.checkin(newContentNode.getPath());

        VersionHistory newVersionHistory =
            versionManager.getVersionHistory(newContentNode.getPath());

        newVersionHistory.addVersionLabel(
            newVersion.getName(), versionLabels[i], PropsValues.DL_STORE_JCR_MOVE_VERSION_LABELS);
      }

      fileNode.remove();

      session.save();
    } catch (PathNotFoundException pnfe) {
      throw new NoSuchFileException(fileName);
    } catch (RepositoryException re) {
      throw new SystemException(re);
    } finally {
      JCRFactoryUtil.closeSession(session);
    }
  }
Esempio n. 18
0
  @Override
  public void deleteFile(long companyId, long repositoryId, String fileName)
      throws PortalException, SystemException {

    Session session = null;

    // A bug in Jackrabbit requires us to create a dummy node and delete the
    // version tree manually to successfully delete a file

    // Create a dummy node

    try {
      session = JCRFactoryUtil.createSession();

      Workspace workspace = session.getWorkspace();

      VersionManager versionManager = workspace.getVersionManager();

      Node rootNode = getRootNode(session, companyId);

      Node repositoryNode = getFolderNode(rootNode, repositoryId);

      Node fileNode = repositoryNode.getNode(fileName);

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

      versionManager.checkout(contentNode.getPath());

      contentNode.setProperty(JCRConstants.JCR_MIME_TYPE, "text/plain");
      contentNode.setProperty(JCRConstants.JCR_DATA, "");
      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(), "0.0", false);
    } catch (PathNotFoundException pnfe) {
      throw new NoSuchFileException(fileName);
    } catch (RepositoryException re) {
      throw new SystemException(re);
    } finally {
      JCRFactoryUtil.closeSession(session);
    }

    // Delete version tree

    try {
      session = JCRFactoryUtil.createSession();

      Workspace workspace = session.getWorkspace();

      VersionManager versionManager = workspace.getVersionManager();

      Node rootNode = getRootNode(session, companyId);

      Node repositoryNode = getFolderNode(rootNode, repositoryId);

      Node fileNode = repositoryNode.getNode(fileName);

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

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

      VersionIterator itr = versionHistory.getAllVersions();

      while (itr.hasNext()) {
        Version version = itr.nextVersion();

        if (itr.getPosition() == itr.getSize()) {
          break;
        } else {
          if (!StringUtils.equals(JCRConstants.JCR_ROOT_VERSION, version.getName())) {

            versionHistory.removeVersion(version.getName());
          }
        }
      }

      session.save();
    } catch (PathNotFoundException pnfe) {
      throw new NoSuchFileException(fileName);
    } catch (RepositoryException re) {
      throw new SystemException(re);
    } finally {
      JCRFactoryUtil.closeSession(session);
    }

    // Delete file

    try {
      session = JCRFactoryUtil.createSession();

      Node rootNode = getRootNode(session, companyId);

      Node repositoryNode = getFolderNode(rootNode, repositoryId);

      Node fileNode = repositoryNode.getNode(fileName);

      fileNode.remove();

      session.save();
    } catch (PathNotFoundException pnfe) {
      throw new NoSuchFileException(fileName);
    } catch (RepositoryException re) {
      throw new SystemException(re);
    } finally {
      JCRFactoryUtil.closeSession(session);
    }
  }