Java Code Examples for org.apache.sling.api.SlingHttpServletRequest#setAttribute()

The following examples show how to use org.apache.sling.api.SlingHttpServletRequest#setAttribute() . 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: GraphqlProductViewHandler.java    From commerce-cif-connector with Apache License 2.0 6 votes vote down vote up
protected String generateHtmlOutput(Collection<Hit> hits, SlingHttpServletRequest request,
    SlingHttpServletResponse response) throws ServletException, IOException {
    // if resource type is not set return String representation of search result
    if (request.getParameter("itemResourceType") == null) {
        return hits.toString();
    }

    StringResponseWrapper hitResponse = new StringResponseWrapper(response);

    RequestDispatcherOptions requestDispatcherOptions = new RequestDispatcherOptions(null);

    // Force a resource type, to render the resource in a specific way
    requestDispatcherOptions.setForceResourceType(request.getParameter("itemResourceType"));

    for (Hit hit : hits) {
        Resource resource = (Resource) hit.get("resource");
        if (resource != null) {
            request.setAttribute(Resource.class.getCanonicalName(), resource);
            RequestDispatcher dispatcher = request.getRequestDispatcher(resource, requestDispatcherOptions);
            dispatcher.include(request, hitResponse);
            request.removeAttribute(Resource.class.getCanonicalName());
        }
    }
    return hitResponse.getString();
}
 
Example 3
Source File: AEMDataLayerInterceptorFilter.java    From AEM-DataLayer with Apache License 2.0 6 votes vote down vote up
private boolean isApplicable(SlingHttpServletRequest request) {
	Object appliable = request.getAttribute(REQUEST_PROPERTY_AEM_DATALAYER_APPLICABLE);
	if (appliable == null) {
		Resource resource = request.getResource();
		PageManager pMgr = resource.getResourceResolver().adaptTo(PageManager.class);
		Page page = pMgr.getContainingPage(resource);
		AEMDataLayerConfig config = AEMDataLayerConfig.getDataLayerConfig(page);
		if (config != null) {
			DataLayer dataLayer = new DataLayer(config, page);
			request.setAttribute(DataLayerConstants.REQUEST_PROPERTY_AEM_DATALAYER, dataLayer);
			request.setAttribute(REQUEST_PROPERTY_AEM_DATALAYER_APPLICABLE, Boolean.TRUE);
			return true;
		} else {
			request.setAttribute(REQUEST_PROPERTY_AEM_DATALAYER_APPLICABLE, Boolean.FALSE);
			return false;
		}
	} else {
		return Boolean.TRUE.equals(appliable);
	}
}
 
Example 4
Source File: ExportServlet.java    From sling-org-apache-sling-models-impl with Apache License 2.0 6 votes vote down vote up
private void addScriptBindings(SlingScriptHelper scriptHelper, SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws IOException {
    SimpleBindings bindings = new SimpleBindings();
    bindings.put(SLING, scriptHelper);
    bindings.put(RESOURCE, request.getResource());
    bindings.put(SlingModelsScriptEngineFactory.RESOLVER, request.getResource().getResourceResolver());
    bindings.put(REQUEST, request);
    bindings.put(RESPONSE, response);
    try {
        bindings.put(READER, request.getReader());
    } catch (Exception e) {
        bindings.put(READER, new BufferedReader(new StringReader("")));
    }
    bindings.put(OUT, response.getWriter());
    bindings.put(LOG, logger);

    scriptEngineFactory.invokeBindingsValuesProviders(bindingsValuesProvidersByContext, bindings);

    SlingBindings slingBindings = new SlingBindings();
    slingBindings.putAll(bindings);

    request.setAttribute(SlingBindings.class.getName(), slingBindings);

}
 
Example 5
Source File: CatalogIdentifierDatasource.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(@Nonnull SlingHttpServletRequest request, @Nonnull SlingHttpServletResponse response) throws ServletException,
    IOException {
    DataSource ds;

    if (catalogIdentifierService == null) {
        ds = EmptyDataSource.instance();
    } else {
        ds = buildValuesList(request.getResourceResolver());
    }

    request.setAttribute(DataSource.class.getName(), ds);
}
 
Example 6
Source File: IsProductDetailPageServlet.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
    final Config cfg = new Config(request.getResource());
    final SlingScriptHelper sling = ((SlingBindings) request.getAttribute(SlingBindings.class.getName())).getSling();
    final ExpressionHelper ex = new ExpressionHelper(sling.getService(ExpressionResolver.class), request);
    final String path = ex.getString(cfg.get("path", String.class));
    boolean decision = isProductDetailPage(path, request.getResourceResolver());
    request.setAttribute(RenderCondition.class.getName(), new SimpleRenderCondition(decision));
    if (decision) {
        prepareCatalogPathProperty(path, request);
    }
}
 
