Ejemplo n.º 1
0
  @Before
  public void setUp() {
    MockSlingExtensions.setUp(context);

    context.addModelsForPackage("io.wcm.wcm.parsys.controller");

    context.request().setAttribute(ComponentContext.CONTEXT_ATTR_NAME, componentContext);
    when(componentContext.getComponent()).thenReturn(component);
    when(component.getPath()).thenReturn(RESOURCE_TYPE_SAMPLE);
    when(component.getProperties()).thenReturn(ImmutableValueMap.of());

    page = context.create().page("/content/page1", "/apps/sample/templates/test1");
    parsysResource = context.create().resource(page.getContentResource().getPath() + "/parsys");
    par1Resource =
        context
            .create()
            .resource(
                parsysResource.getPath() + "/par1",
                ImmutableValueMap.of("sling:resourceType", COMPONENT_PATH_1));
    par2Resource =
        context
            .create()
            .resource(
                parsysResource.getPath() + "/par2",
                ImmutableValueMap.of("sling:resourceType", COMPONENT_PATH_2));

    context.currentResource(parsysResource);
  }
Ejemplo n.º 2
0
  /** {@inheritDoc} */
  public static String getParentRelPath(final Resource resource) {

    Resource parent = resource.getParent();

    while (parent != null) {

      try {
        final Property primaryType =
            parent.adaptTo(Node.class).getProperty(JcrConstants.JCR_PRIMARYTYPE);

        if (primaryType.getString().equals(JcrConstants.NT_UNSTRUCTURED)) {
          // We reached the beginning of the comment tree so this must be
          // a comment.
          return null;
        } else if (primaryType.getString().equals(Comment.NODE_TYPE)) {
          // Found parent. Now return its relative path.
          final String nodePath = parent.getPath();
          int relPathStart =
              nodePath.indexOf(JcrConstants.JCR_CONTENT) + JcrConstants.JCR_CONTENT.length() + 2;
          relPathStart = nodePath.indexOf('/', relPathStart) + 1;
          final String relPath = nodePath.substring(relPathStart);
          return relPath;
        }
      } catch (final RepositoryException e) {
        log.error("Error computing parentRelPath for " + resource.getPath(), e);
        return null;
      }
      parent = parent.getParent();
    }

    return null;
  }
