<commit_before>/*
 * eXist-db Open Source Native XML Database
 * Copyright (C) 2001 The eXist-db Authors
 *
 * <EMAIL>
 * http://www.exist-db.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package org.exist.http.servlets;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.file.Path;
import java.security.Principal;
import java.util.*;

import static java.nio.charset.StandardCharsets.UTF_8;


/**
 * A wrapper for requests processed by a servlet. All parameters, submitted as part of
 * the URL and via the http POST body (application/x-www-form-urlencoded and
 * multipart/form-data encoded) are made available transparently.
 * 
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 */
public class HttpRequestWrapper implements RequestWrapper {

    private static final Logger LOG = LogManager.getLogger(HttpRequestWrapper.class);
    
    private final HttpServletRequest servletRequest;
    private final String formEncoding;
    private String containerEncoding = null;

    private String pathInfo = null;
    private String servletPath = null;

    private final boolean isMultipartContent;

    // Use linkedhashmap to preserver order
    // Object can be a single object, or a List of objects
    private final Map<String, Object> params = new LinkedHashMap<>();

    // flag to administer wether multi-part formdata was processed
    private final boolean isFormDataParsed;

    /**
     * Constructs a wrapper for the given servlet request. multipart/form-data 
     * will be parsed when available upon indication.
     *
     * Defaults to UTF-8 encoding
     * 
     * @param servletRequest The request as viewed by the servlet
     */
    public HttpRequestWrapper(final HttpServletRequest servletRequest) {
        this(servletRequest, UTF_8.name(), UTF_8.name());
    }
    
    /**
     * Constructs a wrapper for the given servlet request. multipart/form-data 
     * will be parsed when available upon indication.
     *
     * @param servletRequest The request as viewed by the servlet
     * @param formEncoding The encoding of the request's forms
     * @param containerEncoding The encoding of the servlet
     */
    public HttpRequestWrapper(final HttpServletRequest servletRequest, final String formEncoding,
            final String containerEncoding) {
        this(servletRequest, formEncoding, containerEncoding, true);
    }

    /**
     * Constructs a wrapper for the given servlet request.
     *
     * @param servletRequest The request as viewed by the servlet
     * @param formEncoding The encoding of the request's forms
     * @param containerEncoding The encoding of the servlet
     * @param parseMultipart Set to TRUE to enable parse multipart/form-data when available.
     */
    public HttpRequestWrapper(final HttpServletRequest servletRequest, final String formEncoding,
            final String containerEncoding, final boolean parseMultipart) {
        this.servletRequest = servletRequest;
        this.formEncoding = formEncoding;
        this.containerEncoding = containerEncoding;
        this.pathInfo = servletRequest.getPathInfo();
        this.servletPath = servletRequest.getServletPath();


        // Get url-encoded parameters (url-ecoded from http GET and POST)
        parseParameters();

        // Determine if request is a multipart
        isMultipartContent = ServletFileUpload.isMultipartContent(servletRequest);

        // Get multi-part formdata parameters when it is a mpfd request
        // and when instructed to do so
        if (parseMultipart && isMultipartContent) {

            // Formdata is actually parsed
            isFormDataParsed = true;

            // Get multi-part formdata
            parseMultipartContent();
        } else {
            isFormDataParsed = false;
        }

        LOG.debug("Retrieved {} parameters.", params.size());
    }

    @Override
    public Object getAttribute(final String name) {
        return servletRequest.getAttribute(name);
    }

    @Override
    public Enumeration<String> getAttributeNames() {
        return servletRequest.getAttributeNames();
    }

    /**
     * Returns an array of Cookies
     */
    @Override
    public Cookie[] getCookies() {
        return servletRequest.getCookies();
    }

    private static void addParameter(final Map<String, Object> map, final String paramName, final Object value) {

        final Object original = map.get(paramName);

        if (original != null) {

            // Check if original value was already a List
            if (original instanceof List) {
                // Add value to existing List
                ((List) original).add(value);

            } else {
                // Single value already detected, convert to List and add both items
                final List<Object> list = new ArrayList<>();
                list.add(original);
                list.add(value);
                map.put(paramName, list);
            }

        } else {
            // Parameter did not exist yet, add single value
            map.put(paramName, value);
        }
    }

    /**
     * Parses multi-part requests in order to set the parameters. 
     */
    private void parseMultipartContent() {
        // Create a factory for disk-based file items
        final DiskFileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        final ServletFileUpload upload = new ServletFileUpload(factory);

        try {

            final List<FileItem> items = upload.parseRequest(servletRequest);

            // Iterate over all mult-part formdata items and
            // add all data (field and files) to parmeters
            for (final FileItem item : items) {
                addParameter(params, item.getFieldName(), item);
            }

        } catch (final FileUploadException e) {
            LOG.error(e);
        }

    }

