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

The following java examples will help you to understand the usage of org.apache.sling.api.SlingHttpServletRequest. These source code samples are taken from different open source projects.

Example 1
Project: aem-id-googlesearch-master  File: Functions.java View source code
public static String Translate(Page currentPage, SlingHttpServletRequest slingRequest, String value) {
    if (!"".equals(value)) {
        Locale pageLocale = currentPage.getLanguage(false);
        //Locale myLocale = new Locale("fr");  
        ResourceBundle resourceBundle = slingRequest.getResourceBundle(pageLocale);
        I18n i18n = new I18n(resourceBundle);
        //			I18n i18n = new I18n(slingRequest);
        return i18n.get(value);
    //return i18n.get(value);
    }
    return "";
}
Example 2
Project: sling-master  File: ContentDispositionFilterTest.java View source code
@Test
public void test_doFilter1() throws Throwable {
    final SlingHttpServletRequest request = context.mock(SlingHttpServletRequest.class);
    final SlingHttpServletResponse response = context.mock(SlingHttpServletResponse.class);
    final Resource resource = context.mock(Resource.class, "resource");
    callActivateWithConfiguration(new String[] { "/content/usergenerated" }, new String[] { "" });
    context.checking(new Expectations() {

        {
            allowing(request).getMethod();
            will(returnValue("GET"));
            allowing(request).getAttribute(RewriterResponse.ATTRIBUTE_NAME);
            will(returnValue(null));
            allowing(request).setAttribute(RewriterResponse.ATTRIBUTE_NAME, "text/html");
            allowing(request).getResource();
            will(returnValue(resource));
            allowing(resource).getPath();
            will(returnValue("/libs"));
            allowing(response).setContentType("text/html");
            //CONTENT DISPOSITION MUST NOT SET
            never(response).addHeader("Content-Disposition", "attachment");
        }
    });
    ContentDispositionFilter.RewriterResponse rewriterResponse = contentDispositionFilter.new RewriterResponse(request, response);
    rewriterResponse.setContentType("text/html");
}
Example 3
Project: com.activecq.samples-master  File: GQLToQueryBuilderConverter.java View source code
public static Map<String, String> addOrder(final SlingHttpServletRequest request, Map<String, String> map, final String queryString) {
    if (has(request, CF_ORDER)) {
        int count = 1;
        for (String value : getAll(request, CF_ORDER)) {
            value = StringUtils.trim(value);
            final String orderGroupId = String.valueOf(GROUP_ORDERBY_USERDEFINED + count) + "_group";
            boolean sortAsc = false;
            if (StringUtils.startsWith(value, "-")) {
                sortAsc = false;
                value = StringUtils.removeStart(value, "-");
            } else if (StringUtils.startsWith(value, "+")) {
                sortAsc = true;
                value = StringUtils.removeStart(value, "+");
            }
            // 20000_orderby : jcr:title
            // 20000_orderby.sort : ASC
            map.put(orderGroupId, StringUtils.trim(value));
            map.put(orderGroupId + ".sort", sortAsc ? Predicate.SORT_ASCENDING : Predicate.SORT_DESCENDING);
            count++;
        }
    } else {
        final boolean isPage = isPage(get(request, CF_TYPE));
        final boolean isAsset = isAsset(get(request, CF_TYPE));
        final String prefix = getPropertyPrefix(request);
        if (StringUtils.isNotBlank(queryString)) {
            map.put(GROUP_ORDERBY_SCORE + "_orderby", "@" + JcrConstants.JCR_SCORE);
            map.put(GROUP_ORDERBY_SCORE + "_orderby.sort", Predicate.SORT_DESCENDING);
        }
        String modifiedOrderProperty = "@" + JcrConstants.JCR_LASTMODIFIED;
        if (isPage) {
            modifiedOrderProperty = "@" + prefix + NameConstants.PN_PAGE_LAST_MOD;
        } else if (isAsset) {
            modifiedOrderProperty = "@" + prefix + JcrConstants.JCR_LASTMODIFIED;
        }
        map.put(GROUP_ORDERBY_MODIFIED + "_orderby", modifiedOrderProperty);
        map.put(GROUP_ORDERBY_MODIFIED + "_orderby.sort", Predicate.SORT_DESCENDING);
    }
    return map;
}
Example 4
Project: 2014-sling-rookie-session-master  File: JcrReadSample.java View source code
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
    Session session = request.getResourceResolver().adaptTo(Session.class);
    try {
        String jcrContent = readJcrContent(session);
        response.setContentType("text/plain;charset=UTF-8");
        response.getWriter().write(jcrContent);
    } catch (RepositoryException ex) {
        throw new ServletException(ex);
    }
}
Example 5
Project: acs-aem-commons-master  File: ErrorPageHandlerImpl.java View source code
/**
     * Find the JCR full path to the most appropriate Error Page.
     *
     * @param request
     * @param errorResource
     * @return
     */