Ejemplo n.º 3
0
  @Test
  public void testOtherParentParsysResource() {
    parsysResource =
        context.create().resource(page.getContentResource().getPath() + "/parsysOther");
    par1Resource = context.create().resource(parsysResource.getPath() + "/par1");

    context.request().setAttribute(RA_PARSYS_PARENT_RESOURCE, parsysResource);

    WCMMode.EDIT.toRequest(context.request());
    Parsys parsys = context.request().adaptTo(Parsys.class);

    List<Item> items = parsys.getItems();
    assertEquals(2, items.size());

    Item item1 = items.get(0);
    assertEquals(par1Resource.getPath(), item1.getResourcePath());
    assertNull(item1.getResourceType());
    assertEquals(SECTION_DEFAULT_CLASS_NAME, item1.getCssClassName());
    assertFalse(item1.isNewArea());

    Item item2 = items.get(1);
    assertEquals(NEWAREA_RESOURCE_PATH, item2.getResourcePath());
    assertEquals(FALLBACK_NEWAREA_RESOURCE_TYPE, item2.getResourceType());
    assertEquals(
        NEWAREA_CSS_CLASS_NAME + " " + SECTION_DEFAULT_CLASS_NAME, item2.getCssClassName());
    assertTrue(item2.isNewArea());
  }
 protected void addOrUpdatePage(Resource pageRes, SolrClient solr) {
   if (pageRes == null) {
     LOG.error("Page does not exist to add/update in solr");
     return;
   }
   GeometrixxContentType dataPage = GeometrixxContentTypeFactory.getInstance(pageRes);
   try {
     LOG.info("Adding/updating page " + pageRes.getPath());
     solr.add(dataPage.getSolrDoc());
     solr.commit();
   } catch (Exception e) {
     LOG.error("Failure to add/update page " + pageRes.getPath(), e);
   }
 }
  protected static Map<String, Map<Long, ResponseValue>> getTallyResponses(Resource tallyResource)
      throws JSONException {
    Map<String, Map<Long, ResponseValue>> returnValue =
        new HashMap<String, Map<Long, ResponseValue>>();
    final ResourceResolver resolver = tallyResource.getResourceResolver();
    final String tallyPath = tallyResource.getPath();
    if (!tallyPath.startsWith("/content/usergenerated")) {
      tallyResource = resolver.resolve("/content/usergenerated" + tallyPath);
    }
    final Resource responsesNode = tallyResource.getChild(TallyConstants.RESPONSES_PATH);
    if (responsesNode == null) {
      return null;
    }
    NestedBucketStorageSystem bucketSystem = getBucketSystem(responsesNode);
    if (null == bucketSystem) {
      return null;
    }

    final Iterator<Resource> buckets = bucketSystem.listBuckets();
    while (buckets.hasNext()) {
      final Resource bucketResource = buckets.next();
      final Node bucketNode = bucketResource.adaptTo(Node.class);
      try {
        final NodeIterator userNodesInBucket = bucketNode.getNodes();
        while (userNodesInBucket.hasNext()) {
          final Node userNode = userNodesInBucket.nextNode();
          final NestedBucketStorageSystem userBucketSystem =
              getBucketSystem(resolver.getResource(userNode.getPath()));
          final Iterator<Resource> userBuckets = userBucketSystem.listBuckets();
          final Map<Long, ResponseValue> userReturnValue = new HashMap<Long, ResponseValue>();
          while (userBuckets.hasNext()) {
            final NodeIterator userResponses = userBuckets.next().adaptTo(Node.class).getNodes();
            while (userResponses.hasNext()) {
              final Node responseNode = userResponses.nextNode();
              final Long responseTimestamp = responseNode.getProperty(TIMESTAMP_PROPERTY).getLong();
              userReturnValue.put(
                  responseTimestamp,
                  new PollResponse(responseNode.getProperty(RESPONSE_PROPERTY).getString()));
            }
          }
          returnValue.put(userNode.getName(), userReturnValue);
        }
      } catch (final RepositoryException e) {
        throw new JSONException(
            "Error trying to read user responses from bucket in " + bucketResource.getPath(), e);
      }
    }
    return returnValue;
  }
  /*
   * (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;
  }
  public static void extractAttachment(
      final Writer ioWriter, final JSONWriter writer, final Resource node)
      throws JSONException, UnsupportedEncodingException {
    Resource contentNode = node.getChild("jcr:content");
    if (contentNode == null) {
      writer.key(ContentTypeDefinitions.LABEL_ERROR);
      writer.value(
          "provided resource was not an attachment - no content node beneath " + node.getPath());
      return;
    }
    ValueMap content = contentNode.adaptTo(ValueMap.class);
    if (!content.containsKey("jcr:mimeType") || !content.containsKey("jcr:data")) {
      writer.key(ContentTypeDefinitions.LABEL_ERROR);
      writer.value(
          "provided resource was not an attachment - content node contained no attachment data under "
              + node.getPath());
      return;
    }
    writer.key("filename");
    writer.value(URLEncoder.encode(node.getName(), "UTF-8"));
    writer.key("jcr:mimeType");
    writer.value(content.get("jcr:mimeType"));

    try {
      ioWriter.write(",\"jcr:data\":\"");
      final InputStream data = (InputStream) content.get("jcr:data");
      byte[] byteData = new byte[DATA_ENCODING_CHUNK_SIZE];
      int read = 0;
      while (read != -1) {
        read = data.read(byteData);
        if (read > 0 && read < DATA_ENCODING_CHUNK_SIZE) {
          // make a right-size container for the byte data actually read
          byte[] byteArray = new byte[read];
          System.arraycopy(byteData, 0, byteArray, 0, read);
          byte[] encodedBytes = Base64.encodeBase64(byteArray);
          ioWriter.write(new String(encodedBytes));
        } else if (read == DATA_ENCODING_CHUNK_SIZE) {
          byte[] encodedBytes = Base64.encodeBase64(byteData);
          ioWriter.write(new String(encodedBytes));
        }
      }
      ioWriter.write("\"");
    } catch (IOException e) {
      writer.key(ContentTypeDefinitions.LABEL_ERROR);
      writer.value(
          "IOException while getting attachment at " + node.getPath() + ": " + e.getMessage());
    }
  }
 /**
  * Used to get Full form of URL from the Given Short Page URL
  *
  * @param pageFullPath
  * @return {@link String}
  * @throws Exception
  */
 public static String getFullURLPath(String shortUrlPath) throws Exception {
   ResourceResolver resourceResolver = null;
   try {
     Bundle bndl = FrameworkUtil.getBundle(ResourceResolverFactory.class);
     BundleContext bundleContext = bndl.getBundleContext();
     ServiceReference ref =
         bundleContext.getServiceReference(ResourceResolverFactory.class.getName());
     ResourceResolverFactory resolverFactory =
         (ResourceResolverFactory) bundleContext.getService(ref);
     resourceResolver = resolverFactory.getAdministrativeResourceResolver(null);
     Resource resource = resourceResolver.resolve(shortUrlPath);
     if (null != resource) {
       return java.net.URLDecoder.decode(resource.getPath(), "UTF-8");
     } else {
       if (LOGGER.isDebugEnabled()) {
         LOGGER.debug("Resource doesn't exists..." + shortUrlPath);
       }
     }
   } catch (Exception e) {
     LOGGER.error(
         " Error while getting Full URL for the path :"
             + shortUrlPath
             + " and the error message is :",
         e);
   } finally {
     resourceResolver.close();
   }
   return shortUrlPath;
 }
 private void assertConfigurationIds(String resourcePath, String... configurationIds) {
   List<String> expectedConfigurationIds = ImmutableList.copyOf(configurationIds);
   when(resource.getPath()).thenReturn(resourcePath);
   List<String> detectedConfigurationIds =
       ImmutableList.copyOf(underTest.findConfigurationIds(resource));
   assertEquals(expectedConfigurationIds, detectedConfigurationIds);
 }
  @Override
  public void sendMail(String emailRecipient, String message) {
    try {
      /*Should use subservice to get administrative resource resolver instead of this code*/
      ResourceResolver resourceResolver =
          resourceResolverFactory.getAdministrativeResourceResolver(null);
      Resource templateResource = resourceResolver.getResource(RabbitMQUtil.EMAIL_TEMPLATE_PATH);
      if (templateResource.getChild("file") != null) {
        templateResource = templateResource.getChild("file");
      }
      ArrayList<InternetAddress> emailRecipients = new ArrayList<InternetAddress>();
      final MailTemplate mailTemplate =
          MailTemplate.create(
              templateResource.getPath(),
              templateResource.getResourceResolver().adaptTo(Session.class));
      HtmlEmail email = new HtmlEmail();
      Map<String, String> mailTokens = new HashMap<String, String>();
      mailTokens.put("message", message);
      mailTokens.put("subject", "Dummy Subject");
      mailTokens.put("email", emailRecipient);
      if (mailTemplate != null) {

        emailRecipients.add(new InternetAddress(emailRecipient));
        email.setTo(emailRecipients);
        email.setSubject("Dummy Mail");
        email.setTextMsg(message);
        messageGateway = messageGatewayService.getGateway(HtmlEmail.class);
        messageGateway.send(email);
      }
    } catch (Exception e) {
      /*Put message in queue again in case of exception.. Based on type of exception, it can be decided whether it has to be put in queue again or not*/
      RabbitMQUtil.addMessageToQueue(scrService);
      e.printStackTrace(System.out);
    }
  }
