@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();
     }
   }
 }
  @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();
      }
    }
  }
  /**
   * 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);
  }
  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();
      }
    }
  }
  @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 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;
      }
    }
  }
  public void route(Node n, MessageRoutes routing) {
    List<MessageRoute> toRemove = new ArrayList<MessageRoute>();
    List<MessageRoute> toAdd = new ArrayList<MessageRoute>();

    // Check if this message is a discussion message.
    try {
      if (n.hasProperty(MessageConstants.PROP_SAKAI_TYPE)
          && n.hasProperty(DiscussionConstants.PROP_MARKER)
          && DiscussionTypes.hasValue(
              n.getProperty(MessageConstants.PROP_SAKAI_TYPE).getString())) {

        // This is a discussion message, find the settings file for it.
        String marker = n.getProperty(DiscussionConstants.PROP_MARKER).getString();
        String type = n.getProperty(MessageConstants.PROP_SAKAI_TYPE).getString();

        // TODO: I have a feeling that this is really part of something more generic
        //   and not specific to discussion. If we make it specific to discussion we
        //   will loose unified messaging and control of that messaging.

        Node settings = discussionManager.findSettings(marker, n.getSession(), type);
        if (settings != null && settings.hasProperty(DiscussionConstants.PROP_NOTIFICATION)) {
          boolean sendMail =
              settings.getProperty(DiscussionConstants.PROP_NOTIFICATION).getBoolean();
          if (sendMail && settings.hasProperty(DiscussionConstants.PROP_NOTIFY_ADDRESS)) {
            String address =
                settings.getProperty(DiscussionConstants.PROP_NOTIFY_ADDRESS).getString();
            toAdd.add(new DiscussionRoute("internal:" + address));
          }
        }
      }
    } catch (ValueFormatException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (PathNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (RepositoryException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    for (MessageRoute route : routing) {
      if (DiscussionTypes.hasValue(route.getTransport())) {
        toAdd.add(new DiscussionRoute("internal:" + route.getRcpt()));
        toRemove.add(route);
      }
    }
    // Add the new routes
    for (MessageRoute route : toAdd) {
      routing.add(route);
    }
    // Remove the discussion route (if there is any).
    for (MessageRoute route : toRemove) {
      routing.remove(route);
    }
  }
 @Override
 public void init() throws ServletException {
   super.init();
   try {
     RepositoryManager.initRepository();
   } catch (RepositoryException e) {
     e.printStackTrace();
   }
   JcrSessionManager.initAnnotationMapper();
 }
 private boolean createLogin(String user, String password) {
   try {
     return userManager.createUser(user, password) != null;
   } catch (AuthorizableExistsException e) {
     e.printStackTrace();
     return true;
   } catch (RepositoryException e) {
     e.printStackTrace();
   }
   return false;
 }
Exemple #10
0
  public void testRemoveMixVersionable() throws Exception {

    testRoot.checkout();

    try {
      testRoot.removeMixin("mix:versionable");
      testRoot.save();
    } catch (RepositoryException e) {
      e.printStackTrace();
      fail("removeMixin(\"mix:versionable\") impossible due to error " + e.getMessage());
    }
  }
  @Override
  public List<EcmDocument> readWorkspace() throws EcmException {

    /** Get the root folder */
    try {
      Node rootNode = this.session.getRootNode();
      System.out.println(rootNode.getPath());
      listChildren("=", rootNode, System.out);
    } catch (RepositoryException e) {

      e.printStackTrace();
    }

    return null;
  }
  @Override
  public void initialize(
      Subject subject,
      CallbackHandler callbackHandler,
      Map<String, ?> sharedState,
      Map<String, ?> options) {
    if (adminId == null || SecurityConstants.ADMIN_ID.equals(adminId)) {
      try {
        adminId = getSecurityHelper().getSuperAdminId();
      } catch (RepositoryException e) {
        e.printStackTrace();
      }
    }

    super.initialize(subject, callbackHandler, sharedState, options);
  }
 @Test
 @FixFor("MODE-1975")
 public void shouldNotAllowCloneWithinTheSameWs() throws Exception {
   federationManager.createProjection(
       "/testRoot", SOURCE_NAME, MockConnector.DOC1_LOCATION, "fed1");
   try {
     jcrSession()
         .getWorkspace()
         .clone(jcrSession().getWorkspace().getName(), "/testRoot", "/testRoot1", false);
     fail("Should not be able to clone in the same ws if external nodes are involved");
   } catch (RepositoryException e) {
     // expected
     if (print) {
       e.printStackTrace();
     }
   }
 }
 @Test
 @FixFor("MODE-1976")
 public void shouldNotCopyIfSourceAndTargetSourcesDoNotMatch() throws Exception {
   federationManager.createProjection(
       "/testRoot", SOURCE_NAME, MockConnector.DOC1_LOCATION, "fed1");
   federationManager.createProjection(
       "/testRoot", "mock-source-non-queryable", MockConnector.DOC2_LOCATION, "fed2");
   try {
     jcrSession().getWorkspace().copy("/testRoot/fed1", "/testRoot/fed2/fed1");
     fail("Should not allow copy if source and target don't belong to the same source");
   } catch (RepositoryException e) {
     // expected
     if (print) {
       e.printStackTrace();
     }
   }
 }
 @Test
 @FixFor("MODE-1977")
 public void shouldNotAllowMoveIfSourceAndTargetBelongToDifferentSources() throws Exception {
   federationManager.createProjection(
       "/testRoot", SOURCE_NAME, MockConnector.DOC1_LOCATION, "fed1");
   federationManager.createProjection(
       "/testRoot", "mock-source-non-queryable", MockConnector.DOC2_LOCATION, "fed2");
   try {
     session.move("/testRoot/fed1", "/testRoot/fed2");
     fail("Should not allow move if source and target don't belong to the same source");
   } catch (RepositoryException e) {
     // expected
     if (print) {
       e.printStackTrace();
     }
   }
 }
 @Test
 @FixFor("MODE-1975")
 public void shouldAllowCloneOnlyIfEntireWsAreUsed() throws Exception {
   federationManager.createProjection(
       "/testRoot", SOURCE_NAME, MockConnector.DOC1_LOCATION, "fed1");
   Session ws1Session = jcrSessionTo("ws1");
   try {
     ws1Session.getWorkspace().clone("default", "/testRoot", "/testRoot", true);
     fail("Should only be able to clone between workspaces if the entire workspace is used");
   } catch (RepositoryException e) {
     // expected
     if (print) {
       e.printStackTrace();
     }
   } finally {
     ws1Session.logout();
   }
 }
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {

    Resource resource = request.getResource();
    Node node = (Node) resource.adaptTo(Node.class);

    String filename = null;
    try {
      if (node.hasNode(JcrConstants.JCR_CONTENT)) {
        Node content = node.getNode(JcrConstants.JCR_CONTENT);
        response.setHeader(
            "Content-Type", content.getProperty(JcrConstants.JCR_MIMETYPE).getString());
        response.setHeader(
            "Content-Length", "" + content.getProperty(JcrConstants.JCR_DATA).getLength());
      }
      if (node.hasProperty(FilesConstants.SAKAI_FILENAME)) {
        filename = node.getProperty(FilesConstants.SAKAI_FILENAME).getString();
      }

      // If we provided a filename and we haven't changed the name in a previous request.
      if (filename != null && !response.containsHeader("Content-Disposition")) {
        response.setHeader("Content-Disposition", "filename=\"" + filename + "\"");
      }

      response.setStatus(HttpServletResponse.SC_OK);
      InputStream in = (InputStream) request.getResource().adaptTo(InputStream.class);
      OutputStream out = response.getOutputStream();

      IOUtils.stream(in, out);
    } catch (RepositoryException e) {
      logger.warn("Unable to download file due to repositoryexception!");
      e.printStackTrace();
      response.sendError(500);
    }
  }
 @Override
 public boolean bind(Object content, Node node) throws ContentNodeBindingException {
   // TODO Auto-generated method stub
   log.info("Let's update the document by binder");
   BeanInfo bi;
   try {
     bi = Introspector.getBeanInfo(content.getClass());
     PropertyDescriptor[] properties = bi.getPropertyDescriptors();
     DirectFieldAccessor directFieldAccessor = new DirectFieldAccessor(content);
     for (PropertyDescriptor property : properties) {
       if (formMap.getField(property.getName()) != null) {
         log.info("have a founding");
         if (node != null) {
           Class<?> theTypeClass = directFieldAccessor.getPropertyType(property.getName());
           if (!theTypeClass.isPrimitive()) {
             try {
               Class<?> thePrimitiveClass =
                   (Class<?>) theTypeClass.getDeclaredField("TYPE").get(node);
               if (thePrimitiveClass != null) {
                 theTypeClass = thePrimitiveClass;
               }
             } catch (NoSuchFieldException e) {
               // TODO Auto-generated catch block
               // e.printStackTrace();
             }
           }
           Object theValue =
               formMap.getField(property.getName()).getValue(); // theReadMethod.invoke(anObject);
           Method theMethod =
               MethodUtils.getAccessibleMethod(
                   node.getClass(), "setProperty", new Class[] {String.class, theTypeClass});
           if (theMethod != null) {
             theMethod.invoke(node, "mootlywcm:" + property.getName(), theValue);
           } else {
             if (node.hasNode("mootlywcm:" + property.getName())) {
               Node htmlNode = node.getNode("mootlywcm:" + property.getName());
               if (theValue != null) {
                 htmlNode.setProperty("hippostd:content", theValue.toString());
               }
             }
           }
         }
       }
       // }
     }
   } catch (IntrospectionException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IllegalAccessException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IllegalArgumentException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (InvocationTargetException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (SecurityException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (RepositoryException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   return true;
 }
Exemple #19
0
  public void testJcr() throws Exception {
    Credentials credentials = new SimpleCredentials("admin", "admin".toCharArray());
    final Session jcrSession;
    try {
      jcrSession = repository.login(credentials, null);
    } catch (RepositoryException e) {
      e.printStackTrace();
      return;
    }

    try {
      String seedWord = "";
      int numDocs = 100;
      List<String> filetypes = Arrays.asList(new String[] {"pdf", "rtf", "doc", "ppt", "xls"});

      Node root = jcrSession.getRootNode();
      int n = 0;
      for (int typeIdx = 0; typeIdx < filetypes.size(); typeIdx++) {
        String type = (String) filetypes.get(typeIdx);
        int offset = 0;
        while (n < numDocs * (typeIdx + 1) / filetypes.size()) {
          final URL[] urls = new Search(type, seedWord, offset).getURLs();
          if (urls.length == 0) {
            break;
          }
          for (int i = 0; i < urls.length; i++) {
            final URL currentURL = urls[i];
            String path = urls[i].getPath();
            if (path.startsWith("/")) {
              path = path.substring(1);
            }
            final String host = urls[i].getHost();
            List<String> folderNames = new ArrayList<>();
            folderNames.addAll(Arrays.asList(host.split("\\.")));
            Collections.reverse(folderNames);
            folderNames.addAll(Arrays.asList(path.split("/", 0)));
            final String fileName =
                URLDecoder.decode((String) folderNames.remove(folderNames.size() - 1), "UTF-8")
                    .replaceAll(":", "_");
            Node node = root;
            for (Iterator<String> fn = folderNames.iterator(); fn.hasNext(); ) {
              String name = URLDecoder.decode(fn.next(), "UTF-8");
              name = name.replaceAll(":", "_");
              if (name.length() == 0) {
                continue;
              }
              if (!node.hasNode(name)) {
                node.addNode(name, "nt:folder");
              }
              node = node.getNode(name);
            }
            if (!node.hasNode(fileName)) {
              final PrintStream fOut = System.out;
              Node file = node.addNode(fileName, "nt:file");
              final Node resource = file.addNode("jcr:content", "nt:resource");
              final Exception[] ex = new Exception[1];
              Thread t =
                  new Thread(
                      () -> {
                        try {
                          String info = fileName + " (" + host + ")";
                          URLConnection con = currentURL.openConnection();
                          InputStream in = con.getInputStream();
                          try {
                            synchronized (fOut) {
                              fOut.println("<script>dp.inform(0, '" + info + "')</script>");
                              fOut.flush();
                            }
                            int length = con.getContentLength();
                            if (length != -1) {
                              in = new ProgressInputStream(in, length, info, "dp", fOut);
                            }
                            Binary binary = jcrSession.getValueFactory().createBinary(in);
                            resource.setProperty("jcr:data", binary);
                            String mimeType = URLConnection.guessContentTypeFromName(fileName);
                            if (mimeType == null) {
                              if (fileName.endsWith(".doc")) {
                                mimeType = "application/msword";
                              } else if (fileName.endsWith(".xls")) {
                                mimeType = "application/vnd.ms-excel";
                              } else if (fileName.endsWith(".ppt")) {
                                mimeType = "application/mspowerpoint";
                              } else {
                                mimeType = "application/octet-stream";
                              }
                            }
                            resource.setProperty("jcr:mimeType", mimeType);
                            Calendar lastModified = Calendar.getInstance();
                            lastModified.setTimeInMillis(con.getLastModified());
                            resource.setProperty("jcr:lastModified", lastModified);
                          } finally {
                            in.close();
                          }
                        } catch (Exception e) {
                          ex[0] = e;
                        }
                      });
              t.start();
              for (int s = 0; t.isAlive(); s++) {
                Thread.sleep(100);
                if (s % 10 == 0) {
                  synchronized (fOut) {
                    fOut.println("<script>pb.inform(" + n + ", '')</script>");
                    fOut.flush();
                  }
                }
              }
              if (ex[0] == null) {
                jcrSession.save();
                n++;
                synchronized (fOut) {
                  fOut.println("<script>pb.inform(" + n + ", '')</script>");
                  fOut.flush();
                }
                if (n >= numDocs * (typeIdx + 1) / filetypes.size()) {
                  break;
                }
              } else {
                jcrSession.refresh(false);
              }
            }
          }
          offset += 10;
        }
      }
    } finally {
      if (jcrSession != null) {
        jcrSession.logout();
      }
    }
  }