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

The following examples show how to use org.apache.sling.api.resource.ValueMap. 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: RatingsServiceImpl.java    From sling-samples with Apache License 2.0 7 votes vote down vote up
/**
 * @see org.apache.sling.sample.slingshot.ratings.RatingsService#getRating(org.apache.sling.api.resource.Resource)
 */
@Override
public double getRating(final Resource resource) {
    final String fullPath = getRatingsResourcePath(resource);
    float rating = 0;
    if ( fullPath != null ) {
        final Resource ratingsResource = resource.getChild(fullPath);
        if ( ratingsResource != null ) {
            int count = 0;
            for(final Resource r : ratingsResource.getChildren()) {
                final ValueMap vm = r.getValueMap();
                final double current = vm.get(RatingsUtil.PROPERTY_RATING, 0.0);
                rating += current;
                count++;
            }
            if ( count > 0 ) {
                rating = rating / count;
            }
        }
    }
    return rating;
}
 
Example #2
Source File: ProductBindingCreator.java    From commerce-cif-connector with Apache License 2.0 6 votes vote down vote up
private void processDeletion(ResourceChange change) {
    String path = change.getPath();
    LOG.debug("Process resource deletion at path {}", path);

    Resource parent = resolver.getResource(BINDINGS_PARENT_PATH);
    Iterator<Resource> resourceIterator = parent.listChildren();

    Stream<Resource> targetStream = StreamSupport.stream(Spliterators.spliteratorUnknownSize(resourceIterator, Spliterator.ORDERED),
        false);

    targetStream.filter(res -> {
        ValueMap properties = res.getValueMap();
        LOG.debug("Checking the binding at {}", res.getPath());
        String cqConf = properties.get(Constants.PN_CONF, "");
        if (StringUtils.isEmpty(cqConf)) {
            return false;
        }
        return path.equals(cqConf + "/" + Constants.COMMERCE_BUCKET_PATH);
    }).findFirst().ifPresent(res -> {
        LOG.debug("Found a binding at {} that uses {}, we'll delete it", res.getPath(), path);
        deleteJcrNode(res);
    });
}
 
Example #3
Source File: RemoteScriptExecutionActionReceiver.java    From APM with Apache License 2.0 6 votes vote down vote up
@Override
public void handleAction(final ValueMap valueMap) {
	checkState(instanceTypeProvider.isOnAuthor(), "Action Receiver has to be called in author");
	String userId = valueMap.get(ReplicationAction.PROPERTY_USER_ID, String.class);
	SlingHelper.operateTraced(resolverFactory, userId, resolver -> {
		//FIXME would be lovely to cast ValueMap -> ModifiableEntryBuilder
		String scriptLocation = valueMap.get(HistoryEntryImpl.SCRIPT_PATH, String.class);
		Resource scriptResource = resolver.getResource(scriptLocation);
		Script script = scriptResource.adaptTo(ScriptModel.class);
		InstanceDetails instanceDetails = getInstanceDetails(valueMap);
		Progress progress = getProgress(valueMap, resolver.getUserID());
		Calendar executionTime = getCalendar(valueMap);
		ExecutionMode mode = getMode(valueMap);
		history.logRemote(script, mode, progress, instanceDetails, executionTime);
	});
}
 
Example #4
Source File: BaseEncryptionTest.java    From sling-whiteboard with Apache License 2.0 6 votes vote down vote up
/**
 * Tests the decryption and handling of pre-existing values
 * 
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 */
@Test
public void testPreEncryptedArrayofValues() {
    Resource resource = context.resourceResolver().getResource(ARRAY_PATH);

    ValueMap map = resource.adaptTo(ValueMap.class);
    EncryptableValueMap encryptionMap = resource.adaptTo(EncryptableValueMap.class);

    // verify original is encrypted
    String[] value = map.get(encryptedProperty, String[].class);
    assertNotEquals("foo", value[0]);
    assertNotEquals("dog", value[1]);

    // get decrypted values and validate
    value = (String[]) encryptionMap.get(encryptedProperty);
    assertArrayEquals(new String[] { "foo", "dog" }, value);

    // decrypt pre-encrypted properties
    encryptionMap.decrypt(encryptedProperty);
    value = (String[]) map.get(encryptedProperty);
    assertArrayEquals(new String[] { "foo", "dog" }, value);
}
 