Ejemplo n.º 11
0
  /**
   * 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;
    }
  }
  /**
   * Extract the value of a MultiFieldPanel property into a list of maps. Will never return a null
   * map, but may return an empty one. Invalid property values are logged and skipped.
   *
   * @param resource the resource
   * @param name the property name
   * @return a list of maps.
   */
  @Function
  public static List<Map<String, String>> getMultiFieldPanelValues(Resource resource, String name) {
    ValueMap map = resource.adaptTo(ValueMap.class);
    List<Map<String, String>> results = new ArrayList<Map<String, String>>();
    if (map.containsKey(name)) {
      String[] values = map.get(name, new String[0]);
      for (String value : values) {

        try {
          JSONObject parsed = new JSONObject(value);
          Map<String, String> columnMap = new HashMap<String, String>();
          for (Iterator<String> iter = parsed.keys(); iter.hasNext(); ) {
            String key = iter.next();
            String innerValue = parsed.getString(key);
            columnMap.put(key, innerValue);
          }

          results.add(columnMap);

        } catch (JSONException e) {
          log.error(
              String.format("Unable to parse JSON in %s property of %s", name, resource.getPath()),
              e);
        }
      }
    }
    return results;
  }
Ejemplo n.º 13
0
  private void updateEncodingPresets(Resource configResource, S7Config s7Config, String typeHandle)
      throws RepositoryException {

    // Get the presets from S7 and store them on the node
    //
    List<Scene7PropertySet> propertySets = scene7Service.getPropertySets(typeHandle, s7Config);

    String path = configResource.getPath() + "/" + Scene7PresetsService.REL_PATH_ENCODING_PRESETS;
    Node node = prepNode(configResource.getResourceResolver(), path);
    Node presetNode;
    int i = 0;
    for (Scene7PropertySet propertySet : propertySets) {
      String handle = propertySet.getSetHandle();
      String nodeName = getNodeName(handle);
      if (StringUtils.isNotBlank(nodeName)) {
        presetNode = node.addNode(nodeName);
        presetNode.setProperty("handle", handle);
        Map<String, String> properties = propertySet.getProperties();
        for (String key : properties.keySet()) {
          String value = properties.get(key);
          key = StringUtils.uncapitalize(key);
          presetNode.setProperty(key, value);
        }
      }
    }
  }
