org.apache.sling.api.resource.ModifiableValueMap Java Examples

The following examples show how to use org.apache.sling.api.resource.ModifiableValueMap. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AkismetServiceImpl.java    From publick-sling-blog with Apache License 2.0 6 votes vote down vote up
/**
 * Submit comment as ham to the Akismet servers.
 *
 * If a comment gets checked and incorrectly is reported as spam, this will
 * submit it back to the servers as ham to correct a false positive.
 *
 * @param commentResource The publick:comment resource to act upon.
 * @return true if submission was successful.
 */
public boolean submitHam(final Resource commentResource) {
    final boolean result = doAkismet(AkismetAction.SUBMIT_HAM, commentResource);

    if (result) {
        try {
            final ModifiableValueMap properties = commentResource.adaptTo(ModifiableValueMap.class);
            properties.put(PublickConstants.COMMENT_PROPERTY_SPAM, false);
            properties.put(PublickConstants.COMMENT_PROPERTY_DISPLAY, true);
            commentResource.getResourceResolver().commit();
        } catch (PersistenceException e) {
            LOGGER.error("Could not save spam properties", e);
        }
    }

    return result;
}
 
Example #2
Source File: AkismetServiceImpl.java    From publick-sling-blog with Apache License 2.0 6 votes vote down vote up
/**
 * Submit comment as spam to the Akismet servers.
 *
 * If a comment gets checked and incorrectly is reported as ham, this will
 * submit it back to the servers as spam to help make the world a better
 * place.
 *
 * @param commentResource The publick:comment resource to act upon.
 * @return true if submission was successful.
 */
public boolean submitSpam(final Resource commentResource) {
    final boolean result = doAkismet(AkismetAction.SUBMIT_SPAM, commentResource);

    if (result) {
        try {
            final ModifiableValueMap properties = commentResource.adaptTo(ModifiableValueMap.class);
            properties.put(PublickConstants.COMMENT_PROPERTY_SPAM, true);
            properties.put(PublickConstants.COMMENT_PROPERTY_DISPLAY, false);
            commentResource.getResourceResolver().commit();
        } catch (PersistenceException e) {
            LOGGER.error("Could not save spam properties", e);
        }
    }

    return result;
}
 
Example #3
Source File: MessageStoreImplRepositoryTest.java    From sling-samples with Apache License 2.0 6 votes vote down vote up
private void assertSaveMessage(String messageFile) throws MimeException, IOException, FileNotFoundException {
	MessageBuilder builder = new DefaultMessageBuilder();
	Message msg = builder.parseMessage(new FileInputStream(new File(TU.TEST_FOLDER, messageFile)));

	store.save(msg);

	final Resource r = resolver.getResource(getResourcePath(msg, store));
	assertNotNull("Expecting non-null Resource", r);
	final ModifiableValueMap m = r.adaptTo(ModifiableValueMap.class);

	File bodyFile = new File(TU.TEST_FOLDER, specialPathFromFilePath(messageFile, BODY_SUFFIX));
	if (bodyFile.exists()) {
		String expectedBody = readTextFile(bodyFile);
		assertValueMap(m, "Body", expectedBody);
	}

	File headersFile = new File(TU.TEST_FOLDER, specialPathFromFilePath(messageFile, HEADERS_SUFFIX));
	if (headersFile.exists()) {
		MessageStoreImplRepositoryTestUtil.assertHeaders(headersFile, m);
	}

	assertTrue(headersFile.exists() || bodyFile.exists()); // test at least something 
}
 
Example #4
Source File: RatingsServiceImpl.java    From sling-samples with Apache License 2.0 6 votes vote down vote up
/**
 * @see org.apache.sling.sample.slingshot.ratings.RatingsService#setRating(org.apache.sling.api.resource.Resource, java.lang.String, int)
 */
@Override
public void setRating(final Resource resource, final String userId, final double rating)
throws PersistenceException {
    final String ratingsPath = getRatingsResourcePath(resource) ;

    final Map<String, Object> props = new HashMap<String, Object>();
    props.put(ResourceResolver.PROPERTY_RESOURCE_TYPE, RESOURCETYPE_RATINGS);
    final Resource ratingsResource = ResourceUtil.getOrCreateResource(resource.getResourceResolver(),
            ratingsPath, props, null, true);

    final Resource ratingRsrc = resource.getResourceResolver().getResource(ratingsResource, userId);
    if ( ratingRsrc == null ) {
        props.clear();
        props.put(ResourceResolver.PROPERTY_RESOURCE_TYPE, RatingsUtil.RESOURCETYPE_RATING);
        props.put(RatingsUtil.PROPERTY_RATING, String.valueOf(rating));

        resource.getResourceResolver().create(ratingsResource, userId, props);
    } else {
        final ModifiableValueMap mvm = ratingRsrc.adaptTo(ModifiableValueMap.class);
        mvm.put(RatingsUtil.PROPERTY_RATING, String.valueOf(rating));
    }
    resource.getResourceResolver().commit();
}
 
