コード例 #1
0
ファイル: RestQueryHandler.java プロジェクト: nikss/modeshape
  /**
   * Executes a the given query string (based on the language information) against a JCR repository,
   * returning a rest model based result.
   *
   * @param request a non-null {@link HttpServletRequest}
   * @param repositoryName a non-null, URL encoded {@link String} representing the name of a
   *     repository
   * @param workspaceName a non-null, URL encoded {@link String} representing the name of a
   *     workspace
   * @param language a non-null String which should be a valid query language, as recognized by the
   *     {@link javax.jcr.query.QueryManager}
   * @param statement a non-null String which should be a valid query string in the above language.
   * @param offset a numeric value which indicates the index in the result set from where results
   *     should be returned.
   * @param limit a numeric value indicating the maximum number of rows to return.
   * @param uriInfo a non-null {@link UriInfo} object which is provided by RestEASY, allowing extra
   *     request parameters to be retrieved.
   * @return a {@link RestQueryHandler} instance
   * @throws RepositoryException if any operation fails at the JCR level
   */
  public RestQueryResult executeQuery(
      HttpServletRequest request,
      String repositoryName,
      String workspaceName,
      String language,
      String statement,
      long offset,
      long limit,
      UriInfo uriInfo)
      throws RepositoryException {
    assert repositoryName != null;
    assert workspaceName != null;
    assert language != null;
    assert statement != null;

    Session session = getSession(request, repositoryName, workspaceName);
    Query query = createQuery(language, statement, session);
    bindExtraVariables(uriInfo, session.getValueFactory(), query);

    QueryResult result = query.execute();
    RestQueryResult restQueryResult = new RestQueryResult();

    String[] columnNames = result.getColumnNames();
    setColumns(result, restQueryResult, columnNames);

    String baseUrl = RestHelper.repositoryUrl(request);

    setRows(offset, limit, session, result, restQueryResult, columnNames, baseUrl);

    return restQueryResult;
  }
コード例 #2
0
 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;
 }
