Search in sources :

Example 6 with RequestParameter

use of org.apache.sling.api.request.RequestParameter in project acs-aem-commons by Adobe-Consulting-Services.

the class AnnotatedFieldDeserializer method parseInput.

@SuppressWarnings("squid:S3776")
private static void parseInput(Object target, ValueMap input, Field field) throws ReflectiveOperationException, ParseException {
    FormField inputAnnotation = field.getAnnotation(FormField.class);
    Object value;
    if (input.get(field.getName()) == null) {
        if (inputAnnotation != null && inputAnnotation.required()) {
            if (field.getType() == Boolean.class || field.getType() == Boolean.TYPE) {
                value = false;
            } else {
                throw new NullPointerException("Required field missing: " + field.getName());
            }
        } else {
            return;
        }
    } else {
        value = input.get(field.getName());
    }
    if (hasMultipleValues(field.getType())) {
        parseInputList(target, serializeToStringArray(value), field);
    } else {
        Object val = value;
        if (value.getClass().isArray()) {
            val = ((Object[]) value)[0];
        }
        if (val instanceof RequestParameter) {
            /**
             * Special case handling uploaded files; Method call ~ copied from parseInputValue(..) *
             */
            if (field.getType() == RequestParameter.class) {
                FieldUtils.writeField(field, target, val, true);
            } else {
                try {
                    FieldUtils.writeField(field, target, ((RequestParameter) val).getInputStream(), true);
                } catch (IOException ex) {
                    LOG.error("Unable to get InputStream for uploaded file [ {} ]", ((RequestParameter) val).getName(), ex);
                }
            }
        } else {
            parseInputValue(target, String.valueOf(val), field);
        }
    }
}
Also used : RequestParameter(org.apache.sling.api.request.RequestParameter) IOException(java.io.IOException) FormField(com.adobe.acs.commons.mcp.form.FormField)

Example 7 with RequestParameter

use of org.apache.sling.api.request.RequestParameter in project acs-aem-commons by Adobe-Consulting-Services.

the class TagWidgetConfigurationServlet method writeConfigResource.