Example #5
Source File: AkismetServiceImpl.java    From publick-sling-blog with Apache License 2.0 6 votes vote down vote up
/**
 * Check comment against Akismet servers.
 *
 * Be aware that this method returns whether the submission is spam or not.
 * A false response means that the submission was successful and that the
 * comment is not spam. This behavior is inline with Akismet's behavior.
 *
 * @param commentResource The publick:comment resource to act upon.
 * @return true if comment is spam, false if comment is valid.
 */
public boolean isSpam(final Resource commentResource) {
    final boolean result = doAkismet(AkismetAction.CHECK_COMMENT, commentResource);

    if (result) {
        try {
            final ModifiableValueMap properties = commentResource.adaptTo(ModifiableValueMap.class);
            properties.put(PublickConstants.COMMENT_PROPERTY_SPAM, true);
            commentResource.getResourceResolver().commit();
        } catch (PersistenceException e) {
            LOGGER.error("Could not save spam properties", e);
        }
    }

    return result;
}
 
Example #6
Source File: EncryptableValueMapAdapterFactory.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> T getAdapter(Object adaptable, Class<T> type) {
    ValueMap map = ((Resource) adaptable).adaptTo(ModifiableValueMap.class);
    if (map == null) {
        map = ((Resource) adaptable).adaptTo(ValueMap.class);
    }
    return (T) new EncryptableValueMapDecorator(map, encryptionProvider);
}
 
Example #7
Source File: ModifiableValueMapUsageCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
public Resource setProperty(Resource resource) {
    ModifiableValueMap resourceProperties = resource.adaptTo(ModifiableValueMap.class);
    if (resourceProperties != null) {
        resourceProperties.put("test", resource.getName());
    }
    return resource;
}
 
Example #8
Source File: HistoryEntryWriter.java    From APM with Apache License 2.0 5 votes vote down vote up
public void writeTo(Resource historyLogResource) {
  ModifiableValueMap valueMap = historyLogResource.adaptTo(ModifiableValueMap.class);
  valueMap.put(HistoryEntryImpl.SCRIPT_NAME, fileName);
  valueMap.put(HistoryEntryImpl.SCRIPT_PATH, filePath);
  valueMap.put(HistoryEntryImpl.AUTHOR, author);
  valueMap.put(HistoryEntryImpl.MODE, mode);
  valueMap.put(HistoryEntryImpl.PROGRESS_LOG, progressLog);
  valueMap.put(HistoryEntryImpl.INSTANCE_TYPE, instanceType);
  valueMap.put(HistoryEntryImpl.INSTANCE_HOSTNAME, instanceHostname);
  valueMap.put(HistoryEntryImpl.IS_RUN_SUCCESSFUL, isRunSuccessful);
  valueMap.put(HistoryEntryImpl.EXECUTION_TIME, executionTime);
  valueMap.put(HistoryEntryImpl.EXECUTOR, executor);
}
 
Example #9
Source File: ScriptModel.java    From APM with Apache License 2.0 5 votes vote down vote up
private void setProperty(String name, Object value) throws PersistenceException {
  ModifiableValueMap vm = resource.adaptTo(ModifiableValueMap.class);
  ResourceMixinUtil.addMixin(vm, ScriptNode.APM_SCRIPT);
  vm.put(name, convertValue(value));

  resource.getResourceResolver().commit();
}
 
Example #10
Source File: EncryptionOSGiStoreTest.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
private AdapterFactory adapterFactory(EncryptionProvider ep) {
    return new AdapterFactory() {
        @SuppressWarnings("unchecked")
        public <AdapterType> AdapterType getAdapter(Object adaptable, Class<AdapterType> type) {
            ValueMap map = ((Resource) adaptable).adaptTo(ModifiableValueMap.class);
            if (map == null) {
                map = ((Resource) adaptable).adaptTo(ValueMap.class);
            }
            return (AdapterType) new EncryptableValueMapDecorator(map, ep);
        }
    };
}
 
