Example #1
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();
  }
  public void writeResults(
      SlingHttpServletRequest request, JSONWriter write, Iterator<Result> results)
      throws JSONException {
    ExtendedJSONWriter exWriter = (ExtendedJSONWriter) write;
    Session session =
        StorageClientUtils.adaptToSession(
            request.getResourceResolver().adaptTo(javax.jcr.Session.class));

    String currUser = request.getRemoteUser();
    try {
      // write out the profile information for each result
      while (results.hasNext()) {
        Result result = results.next();
        // start the object here so we can decorate with contact details
        write.object();
        super.writeResult(request, write, result, true);

        // add contact information if appropriate
        String otherUser = String.valueOf(result.getFirstValue("path"));
        connMgr.writeConnectionInfo(exWriter, session, currUser, otherUser);

        write.endObject();
      }
    } catch (StorageClientException e) {
      LOGGER.error(e.getMessage(), e);
    } catch (AccessDeniedException e) {
      LOGGER.error(e.getMessage(), e);
    }
  }
 public boolean accepts(SlingHttpServletRequest request) {
   log.debug("accepts(" + request.getRequestPathInfo().getResourcePath() + ")");
   if (request.getRequestPathInfo().getResourcePath().startsWith("/gather/sample")) {
     return true;
   }
   return false;
 }
 @Override
 protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
     throws ServletException, IOException {
   String paramUser = request.getParameter(SiteService.SiteEvent.USER);
   logger.info("Request to add user " + paramUser);
   String paramGroup = "";
   try {
     Node requestedNode = request.getResource().adaptTo(Node.class);
     Value[] authorizables = requestedNode.getProperty("sakai:authorizables").getValues();
     paramGroup = authorizables[1].getString();
     request.setAttribute(JoinRequestConstants.PARAM_SITENODE, requestedNode);
     Session session = slingRepository.loginAdministrative(null);
     UserManager userManager = AccessControlUtil.getUserManager(session);
     Authorizable userAuth = userManager.getAuthorizable(paramUser);
     Group groupAuth = (Group) userManager.getAuthorizable(paramGroup);
     if (siteJoinIsAuthorized(request)) {
       groupAuth.addMember(userAuth);
       logger.info(paramUser + " added as member of group " + paramGroup);
     } else {
       response.sendError(403, "Not authorized to add member to site.");
     }
     if (session.hasPendingChanges()) {
       session.save();
     }
   } catch (Exception e) {
     response.sendError(500, e.getMessage());
   }
 }
  /**
   * Adds the date range values to the search template.
   *
   * <pre>{@code
   * - _date-start
   * - _date-end
   *
   * }</pre>
   *
   * If there is no 'start' and 'end' request parameter, then the current day is used. A day starts
   * at 00:00 and ends the next day at 00:00
   *
   * @param request The request that has been done on the search node.
   * @param propertiesMap The map where the key-values should be added to.
   */
  protected void addStartEnd(SlingHttpServletRequest request, Map<String, String> propertiesMap) {
    try {
      // Default is today
      Calendar cStart = getDayCalendar();
      Calendar cEnd = getDayCalendar();
      cEnd.add(Calendar.DAY_OF_MONTH, 1);

      // If a parameter is specified, we try to parse it and use that one.
      RequestParameter startParam = request.getRequestParameter(START_DAY_PARAM);
      RequestParameter endParam = request.getRequestParameter(END_DAY_PARAM);
      if (startParam != null && endParam != null) {
        String start = startParam.getString("UTF-8");
        String end = endParam.getString("UTF-8");
        cStart.setTime(format.parse(start));
        cEnd.setTime(format.parse(end));
      }

      // Calculate the beginning and the end date.
      String beginning = DateUtils.iso8601jcr(cStart);
      String end = DateUtils.iso8601jcr(cEnd);

      // Add to map.
      propertiesMap.put("_date-start", ClientUtils.escapeQueryChars(beginning));
      propertiesMap.put("_date-end", ClientUtils.escapeQueryChars(end));
    } catch (UnsupportedEncodingException e) {
      LOGGER.error(
          "Caught an UnsupportedEncodingException when trying to provide properties for the calendar search templates.",
          e);
    } catch (ParseException e) {
      LOGGER.error(
          "Caught a ParseException when trying to provide properties for the calendar search templates.",
          e);
    }
  }
 public void writeResult(SlingHttpServletRequest request, JSONWriter write, Result result)
     throws JSONException {
   String contentPath = result.getPath();
   Session session =
       StorageClientUtils.adaptToSession(
           request.getResourceResolver().adaptTo(javax.jcr.Session.class));
   try {
     Content contentResult = session.getContentManager().get(contentPath);
     if (contentResult != null) {
       write.object();
       writeCanManageProperty(request, write, session, contentResult);
       writeCommentCountProperty(write, session, contentResult);
       int depth = SolrSearchUtil.getTraversalDepth(request);
       ExtendedJSONWriter.writeContentTreeToWriter(write, contentResult, true, depth);
       write.endObject();
     }
   } catch (AccessDeniedException ade) {
     // if access is denied we simply won't
     // write anything for this result
     // this implies content was private
     LOGGER.info("Denied {} access to {}", request.getRemoteUser(), contentPath);
     return;
   } catch (Exception e) {
     throw new JSONException(e);
   }
 }
  /**
   * This method sets the default properties on a comment being created. These properties are:
   *
   * <ul>
   *   <li>Date ({@link Comment#PROP_DATE}
   *   <li>Email ({@link CollabUser#PROP_EMAIL}
   *   <li>Website ({@link CollabUser#PROP_WEBSITE}
   *   <li>IP Address ({@link Comment#PROP_IP_ADDRESS}
   *   <li>User Agent ({@link Comment#PROP_USER_AGENT}
   *   <li>Referer ({@link Comment#PROP_REFERER}
   * </ul>
   *
   * @param request The request from which to retrieve the parameters for the properties to be set.
   * @param node The comment node upon which to set the properties.
   * @throws RepositoryException If an error occurs setting the properties.
   */
  protected void setCommentProperties(final SlingHttpServletRequest request, final Node node)
      throws RepositoryException {

    // date
    final Calendar cal = Calendar.getInstance();
    node.setProperty(Comment.PROP_DATE, cal);

    // email
    String email = request.getParameter(CollabUser.PROP_EMAIL);
    if (email == null) {
      email = "";
    }
    node.setProperty(CollabUser.PROP_EMAIL, email);

    // website
    String website = request.getParameter(CollabUser.PROP_WEBSITE);
    if (website == null) {
      website = "";
    } else if (!"".equals(website) && !website.matches("^.*\\:\\/\\/.*$")) {
      website = "http://" + website;
    }
    node.setProperty(CollabUser.PROP_WEBSITE, website);

    // ip
    node.setProperty(Comment.PROP_IP_ADDRESS, request.getRemoteAddr());
    // userAgent
    node.setProperty(Comment.PROP_USER_AGENT, request.getHeader("User-Agent"));
    // referer
    node.setProperty(Comment.PROP_REFERER, request.getHeader("Referer"));

    // authorizable id
    setAuthorizableId(request, node);

    log.debug("additional properties set on " + node.getPath());
  }
