Example usage for org.apache.commons.fileupload MultipartStream readBoundary

List of usage examples for org.apache.commons.fileupload MultipartStream readBoundary

Introduction

In this page you can find the example usage for org.apache.commons.fileupload MultipartStream readBoundary.

Prototype

public boolean readBoundary() throws MalformedStreamException 

Source Link

Document

Skips a boundary token, and checks whether more encapsulations are contained in the stream.

Usage

From source file:lucee.runtime.net.http.MultiPartResponseUtils.java

public static Array getParts(byte[] barr, String contentTypeHeader) throws IOException, PageException {
    String boundary = extractBoundary(contentTypeHeader, "");
    ByteArrayInputStream bis = new ByteArrayInputStream(barr);
    MultipartStream stream;
    Array result = new ArrayImpl();
    stream = new MultipartStream(bis, getBytes(boundary, "UTF-8"));// 

    boolean hasNextPart = stream.skipPreamble();
    while (hasNextPart) {
        result.append(getPartData(stream));
        hasNextPart = stream.readBoundary();
    }// w  w  w .  j a va2  s  .  com
    return result;
}

From source file:ch.sportchef.business.event.boundary.EventImageResource.java

@PUT
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadImage(@Context HttpServletRequest request) throws IOException, ServletException {
    final String contentType = request.getContentType();
    final byte[] boundary = contentType.substring(contentType.indexOf("boundary=") + 9).getBytes();

    try (final BufferedInputStream inputStream = new BufferedInputStream(request.getInputStream(), 8192)) {
        final MultipartStream multipartStream = new MultipartStream(inputStream, boundary, 8192, null);
        boolean nextPart = multipartStream.skipPreamble();
        while (nextPart) {
            multipartStream.readHeaders(); // don't remove, strips headers off
            try (final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(8192)) {
                multipartStream.readBodyData(outputStream);
                nextPart = multipartStream.readBoundary();
                final byte[] image = outputStream.toByteArray();
                eventImageService.uploadImage(eventId, image);
                return Response.ok().build();
            }// www .  j a v a  2s  .c o m
        }
    }

    return Response.status(BAD_REQUEST).build();
}

From source file:io.selendroid.testapp.webdrivertestserver.handler.UploadFileHandler.java

public void handleHttpRequest(HttpRequest request, HttpResponse response, HttpControl control)
        throws Exception {
    response.header("Content-Type", "text/html; charset=" + Charsets.UTF_8.name());

    String contentTypeHeader = request.header("Content-Type");
    Map<String, String> contentTypeHeaderFields = extractFields(contentTypeHeader);

    ByteArrayInputStream input = new ByteArrayInputStream(request.bodyAsBytes());
    MultipartStream multipartStream = new MultipartStream(input,
            contentTypeHeaderFields.get("boundary").getBytes());

    boolean hasNext = multipartStream.skipPreamble();
    while (hasNext) {
        Map<String, String> allHeaders = splitHeaders(multipartStream.readHeaders());
        String inputFieldName = extractFields(allHeaders.get("Content-Disposition")).get("name");
        if (UPLOAD_NAMES.contains(inputFieldName)) {
            ByteArrayOutputStream data = new ByteArrayOutputStream();
            multipartStream.readBodyData(data);
            response.content(data.toByteArray());
        } else {/*from  w ww  .j  a v a 2  s. c o  m*/
            multipartStream.discardBodyData();
        }

        hasNext = multipartStream.readBoundary();
    }

    response.content("<script>window.top.window.onUploadDone();</script>").end();
}

From source file:com.intuit.tank.http.multipart.MultiPartRequest.java

@Override
public void setBody(String bodyEncoded) {
    String s = new String(Base64.decodeBase64(bodyEncoded));
    String boundary = StringUtils.substringBefore(s, "\r\n").substring(2);
    super.setBody(s);
    try {/*from  www .j  av a 2s . co  m*/
        // s = getBody();
        @SuppressWarnings("deprecation")
        MultipartStream multipartStream = new MultipartStream(
                new ByteArrayInputStream(Base64.decodeBase64(bodyEncoded)), boundary.getBytes());
        boolean nextPart = multipartStream.skipPreamble();
        while (nextPart) {
            String header = multipartStream.readHeaders();
            // process headers
            // create some output stream
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            multipartStream.readBodyData(bos);
            PartHolder p = new PartHolder(bos.toByteArray(), header);
            parameters.add(p);
            nextPart = multipartStream.readBoundary();
        }
    } catch (MultipartStream.MalformedStreamException e) {
        LOG.error(e.toString(), e);
        // the stream failed to follow required syntax
    } catch (IOException e) {
        LOG.error(e.toString(), e);
        // a read or write error occurred
    }
}

