com.day.cq.commons.jcr.JcrConstants Java Examples

The following examples show how to use com.day.cq.commons.jcr.JcrConstants. 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: RelationTypesDataSourceServlet.java    From aem-core-cif-components with Apache License 2.0 7 votes vote down vote up
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {

    ResourceBundle resourceBundle = request.getResourceBundle(null);
    List<Resource> values = new ArrayList<>();

    for (RelationType relationType : RelationType.values()) {
        ValueMap vm = new ValueMapDecorator(new HashMap<String, Object>());
        vm.put("value", relationType);
        vm.put("text", toText(resourceBundle, relationType.getText()));
        values.add(new ValueMapResource(request.getResourceResolver(), new ResourceMetadata(), JcrConstants.NT_UNSTRUCTURED, vm));
    }

    DataSource ds = new SimpleDataSource(values.iterator());
    request.setAttribute(DataSource.class.getName(), ds);
}
 
Example #2
Source File: ErrorResource.java    From commerce-cif-connector with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a SyntheticResource for the given Magento GraphQL CategoryTree.
 *
 * @param resourceResolver The resource resolver.
 * @param parentPath The path of the category resource that will be created.
 */
ErrorResource(ResourceResolver resourceResolver, String parentPath) {
    super(resourceResolver, parentPath + "/" + NAME, JcrResourceConstants.NT_SLING_FOLDER);
    Map<String, Object> map = new HashMap<>();
    map.put(JcrConstants.JCR_PRIMARYTYPE, JcrResourceConstants.NT_SLING_FOLDER);
    map.put(ResourceResolver.PROPERTY_RESOURCE_TYPE, JcrResourceConstants.NT_SLING_FOLDER);
    map.put(CommerceConstants.PN_COMMERCE_TYPE, CATEGORY);
    map.put(CommerceConstants.PN_COMMERCE_PROVIDER, MAGENTO_GRAPHQL_PROVIDER);

    map.put(JcrConstants.JCR_TITLE, "Server error");
    map.put(LEAF_CATEGORY, true);
    map.put(HAS_CHILDREN, false);
    map.put(IS_ERROR, true);

    values = new DeepReadValueMapDecorator(this, new ValueMapDecorator(map));
}
 
Example #3
Source File: ScriptsRowModel.java    From APM with Apache License 2.0 6 votes vote down vote up
@PostConstruct
protected void afterCreated() {
  this.isFolder = isFolder(resource);
  this.scriptName = defaultIfEmpty(getProperty(resource, JcrConstants.JCR_TITLE), resource.getName());
  if (!isFolder) {
    Optional.ofNullable(resource.adaptTo(ScriptModel.class)).ifPresent(script -> {
      ScriptHistory scriptHistory = history.findScriptHistory(resource.getResourceResolver(), script);
      this.author = script.getAuthor();
      this.isValid = script.isValid();
      this.lastModified = CalendarUtils.asCalendar(script.getLastModified());
      this.runs.add(createScriptRun("runOnAuthor", script, scriptHistory.getLastLocalRun()));
      this.runs.add(createScriptRun("runOnPublish", script, scriptHistory.getLastRemoteRun()));
      this.runs.add(createScriptRun("dryRun", script, scriptHistory.getLastLocalDryRun()));
      this.launchMode = label(script.getLaunchMode());
      this.launchEnvironment = label(script.getLaunchEnvironment());
      this.isLaunchEnabled = script.isLaunchEnabled();
    });
  }
}
 
Example #4
Source File: ProductBindingCreator.java    From commerce-cif-connector with Apache License 2.0 6 votes vote down vote up
@Override
public void onChange(List<ResourceChange> list) {
    LOG.debug("Change detected somewhere...");
    list.stream().filter(change -> {
        String path = change.getPath();
        LOG.debug("Processing path {}", path);
        return !path.endsWith(JcrConstants.JCR_CONTENT) && path.contains(Constants.COMMERCE_BUCKET_PATH);
    }).forEach(change -> {
        if (change.getType() == ResourceChange.ChangeType.ADDED) {
            processAddition(change);
        }
        if (change.getType() == ResourceChange.ChangeType.REMOVED) {
            processDeletion(change);
        }
    });
}
 