Example #11
Source File: EncryptionKeyStoreTest.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
private AdapterFactory adapterFactory(EncryptionProvider ep) {
    return new AdapterFactory() {
        @SuppressWarnings("unchecked")
        public <AdapterType> AdapterType getAdapter(Object adaptable, Class<AdapterType> type) {
            ValueMap map = ((Resource) adaptable).adaptTo(ModifiableValueMap.class);
            if (map == null) {
                map = ((Resource) adaptable).adaptTo(ValueMap.class);
            }
            return (AdapterType) new EncryptableValueMapDecorator(map, ep);
        }
    };
}
 
Example #12
Source File: ModelPersistorImpl.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
private void persistField(@NotNull Resource resource, @NotNull Object instance, Field field, boolean deepPersist) {
    try {
        // read the existing resource map
        ModifiableValueMap values = resource.adaptTo(ModifiableValueMap.class);
        String nodePath = resource.getPath();

        // find the type of field
        final Class<?> fieldType = field.getType();
        final String fieldName = ReflectionUtils.getFieldName(field);

        // set accessible
        field.setAccessible(true);

        // handle the value as primitive first
        if (ReflectionUtils.isPrimitiveFieldType(fieldType) || ReflectionUtils.isCollectionOfPrimitiveType(field)) {

            Object value = ReflectionUtils.getStorableValue(field.get(instance));

            // remove the attribute that is null, or remove in case it changes type
            values.remove(fieldName);
            if (value != null) {
                values.put(fieldName, value);
            }
        } else if (deepPersist) {
            boolean directDescendents = field.getAnnotation(DirectDescendants.class) != null;
            persistComplexValue(field.get(instance), directDescendents, fieldName, resource);
        }
    } catch (IllegalAccessException | RepositoryException | PersistenceException ex) {
        LOGGER.error("Error when persisting content to " + resource.getPath(), ex);
    }
}
 
Example #13
Source File: MessageStoreImplAttachmentsTest.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
private void assertSaveMessageWithAttachments(Message msg, int num) throws IOException {
    store.save(msg);

    List<BodyPart> attList = new LinkedList<BodyPart>();
    MessageStoreImpl.recursiveMultipartProcessing((Multipart) msg.getBody(), new StringBuilder(), new StringBuilder(), false, attList); 
    @SuppressWarnings("unchecked")
    Queue<BodyPart> attachmentsMsg = (Queue<BodyPart>) attList;
    assertTrue("No attachments found", attachmentsMsg.size() > 0);
    assertEquals("", num, attachmentsMsg.size());
    
    final Resource r = resolver.getResource(getResourcePath(msg, store));
    assertNotNull("Expecting non-null Resource", r);
    for (Resource aRes : r.getChildren()) {
        final ModifiableValueMap aMap = aRes.adaptTo(ModifiableValueMap.class);
        BodyPart aMsg = attachmentsMsg.poll();
        assertNotNull("JCR contains more attachments", aMsg);

        for (Field f : aMsg.getHeader().getFields()) {
            String name = f.getName();
            assertEquals("Field "+name+" is different", (aMap.get(name, String.class)), f.getBody());
        }
        
        if (aMsg.getBody() instanceof TextBody) {
            assertEquals("Content is not the same", MessageStoreImpl.getTextPart(aMsg), aMap.get(CONTENT, String.class));
        } else if (aMsg.getBody() instanceof BinaryBody) {
            assertEquals("Content is not the same", getBinPart(aMsg), aMap.get(CONTENT, String.class));
        } else {
            fail("Unknown type of attachment body");
        }
    }
    assertEquals("Message contains more attachments", attachmentsMsg.poll(), null);
}
 
Example #14
Source File: MessageStoreImplRepositoryTestUtil.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
static void assertLayer(Resource root, List<String> types, int depth) {
    for (Resource child : root.getChildren()) {
        final ModifiableValueMap m = child.adaptTo(ModifiableValueMap.class);
        if (m.keySet().contains(MessageStoreImplRepositoryTest.TEST_RT_KEY)) {
            String type = m.get(MessageStoreImplRepositoryTest.TEST_RT_KEY, String.class);
            assertEquals(String.format("Expecting %s to have %s type", child.getPath(), types.get(depth)), types.get(depth), type);
        }
        if (child.getChildren().iterator().hasNext()) {
            assertLayer(child, types, depth+1);
        }
    }

}
 
Example #15
Source File: ResourceMixinUtil.java    From APM with Apache License 2.0 4 votes vote down vote up
public static void addMixin(ModifiableValueMap vm, String mixin) {
	Set<String> mixins = new HashSet<>(Arrays.asList(vm.get(JcrConstants.JCR_MIXINTYPES, new String[0])));
	mixins.add(mixin);
	vm.put(JcrConstants.JCR_MIXINTYPES, mixins.toArray(new String[]{}));
}
 