コード例 #3
0
  /** {@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();
    }
  }
コード例 #4
0
  @Test
  public void testProperPoolId()
      throws ItemNotFoundException, RepositoryException, NoSuchAlgorithmException,
          UnsupportedEncodingException {
    SlingHttpServletRequest request = mock(SlingHttpServletRequest.class);
    HtmlResponse response = new HtmlResponse();

    ResourceResolver resolver = mock(ResourceResolver.class);

    String poolId = "foobarbaz";
    Resource resource = mock(Resource.class);

    // The tagnode
    Node tagNode = new MockNode("/path/to/tag");
    tagNode.setProperty(SLING_RESOURCE_TYPE_PROPERTY, FilesConstants.RT_SAKAI_TAG);
    tagNode.setProperty(FilesConstants.SAKAI_TAG_NAME, "urban");

    // The file we want to tag.
    Node fileNode = mock(Node.class);
    when(fileNode.getPath()).thenReturn("/path/to/file");
    NodeType type = mock(NodeType.class);
    when(type.getName()).thenReturn("foo");
    when(fileNode.getMixinNodeTypes()).thenReturn(new NodeType[] {type});
    Property tagsProp = mock(Property.class);
    MockPropertyDefinition tagsPropDef = new MockPropertyDefinition(false);
    Value v = new MockValue("uuid-to-other-tag");
    when(tagsProp.getDefinition()).thenReturn(tagsPropDef);
    when(tagsProp.getValue()).thenReturn(v);
    when(fileNode.getProperty(FilesConstants.SAKAI_TAGS)).thenReturn(tagsProp);
    when(fileNode.hasProperty(FilesConstants.SAKAI_TAGS)).thenReturn(true);

    // Stuff to check if this is a correct request
    when(session.getNode(CreateContentPoolServlet.hash(poolId))).thenReturn(tagNode);
    RequestParameter poolIdParam = mock(RequestParameter.class);
    when(resolver.adaptTo(Session.class)).thenReturn(session);
    when(resource.adaptTo(Node.class)).thenReturn(fileNode);
    when(poolIdParam.getString()).thenReturn(poolId);
    when(request.getResource()).thenReturn(resource);
    when(request.getResourceResolver()).thenReturn(resolver);
    when(request.getRequestParameter("key")).thenReturn(poolIdParam);
    when(request.getRemoteUser()).thenReturn("john");

    // Actual tagging procedure
    Session adminSession = mock(Session.class);
    when(adminSession.getItem(fileNode.getPath())).thenReturn(fileNode);
    ValueFactory valueFactory = mock(ValueFactory.class);
    Value newValue = new MockValue("uuid-of-tag");
    when(valueFactory.createValue(Mockito.anyString(), Mockito.anyInt()))
        .thenReturn(newValue)
        .thenReturn(newValue);
    when(adminSession.getValueFactory()).thenReturn(valueFactory).thenReturn(valueFactory);
    when(slingRepo.loginAdministrative(null)).thenReturn(adminSession);

    when(adminSession.hasPendingChanges()).thenReturn(true);
    operation.doRun(request, response, null);

    assertEquals(200, response.getStatusCode());
    verify(adminSession).save();
    verify(adminSession).logout();
  }
コード例 #5
0
ファイル: JCRStore.java プロジェクト: sunnygao/liferay-portal
  @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);
    }
  }
コード例 #6
0
ファイル: JCRStore.java プロジェクト: sunnygao/liferay-portal
  @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);
    }
  }
コード例 #7
0
 private void writePartAsFile(Session session, BodyPart part, String nodeName, Node parentNode)
     throws RepositoryException, MessagingException, IOException {
   Node fileNode = parentNode.addNode(nodeName, "nt:file");
   Node resourceNode = fileNode.addNode("jcr:content", "nt:resource");
   resourceNode.setProperty("jcr:mimeType", part.getContentType());
   resourceNode.setProperty(
       "jcr:data", session.getValueFactory().createValue(part.getInputStream()));
   resourceNode.setProperty("jcr:lastModified", Calendar.getInstance());
 }
コード例 #8
0
ファイル: JCRHelper.java プロジェクト: noobandy/ProjectIdea
  public void saveProfilePic(String username, InputStream inputStream) {
    Session session = null;
    try {
      session = repository.login(credentials);
      Node rootNode = session.getRootNode();
      Node userHomeFolder = null;
      if (rootNode.hasNode(username)) {
        userHomeFolder = rootNode.getNode(username);
      } else {
        userHomeFolder = rootNode.addNode(username, NodeType.NT_FOLDER);
      }

      Node userProfilePicFile = null;
      if (userHomeFolder.hasNode(username)) {
        userProfilePicFile = userHomeFolder.getNode(username);
      } else {
        userProfilePicFile = userHomeFolder.addNode(username, NodeType.NT_FILE);
      }

      Node userProfilePicData = null;

      if (userProfilePicFile.hasNode(username + ".jpg")) {
        userProfilePicData = userProfilePicFile.getNode(username + ".jpg");
      } else {
        userProfilePicData = userProfilePicFile.addNode(username + ".jpg", NodeType.NT_RESOURCE);
      }

      Binary value = session.getValueFactory().createBinary(inputStream);

      userProfilePicData.setProperty(Property.JCR_DATA, value);

      session.save();

    } catch (LoginException e) {

      new ApplicationException("Failed to authenticate with content repository", e);
    } catch (RepositoryException e) {

      new ApplicationException("failed to add file", e);
    } finally {
      if (session != null && session.isLive()) {
        session.logout();
      }
    }
  }
コード例 #9
0
 public void setUserDescription(
     Session session, final ITenant theTenant, final String userName, final String description)
     throws NotFoundException, RepositoryException {
   User jackrabbitUser = getJackrabbitUser(theTenant, userName, session);
   if ((jackrabbitUser == null)
       || !TenantUtils.isAccessibleTenant(
           theTenant == null
               ? tenantedUserNameUtils.getTenant(jackrabbitUser.getID())
               : theTenant)) {
     throw new NotFoundException(
         Messages.getInstance()
             .getString("AbstractJcrBackedUserRoleDao.ERROR_0003_USER_NOT_FOUND"));
   }
   if (description == null) {
     jackrabbitUser.removeProperty("description"); // $NON-NLS-1$
   } else {
     jackrabbitUser.setProperty(
         "description", session.getValueFactory().createValue(description)); // $NON-NLS-1$
   }
 }
コード例 #10
0
 public void setRoleDescription(
     Session session, final ITenant theTenant, final String roleName, final String description)
     throws NotFoundException, RepositoryException {
   Group jackrabbitGroup = getJackrabbitGroup(theTenant, roleName, session);
   if (jackrabbitGroup != null
       && TenantUtils.isAccessibleTenant(
           theTenant == null
               ? tenantedRoleNameUtils.getTenant(jackrabbitGroup.getID())
               : theTenant)) {
     if (description == null) {
       jackrabbitGroup.removeProperty("description"); // $NON-NLS-1$
     } else {
       jackrabbitGroup.setProperty(
           "description", session.getValueFactory().createValue(description)); // $NON-NLS-1$
     }
   } else {
     throw new NotFoundException(
         Messages.getInstance()
             .getString("AbstractJcrBackedUserRoleDao.ERROR_0002_ROLE_NOT_FOUND"));
   }
 }
コード例 #11
0
 /**
  * Update link status.
  *
  * @param session the session
  * @param queryCommand the query command
  * @throws Exception the exception
  */
 private void updateLinkStatus(Session session, String queryCommand) throws Exception {
   List<String> listBrokenLinks = new ArrayList<String>();
   ValueFactory valueFactory = session.getValueFactory();
   QueryManager queryManager = session.getWorkspace().getQueryManager();
   Query query = queryManager.createQuery(queryCommand, Query.SQL);
   QueryResult results = query.execute();
   NodeIterator iter = results.getNodes();
   for (; iter.hasNext(); ) {
     Node webContent = iter.nextNode();
     if (!webContent.isCheckedOut()
         || webContent.isLocked()
         || (webContent.isCheckedOut() && !webContent.getParent().isCheckedOut())) {
       continue;
     }
     Property links = webContent.getProperty("exo:links");
     Value[] oldValues = links.getValues();
     Value[] newValues = new Value[oldValues.length];
     for (int iValues = 0; iValues < oldValues.length; iValues++) {
       String oldLink = oldValues[iValues].getString();
       if (!oldLink.equals("")) {
         LinkBean linkBean = LinkBean.parse(oldLink);
         String oldUrl = linkBean.getUrl();
         String oldStatus = getLinkStatus(oldUrl);
         String updatedLink = new LinkBean(oldUrl, oldStatus).toString();
         if (LOG.isInfoEnabled()) {
           LOG.info(updatedLink);
         }
         newValues[iValues] = valueFactory.createValue(updatedLink);
         if (oldStatus.equals(LinkBean.STATUS_BROKEN)) {
           listBrokenLinks.add(oldUrl);
         }
       }
     }
     webContent.setProperty("exo:links", newValues);
     brokenLinksCache.put(webContent.getUUID(), listBrokenLinks);
   }
   session.save();
 }