Example #8
0
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {

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

    String[] prefixes;
    try {
      Session session = (Session) request.getResourceResolver().adaptTo(Session.class);
      prefixes = session.getNamespacePrefixes();
    } catch (RepositoryException re) {
      prefixes = new String[] {""};
    }

    try {
      TidyJSONWriter out = new TidyJSONWriter(response.getWriter());
      out.setTidy("true".equals(request.getParameter(TIDY)));
      out.object();
      out.key("namespaces");
      out.array();
      for (String p : prefixes) {
        out.value(p);
      }
      out.endArray();
      out.endObject();
    } catch (JSONException e) {
      // todo...
    }
  }
  public void setUp() throws IOException {
    // Init mocks
    MockitoAnnotations.initMocks(this);

    Map<String, String[]> properties = new HashMap<String, String[]>();
    properties.put(WidgetServiceImpl.WIDGET_IGNORE_NAMES, new String[] {"bundles"});
    properties.put(
        WidgetServiceImpl.WIDGET_VALID_MIMETYPES,
        new String[] {
          "text/plain", "text/css", "text/html", "application/json", "application/xml"
        });
    properties.put(WidgetServiceImpl.WIDGET_FOLDERS, new String[] {"/widgets"});

    widgetService = new WidgetServiceImpl();
    widgetService.cacheManagerService = cacheManagerService;
    widgetService.activate(properties);

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

    // For test cases we will always assume that a locale of nl_NL is request.
    RequestParameter localeParam = mock(RequestParameter.class);
    when(localeParam.getString()).thenReturn("nl_NL");
    when(request.getRequestParameter("locale")).thenReturn(localeParam);

    // Mock the response print writer.
    stringWriter = new StringWriter();
    printWriter = new PrintWriter(stringWriter);
    when(response.getWriter()).thenReturn(printWriter);

    // Mock all the test resources as "Sling Resources".
    File file = new File(getClass().getResource("/widgets").getPath());
    mockResource("/widgets", file);
  }
 @Override
 protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
     throws ServletException, IOException {
   Resource resource = request.getResource();
   Node node = resource.adaptTo(Node.class);
   Content content = resource.adaptTo(Content.class);
   if (node != null) {
     try {
       Session jcrSession = request.getResourceResolver().adaptTo(Session.class);
       JSONWriter write = new JSONWriter(response.getWriter());
       FileUtils.writeLinkNode(node, jcrSession, write);
     } catch (JSONException e) {
       response.sendError(500, "Unable to parse JSON.");
     } catch (RepositoryException e) {
       LOGGER.warn("Unable to get file info for link.");
       response.sendError(500, "Unable get file info.");
     }
   } else {
     try {
       org.sakaiproject.nakamura.api.lite.Session session =
           resource.adaptTo(org.sakaiproject.nakamura.api.lite.Session.class);
       JSONWriter write = new JSONWriter(response.getWriter());
       FileUtils.writeLinkNode(content, session, write);
     } catch (StorageClientException e) {
       LOGGER.warn("Unable to get file info for link.");
       response.sendError(500, "Unable get file info.");
     } catch (JSONException e) {
       response.sendError(500, "Unable to parse JSON.");
     }
   }
 }
  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();
  }
  /** {@inheritDoc} */
  public void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    try {
      Resource resource = request.getResource();
      Node node = resource.adaptTo(Node.class);
      if (node == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
      }
      Version version = versionService.saveNode(node, request.getRemoteUser());

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

      ExtendedJSONWriter write = new ExtendedJSONWriter(response.getWriter());
      write.object();
      write.key("versionName");
      write.value(version.getName());
      ExtendedJSONWriter.writeNodeContentsToWriter(write, version);
      write.endObject();
    } catch (RepositoryException e) {
      LOGGER.info("Failed to save version ", e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
      return;
    } catch (JSONException e) {
      LOGGER.info("Failed to save version ", e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
      return;
    }
  }
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {

    // setup SSE headers
    response.setContentType("text/event-stream");
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Connection", "keep-alive");
    // needed to allow the JavaScript EventSource API to make a call from author to this server and
    // listen for the events
    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Allow-Credentials", "true");

    String agentName =
        request.getResource().getParent().getParent().adaptTo(ReplicationAgent.class).getName();
    PrintWriter writer = response.getWriter();
    while (true) {
      try {
        synchronized (cachedEvents) {
          cachedEvents.wait();
          Collection<String> eventsForAgent = cachedEvents.get(agentName);
          if (eventsForAgent != null) {
            for (String event : eventsForAgent) {
              writeEvent(writer, agentName + "-queue-event", event);
            }
          }
        }
      } catch (InterruptedException e) {
        log.error("error during SSE", e);
        throw new ServletException(e);
      }
    }
  }
 @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());
   }
 }
