Java源码示例:org.apache.sling.api.resource.ResourceResolver

示例1
/**
 * Get the blog post associated with the given comment.
 *
 * There are only two levels of comments. You can reply to a post
 * and you can reply to a top level comment.
 *
 * @param comment The current comment
 * @return the number of replies to the given comment
 */
public Resource getParentPost(final Resource comment) {
    final ResourceResolver resolver = comment.getResourceResolver();
    Resource parent = comment.getParent();

    // Try one level up
    Resource post = resolver.getResource(parent.getPath().replace("/comments/", "/blog/"));

    if (post == null) {
        //try two levels up
        parent = parent.getParent();
        post = resolver.getResource(parent.getPath().replace("/comments/", "/blog/"));
    }

    return post;
}
 
示例2
/**
 * Creates an instance of a *variant* product and all its variants.<br>
 * All the methods that access properties (e.g. prices, descriptions, etc) defined in both the active variant
 * and the base product will first get the properties defined in the variant and will fallback to the
 * property of the base product if a variant property is null.
 * 
 * @param resourceResolver The resource resolver for that resource.
 * @param path The resource path of this product.
 * @param product The Magento base product.
 * @param activeVariantSku The SKU of the "active" variant product or null if this product represents the base product.
 */
public MagentoProduct(ResourceResolver resourceResolver, String path, ProductInterface product, String activeVariantSku) {
    this.resourceResolver = resourceResolver;
    this.path = path;
    this.product = product;
    this.activeVariantSku = activeVariantSku;
    if (product instanceof ConfigurableProduct) {
        ConfigurableProduct cp = (ConfigurableProduct) product;
        if (cp.getVariants() != null && cp.getVariants().size() > 0) {
            if (activeVariantSku != null) {
                masterVariant = cp.getVariants()
                    .stream()
                    .map(cv -> cv.getProduct())
                    .filter(sp -> activeVariantSku.equals(sp.getSku()))
                    .findFirst()
                    .orElse(null);
            }

            // fallback + default
            if (masterVariant == null) {
                masterVariant = cp.getVariants().get(0).getProduct();
            }
        }
    }
}
 
示例3
public Tag findTag(String tagId, Asset asset, Session session) {
    Tag tag = null;
    ResourceResolver resourceResolver = null;

    try {
        resourceResolver = getResourceResolver(session);
        TagManager tagManager = resourceResolver.adaptTo(TagManager.class);
        tag = tagManager.resolve(tagId);
    } finally {
        if (null != resourceResolver && resourceResolver.isLive()) {
            resourceResolver.close();
        }
    }

    return tag;
}
 
示例4
/**
 * Retrieve values from repository with wrapped impersonated session (automatically opened and closed).
 */
@SuppressWarnings("unchecked")
public static <T> T resolve(ResourceResolverFactory factory, String userId, ResolveCallback callback)
    throws ResolveException {
  ResourceResolver resolver = null;
  try {
    resolver = getResourceResolverForUser(factory, userId);
    return (T) callback.resolve(resolver);
  } catch (Exception e) {
    throw new ResolveException(RESOLVE_ERROR_MESSAGE, e);
  } finally {
    if (resolver != null && resolver.isLive()) {
      resolver.close();
    }
  }
}
 
示例5
void processScript(Script script, ResourceResolver resolver, LauncherType launcherType)
    throws PersistenceException {

  final String scriptPath = script.getPath();
  try {
    if (!script.isValid()) {
      getScriptManager().process(script, ExecutionMode.VALIDATION, resolver);
    }
    if (script.isValid()) {
      final ExecutionResult result = getScriptManager().process(script, ExecutionMode.AUTOMATIC_RUN, resolver);
      logStatus(scriptPath, result.isSuccess(), launcherType);
    } else {
      logger.warn("{} launcher cannot execute script which is not valid: {}", launcherType.toString(), scriptPath);
    }
  } catch (RepositoryException e) {
    logger.error("Script cannot be processed because of repository error: {}", scriptPath, e);
  }
}
 