Example #5
Source File: children.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
@Override
public boolean evaluate(Resource resource) {
    if (resource.isResourceType("sling:Folder")
            || resource.isResourceType("sling:OrderedFolder")
            || resource.isResourceType(JcrConstants.NT_FOLDER))
        return true;

    return categoryPredicate.evaluate(resource);
}
 
Example #6
Source File: HistoryImpl.java    From APM with Apache License 2.0 5 votes vote down vote up
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()));
}
 
Example #7
Source File: ScriptModel.java    From APM with Apache License 2.0 5 votes vote down vote up
@Override
public String getData() {
  if (data == null) {
    Resource child = resource.getChild(JcrConstants.JCR_CONTENT);
    if (child != null) {
      data = child.getValueMap().get(JcrConstants.JCR_DATA, String.class);
    } else {
      data = "";
    }
  }
  return data;
}
 
Example #8
Source File: ScriptStorageImpl.java    From APM with Apache License 2.0 5 votes vote down vote up
private Script saveScript(FileDescriptor descriptor, LaunchMetadata launchMetadata, boolean overwrite,
    ResourceResolver resolver) {
  Script result = null;
  try {
    final Session session = resolver.adaptTo(Session.class);
    final ValueFactory valueFactory = session.getValueFactory();
    final Binary binary = valueFactory.createBinary(descriptor.getInputStream());
    final Node saveNode = session.getNode(descriptor.getPath());

    final Node fileNode, contentNode;
    if (overwrite && saveNode.hasNode(descriptor.getName())) {
      fileNode = saveNode.getNode(descriptor.getName());
      contentNode = fileNode.getNode(JcrConstants.JCR_CONTENT);
    } else {
      fileNode = saveNode.addNode(generateFileName(descriptor.getName(), saveNode), JcrConstants.NT_FILE);
      contentNode = fileNode.addNode(JcrConstants.JCR_CONTENT, JcrConstants.NT_RESOURCE);
    }

    contentNode.setProperty(JcrConstants.JCR_DATA, binary);
    contentNode.setProperty(JcrConstants.JCR_ENCODING, SCRIPT_ENCODING.name());
    fileNode.addMixin(ScriptNode.APM_SCRIPT);
    fileNode.setProperty(ScriptNode.APM_LAUNCH_ENABLED, launchMetadata.isExecutionEnabled());
    setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_MODE, launchMetadata.getLaunchMode());
    setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_ENVIRONMENT, launchMetadata.getLaunchEnvironment());
    setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_HOOK, launchMetadata.getExecutionHook());
    setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_SCHEDULE, launchMetadata.getExecutionSchedule());
    removeProperty(fileNode, ScriptNode.APM_LAST_EXECUTED);
    JcrUtils.setLastModified(fileNode, Calendar.getInstance());
    session.save();
    result = scriptFinder.find(fileNode.getPath(), resolver);
  } catch (RepositoryException e) {
    LOG.error(e.getMessage(), e);
  }
  return result;
}
 
Example #9
Source File: SimpleDataSourceBuilder.java    From APM with Apache License 2.0 5 votes vote down vote up
private Resource createDataSourceItem(ResourceResolver resolver, String name, String value) {
  Map<String, Object> valueMap = ImmutableMap.of(
      CONFIGURATION_NAME_PROP, name,
      CONFIGURATION_PATH_PROP, value
  );
  ValueMapDecorator result = new ValueMapDecorator(valueMap);
  return new ValueMapResource(resolver, new ResourceMetadata(), JcrConstants.NT_RESOURCE, result);
}
 