public String findErrorPage(SlingHttpServletRequest request, Resource errorResource) {
    if (!isEnabled()) {
        return null;
    }
    final String errorsPath = findErrorsPath(request, errorResource);
    Resource errorPage = null;
    if (StringUtils.isNotBlank(errorsPath)) {
        final ResourceResolver resourceResolver = errorResource.getResourceResolver();
        final String errorPath = errorsPath + "/" + getErrorPageName(request);
        errorPage = getResource(resourceResolver, errorPath);
        if (errorPage == null && StringUtils.isNotBlank(errorsPath)) {
            log.trace("No error-specific errorPage could be found, use the 'default' error errorPage for the Root content path");
            errorPage = resourceResolver.resolve(errorsPath);
        }
    }
    String errorPagePath = null;
    if (errorPage == null || ResourceUtil.isNonExistingResource(errorPage)) {
        log.trace("no custom error page could be found");
        if (this.hasSystemErrorPage()) {
            errorPagePath = this.getSystemErrorPagePath();
            log.trace("using system error page [ {} ]", errorPagePath);
        }
    } else {
        errorPagePath = errorPage.getPath();
    }
    if (errorImagesEnabled && this.isImageRequest(request)) {
        if (StringUtils.startsWith(this.errorImagePath, "/")) {
            // Absolute path
            return this.errorImagePath;
        } else if (StringUtils.isNotBlank(errorPagePath)) {
            if (StringUtils.startsWith(this.errorImagePath, ".")) {
                final String selectorErrorImagePath = errorPagePath + this.errorImagePath;
                log.debug("Using selector-based error image: {}", selectorErrorImagePath);
                return selectorErrorImagePath;
            } else {
                final String relativeErrorImagePath = errorPagePath + "/" + StringUtils.removeStart(this.errorImagePath, "/");
                log.debug("Using relative path-based error image: {}", relativeErrorImagePath);
                return relativeErrorImagePath;
            }
        } else {
            log.warn("Error image path found, but no error page could be found so relative path cannot " + "be applied: {}", this.errorImagePath);
        }
    } else if (StringUtils.isNotBlank(errorPagePath)) {
        errorPagePath = StringUtils.stripToNull(applyExtension(errorPagePath));
        log.debug("Using resolved error page: {}", errorPagePath);
        return errorPagePath;
    } else {
        log.debug("ACS AEM Commons Error Page Handler is enabled but mis-configured. A valid error image" + " handler nor a valid error page could be found.");
    }
    return null;
}
Example 6
Project: neba-master  File: RequestScopedResourceModelCache.java View source code
/**
     * Returns the key for a cacheHolder. If the key changes, the cacheHolder will be cleared.
     * The key consists of:
     * <ul><li>The current resources page</li>
     * <li>the selector string</li>
     * <li>the extension</li>
     * <li>the suffix</li>
     * <li>the query string</li>
     * </ul>
     */