    /**<commit_msg>[hotfix] multipart body contents in XQuery<commit_after>/*
 * eXist-db Open Source Native XML Database
 * Copyright (C) 2001 The eXist-db Authors
 *
 * <EMAIL>
 * http://www.exist-db.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package org.exist.http.servlets;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.file.Path;
import java.security.Principal;
import java.util.*;

import static java.nio.charset.StandardCharsets.UTF_8;


/**
 * A wrapper for requests processed by a servlet. All parameters, submitted as part of
 * the URL and via the http POST body (application/x-www-form-urlencoded and
 * multipart/form-data encoded) are made available transparently.
 * 
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 */
public class HttpRequestWrapper implements RequestWrapper {

    private static final Logger LOG = LogManager.getLogger(HttpRequestWrapper.class);
    
    private final HttpServletRequest servletRequest;
    private final String formEncoding;
    private String containerEncoding = null;

    private String pathInfo = null;
    private String servletPath = null;

    private final boolean isMultipartContent;

    // Use linkedhashmap to preserver order
    // Object can be a single object, or a List of objects
    private final Map<String, Object> params = new LinkedHashMap<>();

    // flag to administer wether multi-part formdata was processed
    private final boolean isFormDataParsed;

    /**
     * Constructs a wrapper for the given servlet request. multipart/form-data 
     * will be parsed when available upon indication.
     *
     * Defaults to UTF-8 encoding
     * 
     * @param servletRequest The request as viewed by the servlet
     */
    public HttpRequestWrapper(final HttpServletRequest servletRequest) {
        this(servletRequest, UTF_8.name(), UTF_8.name());
    }
    
    /**
     * Constructs a wrapper for the given servlet request. multipart/form-data 
     * will be parsed when available upon indication.
     *
     * @param servletRequest The request as viewed by the servlet
     * @param formEncoding The encoding of the request's forms
     * @param containerEncoding The encoding of the servlet
     */
    public HttpRequestWrapper(final HttpServletRequest servletRequest, final String formEncoding,
            final String containerEncoding) {
        this(servletRequest, formEncoding, containerEncoding, true);
    }

    /**
     * Constructs a wrapper for the given servlet request.
     *
     * @param servletRequest The request as viewed by the servlet
     * @param formEncoding The encoding of the request's forms
     * @param containerEncoding The encoding of the servlet
     * @param parseMultipart Set to TRUE to enable parse multipart/form-data when available.
     */
    public HttpRequestWrapper(final HttpServletRequest servletRequest, final String formEncoding,
            final String containerEncoding, final boolean parseMultipart) {
        this.servletRequest = servletRequest;
        this.formEncoding = formEncoding;
        this.containerEncoding = containerEncoding;
        this.pathInfo = servletRequest.getPathInfo();
        this.servletPath = servletRequest.getServletPath();


        // Get url-encoded parameters (url-ecoded from http GET and POST)
        parseParameters();

        // Determine if request is a multipart
        isMultipartContent = ServletFileUpload.isMultipartContent(servletRequest);

        // Get multi-part formdata parameters when it is a mpfd request
        // and when instructed to do so
        if (parseMultipart && isMultipartContent) {

            // Formdata is actually parsed
            isFormDataParsed = true;

            // Get multi-part formdata
            parseMultipartContent();
        } else {
            isFormDataParsed = false;
        }

        LOG.debug("Retrieved {} parameters.", params.size());
    }

    @Override
    public Object getAttribute(final String name) {
        return servletRequest.getAttribute(name);
    }

    @Override
    public Enumeration<String> getAttributeNames() {
        return servletRequest.getAttributeNames();
    }

    /**
     * Returns an array of Cookies
     */
    @Override
    public Cookie[] getCookies() {
        return servletRequest.getCookies();
    }

    private static void addParameter(final Map<String, Object> map, final String paramName, final Object value) {

        final Object original = map.get(paramName);

        if (original != null) {

            // Check if original value was already a List
            if (original instanceof List) {
                // Add value to existing List
                ((List) original).add(value);

            } else {
                // Single value already detected, convert to List and add both items
                final List<Object> list = new ArrayList<>();
                list.add(original);
                list.add(value);
                map.put(paramName, list);
            }

        } else {
            // Parameter did not exist yet, add single value
            map.put(paramName, value);
        }
    }

    /**
     * Parses multi-part requests in order to set the parameters. 
     */
    private void parseMultipartContent() {
        // Create a factory for disk-based file items
        final DiskFileItemFactory factory = new DiskFileItemFactory();

        // Ensure small attachments are readable in XQuery context
        factory.setSizeThreshold(0);

        // Create a new file upload handler
        final ServletFileUpload upload = new ServletFileUpload(factory);

        try {

            final List<FileItem> items = upload.parseRequest(servletRequest);

            // Iterate over all mult-part formdata items and
            // add all data (field and files) to parmeters
            for (final FileItem item : items) {
                addParameter(params, item.getFieldName(), item);
            }

        } catch (final FileUploadException e) {
            LOG.error(e);
        }

    }

    /**
{'fraction_non_alphanumeric': 0.0810483870967742, 'fraction_numerical': 0.0031586021505376344, 'mean_word_length': 2.798111281265952, 'pattern_counts': {'":': 0, '<': 51, '<?xml version=': 0, '>': 51, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1566958', 'n_tokens_mistral': 3874, 'n_tokens_neox': 3724, 'n_words': 1328}