Example #10
Source File: UrlProviderImpl.java    From aem-core-cif-components with Apache License 2.0 5 votes vote down vote up
/**
 * This method checks if any of the children of the given <code>page</code> resource
 * is a page with a <code>selectorFilter</code> property set with the value
 * of the given <code>selector</code>.
 * 
 * @param page The page resource, from where children pages will be checked.
 * @param selector The searched value for the <code>selectorFilter</code> property.
 * @return If found, a child page resource that contains the given <code>selectorFilter</code> value.
 *         If not found, this method returns null.
 */
public static Resource toSpecificPage(Resource page, String selector) {
    Iterator<Resource> children = page.listChildren();
    while (children.hasNext()) {
        Resource child = children.next();
        if (!NameConstants.NT_PAGE.equals(child.getResourceType())) {
            continue;
        }

        Resource jcrContent = child.getChild(JcrConstants.JCR_CONTENT);
        if (jcrContent == null) {
            continue;
        }

        Object filter = jcrContent.getValueMap().get(SELECTOR_FILTER_PROPERTY);
        if (filter == null) {
            continue;
        }

        // The property is saved as a String when it's a simple selection, or an array when a multi-selection is done
        String[] selectors = filter.getClass().isArray() ? ((String[]) filter) : ArrayUtils.toArray((String) filter);

        if (ArrayUtils.contains(selectors, selector)) {
            LOGGER.debug("Page has a matching sub-page for selector {} at {}", selector, child.getPath());
            return child;
        }
    }
    return null;
}
 
Example #11
Source File: CIFProductFieldHelper.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
public boolean isCloudFolder() {
    Resource resource = getResource();

    return (isVirtual(resource) || isCloudBoundFolder(resource)) && (resource.isResourceType("sling:Folder")
            || resource.isResourceType("sling:OrderedFolder")
            || resource.isResourceType(JcrConstants.NT_FOLDER));
}
 
Example #12
Source File: ViewHelper.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
public boolean isNew() {
    Calendar modifiedDateRaw = getProperties().get(JcrConstants.JCR_LASTMODIFIED, Calendar.class);
    Calendar createdDateRaw = getProperties().get(JcrConstants.JCR_CREATED, Calendar.class);
    if ((createdDateRaw == null) || (modifiedDateRaw != null && modifiedDateRaw.before(createdDateRaw))) {
        createdDateRaw = modifiedDateRaw;
    }
    Calendar twentyFourHoursAgo = Calendar.getInstance();
    twentyFourHoursAgo.add(Calendar.DATE, -1);
    return createdDateRaw != null && twentyFourHoursAgo.before(createdDateRaw);
}
 
Example #13
Source File: ViewHelper.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
public boolean isFolder() {
    Resource resource = getResource();

    return resource.isResourceType("sling:Folder")
            || resource.isResourceType("sling:OrderedFolder")
            || resource.isResourceType(JcrConstants.NT_FOLDER);
}
 
Example #14
Source File: ViewHelper.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
@Override
public void activate() throws Exception {
    product = getResource().adaptTo(Product.class);

    i18n = new I18n(getRequest());

    String lastReplicationAction = getProperties().get("cq:lastReplicationAction", String.class);
    boolean deactivated = "Deactivate".equals(lastReplicationAction);

    publishedTime = getProperties().get("cq:lastReplicated", Calendar.class);
    modifiedTime = getProperties().get(JcrConstants.JCR_LASTMODIFIED, Calendar.class);

    resolver = getResourceResolver();
    externalizer = resolver.adaptTo(Externalizer.class);
}
 
Example #15
Source File: CIFCategoryFieldHelper.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
public boolean isCloudFolder() {
    Resource resource = getResource();

    return (isVirtual(resource) || isCloudBoundFolder(resource)) && (resource.isResourceType("sling:Folder")
            || resource.isResourceType("sling:OrderedFolder")
            || resource.isResourceType(JcrConstants.NT_FOLDER));
}
 