From source file:com.predic8.membrane.core.multipart.XOPReconstitutor.java

@SuppressWarnings("deprecation")
private HashMap<String, Part> split(Message message, String boundary)
        throws IOException, EndOfStreamException, MalformedStreamException {
    HashMap<String, Part> parts = new HashMap<String, Part>();

    MultipartStream multipartStream = new MultipartStream(MessageUtil.getContentAsStream(message),
            boundary.getBytes(Constants.UTF_8_CHARSET));
    boolean nextPart = multipartStream.skipPreamble();
    while (nextPart) {
        Header header = new Header(multipartStream.readHeaders());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        multipartStream.readBodyData(baos);

        // see http://www.iana.org/assignments/transfer-encodings/transfer-encodings.xml
        String cte = header.getFirstValue("Content-Transfer-Encoding");
        if (cte != null && !cte.equals("binary") && !cte.equals("8bit") && !cte.equals("7bit"))
            throw new RuntimeException("Content-Transfer-Encoding '" + cte + "' not implemented.");

        Part part = new Part(header, baos.toByteArray());
        String id = part.getContentID();
        if (id != null) {
            parts.put(id, part);//from  w  w w .j a  va 2 s.c o m
        }

        nextPart = multipartStream.readBoundary();
    }
    return parts;
}

From source file:info.novatec.inspectit.rcp.storage.util.DataRetriever.java

/**
 * Retrieves the wanted data described in the {@link StorageDescriptor} from the desired
 * {@link CmrRepositoryDefinition}. This method will try to invoke as less as possible HTTP
 * requests for all descriptors./*w w  w.  j ava 2 s .co  m*/
 * <p>
 * The method will execute the HTTP requests sequentially.
 * <p>
 * It is not guaranteed that amount of returned objects in the list is same as the amount of
 * provided descriptors. If some of the descriptors are pointing to the wrong files or files
 * positions, it can happen that this influences the rest of the descriptor that point to the
 * same file. Thus, a special care needs to be taken that the data in descriptors is correct.
 * 
 * @param <E>
 *            Type of the objects are wanted.
 * @param cmrRepositoryDefinition
 *            {@link CmrRepositoryDefinition}.
 * @param storageData
 *            {@link StorageData} that points to the wanted storage.
 * @param descriptors
 *            Descriptors.
 * @return List of objects in the supplied generic type. Note that if the data described in the
 *         descriptor is not of a supplied generic type, there will be a casting exception
 *         thrown.
 * @throws SerializationException
 *             If {@link SerializationException} occurs.
 * @throws IOException
 *             If {@link IOException} occurs.
 */
@SuppressWarnings("unchecked")
public <E extends DefaultData> List<E> getDataViaHttp(CmrRepositoryDefinition cmrRepositoryDefinition,
        IStorageData storageData, List<IStorageDescriptor> descriptors)
        throws IOException, SerializationException {
    Map<Integer, List<IStorageDescriptor>> separateFilesGroup = createFilesGroup(descriptors);
    List<E> receivedData = new ArrayList<E>();
    String serverUri = getServerUri(cmrRepositoryDefinition);

    HttpClient httpClient = new DefaultHttpClient();
    for (Map.Entry<Integer, List<IStorageDescriptor>> entry : separateFilesGroup.entrySet()) {
        HttpGet httpGet = new HttpGet(
                serverUri + storageManager.getHttpFileLocation(storageData, entry.getKey()));
        StringBuilder rangeHeader = new StringBuilder("bytes=");

        RangeDescriptor rangeDescriptor = null;
        for (IStorageDescriptor descriptor : entry.getValue()) {
            if (null == rangeDescriptor) {
                rangeDescriptor = new RangeDescriptor(descriptor);
            } else {
                if (rangeDescriptor.getEnd() + 1 == descriptor.getPosition()) {
                    rangeDescriptor.setEnd(descriptor.getPosition() + descriptor.getSize() - 1);
                } else {
                    rangeHeader.append(rangeDescriptor.toString());
                    rangeHeader.append(',');
                    rangeDescriptor = new RangeDescriptor(descriptor);
                }
            }
        }
        rangeHeader.append(rangeDescriptor);

        httpGet.addHeader("Range", rangeHeader.toString());
        ISerializer serializer = null;
        try {
            serializer = serializerQueue.take();
        } catch (InterruptedException e) {
            Thread.interrupted();
        }
        InputStream inputStream = null;
        Input input = null;
        try {
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (MultipartEntityUtil.isMultipart(entity)) {
                inputStream = entity.getContent();
                @SuppressWarnings("deprecation")
                // all non-deprecated constructors have default modifier
                MultipartStream multipartStream = new MultipartStream(inputStream,
                        MultipartEntityUtil.getBoundary(entity).getBytes());
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                boolean nextPart = multipartStream.skipPreamble();
                while (nextPart) {
                    multipartStream.readHeaders();
                    multipartStream.readBodyData(byteArrayOutputStream);
                    input = new Input(byteArrayOutputStream.toByteArray());
                    while (KryoUtil.hasMoreBytes(input)) {
                        Object object = serializer.deserialize(input);
                        E element = (E) object;
                        receivedData.add(element);
                    }
                    nextPart = multipartStream.readBoundary();
                }
            } else {
                // when kryo changes the visibility of optional() method, we can really stream
                input = new Input(EntityUtils.toByteArray(entity));
                while (KryoUtil.hasMoreBytes(input)) {
                    Object object = serializer.deserialize(input);
                    E element = (E) object;
                    receivedData.add(element);
                }
            }
        } finally {
            if (null != inputStream) {
                inputStream.close();
            }
            if (null != input) {
                input.close();
            }
            serializerQueue.add(serializer);
        }
    }
    return receivedData;
}