コード例 #12
0
ファイル: NodeTypeLoader.java プロジェクト: JEBailey/sling
 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;
 }
コード例 #13
0
  /**
   * This method renders the given request URI using the Sling request processing and stores the
   * result at the request's location relative to the cache root folder. The request is processed in
   * the context of the given user's session.
   *
   * @param uri The request URI including selectors and extensions
   * @param configCacheRoot The cache root folder
   * @param admin The admin session used to store the result in the cache
   * @param session The user's session
   * @return <code>true</code> if the cache was updated
   */
  protected boolean renderResource(
      String uri, String configCacheRoot, Session admin, Session session)
      throws RepositoryException, ServletException, IOException {
    String cachePath = configCacheRoot + getTargetPath(uri);

    ResourceResolver resolver = null;
    try {
      resolver = createResolver(session.getUserID());

      // render resource
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      HttpServletRequest request = createRequest(uri);
      HttpServletResponse response = requestResponseFactory.createResponse(out);

      slingServlet.processRequest(request, response, resolver);
      response.getWriter().flush();

      // compare md5 checksum with cache
      String md5 = requestResponseFactory.getMD5(response);
      String md5Path = cachePath + "/" + JcrConstants.JCR_CONTENT + "/" + MD5_HASH_PROPERTY;

      if (!admin.propertyExists(md5Path) || !admin.getProperty(md5Path).getString().equals(md5)) {
        log.info("MD5 hash missing or not equal, updating content sync cache: {}", cachePath);

        JcrUtil.createPath(cachePath, "sling:Folder", "nt:file", admin, false);

        Node cacheContentNode =
            JcrUtil.createPath(cachePath + "/jcr:content", "nt:resource", admin);
        if (needsUtf8Encoding(response)) {
          cacheContentNode.setProperty(
              JcrConstants.JCR_DATA,
              admin
                  .getValueFactory()
                  .createBinary(
                      IOUtils.toInputStream(out.toString(response.getCharacterEncoding()))));
        } else {
          cacheContentNode.setProperty(
              JcrConstants.JCR_DATA,
              admin.getValueFactory().createBinary(new ByteArrayInputStream(out.toByteArray())));
        }
        cacheContentNode.setProperty(JcrConstants.JCR_LASTMODIFIED, Calendar.getInstance());
        if (response.getContentType() != null) {
          cacheContentNode.setProperty(JcrConstants.JCR_MIMETYPE, response.getContentType());
        }
        if (response.getCharacterEncoding() != null) {
          cacheContentNode.setProperty(JcrConstants.JCR_ENCODING, response.getCharacterEncoding());
        }

        cacheContentNode.addMixin(NT_MD5_HASH);
        cacheContentNode.setProperty(MD5_HASH_PROPERTY, md5);

        admin.save();

        return true;
      } else {
        log.info("Skipping update of content sync cache: {}", uri);

        return false;
      }
    } catch (LoginException e) {
      log.error("Creating resource resolver for resource rendering failed: ", e);
      return false;
    } finally {
      if (resolver != null) {
        resolver.close();
      }

      if (admin.hasPendingChanges()) {
        admin.refresh(false);
      }
    }
  }