Example #16
Source File: ContentResourceShouldBeNullCheckedCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 4 votes vote down vote up
private void directlyCallMethodOnGetContentResourceReturn(Resource resource) {
  Page page = resource.adaptTo(Page.class);
  ValueMap map = page.getContentResource().getValueMap(); // Noncompliant
  ModifiableValueMap modifiableValueMap = page.getContentResource().adaptTo(ModifiableValueMap.class); // Noncompliant
}
 
Example #17
Source File: ModifiableValueMapUsageCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 4 votes vote down vote up
public Object getProperty(Resource resource) {
    ModifiableValueMap createdResourceProperties = resource.adaptTo(ModifiableValueMap.class); // Noncompliant ValueMap should be used
    return getPropertyFromValueMap("propName", createdResourceProperties);
}
 
Example #18
Source File: ModifiableValueMapUsageCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 4 votes vote down vote up
public Object getPropertyFromResource(Resource resource) {
    ModifiableValueMap createdResourceProperties = resource.adaptTo(ModifiableValueMap.class); // Noncompliant ValueMap should be used
    return createdResourceProperties.get("propName");
}
 
Example #19
Source File: ModifiableValueMapUsageCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 4 votes vote down vote up
public Resource removeProperty(Resource resource) {
    ModifiableValueMap resourcePropertiesToSet = resource.adaptTo(ModifiableValueMap.class);
    removePropertyFromMVM("testName", "testValue", resourcePropertiesToSet);
    return resource;
}
 
Example #20
Source File: ProductBindingCreator.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
private void processAddition(ResourceChange change) {
    resolver.refresh();
    String path = change.getPath();
    LOG.debug("Process resource addition at path {}", path);

    Resource changedResource = resolver.getResource(path);
    if (changedResource == null) {
        LOG.warn("Cannot retrieve resource at {}. Does the user have the require privileges?", path);
        return;
    }
    Resource contentResource = changedResource.getChild(JcrConstants.JCR_CONTENT);

    ValueMap properties;
    if (contentResource != null) {
        properties = contentResource.getValueMap();
    } else {
        properties = changedResource.getValueMap();
    }

    String storeView = properties.get(Constants.PN_MAGENTO_STORE, "");
    if (StringUtils.isEmpty(storeView)) {
        LOG.warn("The configuration at path {} doesn't have a '{}' property", path, Constants.PN_MAGENTO_STORE);
        return;
    }

    String configRoot = path.substring(0, path.indexOf(Constants.COMMERCE_BUCKET_PATH) - 1);
    String configName = configRoot.substring(configRoot.lastIndexOf("/") + 1);

    String bindingName = configName + "-" + storeView;
    LOG.debug("New binding name: {}", bindingName);

    Map<String, Object> mappingProperties = new HashMap<>();
    mappingProperties.put(JcrConstants.JCR_PRIMARYTYPE, "sling:Folder");
    mappingProperties.put(JcrConstants.JCR_TITLE, bindingName);
    mappingProperties.put(Constants.PN_CONF, configRoot);

    Resource parent = resolver.getResource(BINDINGS_PARENT_PATH);
    if (parent == null) {
        LOG.warn("Binding parent path not found at {}. Nothing to do here...", BINDINGS_PARENT_PATH);
        return;
    }

    String bindingPath = parent.getPath() + "/" + bindingName;
    LOG.debug("Check if we already have a binding at {}", bindingPath);

    try {
        LOG.debug("Creating a new resource at {}", bindingPath);
        ResourceUtil.getOrCreateResource(resolver, bindingPath, mappingProperties, "", true);

        if (contentResource != null) {
            LOG.debug("Adding {} property at {}", Constants.PN_CATALOG_PATH, contentResource.getPath());
            ModifiableValueMap map = contentResource.adaptTo(ModifiableValueMap.class);
            map.put(Constants.PN_CATALOG_PATH, bindingPath);
            resolver.commit();
        }
    } catch (PersistenceException e) {
        LOG.error(e.getMessage(), e);
    }

}
 
