/**
   * Converts file to JCR binary content and stores to new node
   *
   * @param userNode note to which children node will be created with binary content * @param
   *     cvIStream CV file input stream
   * @param fileType type of file stored to node
   */
  public static void convertFileStreamToNode(
      Node userNode, InputStream cvIStream, AllowedFileType fileType) {
    if (userNode == null) {
      throw new IllegalArgumentException("User node is null");
    }
    if (cvIStream == null) {
      throw new IllegalArgumentException("CV file input stream is null");
    }
    if (fileType == null) {
      throw new IllegalArgumentException("File type is null");
    }

    try {
      Node cvNode = userNode.addNode(fileType.getNodeType().toString(), "nt:file");
      cvNode.addMixin(MIXIN_HASCONTENT.toString());
      Node content = cvNode.addNode("jcr:content", "nt:resource");
      content.setProperty(
          "jcr:data", userNode.getSession().getValueFactory().createBinary(cvIStream));
      content.setProperty("jcr:mimeType", fileType.getMimeType());
      cvNode.setProperty(
          PROP_CONTENT.toString(),
          Utils.extractText(content.getProperty("jcr:data").getBinary().getStream(), fileType));
    } catch (RepositoryException e) {
      logger.error(
          "Failed to convert " + fileType.toString() + " file to binary node. " + e.getMessage());
    }
  }
 public void send(
     SlingHttpServletRequest request, SlingHttpServletResponse response, HtmlLibrary library) {
   InputStream libraryInputStream = null;
   // NOTE: HtmlLibraryManager#getLibrary should have prepared ClientLibraryImpl
   // and related binary stream should be ready
   try {
     Node node =
         JcrUtils.getNodeIfExists(getLibraryNode(request, library), JcrConstants.JCR_CONTENT);
     response.setDateHeader(
         "Last-Modified", JcrUtils.getLongProperty(node, JcrConstants.JCR_LASTMODIFIED, 0L));
     response.setContentType(library.getType().contentType);
     response.setCharacterEncoding("utf-8");
     libraryInputStream = JcrUtils.readFile(node);
   } catch (RepositoryException re) {
     log.debug("JCR issue retrieving library node at {}: ", library.getPath(), re.getMessage());
   }
   try {
     if (libraryManager.isGzipEnabled()) {
       response.setHeader("Content-Encoding", "gzip");
       GZIPOutputStream gzipOut = new GZIPOutputStream(response.getOutputStream());
       IOUtils.copy(libraryInputStream, gzipOut);
       gzipOut.finish();
     } else {
       IOUtils.copy(libraryInputStream, response.getOutputStream());
     }
   } catch (IOException ioe) {
     log.debug("gzip IO issue for library {}: ", library.getPath(), ioe.getMessage());
   } finally {
     IOUtils.closeQuietly(libraryInputStream);
   }
 }
 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;
 }
示例#4
0
  @Override
  public List<JcrNode> childNodes(String path) throws RemoteException {
    List<JcrNode> children = null;
    if (path == null || path.trim().length() == 0) {
      return Collections.emptyList();
    }
    try {
      Node node = (Node) session().getItem(path);
      NodeIterator it = node.getNodes();
      children = new ArrayList<JcrNode>((int) it.getSize());

      while (it.hasNext()) {
        Node n = it.nextNode();
        JcrNode childNode = new JcrNode(n.getName(), n.getPath(), n.getPrimaryNodeType().getName());
        childNode.setProperties(getProperties(n));
        childNode.setAcessControlList(getAccessList(session().getAccessControlManager(), node));
        childNode.setMixins(mixins(n));
        childNode.setPropertyDefs(propertyDefs(n));
        children.add(childNode);
      }

    } catch (PathNotFoundException e) {
      log.log(Level.FINER, e.getLocalizedMessage());
    } catch (RepositoryException e) {
      log.log(Level.SEVERE, "Unexpected error", e);
      throw new RemoteException(e.getMessage());
    }

    return children;
  }
