Method to get the file content of the upload file based on the mime type

@param requestElements the request elements
@return byte[] the upload file content
@throws FMSException
518324
private byte[] getUploadFileContent(RequestElements requestElements) throws FMSException {
		Attachable attachable = (Attachable) requestElements.getEntity();
		InputStream docContent = requestElements.getUploadRequestElements().getDocContent();
		
		// gets the mime value form the filename
		String mime = getMime(attachable.getFileName(), ".");
		// if null then gets the mime value from content-type of the file
		mime = (mime != null) ? mime : getMime(attachable.getContentType(), "/");
		if (isImageType(mime)) {
			return getImageContent(docContent, mime);
		} else {
			return getContent(docContent);
		}
	}
912938
public Optional<List<FormItem>> parseRequestMultiPartItems(String encoding) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(properties.getInt(Constants.PROPERTY_UPLOADS_MAX_SIZE/*Constants.Params.maxUploadSize.name()*/));//Configuration.getMaxUploadSize());
        factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); //Configuration.getTmpDir());
        //README the file for tmpdir *MIGHT* need to go into Properties
        
        ServletFileUpload upload = new ServletFileUpload(factory);
        
        if(encoding != null)
            upload.setHeaderEncoding(encoding);
        upload.setFileSizeMax(properties.getInt(Constants.PROPERTY_UPLOADS_MAX_SIZE));
        
        try {
            List<FormItem> items = upload.parseRequest(request)
                    .stream()
                    .map(item -> new ApacheFileItemFormItem(item))
                    .collect(Collectors.toList());
            return Optional.of(items);
        } catch (FileUploadException e) {
            //"Error while trying to process mulitpart file upload"
            //README: perhaps some logging
        }
        return Optional.empty();
    }
1317986
private static FormItem getFormItem(PageContext pageContext, String filefield) throws PageException {
	// check filefield
	if (StringUtil.isEmpty(filefield)) {
	    FormItem[] items = getFormItems(pageContext);
	    if (ArrayUtil.isEmpty(items)) throw new ApplicationException("no file send with this form");
	    return items[0];
	}

	PageException pe = pageContext.formScope().getInitException();
	if (pe != null) throw pe;
	lucee.runtime.type.scope.Form upload = pageContext.formScope();
	FormItem fileItem = upload.getUploadResource(filefield);
	if (fileItem == null) {
	    FormItem[] items = upload.getFileItems();
	    StringBuilder sb = new StringBuilder();
	    for (int i = 0; i < items.length; i++) {
		if (i != 0) sb.append(", ");
		sb.append(items[i].getFieldName());
	    }
	    String add = ".";
	    if (sb.length() > 0) add = ", valid field names are [" + sb + "].";

	    if (pageContext.formScope().get(filefield, null) == null) throw new ApplicationException("form field [" + filefield + "] is not a file field" + add);
	    throw new ApplicationException("form field [" + filefield + "] doesn't exist or has no content" + add);
	}

	return fileItem;
    }
1104982
public static byte[] getBodyBytes(ServletRequest request) {
		try {
			return IoUtil.readBytes(request.getInputStream());
		} catch (IOException e) {
			throw new IORuntimeException(e);
		}
	}
874018
def parse(self, mimetypes):
        

        self._parse_top_level_content_type()

        link = 'tools.ietf.org/html/rfc2388'
        parts = cgi.FieldStorage(
            fp=self.req.stream,
            environ=self.req.env,
        )

        if not parts:
            self.fail('A payload in the body of your request is required '
                      '& must be encapsulated by the boundary with proper '
                      'headers according to RFC 2388', link)
        elif len(parts) > 1:
            self.fail('Currently, only 1 upload at a time is allowed. Please '
                      'break up your request into %s individual requests & '
                      'retry' % len(parts), link)
        else:
            self._parse_part(parts.list[0], mimetypes)
            return parts
12084
public static FileItem[] getRequestFileItemValues(final HttpServletRequest request, final String key) {
		return getRequestFileItems(request).get(key);
	}
1071948
public BoxRequestsFile.UploadFile getUploadRequest(File file, String destinationFolderId) {
            BoxRequestsFile.UploadFile request = new BoxRequestsFile.UploadFile(file,  destinationFolderId, getFileUploadUrl(), mSession);
            return request;
    }
552731
private byte[] readRequestBody() {
        int bytesLeft = m_request.getContentLength();
        if (bytesLeft <= 0) {
            return new byte[0];
        }

        int totalBytesRead = 0;
        try {
            byte[] byteBuffer = new byte[bytesLeft];
            try (InputStream inputStream = m_request.getInputStream()) {
                int bytesRead = -1;
                int offset = 0;
                while ((bytesRead = inputStream.read(byteBuffer, offset, bytesLeft)) > 0) {
                    offset += bytesRead;
                    bytesLeft -= bytesRead;
                    totalBytesRead += bytesRead;
                }
            }
            return byteBuffer;
        } catch (IOException e) {
            String errMsg =
                String.format("Error reading from input request; expected %d bytes; only read %d bytes",
                              m_request.getContentLength(), totalBytesRead);
            throw new RuntimeException(errMsg, e);
        }
    }
1331386
public com.google.protobuf.ByteString
      getRequestUrlBytes() {
    java.lang.Object ref = requestUrl_;
    if (ref instanceof java.lang.String) {
      com.google.protobuf.ByteString b = 
          com.google.protobuf.ByteString.copyFromUtf8(
              (java.lang.String) ref);
      requestUrl_ = b;
      return b;
    } else {
      return (com.google.protobuf.ByteString) ref;
    }
  }
894431
public byte[] getContentBytes() throws IOException {
        if (content == null)
            return null;

        DerInputStream dis = new DerInputStream(content.toByteArray());
        return dis.getOctetString();
    }