コード例 #14
0
  /** {@inheritDoc} */
  public List<RepositoryFile> getDeletedFiles(
      final Session session,
      final PentahoJcrConstants pentahoJcrConstants,
      final String origParentFolderPath,
      final String filter)
      throws RepositoryException {
    Node trashNode = getOrCreateTrashInternalFolderNode(session, pentahoJcrConstants);

    // query Trash Structure 2
    QueryObjectModelFactory fac = session.getWorkspace().getQueryManager().getQOMFactory();
    final String selectorName = "selector"; // $NON-NLS-1$

    // selector
    final Selector selector = fac.selector("nt:base", selectorName); // $NON-NLS-1$
    // constraint1
    Constraint origParentFolderPathConstraint =
        fac.comparison(
            fac.propertyValue(selectorName, pentahoJcrConstants.getPHO_ORIGPARENTFOLDERPATH()),
            QueryObjectModelConstants.JCR_OPERATOR_EQUAL_TO,
            fac.literal(session.getValueFactory().createValue(origParentFolderPath)));
    // constraint2
    Constraint origNameConstraint = null;
    if (StringUtils.hasLength(filter)) {
      String convertedFilter = filter.replace('*', '%');
      origNameConstraint =
          fac.comparison(
              fac.propertyValue(selectorName, pentahoJcrConstants.getPHO_ORIGNAME()),
              QueryObjectModelConstants.JCR_OPERATOR_LIKE,
              fac.literal(session.getValueFactory().createValue(convertedFilter)));
    }
    // constraint3
    Constraint descendantNodeConstraint = fac.descendantNode(selectorName, trashNode.getPath());
    // AND together constraints
    Constraint allConstraints = fac.and(descendantNodeConstraint, origParentFolderPathConstraint);
    if (StringUtils.hasLength(filter)) {
      allConstraints = fac.and(allConstraints, origNameConstraint);
    }
    Query query = fac.createQuery(selector, allConstraints, null, null);
    QueryResult result =
        session
            .getWorkspace()
            .getQueryManager()
            .createQuery(query.getStatement(), Query.JCR_JQOM)
            .execute();

    NodeIterator nodeIter = result.getNodes();
    List<RepositoryFile> deletedFiles = new ArrayList<RepositoryFile>();

    while (nodeIter.hasNext()) {
      Node trashFileIdNode = nodeIter.nextNode();
      if (trashFileIdNode.hasNodes()) {
        // since the nodes returned by the query are the trash file ID nodes, need to
        // getNodes().nextNode() to get
        // first
        // (and only) child
        deletedFiles.add(
            nodeToDeletedFile(session, pentahoJcrConstants, trashFileIdNode.getNodes().nextNode()));
      } else {
        throw new RuntimeException(
            Messages.getInstance()
                .getString("DefaultDeleteHelper.ERROR_0002_NOT_CLEAN")); // $NON-NLS-1$
      }
    }

    // now we need to handle legacy trash since legacy trashed files don't have origParentFolderPath
    // property

    Set<RepositoryFile> mergedDeletedFiles = new HashSet<RepositoryFile>();
    mergedDeletedFiles.addAll(deletedFiles);
    mergedDeletedFiles.addAll(
        legacyGetDeletedFiles(
            session,
            pentahoJcrConstants,
            pathConversionHelper.relToAbs(origParentFolderPath),
            filter));

    List<RepositoryFile> mergedList = new ArrayList<RepositoryFile>(mergedDeletedFiles);
    Collections.sort(mergedList);
    return mergedList;
  }
