Search in sources :

Example 11 with RequestParameter

use of org.apache.sling.api.request.RequestParameter in project sling by apache.

the class RequestPropertyTest method collectContent.

@SuppressWarnings("unchecked")
private Map<String, RequestProperty> collectContent(Param... kvs) throws Throwable {
    final List<Map.Entry<String, RequestParameter>> params = new ArrayList<Map.Entry<String, RequestParameter>>();
    for (int i = 0; i < kvs.length; i++) {
        final Param kv = kvs[i];
        final RequestParameter[] param = new RequestParameter[kv.value.length];
        for (int j = 0; j < kv.value.length; j++) {
            final String strValue = kv.value[j];
            final RequestParameter aparam = context.mock(RequestParameter.class, "requestParameter" + i + "#" + j);
            context.checking(new Expectations() {

                {
                    allowing(aparam).getString();
                    will(returnValue(strValue));
                }
            });
            param[j] = aparam;
        }
        final Map.Entry<String, RequestParameter> entry = context.mock(Map.Entry.class, "entry" + i);
        context.checking(new Expectations() {

            {
                allowing(entry).getKey();
                will(returnValue(kv.key));
                allowing(entry).getValue();
                will(returnValue(param));
            }
        });
        params.add(entry);
    }
    final Set set = context.mock(Set.class);
    context.checking(new Expectations() {

        {
            one(set).iterator();
            will(returnValue(params.iterator()));
        }
    });
    final RequestParameterMap map = context.mock(RequestParameterMap.class);
    context.checking(new Expectations() {

        {
            one(map).entrySet();
            will(returnValue(set));
        }
    });
    final SlingHttpServletRequest request = context.mock(SlingHttpServletRequest.class);
    context.checking(new Expectations() {

        {
            Vector names = new Vector();
            names.add("./param");
            one(request).getParameterNames();
            will(returnValue(names.elements()));
            one(request).getRequestParameterMap();
            will(returnValue(map));
        }
    });
    final HtmlResponse response = new HtmlResponse();
    response.setPath("/test/path");
    Map<String, RequestProperty> props = (Map<String, RequestProperty>) PrivateAccessor.invoke(new ModifyOperation(), "collectContent", COLLECT_CLASSES, new Object[] { request, response });
    return props;
}
Also used : Expectations(org.jmock.Expectations) HtmlResponse(org.apache.sling.servlets.post.HtmlResponse) Set(java.util.Set) RequestParameter(org.apache.sling.api.request.RequestParameter) ArrayList(java.util.ArrayList) SlingHttpServletRequest(org.apache.sling.api.SlingHttpServletRequest) RequestParameterMap(org.apache.sling.api.request.RequestParameterMap) RequestProperty(org.apache.sling.servlets.post.impl.helper.RequestProperty) ModifyOperation(org.apache.sling.servlets.post.impl.operations.ModifyOperation) RequestParameterMap(org.apache.sling.api.request.RequestParameterMap) Map(java.util.Map) Vector(java.util.Vector)

Example 12 with RequestParameter

use of org.apache.sling.api.request.RequestParameter in project sling by apache.

the class AbstractAuthorizablePostServlet method collectContent.

// ------ The methods below are based on the private methods from the
// ModifyOperation class -----
/**
     * Collects the properties that form the content to be written back to the
     * repository.
     * @param properties the properties out of which to generate the {@link RequestProperty}s
     * @return the list of {@link RequestProperty}s
     */