Example #16
Source File: ConfigurationColumnPreview.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
@PostConstruct
protected void initModel() {

    Config cfg = new Config(request.getResource());

    final SlingScriptHelper sling = ((SlingBindings) request.getAttribute(SlingBindings.class.getName())).getSling();
    ExpressionResolver expressionResolver = sling.getService(ExpressionResolver.class);
    final ExpressionHelper ex = new ExpressionHelper(expressionResolver, request);

    String itemResourcePath = ex.getString(cfg.get("path", String.class));
    LOG.debug("Item in preview is at path {}", itemResourcePath);

    itemResource = request.getResourceResolver().getResource(itemResourcePath);
    if (itemResource == null) {
        return;
    }
    isFolder = itemResource.isResourceType(JcrConstants.NT_FOLDER) || itemResource.isResourceType(JcrResourceConstants.NT_SLING_FOLDER)
        || itemResource
            .isResourceType(JcrResourceConstants.NT_SLING_ORDERED_FOLDER);

    if (isFolder) {
        properties = itemResource.getValueMap();
    } else {
        Resource jcrContent = itemResource.getChild(JcrConstants.JCR_CONTENT);
        properties = jcrContent != null ? jcrContent.getValueMap() : itemResource.getValueMap();
    }
}
 
Example #17
Source File: ProductsSuggestionOmniSearchHandler.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
@Override
public QueryResult execute() throws InvalidQueryException, RepositoryException {
    // Get JCR results
    QueryResult queryResult = query.execute();

    // Get CIF products
    Iterator<Resource> it = getVirtualResults(resolver, Collections.singletonMap("fulltext", searchTerm), 10, 0);
    if (it == null || !it.hasNext()) {
        return queryResult; // No CIF results
    }

    ValueFactory valueFactory = resolver.adaptTo(Session.class).getValueFactory();
    List<Row> rows = new ArrayList<>();
    while (it.hasNext()) {
        String title = it.next().getValueMap().get(JcrConstants.JCR_TITLE, String.class);
        Value value = valueFactory.createValue(title);
        rows.add(new SuggestionRow(value));
    }

    RowIterator suggestionIterator = queryResult.getRows();
    while (suggestionIterator.hasNext()) {
        rows.add(suggestionIterator.nextRow());
    }

    SuggestionQueryResult result = new SuggestionQueryResult(rows);
    return result;
}
 
Example #18
Source File: CategoryResource.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a SyntheticResource for the given Magento GraphQL CategoryTree.
 * 
 * @param resourceResolver The resource resolver.
 * @param path The path of the category resource that will be created.
 * @param category The Magento GraphQL CategoryTree.
 */
CategoryResource(ResourceResolver resourceResolver, String path, CategoryTree category) {
    super(resourceResolver, path, JcrResourceConstants.NT_SLING_FOLDER);
    Map<String, Object> map = new HashMap<>();
    map.put(JcrConstants.JCR_PRIMARYTYPE, JcrResourceConstants.NT_SLING_FOLDER);
    map.put(ResourceResolver.PROPERTY_RESOURCE_TYPE, JcrResourceConstants.NT_SLING_FOLDER);
    map.put(CommerceConstants.PN_COMMERCE_TYPE, CATEGORY);
    map.put(CommerceConstants.PN_COMMERCE_PROVIDER, MAGENTO_GRAPHQL_PROVIDER);

    if (category != null) {
        map.put(JcrConstants.JCR_TITLE, category.getName());
        map.put(CIF_ID, category.getId());
        String str = category.getChildrenCount();
        int childCount = 0;
        try {
            childCount = Integer.parseInt(str);
        } catch (Exception x) {
            // ignore
        }
        boolean hasChildren = childCount > 0;
        hasChildren |= category.getChildren() != null && !category.getChildren().isEmpty();
        map.put(LEAF_CATEGORY, !hasChildren);
        hasChildren |= category.getProductCount() != null && category.getProductCount() > 0;
        map.put("hasChildren", hasChildren);
    } else {
        map.put(JcrConstants.JCR_TITLE, MAGENTO_GRAPHQL_PROVIDER);
    }
    values = new DeepReadValueMapDecorator(this, new ValueMapDecorator(map));
}
 