Example #5
Source File: AkismetServiceImpl.java    From publick-sling-blog with Apache License 2.0 6 votes vote down vote up
/**
 * Get an AkismetComment from a publick:comment resource.
 *
 * @param commentResource The publick:comment resource.
 * @return Akismet Comment created from the properties of the comment resource.
 */
private AkismetComment getAkismetComment(final Resource commentResource) {
    final AkismetComment akismetComment = new AkismetComment();

    if (commentResource != null) {
        final ValueMap properties = commentResource.getValueMap();

        // Get external link taking extensionless URLs into account
        String externalLink = StringUtils.removeEnd(getDomainName(), "/");
        externalLink = externalLink.concat(linkRewriter.rewriteLink(commentResource.getPath()));

        akismetComment.setUserIp(properties.get(PublickConstants.COMMENT_PROPERTY_USER_IP, String.class));
        akismetComment.setUserAgent(properties.get(PublickConstants.COMMENT_PROPERTY_USER_AGENT, String.class));
        akismetComment.setReferrer(properties.get(PublickConstants.COMMENT_PROPERTY_REFERRER, String.class));
        akismetComment.setPermalink(externalLink);
        akismetComment.setCommentType(AKISMET_COMMENT_TYPE);
        akismetComment.setCommentAuthor(properties.get(PublickConstants.COMMENT_PROPERTY_AUTHOR, String.class));
        akismetComment.setCommentContent(properties.get(PublickConstants.COMMENT_PROPERTY_COMMENT, String.class));
    }

    return akismetComment;
}
 
Example #6
Source File: InjectorSpecificAnnotationTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 6 votes vote down vote up
@Test
public void testOrderForValueAnnotationConstructor() {
    // make sure that that the correct injection is used
    // make sure that log is adapted from value map
    // and not coming from request attribute
    Logger logFromValueMap = LoggerFactory.getLogger(this.getClass());

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("first", "first-value");
    map.put("log", logFromValueMap);
    ValueMap vm = new ValueMapDecorator(map);

    Resource res = mock(Resource.class);
    when(res.adaptTo(ValueMap.class)).thenReturn(vm);
    when(request.getResource()).thenReturn(res);

    org.apache.sling.models.testmodels.classes.constructorinjection.InjectorSpecificAnnotationModel model
            = factory.getAdapter(request, org.apache.sling.models.testmodels.classes.constructorinjection.InjectorSpecificAnnotationModel.class);
    assertNotNull("Could not instanciate model", model);
    assertEquals("first-value", model.getFirst());
    assertEquals(logFromValueMap, model.getLog());
}
 
Example #7
Source File: DefaultTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultWrappersField() {
    ValueMap vm = new ValueMapDecorator(Collections.<String, Object>emptyMap());

    Resource res = mock(Resource.class);
    when(res.adaptTo(ValueMap.class)).thenReturn(vm);

    DefaultWrappersModel model = factory.getAdapter(res, DefaultWrappersModel.class);
    assertNotNull(model);

    assertEquals(Boolean.valueOf(true), model.getBooleanWrapperProperty());
    // we need to wait for JUnit 4.12 for this assertArrayEquals to be working on primitive boolean arrays, https://github.com/junit-team/junit/issues/86!
    assertTrue(Arrays.equals(new Boolean[] { Boolean.TRUE, Boolean.TRUE }, model.getBooleanWrapperArrayProperty()));

    assertEquals(Long.valueOf(1L), model.getLongWrapperProperty());
    assertArrayEquals(new Long[] { Long.valueOf(1L), Long.valueOf(1L) }, model.getLongWrapperArrayProperty());
}
 
