Java Code Examples for org.apache.sling.api.SlingHttpServletRequest

The following examples show how to use org.apache.sling.api.SlingHttpServletRequest. These examples are extracted from open source projects. 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
@Test
public void testWithInitializedRequest() {
    // destroy a wrapper of the root request
    SlingHttpServletRequest destroyedRequest = new SlingHttpServletRequestWrapper(request);
    factory.requestInitialized(new ServletRequestEvent(servletContext, destroyedRequest));

    // but adapt from a wrapper of a wrapper of that wrapper
    SlingHttpServletRequest adaptableRequest = new SlingHttpServletRequestWrapper(new SlingHttpServletRequestWrapper(destroyedRequest));

    TestModel model = factory.getAdapter(adaptableRequest, TestModel.class);
    assertEquals("teststring", model.testString);

    assertNoneDisposed();

    factory.requestDestroyed(new ServletRequestEvent(servletContext, destroyedRequest));

    assertAllDisposed();
}
 
Example 2
Source Project: APM   Source File: ScriptRunBackgroundServlet.java    License: Apache License 2.0 6 votes vote down vote up
private BackgroundJobParameters getParameters(final SlingHttpServletRequest request,
    final SlingHttpServletResponse response) throws IOException {
  final String searchPath = request.getParameter(FILE_REQUEST_PARAMETER);
  final String modeName = request.getParameter(MODE_REQUEST_PARAMETER);
  final String userName = request.getResourceResolver().getUserID();

  if (StringUtils.isEmpty(searchPath)) {
    ServletUtils.writeMessage(response, ERROR_RESPONSE_TYPE,
        "Please set the script file name: -d \"file=[name]\"");
    return null;
  }

  if (StringUtils.isEmpty(modeName)) {
    ServletUtils.writeMessage(response, ERROR_RESPONSE_TYPE, "Running mode not specified.");
    return null;
  }

  return new BackgroundJobParameters(searchPath, modeName, userName);
}
 
Example 3
Source Project: aem-solr-search   Source File: SolrQueryHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");

    JSONArray solrDocs = new JSONArray();

    SolrClient solr = getQueryingSolrClient();

    try {
        LOG.debug("Query using Solr Client {} and the solr core {}", solr, core);
        QueryResponse result = solr.query(core, new SolrQuery("*:*"));
        SolrDocumentList list=result.getResults();
        response.getWriter().write(list.toString());

    } catch (SolrServerException e) {
        e.printStackTrace();
    }


}
 
Example 4
@Test
public void testWithUnitializedRequest() {
    // destroy a wrapper of the root request
    SlingHttpServletRequest destroyedRequest = new SlingHttpServletRequestWrapper(request);

    // but adapt from a wrapper of a wrapper of that wrapper
    SlingHttpServletRequest adaptableRequest = new SlingHttpServletRequestWrapper(new SlingHttpServletRequestWrapper(destroyedRequest));

    TestModel model = factory.getAdapter(adaptableRequest, TestModel.class);
    assertEquals("teststring", model.testString);

    assertNoneDisposed();

    factory.requestDestroyed(new ServletRequestEvent(servletContext, destroyedRequest));

    assertNoneDisposed();
}
 
Example 5
Source Project: publick-sling-blog   Source File: CommentServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Delete comment by setting it's display property to false.
 *
 * @param request The current request to get session and Resource Resolver
 * @param id The comment UUID
 * @return true if the operation was successful
 */
public boolean deleteComment(final SlingHttpServletRequest request, final String id) {
    boolean result = false;

    try {
        Session session = request.getResourceResolver().adaptTo(Session.class); 
        Node node = session.getNodeByIdentifier(id);

        if (node != null) {
            JcrResourceUtil.setProperty(node, PublickConstants.COMMENT_PROPERTY_DISPLAY, false);
            session.save();
            result = true;
        }
    } catch (RepositoryException e) {
        LOGGER.error("Could not delete comment from JCR", e);
    }

    return result;
}
 