896592
public static String getInvalidFileTypeMessage(final List<String> fileTypes) {
		if (fileTypes == null) {
			return null;
		}
		return String.format(I18nUtilities.format(null,
			InternalMessages.DEFAULT_VALIDATION_ERROR_FILE_WRONG_TYPE),
			StringUtils.join(fileTypes.toArray(new Object[fileTypes.size()]), ","));
	}
889034
void processFormSubmitRequest(HttpServletRequest request) {

        String formDataId = getFormDataId(request);
        List<FileItem> items = CmsRequestUtil.readMultipartFileItems(request);
        m_storedFormData.put(formDataId, items);
    }
347121
private byte[] getImageContent(InputStream in, String mime) throws FMSException {
		byte[] imageInByte = null;
		ByteArrayOutputStream baos = null;
		try {
			BufferedImage originalImage = ImageIO.read(in);
			baos = new ByteArrayOutputStream();
			ImageIO.write(originalImage, mime, baos);
			baos.flush();
			imageInByte = baos.toByteArray();
			baos.close();
		} catch (IOException e) {
			throw new FMSException("Error while reading the upload file.", e);
		} finally {
			close(baos);
			close(in);
		}
		return imageInByte;
	}
726669
public byte[] getValidationParameter() throws ProposalException {

        ByteString payloadBytes = parsePayload().getValidationParameter();
        if (null == payloadBytes) {
            return null;
        }
        return payloadBytes.toByteArray();
    }
1084299
private function _filterFile(\Mmi\Http\RequestFile $requestFile)
    {
        if (empty($this->_filters)) {
            return true;
        }
        if (!isset($this->_filters['mime_types']) || empty($this->_filters['mime_types'])) {
            return true;
        }
        $allowedTypes = $allowedExts = [];
        foreach ($this->_filters['mime_types'] as $mt) {
            if (array_key_exists('mime', $mt)) {
                $allowedTypes[] = strtolower($mt['mime']);
            } elseif (array_key_exists('extensions', $mt)) {
                $allowedExts = array_merge($allowedExts, explode(",", strtolower(preg_replace('/ \s/', '', $mt['extensions']))));
            }
        }
        //sprawdzamy typy mime
        if (in_array(strtolower($requestFile->type), $allowedTypes)) {
            return true;
        }
        //sprawdzamy rozszerzenie
        if (strrpos($this->_fileName, '.') > 0) {
            $ext = strtolower(substr($this->_fileName, strrpos($this->_fileName, '.') + 1));
            if (in_array($ext, $allowedExts)) {
                return true;
            }
        }
        return false;
    }
389353
private QueryRequest createQueryRequest(String[] elements) {
        QueryRequest request = QueryRequest.create();
        for (String element : elements) {
            String[] parts = StringUtils.split(element, ":", 2);
            parts[0] = parts[0].replace("\\", "\\\\");
            parts[1] = parts[1].replace("\\", "\\\\");
            request.addParameter(parts[0], parts[1].substring(1, parts[1].length() - 1));
        }
        return request;
    }
713696
public static RequestContent getRequestContent(HttpServletRequest request,
                                            HttpHeaders headers)
    throws Exception {
        RequestContent rContent = null;

        // See if the request is a multi-part file upload request
        if(ServletFileUpload.isMultipartContent(request)) {

        	logger.debug("processing multipart content...");
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload();

            // Parse the request, use the first available File item
            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                if (!item.isFormField()) {
                    rContent = new RequestContent();
                    rContent.contentStream = item.openStream();
                    rContent.mimeType = item.getContentType();

                    FileItemHeaders itemHeaders = item.getHeaders();
                    if(itemHeaders != null) {
                        String contentLength = itemHeaders.getHeader("Content-Length");
                        if(contentLength != null) {
                            rContent.size = Long.parseLong(contentLength);
                        }
                    }

                    break;
                } else {
                	logger.trace("ignoring form field \"{}\" \"{}\"", item.getFieldName(), item.getName());
                }
            }
        } else {
            // If the content stream was not been found as a multipart,
            // try to use the stream from the request directly
            if(rContent == null) {
                String contentLength = request.getHeader("Content-Length");
                long size = 0;
                if(contentLength != null) {
                    size = Long.parseLong(contentLength);
                } else size = request.getContentLength();
                if (size > 0) {
                  rContent = new RequestContent();
                  rContent.contentStream = request.getInputStream();
                  rContent.size = size;
                } else {
                    String transferEncoding =
                            request.getHeader("Transfer-Encoding");
                    if (transferEncoding != null && transferEncoding.contains("chunked")) {
                        BufferedInputStream bis =
                            new BufferedInputStream(request.getInputStream());
                        bis.mark(2);
                        if (bis.read() > 0) {
                            bis.reset();
                            rContent = new RequestContent();
                            rContent.contentStream = bis;
                        }
                    } else {
                    	logger.warn(
                    			"Expected chunked data not found- " +
                    	        "Transfer-Encoding : {}, Content-Length: {}",
                    	        transferEncoding, size);
                    }
                }
            }
        }

        // Attempt to set the mime type and size if not already set
        if(rContent != null) {
            if(rContent.mimeType == null) {
                MediaType mediaType = headers.getMediaType();
                if(mediaType != null) {
                    rContent.mimeType = mediaType.toString();
                }
            }

            if(rContent.size == 0) {
                List<String> lengthHeaders =
                    headers.getRequestHeader("Content-Length");
                if(lengthHeaders != null && lengthHeaders.size() > 0) {
                    rContent.size = Long.parseLong(lengthHeaders.get(0));
                }
            }
        }

        return rContent;
    }