private static Key toKey(SlingHttpServletRequest request) {
    final RequestPathInfo requestPathInfo = request.getRequestPathInfo();
    return new Key(StringUtils.substringBefore(requestPathInfo.getResourcePath(), "/jcr:content"), requestPathInfo.getSelectorString(), requestPathInfo.getExtension(), requestPathInfo.getSuffix(), request.getQueryString());
}
Example 7
Project: Sling-Dynamic-Include-master  File: IncludeTagWritingFilter.java View source code
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request;
    final String resourceType = slingRequest.getResource().getResourceType();
    final Configuration config = configurationWhiteboard.getConfiguration(slingRequest, resourceType);
    if (config == null) {
        chain.doFilter(request, response);
        return;
    }
    final IncludeGenerator generator = generatorWhiteboard.getGenerator(config.getIncludeTypeName());
    if (generator == null) {
        LOG.error("Invalid generator: " + config.getIncludeTypeName());
        chain.doFilter(request, response);
        return;
    }
    final PrintWriter writer = response.getWriter();
    final String url = getUrl(config, slingRequest);
    if (url == null) {
        chain.doFilter(request, response);
        return;
    }
    if (config.getAddComment()) {
        writer.append(String.format(COMMENT, StringEscapeUtils.escapeHtml(url), resourceType));
    }
    // Only write the includes markup if the required, configurable request header is present
    if (shouldWriteIncludes(config, slingRequest)) {
        String include = generator.getInclude(url);
        LOG.debug(include);
        writer.append(include);
    } else {
        chain.doFilter(request, response);
    }
}
Example 8
Project: acs-aem-tools-master  File: CsvAssetImporterServlet.java View source code
@Override
protected final void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws IOException {
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    final JSONObject jsonResponse = new JSONObject();
    final Parameters params = new Parameters(request);
    if (params.getFile() != null) {
        final long start = System.currentTimeMillis();
        final Iterator<String[]> rows = this.getRowsFromCsv(params);
        try {
            // First row is property names
            // Get the required properties for this tool (source and dest)
            final String[] requiredProperties = new String[] { //params.getRelSrcPathProperty(),
            params.getAbsTargetPathProperty() };
            // Get the columns from the first row of the CSV
            final Map<String, Column> columns = Column.getColumns(rows.next(), params.getMultiDelimiter(), params.getIgnoreProperties(), requiredProperties);
            // Process Asset row entries
            final List<String> result = new ArrayList<String>();
            final List<String> batch = new ArrayList<String>();
            final List<String> failures = new ArrayList<String>();
            log.info(params.toString());
            request.getResourceResolver().adaptTo(Session.class).getWorkspace().getObservationManager().setUserData("acs-aem-tools.csv-asset-importer");
            while (rows.hasNext()) {
                final String[] row = rows.next();
                log.debug("Processing row {}", Arrays.asList(row));
                try {
                    if (!this.isSkippedRow(params, columns, row)) {
                        batch.add(this.importAsset(request.getResourceResolver(), params, columns, row));
                    }
                } catch (FileNotFoundException e) {
                    failures.add(row[columns.get(params.getAbsTargetPathProperty()).getIndex()]);
                    log.error("Could not find file for row ", Arrays.asList(row), e);
                } catch (CsvAssetImportException e) {
                    failures.add(row[columns.get(params.getAbsTargetPathProperty()).getIndex()]);
                    log.error("Could not import the row due to ", e.getMessage(), e);
                }
                log.debug("Processed row {}", Arrays.asList(row));
                if (batch.size() % params.getBatchSize() == 0) {
                    this.save(request.getResourceResolver(), batch.size());
                    result.addAll(batch);
                    batch.clear();
                    // Throttle saves
                    if (params.getThrottle() > 0) {
                        log.info("Throttling CSV Asset Importer batch processing for {} ms", params.getThrottle());
                        Thread.sleep(params.getThrottle());
                    }
                }
            }
            // Final save to catch any non-modulo stragglers; will only invoke persist if there are changes
            this.save(request.getResourceResolver(), batch.size());
            result.addAll(batch);
            if (log.isInfoEnabled()) {
                log.info("Imported as TOTAL of [ {} ] assets in {} ms", result.size(), System.currentTimeMillis() - start);
            }
            try {
                jsonResponse.put("assets", result);
                jsonResponse.put("failures", failures);
            } catch (JSONException e) {
                log.error("Could not serialized Excel Importer results into JSON", e);
                this.addMessage(jsonResponse, "Could not serialized Excel Importer results into JSON");
                response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (RepositoryException e) {
            log.error("Could not save Assets to JCR", e);
            this.addMessage(jsonResponse, "Could not save assets. " + e.getMessage());
            response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (Exception e) {
            log.error("Could not process CSV import", e);
            this.addMessage(jsonResponse, "Could not process CSV import. " + e.getMessage());
            response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } else {
        log.error("Could not find CSV file in request.");
        this.addMessage(jsonResponse, "CSV file is missing");
        response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    response.getWriter().print(jsonResponse.toString());
}
Example 9
Project: Adobe-CQ5-Brightcove-Connector-master  File: ServiceUtil.java View source code
public static Cookie getAccountCookie(SlingHttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    Map<String, Cookie> cookiesMap = new TreeMap<String, Cookie>();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            cookiesMap.put(cookies[i].getName(), cookies[i]);
        }
        ;
    }
    return cookiesMap.get("brc_act");
}
Example 10
Project: aem-samples-master  File: ReferencedAssetsServlet.java View source code
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
    response.setContentType("application/json");
    try {
        JSONObject jsonOut = new JSONObject();
        Node jcrNode = request.getResource().adaptTo(Node.class);
        if (jcrNode == null) {
            // every adaptTo() can return null, so let's handle that case here 
            // although it's very unlikely
            LOG.error("cannot adapt resource {} to a node", request.getResource().getPath());
            response.getOutputStream().print(new JSONObject().toString());
            return;
        }
        // let's use the specialized assetReferenceSearch, which does all the work for us
        AssetReferenceSearch search = new AssetReferenceSearch(jcrNode, DAM_ROOT, request.getResourceResolver());
        Map<String, Asset> result = search.search();
        for (String key : result.keySet()) {
            Asset asset = result.get(key);
            JSONObject assetDetails = new JSONObject();
            assetDetails.put("path", asset.getPath());
            assetDetails.put("mimetype", asset.getMimeType());
            jsonOut.put(asset.getName(), assetDetails);
        }
        response.getOutputStream().print(jsonOut.toString(2));
    } catch (JSONException e) {
        LOG.error("Cannot serialize JSON", e);
        response.getOutputStream().print(new JSONObject().toString());
    }
}
Example 11
Project: sling-metrics-master  File: ComponentFilter.java View source code
@Override
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
    LOG.debug("ComponentFilter doFilter()");
    if (isEnabled && metricService.isEnabled()) {
        if (servletRequest instanceof SlingHttpServletRequest) {
            final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) servletRequest;
            final String resourceType = slingRequest.getResource().getResourceType();
            final String metricName = normalizeResourceType(resourceType);
            if (metricName.matches(whitelist)) {
                final Timer.Context context = metricService.timer(metricName).time();
                try {
                    filterChain.doFilter(servletRequest, servletResponse);
                } finally {
                    context.stop();
                }
            }
        } else {
            LOG.error("Metrics ComponentFilter got called for non SlingHttpServletRequest");
        }
    }
}
Example 12
Project: wcm-io-wcm-master  File: CacheHeader.java View source code
/**
   * Compares the "If-Modified-Since header" of the incoming request with the last modification date of an aggregated
   * resource. If the resource was not modified since the client retrieved the resource, a 304-redirect is send to the
   * response (and the method returns true). If the resource has changed (or the client didn't) supply the
   * "If-Modified-Since" header a "Last-Modified" header is set so future requests can be cached.
   * @param dateProvider abstraction layer that calculates the last-modification time of an aggregated resource
   * @param request Request
   * @param response Response
   * @param setExpiresHeader Set expires header to -1 to ensure the browser checks for a new version on every request.
   * @return true if the method send a 304 redirect, so that the caller shouldn't write any output to the response
   *         stream
   * @throws IOException I/O exception
   */