Example 6
@Override
public Object getAdaptable(Object original, String value) {
    if (StringUtils.isBlank(value)) {
        return ORIGINAL;
    }
    if (original instanceof Resource) {
        return ((Resource) original).getChild(value);
    } else if (original instanceof SlingHttpServletRequest) {
        final SlingHttpServletRequest request = (SlingHttpServletRequest) original;
        final Resource resource = request.getResource();
        if (resource == null) {
            return null;
        }
        Resource child = resource.getChild(value);
        if (child == null) {
            log.debug("Could not obtain child {} of resource {}", value, resource.getPath());
            return null;
        }
        return new ChildResourceRequestWrapper(request, child);
    } else {
        log.warn("Received unexpected adaptable of type {}.", original.getClass().getName());
        return null;
    }
}
 
Example 7
Source Project: APM   Source File: ScriptResultServlet.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
    throws IOException {

  String fileName = request.getParameter("filename");
  String content = request.getParameter("content");

  if (fileName == null || fileName.length() == 0) {
    LOGGER.error("Parameter fileName is required");
    return;
  }

  response.setContentType("application/octet-stream");
  response.setHeader("Content-Disposition",
      "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

  InputStream input = IOUtils.toInputStream(content);
  IOUtils.copy(input, response.getOutputStream());
}
 
Example 8
@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 9
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 10
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 11
Source Project: sling-samples   Source File: HexNodeNameGenerator.java    License: Apache License 2.0 6 votes vote down vote up
/** @inheritDoc */
public String getNodeName(
        SlingHttpServletRequest request, 
        String parentPath, 
        boolean requirePrefix, 
        NodeNameGenerator defaultNng) 
{
    if(SlingbucksConstants.ORDERS_PATH.equals(parentPath)) {
        final StringBuilder name = new StringBuilder();
        for(int i=0; i < 2; i++) {
            name.append(Long.toHexString(random.nextLong()));
        }
        log.debug("Called for {} parent path, node name is {}", parentPath, name.toString());
        return name.toString();
    }
    log.debug("Path does not match {}, doing nothing", SlingbucksConstants.ORDERS_PATH);
    return null;
}
 
Example 12
@SuppressWarnings("unchecked")
private Map<String, String> createOptionMap(SlingHttpServletRequest request) {
    Map<String, String[]> parameterMap = request.getParameterMap();
    String[] selectors = request.getRequestPathInfo().getSelectors();
    Map<String, String> result = new HashMap<String, String>(baseOptions.size() + parameterMap.size() + selectors.length - 1);
    result.putAll(baseOptions);
    for (String selector : selectors) {
        if (!selector.equals(registeredSelector)) {
            result.put(selector, "true");
        }
    }

    for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
        if (entry.getValue().length == 0) {
            result.put(entry.getKey(), Boolean.TRUE.toString());
        } else {
            result.put(entry.getKey(), entry.getValue()[0]);
        }
    }
    return result;
}
 
Example 13
private boolean doStep(Map<String, Object> properties, SlingHttpServletRequest request) {
    Iterator<String> it = properties.keySet().iterator();
    while (it.hasNext()) {
        String key = it.next();
        switch (key) {
        case TransformationConstants.PATHS:
            String value = (String) properties.get(key);
            if (!request.getRequestURI().matches(value)) {
                return false;
            }
            break;
        case TransformationConstants.EXTENSIONS:
            String extension = (String) properties.get(key);
            if (!request.getRequestURI().endsWith(extension)) {
                return false;
            }
            break;
        default:
        }

    }
    return true;
}
 
Example 14
private String getUrl(Configuration config, SlingHttpServletRequest request) {
    String url = buildUrl(config, request);
    if (config.isRewritePath()) {
        url = removeQuestionMark(url);
        url = request.getResourceResolver().map(request, url);
    } else {
        url = encodeJcrContentPart(url);
        try {
            url = new URI(null, null, url, null).toASCIIString();
        } catch (URISyntaxException e) {
            LOG.error("Include url is in the wrong format", e);
            return null;
        }
    }

    return url;
}
 