Ejemplo n.º 14
0
  @Test
  public void testEditMode_Customized() {
    when(component.getProperties())
        .thenReturn(
            ImmutableValueMap.builder()
                .put(PN_PARSYS_GENERATE_DEAFULT_CSS, false)
                .put(PN_PARSYS_PARAGRAPH_CSS, "paracss")
                .put(PN_PARSYS_NEWAREA_CSS, "newareacss")
                .put(PN_PARSYS_PARAGRAPH_ELEMENT, "li")
                .put(PN_PARSYS_WRAPPER_ELEMENT, "ul")
                .put(PN_PARSYS_WRAPPER_CSS, "wrappercss")
                .build());

    WCMMode.EDIT.toRequest(context.request());
    Parsys parsys = context.request().adaptTo(Parsys.class);

    assertTrue(parsys.isWrapperElement());
    assertEquals("wrappercss", parsys.getWrapperCss());
    assertEquals("ul", parsys.getWrapperElementName());

    List<Item> items = parsys.getItems();
    assertEquals(3, items.size());

    Item item1 = items.get(0);
    assertEquals(par1Resource.getPath(), item1.getResourcePath());
    assertNull(item1.getResourceType());
    assertNull(item1.getStyle());
    assertEquals("paracss", item1.getCssClassName());
    assertEquals("li", item1.getElementName());
    assertFalse(item1.isNewArea());

    Item item2 = items.get(1);
    assertEquals(par2Resource.getPath(), item2.getResourcePath());
    assertNull(item2.getResourceType());
    assertNull(item2.getStyle());
    assertEquals("paracss", item2.getCssClassName());
    assertEquals("li", item2.getElementName());
    assertFalse(item2.isNewArea());

    Item item3 = items.get(2);
    assertEquals(NEWAREA_RESOURCE_PATH, item3.getResourcePath());
    assertEquals(FALLBACK_NEWAREA_RESOURCE_TYPE, item3.getResourceType());
    assertNull(item3.getStyle());
    assertEquals(NEWAREA_CSS_CLASS_NAME + " newareacss", item3.getCssClassName());
    assertEquals("li", item3.getElementName());
    assertTrue(item3.isNewArea());
  }
Ejemplo n.º 15
0
 /**
  * Get the comment system for the given resource.
  *
  * @param r The resource for which to retrieve the comment system.
  * @param session The {@link Session}.
  * @return The {@link com.day.cq.collab.commons.CommentSystem}.
  */
 protected CommentSystem getCommentSystem(final Resource r, final Session session) {
   final Resource res = getResourceResolver(session).resolve(r.getPath());
   if (null != res) {
     return res.adaptTo(CommentSystem.class);
   } else {
     return null;
   }
 }
Ejemplo n.º 16
0
  @Test
  public void testWcmDisabledMode() {
    WCMMode.DISABLED.toRequest(context.request());
    Parsys parsys = context.request().adaptTo(Parsys.class);

    List<Item> items = parsys.getItems();
    assertEquals(2, items.size());

    Item item1 = items.get(0);
    assertEquals(par1Resource.getPath(), item1.getResourcePath());
    assertNull(item1.getResourceType());
    assertEquals(SECTION_DEFAULT_CLASS_NAME, item1.getCssClassName());
    assertFalse(item1.isNewArea());

    Item item2 = items.get(1);
    assertEquals(par2Resource.getPath(), item2.getResourcePath());
    assertNull(item2.getResourceType());
    assertEquals(SECTION_DEFAULT_CLASS_NAME, item2.getCssClassName());
    assertFalse(item2.isNewArea());
  }