Example 7
Source File: IsProductListPageServlet.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
    final Config cfg = new Config(request.getResource());
    final SlingScriptHelper sling = ((SlingBindings) request.getAttribute(SlingBindings.class.getName())).getSling();
    final ExpressionHelper ex = new ExpressionHelper(sling.getService(ExpressionResolver.class), request);
    final String path = ex.getString(cfg.get("path", String.class));
    boolean decision = isProductListPage(path, request.getResourceResolver());
    request.setAttribute(RenderCondition.class.getName(), new SimpleRenderCondition(decision));
    if (decision) {
        prepareCatalogPathProperty(path, request);
    }
}
 
Example 8
Source File: SearchDataSourceServlet.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
    final String PARAMETER_OFFSET = "_commerce_offset";
    final String PARAMETER_LIMIT = "_commerce_limit";
    final String PARAMETER_COMMERCE_TYPE = "_commerce_commerce_type";
    final Config cfg = new Config(request.getResource().getChild(Config.DATASOURCE));
    final SlingScriptHelper sling = ((SlingBindings) request.getAttribute(SlingBindings.class.getName())).getSling();
    final ExpressionHelper ex = new ExpressionHelper(sling.getService(ExpressionResolver.class), request);
    final String itemRT = cfg.get("itemResourceType", String.class);
    final long offset = ex.get(cfg.get("offset", "0"), long.class);
    final long limit = ex.get(cfg.get("limit", "20"), long.class);
    final String commerceType = ex.get(cfg.get("commerceType", "product"), String.class);

    Map<String, Object> queryParameters = new HashMap<>(request.getParameterMap());
    queryParameters.put(PARAMETER_OFFSET, String.valueOf(offset));
    queryParameters.put(PARAMETER_LIMIT, String.valueOf(limit));
    queryParameters.put(PARAMETER_COMMERCE_TYPE, commerceType);

    final String rootPath = request.getParameter("root");

    String rootCategoryId = new CatalogSearchSupport(request.getResourceResolver()).findCategoryId(rootPath);
    if (rootCategoryId != null) {
        queryParameters.put(CATEGORY_ID_PARAMETER, rootCategoryId);
        queryParameters.put(CATEGORY_PATH_PARAMETER, rootPath);
    }
    String queryString = new ObjectMapper().writeValueAsString(queryParameters);
    try {
        Iterator<Resource> virtualResults = request.getResourceResolver().findResources(queryString, VIRTUAL_PRODUCT_QUERY_LANGUAGE);

        final DataSource ds = new SimpleDataSource(new TransformIterator<>(virtualResults, r -> new ResourceWrapper(r) {
            public String getResourceType() {
                return itemRT;
            }
        }));

        request.setAttribute(DataSource.class.getName(), ds);
    } catch (Exception x) {
        response.sendError(500, x.getMessage());
        LOGGER.error("Error finding resources", x);
    }
}
 
Example 9
Source File: ScriptsDatasourceServlet.java    From APM with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
  String path = request.getRequestPathInfo().getSuffix();
  List<Resource> scripts = new ArrayList<>();
  Resource resource = request.getResourceResolver().getResource(path);
  for (Resource child : resource.getChildren()) {
    if (ScriptsRowModel.isFolder(child) || ScriptModel.isScript(child)) {
      scripts.add(new ResourceTypeWrapper(child));
    }
  }
  DataSource dataSource = new SimpleDataSource(scripts.iterator());
  request.setAttribute(DataSource.class.getName(), dataSource);
}
 
Example 10
Source File: HistoryDatasourceServlet.java    From APM with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
  Pagination pagination = createPagination(request);
  List<Resource> allHistoryResources = pagination.getPage(history.findAllResources(request.getResourceResolver()))
      .stream()
      .map(ResourceTypeWrapper::new)
      .collect(Collectors.toList());
  DataSource dataSource = new SimpleDataSource(allHistoryResources.iterator());
  request.setAttribute(DataSource.class.getName(), dataSource);
}
 
Example 11
Source File: ChildrenDatasourceServlet.java    From APM with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
  Iterator<Resource> iterator = Optional.ofNullable(request.getResource())
      .flatMap(parent -> Optional.ofNullable(parent.getChild("items")))
      .map(items -> items.listChildren())
      .orElse(Collections.emptyIterator());
  DataSource dataSource = new SimpleDataSource(iterator);
  request.setAttribute(DataSource.class.getName(), dataSource);
}
 
Example 12
Source File: AbstractDatasourceServlet.java    From APM with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
  SimpleDataSourceBuilder builder = new SimpleDataSourceBuilder(request.getResourceResolver());
  if (emptyOption != null) {
    builder.addOption(emptyOption);
  }
  options.forEach(item -> builder.addOption(getName(item.toString()), item.toString()));
  request.setAttribute(DataSource.class.getName(), builder.build());
}
 