Example 15
Source Project: sling-samples   Source File: LinkOperation.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doRun(SlingHttpServletRequest request,
        HtmlResponse response, List<Modification> changes)
        throws RepositoryException {

    Session session = request.getResourceResolver().adaptTo(Session.class);
    String resourcePath = request.getResource().getPath();
    if (session.itemExists(resourcePath)) {
        Node source = (Node) session.getItem(resourcePath);

        // create a symetric link
        RequestParameter linkParam = request.getRequestParameter("target");
        if (linkParam != null) {
            String linkPath = linkParam.getString();
            if (session.itemExists(linkPath)) {
                Item targetItem = session.getItem(linkPath);
                if (targetItem.isNode()) {
                    linkHelper.createSymetricLink(source,
                        (Node) targetItem, "link");
                }
            }
        }
    }

}
 
Example 16
@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 17
/**
 * Searches for the {@link #PN_CATALOG_PATH} property of the current site using algorithms specific to pickers.
 *
 * @param request the current {@code SlingHttpServletRequest}
 *
 * @return the value of the {@link #PN_CATALOG_PATH} property or or {@code null} if not found
 */
public String findCatalogPathForPicker(SlingHttpServletRequest request) {
    String requestURI = request.getRequestURI();
    if (requestURI.contains(COMPONENT_DIALOG_URI_MARKER)) {
        String suffix = request.getRequestPathInfo().getSuffix();
        return findCatalogPath(suffix);
    } else if (requestURI.contains(PAGE_PROPERTIES_URI_MARKER)) {
        String item = request.getParameter("item");
        return findCatalogPath(item);
    }

    return null;
}
 
Example 18
Source Project: sling-whiteboard   Source File: EncryptPostProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void process(SlingHttpServletRequest slingRequest, List<Modification> modifications) throws Exception {

    Set<Modification> mods = modifications.stream()
            .filter(modification -> modification.getSource().endsWith(config.suffix())).collect(Collectors.toSet());

    if (mods.isEmpty()) {
        return;
    }

    ResourceResolver resolver = slingRequest.getResourceResolver();
    Session session = resolver.adaptTo(Session.class);

    for (Modification mod : mods) {
        String encryptPropertyPath = mod.getSource();

        String propertyPath = encryptPropertyPath.substring(0, encryptPropertyPath.lastIndexOf(config.suffix()));
        String resourcePath = propertyPath.substring(0, propertyPath.lastIndexOf('/'));

        if (config.inline()) {
            session.move(encryptPropertyPath, propertyPath);
        }

        EncryptableValueMap map = resolver.resolve(resourcePath).adaptTo(EncryptableValueMap.class);
        map.encrypt(propertyPath.substring(resourcePath.length() + 1, propertyPath.length()));
        session.removeItem(encryptPropertyPath);
    }

    modifications.removeAll(mods);

    mods.forEach(mod -> {
        logger.debug("removed {} for source {}", mod.getType() , mod.getSource());
    });
}
 
Example 19
Source Project: AEM-Rules-for-SonarQube   Source File: SampleServlet.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
    throws ServletException, IOException {
    ResourceResolver resourceResolver = null;
    resourceResolver = request.getResourceResolver();
    // do sth
}
 
Example 20
/**
 * Finds the {@code cq:catalogPath} property at the given path and exposes its value in the property
 * {@link #CATALOG_PATH_PROPERTY} to Granite UI expressions.
 *
 * @param path a Sling resource path
 * @param request the current request
 */
static void prepareCatalogPathProperty(String path, SlingHttpServletRequest request) {
    ResourceResolver resourceResolver = request.getResourceResolver();
    CatalogSearchSupport catalogSearchSupport = new CatalogSearchSupport(resourceResolver);
    String catalogPath = catalogSearchSupport.findCatalogPath(path);
    if (StringUtils.isBlank(catalogPath)) {
        CommerceBasePathsService pathsService = resourceResolver.adaptTo(CommerceBasePathsService.class);
        catalogPath = pathsService.getProductsBasePath();
    }
    ExpressionCustomizer customizer = ExpressionCustomizer.from(request);
    customizer.setVariable(CATALOG_PATH_PROPERTY, catalogPath);
}
 