protected Collection<RequestProperty> collectContent(Map<String, ?> properties) {
    boolean requireItemPrefix = requireItemPathPrefix(properties);
    // walk the request parameters and collect the properties (the key is the property path).
    Map<String, RequestProperty> reqProperties = new HashMap<String, RequestProperty>();
    for (Map.Entry<String, ?> e : properties.entrySet()) {
        final String paramName = e.getKey();
        // do not store parameters with names starting with sling:post
        if (paramName.startsWith(SlingPostConstants.RP_PREFIX)) {
            continue;
        }
        // SLING-298: skip form encoding parameter
        if (paramName.equals("_charset_")) {
            continue;
        }
        // skip parameters that do not start with the save prefix
        if (requireItemPrefix && !hasItemPathPrefix(paramName)) {
            continue;
        }
        // ensure the paramName is an absolute property path (i.e. starts with "/", where root refers to the authorizable's root, https://issues.apache.org/jira/browse/SLING-1577)
        String propPath;
        if (paramName.startsWith("./")) {
            propPath = paramName.substring(1);
        } else {
            propPath = "/" + paramName;
        }
        if (propPath.indexOf("..") != -1) {
            // it is not supported to set properties potentially outside of the authorizable node
            LOG.warn("Property path containing '..' is not supported, skipping parameter {}", SlingPostConstants.SUFFIX_COPY_FROM, paramName);
            // skip it.
            continue;
        }
        // causes the setProperty using the 'long' property type
        if (propPath.endsWith(SlingPostConstants.TYPE_HINT_SUFFIX)) {
            RequestProperty prop = getOrCreateRequestProperty(reqProperties, propPath, SlingPostConstants.TYPE_HINT_SUFFIX);
            String typeHintValue = convertToString(e.getValue());
            if (typeHintValue != null) {
                prop.setTypeHintValue(typeHintValue);
            }
            continue;
        }
        // @DefaultValue
        if (propPath.endsWith(SlingPostConstants.DEFAULT_VALUE_SUFFIX)) {
            RequestProperty prop = getOrCreateRequestProperty(reqProperties, propPath, SlingPostConstants.DEFAULT_VALUE_SUFFIX);
            prop.setDefaultValues(convertToRequestParameterArray(e.getValue()));
            continue;
        }
        // fulltext form field.
        if (propPath.endsWith(SlingPostConstants.VALUE_FROM_SUFFIX)) {
            RequestProperty prop = getOrCreateRequestProperty(reqProperties, propPath, SlingPostConstants.VALUE_FROM_SUFFIX);
            // @ValueFrom params must have exactly one value, else ignored
            String[] valueFrom = convertToStringArray(e.getValue());
            if (valueFrom.length == 1) {
                String refName = valueFrom[0];
                RequestParameter[] refValues = convertToRequestParameterArray(refName);
                if (refValues != null) {
                    prop.setValues(refValues);
                }
            }
            continue;
        }
        // causes the JCR Text property to be deleted before update
        if (propPath.endsWith(SlingPostConstants.SUFFIX_DELETE)) {
            RequestProperty prop = getOrCreateRequestProperty(reqProperties, propPath, SlingPostConstants.SUFFIX_DELETE);
            prop.setDelete(true);
            continue;
        }
        // property to Text.
        if (propPath.endsWith(SlingPostConstants.SUFFIX_MOVE_FROM)) {
            // don't support @MoveFrom here
            LOG.warn("Suffix {} not supported, skipping parameter {}", SlingPostConstants.SUFFIX_MOVE_FROM, paramName);
            continue;
        }
        // property to Text.
        if (propPath.endsWith(SlingPostConstants.SUFFIX_COPY_FROM)) {
            // don't support @CopyFrom here
            LOG.warn("Suffix {} not supported, skipping parameter {}", SlingPostConstants.SUFFIX_COPY_FROM, paramName);
            continue;
        }
        // plain property, create from values
        RequestProperty prop = getOrCreateRequestProperty(reqProperties, propPath, null);
        prop.setValues(convertToRequestParameterArray(e.getValue()));
    }
    return reqProperties.values();
}
Also used : HashMap(java.util.HashMap) RequestProperty(org.apache.sling.servlets.post.impl.helper.RequestProperty) RequestParameter(org.apache.sling.api.request.RequestParameter) HashMap(java.util.HashMap) Map(java.util.Map)

Example 13 with RequestParameter

use of org.apache.sling.api.request.RequestParameter in project sling by apache.

the class StatsTestServlet method doPost.