Example #21
Source File: MultiFieldDropTargetPostProcessor.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
private void processProperty(Resource resource, String target, String propertyValue, String originalKey, String selectionType,
    boolean multiple) throws Exception {

    String[] paths = target.split(SLASH);

    ResourceResolver resourceResolver = resource.getResourceResolver();

    // clean-up the dropTarget property or node
    ModifiableValueMap originalProperties = resource.adaptTo(ModifiableValueMap.class);
    originalProperties.remove(originalKey);

    String dropTargetNodeName = DROP_TARGET_PREFIX.replace(SLING_PROPERTY_PREFIX, StringUtils.EMPTY);
    Resource dropTargetResource = resource.getChild(dropTargetNodeName);
    if (dropTargetResource != null) {
        resourceResolver.delete(dropTargetResource);
    }

    if (selectionType != null) {
        if (SKU.equals(selectionType)) {
            propertyValue = StringUtils.substringAfterLast(propertyValue, "/");
        } else if (SLUG.equals(selectionType)) {
            Resource product = resourceResolver.getResource(propertyValue);
            if (product != null) {
                String slug = product.getValueMap().get(SLUG, String.class);
                if (slug != null) {
                    propertyValue = slug;
                }
            }
        }
    }

    // check all paths and create correct resources and properties
    boolean isArray = true;
    Resource currentResource = resource;
    for (String path : paths) {
        if (path.startsWith(PROPERTY_PREFIX)) {
            // this is the property
            String propertyName = path.replace(PROPERTY_PREFIX, StringUtils.EMPTY);
            ModifiableValueMap properties = currentResource.adaptTo(ModifiableValueMap.class);
            if (isArray && multiple) {
                List<String> childPages = new ArrayList<>(Arrays.asList(properties.get(propertyName, new String[0])));
                childPages.add(propertyValue);
                properties.remove(propertyName);
                properties.put(propertyName, childPages.toArray());
            } else {
                properties.put(propertyName, propertyValue);
            }
            // These properties are added by the drag and drop, they do not belong to the component configuration
            properties.remove(MULTIPLE.replace(PROPERTY_PREFIX, StringUtils.EMPTY));
            properties.remove(SELECTION_ID.replace(PROPERTY_PREFIX, StringUtils.EMPTY));
        } else if (path.equals(COMPOSITE_VARIABLE)) {
            // create new subNode
            int count = Iterators.size(currentResource.getChildren().iterator());
            String nodeName = "item" + count;
            currentResource = resourceResolver.create(currentResource, nodeName, new HashMap<>());
            isArray = false;
        } else if (StringUtils.isNotBlank(path)) {
            // get or create new node
            Resource subResource = currentResource.getChild(path);
            if (subResource == null) {
                currentResource = resourceResolver.create(currentResource, path, new HashMap<>());
            } else {
                currentResource = subResource;
            }
        }
    }
}
 
Example #22
Source File: MultiFieldDropTargetPostProcessor.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
@Override
public void process(SlingHttpServletRequest request, List<Modification> modifications) throws Exception {
    RequestParameterMap requestParameterMap = request.getRequestParameterMap();

    for (String key : requestParameterMap.keySet()) {
        if (key.startsWith(DROP_TARGET_PREFIX)) {

            RequestParameter requestParameter = requestParameterMap.getValue(key);
            if (requestParameter != null) {
                String target = key.replace(DROP_TARGET_PREFIX, StringUtils.EMPTY);
                String propertyValue = requestParameter.getString();
                Resource resource = request.getResource();

                // If it's actually a drag and drop, the POST contains a Sling './@CopyFrom' parameter
                // and the modifications map will already contain the COPY operation done by the D'n'D
                if (requestParameterMap.containsKey(SLING_COPY_FROM)) {
                    Modification copyFrom = modifications
                        .stream()
                        .filter(m -> ModificationType.COPY.equals(m.getType()))
                        .findFirst().orElseGet(null);
                    if (copyFrom != null) {
                        Resource dropComponent = resource.getResourceResolver().getResource(copyFrom.getDestination());
                        ModifiableValueMap properties = dropComponent.adaptTo(ModifiableValueMap.class);
                        properties.remove(target);
                        resource = dropComponent; // The property changes will be done on the D'n'D target resource
                    }
                }

                RequestParameter selectionTypeParameter = requestParameterMap.getValue(SELECTION_ID);
                String selectionType = selectionTypeParameter != null ? selectionTypeParameter.getString() : null;

                RequestParameter multipleParameter = requestParameterMap.getValue(MULTIPLE);
                boolean multiple = true;
                if (multipleParameter != null) {
                    multiple = Boolean.valueOf(multipleParameter.getString());
                }

                processProperty(resource, target, propertyValue, key, selectionType, multiple);
                modifications.add(Modification.onModified(resource.getPath()));
            }
        }
    }
}