Example 21
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 22
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 23
@Before
public void before() {
    servlet = new IsProductListPageServlet();
    request = mock(SlingHttpServletRequest.class);
    response = mock(SlingHttpServletResponse.class);

    SlingBindings slingBindings = mock(SlingBindings.class);
    Map<String, Object> requestAttributes = new HashMap<>();
    doAnswer(invocation -> requestAttributes.put((String) invocation.getArguments()[0], invocation.getArguments()[1])).when(request)
        .setAttribute(anyString(), anyObject());
    when(request.getAttribute(anyString())).thenAnswer(invocationOnMock -> requestAttributes.get(invocationOnMock.getArguments()[0]));
    requestAttributes.put(SlingBindings.class.getName(), slingBindings);
    SlingScriptHelper slingScriptHelper = mock(SlingScriptHelper.class);
    when(slingBindings.getSling()).thenReturn(slingScriptHelper);
    ExpressionResolver expressionResolver = mock(ExpressionResolver.class);
    when(slingScriptHelper.getService(ExpressionResolver.class)).thenReturn(expressionResolver);

    Resource resource = mock(Resource.class);
    when(request.getResource()).thenReturn(resource);
    resourceProperties = new ModifiableMappedValueMapDecorator(new HashMap<>());
    when(resource.getValueMap()).thenReturn(resourceProperties);
    ResourceResolver resourceResolver = spy(context.resourceResolver());
    when(request.getResourceResolver()).thenReturn(resourceResolver);
    CommerceBasePathsService pathsService = mock(CommerceBasePathsService.class);
    when(pathsService.getProductsBasePath()).thenReturn("/var/commerce/products");
    when(resourceResolver.adaptTo(CommerceBasePathsService.class)).thenReturn(pathsService);

    when(expressionResolver.resolve(anyString(), (Locale) anyObject(), (Class<? extends Object>) anyObject(),
        (SlingHttpServletRequest) anyObject())).thenAnswer((Answer<Object>) invocation -> long.class.equals(invocation
            .getArguments()[2]) ? Long.valueOf((String) invocation.getArguments()[0]) : invocation.getArguments()[0]);

    when(resource.getPath()).thenAnswer(invocationOnMock -> resourceProperties.get("path"));
}
 
Example 24
@Before
public void setUp() {
    context.load().json("/context/jcr-conf-console.json", "/conf");

    ExpressionResolver expressionResolver = Mockito.mock(ExpressionResolver.class);
    Mockito.when(expressionResolver.resolve(Mockito.any(String.class), Mockito.any(Locale.class), Mockito.any(Class.class), Mockito.any(
        SlingHttpServletRequest.class))).thenReturn(CONFIGURATION_PATH);

    context.registerService(ExpressionResolver.class, expressionResolver);
    context.addModelsForClasses(ConfigurationColumnPreview.class);

    Map<String, Object> columnPreviewProps = ImmutableMap.of("sling:resourceType",
        "commerce/gui/components/configuration/columnpreview", "path", CONFIGURATION_PATH);
    columnPreviewDef = context.create().resource("/libs/something/columnpreview", columnPreviewProps);
}
 
Example 25
@Before
public void setUp() {
    SlingScriptHelper sling = mock(SlingScriptHelper.class);
    bindings.put(SlingBindings.SLING, sling);
    ExpressionResolver expressionResolver = mock(ExpressionResolver.class);
    when(expressionResolver.resolve(anyString(), any(), any(), (SlingHttpServletRequest) any())).thenAnswer(
        invocationOnMock -> invocationOnMock.getArguments()[0]);
    when(sling.getService(ExpressionResolver.class)).thenReturn(expressionResolver);
    CommerceBasePathsService pathService = mock(CommerceBasePathsService.class);
    when(pathService.getProductsBasePath()).thenReturn(PRODUCTS_BASE_PATH);
    when(sling.getService(CommerceBasePathsService.class)).thenReturn(pathService);
    doAnswer(invocationOnMock -> {
        includedResourceSample = (Resource) invocationOnMock.getArguments()[0];
        return null;
    }).when(sling).include(any(Resource.class));
    request = mock(SlingHttpServletRequest.class);
    when(request.getRequestURI()).thenReturn("some_request_uri");
    bindings.put(SlingBindings.REQUEST, request);
    requestPathInfo = mock(RequestPathInfo.class);
    when(request.getRequestPathInfo()).thenReturn(requestPathInfo);
    valueMap = new ModifiableValueMapDecorator(new HashMap<>());
    bindings.put(WCMBindingsConstants.NAME_PROPERTIES, valueMap);

    ResourceResolver resourceResolver = mock(ResourceResolver.class);
    when(request.getResourceResolver()).thenReturn(resourceResolver);
    PageManager pageManager = mock(PageManager.class);
    when(resourceResolver.adaptTo(PageManager.class)).thenReturn(pageManager);
    Page page = mock(Page.class);
    when(pageManager.getContainingPage(anyString())).thenReturn(page);
    contentResource = mock(Resource.class);
    contentResourceProperties = new ModifiableValueMapDecorator(new HashMap<>());
    when(contentResource.getValueMap()).thenReturn(contentResourceProperties);
    when(page.getContentResource()).thenReturn(contentResource);
}
 