Example #8
Source File: InjectorSpecificAnnotationTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 6 votes vote down vote up
@Test
public void testOrderForValueAnnotationField() {
    // make sure that that the correct injection is used
    // make sure that log is adapted from value map
    // and not coming from request attribute
    Logger logFromValueMap = LoggerFactory.getLogger(this.getClass());

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("first", "first-value");
    map.put("log", logFromValueMap);
    ValueMap vm = new ValueMapDecorator(map);

    Resource res = mock(Resource.class);
    when(res.adaptTo(ValueMap.class)).thenReturn(vm);
    when(request.getResource()).thenReturn(res);

    InjectorSpecificAnnotationModel model = factory.getAdapter(request, InjectorSpecificAnnotationModel.class);
    assertNotNull("Could not instanciate model", model);
    assertEquals("first-value", model.getFirst());
    assertEquals(logFromValueMap, model.getLog());
}
 
Example #9
Source File: GraphqlResourceProviderTest.java    From commerce-cif-connector with Apache License 2.0 6 votes vote down vote up
@Test
public void testCategoryTreeError() throws Throwable {
    Utils.setupHttpResponse("magento-graphql-error.json", httpClient, HttpStatus.SC_OK);

    Resource root = provider.getResource(resolveContext, CATALOG_ROOT_PATH, null, null);
    assertNotNull(root);
    Iterator<Resource> it = provider.listChildren(resolveContext, root);
    assertNotNull(it);
    assertTrue(it.hasNext());
    Resource error = it.next();
    assertTrue(error instanceof ErrorResource);
    assertNull(error.adaptTo(Product.class));
    assertEquals(ErrorResource.NAME, error.getName());
    assertEquals(CATALOG_ROOT_PATH + "/" + ErrorResource.NAME, error.getPath());
    ValueMap map = error.adaptTo(ValueMap.class);
    assertNotNull(map);
    assertTrue(map.get(IS_ERROR, false));
    assertFalse(map.get(HAS_CHILDREN, true));
    assertTrue(map.get(LEAF_CATEGORY, false));
}
 
Example #10
Source File: ResourceModelClassesTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 6 votes vote down vote up
@Test
public void testArrayWrappersModel() {
    Map<String, Object> map = new HashMap<>();
    map.put("intArray", new Integer[] {1, 2, 9, 8});
    map.put("secondIntArray", new int[] {1, 2, 9, 8});

    ValueMap vm = new ValueMapDecorator(map);
    Resource res = mock(Resource.class);
    when(res.adaptTo(ValueMap.class)).thenReturn(vm);

    ArrayWrappersModel model = factory.getAdapter(res, ArrayWrappersModel.class);
    assertNotNull(model);

    Integer[] intArray = model.getIntArray();
    assertEquals(4, intArray.length);
    assertEquals(new Integer(2), intArray[1]);

    Integer[] secondIntArray = model.getSecondIntArray();
    assertEquals(4, secondIntArray.length);
    assertEquals(new Integer(2), secondIntArray[1]);
}
 
Example #11
Source File: InjectorSpecificAnnotationTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleValueModelField() {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("first", "first-value");
    map.put("second", "second-value");
    ValueMap vm = new ValueMapDecorator(map);

    Resource res = mock(Resource.class);
    when(res.adaptTo(ValueMap.class)).thenReturn(vm);
    when(request.getResource()).thenReturn(res);

    InjectorSpecificAnnotationModel model = factory.getAdapter(request, InjectorSpecificAnnotationModel.class);
    assertNotNull("Could not instanciate model", model);
    assertEquals("first-value", model.getFirst());
    assertEquals("second-value", model.getSecond());
}
 
Example #12
Source File: ResourceModelInterfacesTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimplePropertyModel() {
    Map<String, Object> map = new HashMap<>();
    map.put("first", "first-value");
    map.put("third", "third-value");
    map.put("fourth", true);
    ValueMap vm = new ValueMapDecorator(map);

    Resource res = mock(Resource.class);
    when(res.adaptTo(ValueMap.class)).thenReturn(vm);

    SimplePropertyModel model = factory.getAdapter(res, SimplePropertyModel.class);
    assertNotNull(model);
    assertEquals("first-value", model.getFirst());
    assertNull(model.getSecond());
    assertEquals("third-value", model.getThirdProperty());
    assertTrue(model.isFourth());

    verify(res, times(1)).adaptTo(ValueMap.class);
}
 