示例#5
0
 private JcrNodeModel getPhysicalNode(JcrNodeModel model) {
   Node node = model.getNode();
   if (node != null) {
     try {
       if (node.isNodeType("nt:version")) {
         Node frozen = node.getNode("jcr:frozenNode");
         String uuid = frozen.getProperty("jcr:frozenUuid").getString();
         try {
           Node docNode = node.getSession().getNodeByUUID(uuid);
           if (docNode.getDepth() > 0) {
             Node parent = docNode.getParent();
             if (parent.isNodeType(HippoNodeType.NT_HANDLE)) {
               return new JcrNodeModel(parent);
             }
           }
           return new JcrNodeModel(docNode);
         } catch (ItemNotFoundException infe) {
           // node doesn't exist anymore.  If it's a document, the handle
           // should still be available though.
           if (frozen.hasProperty(HippoNodeType.HIPPO_PATHS)) {
             Value[] ancestors = frozen.getProperty(HippoNodeType.HIPPO_PATHS).getValues();
             if (ancestors.length > 1) {
               uuid = ancestors[1].getString();
               return new JcrNodeModel(node.getSession().getNodeByUUID(uuid));
             }
           }
           throw infe;
         }
       }
     } catch (RepositoryException ex) {
       log.error(ex.getMessage());
     }
   }
   return model;
 }
  public void execute(WorkItem item, WorkflowSession session, MetaDataMap args)
      throws WorkflowException {
    WorkflowData workflowData = item.getWorkflowData();
    log.info("==================== <> ======================");
    Iterator props = args.entrySet().iterator();
    String pathToArchive = args.get("PROCESS_ARGS", String.class);
    if (pathToArchive != null)
      if (workflowData.getPayloadType().equals(TYPE_JCR_PATH)) {
        String path = workflowData.getPayload().toString();
        try {
          Node node = (Node) session.getSession().getItem(path + "/jcr:content");

          String orderBy = node.getProperty("orderby").getString();
          log.info("----------orderby: " + orderBy);
          Node nodeToOrder = (Node) session.getSession().getItem(pathToArchive);
          Iterator<Node> iterator = nodeToOrder.getNodes();
          List<Node> nodes = copyIterator(iterator);

          Collections.sort(nodes, new NodeComparator(orderBy));

          for (Node orderNode : nodes) {
            session
                .getSession()
                .getWorkspace()
                .move(
                    pathToArchive + "/" + orderNode.getName(),
                    pathToArchive + "/" + orderNode.getName());
          }

        } catch (RepositoryException e) {
          throw new WorkflowException(e.getMessage(), e);
        }
      }
  }
  @Override
  public List<String> getEnabledExtensions() throws OKMException {
    List<String> extensions = new ArrayList<String>();
    Session session = null;

    try {
      Profile up = new Profile();
      session = JCRUtils.getSession();
      UserConfig uc = UserConfigDAO.findByPk(session, session.getUserID());
      up = uc.getProfile();
      extensions = new ArrayList<String>(up.getMisc().getExtensions());
    } catch (LoginException e) {
      log.error(e.getMessage(), e);
      throw new OKMException(
          ErrorCode.get(ErrorCode.ORIGIN_OKMGeneralService, ErrorCode.CAUSE_Repository),
          e.getMessage());
    } catch (javax.jcr.RepositoryException e) {
      log.error(e.getMessage(), e);
      throw new OKMException(
          ErrorCode.get(ErrorCode.ORIGIN_OKMGeneralService, ErrorCode.CAUSE_Repository),
          e.getMessage());
    } catch (DatabaseException e) {
      log.warn(e.getMessage(), e);
      throw new OKMException(
          ErrorCode.get(ErrorCode.ORIGIN_OKMGeneralService, ErrorCode.CAUSE_Database),
          e.getMessage());
    } finally {
      JCRUtils.logout(session);
    }

    return extensions;
  }