Example #15
0
  /**
   * Load properties from the query node, request and property provider.<br>
   * Overwrite order: query node &lt; request &lt; property provider<br>
   * This ordering allows the query node to set defaults, the request to override those defaults but
   * the property provider to have the final say in what value is set.
   *
   * @param request
   * @param propertyProviderName
   * @return
   * @throws RepositoryException
   */
  private Map<String, String> loadProperties(
      SlingHttpServletRequest request, String propertyProviderName, Node node)
      throws RepositoryException {
    Map<String, String> propertiesMap = new HashMap<String, String>();

    // 0. load authorizable (user) information
    String userId = request.getRemoteUser();
    String userPrivatePath = ClientUtils.escapeQueryChars(LitePersonalUtils.getPrivatePath(userId));
    propertiesMap.put("_userPrivatePath", userPrivatePath);
    propertiesMap.put("_userId", ClientUtils.escapeQueryChars(userId));

    // 1. load in properties from the query template node so defaults can be set
    PropertyIterator props = node.getProperties();
    while (props.hasNext()) {
      javax.jcr.Property prop = props.nextProperty();
      if (!propertiesMap.containsKey(prop.getName()) && !prop.isMultiple()) {
        propertiesMap.put(prop.getName(), prop.getString());
      }
    }

    // 2. load in properties from the request
    RequestParameterMap params = request.getRequestParameterMap();
    for (Entry<String, RequestParameter[]> entry : params.entrySet()) {
      String key = entry.getKey();
      RequestParameter[] vals = entry.getValue();
      String requestValue = vals[0].getString();

      // blank values aren't cool
      if (StringUtils.isBlank(requestValue)) {
        continue;
      }

      // KERN-1601 Wildcard searches have to be manually lowercased for case insensitive
      // matching as Solr bypasses the analyzer when dealing with a wildcard or fuzzy
      // search.
      if (StringUtils.contains(requestValue, '*') || StringUtils.contains(requestValue, '~')) {
        requestValue = requestValue.toLowerCase();
      }
      // KERN-1703 Escape just :
      requestValue = StringUtils.replace(requestValue, ":", "\\:");
      propertiesMap.put(entry.getKey(), requestValue);
    }

    // 3. load properties from a property provider
    if (propertyProviderName != null) {
      LOGGER.debug("Trying Provider Name {} ", propertyProviderName);
      SolrSearchPropertyProvider provider = propertyProvider.get(propertyProviderName);
      if (provider != null) {
        LOGGER.debug("Trying Provider {} ", provider);
        provider.loadUserProperties(request, propertiesMap);
      } else {
        LOGGER.warn("No properties provider found for {} ", propertyProviderName);
      }
    } else {
      LOGGER.debug("No Provider ");
    }

    return propertiesMap;
  }