Example 13
Source File: children.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response){

        final SlingScriptHelper sling = getScriptHelper(request);

        final ExpressionHelper ex = new ExpressionHelper(sling.getService(ExpressionResolver.class), request);
        final Config dsCfg = new Config(request.getResource().getChild(Config.DATASOURCE));
        final CommerceBasePathsService cbps = sling.getService(CommerceBasePathsService.class);

        final String query = ex.getString(dsCfg.get("query", String.class));

        final String parentPath;
        final String searchName;
        final String rootPath = ex.getString(dsCfg.get("rootPath", cbps.getProductsBasePath()));

        if (query != null) {
            final int slashIndex = query.lastIndexOf('/');
            if (slashIndex < 0) {
                parentPath = rootPath;
                searchName = query.toLowerCase();
            } else if (!query.startsWith(rootPath)) {
                parentPath = rootPath;
                searchName = null;
            } else if (slashIndex == query.length() - 1) {
                parentPath = query;
                searchName = null;
            } else {
                parentPath = query.substring(0, slashIndex + 1);
                searchName = query.substring(slashIndex + 1).toLowerCase();
            }
        } else {
            parentPath = ex.getString(dsCfg.get("path", String.class));
            searchName = null;
        }

        final Resource parent = request.getResourceResolver().getResource(parentPath);

        final DataSource ds;
        if (parent == null) {
            ds = EmptyDataSource.instance();
        } else {
            final Integer offset = ex.get(dsCfg.get("offset", String.class), Integer.class);
            final Integer limit = ex.get(dsCfg.get("limit", String.class), Integer.class);
            final String itemRT = dsCfg.get("itemResourceType", String.class);
            final String filter = ex.getString(dsCfg.get("filter", String.class));

            final Collection<Predicate<Resource>> predicates = new ArrayList<>(2);
            predicates.add(createPredicate(filter));

            if (searchName != null) {
                final Pattern searchNamePattern = Pattern.compile(Pattern.quote(searchName), Pattern.CASE_INSENSITIVE);
                predicates.add(resource -> searchNamePattern.matcher(resource.getName()).lookingAt());
            }

            final Predicate predicate = PredicateUtils.allPredicate(predicates);
            final Transformer transformer = createTransformer(itemRT, predicate);


            final List<Resource> list;
            if (FILTER_CATEGORY.equals(filter)) {
                class CategoryFinder extends AbstractResourceVisitor {
                    private CategoryPredicate categoryPredicate = new CategoryPredicate();
                    private List<Resource> categories = new ArrayList<Resource>();
                    @Override
                    protected void visit(Resource res) {
                        if (categoryPredicate.evaluate(res)) {
                            categories.add(res);
                        }
                    }
                };
                CategoryFinder categoryFinder = new CategoryFinder();
                categoryFinder.accept(parent);
                list = IteratorUtils.toList(new FilterIterator(categoryFinder.categories.iterator(), predicate));
            } else {
                list =IteratorUtils.toList(new FilterIterator(parent.listChildren(), predicate));
            }

            //force reloading the children of the root node to hit the virtual resource provider
            if (rootPath.equals(parentPath)) {
                for (int i = 0; i < list.size(); i++) {
                    list.set(i, request.getResourceResolver().getResource(list.get(i).getPath()));
                }
            }

            @SuppressWarnings("unchecked")
            DataSource datasource = new AbstractDataSource() {

                public Iterator<Resource> iterator() {
                    Collections.sort(list, Comparator.comparing(Resource::getName));
                    return new TransformIterator(new PagingIterator<>(list.iterator(), offset, limit), transformer);
                }
            };

            ds = datasource;
        }

        request.setAttribute(DataSource.class.getName(), ds);
    }
 
Example 14
Source File: GraphqlClientDataSourceServlet.java    From aem-core-cif-components with Apache License 2.0 4 votes vote down vote up
@Override
protected void doGet(@Nonnull SlingHttpServletRequest request, @Nonnull SlingHttpServletResponse response) {
    i18n = new I18n(request);
    SimpleDataSource graphqlClientDataSource = new SimpleDataSource(getGraphqlClients(request).iterator());
    request.setAttribute(DataSource.class.getName(), graphqlClientDataSource);
}
 
Example 15
Source File: PageTypeRenderConditionServlet.java    From aem-core-cif-components with Apache License 2.0 4 votes vote down vote up
@Override
protected void doGet(@Nonnull SlingHttpServletRequest request, @Nonnull SlingHttpServletResponse response) {
    String pageType = request.getResource().getValueMap().get(PAGE_TYPE_PROPERTY, "");
    request.setAttribute(RenderCondition.class.getName(), new SimpleRenderCondition(checkPageType(request, pageType)));
}
 
Example 16
Source File: MockServletResolver.java    From sling-whiteboard with Apache License 2.0 4 votes vote down vote up
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
    request.setAttribute(RESOURCE_ATTR, request.getResource());
}