Example #13
Source File: HtmlResourceRenderer.java    From sling-whiteboard with Apache License 2.0 6 votes vote down vote up
private void form(ResourceSchema m, ValueMap vm, String title, String subtitle, String cssClass, String actionPath, String redirectPath, String formMarkerFieldName) {
    html("\n<div class='%s'>\n", cssClass);
    if(title != null) {
        html("<h2>%s</h2>\n", title);
    }
    if(subtitle != null) {
        html("<p>%s</p>\n", subtitle);
    }
    html("<form method='POST' action='%s' enctype='multipart/form-data'>\n", actionPath);
    hiddenField("sling:resourceType", ResponseUtil.escapeXml(m.getName()));
    if(redirectPath != null) {
        hiddenField(":redirect", ResponseUtil.escapeXml(redirectPath));
    }
    if(formMarkerFieldName != null) {
        hiddenField(formMarkerFieldName, "");
    }
    for(ResourceProperty p : m.getProperties()) {
        html("<br/>\n");
        inputField(p, vm);
    }
    html("<br/>\n<input type='submit'/>\n");
    html("</form>\n</div>\n");
}
 
Example #14
Source File: NavigationImplTest.java    From aem-core-cif-components with Apache License 2.0 6 votes vote down vote up
private void initCatalogPage(boolean catalogRoot, boolean showMainCategories, boolean useCaConfig) {
    Page catalogPage = mock(Page.class);
    Resource catalogPageContent = mock(Resource.class);
    when(catalogPageContent.isResourceType(RT_CATALOG_PAGE)).thenReturn(catalogRoot);
    Map<String, Object> catalogPageProperties = new HashMap<>();
    catalogPageProperties.put(PN_SHOW_MAIN_CATEGORIES, showMainCategories);

    if (!useCaConfig) {
        catalogPageProperties.put(PN_MAGENTO_ROOT_CATEGORY_ID, 4);
    }
    when(catalogPageContent.adaptTo(ComponentsConfiguration.class)).thenReturn(new ComponentsConfiguration(new ValueMapDecorator(
        ImmutableMap.of(PN_MAGENTO_ROOT_CATEGORY_ID, 4))));
    when(catalogPageContent.getValueMap()).thenReturn(new ValueMapDecorator(catalogPageProperties));
    when(catalogPage.getContentResource()).thenReturn(catalogPageContent);
    when(catalogPage.getPath()).thenReturn("/content/catalog");
    when(catalogPageContent.getPath()).thenReturn("/content/catalog/jcr:content");
    ResourceResolver mockResourceResolver = mock(ResourceResolver.class);
    when(mockResourceResolver.getResource(any(String.class))).thenReturn(null);
    when(catalogPageContent.getResourceResolver()).thenReturn(mockResourceResolver);
    when(pageManager.getPage(CATALOG_PAGE_PATH)).thenReturn(catalogPage);

    ValueMap configProperties = new ValueMapDecorator(ImmutableMap.of(PN_MAGENTO_ROOT_CATEGORY_ID, 4));

    when(catalogPage.adaptTo(ComponentsConfiguration.class)).thenReturn(new ComponentsConfiguration(configProperties));
}
 
Example #15
Source File: InitializerTest.java    From commerce-cif-connector with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaults() {
    initializer.init(bindings);

    assertNotNull(includedResourceSample);

    ValueMap properties = includedResourceSample.getValueMap();
    assertNotNull(properties);
    assertEquals(Initializer.DEFAULT_FILTER, properties.get("filter", String.class));
    assertEquals("Product ID", properties.get("emptyText", String.class));
    assertFalse(properties.get("multiple", Boolean.class));
    assertEquals("commerce/gui/components/common/productfield", properties.get("sling:resourceType", String.class));
    assertEquals(PRODUCTS_BASE_PATH, properties.get("rootPath", String.class));
    assertTrue(properties.get("forceselection", Boolean.class));
    String pickerSrc = "/mnt/overlay/commerce/gui/content/common/cifproductfield/picker.html?root=products%2fbase%2fpath&"
        + "filter=folderOrProduct&selectionCount=single&selectionId=id";
    assertEquals(pickerSrc, properties.get("pickerSrc", String.class));
}
 