Ejemplo n.º 17
0
  private void updateViewerPresets(Resource configResource, S7Config s7Config)
      throws RepositoryException {

    // Get the presets from S7 and store them on the node
    //
    List<Scene7Asset> assets =
        scene7Service.searchAssets(
            s7Config.getBasePath(),
            Boolean.TRUE,
            Boolean.TRUE,
            new String[] {"ViewerPreset"},
            null,
            new String[] {
              "assetArray/items/assetHandle",
              "assetArray/items/type",
              "assetArray/items/name",
              "assetArray/items/viewerPresetInfo"
            },
            null,
            s7Config);

    if (assets.size() > 0) {
      String path = configResource.getPath() + "/" + Scene7PresetsService.REL_PATH_VIEWER_PRESETS;

      Node node = prepNode(configResource.getResourceResolver(), path);
      int i = 0;
      for (Scene7Asset asset : assets) {
        String name = asset.getName();
        String type = asset.getViewerPresetType();

        Node presetNode = node.addNode("preset" + i);
        presetNode.setProperty("name", name);
        presetNode.setProperty("type", (type != null ? type : ""));
        presetNode.setProperty("config", s7Config.getBasePath() + name);

        Map<String, String> viewerPresetConfigurationSettings =
            asset.getViewerPresetConfigurationSettings();
        if (viewerPresetConfigurationSettings != null
            && !viewerPresetConfigurationSettings.isEmpty()) {
          presetNode = presetNode.addNode("settings");
          for (Entry<String, String> entry : viewerPresetConfigurationSettings.entrySet()) {
            String settingName = entry.getKey();
            String value = entry.getValue();
            if (settingName != null && value != null) {
              presetNode.setProperty(settingName, value);
            }
          }
        }
        i++;
      }
    }
  }
Ejemplo n.º 18
0
  /**
   * Writes a proper UGC response to the response. This handles both HTML and REST style responses.
   *
   * @param request the current request
   * @param response the response to write to
   * @param resource the resource to serialize
   * @param location a different location to send to the client.
   * @return if it can write to UGC
   * @throws IOException IO Error
   * @throws ServletException Servlet Error
   */
  protected boolean writeUGCResponse(
      final SlingHttpServletRequest request,
      final SlingHttpServletResponse response,
      final Resource resource,
      final String location)
      throws ServletException, IOException {

    final String extension = request.getRequestPathInfo().getExtension();
    boolean ugcResponseWritten = false;
    if (StringUtils.equalsIgnoreCase(extension, "html")) {
      response.setHeader(HttpHeaders.CONTENT_TYPE, "text/html");
      response.setCharacterEncoding("utf-8");
      final SlingHttpServletRequest includeRequest = new TemplateHandlingRequest(request);
      final String templateRequested = request.getParameter(TEMPLATE_FORM_ID);
      final RequestDispatcherOptions options = new RequestDispatcherOptions();
      if (null != templateRequested) {
        options.setReplaceSelectors(templateRequested);
        final Resource newResource = request.getResourceResolver().getResource(resource.getPath());
        includeRequest.getRequestDispatcher(newResource, options).include(includeRequest, response);
        response.setStatus(HttpServletResponse.SC_CREATED);

        final String locationURL = (null != location) ? location : resource.getPath();
        if (!isCORS(request)) {
          response.setHeader(HttpHeaders.LOCATION, locationURL);
        } else {
          // response.setHeader(HttpHeaders.LOCATION,
          // externalizer.externalLink(request.getResourceResolver(),
          // (wcmMode == WCMMode.DISABLED) ? Externalizer.PUBLISH : Externalizer.AUTHOR,
          // locationURL));
          response.setHeader(
              HttpHeaders.LOCATION,
              externalizer.absoluteLink(request, request.getScheme(), locationURL));
        }
        ugcResponseWritten = true;
      }
    }
    return ugcResponseWritten;
  }
