Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * JBoss, Home of Professional Open Source.
   * Copyright 2014 Red Hat, Inc., and individual contributors
   * as indicated by the @author tags.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
  *     http://www.apache.org/licenses/LICENSE-2.0
  *
  *  Unless required by applicable law or agreed to in writing, software
  *  distributed under the License is distributed on an "AS IS" BASIS,
  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  */
 
 package io.undertow.server.handlers.form;
 
 
 import java.io.File;
 import java.util.List;

Author(s):
Stuart Douglas
 
 
     public static final String MULTIPART_FORM_DATA = "multipart/form-data";
 
     private Executor executor;
 
     private File tempFileLocation;
 
     private String defaultEncoding = "ISO-8859-1";
 
     private long maxIndividualFileSize = -1;
 
     public MultiPartParserDefinition() {
          = new File(System.getProperty("java.io.tmpdir"));
     }
 
     public MultiPartParserDefinition(final File tempDir) {
          = tempDir;
     }
 
     @Override
     public FormDataParser create(final HttpServerExchange exchange) {
         String mimeType = exchange.getRequestHeaders().getFirst(.);
         if (mimeType != null && mimeType.startsWith()) {
             String boundary = Headers.extractTokenFromHeader(mimeType"boundary");
             if (boundary == null) {
                 ..debugf("Could not find boundary in multipart request with ContentType: %s, multipart data will not be available"mimeType);
                 return null;
             }
             final MultiPartUploadHandler parser = new MultiPartUploadHandler(exchangeboundary);
             exchange.addExchangeCompleteListener(new ExchangeCompletionListener() {
                 @Override
                 public void exchangeEvent(final HttpServerExchange exchangefinal NextListener nextListener) {
                     IoUtils.safeClose(parser);
                     nextListener.proceed();
                 }
             });
             return parser;
 
         }
         return null;
     }
 
     public Executor getExecutor() {
         return ;
     }
 
     public MultiPartParserDefinition setExecutor(final Executor executor) {
        this. = executor;
        return this;
    }
    public File getTempFileLocation() {
        return ;
    }
    public MultiPartParserDefinition setTempFileLocation(File tempFileLocation) {
        this. = tempFileLocation;
        return this;
    }
    public String getDefaultEncoding() {
        return ;
    }
    public MultiPartParserDefinition setDefaultEncoding(final String defaultEncoding) {
        this. = defaultEncoding;
        return this;
    }
    public long getMaxIndividualFileSize() {
        return ;
    }
    public void setMaxIndividualFileSize(final long maxIndividualFileSize) {
        this. = maxIndividualFileSize;
    }
    private final class MultiPartUploadHandler implements FormDataParserMultipartParser.PartHandler {
        private final HttpServerExchange exchange;
        private final FormData data;
        private final String boundary;
        private final List<FilecreatedFiles = new ArrayList<>();
        private final long maxIndividualFileSize;
        private String defaultEncoding;
        private final ByteArrayOutputStream contentBytes = new ByteArrayOutputStream();
        private String currentName;
        private String fileName;
        private File file;
        private FileChannel fileChannel;
        private HeaderMap headers;
        private HttpHandler handler;
        private long currentFileSize;
        private final MultipartParser.ParseState parser;
        private MultiPartUploadHandler(final HttpServerExchange exchangefinal String boundaryfinal long maxIndividualFileSizefinal String defaultEncoding) {
            this. = exchange;
            this. = boundary;
            this. = maxIndividualFileSize;
            this. = defaultEncoding;
            this. = new FormData(exchange.getConnection().getUndertowOptions().get(., 1000));
            this. = MultipartParser.beginParse(exchange.getConnection().getBufferPool(), thisboundary.getBytes(), exchange.getRequestCharset());
        }
        @Override
        public void parse(final HttpHandler handlerthrows Exception {
            if (.getAttachment() != null) {
                handler.handleRequest();
                return;
            }
            this. = handler;
            //we need to delegate to a thread pool
            //as we parse with blocking operations
            StreamSourceChannel requestChannel = .getRequestChannel();
            if (requestChannel == null) {
                throw new IOException(..requestChannelAlreadyProvided());
            }
            if ( == null) {
                .dispatch(new NonBlockingParseTask(.getConnection().getWorker(), requestChannel));
            } else {
                .dispatch(new NonBlockingParseTask(requestChannel));
            }
        }
        @Override
        public FormData parseBlocking() throws IOException {
            final FormData existing = .getAttachment();
            if (existing != null) {
                return existing;
            }
            final MultipartParser.ParseState parser = MultipartParser.beginParse(.getConnection().getBufferPool(), this.getBytes(), .getRequestCharset());
            InputStream inputStream = .getInputStream();
            if (inputStream == null) {
                throw new IOException(..requestChannelAlreadyProvided());
            }
            byte[] buf = new byte[1024];
            try {
                while (true) {
                    int c = inputStream.read(buf);
                    if (c == -1) {
                        if (parser.isComplete()) {
                            break;
                        } else {
                            throw ..connectionTerminatedReadingMultiPartData();
                        }
                    } else if (c != 0) {
                        parser.parse(ByteBuffer.wrap(buf, 0, c));
                    }
                }
                .putAttachment();
            } catch (MalformedMessageException e) {
                throw new IOException(e);
            }
            return .getAttachment();
        }
        @Override
        public void beginPart(final HeaderMap headers) {
            this. = 0;
            this. = headers;
            final String disposition = headers.getFirst(.);
            if (disposition != null) {
                if (disposition.startsWith("form-data")) {
                     = Headers.extractQuotedValueFromHeader(disposition"name");
                     = Headers.extractQuotedValueFromHeader(disposition"filename");
                    if ( != null) {
                        try {
                             = File.createTempFile("undertow""upload");
                            .add();
                             = .getConnection().getWorker().getXnio().openFile(.);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }
        @Override
        public void data(final ByteBuffer bufferthrows IOException {
            this. += buffer.remaining();
            if (this. > 0 && this. > this.) {
                throw ..maxFileSizeExceeded(this.);
            }
            if ( == null) {
                while (buffer.hasRemaining()) {
                    .write(buffer.get());
                }
            } else {
                .write(buffer);
            }
        }
        @Override
        public void endPart() {
            if ( != null) {
                .add();
                 = null;
                try {
                    .close();
                     = null;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else {
                try {
                    String charset = ;
                    String contentType = .getFirst(.);
                    if (contentType != null) {
                        String cs = Headers.extractQuotedValueFromHeader(contentType"charset");
                        if (cs != null) {
                            charset = cs;
                        }
                    }
                    .add(new String(.toByteArray(), charset), );
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
                .reset();
            }
        }
        public List<FilegetCreatedFiles() {
            return ;
        }
        @Override
        public void close() throws IOException {
            //we have to dispatch this, as it may result in file IO
            final List<Filefiles = new ArrayList<>(getCreatedFiles());
            .getConnection().getWorker().execute(new Runnable() {
                @Override
                public void run() {
                    for (final File file : files) {
                        if (file.exists()) {
                            if (!file.delete()) {
                                ..cannotRemoveUploadedFile(file);
                            }
                        }
                    }
                }
            });
        }
        @Override
        public void setCharacterEncoding(final String encoding) {
            this. = encoding;
        }
        private final class NonBlockingParseTask implements Runnable {
            private final Executor executor;
            private final StreamSourceChannel requestChannel;
            private NonBlockingParseTask(Executor executorStreamSourceChannel requestChannel) {
                this. = executor;
                this. = requestChannel;
            }
            @Override
            public void run() {
                try {
                    final FormData existing = .getAttachment();
                    if (existing != null) {
                        .dispatch(.);
                        return;
                    }
                    Pooled<ByteBufferpooled = .getConnection().getBufferPool().allocate();
                    try {
                        while (true) {
                            int c = .read(pooled.getResource());
                            if(c == 0) {
                                .getReadSetter().set(new ChannelListener<StreamSourceChannel>() {
                                    @Override
                                    public void handleEvent(StreamSourceChannel channel) {
                                        channel.suspendReads();
                                        .execute(NonBlockingParseTask.this);
                                    }
                                });
                                .resumeReads();
                                return;
                            } else if (c == -1) {
                                if (.isComplete()) {
                                    .putAttachment();
                                    .dispatch(.);
                                } else {
                                    ..ioException(..connectionTerminatedReadingMultiPartData());
                                    .setResponseCode(500);
                                    .endExchange();
                                }
                                return;
                            } else {
                                pooled.getResource().flip();
                                .parse(pooled.getResource());
                                pooled.getResource().compact();
                            }
                        }
                    } catch (MalformedMessageException e) {
                        ..ioException(e);
                        .setResponseCode(500);
                        .endExchange();
                    } finally {
                        pooled.free();
                    }
                } catch (Throwable e) {
                    ..debug("Exception parsing data"e);
                    .setResponseCode(500);
                    .endExchange();
                }
            }
        }
     }
New to GrepCode? Check out our FAQ X