Example #16
Source File: ResourceModelClassesTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 6 votes vote down vote up
@Test
public void testArrayPrimitivesModel() {
    Map<String, Object> map = new HashMap<>();
    map.put("intArray", new int[] { 1, 2, 9, 8 });
    map.put("secondIntArray", new Integer[] {1, 2, 9, 8});

    ValueMap vm = new ValueMapDecorator(map);
    Resource res = mock(Resource.class);
    when(res.adaptTo(ValueMap.class)).thenReturn(vm);

    ArrayPrimitivesModel model = factory.getAdapter(res, ArrayPrimitivesModel.class);
    assertNotNull(model);

    int[] primitiveIntArray = model.getIntArray();
    assertEquals(4, primitiveIntArray.length);
    assertEquals(2, primitiveIntArray[1]);

    int[] secondPrimitiveIntArray = model.getSecondIntArray();
    assertEquals(4, secondPrimitiveIntArray.length);
    assertEquals(2, secondPrimitiveIntArray[1]);
}
 
Example #17
Source File: NPEfix19_nineteen_t.java    From coming with MIT License 6 votes vote down vote up
private boolean isJcrData(Resource resource){
    boolean jcrData = false;
    if (resource!= null) {
        ValueMap props = resource.adaptTo(ValueMap.class);
        if (props != null && props.containsKey(PROP_JCR_DATA) ) {
            jcrData = true;
        } else {
            Resource jcrContent = resource.getChild(JCR_CONTENT_LEAF);
            if (jcrContent!= null) {
                props = jcrContent.adaptTo(ValueMap.class);
                if (props != null && props.containsKey(PROP_JCR_DATA) ) {
                    jcrData = true;
                }
            }
        }
    }
    return jcrData;
}
 
Example #18
Source File: OptionalPrimitivesTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
@Test
    public void testConstructorInjection() {
        ValueMap vm = ValueMap.EMPTY;

        Resource res = mock(Resource.class);
        when(res.adaptTo(ValueMap.class)).thenReturn(vm);

        org.apache.sling.models.testmodels.classes.constructorinjection.OptionalPrimitivesModel model
                = factory.getAdapter(res, org.apache.sling.models.testmodels.classes.constructorinjection.OptionalPrimitivesModel.class);
        assertNotNull(model);

        // make sure primitives are initialized with initial value
        assertEquals(0, model.getByteValue());
        assertEquals(0, model.getShortValue());
        assertEquals(0, model.getIntValue());
        assertEquals(0L, model.getLongValue());
        assertEquals(0.0f, model.getFloatValue(), 0.00001d);
        assertEquals(0.0d, model.getDoubleValue(), 0.00001d);
        assertEquals('\u0000', model.getCharValue());
        assertEquals(false, model.getBooleanValue());

        // make sure object wrapper of primitives are null
        assertNull(model.getByteObjectValue());
        assertNull(model.getShortObjectValue());
        assertNull(model.getIntObjectValue());
        assertNull(model.getLongObjectValue());
        assertNull(model.getFloatObjectValue());
        assertNull(model.getDoubleObjectValue());
        assertNull(model.getCharObjectValue());
        assertNull(model.getBooleanObjectValue());
}
 
Example #19
Source File: BlogView.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
/**
 * Get the blog post properties from the resource.
 *
 * @param blog The blog post resource.
 */