Ejemplo n.º 19
0
  @Test
  public void testComponentWithTagDecoration() {

    // prepare tag decoration for one component
    context
        .create()
        .resource(
            "/apps/sample/components/comp1/" + NameConstants.NN_HTML_TAG,
            ImmutableValueMap.of(NameConstants.PN_TAG_NAME, "article", "class", "css1"));

    WCMMode.EDIT.toRequest(context.request());
    Parsys parsys = context.request().adaptTo(Parsys.class);

    List<Item> items = parsys.getItems();
    assertEquals(3, items.size());

    Item item1 = items.get(0);
    assertEquals(par1Resource.getPath(), item1.getResourcePath());
    assertNull(item1.getResourceType());
    assertEquals("css1 section", item1.getCssClassName());
    assertEquals("article", item1.getElementName());
    assertFalse(item1.isNewArea());

    Item item2 = items.get(1);
    assertEquals(par2Resource.getPath(), item2.getResourcePath());
    assertNull(item2.getResourceType());
    assertEquals(SECTION_DEFAULT_CLASS_NAME, item2.getCssClassName());
    assertEquals(DEFAULT_ELEMENT_NAME, item2.getElementName());
    assertFalse(item2.isNewArea());

    Item item3 = items.get(2);
    assertEquals(NEWAREA_RESOURCE_PATH, item3.getResourcePath());
    assertEquals(FALLBACK_NEWAREA_RESOURCE_TYPE, item3.getResourceType());
    assertEquals(
        NEWAREA_CSS_CLASS_NAME + " " + SECTION_DEFAULT_CLASS_NAME, item3.getCssClassName());
    assertEquals(DEFAULT_ELEMENT_NAME, item3.getElementName());
    assertTrue(item3.isNewArea());
  }
  @Override
  public final void accept(final Resource resource) {
    // Only accept the Root folder and cq:Page and cq:PageContent nodes; All other structures are
    // uninteresting
    // to this functionality and may be very large
    final ValueMap properties = resource.adaptTo(ValueMap.class);
    final String primaryType = properties.get(JcrConstants.JCR_PRIMARYTYPE, String.class);

    if (BULK_WORKFLOW_MANAGER_PAGE_FOLDER_PATH.equals(resource.getPath())) {
      super.accept(resource);
    } else if (ArrayUtils.contains(ACCEPTED_PRIMARY_TYPES, primaryType)) {
      super.accept(resource);
    }
  }
Ejemplo n.º 21
0
  @Test
  public void testEditMode() {
    WCMMode.EDIT.toRequest(context.request());
    Parsys parsys = context.request().adaptTo(Parsys.class);

    assertFalse(parsys.isWrapperElement());
    assertNull(parsys.getWrapperCss());
    assertEquals(DEFAULT_ELEMENT_NAME, parsys.getWrapperElementName());

    List<Item> items = parsys.getItems();
    assertEquals(3, items.size());

    Item item1 = items.get(0);
    assertEquals(par1Resource.getPath(), item1.getResourcePath());
    assertNull(item1.getResourceType());
    assertNull(item1.getStyle());
    assertEquals(SECTION_DEFAULT_CLASS_NAME, item1.getCssClassName());
    assertEquals(DEFAULT_ELEMENT_NAME, item1.getElementName());
    assertFalse(item1.isNewArea());

    Item item2 = items.get(1);
    assertEquals(par2Resource.getPath(), item2.getResourcePath());
    assertNull(item2.getResourceType());
    assertNull(item2.getStyle());
    assertEquals(SECTION_DEFAULT_CLASS_NAME, item2.getCssClassName());
    assertEquals(DEFAULT_ELEMENT_NAME, item2.getElementName());
    assertFalse(item2.isNewArea());

    Item item3 = items.get(2);
    assertEquals(NEWAREA_RESOURCE_PATH, item3.getResourcePath());
    assertEquals(FALLBACK_NEWAREA_RESOURCE_TYPE, item3.getResourceType());
    assertEquals(NEWAREA_STYLE, item3.getStyle());
    assertEquals(
        NEWAREA_CSS_CLASS_NAME + " " + SECTION_DEFAULT_CLASS_NAME, item3.getCssClassName());
    assertEquals(DEFAULT_ELEMENT_NAME, item3.getElementName());
    assertTrue(item3.isNewArea());
  }
Ejemplo n.º 22
0
  protected void dumpRequestAsProperties(
      SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
    final Properties props = new Properties();
    response.setContentType("text/plain");
    props.put("servlet.class.name", getClass().getName());

    final Resource r = request.getResource();
    props.put("sling.resource.path", r == null ? "" : r.getPath());
    props.put("sling.resource.type", r == null ? "" : r.getResourceType());
    props.put("http.request.method", request.getMethod());

    props.store(
        response.getOutputStream(),
        "Data created by " + getClass().getName() + " at " + new Date());
    response.getOutputStream().flush();
  }