示例#8
0
 @Test
 @FixFor("MODE-1977")
 public void shouldNotAllowMoveIfSourceIsFederatedAndTargetIsNot() throws Exception {
   federationManager.createProjection(
       "/testRoot", SOURCE_NAME, MockConnector.DOC1_LOCATION, "fed1");
   ((Node) session.getRootNode()).addNode("testRoot2");
   session.save();
   try {
     session.move("/testRoot", "/testRoot2");
     fail("Should not allow move is source is federated is target is not.");
   } catch (RepositoryException e) {
     // expected
     if (print) {
       e.printStackTrace();
     }
   }
   try {
     session.move("/testRoot/fed1", "/testRoot2");
     fail("Should not allow move is source is federated is target is not.");
   } catch (RepositoryException e) {
     // expected
     if (print) {
       e.printStackTrace();
     }
   }
 }
示例#9
0
  @Test
  @FixFor("MODE-1977")
  public void shouldNotAllowMoveIfSourceOrTargetIsProjection() throws Exception {
    federationManager.createProjection(
        "/testRoot", SOURCE_NAME, MockConnector.DOC1_LOCATION, "fed1");
    federationManager.createProjection(
        "/testRoot", SOURCE_NAME, MockConnector.DOC2_LOCATION, "fed2");
    try {
      session.move("/testRoot/fed2/federated3", "/testRoot/fed1");
      fail("Should not allow move if target is projection");
    } catch (RepositoryException e) {
      // expected
      if (print) {
        e.printStackTrace();
      }
    }

    try {
      session.move("/testRoot/fed2", "/testRoot/fed1");
      fail("Should not allow move if source is projection");
    } catch (RepositoryException e) {
      // expected
      if (print) {
        e.printStackTrace();
      }
    }
  }
示例#10
0
 public JcrRepository call() throws Exception {
   JcrRepository repository = null;
   try {
     repository = doCreateJcrRepository(repositoryName);
     getLogger().info(JcrI18n.completedStartingRepository, repositoryName);
     return repository;
   } catch (RepositoryException t) {
     // Record this in the problems ...
     problems()
         .addError(
             t,
             JcrI18n.errorStartingRepositoryCheckConfiguration,
             repositoryName,
             t.getMessage());
     throw t;
   } catch (Throwable t) {
     // Record this in the problems ...
     problems()
         .addError(
             t,
             JcrI18n.errorStartingRepositoryCheckConfiguration,
             repositoryName,
             t.getMessage());
     String msg =
         JcrI18n.errorStartingRepositoryCheckConfiguration.text(repositoryName, t.getMessage());
     throw new RepositoryException(msg, t);
   } finally {
     if (latch != null) latch.countDown();
   }
 }
示例#11
0
  @Test
  public void shouldNotAllowInternalNodesAsReferrers() throws Exception {
    federationManager.createProjection(
        "/testRoot", SOURCE_NAME, MockConnector.DOC1_LOCATION, "federated1");
    Node doc1Federated = session.getNode("/testRoot/federated1");
    Node externalNode = doc1Federated.addNode("federated1_1", null);
    externalNode.addMixin("mix:referenceable");
    session.save();

    Value weakRef = session.getValueFactory().createValue(externalNode, true);
    testRoot.setProperty("weakRef", weakRef);
    try {
      session.save();
      fail(
          "It should not be possible to create weak references from internal nodes to external nodes");
    } catch (RepositoryException e) {
      assertTrue(e.getCause() instanceof ConnectorException);
    }

    Value strongRef = session.getValueFactory().createValue(externalNode, false);
    testRoot.setProperty("strongRef", strongRef);
    try {
      session.save();
      fail(
          "It should not be possible to create strong references from internal nodes to external nodes");
    } catch (RepositoryException e) {
      assertTrue(e.getCause() instanceof ConnectorException);
    }
  }