コード例 #15
0
  @Test
  public void testAggregateIndex()
      throws IOException, RepositoryException, InterruptedException, ClientPoolException,
          StorageClientException, AccessDeniedException, ClassNotFoundException {
    RepositoryBase repositoryBase = RepositoryBaseTest.getRepositoryBase();
    Repository repository = repositoryBase.getRepository();
    Session session = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
    NodeTypeManager ntm = session.getWorkspace().getNodeTypeManager();

    NodeTypeTemplate ntt = ntm.createNodeTypeTemplate();
    ntt.setDeclaredSuperTypeNames(new String[] {"nt:unstructured"});
    ntt.setName("sakai:user-home");

    ntm.registerNodeType(ntt, true);

    Node rootNode = session.getRootNode();
    Node homeNode = rootNode.addNode("iebhome", "sakai:user-home");
    homeNode.setProperty("sling:resourceType", "sakai/user-home");
    Node publicNode = homeNode.addNode("public", "nt:unstructured");
    Node publicSub = publicNode.addNode("sub", "nt:unstructured");
    publicSub.setProperty("test", "The brown fox");
    Node publicSub2 = publicNode.addNode("sub2", "nt:unstructured");
    publicSub2.setProperty("test", "The brown fox");
    Node childFileNode = publicSub.addNode("childNode", "nt:file");
    Node resourceNode = childFileNode.addNode("jcr:content", "nt:resource");
    ValueFactory valueFactory = session.getValueFactory();
    InputStream fileStream = new ByteArrayInputStream(FILE_CONTENT.getBytes("UTF-8"));
    Binary binary = valueFactory.createBinary(fileStream);
    resourceNode.setProperty("jcr:data", binary);
    session.save();
    session.logout();

    Thread.sleep(100);

    session = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
    Node n = session.getNode("/iebhome/public/sub");
    Assert.assertEquals("The brown fox", n.getProperty("test").getString());

    QueryManager qm = session.getWorkspace().getQueryManager();
    {
      Query q =
          qm.createQuery(
              "//*[@sling:resourceType = 'sakai/user-home' and jcr:contains(.,'brown')]",
              Query.XPATH);
      QueryResult qr = q.execute();
      NodeIterator nodeIterator = qr.getNodes();
      Assert.assertTrue(nodeIterator.hasNext());
      Assert.assertEquals("/iebhome", nodeIterator.nextNode().getPath());
      Assert.assertFalse(nodeIterator.hasNext());
    }
    {
      Query q = qm.createQuery("//*[@sling:resourceType = 'sakai/user-home']", Query.XPATH);
      QueryResult qr = q.execute();
      NodeIterator nodeIterator = qr.getNodes();
      Assert.assertTrue(nodeIterator.hasNext());
      Assert.assertEquals("/iebhome", nodeIterator.nextNode().getPath());
      Assert.assertFalse(nodeIterator.hasNext());
    }
    {
      Query q = qm.createQuery("//*[jcr:contains(.,'brown')]", Query.XPATH);
      QueryResult qr = q.execute();
      NodeIterator nodeIterator = qr.getNodes();
      List<String> paths = new ArrayList<String>();
      while (nodeIterator.hasNext()) {
        paths.add(nodeIterator.nextNode().getPath());
      }

      Assert.assertTrue(paths.contains("/iebhome"));
      Assert.assertTrue(paths.contains("/iebhome/public/sub"));
      Assert.assertTrue(paths.contains("/iebhome/public/sub2"));
    }
    session.logout();
  }