Example 26
Source Project: APM   Source File: HistoryDatasourceServlet.java    License: Apache License 2.0 5 votes vote down vote up
private Pagination createPagination(SlingHttpServletRequest request) {
  String[] selectors = request.getRequestPathInfo().getSelectors();
  if (selectors == null || selectors.length < 2) {
    return new Pagination(0, DEFAULT_LIMIT + 1);
  } else {
    Integer offset = Ints.tryParse(selectors[0]);
    Integer limit = Ints.tryParse(selectors[1]);
    return new Pagination(offset, limit + 1);
  }
}
 
Example 27
Source Project: publick-sling-blog   Source File: PackageServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a JCR package and store it under /etc/packages/group_name/package_name-version.zip.
 * {@link org.apache.sling.distribution.serialization.impl.vlt.JcrVaultDistributionPackageBuilder#createPackageForAdd}
 *
 * @param request The Sling HTTP servlet request
 * @param groupName The name of the package group
 * @param packageName The name of the package
 * @param version The version of the package
 * @param paths The JCR paths to include in the package
 * @return true  the saved JCR Package
 */
public JcrPackage createPackage(final SlingHttpServletRequest request, final String groupName,
        final String packageName, final String version, final String[] paths) {

    Session session = null;
    VaultPackage vaultPackage = null;
    JcrPackage savedPackage = null;

    File tempDirectory = VltUtils.getTempFolder(settingsService.getTemporaryDirectory());

    try {
        session = request.getResourceResolver().adaptTo(Session.class);

        WorkspaceFilter filter = VltUtils.createFilter(paths, true);
        ExportOptions opts = VltUtils.getExportOptions(filter, paths, groupName, packageName, version);

        vaultPackage = VltUtils.createPackage(packaging.getPackageManager(), session, opts, tempDirectory);

        savedPackage = uploadPackage(session, vaultPackage);

        session.save();
    } catch (Exception e) {
        VltUtils.deletePackage(vaultPackage);
    }

    return savedPackage;
}
 
Example 28
Source Project: aem-solr-search   Source File: SolrUpdateHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");

    Resource page = request.getResource();
    GeometrixxMediaContentType contentType = page.adaptTo(GeometrixxMediaPage.class);

    response.getWriter().write(contentType.getJson().toJSONString());
}
 
Example 29
/**
 * Extracts a list of products suitable for Sling Model consumption from the graphql response.
 *
 * @param products a {@link List<ProductInterface>} object
 * @param request
 * @return a list of {@link ProductListItem} objects
 */
@Nonnull
private List<ProductListItem> extractProductsFromResponse(List<ProductInterface> products, Page productPage,
    final SlingHttpServletRequest request) {

    LOGGER.debug("Found {} products for search term", products.size());

    ProductToProductListItemConverter converter = new ProductToProductListItemConverter(productPage, request, urlProvider);

    return products.stream()
        .map(converter)
        .filter(Objects::nonNull) // the converter returns null if the conversion fails
        .collect(Collectors.toList());
}
 
Example 30
Source Project: APM   Source File: ScriptRemoveServlet.java    License: Apache License 2.0 5 votes vote down vote up
@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");
	}
}