Example #19
Source File: ProductResource.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
/**
 * 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));
}
 
Example #20
Source File: CIFCategoryFieldHelper.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
private boolean isFolder(Resource resource ) {
    return resource.isResourceType("sling:Folder")
            || resource.isResourceType("sling:OrderedFolder")
            || resource.isResourceType(JcrConstants.NT_FOLDER);
}
 
Example #21
Source File: ProductsSuggestionOmniSearchHandlerTest.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
@Test
public void testSuggestionQuery() throws Exception {

    // The mocked JCR result
    MockNode jcrNode = new MockNode("/var/commerce/products/jcrnode");
    jcrNode.setProperty("rep:suggest()", BROOKLYN_COAT);
    MockQueryResult jcrResults = new MockQueryResult(Collections.singletonList(jcrNode));
    Query jcrQuery = Mockito.mock(Query.class);
    Mockito.when(jcrQuery.execute()).thenReturn(jcrResults);

    Mockito.doReturn(jcrQuery).when(suggestionHandler).getSuperSuggestionQuery(resolver, "coats");
    Mockito.doReturn(resolver).when(suggestionHandler).getResourceResolver();

    ValueFactory valueFactory = Mockito.mock(ValueFactory.class);
    Mockito.when(valueFactory.createValue(EL_GORDO_DOWN_JACKET)).thenReturn(new MockValue(EL_GORDO_DOWN_JACKET));
    Session session = Mockito.mock(Session.class);
    Mockito.when(resolver.adaptTo(Session.class)).thenReturn(session);
    Mockito.when(session.getValueFactory()).thenReturn(valueFactory);

    // The mocked CIF result
    MockResource cifProduct = new MockResource(resolver, "/var/commerce/products/graphql/cifresource", "commerce/components/product");
    cifProduct.addProperty(JcrConstants.JCR_TITLE, EL_GORDO_DOWN_JACKET); // The title is used for the suggestion
    Mockito.when(resolver.findResources(Mockito.any(), Mockito.any()))
        .thenReturn(Collections.singletonList((Resource) cifProduct).iterator());

    suggestionHandler.activate(null);
    suggestionHandler.onEvent(null);

    Query suggestionQuery = suggestionHandler.getSuggestionQuery(resolver, "coats");
    QueryResult queryResult = suggestionQuery.execute();
    RowIterator rows = queryResult.getRows();

    // The CIF result is first, then the JCR result
    Row row = rows.nextRow();
    Assert.assertEquals(EL_GORDO_DOWN_JACKET, row.getValue("rep:suggest()").getString());
    Assert.assertEquals(BROOKLYN_COAT, rows.nextRow().getValue("rep:suggest()").getString());

    // Not implemented
    Assert.assertNull(suggestionQuery.getLanguage());
    Assert.assertNull(suggestionQuery.getStatement());
    Assert.assertNull(suggestionQuery.getStoredQueryPath());
    Assert.assertNull(suggestionQuery.getBindVariableNames());
    Assert.assertNull(suggestionQuery.storeAsNode("whatever"));

    Assert.assertNull(queryResult.getColumnNames());
    Assert.assertNull(queryResult.getNodes());
    Assert.assertNull(queryResult.getSelectorNames());

    Assert.assertNull(row.getValues());
    Assert.assertNull(row.getPath());
    Assert.assertNull(row.getPath("whatever"));
    Assert.assertNull(row.getNode());
    Assert.assertNull(row.getNode("whatever"));
    Assert.assertEquals(0d, row.getScore(), 0);
    Assert.assertEquals(0d, row.getScore("whatever"), 0);

    suggestionHandler.deactivate(null);
}
 
Example #22
Source File: GraphqlResourceProviderTest.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testSimpleProductResource() throws IOException, CommerceException {
    Utils.setupHttpResponse("magento-graphql-categorylist-empty.json", httpClient, HttpStatus.SC_OK,
        "{categoryList(filters:{url_key:{eq:\"24-MB01\"");
    Utils.setupHttpResponse("magento-graphql-categorylist-coats.json", httpClient, HttpStatus.SC_OK,
        "{categoryList(filters:{url_key:{eq:\"coats\"");
    Utils.setupHttpResponse("magento-graphql-categorylist-empty.json", httpClient, HttpStatus.SC_OK,
        "{categoryList(filters:{url_key:{eq:\"image\"");
    Utils.setupHttpResponse("magento-graphql-simple-product.json", httpClient, HttpStatus.SC_OK, "{product");

    String productPath = CATALOG_ROOT_PATH + "/men/coats/24-MB01";

    Resource resource = provider.getResource(resolveContext, productPath, null, null);
    assertTrue(resource instanceof ProductResource);
    assertTrue(MagentoProduct.isAProductOrVariant(resource));
    assertEquals("24-MB01", resource.getValueMap().get("sku", String.class));
    Date lastModified = resource.getValueMap().get(JcrConstants.JCR_LASTMODIFIED, Date.class);
    assertTrue(lastModified != null);

    Product product = resource.adaptTo(Product.class);
    assertEquals(product, product.getBaseProduct());
    assertEquals(product, product.getPIMProduct());
    assertEquals("24-MB01", product.getSKU());
    assertFalse(resource.getValueMap().get("hasChildren", Boolean.class));
    assertEquals("Joust Duffle Bag", product.getTitle());
    assertEquals("The sporty Joust Duffle Bag can't be beat", product.getDescription());

    String imageUrl = "http://hostname/pub/media/catalog/product/mb01-blue-0.jpg";
    assertEquals(imageUrl, product.getImageUrl());
    assertEquals(imageUrl, product.getThumbnailUrl());
    assertEquals(imageUrl, product.getThumbnailUrl(123));
    assertEquals(imageUrl, product.getThumbnailUrl("selector"));
    assertNull(product.getThumbnail());
    assertEquals("joust-duffle-bag", product.getProperty("urlKey", String.class));
    assertNull(product.getProperty("whatever", String.class));

    assertEquals(imageUrl, product.getAsset().getPath());
    assertEquals(imageUrl, product.getAssets().get(0).getPath());

    assertEquals(productPath + "/image", product.getImage().getPath());
    assertEquals(productPath + "/image", product.getImages().get(0).getPath());
    assertNull(product.getImagePath());

    // We do not extract variant axes
    assertFalse(product.getVariantAxes().hasNext());
    assertFalse(product.axisIsVariant("whatever"));

    // A simple product doesn't have any variant
    assertFalse(product.getVariants().hasNext());

    Iterator<Resource> it = provider.listChildren(resolveContext, resource);

    // First child is the image
    Resource imageResource = it.next();
    assertEquals(productPath + "/image", imageResource.getPath());
    assertEquals(imageUrl, imageResource.getValueMap().get(DownloadResource.PN_REFERENCE, String.class));
    // Deep read image/fileReference of product
    assertEquals(imageUrl, resource.getValueMap().get("image/" + DownloadResource.PN_REFERENCE, String.class));

    // A simple product doesn't have any variant
    assertFalse(it.hasNext());
}
 
Example #23
Source File: GraphqlResourceProviderTest.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testConfigurableProductResource() throws IOException, CommerceException {
    Utils.setupHttpResponse("magento-graphql-categorylist-empty.json", httpClient, HttpStatus.SC_OK,
        "{categoryList(filters:{url_key:{eq:\"meskwielt\"");
    Utils.setupHttpResponse("magento-graphql-categorylist-coats.json", httpClient, HttpStatus.SC_OK,
        "{categoryList(filters:{url_key:{eq:\"coats\"");
    Utils.setupHttpResponse("magento-graphql-product.json", httpClient, HttpStatus.SC_OK, "{product");
    Utils.setupHttpResponse("magento-graphql-categorylist-empty.json", httpClient, HttpStatus.SC_OK,
        "{categoryList(filters:{url_key:{eq:\"meskwielt-Purple-XS\"");

    Resource resource = provider.getResource(resolveContext, PRODUCT_PATH, null, null);
    assertTrue(resource instanceof ProductResource);
    assertTrue(MagentoProduct.isAProductOrVariant(resource));
    assertEquals(SKU, resource.getValueMap().get("sku", String.class));
    assertTrue(resource.getValueMap().get("hasChildren", Boolean.class));
    Date lastModified = resource.getValueMap().get(JcrConstants.JCR_LASTMODIFIED, Date.class);
    assertTrue(lastModified != null);

    Product product = resource.adaptTo(Product.class);
    assertEquals(product, product.getBaseProduct());
    assertEquals(product, product.getPIMProduct());
    assertEquals(SKU, product.getSKU());
    assertEquals(NAME, product.getTitle());
    assertEquals(DESCRIPTION, product.getDescription());
    assertEquals(IMAGE_URL, product.getImageUrl());
    assertEquals(IMAGE_URL, product.getThumbnailUrl());
    assertEquals(IMAGE_URL, product.getThumbnailUrl(123));
    assertEquals(IMAGE_URL, product.getThumbnailUrl("selector"));
    assertNull(product.getThumbnail());
    assertEquals(URL_KEY, product.getProperty("urlKey", String.class));
    assertNull(product.getProperty("whatever", String.class));

    assertEquals(IMAGE_URL, product.getAsset().getPath());
    assertEquals(IMAGE_URL, product.getAssets().get(0).getPath());

    assertEquals(PRODUCT_PATH + "/image", product.getImage().getPath());
    assertEquals(PRODUCT_PATH + "/image", product.getImages().get(0).getPath());
    assertNull(product.getImagePath());

    // We do not extract variant axes
    assertFalse(product.getVariantAxes().hasNext());
    assertFalse(product.axisIsVariant("whatever"));

    // Test master variant when fetched via Product API
    Product masterVariant = product.getVariants().next();
    assertMasterVariant(masterVariant);

    Iterator<Resource> it = provider.listChildren(resolveContext, resource);

    // First child is the image
    Resource imageResource = it.next();
    assertEquals(PRODUCT_PATH + "/image", imageResource.getPath());
    assertEquals(IMAGE_URL, imageResource.getValueMap().get(DownloadResource.PN_REFERENCE, String.class));

    // Test master variant when fetched via Resource API
    Resource firstVariant = it.next();
    assertEquals(MASTER_VARIANT_SKU, firstVariant.getValueMap().get("sku", String.class));

    // Test deep read firstVariantName/sku
    assertEquals(MASTER_VARIANT_SKU, resource.getValueMap().get(firstVariant.getName() + "/sku", String.class));
}
 
Example #24
Source File: ConfigurationColumnViewItem.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
private boolean isFolder(Resource resource) {
    return resource.isResourceType(JcrConstants.NT_FOLDER) || isSlingFolder(resource);
}
 
Example #25
Source File: ConfigurationColumnViewItem.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
public String getTitle() {
    Resource jcrContent = resource.getChild(JcrConstants.JCR_CONTENT);
    ValueMap properties = jcrContent != null ? jcrContent.getValueMap() : resource.getValueMap();
    return properties.get(JcrConstants.JCR_TITLE, resource.getName());
}
 
Example #26
Source File: ConfigurationColumnPreview.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
public String getTitle() {
    return properties != null ? properties.get(JcrConstants.JCR_TITLE, itemResource.getName()) : "";
}
 
Example #27
Source File: DefaultPageDataElement.java    From AEM-DataLayer with Apache License 2.0 4 votes vote down vote up
@Override
public void updateDataLayer(DataLayer dataLayer) {
	EventInfo event = new EventInfo();
	event.setEventAction("pageLoad");
	event.setEventName("Page Load");
	dataLayer.getEvents().add(event);

	Page page = dataLayer.getPage();

	PageInfo pageInfo = new PageInfo();
	if (dataLayer.getConfig().getSetAuthor() == true) {
		pageInfo.setAuthor(dataLayer.getAEMPage().getLastModifiedBy());
	}

	List<String> breadcrumbs = new ArrayList<String>();
	com.day.cq.wcm.api.Page currentPage = dataLayer.getAEMPage();
	while (currentPage != null && currentPage.getDepth() > dataLayer.getConfig().getSiteRootLevel()) {
		breadcrumbs.add(currentPage.getTitle());
		currentPage = currentPage.getParent();
	}

	Collections.reverse(breadcrumbs);
	pageInfo.setBreadcrumbs(breadcrumbs.toArray(new String[breadcrumbs.size()]));

	currentPage = dataLayer.getAEMPage();
	ValueMap properties = currentPage.getContentResource().getValueMap();
	String path = DataLayerUtil.getSiteSubpath(currentPage, dataLayer.getConfig());

	pageInfo.setDestinationUrl(DataLayerUtil.getSiteUrl(currentPage, dataLayer.getConfig()));
	if (currentPage.getOnTime() != null) {
		pageInfo.setEffectiveDate(currentPage.getOnTime().getTime());
	} else if (properties.containsKey(JcrConstants.JCR_CREATED)) {
		pageInfo.setEffectiveDate(properties.get(JcrConstants.JCR_CREATED, Date.class));
	}
	if (currentPage.getOffTime() != null) {
		pageInfo.setExpiryDate(currentPage.getOffTime().getTime());
	}
	if (properties.containsKey(JcrConstants.JCR_CREATED)) {
		pageInfo.setIssueDate(properties.get(JcrConstants.JCR_CREATED, Date.class));
	}
	pageInfo.setLanguage(currentPage.getLanguage(false).toString());
	pageInfo.setPageId(path);
	pageInfo.setPageName(currentPage.getTitle());
	if (StringUtils.isNotEmpty(dataLayer.getConfig().getPublisher())) {
		pageInfo.setPublisher(dataLayer.getConfig().getPublisher());
	}
	pageInfo.setSysEnv(dataLayer.getConfig().getEnvironment());

	page.setPageInfo(pageInfo);

	String templateName = StringUtils.substringAfterLast(properties.get(NameConstants.NN_TEMPLATE, String.class),
			"/");
	List<String> tags = new ArrayList<String>();

	Category category = new Category();
	category.setPrimaryCategory(templateName);
	for (int i = 0; i < currentPage.getTags().length; i++) {
		category.put("tag" + i, currentPage.getTags()[i].getTitle());
		tags.add(currentPage.getTags()[i].getTitle());
	}
	page.setCategory(category);

	Map<String, Object> attributes = new HashMap<String, Object>();
	attributes.put("tags", tags.toArray(new String[tags.size()]));
	attributes.put("template", templateName);
	page.setAttributes(attributes);

}
 
Example #28
Source File: ScriptsRowModel.java    From APM with Apache License 2.0 4 votes vote down vote up
public static boolean isFolder(Resource resource) {
  return FOLDER_TYPES.contains(getProperty(resource, JcrConstants.JCR_PRIMARYTYPE));
}
 
Example #29
Source File: ScriptModel.java    From APM with Apache License 2.0 4 votes vote down vote up
public static boolean isScript(Resource resource) {
  return java.util.Optional.ofNullable(resource)
      .map(child -> getArrayProperty(child, JcrConstants.JCR_MIXINTYPES).contains(ScriptNode.APM_SCRIPT))
      .orElse(false);
}
 
Example #30
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);
    }

}