コード例 #16
0
ファイル: Types.java プロジェクト: Jahia/jcrestapi
  @GET
  @Path("/{type}")
  @Produces({Utils.MEDIA_TYPE_APPLICATION_HAL_PLUS_JSON, MediaType.APPLICATION_JSON})
  public Object getByType(
      @PathParam("workspace") String workspace,
      @PathParam("language") String language,
      @PathParam("type") String type,
      @QueryParam("nameContains") List<String> nameConstraints,
      @QueryParam("orderBy") String orderBy,
      @QueryParam("limit") int limit,
      @QueryParam("offset") int offset,
      @QueryParam("depth") int depth,
      @Context UriInfo context) {

    if (API.isQueryDisabled()) {
      APIExceptionMapper.LOGGER.debug("Types endpoint is disabled. Attempted query on " + type);
      return Response.status(Response.Status.NOT_FOUND).build();
    }

    final String unescapedNodetype = Names.unescape(type);
    if (API.excludedNodeTypes.contains(unescapedNodetype)) {
      return Response.status(Response.Status.FORBIDDEN)
          .entity("'" + unescapedNodetype + "' is not available for querying.")
          .build();
    }

    Session session = null;

    try {

      session = getSession(workspace, language);
      final QueryObjectModelFactory qomFactory =
          session.getWorkspace().getQueryManager().getQOMFactory();
      final ValueFactory valueFactory = session.getValueFactory();
      final Selector selector = qomFactory.selector(unescapedNodetype, SELECTOR_NAME);

      // language constraint: either jcr:language doesn't exist or jcr:language is current language
      Constraint constraint =
          qomFactory.or(
              qomFactory.not(qomFactory.propertyExistence(SELECTOR_NAME, Constants.JCR_LANGUAGE)),
              stringComparisonConstraint(
                  qomFactory.propertyValue(SELECTOR_NAME, Constants.JCR_LANGUAGE),
                  language,
                  qomFactory,
                  valueFactory));

      // if we have passed "nameContains" query parameters, only return nodes which name contains
      // the specified terms
      if (nameConstraints != null && !nameConstraints.isEmpty()) {
        for (String name : nameConstraints) {
          final Comparison likeConstraint =
              qomFactory.comparison(
                  qomFactory.nodeLocalName(SELECTOR_NAME),
                  QueryObjectModelFactory.JCR_OPERATOR_LIKE,
                  qomFactory.literal(
                      valueFactory.createValue("%" + name + "%", PropertyType.STRING)));
          constraint = qomFactory.and(constraint, likeConstraint);
        }
      }

      Ordering[] orderings = null;
      // ordering deactivated because it currently doesn't work, probably due to a bug in
      // QueryServiceImpl
      if (Utils.exists(orderBy)) {
        if ("desc".equalsIgnoreCase(orderBy)) {
          orderings =
              new Ordering[] {qomFactory.descending(qomFactory.nodeLocalName(SELECTOR_NAME))};
        } else {
          orderings =
              new Ordering[] {qomFactory.ascending(qomFactory.nodeLocalName(SELECTOR_NAME))};
        }
      }

      final QueryObjectModel query =
          qomFactory.createQuery(
              selector,
              constraint,
              orderings,
              new Column[] {qomFactory.column(SELECTOR_NAME, null, null)});
      if (limit > 0) {
        query.setLimit(limit);
      }
      query.setOffset(offset);

      final QueryResult queryResult = query.execute();

      final NodeIterator nodes = queryResult.getNodes();
      final List<JSONNode> result = new LinkedList<JSONNode>();
      final Filter filter = Utils.getFilter(context);
      while (nodes.hasNext()) {
        final Node resultNode = nodes.nextNode();
        if (filter.acceptChild(resultNode)) {
          JSONNode node = getFactory().createNode(resultNode, filter, depth);
          result.add(node);
        }
      }

      return Response.ok(result).build();
    } catch (Exception e) {
      throw new APIException(e);
    } finally {
      closeSession(session);
    }
  }
コード例 #17
0
ファイル: JcrBean.java プロジェクト: pengliaoye/exchange
  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();
      }
    }
  }
コード例 #18
0
ファイル: JcrRdfTools.java プロジェクト: hardyoyo/fcrepo4
 /**
  * Create a JCR value from an RDFNode with the given JCR type
  *
  * @param data
  * @param type
  * @return
  * @throws RepositoryException
  */
 public Value createValue(final RDFNode data, final int type) throws RepositoryException {
   return createValue(session.getValueFactory(), data, type);
 }