From source file:be.integrationarchitects.web.dragdrop.servlet.impl.DragDropServlet.java

protected void prepareMultiPartFile(DragDropMimeHandlerRequest mimeRequest, File f,
        HttpServletResponse response) throws IOException {
    logger.logTrace("process multipart");
    mimeRequest.setFiles(new ArrayList<DragDropMimeFile>());

    PrintWriter out = response.getWriter();

    FileInputStream fin = new FileInputStream(f);

    int partcount = 0;

    try {/*  w w w.  j  av  a 2s  . c  om*/

        MultipartStream multipartStream = new MultipartStream(fin, mimeRequest.getMimeBoundary().getBytes(),
                1000, null);
        boolean nextPart = multipartStream.skipPreamble();
        int filecount = 0;
        while (nextPart) {
            partcount++;
            String header = multipartStream.readHeaders();
            logger.logTrace("PART HEADER:" + header);
            if (header.startsWith("Content-Disposition: form-data")) {
                filecount++;

                //params
                Map<String, String> params = utils.getFilePartParams(header);

                //also save request params to .inf file
                for (String key : mimeRequest.getRequestParams().keySet()) {
                    params.put(key, mimeRequest.getRequestParams().get(key));
                }
                params.put("user", mimeRequest.getCtx().getUser());

                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                bout.write(params.toString().getBytes());
                File f2 = new File(cfg.getFolder(), f.getName() + "." + filecount + ".inf");
                FileOutputStream output = new FileOutputStream(f2);
                output.write(bout.toByteArray());
                output.close();

                //file
                File f3 = new File(cfg.getFolder(), f.getName() + "." + filecount + ".dat");
                FileOutputStream output3 = new FileOutputStream(f3);
                multipartStream.readBodyData(output3);
                output3.close();
                String hash = utils.getHash(f3);
                logger.logTrace("hash:" + hash + ":" + params.get("md5") + ", equals:"
                        + hash.trim().equalsIgnoreCase(params.get("md5").trim()));
                if (cfg.checkHash()) {
                    if (!hash.trim().equalsIgnoreCase(params.get("md5").trim())) {
                        logger.logError("Invalid hash:" + params.get("md5"), null);
                        throw new IllegalArgumentException("Invalid hash:" + params.get("md5"));
                    }
                }

                if (cfg.getMaxFileSizePerFile() > 0 && f3.length() > cfg.getMaxFileSizePerFile()) {
                    logger.logError("File too big hash:" + f3.length(), null);
                } else {
                    DragDropMimeFile tf = new DragDropMimeFile();
                    tf.setFile(f3);
                    tf.setHash(hash);
                    tf.setPrepareParams(params);
                    tf.setFileName(params.get("filename"));
                    mimeRequest.getFiles().add(tf);
                }
            } else {
                System.err.println("skipping part:" + header);
                multipartStream.readBodyData(new ByteArrayOutputStream());

            }

            nextPart = multipartStream.readBoundary();
        }
        // f.delete();//delete multipart upload file since already splitted in info and data
    } catch (MultipartStream.MalformedStreamException e) {
        logger.logError(e.getMessage(), e);
        e.printStackTrace();
        throw new IllegalArgumentException(e);
    } catch (IOException e) {
        logger.logError(e.getMessage(), e);
        e.printStackTrace();
        throw new IllegalArgumentException(e);

    }

    if (cfg.getHandler() != null) {
        DragDropMimeHandlerResponse mimeResponse = cfg.getHandler().prepare(mimeRequest);
        if (mimeResponse.getResponseContent() != null) {
            logger.logTrace("setting html response content...");
            response.setContentType(mimeResponse.getResponseContentType().getMimeType());
            out.println(mimeResponse.getResponseContent());
        } else {

            //TODO check redirects

        }
        //handler.handleFile(f2,params,reqparams,reqheaders);
    }

}