Ejemplo n.º 23
0
  private void doRequest(
      SlingHttpServletRequest request,
      SlingHttpServletResponse response,
      RequestInfo requestInfo,
      JSONWriter write)
      throws JSONException {
    // Look for a matching resource in the usual way. If one is found,
    // the resource will also be embedded with any necessary RequestPathInfo.
    String requestPath = requestInfo.getUrl();
    ResourceResolver resourceResolver = request.getResourceResolver();
    Resource resource = resourceResolver.resolve(request, requestPath);

    // Wrap the request and response.
    RequestWrapper requestWrapper = new RequestWrapper(request, requestInfo);
    ResponseWrapper responseWrapper = new ResponseWrapper(response);
    RequestDispatcher requestDispatcher;
    try {
      // Get the response
      try {
        if (resource != null) {
          LOGGER.info(
              "Dispatching to request path='{}', resource path='{}'",
              requestPath,
              resource.getPath());
          requestDispatcher = request.getRequestDispatcher(resource);
        } else {
          LOGGER.info("Dispatching to request path='{}', no resource", requestPath);
          requestDispatcher = request.getRequestDispatcher(requestPath);
        }
        requestDispatcher.forward(requestWrapper, responseWrapper);
      } catch (ResourceNotFoundException e) {
        responseWrapper.setStatus(HttpServletResponse.SC_NOT_FOUND);
      } catch (SlingException e) {
        responseWrapper.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      }
      // Write the response (status, headers, body) back to the client.
      writeResponse(write, responseWrapper, requestInfo);
    } catch (ServletException e) {
      writeFailedRequest(write, requestInfo);
    } catch (IOException e) {
      writeFailedRequest(write, requestInfo);
    }
  }
Ejemplo n.º 24
0
  @Override
  public void delete(final Resource resource, final boolean shallow, final boolean autoSave)
      throws WCMException {
    try {
      if (shallow) {
        Resource contentResource = resource.getChild(JcrConstants.JCR_CONTENT);
        if (contentResource != null) {
          this.resourceResolver.delete(contentResource);
        }
      } else {
        this.resourceResolver.delete(resource);
      }

      if (autoSave) {
        this.resourceResolver.commit();
      }
    } catch (PersistenceException ex) {
      throw new WCMException("Deleting resource at " + resource.getPath() + " failed.", ex);
    }
  }
Ejemplo n.º 25
0
  @SuppressWarnings("unchecked")
  private <AdapterType> AdapterType getAdapter(
      final Resource resource, final Class<AdapterType> type) {
    try {
      if (FORUM_CLASS == type) {
        return (AdapterType) new ForumImpl(resource, eventAdmin);
      } else if (POST_CLASS == type || MUTABLE_POST_CLASS == type) {
        return (AdapterType)
            new PostImpl(
                resource,
                resource.getResourceResolver(),
                eventAdmin,
                notificationManager,
                workflowService);
      }
    } catch (final ForumException e) {
      log.debug("failed adapting resource [{}] to [" + type + "]: {}", resource.getPath(), e);
    }

    return null;
  }
  private Resource mockResource(String path, File file) {
    // Get the inputstream for this file (null if directory.)
    InputStream in = getStream(file);

    // Mock the resource
    Resource resource = mock(Resource.class);
    when(resource.adaptTo(InputStream.class)).thenReturn(in);
    when(resource.adaptTo(File.class)).thenReturn(file);
    when(resource.getResourceResolver()).thenReturn(resolver);
    when(resource.getPath()).thenReturn(path);

    // Add the resource to the resource resolver.
    when(resolver.getResource(path)).thenReturn(resource);

    // Mock all the children
    List<Resource> resources = mockFileChildren(path, file);
    when(resolver.listChildren(resource)).thenReturn(resources.iterator());

    // If not using ResourceUtil
    when(resource.listChildren()).thenReturn(resources.iterator());
    when(resource.getName()).thenReturn(file.getName());
    return resource;
  }
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {

    try {
      final ResourceResolver resolver = request.getResourceResolver();
      final String vanityPath = request.getParameter("vanityPath");
      final String pagePath = request.getParameter("pagePath");
      log.debug(
          "vanity path parameter passed is {}; page path parameter passed is {}",
          vanityPath,
          pagePath);

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

      JSONWriter jsonWriter = new JSONWriter(response.getWriter());
      jsonWriter.array();

      if (StringUtils.isNotBlank(vanityPath)) {
        String xpath =
            "//element(*)[" + NameConstants.PN_SLING_VANITY_PATH + "='" + vanityPath + "']";
        @SuppressWarnings("deprecation")
        Iterator<Resource> resources = resolver.findResources(xpath, Query.XPATH);
        while (resources.hasNext()) {
          Resource resource = resources.next();
          String path = resource.getPath();
          if (path.startsWith("/content") && !path.equals(pagePath)) {
            jsonWriter.value(path);
          }
        }
      }
      jsonWriter.endArray();
    } catch (JSONException e) {
      throw new ServletException("Unable to generate JSON result", e);
    }
  }
