public Resource next() {
   Principal nextPrincipal = principals.nextPrincipal();
   try {
     ResourceResolver resourceResolver = parent.getResourceResolver();
     if (resourceResolver != null) {
       Session session = resourceResolver.adaptTo(Session.class);
       if (session != null) {
         UserManager userManager = AccessControlUtil.getUserManager(session);
         if (userManager != null) {
           Authorizable authorizable = userManager.getAuthorizable(nextPrincipal.getName());
           if (authorizable != null) {
             String path;
             if (authorizable.isGroup()) {
               path = SYSTEM_USER_MANAGER_GROUP_PREFIX + nextPrincipal.getName();
             } else {
               path = SYSTEM_USER_MANAGER_USER_PREFIX + nextPrincipal.getName();
             }
             return new SakaiAuthorizableResource(authorizable, resourceResolver, path);
           }
         }
       }
     }
   } catch (RepositoryException re) {
     log.error("Exception while looking up authorizable resource.", re);
   }
   return null;
 }
 @Test
 public void testNonSiteNode() throws RepositoryException, JSONException {
   SiteSearchResultProcessor siteSearchResultProcessor = new SiteSearchResultProcessor();
   SiteService siteService = createMock(SiteService.class);
   siteSearchResultProcessor.bindSiteService(siteService);
   Row row = createMock(Row.class);
   Value val = createMock(Value.class);
   expect(val.getString()).andReturn("");
   expect(row.getValue("jcr:path")).andReturn(val);
   expect(siteService.isSite(isA(Item.class))).andReturn(false);
   Node resultNode = createMock(Node.class);
   expect(resultNode.getPath()).andReturn("");
   SlingHttpServletRequest request = createMock(SlingHttpServletRequest.class);
   ResourceResolver resourceResolver = createMock(ResourceResolver.class);
   Session session = createMock(Session.class);
   expect(request.getResourceResolver()).andReturn(resourceResolver);
   expect(resourceResolver.adaptTo(Session.class)).andReturn(session);
   expect(session.getItem("")).andReturn(resultNode);
   replay();
   try {
     siteSearchResultProcessor.writeNode(request, null, null, row);
     fail();
   } catch (JSONException e) {
     assertEquals("Unable to write non-site node result", e.getMessage());
   }
 }
  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();
  }
  /**
   * Converts the resource type to an absolute path. If it does not start with "/" the resource is
   * resolved via search paths using resource resolver. If not matching resource is found it is
   * returned unchanged.
   *
   * @param resourceType Resource type
   * @return Absolute resource type
   */
  public static String makeAbsolute(String resourceType, ResourceResolver resourceResolver) {
    if (StringUtils.isEmpty(resourceType) || StringUtils.startsWith(resourceType, "/")) {
      return resourceType;
    }

    // first try to resolve path via component manager - because on publish instance the original
    // resource may not accessible
    ComponentManager componentManager = resourceResolver.adaptTo(ComponentManager.class);
    if (componentManager != null) {
      Component component = componentManager.getComponent(resourceType);
      if (component != null) {
        return component.getPath();
      } else {
        return resourceType;
      }
    }

    // otherwise use resource resolver directly
    Resource resource = resourceResolver.getResource(resourceType);
    if (resource != null) {
      return resource.getPath();
    } else {
      return resourceType;
    }
  }
  @Test
  public void testFlush() throws Exception {
    final ResourceResolver resourceResolver = mock(ResourceResolver.class);
    final Session session = mock(Session.class);
    when(resourceResolver.adaptTo(Session.class)).thenReturn(session);

    final String path1 = "/content/foo";
    final String path2 = "/content/bar";

    dispatcherFlusher.flush(resourceResolver, path1, path2);

    verify(replicator, times(1))
        .replicate(
            eq(session),
            eq(ReplicationActionType.ACTIVATE),
            eq(path1),
            any(ReplicationOptions.class));

    verify(replicator, times(1))
        .replicate(
            eq(session),
            eq(ReplicationActionType.ACTIVATE),
            eq(path2),
            any(ReplicationOptions.class));

    verifyNoMoreInteractions(replicator);
  }
  public TrainingProductImpl(Resource resource) {
    super(resource);

    resourceResolver = resource.getResourceResolver();
    pageManager = resourceResolver.adaptTo(PageManager.class);
    productPage = pageManager.getContainingPage(resource);
  }
  @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();
  }
  @Test
  public void testRequestTrusted() throws RepositoryException {
    CreateSakaiUserServlet csus = new CreateSakaiUserServlet();

    JackrabbitSession session = createMock(JackrabbitSession.class);

    ResourceResolver rr = createMock(ResourceResolver.class);
    expect(rr.adaptTo(Session.class)).andReturn(session);

    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("typeA");
    RequestTrustValidatorService requestTrustValidatorService =
        createMock(RequestTrustValidatorService.class);
    RequestTrustValidator requestTrustValidator = createMock(RequestTrustValidator.class);
    expect(requestTrustValidatorService.getValidator("typeA")).andReturn(requestTrustValidator);
    expect(requestTrustValidator.getLevel()).andReturn(RequestTrustValidator.CREATE_USER);
    expect(requestTrustValidator.isTrusted(request)).andReturn(true);

    expect(request.getParameter(SlingPostConstants.RP_NODE_NAME)).andReturn("foo");
    expect(request.getParameter("pwd")).andReturn("bar");
    expect(request.getParameter("pwdConfirm")).andReturn("baz");

    HtmlResponse response = new HtmlResponse();

    csus.requestTrustValidatorService = requestTrustValidatorService;
    replay();

    try {
      csus.handleOperation(request, response, null);
      fail();
    } catch (RepositoryException e) {
      assertEquals("Password value does not match the confirmation password", e.getMessage());
    }
    verify();
  }
 public LockAwareComponentManager(ResourceResolver resolver) {
   this.wrapped = resolver.adaptTo(ComponentManager.class);
   this.lockManager = new ComponentLockRepository(resolver);
   try {
     principalIds = AuthorizableUtil.getPrincipalIds(resolver);
   } catch (RepositoryException e) {
     throw new IllegalStateException(e); // TODO
   }
 }
 @Before
 public void setup() throws Exception {
   stringWriter = new StringWriter();
   jsonWriter = new JSONWriter(stringWriter);
   activityNodes = new HashMap<String, Node>();
   resourceNodes = new HashMap<String, Node>();
   when(request.getResourceResolver()).thenReturn(resourceResolver);
   when(resourceResolver.adaptTo(Session.class)).thenReturn(session);
 }
  public void testAnonymous() throws Exception {
    Session session = mock(Session.class);
    when(session.getUserID()).thenReturn(UserConstants.ANON_USERID);
    ResourceResolver resolver = mock(ResourceResolver.class);
    when(resolver.adaptTo(Session.class)).thenReturn(session);

    when(request.getResourceResolver()).thenReturn(resolver);

    makeRequest();
    verify(response).sendError(HttpServletResponse.SC_FORBIDDEN);
  }
 private Node prepNode(ResourceResolver resolver, String path) throws RepositoryException {
   // Get the encoding node, remove it (as a way to easily remove all the existing presets), then
   // create the node again
   //
   Session session = resolver.adaptTo(Session.class);
   Node targetNode =
       JcrResourceUtil.createPath(path, "nt:unstructured", "nt:unstructured", session, false);
   Node parent = targetNode.getParent();
   String nodeName = targetNode.getName();
   targetNode.remove();
   return parent.addNode(nodeName);
 }
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    String path = TemplateUtils.getParameterValue("path", request);
    boolean success = false;

    if (path != null) {
      resourceResolver = request.getResourceResolver();
      session = resourceResolver.adaptTo(Session.class);
      success = removeNode(path);
    }

    response.getWriter().write("{\"success\":" + success + "}");
  }
  @Before
  public void before() throws ClientPoolException, StorageClientException, AccessDeniedException {

    javax.jcr.Session jcrSession =
        Mockito.mock(
            javax.jcr.Session.class,
            Mockito.withSettings().extraInterfaces(SessionAdaptable.class));
    session = repository.loginAdministrative("ieb");
    Mockito.when(((SessionAdaptable) jcrSession).getSession()).thenReturn(session);
    Mockito.when(resourceResolver.adaptTo(javax.jcr.Session.class)).thenReturn(jcrSession);
    when(request.getRemoteUser()).thenReturn("ieb");
    when(request.getResourceResolver()).thenReturn(resourceResolver);

    servlet = new LiteUserExistsServlet();
  }
  /*
   * (non-Javadoc)
   * @see
   * org.apache.sling.api.resource.ResourceProvider#listChildren(org.apache
   * .sling.api.resource.Resource)
   */
  public Iterator<Resource> listChildren(Resource parent) {
    if (parent == null) {
      throw new NullPointerException("parent is null");
    }
    try {
      String path = parent.getPath();
      ResourceResolver resourceResolver = parent.getResourceResolver();

      // handle children of /system/userManager
      if (SYSTEM_USER_MANAGER_PATH.equals(path)) {
        List<Resource> resources = new ArrayList<Resource>();
        if (resourceResolver != null) {
          resources.add(getResource(resourceResolver, SYSTEM_USER_MANAGER_USER_PATH));
          resources.add(getResource(resourceResolver, SYSTEM_USER_MANAGER_GROUP_PATH));
        }
        return resources.iterator();
      }

      int searchType = -1;
      if (SYSTEM_USER_MANAGER_USER_PATH.equals(path)) {
        searchType = PrincipalManager.SEARCH_TYPE_NOT_GROUP;
      } else if (SYSTEM_USER_MANAGER_GROUP_PATH.equals(path)) {
        searchType = PrincipalManager.SEARCH_TYPE_GROUP;
      }
      if (searchType != -1) {
        PrincipalIterator principals = null;

        // TODO: this actually does not work correctly since the
        // jackrabbit findPrincipals API
        // currently does an exact match of the search filter so it
        // won't match a wildcard
        Session session = resourceResolver.adaptTo(Session.class);
        if (session != null) {
          PrincipalManager principalManager = AccessControlUtil.getPrincipalManager(session);
          principals =
              principalManager.findPrincipals(".*", PrincipalManager.SEARCH_TYPE_NOT_GROUP);
        }

        if (principals != null) {
          return new ChildrenIterator(parent, principals);
        }
      }
    } catch (RepositoryException re) {
      throw new SlingException("Error listing children of resource: " + parent.getPath(), re);
    }

    return null;
  }
 @Before
 public void setUp() throws Exception {
   Map<String, Object> map = new HashMap<String, Object>();
   String path = "/content/geometrixx/en";
   map.put("path", path);
   ValueMap vm = new ValueMapDecorator(map);
   when(resource.getValueMap()).thenReturn(vm);
   when(resource.getResourceResolver()).thenReturn(resolver);
   when(resolver.adaptTo(PageManager.class)).thenReturn(manager);
   when(manager.getContainingPage(path)).thenReturn(referredpage);
   when(referredpage.getPath()).thenReturn(path);
   when(resource.listChildren()).thenReturn(iter);
   when(iter.hasNext()).thenReturn(false);
   when(resolver.getResource(path)).thenReturn(res);
   when(res.adaptTo(Page.class)).thenReturn(referredpage);
   when(referredpage.getName()).thenReturn("geometrixx");
   Calendar cal = GregorianCalendar.getInstance();
   when(referredpage.getLastModified()).thenReturn(cal);
 }
  @Test
  public void testMissingResource() throws RepositoryException {
    // This shouldn't really happen, but hey!
    SlingHttpServletRequest request = mock(SlingHttpServletRequest.class);
    HtmlResponse response = new HtmlResponse();

    ResourceResolver resolver = mock(ResourceResolver.class);
    when(resolver.adaptTo(Session.class)).thenReturn(session);

    Resource resource = mock(Resource.class);
    when(resource.adaptTo(Node.class)).thenReturn(null);
    when(request.getResource()).thenReturn(resource);
    when(request.getResourceResolver()).thenReturn(resolver);
    when(request.getRemoteUser()).thenReturn("john");

    operation.doRun(request, response, null);

    assertEquals(400, response.getStatusCode());
  }
  /*
   * (non-Javadoc)
   * @see
   * org.apache.sling.api.resource.ResourceProvider#getResource(org.apache
   * .sling.api.resource.ResourceResolver, java.lang.String)
   */
  public Resource getResource(ResourceResolver resourceResolver, String path) {

    // handle resources for the virtual container resources
    if (path.equals(SYSTEM_USER_MANAGER_PATH)) {
      return new SyntheticResource(resourceResolver, path, "sling/userManager");
    } else if (path.equals(SYSTEM_USER_MANAGER_USER_PATH)) {
      return new SyntheticResource(resourceResolver, path, "sling/users");
    } else if (path.equals(SYSTEM_USER_MANAGER_GROUP_PATH)) {
      return new SyntheticResource(resourceResolver, path, "sling/groups");
    }

    // the principalId should be the first segment after the prefix
    String pid = null;
    if (path.startsWith(SYSTEM_USER_MANAGER_USER_PREFIX)) {
      pid = path.substring(SYSTEM_USER_MANAGER_USER_PREFIX.length());
    } else if (path.startsWith(SYSTEM_USER_MANAGER_GROUP_PREFIX)) {
      pid = path.substring(SYSTEM_USER_MANAGER_GROUP_PREFIX.length());
    }

    if (pid != null) {
      if (pid.indexOf('/') != -1) {
        return null; // something bogus on the end of the path so bail
        // out now.
      }
      try {
        Session session = resourceResolver.adaptTo(Session.class);
        if (session != null) {
          UserManager userManager = AccessControlUtil.getUserManager(session);
          if (userManager != null) {
            Authorizable authorizable = userManager.getAuthorizable(pid);
            if (authorizable != null) {
              // found the Authorizable, so return the resource
              // that wraps it.
              return new SakaiAuthorizableResource(authorizable, resourceResolver, path);
            }
          }
        }
      } catch (RepositoryException re) {
        throw new SlingException("Error looking up Authorizable for principal: " + pid, re);
      }
    }
    return null;
  }
  @Test
  public void testMissingParams() throws RepositoryException {
    SlingHttpServletRequest request = mock(SlingHttpServletRequest.class);
    HtmlResponse response = new HtmlResponse();

    ResourceResolver resolver = mock(ResourceResolver.class);
    when(resolver.adaptTo(Session.class)).thenReturn(session);

    Resource resource = mock(Resource.class);
    Node node = new MockNode("/bla/bla");
    when(resource.adaptTo(Node.class)).thenReturn(node);

    when(request.getResource()).thenReturn(resource);
    when(request.getResourceResolver()).thenReturn(resolver);
    when(request.getRequestParameter("key")).thenReturn(null);
    when(request.getRemoteUser()).thenReturn("john");

    operation.doRun(request, response, null);

    assertEquals(400, response.getStatusCode());
  }
  @Test
  public void testFlush_2() throws Exception {
    final ResourceResolver resourceResolver = mock(ResourceResolver.class);
    final Session session = mock(Session.class);
    when(resourceResolver.adaptTo(Session.class)).thenReturn(session);

    final ReplicationActionType actionType = ReplicationActionType.DELETE;
    final boolean synchronous = false;

    final String path1 = "/content/foo";
    final String path2 = "/content/bar";

    dispatcherFlusher.flush(resourceResolver, actionType, synchronous, path1, path2);

    verify(replicator, times(1))
        .replicate(eq(session), eq(actionType), eq(path1), any(ReplicationOptions.class));

    verify(replicator, times(1))
        .replicate(eq(session), eq(actionType), eq(path2), any(ReplicationOptions.class));

    verifyNoMoreInteractions(replicator);
  }
  protected void simpleResultCountCheck(SearchResultProcessor processor)
      throws RepositoryException, JSONException {
    int itemCount = 12;
    QueryResult queryResult = createMock(QueryResult.class);
    RowIterator results = createMock(RowIterator.class);
    expect(queryResult.getRows()).andReturn(results);
    expect(results.getSize()).andReturn(500L).anyTimes();
    Row dummyRow = createMock(Row.class);
    Value val = createMock(Value.class);
    expect(val.getString()).andReturn("").times(itemCount);
    expect(dummyRow.getValue("jcr:path")).andReturn(val).times(itemCount);
    expect(results.hasNext()).andReturn(true).anyTimes();
    expect(results.nextRow()).andReturn(dummyRow).times(itemCount);
    SlingHttpServletRequest request = createMock(SlingHttpServletRequest.class);
    ResourceResolver resourceResolver = createMock(ResourceResolver.class);
    Session session = createMock(Session.class);
    Node resultNode = createMock(Node.class);
    expect(resultNode.getPath()).andReturn("/path/to/node").anyTimes();
    expect(resultNode.getName()).andReturn("node").anyTimes();
    expect(request.getResourceResolver()).andReturn(resourceResolver).times(itemCount);
    expect(resourceResolver.adaptTo(Session.class)).andReturn(session).times(itemCount);
    expect(session.getItem("")).andReturn(resultNode).times(itemCount);
    PropertyIterator propIterator = createMock(PropertyIterator.class);
    expect(propIterator.hasNext()).andReturn(false).anyTimes();
    expect(resultNode.getProperties()).andReturn(propIterator).anyTimes();

    replay();
    JSONWriter write = new JSONWriter(new PrintWriter(new ByteArrayOutputStream()));
    write.array();
    RowIterator iterator = queryResult.getRows();
    int i = 0;
    while (iterator.hasNext() && i < itemCount) {
      processor.writeNode(request, write, null, iterator.nextRow());
      i++;
    }
    write.endArray();
    verify();
  }