From source file:com.rhfung.P2PDictionary.DataConnection.java

private void HandleReadPost(String contentLocation, String contentType, String accepts, ListInt senders,
        byte[] payload) {
    if (contentLocation.equals(ADDENTRY_NS_API) || contentLocation.equals(ADDENTRY_NS_BYTES_API)
            || contentLocation.equals(ADDENTRY_NS_MIME_API)) {
        boolean sendMime = contentLocation.equals(ADDENTRY_NS_MIME_API);

        String boundary = getBoundaryFromContentType(contentType);
        if (boundary == null) {
            WriteDebug("Cannot identify boundary from POST");
            return;
        }/*from ww  w . j a  v a 2 s .  c om*/

        String filename = "content";
        try {

            MultipartStream multipartStream = new MultipartStream(new ByteArrayInputStream(payload),
                    boundary.getBytes());
            boolean nextPart = multipartStream.skipPreamble();

            while (nextPart) {

                String header = multipartStream.readHeaders();
                Hashtable<String, String> hdr = ReadHeaders(
                        new InputStreamReader(new ByteArrayInputStream(header.getBytes())));
                String val = hdr.get("Content-Disposition");

                if (val != null) {
                    final String FILENAME = "filename=\"";
                    int filenameIdx = val.indexOf(FILENAME);
                    filename = val.substring(filenameIdx + FILENAME.length(),
                            val.indexOf("\"", filenameIdx + FILENAME.length()));

                }

                // process headers
                // create some output stream
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                multipartStream.readBodyData(output);
                if (sendMime) {
                    String valType = hdr.get("Content-Type");
                    controller.put(filename, new MIMEByteObject(valType, output.toByteArray()));
                }

                else {
                    controller.put(filename, output.toByteArray());
                }
                nextPart = multipartStream.readBoundary();
            }

            // only reply back with ONE file uploaded
            MemoryStream bufferedOutput = new MemoryStream();
            String key = controller.getFullKey(filename);
            dataLock.readLock().lock();
            try {
                DataEntry entry = data.get(key);
                WriteResponseInfo(bufferedOutput.createStreamWriter(), ADDENTRY_NS_API, entry);
                synchronized (sendBuffer) {
                    sendBuffer.add(bufferedOutput);
                }
            } finally {
                dataLock.readLock().unlock();
            }

        } catch (Exception e) {
            MemoryStream bufferedOutput = new MemoryStream();
            WriteErrorNotFound(bufferedOutput.createStreamWriter(), "GET", contentLocation, 500);
            synchronized (sendBuffer) {
                sendBuffer.add(bufferedOutput);
            }
        }

    } else {
        MemoryStream bufferedOutput = new MemoryStream();
        WriteErrorNotFound(bufferedOutput.createStreamWriter(), "GET", contentLocation, 501);
        synchronized (sendBuffer) {
            sendBuffer.add(bufferedOutput);
        }
    }
}

From source file:com.oneis.appserver.FileUploads.java

/**
 * Handle the incoming stream, processing files.
 *///from  w w  w  .  j a  va 2  s.  com