示例6
private static void deleteOrphanNodes(ResourceResolver resourceResolver, final String collectionRoot, Set<String> childNodes) {
    // Delete any children that are not in the list
    Resource collectionParent = resourceResolver.getResource(collectionRoot);
    if (collectionParent != null) {
        StreamSupport
                .stream(resourceResolver.getChildren(collectionParent).spliterator(), false)
                .filter(r -> !childNodes.contains(r.getPath()))
                .forEach(r -> {
                    try {
                        resourceResolver.delete(r);
                    } catch (PersistenceException ex) {
                        LOGGER.error("Unable to remove stale resource at " + r.getPath(), ex);
                    }
                });
    }
}
 
示例7
private HistoryEntry createHistoryEntry(ResourceResolver resolver, Script script, ExecutionMode mode,
    HistoryEntryWriter historyEntryWriter, boolean remote) {
  try {
    Session session = resolver.adaptTo(Session.class);

    Node scriptHistoryNode = createScriptHistoryNode(script, session);
    Node historyEntryNode = createHistoryEntryNode(scriptHistoryNode, script, mode, remote);
    historyEntryNode.setProperty(HistoryEntryImpl.SCRIPT_CONTENT_PATH, versionService.getVersionPath(script));
    writeProperties(resolver, historyEntryNode, historyEntryWriter);

    session.save();
    resolver.commit();
    return resolver.getResource(historyEntryNode.getPath()).adaptTo(HistoryEntryImpl.class);
  } catch (PersistenceException | RepositoryException e) {
    LOG.error("Issues with saving to repository while logging script execution", e);
    return null;
  }
}
 
示例8
@Override
public Script find(String scriptPath, ResourceResolver resolver) {
  Script result = null;
  if (StringUtils.isNotEmpty(scriptPath)) {
    Resource resource;
    if (isAbsolute(scriptPath)) {
      resource = resolver.getResource(scriptPath);
    } else {
      resource = resolver.getResource(SCRIPT_PATH + "/" + scriptPath);
    }
    if (resource != null && ScriptModel.isScript(resource)) {
      result = resource.adaptTo(ScriptModel.class);
    }
  }
  return result;
}
 
示例9
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));
}
 
示例10
/**
 * Do some operation on repository (delete or update resource etc) with wrapped impersonated session
 * (automatically opened and closed).
 */
public static void operate(ResourceResolverFactory factory, String userId, OperateCallback callback)
    throws OperateException {
  ResourceResolver resolver = null;
  try {
    resolver = getResourceResolverForUser(factory, userId);
    callback.operate(resolver);
    resolver.commit();
  } catch (Exception e) {
    throw new OperateException(OPERATE_ERROR_MESSAGE, e);
  } finally {
    if (resolver != null && resolver.isLive()) {
      resolver.close();
    }
  }
}
 
示例11
@Override
public Progress process(Script script, final ExecutionMode mode, final Map<String, String> customDefinitions,
    ResourceResolver resolver) throws RepositoryException, PersistenceException {
  Progress progress;
  try {
    progress = execute(script, mode, customDefinitions, resolver);

  } catch (ExecutionException e) {
    progress = new ProgressImpl(resolver.getUserID());
    progress.addEntry(Status.ERROR, e.getMessage());
  }

  updateScriptProperties(script, mode, progress.isSuccess());
  versionService.updateVersionIfNeeded(resolver, script);
  saveHistory(script, mode, progress);
  eventManager.trigger(Event.AFTER_EXECUTE, script, mode, progress);

  return progress;
}
 