示例#12
0
  @Override
  public void doTag() throws JspException {

    this.setUp();

    try {
      Content imageContentNode = ContentUtil.asContent(getImageContentNode());

      String[] subStrings = this.getTextSubStrings(this.text);
      String[] imageURIs =
          this.getImageURIs(
              subStrings,
              (HttpServletRequest) ((PageContext) this.getJspContext()).getRequest(),
              imageContentNode);
      this.drawTextImages(imageURIs, subStrings);
    } catch (PathNotFoundException e) {
      log.error(
          "PathNotFoundException occured during text-to-image conversion: " + e.getMessage(), e);
    } catch (AccessDeniedException e) {
      log.error(
          "AccessDeniedException occured during text-to-image conversion: " + e.getMessage(), e);
    } catch (RepositoryException e) {
      log.error(
          "RepositoryException occured during text-to-image conversion: " + e.getMessage(), e);
    } catch (FileNotFoundException e) {
      log.error(
          "FileNotFoundException occured during text-to-image conversion: " + e.getMessage(), e);
    } catch (IOException e) {
      log.error("IOException occured during text-to-image conversion: " + e.getMessage(), e);
    } catch (FontFormatException e) {
      log.error(
          "FontFormatException occured during text-to-image conversion: " + e.getMessage(), e);
    }
    this.cleanUp();
  }
  /** {@inheritDoc} */
  public void start() {
    configuredTemplates_ = new HashMap<String, Set<String>>();
    RepositoryEntry repositoryEntry = null;
    try {
      repositoryEntry = repositoryService.getCurrentRepository().getConfiguration();
    } catch (RepositoryException e) {
      if (LOG.isErrorEnabled()) {
        LOG.error(e.getMessage(), e);
      }
    }

    String repoName = repositoryEntry.getName();
    String workspaceName = repositoryEntry.getSystemWorkspaceName();
    storedWorkspaces.put(repoName, workspaceName);
    basedApplicationTemplatesPath = hierarchyCreator.getJcrPath(BasePath.CMS_VIEWTEMPLATES_PATH);

    SessionProvider sessionProvider = SessionProvider.createSystemProvider();
    for (Iterator<String> repositories = storedWorkspaces.keySet().iterator();
        repositories.hasNext(); ) {
      String repository = repositories.next();
      try {
        Node storedTemplateHome = getBasedApplicationTemplatesHome(sessionProvider);
        importPredefinedTemplateToDB(storedTemplateHome);
      } catch (Exception e) {
        if (LOG.isErrorEnabled()) {
          LOG.error(
              "Exception when import predefine application template into repository: " + repository,
              e);
        }
      }
    }
    sessionProvider.close();
  }
  public String pasteNode(String pathOrigin, String pathSelected, int pasteType, int action)
      throws ExchangeException, RepositoryException {
    boolean move = false;
    if (action == Tree.ACTION_MOVE) {
      move = true;
    }
    String label = StringUtils.substringAfterLast(pathOrigin, "/"); // $NON-NLS-1$
    String slash = "/"; // $NON-NLS-1$
    if (pathSelected.equals("/")) { // $NON-NLS-1$
      slash = StringUtils.EMPTY;
    }
    String destination = pathSelected + slash + label;
    if (pasteType == Tree.PASTETYPE_SUB
        && action != Tree.ACTION_COPY
        && destination.equals(pathOrigin)) {
      // drag node to parent node: move to last position
      pasteType = Tree.PASTETYPE_LAST;
    }
    if (pasteType == Tree.PASTETYPE_SUB) {
      destination = pathSelected + slash + label;
      Content touchedContent = this.copyMoveNode(pathOrigin, destination, move);
      if (touchedContent == null) {
        return StringUtils.EMPTY;
      }
      return touchedContent.getHandle();

    } else if (pasteType == Tree.PASTETYPE_LAST) {
      // LAST only available for sorting inside the same directory
      try {
        Content touchedContent = getHierarchyManager().getContent(pathOrigin);
        return touchedContent.getHandle();
      } catch (RepositoryException re) {
        return StringUtils.EMPTY;
      }
    } else {
      try {
        // PASTETYPE_ABOVE | PASTETYPE_BELOW
        String nameSelected = StringUtils.substringAfterLast(pathSelected, "/"); // $NON-NLS-1$
        String nameOrigin = StringUtils.substringAfterLast(pathOrigin, "/"); // $NON-NLS-1$
        Content tomove = getHierarchyManager().getContent(pathOrigin);
        Content selected = getHierarchyManager().getContent(pathSelected);
        if (tomove.getParent().getUUID().equals(selected.getParent().getUUID())) {
          tomove.getParent().orderBefore(nameOrigin, nameSelected);
          tomove.getParent().save();
        } else {
          String newOrigin = selected.getParent().getHandle() + "/" + nameOrigin;
          getHierarchyManager().moveTo(pathOrigin, newOrigin);
          Content newNode = getHierarchyManager().getContent(newOrigin);
          if (pasteType == Tree.PASTETYPE_ABOVE) {
            newNode.getParent().orderBefore(nameOrigin, nameSelected);
          }
        }
        return tomove.getHandle();
      } catch (RepositoryException re) {
        re.printStackTrace();
        log.error("Problem when pasting node", re);
        return StringUtils.EMPTY;
      }
    }
  }
  /**
   * Add a new version-able <code>EcmDocument</code> under the parent folder name provided
   *
   * @param pFolderPath the name of the parent folder
   * @param document the <code>EcmDocument</code> object
   * @throws EcmException if there is any error
   */
  public void addNewVersionableDocumentToFolder(String pFolderPath, EcmDocument document)
      throws EcmException {
    logger.debug("Adding versionable document to folder:" + pFolderPath);
    try {
      Node parentNode = this.getNode(pFolderPath);

      Node fileNode = parentNode.addNode(document.getMetadata().getFileName(), NodeType.NT_FILE);
      fileNode.addMixin(NodeType.MIX_VERSIONABLE);

      this.createFileContentNode(fileNode, document);

      this.session.save();

      /** Get the version manager */
      VersionManager vm = this.session.getWorkspace().getVersionManager();

      /** Check in the changes as a new version */
      vm.checkin(fileNode.getPath());
      this.session.save();

    } catch (RepositoryException e) {
      e.printStackTrace();
    }
    logger.debug("A document has been added to the folder:" + pFolderPath);
  }