@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
    final RequestParameter param = request.getRequestParameter(IMPORT_FILE_ATTRIB_NAME);
    if (param == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing required parameter " + IMPORT_FILE_ATTRIB_NAME);
        return;
    }
    InputStream is = null;
    final PrintWriter pw = response.getWriter();
    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");
    try {
        is = param.getInputStream();
        pw.println("Creating stats from supplied mbox file...");
        int counter = 0;
        final Iterator<Message> it = parser.parse(is);
        while (it.hasNext()) {
            final Message m = it.next();
            final String[] to = MailStatsProcessorImpl.toArray(m.getTo());
            final String[] cc = MailStatsProcessorImpl.toArray(m.getCc());
            for (String from : MailStatsProcessorImpl.toArray(m.getFrom())) {
                processor.computeStats(m.getDate(), from.toString(), to, cc);
            }
            counter++;
        }
        pw.println(counter + " messages parsed");
    } finally {
        processor.flush();
        pw.flush();
        if (is != null) {
            is.close();
        }
    }
}
Also used : Message(org.apache.james.mime4j.dom.Message) RequestParameter(org.apache.sling.api.request.RequestParameter) InputStream(java.io.InputStream) PrintWriter(java.io.PrintWriter)

Example 14 with RequestParameter

use of org.apache.sling.api.request.RequestParameter in project sling by apache.

the class LinkOperation method doRun.

@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");
                }
            }
        }
    }
}
Also used : Item(javax.jcr.Item) RequestParameter(org.apache.sling.api.request.RequestParameter) Node(javax.jcr.Node) Session(javax.jcr.Session)

Example 15 with RequestParameter

use of org.apache.sling.api.request.RequestParameter in project sling by apache.

the class ParameterSupport method parseMultiPartPost.

private void parseMultiPartPost(ParameterMap parameters) {
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    upload.setSizeMax(ParameterSupport.maxRequestSize);
    upload.setFileSizeMax(ParameterSupport.maxFileSize);
    upload.setFileItemFactory(new DiskFileItemFactory(ParameterSupport.fileSizeThreshold, ParameterSupport.location));
    RequestContext rc = new ServletRequestContext(this.getServletRequest()) {

        @Override
        public String getCharacterEncoding() {
            String enc = super.getCharacterEncoding();
            return (enc != null) ? enc : Util.ENCODING_DIRECT;
        }
    };
    // Parse the request
    List<?> /* FileItem */
    items = null;
    try {
        items = upload.parseRequest(rc);
    } catch (FileUploadException fue) {
        this.log.error("parseMultiPartPost: Error parsing request", fue);
    }
    if (items != null && items.size() > 0) {
        for (Iterator<?> ii = items.iterator(); ii.hasNext(); ) {
            FileItem fileItem = (FileItem) ii.next();
            RequestParameter pp = new MultipartRequestParameter(fileItem);
            parameters.addParameter(pp, false);
        }
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) RequestParameter(org.apache.sling.api.request.RequestParameter) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) RequestContext(org.apache.commons.fileupload.RequestContext) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Aggregations

RequestParameter (org.apache.sling.api.request.RequestParameter)25 RequestParameterMap (org.apache.sling.api.request.RequestParameterMap)8 Map (java.util.Map)5 InputStream (java.io.InputStream)4 HashMap (java.util.HashMap)4 Resource (org.apache.sling.api.resource.Resource)4 RequestProperty (org.apache.sling.servlets.post.impl.helper.RequestProperty)4 ArrayList (java.util.ArrayList)3 Node (javax.jcr.Node)3 Session (javax.jcr.Session)3 PersistenceException (org.apache.sling.api.resource.PersistenceException)3 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)3 PageManager (com.day.cq.wcm.api.PageManager)2 IOException (java.io.IOException)2 HashSet (java.util.HashSet)2 Set (java.util.Set)2 PostConstruct (javax.annotation.PostConstruct)2 SlingHttpServletRequest (org.apache.sling.api.SlingHttpServletRequest)2 ModifiableValueMap (org.apache.sling.api.resource.ModifiableValueMap)2 ValueMap (org.apache.sling.api.resource.ValueMap)2