示例12
private void removeSingleFile(ResourceResolver resolver, SlingHttpServletResponse response,
		String fileName) throws IOException {
	if (StringUtils.isEmpty(fileName)) {
		ServletUtils.writeMessage(response, "error", "File name to be removed cannot be empty");
	} else {
		final Script script = scriptFinder.find(fileName, resolver);
		if (script == null) {
			ServletUtils
					.writeMessage(response, "error", String.format("Script not found: '%s'", fileName));
		} else {
			final String scriptPath = script.getPath();

			try {
				scriptStorage.remove(script, resolver);

				ServletUtils.writeMessage(response, "success",
						String.format("Script removed successfully: %s", scriptPath));
			} catch (RepositoryException e) {
				response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				ServletUtils.writeJson(response,
						String.format("Cannot remove script: '%s'." + " Repository error: %s", scriptPath,
								e.getMessage()));
			}
		}
	}
}
 
示例13
/**
 * For "see also", our articles have just the article name but no path or
 * section. This maps those names (which are Sling Resource names) to their
 * Resource, so we can use the full path + title to render links.
 */
private static Map<String, Object> toArticleRef(ResourceResolver resolver, String nodeName) {
    final String jcrQuery = String.format("/jcr:root%s//*[@filename='%s']", Constants.ARTICLES_ROOT, nodeName);
    final Iterator<Resource> it = resolver.findResources(jcrQuery, "xpath");

    // We want exactly one result
    if (!it.hasNext()) {
        throw new RuntimeException("No Resource found:" + jcrQuery);
    }
    final Map<String, Object> result = SlingWrappers.resourceWrapper(it.next());
    if (it.hasNext()) {
        throw new RuntimeException("More than one Resource found:" + jcrQuery);
    }

    return result;
}
 
示例14
private DataSource buildValuesList(ResourceResolver resourceResolver) {
    Map<String, Collection<String>> identifiersMap = catalogIdentifierService.getCatalogIdentifiersForAllCommerceProviders();

    List<String> providerIdentifiers = flattenMapToList(identifiersMap);
    List<Resource> syntheticResources = generateResources(resourceResolver, providerIdentifiers);

    return toDataSource(syntheticResources);
}
 
示例15
public MockResource(ResourceResolver resolver, String path) {
    this.resolver = resolver;
    this.path = path;
    this.metadata = new ResourceMetadata();
    metadata.put(ResourceMetadata.RESOLUTION_PATH, path);
    metadata.put(ResourceMetadata.RESOLUTION_PATH_INFO, path);
}
 
示例16
@Test
public void testGenerateResources() {
    List<String> testData = Arrays.asList("key1:value1", "key1:value2", "key2:value3", "key2:value4");
    List<Resource> results = classUnderTest.generateResources(Mockito.mock(ResourceResolver.class), testData);

    Assert.assertEquals("The list has the correct number of elements", testData.size(), results.size());
    testData.stream().forEach(testProperty -> {
        Resource resourceToCheck = results.get(testData.indexOf(testProperty));
        ValueMap resourceProperties = resourceToCheck.getValueMap();

        Assert.assertEquals("The value of property [text] is [" + testProperty + "]", testProperty, resourceProperties.get("text"));
        Assert.assertEquals("The value of property [value] is [" + testProperty + "]", testProperty, resourceProperties.get("value"));
    });
}
 