Exemple #22
0
 /**
  * Resolves a Node given one of three possible passed parameters: 1) A fully qualified path to a
  * Node (e.g. "/foo/bar/baz"), 2) a Node's UUID, or 3) the PoolId from a ContentPool.
  *
  * @param pathOrIdentifier One of three possible parameters: 1) A fully qualified path to a Node
  *     (e.g. "/foo/bar/baz"), 2) a Node's UUID, or 3) the PoolId from a ContentPool.
  * @param resourceResolver
  * @return If the Node cannot be resolved, <code>null</code> will be returned.
  * @throws IllegalArgumentException
  */
 public static Node resolveNode(
     final String pathOrIdentifier, final ResourceResolver resourceResolver) {
   if (pathOrIdentifier == null || "".equals(pathOrIdentifier)) {
     throw new IllegalArgumentException("Passed argument was null or empty");
   }
   if (resourceResolver == null) {
     throw new IllegalArgumentException("Resource resolver cannot be null");
   }
   Node node = null;
   try {
     if (pathOrIdentifier.startsWith("/")) { // it is a path specification
       Resource r = resourceResolver.resolve(pathOrIdentifier);
       if (r != null) {
         node = r.adaptTo(Node.class);
       }
     } else {
       // Not a full resource path, so try the two flavors of ID.
       Session session = resourceResolver.adaptTo(Session.class);
       // First, assume we have a UUID and try to resolve
       try {
         node = session.getNodeByIdentifier(pathOrIdentifier);
       } catch (RepositoryException e) {
         log.debug("Swallowed exception; i.e. normal operation: {}", e.getLocalizedMessage(), e);
       }
       if (node == null) {
         log.warn("Unable to Tag Content Pool at this time, tried {} ", pathOrIdentifier);
         // must not have been a UUID; resolve via poolId
         // final String poolPath = CreateContentPoolServlet.hash(pathOrIdentifier);
         // node = session.getNode(poolPath);
       }
     }
   } catch (Throwable e) {
     log.error(e.getLocalizedMessage(), e);
   }
   return node;
 }
  @Test
  public void testProperPost()
      throws ServletException, IOException, RepositoryException, JSONException,
          AccessDeniedException, StorageClientException {
    SlingHttpServletRequest request = createMock(SlingHttpServletRequest.class);
    SlingHttpServletResponse response = createMock(SlingHttpServletResponse.class);

    javax.jcr.Session jcrSession =
        Mockito.mock(
            javax.jcr.Session.class,
            Mockito.withSettings().extraInterfaces(SessionAdaptable.class));
    Session mockSession = mock(Session.class);
    ContentManager contentManager = mock(ContentManager.class);
    when(mockSession.getContentManager()).thenReturn(contentManager);
    Mockito.when(((SessionAdaptable) jcrSession).getSession()).thenReturn(mockSession);
    ResourceResolver resourceResolver = mock(ResourceResolver.class);
    Mockito.when(resourceResolver.adaptTo(javax.jcr.Session.class)).thenReturn(jcrSession);
    expect(request.getResourceResolver()).andReturn(resourceResolver);

    // Provide parameters
    String[] dimensions = new String[] {"16x16", "32x32"};
    addStringRequestParameter(request, "img", "/~johndoe/people.png");
    addStringRequestParameter(request, "save", "/~johndoe/breadcrumbs");
    addStringRequestParameter(request, "x", "10");
    addStringRequestParameter(request, "y", "10");
    addStringRequestParameter(request, "width", "70");
    addStringRequestParameter(request, "height", "70");
    addStringRequestParameter(request, "dimensions", StringUtils.join(dimensions, 0, ';'));
    expect(request.getRemoteUser()).andReturn("johndoe");

    String imagePath = "a:johndoe/people.png";
    when(contentManager.getInputStream(imagePath))
        .thenReturn(getClass().getClassLoader().getResourceAsStream("people.png"));
    when(contentManager.get(anyString())).thenReturn(new Content("foo", null));

    SparseContentResource someResource = mock(SparseContentResource.class);
    when(someResource.adaptTo(Content.class))
        .thenReturn(
            new Content(
                imagePath,
                ImmutableMap.of(
                    "mimeType", (Object) "image/png", "_bodyLocation", "2011/lt/zz/x8")));
    JackrabbitSession jrSession = mock(JackrabbitSession.class);
    SparseMapUserManager userManager = mock(SparseMapUserManager.class);
    when(userManager.getSession()).thenReturn(mockSession);
    when(jrSession.getUserManager()).thenReturn(userManager);
    when(resourceResolver.adaptTo(javax.jcr.Session.class)).thenReturn(jrSession);
    when(resourceResolver.getResource(anyString())).thenReturn(someResource);

    // Capture output.
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintWriter write = new PrintWriter(baos);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    expect(response.getWriter()).andReturn(write);

    replay();
    servlet.doPost(request, response);
    write.flush();

    String s = baos.toString("UTF-8");
    JSONObject o = new JSONObject(s);

    JSONArray files = o.getJSONArray("files");
    assertEquals(2, files.length());
    for (int i = 0; i < files.length(); i++) {
      String url = files.getString(i);
      assertEquals("/~johndoe/breadcrumbs/" + dimensions[i] + "_people.png", url);
    }
  }
  @Override
  protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    HtmlResponse htmlResponse = null;
    ResourceResolver adminResolver = null;
    Session adminSession = null;

    try {
      String email = request.getParameter(REQ_PRM_USERNAME);
      String password = request.getParameter(REQ_PRM_PASSWORD);
      String inviteKey = request.getParameter(REQ_PRM_INVITEKEY);
      String acceptStatus = request.getParameter(REQ_PRM_ACCEPT_STATUS);

      adminResolver = getAdminResolver();
      adminSession = adminResolver.adaptTo(Session.class);

      InvitationToken invToken =
          ccInvitationService.getInvitationTokenByTokenKey(inviteKey, adminResolver);
      if (invToken != null && invToken.isValid() && inviteKey.equals(invToken.getKey())) {

        // Gets user account if user is already configured. Gets null
        // otherwise.
        Resource configResource = CCUtils.getAccountResourceByUserEmail(adminResolver, email);
        if (configResource == null) { // Create configuration if not
          // present. For first time login

          // encrypt the password
          if (!crypto.isProtected(password)) {
            password = crypto.protect(password);
          }
          AccessToken token = null;
          try {
            token = imsService.getAccessToken(email, password);
          } catch (Exception e) {
            log.error(e.getMessage(), e);
            htmlResponse =
                HtmlStatusResponseHelper.createStatusResponse(false, "Invalid Credentials");
          }
          if (token != null) { // succesful login
            String configName = "invited_" + email;
            configName = configName.replace("@", "_at_").replaceAll("\\.", "_");
            PageManager pageManager = pageManagerFactory.getPageManager(adminResolver);
            pageManager.create(CC_CONFIG_ROOT, configName, configName, CC_CONFIG_PAGE_TEMPLATE);

            Node configNode = adminSession.getNode(CC_CONFIG_ROOT + "/" + configName);
            Node contentNode = configNode.getNode("jcr:content");
            contentNode.setProperty(CreativeCloudAccountConfig.PROPERTY_USERNAME, email);
            contentNode.setProperty("sling:resourceType", CreativeCloudAccountConfig.RESOURCE_TYPE);

            contentNode.setProperty(
                CreativeCloudAccountConfig.PROPERTY_ACCESS_TOKEN, token.getAccessToken());
            contentNode.setProperty(
                CreativeCloudAccountConfig.PROPERTY_REFRESH_TOKEN, token.getRefreshToken());
            contentNode.setProperty(
                CreativeCloudAccountConfig.PROPERTY_TOKEN_EXPIRES, token.getExpiresIn());
            contentNode.setProperty(CreativeCloudAccountConfig.PROPERTY_PASSWORD, password);

            Node pollConfigNode = contentNode.addNode(CreativeCloudAccountConfig.NN_POLLCONFIG);
            pollConfigNode.setProperty(
                CreativeCloudAccountConfig.PROPERTY_INTERVAL, importer.getMinimumInterval());
            pollConfigNode.setProperty(CreativeCloudAccountConfig.PROPERTY_ENABLED, true);

            configResource = adminResolver.getResource(contentNode.getPath());
            ccConfigService.initAccount(configResource);
          }
        } else {
          // Sets the jcr content node as the config node
          configResource = configResource.getChild("jcr:content");
        }
        if (acceptStatus != null && acceptStatus.equalsIgnoreCase("false")) {
          htmlResponse = HtmlStatusResponseHelper.createStatusResponse(true, "invitation declined");
        } else {
          String[] paths = invToken.getPaths();
          for (String path : paths) {
            // ccShareService.shareWithCCUser(configResource,
            // adminResolver.getResource(path));
            // Asynchronous sharing
            Object job =
                new CCShareInBackground(factory, configResource.getPath(), path, ccShareService);
            String jobName =
                CCShareInBackground.class.getName()
                    + "_"
                    + UUID.randomUUID().toString().substring(0, 8);
            scheduler.fireJobAt(jobName, job, null, new Date());
          }
          htmlResponse = HtmlStatusResponseHelper.createStatusResponse(true, "invitation accepted");
        }
        ccInvitationService.acceptInvitation(email, inviteKey, adminResolver);
        adminSession.save();

      } else {
        htmlResponse =
            HtmlStatusResponseHelper.createStatusResponse(
                false, "invitation expired or already accepted/declined");
      }
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      htmlResponse = HtmlStatusResponseHelper.createStatusResponse(false, e.getMessage());
      htmlResponse.setError(e);
    } finally {
      if (adminSession != null) {
        adminSession.logout();
      }
      if (adminResolver != null) {
        adminResolver.close();
      }
      assert htmlResponse != null;
      htmlResponse.send(response, true);
    }
  }
  @Test
  public void testCreate() throws Exception {

    // activate
    when(slingRepository.loginAdministrative(null)).thenReturn(adminSession);

    when(request.getResourceResolver()).thenReturn(resourceResolver);
    when(resourceResolver.adaptTo(javax.jcr.Session.class)).thenReturn(jcrSesson);
    Session session = repository.loginAdministrative("ieb");
    when(jcrSesson.getUserManager()).thenReturn(sparseMapUserManager);
    when(sparseMapUserManager.getSession()).thenReturn(session);
    when(clusterTrackingService.getClusterUniqueId())
        .thenReturn(String.valueOf(System.currentTimeMillis()));

    when(request.getRequestPathInfo()).thenReturn(requestPathInfo);
    when(requestPathInfo.getExtension()).thenReturn(null);

    when(adminSession.getUserManager()).thenReturn(userManager);
    when(adminSession.getPrincipalManager()).thenReturn(principalManager);
    when(adminSession.getAccessControlManager()).thenReturn(accessControlManager);
    when(request.getRemoteUser()).thenReturn("ieb");

    when(request.getRequestParameterMap()).thenReturn(requestParameterMap);
    Map<String, RequestParameter[]> map = new HashMap<String, RequestParameter[]>();

    RequestParameter[] requestParameters =
        new RequestParameter[] {
          requestParameter1, requestParameterNot, requestParameter2,
        };
    map.put("files", requestParameters);

    when(requestParameterMap.entrySet()).thenReturn(map.entrySet());

    when(requestParameter1.isFormField()).thenReturn(false);
    when(requestParameter1.getContentType()).thenReturn("application/pdf");
    when(requestParameter1.getFileName()).thenReturn("testfilename.pdf");
    InputStream input1 = new ByteArrayInputStream(new byte[10]);
    when(requestParameter1.getInputStream()).thenReturn(input1);

    when(requestParameter2.isFormField()).thenReturn(false);
    when(requestParameter2.getContentType()).thenReturn("text/html");
    when(requestParameter2.getFileName()).thenReturn("index.html");
    InputStream input2 = new ByteArrayInputStream(new byte[10]);
    when(requestParameter2.getInputStream()).thenReturn(input2);

    when(requestParameterNot.isFormField()).thenReturn(true);

    // deep create
    // when(adminSession.nodeExists(CreateContentPoolServlet.POOLED_CONTENT_ROOT)).thenReturn(true);
    when(adminSession.itemExists(Mockito.anyString())).thenReturn(true);

    // Because the pooled content paths are generated by a private method,
    // mocking the repository is more problematic than usual. The test
    // therefore relies on inside knowledge that there should be three
    // calls to deepGetOrCreateNode for each file: one for the pooled content
    // node, one for its members node, and one for the manager node.
    when(adminSession.getItem(Mockito.anyString()))
        .thenAnswer(
            new Answer<Item>() {
              public Item answer(InvocationOnMock invocation) throws Throwable {
                Object[] args = invocation.getArguments();
                String path = (String) args[0];
                if (path.endsWith(POOLED_CONTENT_MEMBERS_NODE)) {
                  return membersNode;
                } else if (path.endsWith("ieb")) {
                  return memberNode;
                } else {
                  return parentNode;
                }
              }
            });

    when(parentNode.addNode(JCR_CONTENT, NT_RESOURCE)).thenReturn(resourceNode);
    when(adminSession.getValueFactory()).thenReturn(valueFactory);
    when(valueFactory.createBinary(Mockito.any(InputStream.class))).thenReturn(binary);

    // access control utils
    accessControlList =
        new AccessControlList() {

          // Add an "addEntry" method so AccessControlUtil can execute something.
          // This method doesn't do anything useful.
          @SuppressWarnings("unused")
          public boolean addEntry(Principal principal, Privilege[] privileges, boolean isAllow)
              throws AccessControlException {
            return true;
          }

          public void removeAccessControlEntry(AccessControlEntry ace)
              throws AccessControlException, RepositoryException {}

          public AccessControlEntry[] getAccessControlEntries() throws RepositoryException {
            return new AccessControlEntry[0];
          }

          public boolean addAccessControlEntry(Principal principal, Privilege[] privileges)
              throws AccessControlException, RepositoryException {
            return false;
          }
        };
    when(accessControlManager.privilegeFromName(Mockito.anyString())).thenReturn(allPrivilege);
    AccessControlPolicy[] acp = new AccessControlPolicy[] {accessControlList};
    when(accessControlManager.getPolicies(Mockito.anyString())).thenReturn(acp);

    StringWriter stringWriter = new StringWriter();
    when(response.getWriter()).thenReturn(new PrintWriter(stringWriter));

    CreateContentPoolServlet cp = new CreateContentPoolServlet();
    cp.eventAdmin = eventAdmin;
    cp.clusterTrackingService = clusterTrackingService;
    cp.sparseRepository = repository;

    cp.doPost(request, response);

    // Verify that we created all the nodes.

    JSONObject jsonObject = new JSONObject(stringWriter.toString());
    Assert.assertNotNull(jsonObject.getString("testfilename.pdf"));
    Assert.assertNotNull(jsonObject.getString("index.html"));
    Assert.assertEquals(2, jsonObject.length());
  }
  /**
   * {@inheritDoc}
   *
   * @see
   *     org.apache.sling.api.servlets.SlingAllMethodsServlet#doPost(org.apache.sling.api.SlingHttpServletRequest,
   *     org.apache.sling.api.SlingHttpServletResponse)
   */
  @Override
  protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {

    // Check if the current user is logged in.
    if (request.getRemoteUser().equals("anonymous")) {
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Anonymous user cannot crop images.");
      return;
    }

    RequestParameter imgParam = request.getRequestParameter("img");
    RequestParameter saveParam = request.getRequestParameter("save");
    RequestParameter xParam = request.getRequestParameter("x");
    RequestParameter yParam = request.getRequestParameter("y");
    RequestParameter widthParam = request.getRequestParameter("width");
    RequestParameter heightParam = request.getRequestParameter("height");
    RequestParameter dimensionsParam = request.getRequestParameter("dimensions");

    if (imgParam == null
        || saveParam == null
        || xParam == null
        || yParam == null
        || widthParam == null
        || heightParam == null
        || dimensionsParam == null) {
      response.sendError(
          HttpServletResponse.SC_BAD_REQUEST,
          "The following parameters are required: img, save, x, y, width, height, dimensions");
      return;
    }

    try {
      // Grab the session
      ResourceResolver resourceResolver = request.getResourceResolver();
      Session session = resourceResolver.adaptTo(Session.class);

      String img = imgParam.getString();
      String save = saveParam.getString();
      int x = Integer.parseInt(xParam.getString());
      int y = Integer.parseInt(yParam.getString());
      int width = Integer.parseInt(widthParam.getString());
      int height = Integer.parseInt(heightParam.getString());
      String[] dimensionsList = StringUtils.split(dimensionsParam.getString(), ';');
      List<Dimension> dimensions = new ArrayList<Dimension>();
      for (String s : dimensionsList) {
        Dimension d = new Dimension();
        String[] size = StringUtils.split(s, 'x');
        int diWidth = Integer.parseInt(size[0]);
        int diHeight = Integer.parseInt(size[1]);

        diWidth = checkIntBiggerThanZero(diWidth, 0);
        diHeight = checkIntBiggerThanZero(diHeight, 0);

        d.setSize(diWidth, diHeight);
        dimensions.add(d);
      }

      x = checkIntBiggerThanZero(x, 0);
      y = checkIntBiggerThanZero(y, 0);
      width = checkIntBiggerThanZero(width, 0);
      height = checkIntBiggerThanZero(height, 0);

      // Make sure the save path is correct.
      save = PathUtils.normalizePath(save) + "/";

      String[] crop = CropItProcessor.crop(session, x, y, width, height, dimensions, img, save);

      JSONWriter output = new JSONWriter(response.getWriter());
      output.object();
      output.key("files");
      output.array();
      for (String url : crop) {
        output.value(url);
      }
      output.endArray();
      output.endObject();

    } catch (ArrayIndexOutOfBoundsException e) {
      response.sendError(
          HttpServletResponse.SC_BAD_REQUEST,
          "The dimensions have to be specified in a widthxheight;widthxheight fashion.");
      return;
    } catch (NumberFormatException e) {
      response.sendError(
          HttpServletResponse.SC_BAD_REQUEST,
          "The following parameters have to be integers: x, y, width, height. (Dimensions has to be of the form widthxheight;widthxheight");
      return;
    } catch (ImageException e) {
      // Something went wrong..
      logger.warn("ImageException e: " + e.getMessage());
      response.sendError(e.getCode(), e.getMessage());
    } catch (JSONException e) {
      response.sendError(500, "Unable to output JSON.");
    }
  }
 @Override
 public Session getSession() {
   return resourceResolver.adaptTo(Session.class);
 }
  @Test
  public void testRuleExecutionFromBundle() throws RepositoryException, RuleExecutionException {
    String path = "/test/ruleset";

    Mockito.when(request.getResourceResolver()).thenReturn(resourceResolver);
    Mockito.when(resourceResolver.adaptTo(Session.class)).thenReturn(session);
    Mockito.when(session.getUserID()).thenReturn("ieb");

    Mockito.when(resourceResolver.getResource(path)).thenReturn(ruleSet);
    Mockito.when(ruleSet.getResourceType()).thenReturn(RuleConstants.SAKAI_RULE_SET);
    Mockito.when(ruleSet.adaptTo(Node.class)).thenReturn(ruleSetNode);
    Mockito.when(context.getBundleContext()).thenReturn(bundleContext);

    Mockito.when(ruleSetNode.getPath()).thenReturn(path);
    Mockito.when(ruleSetNode.getNodes()).thenReturn(nodeIterator);

    // specify the rule processor
    Mockito.when(ruleSetNode.hasProperty(RuleConstants.PROP_SAKAI_RULE_EXECUTION_PREPROCESSOR))
        .thenReturn(true);
    Mockito.when(ruleSetNode.getProperty(RuleConstants.PROP_SAKAI_RULE_EXECUTION_PREPROCESSOR))
        .thenReturn(preprocessorProperty);
    Mockito.when(preprocessorProperty.getString()).thenReturn("message-test-preprocessor");

    // when the service referece is invoked we need to give it out processor
    Mockito.when(reference.getProperty(RuleConstants.PROCESSOR_NAME))
        .thenReturn("message-test-preprocessor");

    RuleExecutionPreProcessor messageRuleExcutionPreProcessor =
        new MesageRuleExcutionPreProcessor();
    Mockito.when(bundleContext.getService(reference)).thenReturn(messageRuleExcutionPreProcessor);

    // turn on debug for this rule execution, just needs the property to exist.
    Mockito.when(ruleSetNode.hasProperty(RuleConstants.PROP_SAKAI_RULE_DEBUG))
        .thenReturn(true, true, false);

    Mockito.when(nodeIterator.hasNext()).thenReturn(true, false, true, false);
    Mockito.when(nodeIterator.nextNode()).thenReturn(packageNode, packageNode);

    // its an nt:unstrucured node
    Mockito.when(packageNode.getPrimaryNodeType()).thenReturn(packageNodeType);
    Mockito.when(packageNodeType.getName()).thenReturn(NodeType.NT_UNSTRUCTURED);

    Mockito.when(packageNode.hasProperty(RuleConstants.PROP_SAKAI_BUNDLE_LOADER_CLASS))
        .thenReturn(true);

    Mockito.when(packageNode.getProperty(RuleConstants.PROP_SAKAI_BUNDLE_LOADER_CLASS))
        .thenReturn(packageBundleClass);
    Mockito.when(packageBundleClass.getString()).thenReturn(BundleLoaderRuleSet.class.getName());

    Mockito.when(packageNode.getPath()).thenReturn(path + "/package1");

    Mockito.when(packageNode.getProperty(Property.JCR_LAST_MODIFIED)).thenReturn(property);
    Calendar lastModified = GregorianCalendar.getInstance();
    lastModified.setTimeInMillis(System.currentTimeMillis());
    Calendar lastModifiedLater = GregorianCalendar.getInstance();
    lastModifiedLater.setTimeInMillis(System.currentTimeMillis() + 20000);
    Mockito.when(property.getDate()).thenReturn(lastModified, lastModified, lastModifiedLater);

    RuleExecutionServiceImpl res = new RuleExecutionServiceImpl();
    res.activate(context);
    res.bindProcessor(reference);
    Map<String, Object> result =
        res.executeRuleSet(path, request, targetResource, ruleContext, null);

    Assert.assertNotNull(result);
    Assert.assertTrue(result.size() > 0);

    // execute a second time to use the cache.
    result = res.executeRuleSet(path, request, targetResource, ruleContext, null);

    Assert.assertNotNull(result);
    Assert.assertTrue(result.size() > 0);

    // execute a third time time to reload.
    result = res.executeRuleSet(path, request, targetResource, ruleContext, null);

    Assert.assertNotNull(result);
    Assert.assertTrue(result.size() > 0);

    res.deactivate(context);
  }
  @Test
  public void testRuleExecution() throws RepositoryException, RuleExecutionException {
    String path = "/test/ruleset";

    Mockito.when(request.getResourceResolver()).thenReturn(resourceResolver);
    Mockito.when(resourceResolver.adaptTo(Session.class)).thenReturn(session);
    Mockito.when(session.getUserID()).thenReturn("ieb");

    Mockito.when(resourceResolver.getResource(path)).thenReturn(ruleSet);
    Mockito.when(ruleSet.getResourceType()).thenReturn(RuleConstants.SAKAI_RULE_SET);
    Mockito.when(ruleSet.adaptTo(Node.class)).thenReturn(ruleSetNode);
    Mockito.when(context.getBundleContext()).thenReturn(bundleContext);

    Mockito.when(ruleSetNode.getPath()).thenReturn(path);
    Mockito.when(ruleSetNode.getNodes()).thenReturn(nodeIterator);

    // specify the rule processor
    Mockito.when(ruleSetNode.hasProperty(RuleConstants.PROP_SAKAI_RULE_EXECUTION_PREPROCESSOR))
        .thenReturn(true);
    Mockito.when(ruleSetNode.getProperty(RuleConstants.PROP_SAKAI_RULE_EXECUTION_PREPROCESSOR))
        .thenReturn(preprocessorProperty);
    Mockito.when(preprocessorProperty.getString()).thenReturn("message-test-preprocessor");

    // when the service referece is invoked we need to give it out processor
    Mockito.when(reference.getProperty(RuleConstants.PROCESSOR_NAME))
        .thenReturn("message-test-preprocessor");

    RuleExecutionPreProcessor messageRuleExcutionPreProcessor =
        new MesageRuleExcutionPreProcessor();
    Mockito.when(bundleContext.getService(reference)).thenReturn(messageRuleExcutionPreProcessor);

    // turn on debug for this rule execution, just needs the property to exist.
    Mockito.when(ruleSetNode.hasProperty(RuleConstants.PROP_SAKAI_RULE_DEBUG))
        .thenReturn(true, true, false);

    Mockito.when(nodeIterator.hasNext()).thenReturn(true, false, true, false);
    Mockito.when(nodeIterator.nextNode()).thenReturn(packageNode, packageNode);
    Mockito.when(packageNode.getPrimaryNodeType()).thenReturn(packageNodeType);
    Mockito.when(packageNodeType.getName()).thenReturn(NodeType.NT_FILE);

    Mockito.when(packageNode.getPath()).thenReturn(path + "/package1");

    Mockito.when(packageNode.getNode(Node.JCR_CONTENT)).thenReturn(packageFileNode);

    Mockito.when(packageFileNode.getProperty(Property.JCR_LAST_MODIFIED)).thenReturn(property);
    Calendar lastModified = GregorianCalendar.getInstance();
    lastModified.setTimeInMillis(System.currentTimeMillis());
    Calendar lastModifiedLater = GregorianCalendar.getInstance();
    lastModifiedLater.setTimeInMillis(System.currentTimeMillis() + 20000);
    Mockito.when(property.getDate()).thenReturn(lastModified, lastModified, lastModifiedLater);

    Mockito.when(packageFileNode.getProperty(Property.JCR_DATA)).thenReturn(packageFileBody);

    Mockito.when(packageFileBody.getBinary()).thenReturn(binary);

    Mockito.when(binary.getStream())
        .thenAnswer(
            new Answer<InputStream>() {

              public InputStream answer(InvocationOnMock invocation) throws Throwable {
                return this.getClass()
                    .getResourceAsStream(
                        "/SLING-INF/content/var/rules/org.sakaiproject.nakamura.rules/org.sakaiproject.nakamura.rules.example/0.7-SNAPSHOT/org.sakaiproject.nakamura.rules.example-0.7-SNAPSHOT.pkg");
              }
            });

    RuleExecutionServiceImpl res = new RuleExecutionServiceImpl();
    res.activate(context);
    res.bindProcessor(reference);
    Map<String, Object> result =
        res.executeRuleSet(path, request, targetResource, ruleContext, null);

    Assert.assertNotNull(result);
    Assert.assertTrue(result.size() > 0);

    // execute a second time to use the cache.
    result = res.executeRuleSet(path, request, targetResource, ruleContext, null);

    Assert.assertNotNull(result);
    Assert.assertTrue(result.size() > 0);

    // execute a third time time to reload.
    result = res.executeRuleSet(path, request, targetResource, ruleContext, null);

    Assert.assertNotNull(result);
    Assert.assertTrue(result.size() > 0);

    res.deactivate(context);
  }