private void getBlog(Resource blog) {
    if (blog != null) {
        ValueMap properties = blog.adaptTo(ValueMap.class);
        title = properties.get("title", String.class);
        month = properties.get("month", Long.class);
        year = properties.get("year", Long.class);
        url = properties.get("url", String.class);
        visible = Boolean.valueOf(properties.get("visible", false));
        keywords = properties.get("keywords", String[].class);
        content = properties.get("content", String.class);
        description = properties.get("description", String.class);
        image = properties.get("image", String.class);

        if (image != null) {
            image = resolver.map(image);
        }

        Date date = properties.get(JcrConstants.JCR_CREATED, Date.class);

        publishedDate = getDate(date, PUBLISHED_DATE_FORMAT);
        displayDate = getDate(date, DISPLAY_DATE_FORMAT);

        imageRelativePath = image;
        imageAbsolutePath = getAbsolutePath(image);
    }
}
 
Example #20
Source File: BaseEncryptionTest.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
/**
 * Tests encryption and decryption of a String value
 * 
 */
@Test
public void testUnencryptedString() {
    Resource resource = context.resourceResolver().getResource(START_PATH);

    ValueMap map = resource.adaptTo(ValueMap.class);
    EncryptableValueMap encrytionMap = resource.adaptTo(EncryptableValueMap.class);

    String property = "jcr:primaryType";

    // get original value
    String value = encrytionMap.get(property, String.class);
    assertEquals("app:Page", value);

    // encrypt property and validate property appears to be the same
    encrytionMap.encrypt(property);
    value = encrytionMap.get(property, String.class);
    assertEquals("app:Page", value);

    // validate the underlying value is encrypted
    value = map.get(property, "fail");
    assertNotEquals("app:Page", value);
    assertNotEquals("fail", value);

    // decrypt property and validate the underlying map is back to normal
    encrytionMap.decrypt(property);
    value = map.get(property, String.class);
    assertEquals("app:Page", value);
}
 
Example #21
Source File: CommentsView.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
/**
 * Create the comment list by getting the passed in resource's children and collecting
 * their author, comment, and jcr:created properties. Replies are a recursive call to
 * this methods with the children of the resource passed in resource.
 *
 * @param resource The root comments resource or the first level comment.
 * @param getReplies True to get the next level of comments.
 * @return The collection of comments.
 */
private List<HashMap<String, Object>> getCommentList(Resource resource, boolean getReplies) {
    List<HashMap<String, Object>> comments = new ArrayList<HashMap<String, Object>>();

    if (resource != null && resource.hasChildren()) {
        Iterator<Resource> iterator = resource.listChildren();

        while (iterator.hasNext()) {

            Resource commentResource = iterator.next();
            ValueMap properties = commentResource.adaptTo(ValueMap.class);
            HashMap<String, Object> commentProperties = new HashMap<String, Object>();

            String author = properties.get("author", String.class);
            String comment = properties.get("comment", String.class);
            String date = getDate(properties.get(JcrConstants.JCR_CREATED, Date.class), DISPLAY_DATE_FORMAT);
            boolean display = properties.get("display", false);
            boolean edited = properties.get("edited", false);
            boolean spam = properties.get("spam", false);

            if (StringUtils.isNotBlank(author)
                    && StringUtils.isNotBlank(comment)
                    && StringUtils.isNotBlank(date)) {
                commentProperties.put("author", display && !spam ? author : "--");
                commentProperties.put("comment", display && !spam ? comment : "Comment removed by author.");
                commentProperties.put("date", date);
                commentProperties.put("edited", edited);
                commentProperties.put("path", commentResource.getPath());
                if (getReplies) {
                    commentProperties.put("replies", getCommentList(commentResource, false));
                }
                comments.add(commentProperties);
                count++;
            }
        }
    }

    return comments;
}
 
Example #22
Source File: RatingsServiceImpl.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
/**
 * @see org.apache.sling.sample.slingshot.ratings.RatingsService#getRating(org.apache.sling.api.resource.Resource, java.lang.String)
 */
@Override
public double getRating(final Resource resource, final String userId) {
    final String fullPath = getRatingsResourcePath(resource);
    double rating = 0;

    final Resource r = resource.getResourceResolver().getResource(fullPath + "/" + userId);
    if ( r != null ) {
        final ValueMap vm = r.getValueMap();
        rating = vm.get(RatingsUtil.PROPERTY_RATING, 0.0);
    }
    return rating;
}
 