private void writeConfigResource(Resource resource, String propertyName, SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException, JSONException, ServletException {
    JSONObject widget = createEmptyWidget(propertyName);
    RequestParameterMap map = request.getRequestParameterMap();
    for (Map.Entry<String, RequestParameter[]> entry : map.entrySet()) {
        String key = entry.getKey();
        RequestParameter[] params = entry.getValue();
        if (params != null) {
            if (params.length > 1) {
                JSONArray arr = new JSONArray();
                for (int i = 0; i < params.length; i++) {
                    arr.put(params[i].getString());
                }
                widget.put(key, arr);
            } else if (params.length == 1) {
                widget.put(key, params[0].getString());
            }
        }
    }
    widget = underlay(widget, resource);
    JSONObject parent = new JSONObject();
    parent.put("xtype", "dialogfieldset");
    parent.put("border", false);
    parent.put("padding", 0);
    parent.put("style", "padding: 0px");
    parent.accumulate("items", widget);
    parent.write(response.getWriter());
}
Also used : RequestParameterMap(org.apache.sling.api.request.RequestParameterMap) JSONObject(org.apache.sling.commons.json.JSONObject) RequestParameter(org.apache.sling.api.request.RequestParameter) JSONArray(org.apache.sling.commons.json.JSONArray) RequestParameterMap(org.apache.sling.api.request.RequestParameterMap) Map(java.util.Map)

Example 8 with RequestParameter

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

the class ImportOperation method doRun.

@Override
protected void doRun(SlingHttpServletRequest request, PostResponse response, final List<Modification> changes) throws PersistenceException {
    try {
        Object importer = contentImporter;
        if (importer == null) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Missing content importer for import");
            return;
        }
        Map<String, RequestProperty> reqProperties = collectContent(request, response);
        VersioningConfiguration versioningConfiguration = getVersioningConfiguration(request);
        // do not change order unless you have a very good reason.
        Session session = request.getResourceResolver().adaptTo(Session.class);
        processCreate(request.getResourceResolver(), reqProperties, response, changes, versioningConfiguration);
        String path = response.getPath();
        Node node = null;
        try {
            node = (Node) session.getItem(path);
        } catch (RepositoryException e) {
            log.warn(e.getMessage(), e);
        // was not able to resolve the node
        } catch (ClassCastException e) {
            log.warn(e.getMessage(), e);
        // it was not a node
        }
        if (node == null) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND, "Missing target node " + path + " for import");
            return;
        }
        String contentType = getRequestParamAsString(request, SlingPostConstants.RP_CONTENT_TYPE);
        if (contentType == null) {
            response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED, "Required :contentType parameter is missing");
            return;
        }
        //import options passed as request parameters.
        final boolean replace = "true".equalsIgnoreCase(getRequestParamAsString(request, SlingPostConstants.RP_REPLACE));
        final boolean replaceProperties = "true".equalsIgnoreCase(getRequestParamAsString(request, SlingPostConstants.RP_REPLACE_PROPERTIES));
        final boolean checkin = "true".equalsIgnoreCase(getRequestParamAsString(request, SlingPostConstants.RP_CHECKIN));
        final boolean autoCheckout = "true".equalsIgnoreCase(getRequestParamAsString(request, SlingPostConstants.RP_AUTO_CHECKOUT));
        String basePath = getResourcePath(request);
        if (basePath.endsWith("/")) {
            //remove the trailing slash
            basePath = basePath.substring(0, basePath.length() - 1);
        }
        // default to creating content
        response.setCreateRequest(true);
        final String targetName;
        //check if a name was posted to use as the name of the imported root node
        if (getRequestParamAsString(request, SlingPostConstants.RP_NODE_NAME) != null) {
            // exact name
            targetName = getRequestParamAsString(request, SlingPostConstants.RP_NODE_NAME);
            if (targetName.length() > 0 && node.hasNode(targetName)) {
                if (replace) {
                    response.setCreateRequest(false);
                } else {
                    response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED, "Cannot import " + path + "/" + targetName + ": node exists");
                    return;
                }
            }
        } else if (getRequestParamAsString(request, SlingPostConstants.RP_NODE_NAME_HINT) != null) {
            // node name hint only
            String nodePath = generateName(request, basePath);
            String name = nodePath.substring(nodePath.lastIndexOf('/') + 1);
            targetName = name;
        } else {
            // no name posted, so the import won't create a root node
            targetName = "";
        }
        final String contentRootName = targetName + "." + contentType;
        try {
            InputStream contentStream = null;
            RequestParameter contentParameter = request.getRequestParameter(SlingPostConstants.RP_CONTENT);
            if (contentParameter != null) {
                contentStream = contentParameter.getInputStream();
            } else {
                RequestParameter contentFile = request.getRequestParameter(SlingPostConstants.RP_CONTENT_FILE);
                if (contentFile != null) {
                    contentStream = contentFile.getInputStream();
                }
            }
            if (contentStream == null) {
                response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED, "Missing content for import");
                return;
            } else {
                ((ContentImporter) importer).importContent(node, contentRootName, contentStream, new ImportOptions() {

                    @Override
                    public boolean isCheckin() {
                        return checkin;
                    }

                    @Override
                    public boolean isAutoCheckout() {
                        return autoCheckout;
                    }

                    @Override
                    public boolean isIgnoredImportProvider(String extension) {
                        // this probably isn't important in this context.
                        return false;
                    }

                    @Override
                    public boolean isOverwrite() {
                        return replace;
                    }

                    /* (non-Javadoc)
                                 * @see org.apache.sling.jcr.contentloader.ImportOptions#isPropertyOverwrite()
                                 */
                    @Override
                    public boolean isPropertyOverwrite() {
                        return replaceProperties;
                    }
                }, new ContentImportListener() {

                    @Override
                    public void onReorder(String orderedPath, String beforeSibbling) {
                        changes.add(Modification.onOrder(orderedPath, beforeSibbling));
                    }

                    @Override
                    public void onMove(String srcPath, String destPath) {
                        changes.add(Modification.onMoved(srcPath, destPath));
                    }

                    @Override
                    public void onModify(String srcPath) {
                        changes.add(Modification.onModified(srcPath));
                    }

                    @Override
                    public void onDelete(String srcPath) {
                        changes.add(Modification.onDeleted(srcPath));
                    }

                    @Override
                    public void onCreate(String srcPath) {
                        changes.add(Modification.onCreated(srcPath));
                    }

                    @Override
                    public void onCopy(String srcPath, String destPath) {
                        changes.add(Modification.onCopied(srcPath, destPath));
                    }

                    @Override
                    public void onCheckin(String srcPath) {
                        changes.add(Modification.onCheckin(srcPath));
                    }

                    @Override
                    public void onCheckout(String srcPath) {
                        changes.add(Modification.onCheckout(srcPath));
                    }
                });
            }
            if (!changes.isEmpty()) {
                //fill in the data for the response report
                Modification modification = changes.get(0);
                if (modification.getType() == ModificationType.CREATE) {
                    String importedPath = modification.getSource();
                    response.setLocation(externalizePath(request, importedPath));
                    response.setPath(importedPath);
                    int lastSlashIndex = importedPath.lastIndexOf('/');
                    if (lastSlashIndex != -1) {
                        String parentPath = importedPath.substring(0, lastSlashIndex);
                        response.setParentLocation(externalizePath(request, parentPath));
                    }
                }
            }
        } catch (IOException e) {
            throw new PersistenceException(e.getMessage(), e);
        }
    } catch (final RepositoryException re) {
        throw new PersistenceException(re.getMessage(), re);
    }
}
Also used : Modification(org.apache.sling.servlets.post.Modification) InputStream(java.io.InputStream) RequestParameter(org.apache.sling.api.request.RequestParameter) Node(javax.jcr.Node) ContentImportListener(org.apache.sling.jcr.contentloader.ContentImportListener) RepositoryException(javax.jcr.RepositoryException) VersioningConfiguration(org.apache.sling.servlets.post.VersioningConfiguration) IOException(java.io.IOException) ContentImporter(org.apache.sling.jcr.contentloader.ContentImporter) RequestProperty(org.apache.sling.servlets.post.impl.helper.RequestProperty) PersistenceException(org.apache.sling.api.resource.PersistenceException) ImportOptions(org.apache.sling.jcr.contentloader.ImportOptions) Session(javax.jcr.Session)