示例17
@Test
void testResourceReadingFromMetaFile() {
    Resource hey = resourceProvider.getResource(resolveContext, "/content/test-1/hey", resourceContext, null);
    assertNotNull(hey, "Expected to find /content/test-1/hey");
    assertEquals(ServletResolverConstants.DEFAULT_RESOURCE_TYPE, hey.getResourceType(),
            "Expected that /content/test-1/hey's resource type is " + ServletResolverConstants.DEFAULT_RESOURCE_TYPE);
    ValueMap heyProperties = hey.getValueMap();
    assertEquals(1, heyProperties.size());
    assertEquals(ServletResolverConstants.DEFAULT_RESOURCE_TYPE, heyProperties.get(ResourceResolver.PROPERTY_RESOURCE_TYPE,
            String.class));
    assertEquals(ServletResolverConstants.DEFAULT_RESOURCE_TYPE, hey.getResourceType(),
            "Expected that /content/test-1/hey's resource type is " + ServletResolverConstants.DEFAULT_RESOURCE_TYPE);

    Resource joe = resourceProvider.getResource(resolveContext, "/content/test-1/hey/joe", resourceContext, null);
    assertNotNull(joe, "Expected to find /content/test-1/hey/joe");
    assertEquals(ServletResolverConstants.DEFAULT_RESOURCE_TYPE, joe.getResourceType(),
            "Expected that /content/test-1/hey/joe's resource type is " + ServletResolverConstants.DEFAULT_RESOURCE_TYPE);

    ValueMap joeProperties = joe.getValueMap();
    assertEquals(2, joeProperties.size());
    assertEquals(ServletResolverConstants.DEFAULT_RESOURCE_TYPE, joeProperties.get(ResourceResolver.PROPERTY_RESOURCE_TYPE,
            String.class));
    Calendar lastModified = joeProperties.get("lastModifiedDate", Calendar.class);
    assertNotNull(lastModified, String.format("Expected a lastModifiedDate property on %s", joe.getPath()));
    assertEquals(1407421980000L, lastModified.getTimeInMillis());
    assertTrue(wrapsSameResource(joe, getChild(hey, "joe")), "Expected to get a cached representation of /content/test-1/hey/joe");

    Iterator<Resource> joeChildren = resourceProvider.listChildren(resolveContext, joe);
    assertNull(joeChildren, String.format("Did not expect children resources for %s", joe.getPath()));
}
 
示例18
/**
 * Creates a SyntheticResource for the given Magento GraphQL product. The <code>activeVariantSku</code> parameter
 * must be set if the product is a leaf variant not having any child nodes.
 * 
 * @param resourceResolver The resource resolver.
 * @param path The path of the resource.
 * @param product The Magento GraphQL product.
 * @param activeVariantSku The SKU of the "active" variant product or null if this product represents the base product.
 */
ProductResource(ResourceResolver resourceResolver, String path, ProductInterface product, String activeVariantSku) {

    super(resourceResolver, path, PRODUCT_RESOURCE_TYPE);
    this.magentoProduct = product;
    this.activeVariantSku = activeVariantSku;

    Map<String, Object> map = new HashMap<>();
    map.put(JcrConstants.JCR_TITLE, product.getName());
    map.put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED);
    map.put(PRODUCT_IDENTIFIER, product.getId());
    map.put(SKU, activeVariantSku != null ? activeVariantSku : product.getSku());
    map.put(SLUG, product.getUrlKey());
    map.put(ResourceResolver.PROPERTY_RESOURCE_TYPE, PRODUCT_RESOURCE_TYPE);
    map.put(CommerceConstants.PN_COMMERCE_PROVIDER, Constants.MAGENTO_GRAPHQL_PROVIDER);

    if (product.getDescription() != null) {
        map.put(JcrConstants.JCR_DESCRIPTION, product.getDescription().getHtml());
    }

    if (product.getUpdatedAt() != null) {
        map.put(JcrConstants.JCR_LASTMODIFIED, convertToDate(product.getUpdatedAt()));
    }

    String formattedPrice = toFormattedPrice(product);
    if (StringUtils.isNotBlank(formattedPrice)) {
        map.put(Constants.PRODUCT_FORMATTED_PRICE, formattedPrice);
    }

    map.put(CommerceConstants.PN_COMMERCE_TYPE, activeVariantSku != null ? VARIANT : PRODUCT);

    if (activeVariantSku != null || product instanceof SimpleProduct) {
        map.put("hasChildren", false);
    } else if (product instanceof ConfigurableProduct) {
        map.put("hasChildren", true);
    }

    values = new DeepReadValueMapDecorator(this, new ValueMapDecorator(map));
}
 