Example #16
0
 @Test
 public void testAnonRequest() throws RepositoryException {
   SlingHttpServletRequest request = mock(SlingHttpServletRequest.class);
   when(request.getRemoteUser()).thenReturn(UserConstants.ANON_USERID);
   HtmlResponse response = new HtmlResponse();
   operation.doRun(request, response, null);
   assertEquals(403, response.getStatusCode());
 }
Example #17
0
 public ForumSearchImpl(final SlingHttpServletRequest request) {
   this.request = request;
   resolver = request.getResourceResolver();
   properties = ResourceUtil.getValueMap(request.getResource());
   searchPaths = properties.get(PN_SEARCHPATHS, new String[0]);
   query = getParameter(REQUEST_PARAM_QUERY);
   scopeProps = request.getParameterValues(REQUEST_PARAM_QUERY_SCOPE);
   request.setAttribute(ATTRIBUTE_NAME_SEARCH, this);
 }
Example #18
0
  public HtmlResponse performCommand(
      WCMCommandContext ctx,
      SlingHttpServletRequest request,
      SlingHttpServletResponse response,
      PageManager pageManager) {
    try {
      Page master = null;
      String srcPath = request.getParameter(WCMCommand.SRC_PATH_PARAM);
      if (StringUtils.isNotEmpty(srcPath)) {
        if (srcPath.endsWith("/jcr:content")) {
          srcPath = srcPath.substring(0, srcPath.length() - "/jcr:content".length());
        }
        master = pageManager.getPage(srcPath);
      }
      if (master == null) {
        return HtmlStatusResponseHelper.createStatusResponse(
            false, I18n.get(request, "Blueprint {0} not found.", "", srcPath));
      }

      boolean reset = "true".equals(request.getParameter(WCMCommand.FORCE_PARAM));

      String[] targets = request.getParameterValues(WCMCommand.DEST_PATH_PARAM);
      if (targets.length == 0) {
        return HtmlStatusResponseHelper.createStatusResponse(
            false, I18n.get(request, "No targets selected."));
      }

      int successCount = 0;
      int errorCount = 0;
      for (String target : targets) {
        try {
          Page targetPage = pageManager.getContainingPage(target);
          catalogGenerator.rolloutChanges(master, targetPage, reset);
          successCount++;
        } catch (Exception e) {
          log.error("Rollout failed for {}.", target, e);
          errorCount++;
        }
      }

      List<String> messages = new ArrayList<String>();
      messages.add(I18n.get(request, "Rollout Complete.  "));
      if (successCount > 0) {
        messages.add(I18n.get(request, "Rolled out changes to {0} catalogs.", "", successCount));
      }
      if (errorCount > 0) {
        messages.add(I18n.get(request, "Errors encountered in {0} catalogs.", "", errorCount));
      }
      return HtmlStatusResponseHelper.createStatusResponse(
          successCount > 0, messages.toArray(new String[messages.size()]), targets);
    } catch (Exception e) {
      String msg = I18n.get(request, "Error during rollout.");
      log.error(msg, e);
      return HtmlStatusResponseHelper.createStatusResponse(false, msg);
    }
  }
 /**
  * Return if origins are the same.
  *
  * @param request The sling request
  * @return if origins are the same.
  */
 protected Boolean isCORS(final SlingHttpServletRequest request) {
   if (null == externalizer) {
     return false;
   }
   final String localOrigin = externalizer.absoluteLink(request, request.getScheme(), "");
   if (!(localOrigin.equals(request.getHeader("Origin")))) {
     return true;
   }
   return false;
 }