public static boolean isNotModified(ModificationDateProvider dateProvider, SlingHttpServletRequest request, SlingHttpServletResponse response, boolean setExpiresHeader) throws IOException {
    // assume the resource *was* modified until we know better
    boolean isModified = true;
    // get the modification date of the resource(s) in question
    Date lastModificationDate = dateProvider.getModificationDate();
    // get the date of the version from the client's cache
    String ifModifiedSince = request.getHeader(HEADER_IF_MODIFIED_SINCE);
    // only compare if both resource modification date and If-Modified-Since header is available
    if (lastModificationDate != null && StringUtils.isNotBlank(ifModifiedSince)) {
        try {
            Date clientModificationDate = parseDate(ifModifiedSince);
            // resource is considered modified if it's modification date is *after* the client's modification date
            isModified = lastModificationDate.getTime() - DateUtils.MILLIS_PER_SECOND > clientModificationDate.getTime();
        } catch (ParseException ex) {
            log.warn("Failed to parse value '" + ifModifiedSince + "' of If-Modified-Since header.", ex);
        }
    }
    // if resource wasn't modified: send a 304 and return true so the caller knows it shouldn't go on writing the response
    if (!isModified) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return true;
    }
    // set last modified header so future requests can be cached
    if (lastModificationDate != null) {
        response.setHeader(HEADER_LAST_MODIFIED, formatDate(lastModificationDate));
        if (setExpiresHeader) {
            // by setting an expires header we force the browser to always check for updated versions (only on author)
            response.setHeader(HEADER_EXPIRES, "-1");
        }
    }
    // tell the caller it should go on writing the response as no 304-header was send
    return false;
}
Example 13
Project: Component-Bindings-Provider-master  File: CQVariablesServiceImpl.java View source code
/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.sixdimensions.wcm.cq.component.bindings.CQVariablesService#getVariables
	 * (javax.script.Bindings)
	 */