Exemple #30
0
  public SearchResult getResult() throws ForumException {

    if (null == result) {

      final PredicateGroup root = new PredicateGroup(PredicateGroup.TYPE);
      root.setAllRequired(true);

      String topicResourceType = null;
      String postResourceType = null;
      final Designer forumDesign = resolver.adaptTo(Designer.class);
      // -----------------< filter by paths >
      // -----------------------------------------------------------------
      final PredicateGroup pathFilter = new PredicateGroup("paths");
      pathFilter.setAllRequired(false);

      // -----------------< filter by resource type >
      // ----------------------------------------------------------
      final PredicateGroup resourceTypes = new PredicateGroup("resourceTypes");
      resourceTypes.setAllRequired(false);

      // no custom search paths specified, add default one
      if (pathFilter.size() == 0) {
        pathFilter.add(
            new Predicate("ugcRoot", PATH) {
              {
                set(PATH, PATH_UGC + "/content");
              }
            });
      }

      for (final String searchPath : searchPaths) {
        pathFilter.add(
            new Predicate(searchPath, PATH) {
              {
                set(PATH, PATH_UGC + searchPath);
              }
            });
        if (null != forumDesign) {
          final Resource forumResource = resolver.getResource(searchPath);
          final Style currentStyle = forumDesign.getStyle(forumResource);
          if (currentStyle != null) {
            topicResourceType = (String) currentStyle.get(PN_TOPIC_RESOURCETYPE);
            postResourceType = (String) currentStyle.get(PN_POST_RESOURCETYPE);
          }
        }
        if (topicResourceType != null) {
          final String _topicResourceType = topicResourceType;
          resourceTypes.add(
              new Predicate(topicResourceType, PROPERTY) {
                {
                  set(PROPERTY, SLING_RESOURCE_TYPE_PROPERTY);
                  set(VALUE, _topicResourceType);
                }
              });
        }
        if (postResourceType != null) {
          final String _postResourceType = postResourceType;
          resourceTypes.add(
              new Predicate(postResourceType, PROPERTY) {
                {
                  set(PROPERTY, SLING_RESOURCE_TYPE_PROPERTY);
                  set(VALUE, _postResourceType);
                }
              });
        }
      }

      resourceTypes.add(
          new Predicate(RESOURCE_TYPE_TOPIC, PROPERTY) {
            {
              set(PROPERTY, SLING_RESOURCE_TYPE_PROPERTY);
              set(VALUE, RESOURCE_TYPE_TOPIC);
            }
          });
      resourceTypes.add(
          new Predicate(RESOURCE_TYPE_POST, PROPERTY) {
            {
              set(PROPERTY, SLING_RESOURCE_TYPE_PROPERTY);
              set(VALUE, RESOURCE_TYPE_POST);
            }
          });

      // -----------------< filter by node type >
      // -------------------------------------------------------------
      final Predicate nodeTypeFilter =
          new Predicate(NODE_TYPE, TypePredicateEvaluator.TYPE) {
            {
              set(TypePredicateEvaluator.TYPE, NODE_TYPE);
            }
          };

      // -----------------< filter by query >
      // -------------------------------------------------------------
      final PredicateGroup fulltext = new PredicateGroup("fulltext");
      fulltext.setAllRequired(false);
      for (final String prop : getScopeProperties()) {
        fulltext.add(
            new Predicate(prop, FULLTEXT) {
              {
                set(FULLTEXT, getQuery());
                set(REL_PATH, "@" + prop);
              }
            });
      }

      // no custom properties to search, add default one
      if (fulltext.size() == 0) {
        fulltext.add(
            new Predicate(PN_SUBJECT, FULLTEXT) {
              {
                set(FULLTEXT, getQuery());
                set(REL_PATH, "@" + PN_SUBJECT);
              }
            });
      }

      // add predicates to root
      root.add(nodeTypeFilter);
      root.add(pathFilter);
      root.add(resourceTypes);
      root.add(fulltext);

      final QueryBuilder qb = resolver.adaptTo(QueryBuilder.class);
      final Query query = qb.createQuery(root, resolver.adaptTo(Session.class));
      query.setHitsPerPage(properties.get(PN_MAXPERPAGE, 10));
      query.setExcerpt(true);
      query.setStart(NumberUtils.toLong(request.getParameter(REQUEST_PARAM_START), 0));

      // add custom predicates
      for (final Predicate predicate : customPredicates) {
        query.getPredicates().add(predicate);
      }

      result = query.getResult();
    }

    return result;
  }