Example 9 with RequestParameter

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

the class AbstractCreateOperation method generateName.

protected String generateName(SlingHttpServletRequest request, String basePath) throws PersistenceException {
    // SLING-1091: If a :name parameter is supplied, the (first) value of this parameter is used unmodified as the name
    //    for the new node. If the name is illegally formed with respect to JCR name requirements, an exception will be
    //    thrown when trying to create the node. The assumption with the :name parameter is, that the caller knows what
    //    he (or she) is supplying and should get the exact result if possible.
    RequestParameterMap parameters = request.getRequestParameterMap();
    RequestParameter specialParam = parameters.getValue(SlingPostConstants.RP_NODE_NAME);
    if (specialParam != null) {
        if (specialParam.getString() != null && specialParam.getString().length() > 0) {
            // If the path ends with a *, create a node under its parent, with
            // a generated node name
            basePath = basePath += "/" + specialParam.getString();
            // if the resulting path already exists then report an error
            if (request.getResourceResolver().getResource(basePath) != null) {
                throw new PersistenceException("Collision in node names for path=" + basePath);
            }
            return basePath;
        }
    }
    // no :name value was supplied, so generate a name
    boolean requirePrefix = requireItemPathPrefix(request);
    String generatedName = null;
    if (extraNodeNameGenerators != null) {
        for (NodeNameGenerator generator : extraNodeNameGenerators) {
            generatedName = generator.getNodeName(request, basePath, requirePrefix, defaultNodeNameGenerator);
            if (generatedName != null) {
                break;
            }
        }
    }
    if (generatedName == null) {
        generatedName = defaultNodeNameGenerator.getNodeName(request, basePath, requirePrefix, defaultNodeNameGenerator);
    }
    // If the path ends with a *, create a node under its parent, with
    // a generated node name
    basePath += "/" + generatedName;
    basePath = ensureUniquePath(request, basePath);
    return basePath;
}
Also used : RequestParameterMap(org.apache.sling.api.request.RequestParameterMap) RequestParameter(org.apache.sling.api.request.RequestParameter) PersistenceException(org.apache.sling.api.resource.PersistenceException) DefaultNodeNameGenerator(org.apache.sling.servlets.post.impl.helper.DefaultNodeNameGenerator) NodeNameGenerator(org.apache.sling.servlets.post.NodeNameGenerator)