示例#16
0
  @Override
  public ResultSet findSimpleQueryPaginated(String token, String statement, int offset, int limit)
      throws RepositoryException, DatabaseException {
    log.debug(
        "findSimpleQueryPaginated({}, {}, {}, {})", new Object[] {token, statement, offset, limit});
    ResultSet rs = new ResultSet();
    Session session = null;

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

      rs = executeSimpleQuery(session, statement, offset, limit);
    } 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("findSimpleQueryPaginated: {}", rs);
    return rs;
  }
  private void badNodeNameParam(String name, String exception) throws RepositoryException {
    CreateSakaiUserServlet csus = new CreateSakaiUserServlet();
    csus.requestTrustValidatorService = requestTrustValidatorService;

    JackrabbitSession session = createMock(JackrabbitSession.class);

    ResourceResolver rr = createMock(ResourceResolver.class);

    SlingHttpServletRequest request = createMock(SlingHttpServletRequest.class);
    UserManager userManager = createMock(UserManager.class);
    User user = createMock(User.class);
    expect(request.getResourceResolver()).andReturn(rr).anyTimes();
    expect(rr.adaptTo(Session.class)).andReturn(session).anyTimes();

    expect(session.getUserManager()).andReturn(userManager);
    expect(session.getUserID()).andReturn("userID");
    expect(userManager.getAuthorizable("userID")).andReturn(user);
    expect(user.isAdmin()).andReturn(false);

    expect(request.getParameter(":create-auth")).andReturn("reCAPTCHA");
    expect(request.getParameter(SlingPostConstants.RP_NODE_NAME)).andReturn(name);

    HtmlResponse response = new HtmlResponse();

    replay();

    try {
      csus.handleOperation(request, response, null);
      fail();
    } catch (RepositoryException e) {
      assertEquals(exception, e.getMessage());
    }
    verify();
  }