Example #20
0
  @Test
  public void testAnon() throws IOException, ServletException {
    SlingHttpServletRequest request = createMock(SlingHttpServletRequest.class);
    SlingHttpServletResponse response = createMock(SlingHttpServletResponse.class);

    expect(request.getRemoteUser()).andReturn("anonymous");
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Anonymous user cannot crop images.");
    replay();
    servlet.doPost(request, response);
  }
  /**
   * @param request The request that contains the authorizables.
   * @param group The group that should be modified.
   * @param propertyName The name of the property on the group where the authorizable IDs should be
   *     added/deleted.
   * @param paramName The name of the parameter that contains the authorizable IDs. ie: :manager or
   *     :viewer. If :manager is specified, :manager@Delete will be used for deletes.
   * @param extraPropertyValues An array of authorizable IDs that should be added as well.
   * @param toSave
   * @throws RepositoryException
   */
  protected void handleAuthorizablesOnProperty(
      SlingHttpServletRequest request,
      Group group,
      String propertyName,
      String paramName,
      String[] extraPropertyValues,
      Map<String, Object> toSave) {
    Set<String> propertyValueSet = new HashSet<String>();

    if (group.hasProperty(propertyName)) {
      String[] existingProperties = (String[]) group.getProperty(propertyName);
      for (String property : existingProperties) {
        propertyValueSet.add(property);
      }
    }

    boolean changed = false;

    // Remove all the managers that are in the :manager@Delete request parameter.
    String[] propertiesToDelete =
        request.getParameterValues(paramName + SlingPostConstants.SUFFIX_DELETE);
    if (propertiesToDelete != null) {
      for (String propertyToDelete : propertiesToDelete) {
        propertyValueSet.remove(propertyToDelete);
        changed = true;
      }
    }

    // Add the new ones (if any)
    String[] proeprtiesToAdd = request.getParameterValues(paramName);
    if (proeprtiesToAdd != null) {
      for (String propertyToAdd : proeprtiesToAdd) {
        propertyValueSet.add(propertyToAdd);
        changed = true;
      }
    }

    // Add the extra ones (if any.)
    if (extraPropertyValues != null) {
      for (String propertyValue : extraPropertyValues) {
        propertyValueSet.add(propertyValue);
        changed = true;
      }
    }

    // Write the property.
    if (changed) {
      group.setProperty(
          propertyName, propertyValueSet.toArray(new String[propertyValueSet.size()]));
      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Adding to save Queue {} {}", group.getId(), group.getSafeProperties());
      }
      toSave.put(group.getId(), group);
    }
  }
  @Override
  public int doEndTag() throws JspException {
    final JspWriter out = pageContext.getOut();
    final SlingHttpServletRequest request = TagUtil.getRequest(pageContext);
    try {
      out.println(getScript(request, request.adaptTo(UserProperties.class)));

    } catch (IOException e) {
      throw new JspException("Could not write script for context profile property", e);
    }

    return EVAL_PAGE;
  }
  @Override
  public void doFilter(
      final ServletRequest request, final ServletResponse response, final FilterChain filterChain)
      throws IOException, ServletException {

    final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request;
    logger.debug(
        "request for {}, with selector {}",
        slingRequest.getRequestPathInfo().getResourcePath(),
        slingRequest.getRequestPathInfo().getSelectorString());

    filterChain.doFilter(request, response);
  }
 /**
  * Allow origin access control.
  *
  * @param request The sling request
  * @param response The sling response
  */
 protected void allowCORS(
     final SlingHttpServletRequest request, final SlingHttpServletResponse response) {
   if (null == externalizer) {
     return;
   }
   final String localOrigin = externalizer.absoluteLink(request, request.getScheme(), "");
   if (!(localOrigin.equals(request.getHeader("Origin")))) {
     response.setHeader("Access-Control-Allow-Credentials", "true");
     response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
     response.setHeader("Access-Control-Allow-Headers", "CONTENT-TYPE, LOCATION, *");
     response.setHeader("Access-Control-Expose-Headers", "Content-Type, Location");
   }
 }
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    // get current user
    String user = request.getRemoteUser();
    if (user == null) {
      response.sendError(
          HttpServletResponse.SC_UNAUTHORIZED, "User must be logged in to check their status");
    }
    LOGGER.info("GET to PresenceContactsServlet (" + user + ")");

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

    try {
      Writer writer = response.getWriter();
      ExtendedJSONWriter output = new ExtendedJSONWriter(writer);
      // start JSON object
      output.object();
      PresenceUtils.makePresenceJSON(output, user, presenceService, true);
      // add in the list of contacts info
      Session session = request.getResourceResolver().adaptTo(Session.class);
      List<String> userIds = connectionManager.getConnectedUsers(user, ConnectionState.ACCEPTED);
      output.key("contacts");
      output.array();
      for (String userId : userIds) {
        output.object();
        // put in the basics
        PresenceUtils.makePresenceJSON(output, userId, presenceService, true);
        // add in the profile
        output.key("profile");
        Authorizable au = PersonalUtils.getAuthorizable(session, userId);
        Node profileNode = (Node) session.getItem(PersonalUtils.getProfilePath(au));
        ExtendedJSONWriter.writeNodeToWriter(output, profileNode);
        output.endObject();
      }
      output.endArray();
      // finish it
      output.endObject();
    } catch (JSONException e) {
      LOGGER.error(e.getMessage(), e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (RepositoryException e) {
      LOGGER.error(e.getMessage(), e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }

    return;
  }
 /**
  * Set authorizable id.
  *
  * @param request The sling request.
  * @param node The node where the authorizableId property is set
  * @throws RepositoryException if there is an error when saving to repository
  */
 private void setAuthorizableId(final SlingHttpServletRequest request, final Node node)
     throws RepositoryException {
   final String userIdentifier = request.getParameter(CollabUser.PROP_NAME);
   final Profile sessionProfile = getSessionProfile(request);
   String sessionUserId = null;
   if (sessionProfile != null) {
     sessionUserId = sessionProfile.getAuthorizable().getID();
   }
   if (StringUtils.isNotBlank(sessionUserId)) {
     final boolean anonymous = "anonymous".equals(sessionUserId);
     final boolean authorMode = isAuthorMode();
     if (!anonymous && authorMode) {
       final boolean userExists = userExists(userIdentifier, node.getSession());
       final boolean hasPermissions =
           hasPermissions(userIdentifier, getRequestSession(request), node.getSession());
       // use node.getSession() because that's an admin session
       if (userExists && hasPermissions) {
         JcrUtil.setProperty(node, "authorizableId", userIdentifier);
         if (!userIdentifier.equals(sessionUserId)) {
           log.warn(
               "host {} posted a comment with different userIdentifier ({}) than sessionUserId ({})",
               new String[] {request.getRemoteAddr(), userIdentifier, sessionUserId});
         }
       } else {
         log.warn(
             "host {} posted a comment with an unknown userIdentifier ({})",
             request.getRemoteAddr(),
             userIdentifier);
       }
     } else if (!anonymous && !authorMode) {
       final String userId = sessionUserId;
       if (userIdentifier != null && !sessionUserId.equals(userIdentifier)) {
         final StringBuilder exception = new StringBuilder("host ");
         exception.append(request.getRemoteAddr());
         exception.append("posted a comment with suspect userIdentifier (");
         exception.append(userIdentifier);
         exception.append("), sessionUserId (");
         exception.append(sessionUserId);
         exception.append(")");
         final String exceptionMessage = exception.toString();
         if (log.isWarnEnabled()) {
           log.warn(exceptionMessage);
         }
         throw new CommentException(exceptionMessage);
       }
       JcrUtil.setProperty(node, "authorizableId", userId);
     }
   }
 }
  /**
   * @param searchProperties
   * @param p
   * @param request
   * @throws RepositoryException
   */
  protected void handlePropertyWithRegex(
      Map<String, Object> searchProperties, Property p, SlingHttpServletRequest request)
      throws RepositoryException {
    String searchPropertyName = p.getName().replace("sakai:search-prop-", "");
    String searchPropertyValue = "";
    String searchPropertyDefintion = p.getString();
    String searchPropertyRequestParameterName = parseRequestParamName(searchPropertyDefintion);
    if (request.getParameter(searchPropertyRequestParameterName) != null) {
      searchPropertyValue = request.getParameter(searchPropertyRequestParameterName);
    } else {
      searchPropertyValue = parseSearchPropertyDefaultValue(searchPropertyDefintion);
    }

    searchProperties.put(searchPropertyName, searchPropertyValue);
  }
  @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();
  }
 public Node getLibraryNode(SlingHttpServletRequest request, HtmlLibrary library) {
   Node node = null;
   try {
     // we want the non-minified version as the root path
     String cacheRoot =
         Text.getRelativeParent(
             (new StringBuilder(CACHE_PATH).append(library.getPath(false))).toString(), 1);
     String optPath =
         (new StringBuilder(cacheRoot).append("/").append(getLibraryName(library))).toString();
     node = JcrUtils.getNodeIfExists(optPath, getAdminSession());
     if (null == node) {
       // generate empty jcr:data to cache
       node = createEmptyCache(library, cacheRoot, getAdminSession());
     }
     // lib was modified after last cache write
     if (!node.hasNode(JcrConstants.JCR_CONTENT)
         || library.getLastModified(false)
             > JcrUtils.getLongProperty(
                 node.getNode(JcrConstants.JCR_CONTENT), JcrConstants.JCR_LASTMODIFIED, 0L)) {
       // generate new binary, if possible
       node = populateCache(library, node.getPath(), getAdminSession());
     }
     // reassign with user session
     node = request.getResourceResolver().resolve(node.getPath()).adaptTo(Node.class);
   } catch (RepositoryException re) {
     log.debug(re.getMessage());
   } finally {
     getResolver().close();
   }
   return node;
 }
Example #30
0
 /**
  * Makes a URL already built external; the url should be built by the 'getUrl' method.
  *
  * @param request the request as the externalization context
  * @param url the url value (the local URL)
  * @return
  */
 public static String getAbsoluteUrl(SlingHttpServletRequest request, String url) {
   if (!isExternalUrl(url) && url.startsWith("/")) {
     String scheme = request.getScheme().toLowerCase();
     url = scheme + "://" + getAuthority(request) + url;
   }
   return url;
 }