Ejemplo n.º 28
0
  protected void dispatch(
      SlingHttpServletRequest request, SlingHttpServletResponse response, boolean userInputStream)
      throws ServletException, IOException {
    try {

      Resource resource = request.getResource();
      if (!resource.getPath().startsWith(PROXY_PATH_PREFIX)) {
        response.sendError(
            HttpServletResponse.SC_FORBIDDEN,
            "Proxying templates may only be stored in " + PROXY_PATH_PREFIX);
        return;
      }
      Node node = resource.adaptTo(Node.class);
      if (!userInputStream) {
        Value[] v = JcrUtils.getValues(node, SAKAI_REQUEST_STREAM_BODY);
        if (v != null && v.length > 0) {
          userInputStream = Boolean.parseBoolean(v[0].getString());
        }
      }
      Map<String, String> headers = new ConcurrentHashMap<String, String>();
      for (Enumeration<?> enames = request.getHeaderNames(); enames.hasMoreElements(); ) {

        String name = (String) enames.nextElement();
        if (!headerBacklist.contains(name)) {
          headers.put(name, request.getHeader(name));
        }
      }
      // search for special headers.
      if (headers.containsKey(BASIC_USER)) {
        String user = headers.get(BASIC_USER);
        String password = headers.get(BASIC_PASSWORD);
        Base64 base64 = new Base64();
        String passwordDigest =
            new String(base64.encode((user + ":" + password).getBytes("UTF-8")));
        String digest = BASIC + passwordDigest.trim();
        headers.put(AUTHORIZATION, digest);
      }

      for (Entry<String, String> e : headers.entrySet()) {
        if (e.getKey().startsWith(":")) {
          headers.remove(e.getKey());
        }
      }

      // collect the parameters and store into a mutable map.
      RequestParameterMap parameterMap = request.getRequestParameterMap();
      Map<String, Object> templateParams = new ConcurrentHashMap<String, Object>(parameterMap);

      // search for special parameters.
      if (parameterMap.containsKey(BASIC_USER)) {
        String user = parameterMap.getValue(BASIC_USER).getString();
        String password = parameterMap.getValue(BASIC_PASSWORD).getString();
        Base64 base64 = new Base64();
        String passwordDigest =
            new String(base64.encode((user + ":" + password).getBytes("UTF-8")));
        String digest = BASIC + passwordDigest.trim();
        headers.put(AUTHORIZATION, digest);
      }

      // we might want to pre-process the headers
      if (node.hasProperty(ProxyPreProcessor.SAKAI_PREPROCESSOR)) {
        String preprocessorName =
            node.getProperty(ProxyPreProcessor.SAKAI_PREPROCESSOR).getString();
        ProxyPreProcessor preprocessor = preProcessors.get(preprocessorName);
        if (preprocessor != null) {
          preprocessor.preProcessRequest(request, headers, templateParams);
        } else {
          LOGGER.warn(
              "Unable to find pre processor of name {} for node {} ",
              preprocessorName,
              node.getPath());
        }
      }
      ProxyPostProcessor postProcessor = defaultPostProcessor;
      // we might want to post-process the headers
      if (node.hasProperty(ProxyPostProcessor.SAKAI_POSTPROCESSOR)) {
        String postProcessorName =
            node.getProperty(ProxyPostProcessor.SAKAI_POSTPROCESSOR).getString();
        if (postProcessors.containsKey(postProcessorName)) {
          postProcessor = postProcessors.get(postProcessorName);
        }
        if (postProcessor == null) {
          LOGGER.warn(
              "Unable to find post processor of name {} for node {} ",
              postProcessorName,
              node.getPath());
          postProcessor = defaultPostProcessor;
        }
      }

      ProxyResponse proxyResponse =
          proxyClientService.executeCall(node, headers, templateParams, null, -1, null);
      try {
        postProcessor.process(templateParams, response, proxyResponse);
      } finally {
        proxyResponse.close();
      }
    } catch (IOException e) {
      throw e;
    } catch (ProxyClientException e) {
      response.sendError(500, e.getMessage());
    } catch (RepositoryException e) {
      response.sendError(500, e.getMessage());
    }
  }
  @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);
    }
  }
Ejemplo n.º 30
0
 public CreativeCloudMappingImpl(Resource mappingResource) {
   this.properties = mappingResource.adaptTo(ValueMap.class);
   this.path = mappingResource.getPath();
 }