Example 10 with RequestParameter

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

the class AbstractCreateOperation method collectContent.

/**
     * Collects the properties that form the content to be written back to the
     * resource tree.
     */
protected Map<String, RequestProperty> collectContent(final SlingHttpServletRequest request, final PostResponse response) {
    final boolean requireItemPrefix = requireItemPathPrefix(request);
    // walk the request parameters and collect the properties
    final LinkedHashMap<String, RequestProperty> reqProperties = new LinkedHashMap<>();
    for (final Map.Entry<String, RequestParameter[]> e : request.getRequestParameterMap().entrySet()) {
        final String paramName = e.getKey();
        if (ignoreParameter(paramName)) {
            continue;
        }
        // skip parameters that do not start with the save prefix
        if (requireItemPrefix && !hasItemPathPrefix(paramName)) {
            continue;
        }
        // ensure the paramName is an absolute property name
        final String propPath = toPropertyPath(paramName, response);
        // causes the setProperty using the 'long' property type
        if (propPath.endsWith(SlingPostConstants.TYPE_HINT_SUFFIX)) {
            final RequestProperty prop = getOrCreateRequestProperty(reqProperties, propPath, SlingPostConstants.TYPE_HINT_SUFFIX);
            final RequestParameter[] rp = e.getValue();
            if (rp.length > 0) {
                prop.setTypeHintValue(rp[0].getString());
            }
            continue;
        }
        // @DefaultValue
        if (propPath.endsWith(SlingPostConstants.DEFAULT_VALUE_SUFFIX)) {
            final RequestProperty prop = getOrCreateRequestProperty(reqProperties, propPath, SlingPostConstants.DEFAULT_VALUE_SUFFIX);
            prop.setDefaultValues(e.getValue());
            continue;
        }
        // fulltext form field.
        if (propPath.endsWith(SlingPostConstants.VALUE_FROM_SUFFIX)) {
            final RequestProperty prop = getOrCreateRequestProperty(reqProperties, propPath, SlingPostConstants.VALUE_FROM_SUFFIX);
            // @ValueFrom params must have exactly one value, else ignored
            if (e.getValue().length == 1) {
                final String refName = e.getValue()[0].getString();
                final RequestParameter[] refValues = request.getRequestParameters(refName);
                if (refValues != null) {
                    prop.setValues(refValues);
                }
            }
            continue;
        }
        // causes the JCR Text property to be deleted before update
        if (propPath.endsWith(SlingPostConstants.SUFFIX_DELETE)) {
            final RequestProperty prop = getOrCreateRequestProperty(reqProperties, propPath, SlingPostConstants.SUFFIX_DELETE);
            prop.setDelete(true);
            continue;
        }
        // property to Text.
        if (propPath.endsWith(SlingPostConstants.SUFFIX_MOVE_FROM)) {
            final RequestProperty prop = getOrCreateRequestProperty(reqProperties, propPath, SlingPostConstants.SUFFIX_MOVE_FROM);
            // @MoveFrom params must have exactly one value, else ignored
            if (e.getValue().length == 1) {
                final String sourcePath = e.getValue()[0].getString();
                prop.setRepositorySource(sourcePath, true);
            }
            continue;
        }
        // property to Text.
        if (propPath.endsWith(SlingPostConstants.SUFFIX_COPY_FROM)) {
            final RequestProperty prop = getOrCreateRequestProperty(reqProperties, propPath, SlingPostConstants.SUFFIX_COPY_FROM);
            // @MoveFrom params must have exactly one value, else ignored
            if (e.getValue().length == 1) {
                final String sourcePath = e.getValue()[0].getString();
                prop.setRepositorySource(sourcePath, false);
            }
            continue;
        }
        // property to Text.
        if (propPath.endsWith(SlingPostConstants.SUFFIX_IGNORE_BLANKS)) {
            final RequestProperty prop = getOrCreateRequestProperty(reqProperties, propPath, SlingPostConstants.SUFFIX_IGNORE_BLANKS);
            if (e.getValue().length == 1) {
                prop.setIgnoreBlanks(true);
            }
            continue;
        }
        if (propPath.endsWith(SlingPostConstants.SUFFIX_USE_DEFAULT_WHEN_MISSING)) {
            final RequestProperty prop = getOrCreateRequestProperty(reqProperties, propPath, SlingPostConstants.SUFFIX_USE_DEFAULT_WHEN_MISSING);
            if (e.getValue().length == 1) {
                prop.setUseDefaultWhenMissing(true);
            }
            continue;
        }
        // <input name="tags"          value="-orange" type="hidden" />
        if (propPath.endsWith(SlingPostConstants.SUFFIX_PATCH)) {
            final RequestProperty prop = getOrCreateRequestProperty(reqProperties, propPath, SlingPostConstants.SUFFIX_PATCH);
            prop.setPatch(true);
            continue;
        }
        if (propPath.endsWith(SlingPostConstants.SUFFIX_OFFSET)) {
            final RequestProperty prop = getOrCreateRequestProperty(reqProperties, propPath, SlingPostConstants.SUFFIX_OFFSET);
            if (e.getValue().length == 1) {
                Chunk chunk = prop.getChunk();
                if (chunk == null) {
                    chunk = new Chunk();
                }
                chunk.setOffsetValue(Long.parseLong(e.getValue()[0].toString()));
                prop.setChunk(chunk);
            }
            continue;
        }
        if (propPath.endsWith(SlingPostConstants.SUFFIX_COMPLETED)) {
            final RequestProperty prop = getOrCreateRequestProperty(reqProperties, propPath, SlingPostConstants.SUFFIX_COMPLETED);
            if (e.getValue().length == 1) {
                Chunk chunk = prop.getChunk();
                if (chunk == null) {
                    chunk = new Chunk();
                }
                chunk.setCompleted(Boolean.parseBoolean((e.getValue()[0].toString())));
                prop.setChunk(chunk);
            }
            continue;
        }
        if (propPath.endsWith(SlingPostConstants.SUFFIX_LENGTH)) {
            final RequestProperty prop = getOrCreateRequestProperty(reqProperties, propPath, SlingPostConstants.SUFFIX_LENGTH);
            if (e.getValue().length == 1) {
                Chunk chunk = prop.getChunk();
                if (chunk == null) {
                    chunk = new Chunk();
                }
                chunk.setLength(Long.parseLong(e.getValue()[0].toString()));
                prop.setChunk(chunk);
            }
            continue;
        }
        // plain property, create from values
        final RequestProperty prop = getOrCreateRequestProperty(reqProperties, propPath, null);
        prop.setValues(e.getValue());
    }
    return reqProperties;
}
Also used : RequestProperty(org.apache.sling.servlets.post.impl.helper.RequestProperty) RequestParameter(org.apache.sling.api.request.RequestParameter) Chunk(org.apache.sling.servlets.post.impl.helper.Chunk) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) RequestParameterMap(org.apache.sling.api.request.RequestParameterMap) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap)

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