示例#18
0
  /** Execute query */
  private ResultSet executeQuery(Session session, Query query, int offset, int limit)
      throws RepositoryException {
    log.debug("executeQuery({}, {}, {}, {})", new Object[] {session, query, offset, limit});
    ResultSet rs = new ResultSet();

    try {
      ArrayList<QueryResult> al = new ArrayList<QueryResult>();

      // http://n4.nabble.com/Query-performance-for-large-query-results-td531360.html
      ((QueryImpl) query).setLimit(limit);
      ((QueryImpl) query).setOffset(offset);
      QueryResultImpl result = (QueryResultImpl) query.execute();
      RowIterator rit = result.getRows();
      rs.setTotal(result.getTotalSize());

      while (rit.hasNext()) {
        Row row = rit.nextRow();
        QueryResult qr = queryRowResultDigester(session, row);
        al.add(qr);
      }

      rs.setResults(al);
    } catch (javax.jcr.RepositoryException e) {
      log.error(e.getMessage(), e);
      throw new RepositoryException(e.getMessage(), e);
    }

    log.debug("executeQuery: {}", rs);
    return rs;
  }
  /** 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");
  }
示例#20
0
  @Override
  public void updateSearch(String token, QueryParams params)
      throws AccessDeniedException, RepositoryException, DatabaseException {
    log.debug("updateSearch({}, {})", token, params);
    Session session = null;

    if (Config.SYSTEM_READONLY) {
      throw new AccessDeniedException("System is in read-only mode");
    }

    try {
      // TODO This JCR Session could be removed
      if (token == null) {
        session = JCRUtils.getSession();
      } else {
        session = JcrSessionManager.getInstance().get(token);
      }

      params.setUser(session.getUserID());
      QueryParamsDAO.update(params);

      // Activity log
      UserActivity.log(
          session.getUserID(), "UPDATE_SEARCH", params.getName(), null, params.toString());
    } catch (javax.jcr.RepositoryException e) {
      throw new RepositoryException(e.getMessage(), e);
    } catch (DatabaseException e) {
      throw e;
    } finally {
      if (token == null) JCRUtils.logout(session);
    }

    log.debug("updateSearch: void");
  }
示例#21
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);
    }
  }
示例#22
0
  @Before
  public void setUp() throws RepositoryException {
    initMocks(this);
    final String relPath = "/" + testPid;
    final NodeType[] types = new NodeType[0];
    try {
      when(mockObjNode.getName()).thenReturn(testPid);
      when(mockObjNode.getSession()).thenReturn(mockSession);
      when(mockObjNode.getMixinNodeTypes()).thenReturn(types);
      NodeType mockNodeType = mock(NodeType.class);
      when(mockNodeType.getName()).thenReturn("nt:folder");
      when(mockObjNode.getPrimaryNodeType()).thenReturn(mockNodeType);
      when(mockSession.getRootNode()).thenReturn(mockRootNode);
      when(mockRootNode.getNode(relPath)).thenReturn(mockObjNode);
      when(mockSession.getUserID()).thenReturn(mockUser);
      testFedoraObject = new FedoraObject(mockObjNode);

      mockNodetypes = new NodeType[2];
      mockNodetypes[0] = mock(NodeType.class);
      mockNodetypes[1] = mock(NodeType.class);

      when(mockObjNode.getMixinNodeTypes()).thenReturn(mockNodetypes);

      when(mockPredicate.apply(mockObjNode)).thenReturn(true);

    } catch (final RepositoryException e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
  }
 public String printProperty(javax.jcr.Property property) {
   try {
     return printObject(JcrResourceUtil.toJavaObject(property));
   } catch (RepositoryException e1) {
     return e1.getMessage();
   }
 }
  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();
      }
    }
  }
  /** {@inheritDoc} */
  public void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    try {
      Resource resource = request.getResource();
      Node node = resource.adaptTo(Node.class);
      if (node == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
      }
      Version version = versionService.saveNode(node, request.getRemoteUser());

      response.setContentType("application/json");
      response.setCharacterEncoding("UTF-8");

      ExtendedJSONWriter write = new ExtendedJSONWriter(response.getWriter());
      write.object();
      write.key("versionName");
      write.value(version.getName());
      ExtendedJSONWriter.writeNodeContentsToWriter(write, version);
      write.endObject();
    } catch (RepositoryException e) {
      LOGGER.info("Failed to save version ", e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
      return;
    } catch (JSONException e) {
      LOGGER.info("Failed to save version ", e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
      return;
    }
  }
示例#26
0
  protected void fillRecipients(Message email, Execution execution, JCRSessionWrapper session)
      throws MessagingException {
    try {
      // to
      AddressTemplate to = getTemplate().getTo();
      if (to != null) {
        fillRecipients(to, email, Message.RecipientType.TO, execution, session);
      }

      // cc
      AddressTemplate cc = getTemplate().getCc();
      if (cc != null) {
        fillRecipients(cc, email, Message.RecipientType.CC, execution, session);
      }

      // bcc
      AddressTemplate bcc = getTemplate().getBcc();
      if (bcc != null) {
        fillRecipients(bcc, email, Message.RecipientType.BCC, execution, session);
      }
    } catch (ScriptException e) {
      logger.error(e.getMessage(), e);
    } catch (RepositoryException e) {
      logger.error(e.getMessage(), e);
    }
  }
 public Node getLibraryNode(SlingHttpServletRequest request, HtmlLibrary library) {
   Node node = null;
   try {
     // we want the non-minified version as the root path
     String cacheRoot =
         Text.getRelativeParent(
             (new StringBuilder(CACHE_PATH).append(library.getPath(false))).toString(), 1);
     String optPath =
         (new StringBuilder(cacheRoot).append("/").append(getLibraryName(library))).toString();
     node = JcrUtils.getNodeIfExists(optPath, getAdminSession());
     if (null == node) {
       // generate empty jcr:data to cache
       node = createEmptyCache(library, cacheRoot, getAdminSession());
     }
     // lib was modified after last cache write
     if (!node.hasNode(JcrConstants.JCR_CONTENT)
         || library.getLastModified(false)
             > JcrUtils.getLongProperty(
                 node.getNode(JcrConstants.JCR_CONTENT), JcrConstants.JCR_LASTMODIFIED, 0L)) {
       // generate new binary, if possible
       node = populateCache(library, node.getPath(), getAdminSession());
     }
     // reassign with user session
     node = request.getResourceResolver().resolve(node.getPath()).adaptTo(Node.class);
   } catch (RepositoryException re) {
     log.debug(re.getMessage());
   } finally {
     getResolver().close();
   }
   return node;
 }
 /**
  * {@inheritDoc}
  *
  * @return the next frozen node.
  */
 public Node nextNode() {
   try {
     return ((Version) next()).getFrozenNode();
   } catch (RepositoryException e) {
     throw (IllegalStateException) new IllegalStateException(e.toString()).initCause(e);
   }
 }
 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;
 }
  /**
   * Imports custom node types into repository
   *
   * @param session JCR session
   * @param cndFile CND file with node types definition
   */
  public static void importCustomNodeTypes(Session session, InputStream cndFile) {
    if (logger.isInfoEnabled()) {
      logger.info("Importing custom node types into repository");
    }
    NodeType[] nodeTypes = new NodeType[0];
    try {
      nodeTypes =
          CndImporter.registerNodeTypes(
              new BufferedReader(new InputStreamReader(cndFile)), session);
    } catch (ParseException e) {
      logger.error("Failed to parse CND file with repository custom node types. " + e.getMessage());
    } catch (RepositoryException e) {
      logger.error("Failed to import custom node types into repository. " + e.getMessage());
    } catch (IOException e) {
      logger.error(
          "IO Exception while importing custom node types into repository. " + e.getMessage());
    }

    if (logger.isDebugEnabled()) {
      logger.debug("Registered node types: ");
      for (NodeType nt : nodeTypes) {
        logger.debug("\t" + nt.getName());
      }
    }
  }