示例19
@Override
public HistoryEntry findHistoryEntry(ResourceResolver resourceResolver, final String path) {
  Resource resource = resourceResolver.getResource(path);
  if (resource != null) {
    return resource.adaptTo(HistoryEntryImpl.class);
  }
  return null;
}
 
示例20
public void checkWrongJumpMethod() {
    ResourceResolver resourceResolver = null; // Noncompliant
    try {
        resourceResolver = getResourceResolverForUserNestedInit(resourceResolverFactory);
    } catch (LoginException e) {
        e.printStackTrace();
    } finally {
        if (resourceResolver != null) {
            //resourceResolver.close();
        }
    }
}
 
示例21
SyntheticImageResource resolveProductImage(ResourceResolver resolver, String path) {
    String productPath = path.substring(0, path.length() - "/image".length());
    List<String> productParts = resolveProductParts(productPath);
    try {
        String sku = productParts.size() == 1 ? productParts.get(0) : productParts.get(1);
        ProductInterface product = graphqlDataService.getProductBySku(sku, storeView);
        if (product != null) {
            String imageUrl = product.getImage().getUrl();
            if (imageUrl == null && product instanceof ConfigurableProduct) {
                ConfigurableProduct cp = (ConfigurableProduct) product;
                if (cp.getVariants() != null && cp.getVariants().size() > 0) {
                    imageUrl = cp.getVariants().get(0).getProduct().getImage().getUrl();
                }
            }

            if (imageUrl != null) {
                return new SyntheticImageResource(resolver, path, SyntheticImageResource.IMAGE_RESOURCE_TYPE, imageUrl);
            } else {
                return null;
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error while fetching category products", e);
        return null;
    }

    return null;
}
 
示例22
Iterator<Resource> listCategoryChildren(ResourceResolver resolver, Resource parent) {
    String parentPath = parent.getPath();
    String parentCifId = parent.getValueMap().get(Constants.CIF_ID, String.class);
    boolean isRoot = parentPath.equals(root);
    String subPath = isRoot ? "" : parentPath.substring(root.length() + 1);
    List<Resource> children = new ArrayList<>();
    CategoryTree categoryTree;
    try {
        if (StringUtils.isNotBlank(subPath)) {
            categoryTree = graphqlDataService.getCategoryByPath(subPath, storeView);
        } else {
            categoryTree = graphqlDataService.getCategoryById(rootCategoryId, storeView);
        }
    } catch (Exception x) {
        List<Resource> list = new ArrayList<>();
        list.add(new ErrorResource(resolver, parent.getPath()));
        return list.iterator();
    }
    if (categoryTree != null) {
        List<CategoryTree> subChildren = categoryTree.getChildren();
        if (subChildren != null) {
            for (CategoryTree child : subChildren) {
                children.add(new CategoryResource(resolver, root + "/" + child.getUrlPath(), child));
            }
        }
    }

    if (children.isEmpty() && StringUtils.isNotBlank(parentCifId)) {
        try {
            return new CategoryProductsIterator(parent, graphqlDataService, 20, storeView);
        } catch (Exception e) {
            LOGGER.error("Error while fetching category products for " + parentPath + " (" + parentCifId + ")", e);
        }
    }

    return children.isEmpty() ? null : children.iterator();
}
 
示例23
@Override
public Iterator<Resource> listChildren(ResolveContext<Object> ctx, Resource parent) {
    ValueMap valueMap = parent.getValueMap();
    String commerceType = valueMap.get(CommerceConstants.PN_COMMERCE_TYPE, String.class);
    ResourceResolver resolver = ctx.getResourceResolver();
    if (root.equals(parent.getPath()) || CATEGORY.equals(commerceType)) {
        return resourceMapper.listCategoryChildren(resolver, parent);
    } else if (PRODUCT.equals(commerceType)) {
        return resourceMapper.listProductChildren(resolver, parent);
    }
    return null;
}
 
示例24
private HistoryEntryWriterBuilder createBuilder(ResourceResolver resolver, Script script, ExecutionMode mode,
    Progress progressLogger) {
  Resource source = resolver.getResource(script.getPath());
  return HistoryEntryWriter.builder()
      .author(source.getValueMap().get(JcrConstants.JCR_CREATED_BY, StringUtils.EMPTY))
      .executor(resolver.getUserID())
      .fileName(source.getName())
      .filePath(source.getPath())
      .isRunSuccessful(progressLogger.isSuccess())
      .mode(mode.toString())
      .progressLog(ProgressHelper.toJson(progressLogger.getEntries()));
}
 
示例25
private void persistComplexValue(Object obj, Boolean implicitCollection, final String fieldName, Resource resource) throws RepositoryException, IllegalAccessException, IllegalArgumentException, PersistenceException {
    ResourceResolver rr = resource.getResourceResolver();
    String childrenRoot = buildChildrenRoot(resource.getPath(), fieldName, rr, implicitCollection);
    boolean deleteRoot = true;
    if (obj != null) {
        if (Collection.class.isAssignableFrom(obj.getClass())) {
            Collection collection = (Collection) obj;
            if (!collection.isEmpty()) {
                persistCollection(childrenRoot, collection, rr);
                deleteRoot = false;
            }
        } else if (Map.class.isAssignableFrom(obj.getClass())) {
            Map map = (Map) obj;
            if (!map.isEmpty()) {
                persistMap(childrenRoot, map, rr);
                deleteRoot = false;
            }
        } else {
            // this is a single compound object
            // create a child node and persist all its values
            persist(resource.getPath() + "/" + fieldName, obj, rr, true);
            deleteRoot = false;
        }
        if (deleteRoot) {
            Resource rootNode = rr.getResource(childrenRoot);
            if (rootNode != null) {
                rr.delete(rootNode);
            }
        }
    }
}
 
示例26
/**
 * Create a new session for specified user (impersonating).
 */
public static ResourceResolver getResourceResolverForUser(ResourceResolverFactory factory, String userId)
    throws LoginException {
    ResourceResolver resolver;
    if (userId != null) {
        Map<String, Object> authenticationInfo = new HashMap<>();
        authenticationInfo.put(ResourceResolverFactory.USER_IMPERSONATION, userId);
        resolver = factory.getServiceResourceResolver(authenticationInfo);
    } else {
        resolver = factory.getServiceResourceResolver(null);
    }
    return resolver;
}
 
示例27
@Override
public List<HistoryEntry> findAllHistoryEntries(ResourceResolver resourceResolver) {
  return findAllResources(resourceResolver)
      .stream()
      .map(resource -> resource.adaptTo(HistoryEntryImpl.class))
      .collect(Collectors.toList());
}
 
示例28
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
		throws ServletException, IOException {
	final String all = request.getParameter("confirmation");
	final String fileName = request.getParameter("file");
	ResourceResolver resolver = request.getResourceResolver();
	if (fileName != null) {
		removeSingleFile(resolver, response, fileName);
	} else if (all != null) {
		removeAllFiles(resolver, response, all);
	} else {
		response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
		ServletUtils.writeMessage(response, "error", "Invalid arguments specified");
	}
}
 
示例29
public String findName(final String path) {
    String name = "";
    ResourceResolver resourceResolver = null;
    try {
        resourceResolver = resourceResolverProducer.produce();
        name = resourceResolver.getResource(path).getName();
    } finally {
        if (null != resourceResolver && resourceResolver.isLive()) {
            resourceResolver.close();
        }
    }
    return name;
}
 
示例30
public ResourceResolver getResourceResolver(Map<String, Object> credentials) {
    ResourceResolver resolver = null;
    try {
        resolver = resolverFactory.getAdministrativeResourceResolver(credentials); // Noncompliant {{Method 'getAdministrativeResourceResolver' is deprecated. Use 'getServiceResourceResolver' instead.}}
    } catch (LoginException e) {
        //
    }
    return resolver;
}