public void performUploads(HttpServletRequest request) throws IOException, UserReportableFileUploadException {
    instructionsRequired = false;

    // Need a parser for parameters
    ParameterParser paramParser = new ParameterParser();
    paramParser.setLowerCaseNames(true);

    // Thread ID is used for temporary filenames
    long threadId = Thread.currentThread().getId();
    int fileId = 0;

    InputStream requestBody = request.getInputStream();

    MultipartStream multipart = new MultipartStream(requestBody, boundary);
    multipart.setHeaderEncoding("UTF-8");

    boolean nextPart = multipart.skipPreamble();
    while (nextPart) {
        String headerPart = multipart.readHeaders();

        // Parse headers, splitting out the bits we're interested in
        String name = null;
        String filename = null;
        Map<String, String> itemHeaders = HeaderParser.parse(headerPart, true /* keys to lower case */);
        String mimeType = itemHeaders.get("content-type");
        String disposition = itemHeaders.get("content-disposition");
        if (disposition != null) {
            Map disp = paramParser.parse(disposition, PARAMPARSER_SEPERATORS);
            name = (String) disp.get("name");
            filename = (String) disp.get("filename");
        }

        // Set a default MIME type if none is given (Safari may omit it)
        if (mimeType == null) {
            mimeType = "application/octet-stream";
        }

        // Remove the path prefix from IE (before the length check)
        if (filename != null) {
            int slash1 = filename.lastIndexOf('/');
            int slash2 = filename.lastIndexOf('\\');
            int slash = (slash1 > slash2) ? slash1 : slash2;
            if (slash != -1) {
                filename = filename.substring(slash + 1);
            }
        }

        boolean isFile = (filename != null && filename.length() > 0);

        if (isFile) {
            // File - did the app server give instructions about it?
            Upload upload = files.get(name);
            if (upload == null) {
                // Looks like a file, but the app server didn't say it should be. Give up.
                throw new UserReportableFileUploadException(
                        "A file was uploaded, but it was not expected by the application. Field name: '" + name
                                + "'");
            }

            String dir = upload.getSaveDirectory();
            if (dir == null) {
                // Ooops.
                throw new IOException("app server didn't specify dir");
            }

            // Generate a temporary filename
            File outFile = null;
            do {
                outFile = new File(String.format("%1$s/u%2$d.%3$d", dir, threadId, fileId++));
            } while (!outFile.createNewFile());

            OutputStream outStream = new FileOutputStream(outFile);

            // Decorate with a digest?
            MessageDigest digest = null;
            if (upload.getDigestName() != null) {
                try {
                    digest = MessageDigest.getInstance(upload.getDigestName());
                } catch (java.security.NoSuchAlgorithmException e) {
                    digest = null;
                }
                if (digest != null) {
                    outStream = new DigestOutputStream(outStream, digest);
                }
            }

            // Decorate with a decompressor?
            String filterName = upload.getFilterName();
            if (filterName != null && filterName.equals("inflate")) {
                outStream = new InflaterOutputStream(outStream);
            }

            multipart.readBodyData(outStream);
            outStream.close();

            String digestAsString = null;
            if (digest != null) {
                String.format("%1$s_digest", name);
                digestAsString = StringUtils.bytesToHex(digest.digest());
            }

            upload.setUploadDetails(outFile.getPath(), digestAsString, mimeType, filename, outFile.length());
        } else {
            // Normal field - just absorb a few k max of it, turn it into a field
            ByteArrayOutputStream value = new ByteArrayOutputStream();
            // TODO: Limit request size as a whole, not on a per-parameter basis.
            multipart.readBodyData(new LimitedFilterOutputStream(value, MAX_TEXT_PARAMETER_LENGTH));
            params.put(name, value.toString("UTF-8"));
        }

        nextPart = multipart.readBoundary();
    }
}

From source file:io.swagger.inflector.controllers.SwaggerOperationController.java