@Override
public CQVariables getVariables(Bindings bindings) {
    CQVariablesImpl variables = new CQVariablesImpl();
    // Add all of the sling bindings
    SlingHttpServletRequest request = (SlingHttpServletRequest) bindings.get("request");
    variables.putAll(bindings);
    // Add all of the CQ stuff
    Resource resource = request.getResource();
    ResourceResolver resolver = request.getResourceResolver();
    XSSAPI xssAPI = xssApi.getRequestSpecificAPI(request);
    ComponentContext componentContext = WCMUtils.getComponentContext(request);
    EditContext editContext = componentContext != null ? componentContext.getEditContext() : null;
    ValueMap properties = ResourceUtil.getValueMap(resource);
    PageManager pageManager = (PageManager) resolver.adaptTo(PageManager.class);
    ValueMap pageProperties = null;
    Page currentPage = null;
    Page resourcePage = null;
    if (pageManager != null) {
        resourcePage = pageManager.getContainingPage(resource);
        currentPage = componentContext != null ? componentContext.getPage() : null;
        if (currentPage == null) {
            currentPage = resourcePage;
        }
        if (currentPage == null) {
            pageProperties = null;
        } else {
            pageProperties = new HierarchyNodeInheritanceValueMap(currentPage.getContentResource());
        }
    }
    com.day.cq.wcm.api.components.Component component = WCMUtils.getComponent(resource);
    Designer designer = (Designer) request.getResourceResolver().adaptTo(Designer.class);
    if (designer != null) {
        Design currentDesign;
        if (currentPage == null) {
            currentDesign = null;
        } else {
            String currentDesignKey = REQ_ATTR_PREFIX + currentPage.getPath();
            Object cachedCurrentDesign = request.getAttribute(currentDesignKey);
            if (cachedCurrentDesign != null) {
                currentDesign = (Design) cachedCurrentDesign;
            } else {
                currentDesign = designer.getDesign(currentPage);
                request.setAttribute(currentDesignKey, currentDesign);
            }
        }
        Design resourceDesign;
        if (resourcePage == null) {
            resourceDesign = null;
        } else {
            String resourceDesignkey = REQ_ATTR_PREFIX + resourcePage.getPath();
            Object cachedresourceDesign = request.getAttribute(resourceDesignkey);
            if (cachedresourceDesign != null) {
                resourceDesign = (Design) cachedresourceDesign;
            } else {
                resourceDesign = designer.getDesign(resourcePage);
                request.setAttribute(resourceDesignkey, resourceDesign);
            }
        }
        Style currentStyle = currentDesign != null && componentContext != null ? currentDesign.getStyle(componentContext.getCell()) : null;
        variables.put(CQVariables.DESIGNER, designer);
        variables.put(CQVariables.CURRENT_DESIGN, currentDesign);
        variables.put(CQVariables.RESOURCE_DESIGN, resourceDesign);
        variables.put(CQVariables.CURRENT_STYLE, currentStyle);
    }
    variables.put(CQVariables.XSS_API, xssAPI);
    variables.put(CQVariables.COMPONENT_CONTEXT, componentContext);
    variables.put(CQVariables.EDIT_CONTEXT, editContext);
    variables.put(CQVariables.PROPERTIES, properties);
    variables.put(CQVariables.PAGE_MANAGER, pageManager);
    variables.put(CQVariables.CURRENT_PAGE, currentPage);
    variables.put(CQVariables.RESOURCE_PAGE, resourcePage);
    variables.put(CQVariables.PAGE_PROPERTIES, pageProperties);
    variables.put(CQVariables.COMPONENT, component);
    variables.put(CQVariables.SESSION, resource.getResourceResolver().adaptTo(Session.class));
    return variables;
}
Example 14
Project: CQ-Actions-master  File: PushServlet.java View source code
public void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
    if (!authenticate(request, response)) {
        return;
    }
    response.setContentType("text/plain; charset=utf-8");
    synchronized (connectionHold) {
        connectionHold.notifyAll();
    }
    synchronized (this) {
        writer = response.getWriter();
    }
    try {
        synchronized (connectionHold) {
            connectionHold.wait();
        }
    } catch (InterruptedException e) {
        throw new ServletException("Interrupted", e);
    }
}
Example 15
Project: cq5-healthcheck-master  File: RequestFilter.java View source code
// implementation
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    RequestInformationImpl rii = null;
    if (!shutdownInProgress) {
        SlingHttpServletRequest req = (SlingHttpServletRequest) request;
        Resource r = req.getResource();
        String contentType = req.getResponseContentType();
        Page p = r.adaptTo(Page.class);
        String templatePath = "";
        if (p != null && p.getTemplate() != null) {
            templatePath = p.getTemplate().getPath();
        } else {
        // not a page or no template specified
        }
        // If there is no service defined for this mime type yet, we
        // register it
        String designator = buildMBeanName(contentType, templatePath);
        if (!services.containsKey(designator)) {
            registerReportingService(designator, contentType);
        }
        // TODO cache service objects for performance???
        ServiceRegistration reg = services.get(designator);
        Object o = bundleContext.getService(reg.getReference());
        if (o instanceof RequestInformationImpl) {
            rii = (RequestInformationImpl) o;
        } else {
            log.error("Something went wrong with the retrieval of the service object for meban " + designator);
            rii = null;
        }
    }
    // forward the request down the chain and collect timing information
    long t1 = System.currentTimeMillis();
    chain.doFilter(request, response);
    long t2 = System.currentTimeMillis();
    if (!shutdownInProgress && rii != null) {
        rii.update(t2 - t1);
    }
}
Example 16
Project: ease-master  File: QueryServlet.java View source code
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
    String q = request.getParameter("q");
    if (q == null || q.trim().length() == 0) {
        q = "*:*";
    }
    try {
        SolrQuery query = new SolrQuery(q);
        query.addFacetField(IndexFields.LANGUAGE, IndexFields.TAGS);
        query.setFacetMinCount(1);
        query.setRows(Integer.MAX_VALUE);
        query.setFields(IndexFields.PATH, IndexFields.TITLE, "score");
        long time = System.currentTimeMillis();
        QueryResponse result = new HttpSolrServer(url).query(query);
        time = System.currentTimeMillis() - time;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        JSONWriter json = new JSONWriter(response.getWriter());
        json.object();
        json.key("time").value(time);
        json.key("total").value(result.getResults().getNumFound());
        json.key("facets").object();
        for (FacetField facet : result.getFacetFields()) {
            if (facet.getValueCount() > 0) {
                json.key(facet.getName()).array();
                for (FacetField.Count value : facet.getValues()) {
                    json.object();
                    json.key("value").value(value.getName());
                    json.key("count").value(value.getCount());
                    json.endObject();
                }
                json.endArray();
            }
        }
        json.endObject();
        json.key("items").array();
        for (SolrDocument doc : result.getResults()) {
            json.object();
            json.key("path").value(doc.getFieldValue(IndexFields.PATH));
            json.key("title");
            Object titleValues = doc.getFieldValue(IndexFields.TITLE);
            String title = null;
            if (titleValues instanceof List) {
                title = ((List) titleValues).get(0).toString();
            } else if (titleValues != null) {
                title = titleValues.toString();
            }
            json.value(title != null && !title.isEmpty() ? title : doc.getFieldValue(IndexFields.PATH));
            json.key("score").value(doc.getFieldValue("score"));
            json.endObject();
        }
        json.endArray();
        json.endObject();
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().print(e.getMessage());
    }
}
Example 17
Project: Kaltura-OAE-master  File: KalturaServlet.java View source code
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json");
    boolean full = false;
    if (request.getParameter("full") != null) {
        full = true;
    }
    LOG.info("GET: full=" + full);
    PrintWriter pw = response.getWriter();
    ExtendedJSONWriter jsonWriter = new ExtendedJSONWriter(pw);
    if (full) {
        User u = getUser(request, null);
        if (u == null) {
            // Die since we cannot get the current user
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Cannot get the current user!");
            return;
        }
        LOG.info("Current user=" + u.getId());
        Map<String, Object> m = new HashMap<String, Object>();
        m.put("id", u.getId());
        m.put("admin", u.isAdmin());
        try {
            jsonWriter.valueMap(m);
        } catch (JSONException e) {
            LOG.error(e.getMessage(), e);
        }
    } else {
        String userId = getCurrentUserId(request);
        if (userId == null || "".equals(userId)) {
            // Die since we cannot get the current user
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Cannot get the current user!");
            return;
        }
        LOG.info("Current userId=" + userId);
        //String requestedUserId = request.getParameter("uid");
        try {
            jsonWriter.object();
            jsonWriter.key("id");
            jsonWriter.value(userId);
            jsonWriter.endObject();
        } catch (JSONException e) {
            LOG.error(e.getMessage(), e);
        }
    }
}
Example 18
Project: cq-urlfilter-master  File: UrlFilter.java View source code
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (request instanceof SlingHttpServletRequest && response instanceof SlingHttpServletResponse) {
        SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request;
        SlingHttpServletResponse slingResponse = (SlingHttpServletResponse) response;
        RequestPathInfo pathInfo = slingRequest.getRequestPathInfo();
        Component definitionComponent = findUrlFilterDefinitionComponent(slingRequest.getResource(), slingRequest.getResourceResolver().adaptTo(ComponentManager.class));
        if (definitionComponent != null) {
            String definitionPath = definitionComponent.getPath();
            logger.debug("found url filter definition resource at {}", definitionPath);
            ValueMap properties = definitionComponent.getProperties();
            if (properties != null) {
                if (checkSelector(pathInfo, properties) && checkSuffix(pathInfo, properties) && checkExtension(pathInfo, properties)) {
                    logger.debug("url filter definition resource at {} passed for request {}.", definitionPath, slingRequest.getRequestPathInfo());
                } else {
                    logger.info("url filter definition resource at {} FAILED for request {}.", definitionPath, slingRequest.getRequestPathInfo());
                    slingResponse.sendError(403);
                    return;
                }
            }
        }
    }
    chain.doFilter(request, response);
}
Example 19
Project: sling-pipes-master  File: PlumberServletTest.java View source code
@Test
public void testWriteExecute() throws ServletException {
    SlingHttpServletRequest request = mockPlumberServletRequest(context.resourceResolver(), pipedWritePath, null, null, null, null);
    servlet.execute(request, response, true);
    String finalResponse = stringResponse.toString();
    assertFalse("There should be a response", StringUtils.isBlank(finalResponse));
}
Example 20
Project: wcm-io-cq5-master  File: AemObjectInjector.java View source code
@Override
public Object getValue(final Object adaptable, final String name, final Type type, final AnnotatedElement element, final DisposalCallbackRegistry callbackRegistry) {
    // only class types are supported
    if (!(type instanceof Class<?>)) {
        return null;
    }
    Class<?> requestedClass = (Class<?>) type;
    if (adaptable instanceof SlingHttpServletRequest) {
        SlingHttpServletRequest request = (SlingHttpServletRequest) adaptable;
        if (requestedClass.equals(WCMMode.class)) {
            return getWcmMode(request);
        }
        if (requestedClass.equals(ComponentContext.class)) {
            return getComponentContext(request);
        }
        if (requestedClass.equals(Style.class)) {
            return getStyle(request);
        }
        if (requestedClass.equals(XSSAPI.class)) {
            return getXssApi(request);
        }
    }
    if (requestedClass.equals(PageManager.class)) {
        return getPageManager(adaptable);
    } else if (requestedClass.equals(Page.class)) {
        if (StringUtils.equals(name, RESOURCE_PAGE)) {
            return getResourcePage(adaptable);
        } else {
            return getCurrentPage(adaptable);
        }
    } else if (requestedClass.equals(Designer.class)) {
        return getDesigner(adaptable);
    } else if (requestedClass.equals(Design.class)) {
        return getCurrentDesign(adaptable);
    }
    return null;
}
Example 21
Project: Slice-CQ55-master  File: IncludeTag.java View source code
/** {@inheritDoc} */
@Override
public int doEndTag() throws JspException {
    // we consider removing decoration only if we're including a component
    SlingHttpServletRequest request = getRequest();
    WCMMode wcmMode = WCMMode.fromRequest(request);
    ComponentConfiguration componentConfiguration = readComponentConfiguration(request);
    boolean decorationEnabled;
    if (this.enableDecoration == null) {
        decorationEnabled = isDecorationEnabled(componentConfiguration.getDecorationModes(), wcmMode);
    } else {
        decorationEnabled = this.enableDecoration;
    }
    IncludeOptions options = IncludeOptions.getOptions(request, true);
    if (!decorationEnabled) {
        options.forceSameContext(true);
    }
    boolean wcmDisabled;
    if (this.disableWcm == null) {
        // default is in componentConfiguration
        wcmDisabled = componentConfiguration.isDisableWcm();
    } else {
        wcmDisabled = this.disableWcm;
    }
    if (wcmDisabled) {
        WCMMode.DISABLED.toRequest(request);
    }
    try {
        String[] componentAdditionalCssClassNames = componentConfiguration.getAdditionalCssClassNames();
        if ((null != componentAdditionalCssClassNames) && (componentAdditionalCssClassNames.length > 0)) {
            options.getCssClassNames().addAll(Arrays.asList(componentAdditionalCssClassNames));
        }
        if ((null != additionalCssClassNames) && (additionalCssClassNames.length > 0)) {
            options.getCssClassNames().addAll(Arrays.asList(additionalCssClassNames));
        }
        wcmIncludeTag.setResourceType(resourceType);
        return wcmIncludeTag.doEndTag();
    } finally {
        if (wcmDisabled) {
            wcmMode.toRequest(request);
        }
    }
}
Example 22
Project: sling-handlebars-master  File: ScriptContextAdapter.java View source code
public SlingHttpServletRequest getRequest() {
    return request;
}
Example 23
Project: accesscontroltool-master  File: HistoryRenderer.java View source code
public void setSlingRequest(final SlingHttpServletRequest slingRequest) {
    this.request = slingRequest;
}
Example 24
Project: AEM-Integration-Test-Example-master  File: LoggingFilter.java View source code
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain filterChain) throws IOException, ServletException {
    final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request;
    logger.debug("request for {}, with selector {}", slingRequest.getRequestPathInfo().getResourcePath(), slingRequest.getRequestPathInfo().getSelectorString());
    filterChain.doFilter(request, response);
}
Example 25
Project: cq-commerce-impl-sample-master  File: TrainingCommerceServiceImpl.java View source code
public CommerceSession login(SlingHttpServletRequest request, SlingHttpServletResponse response) throws CommerceException {
    return new TrainingCommerceSessionImpl(this, request, response, resource);
}
Example 26
Project: Slice-CQ56-master  File: CQModule.java View source code
@Provides
public // during request
WCMMode getWCMMode(final SlingHttpServletRequest request) {
    return WCMMode.fromRequest(request);
}
Example 27
Project: sling-logback-master  File: SlingMDCFilter.java View source code
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    final SlingHttpServletRequest request = (SlingHttpServletRequest) servletRequest;
    try {
        insertIntoMDC(request);
        filterChain.doFilter(request, servletResponse);
    } finally {
        clearMDC();
    }
}