Example #23
Source File: OptionalPrimitivesTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
@Test
public void testFieldInjectionInterface() {
    ValueMap vm = ValueMap.EMPTY;

    Resource res = mock(Resource.class);
    when(res.adaptTo(ValueMap.class)).thenReturn(vm);

    org.apache.sling.models.testmodels.interfaces.OptionalPrimitivesModel model
            = factory.getAdapter(res, org.apache.sling.models.testmodels.interfaces.OptionalPrimitivesModel.class);
    assertNotNull(model);

    // make sure primitives are initialized with initial value
    assertEquals(0, model.getByteValue());
    assertEquals(0, model.getShortValue());
    assertEquals(0, model.getIntValue());
    assertEquals(0L, model.getLongValue());
    assertEquals(0.0f, model.getFloatValue(), 0.00001d);
    assertEquals(0.0d, model.getDoubleValue(), 0.00001d);
    assertEquals('\u0000', model.getCharValue());
    assertEquals(false, model.getBooleanValue());

    // make sure object wrapper of primitives are null
    assertNull(model.getByteObjectValue());
    assertNull(model.getShortObjectValue());
    assertNull(model.getIntObjectValue());
    assertNull(model.getLongObjectValue());
    assertNull(model.getFloatObjectValue());
    assertNull(model.getDoubleObjectValue());
    assertNull(model.getCharObjectValue());
    assertNull(model.getBooleanObjectValue());
}
 
Example #24
Source File: MarkdownResource.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> T adaptTo(Class<T> type) {
    if ( type == ValueMap.class || type == Map.class ) {
        return (T) getValueMap();
    }
    
    return null;
}
 
Example #25
Source File: PropertiesSupport.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
protected ValueMap getProperties() {
    if ( this.properties == null ) {
        if ( this.resource == null ) {
            this.properties = ResourceUtil.getValueMap(null);
        } else {
            this.properties = resource.getValueMap();
        }
    }
    return this.properties;
}
 
Example #26
Source File: ResourceModelClassesTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
@Test
public void testChildValueMap() {
    ValueMap map = ValueMapDecorator.EMPTY;

    Resource child = mock(Resource.class);
    when(child.adaptTo(ValueMap.class)).thenReturn(map);

    Resource res = mock(Resource.class);
    when(res.getChild("firstChild")).thenReturn(child);

    ChildValueMapModel model = factory.getAdapter(res, ChildValueMapModel.class);
    assertNotNull(model);
    assertEquals(map, model.getFirstChild());
}
 
Example #27
Source File: GraphqlClientDataSourceServlet.java    From aem-core-cif-components with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <AdapterType> AdapterType adaptTo(Class<AdapterType> type) {
    if (type == ValueMap.class) {
        if (valueMap == null) {
            initValueMap();
        }
        return (AdapterType) valueMap;
    } else {
        return super.adaptTo(type);
    }
}
 
Example #28
Source File: TagsResource.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <AdapterType> AdapterType adaptTo(Class<AdapterType> type) {
    if(type == ValueMap.class) {
        return (AdapterType)new ValueMapDecorator(properties);
    }
    return super.adaptTo(type);
}
 
Example #29
Source File: InvalidAdaptationsTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
@Test(expected = ModelClassException.class)
public void testNonModelClassException() {
    Map<String, Object> emptyMap = Collections.<String, Object> emptyMap();

    Resource res = mock(Resource.class);
    when(res.adaptTo(ValueMap.class)).thenReturn(new ValueMapDecorator(emptyMap));

    assertNull(factory.createModel(res, NonModel.class));
}
 
Example #30
Source File: DefaultTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultStringValueField() {
    ValueMap vm = new ValueMapDecorator(Collections.<String, Object>emptyMap());

    Resource res = mock(Resource.class);
    when(res.adaptTo(ValueMap.class)).thenReturn(vm);

    DefaultStringModel model = factory.getAdapter(res, DefaultStringModel.class);
    assertNotNull(model);
    assertEquals("firstDefault", model.getFirstProperty());
    assertEquals(2, model.getSecondProperty().length);
}