@Override
public Response apply(ContainerRequestContext ctx) {
    List<Parameter> parameters = operation.getParameters();
    final RequestContext requestContext = createContext(ctx);

    String path = ctx.getUriInfo().getPath();
    Map<String, Map<String, String>> formMap = new HashMap<String, Map<String, String>>();
    Map<String, File> inputStreams = new HashMap<String, File>();

    Object[] args = new Object[parameters.size() + 1];
    if (parameters != null) {
        int i = 0;

        args[i] = requestContext;//from   w w  w .  ja v a 2  s . c om
        i += 1;
        List<ValidationMessage> missingParams = new ArrayList<ValidationMessage>();
        UriInfo uri = ctx.getUriInfo();
        String formDataString = null;
        String[] parts = null;
        Set<String> existingKeys = new HashSet<String>();

        for (Iterator<String> x = uri.getQueryParameters().keySet().iterator(); x.hasNext();) {
            existingKeys.add(x.next() + ": qp");
        }
        for (Iterator<String> x = uri.getPathParameters().keySet().iterator(); x.hasNext();) {
            existingKeys.add(x.next() + ": pp");
        }
        for (Iterator<String> x = ctx.getHeaders().keySet().iterator(); x.hasNext();) {
            String key = x.next();
            //              if(!commonHeaders.contains(key))
            //                existingKeys.add(key);
        }
        MediaType mt = requestContext.getMediaType();

        for (Parameter p : parameters) {
            Map<String, String> headers = new HashMap<String, String>();
            String name = null;

            if (p instanceof FormParameter) {
                if (formDataString == null) {
                    // can only read stream once
                    if (mt.isCompatible(MediaType.MULTIPART_FORM_DATA_TYPE)) {
                        // get the boundary
                        String boundary = mt.getParameters().get("boundary");

                        if (boundary != null) {
                            try {
                                InputStream output = ctx.getEntityStream();

                                MultipartStream multipartStream = new MultipartStream(output,
                                        boundary.getBytes());
                                boolean nextPart = multipartStream.skipPreamble();
                                while (nextPart) {
                                    String header = multipartStream.readHeaders();
                                    // process headers
                                    if (header != null) {
                                        CSVFormat format = CSVFormat.DEFAULT.withDelimiter(';')
                                                .withRecordSeparator("=");

                                        Iterable<CSVRecord> records = format.parse(new StringReader(header));
                                        for (CSVRecord r : records) {
                                            for (int j = 0; j < r.size(); j++) {
                                                String string = r.get(j);

                                                Iterable<CSVRecord> outerString = CSVFormat.DEFAULT
                                                        .withDelimiter('=').parse(new StringReader(string));
                                                for (CSVRecord outerKvPair : outerString) {
                                                    if (outerKvPair.size() == 2) {
                                                        String key = outerKvPair.get(0).trim();
                                                        String value = outerKvPair.get(1).trim();
                                                        if ("name".equals(key)) {
                                                            name = value;
                                                        }
                                                        headers.put(key, value);
                                                    } else {
                                                        Iterable<CSVRecord> innerString = CSVFormat.DEFAULT
                                                                .withDelimiter(':')
                                                                .parse(new StringReader(string));
                                                        for (CSVRecord innerKVPair : innerString) {
                                                            if (innerKVPair.size() == 2) {
                                                                String key = innerKVPair.get(0).trim();
                                                                String value = innerKVPair.get(1).trim();
                                                                if ("name".equals(key)) {
                                                                    name = value;
                                                                }
                                                                headers.put(key, value);
                                                            }
                                                        }
                                                    }
                                                }
                                                if (name != null) {
                                                    formMap.put(name, headers);
                                                }
                                            }
                                        }
                                    }
                                    String filename = extractFilenameFromHeaders(headers);
                                    if (filename != null) {
                                        try {
                                            File file = new File(Files.createTempDir(), filename);
                                            file.deleteOnExit();
                                            file.getParentFile().deleteOnExit();
                                            FileOutputStream fo = new FileOutputStream(file);
                                            multipartStream.readBodyData(fo);
                                            inputStreams.put(name, file);
                                        } catch (Exception e) {
                                            LOGGER.error("Failed to extract uploaded file", e);
                                        }
                                    } else {
                                        ByteArrayOutputStream bo = new ByteArrayOutputStream();
                                        multipartStream.readBodyData(bo);
                                        String value = bo.toString();
                                        headers.put(name, value);
                                    }
                                    if (name != null) {
                                        formMap.put(name, headers);
                                    }
                                    headers = new HashMap<>();
                                    name = null;
                                    nextPart = multipartStream.readBoundary();
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        try {
                            formDataString = IOUtils.toString(ctx.getEntityStream(), "UTF-8");
                            parts = formDataString.split("&");

                            for (String part : parts) {
                                String[] kv = part.split("=");
                                existingKeys.add(kv[0] + ": fp");
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        for (Parameter parameter : parameters) {
            String in = parameter.getIn();
            Object o = null;

            try {
                if ("formData".equals(in)) {
                    SerializableParameter sp = (SerializableParameter) parameter;
                    String name = parameter.getName();
                    if (mt.isCompatible(MediaType.MULTIPART_FORM_DATA_TYPE)) {
                        // look in the form map
                        Map<String, String> headers = formMap.get(name);
                        if (headers != null && headers.size() > 0) {
                            if ("file".equals(sp.getType())) {
                                o = inputStreams.get(name);
                            } else {
                                Object obj = headers.get(parameter.getName());
                                if (obj != null) {
                                    JavaType jt = parameterClasses[i];
                                    Class<?> cls = jt.getRawClass();

                                    List<String> os = Arrays.asList(obj.toString());
                                    try {
                                        o = validator.convertAndValidate(os, parameter, cls, definitions);
                                    } catch (ConversionException e) {
                                        missingParams.add(e.getError());
                                    } catch (ValidationException e) {
                                        missingParams.add(e.getValidationMessage());
                                    }
                                }
                            }
                        }
                    } else {
                        if (formDataString != null) {
                            for (String part : parts) {
                                String[] kv = part.split("=");
                                if (kv != null) {
                                    if (kv.length > 0) {
                                        existingKeys.remove(kv[0] + ": fp");
                                    }
                                    if (kv.length == 2) {
                                        // TODO how to handle arrays here?
                                        String key = kv[0];
                                        try {
                                            String value = URLDecoder.decode(kv[1], "utf-8");
                                            if (parameter.getName().equals(key)) {
                                                JavaType jt = parameterClasses[i];
                                                Class<?> cls = jt.getRawClass();
                                                try {
                                                    o = validator.convertAndValidate(Arrays.asList(value),
                                                            parameter, cls, definitions);
                                                } catch (ConversionException e) {
                                                    missingParams.add(e.getError());
                                                } catch (ValidationException e) {
                                                    missingParams.add(e.getValidationMessage());
                                                }
                                            }
                                        } catch (UnsupportedEncodingException e) {
                                            LOGGER.error("unable to decode value for " + key);
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    try {
                        String paramName = parameter.getName();
                        if ("query".equals(in)) {
                            existingKeys.remove(paramName + ": qp");
                        }
                        if ("path".equals(in)) {
                            existingKeys.remove(paramName + ": pp");
                        }
                        JavaType jt = parameterClasses[i];
                        Class<?> cls = jt.getRawClass();
                        if ("body".equals(in)) {
                            if (ctx.hasEntity()) {
                                BodyParameter body = (BodyParameter) parameter;
                                o = EntityProcessorFactory.readValue(ctx.getMediaType(), ctx.getEntityStream(),
                                        cls);
                                if (o != null) {
                                    validate(o, body.getSchema(), SchemaValidator.Direction.INPUT);
                                }
                            } else if (parameter.getRequired()) {
                                ValidationException e = new ValidationException();
                                e.message(new ValidationMessage()
                                        .message("The input body `" + paramName + "` is required"));
                                throw e;
                            }
                        }
                        if ("query".equals(in)) {
                            o = validator.convertAndValidate(uri.getQueryParameters().get(parameter.getName()),
                                    parameter, cls, definitions);
                        } else if ("path".equals(in)) {
                            o = validator.convertAndValidate(uri.getPathParameters().get(parameter.getName()),
                                    parameter, cls, definitions);
                        } else if ("header".equals(in)) {
                            o = validator.convertAndValidate(ctx.getHeaders().get(parameter.getName()),
                                    parameter, cls, definitions);
                        }
                    } catch (ConversionException e) {
                        missingParams.add(e.getError());
                    } catch (ValidationException e) {
                        missingParams.add(e.getValidationMessage());
                    }
                }
            } catch (NumberFormatException e) {
                LOGGER.error("Couldn't find " + parameter.getName() + " (" + in + ") to " + parameterClasses[i],
                        e);
            }

            args[i] = o;
            i += 1;
        }
        if (existingKeys.size() > 0) {
            LOGGER.debug("unexpected keys: " + existingKeys);
        }
        if (missingParams.size() > 0) {
            StringBuilder builder = new StringBuilder();
            builder.append("Input error");
            if (missingParams.size() > 1) {
                builder.append("s");
            }
            builder.append(": ");
            int count = 0;
            for (ValidationMessage message : missingParams) {
                if (count > 0) {
                    builder.append(", ");
                }
                if (message != null && message.getMessage() != null) {
                    builder.append(message.getMessage());
                } else {
                    builder.append("no additional input");
                }
                count += 1;
            }
            int statusCode = config.getInvalidRequestStatusCode();
            ApiError error = new ApiError().code(statusCode).message(builder.toString());
            throw new ApiException(error);
        }
    }
    try {
        if (method != null) {
            LOGGER.info("calling method " + method + " on controller " + this.controller + " with args "
                    + Arrays.toString(args));
            try {
                Object response = method.invoke(controller, args);
                if (response instanceof ResponseContext) {
                    ResponseContext wrapper = (ResponseContext) response;
                    ResponseBuilder builder = Response.status(wrapper.getStatus());

                    // response headers
                    for (String key : wrapper.getHeaders().keySet()) {
                        List<String> v = wrapper.getHeaders().get(key);
                        if (v.size() == 1) {
                            builder.header(key, v.get(0));
                        } else {
                            builder.header(key, v);
                        }
                    }

                    // entity
                    if (wrapper.getEntity() != null) {
                        builder.entity(wrapper.getEntity());
                        // content type
                        if (wrapper.getContentType() != null) {
                            builder.type(wrapper.getContentType());
                        } else {
                            final ContextResolver<ContentTypeSelector> selector = providersProvider.get()
                                    .getContextResolver(ContentTypeSelector.class, MediaType.WILDCARD_TYPE);
                            if (selector != null) {
                                selector.getContext(getClass()).apply(ctx.getAcceptableMediaTypes(), builder);
                            }
                        }

                        if (operation.getResponses() != null) {
                            String responseCode = String.valueOf(wrapper.getStatus());
                            io.swagger.models.Response responseSchema = operation.getResponses()
                                    .get(responseCode);
                            if (responseSchema == null) {
                                // try default response schema
                                responseSchema = operation.getResponses().get("default");
                            }
                            if (responseSchema != null && responseSchema.getSchema() != null) {
                                validate(wrapper.getEntity(), responseSchema.getSchema(),
                                        SchemaValidator.Direction.OUTPUT);
                            } else {
                                LOGGER.debug(
                                        "no response schema for code " + responseCode + " to validate against");
                            }
                        }
                    }

                    return builder.build();
                }
                return Response.ok().entity(response).build();
            } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
                for (Throwable cause = e.getCause(); cause != null;) {
                    if (cause instanceof ApiException) {
                        throw (ApiException) cause;
                    }
                    final Throwable next = cause.getCause();
                    cause = next == cause || next == null ? null : next;
                }
                throw new ApiException(ApiErrorUtils.createInternalError(), e);
            }
        }
        Map<String, io.swagger.models.Response> responses = operation.getResponses();
        if (responses != null) {
            String[] keys = new String[responses.keySet().size()];
            Arrays.sort(responses.keySet().toArray(keys));
            int code = 0;
            String defaultKey = null;
            for (String key : keys) {
                if (key.startsWith("2")) {
                    defaultKey = key;
                    code = Integer.parseInt(key);
                    break;
                }
                if ("default".equals(key)) {
                    defaultKey = key;
                    code = 200;
                    break;
                }
                if (key.startsWith("3")) {
                    // we use the 3xx responses as defaults
                    defaultKey = key;
                    code = Integer.parseInt(key);
                }
            }

            if (defaultKey != null) {
                ResponseBuilder builder = Response.status(code);
                io.swagger.models.Response response = responses.get(defaultKey);

                if (response.getHeaders() != null && response.getHeaders().size() > 0) {
                    for (String key : response.getHeaders().keySet()) {
                        Property headerProperty = response.getHeaders().get(key);
                        Object output = ExampleBuilder.fromProperty(headerProperty, definitions);
                        if (output instanceof ArrayExample) {
                            output = ((ArrayExample) output).asString();
                        } else if (output instanceof ObjectExample) {
                            LOGGER.debug(
                                    "not serializing output example, only primitives or arrays of primitives are supported");
                        } else {
                            output = ((Example) output).asString();
                        }
                        builder.header(key, output);
                    }
                }

                Map<String, Object> examples = response.getExamples();
                if (examples != null) {
                    for (MediaType mediaType : requestContext.getAcceptableMediaTypes()) {
                        for (String key : examples.keySet()) {
                            if (MediaType.valueOf(key).isCompatible(mediaType)) {
                                builder.entity(examples.get(key)).type(mediaType);

                                return builder.build();
                            }
                        }
                    }
                }

                Object output = ExampleBuilder.fromProperty(response.getSchema(), definitions);

                if (output != null) {
                    ResponseContext resp = new ResponseContext().entity(output);
                    setContentType(requestContext, resp, operation);
                    builder.entity(output);
                    if (resp.getContentType() != null) {
                        // this comes from the operation itself
                        builder.type(resp.getContentType());
                    } else {
                        // get acceptable content types
                        List<EntityProcessor> processors = EntityProcessorFactory.getProcessors();

                        MediaType responseMediaType = null;

                        // take first compatible one
                        for (EntityProcessor processor : processors) {
                            if (responseMediaType != null) {
                                break;
                            }
                            for (MediaType mt : requestContext.getAcceptableMediaTypes()) {
                                LOGGER.debug("checking type " + mt.toString() + " against "
                                        + processor.getClass().getName());
                                if (processor.supports(mt)) {
                                    builder.type(mt);
                                    responseMediaType = mt;
                                    break;
                                }
                            }
                        }

                        if (responseMediaType == null) {
                            // no match based on Accept header, use first processor in list
                            for (EntityProcessor processor : processors) {
                                List<MediaType> supportedTypes = processor.getSupportedMediaTypes();
                                if (supportedTypes.size() > 0) {
                                    builder.type(supportedTypes.get(0));
                                    break;
                                }
                            }
                        }
                    }

                    builder.entity(output);
                }
                return builder.build();
            } else {
                LOGGER.debug("no response type to map to, assume 200");
                code = 200;
            }
            return Response.status(code).build();
        }
        return Response.ok().build();
    } finally {
        for (String key : inputStreams.keySet()) {
            File file = inputStreams.get(key);
            if (file != null) {
                LOGGER.debug("deleting file " + file.getPath());
                file.delete();
            }
        }
    }
}