Example usage for org.apache.commons.fileupload.util Streams asString

List of usage examples for org.apache.commons.fileupload.util Streams asString

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.util Streams asString.

Prototype

public static String asString(InputStream pStream, String pEncoding) throws IOException 

Source Link

Document

This convenience method allows to read a org.apache.commons.fileupload.FileItemStream 's content into a string, using the given character encoding.

Usage

From source file:com.fullmetalgalaxy.server.AccountServlet.java

@Override
protected void doPost(HttpServletRequest p_request, HttpServletResponse p_response)
        throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();
    Map<String, String> params = new HashMap<String, String>();
    boolean isConnexion = false;
    boolean isPassword = false;

    try {/*from  ww w . java 2 s  . co m*/
        // Parse the request
        FileItemIterator iter = upload.getItemIterator(p_request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                if (item.getFieldName().equalsIgnoreCase("connexion")) {
                    isConnexion = true;
                }
                if (item.getFieldName().equalsIgnoreCase("password")) {
                    isPassword = true;
                }
                params.put(item.getFieldName(), Streams.asString(item.openStream(), "UTF-8"));
            }
        }
    } catch (FileUploadException e) {
        log.error(e);
    }

    if (isConnexion) {
        // user try to connect with an FMG account
        boolean isConnected = true;
        isConnected = connectFmgUser(p_request, p_response, params);
        if (isConnected) {
            String continueUrl = params.get("continue");
            if (continueUrl == null) {
                // by default, my games is the default url
                continueUrl = "/gamelist.jsp";
            }
            p_response.sendRedirect(continueUrl);
        }
        return;
    } else if (isPassword) {
        // user ask for his password to be send on his email
        String msg = "";
        FmgDataStore ds = new FmgDataStore(false);
        Query<EbAccount> query = ds.query(EbAccount.class).filter("m_email", params.get("email"));
        QueryResultIterator<EbAccount> it = query.iterator();
        if (!it.hasNext()) {
            msg = "l'adresse mail " + params.get("email") + " n'a pas t trouv";
        } else {
            EbAccount account = it.next();
            if (account.getLastPasswordAsk() != null && account.getLastPasswordAsk()
                    .getTime() > System.currentTimeMillis() - (1000 * 60 * 60 * 24)) {
                msg = "une seule demande par jour";
            } else if (account.getAuthProvider() != AuthProvider.Fmg) {
                msg = "ce compte FMG est associ a un compte google";
            } else {
                // all is ok, send a mail
                new FmgMessage("askPassword").sendEMail(account);

                msg = "un email a t envoy  " + account.getEmail();
                account.setLastPasswordAsk(new Date());
                ds.put(account);
            }
        }
        ds.close();

        p_response.sendRedirect("/password.jsp?msg=" + msg);
        return;
    } else {
        // update or create new account
        String msg = checkParams(params);
        if (msg != null) {
            p_response.sendRedirect("/account.jsp?msg=" + msg);
            return;
        }
        msg = saveAccount(p_request, p_response, params);
        if (msg != null) {
            p_response.sendRedirect("/account.jsp?msg=" + msg);
            return;
        } else {
            if (!Auth.isUserLogged(p_request, p_response)) {
                Auth.connectUser(p_request, params.get("login"));
            }
            if ("0".equalsIgnoreCase(params.get("accountid"))) {
                // return page new games
                p_response.sendRedirect("/gamelist.jsp?tab=0");
            } else {
                // stay editing profile
                p_response.sendRedirect("/profile.jsp?id=" + params.get("accountid"));
            }
            return;
        }
    }

}

From source file:com.fullmetalgalaxy.server.AdminServlet.java

@Override
protected void doPost(HttpServletRequest p_request, HttpServletResponse p_resp)
        throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();
    Map<String, String> params = new HashMap<String, String>();
    ModelFmpInit modelInit = null;//ww  w.j a  v a  2 s.c  o m

    try {
        // Parse the request
        FileItemIterator iter = upload.getItemIterator(p_request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), Streams.asString(item.openStream(), "UTF-8"));
            } else if (item.getFieldName().equalsIgnoreCase("gamefile")) {
                ObjectInputStream in = new ObjectInputStream(item.openStream());
                modelInit = ModelFmpInit.class.cast(in.readObject());
                in.close();
            }
        }
    } catch (FileUploadException e) {
        log.error(e);
    } catch (ClassNotFoundException e2) {
        log.error(e2);
    }

    // import game from file
    if (modelInit != null) {
        // set transient to avoid override data
        modelInit.getGame().setTrancient();

        // search all accounts in database to correct ID
        for (EbRegistration registration : modelInit.getGame().getSetRegistration()) {
            if (registration.haveAccount()) {
                EbAccount account = FmgDataStore.dao().find(EbAccount.class, registration.getAccount().getId());
                if (account == null) {
                    // corresponding account from this player doesn't exist in database
                    try {
                        // try to find corresponding pseudo
                        account = FmgDataStore.dao().query(EbAccount.class).filter("m_compactPseudo ==",
                                ServerUtil.compactTag(registration.getAccount().getPseudo())).get();
                    } catch (Exception e) {
                    }
                }
                registration.setAccount(account);
            }
        }

        // then save game
        FmgDataStore dataStore = new FmgDataStore(false);
        dataStore.put(modelInit.getGame());
        dataStore.close();

    }

}

From source file:com.github.cxt.Myjersey.jerseycore.FileResource.java

@Path("upload2")
@POST//from  w w  w  .j ava  2s  . com
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public String uploadFile(@Context HttpServletRequest request) throws IOException {
    //??,httpclent?
    System.out.println(request.getCharacterEncoding());
    ServletFileUpload upload = new ServletFileUpload();
    upload.setHeaderEncoding(CHARSET);
    try {
        FileItemIterator fileIterator = upload.getItemIterator(request);
        while (fileIterator.hasNext()) {
            FileItemStream item = fileIterator.next();
            InputStream is = item.openStream();
            try {
                if (!item.isFormField()) {
                    String fileName = item.getName();
                    if (fileName == null || fileName.trim().equals("")) {
                        continue;
                    }
                    String name = Calendar.getInstance().getTimeInMillis() + fileName;
                    String path = request.getServletContext().getRealPath("/");
                    path += File.separator + "data" + File.separator + name;
                    File file = new File(path);
                    FileUtils.copyInputStreamToFile(is, file);
                } else {
                    System.out.println(Streams.asString(is, CHARSET));
                }
            } finally {
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException ignore) {
                    }
                }
            }
        }
        return "{\"success\": true}";
    } catch (IOException | FileUploadException e) {
        return "{\"success\": false}";
    }
}

From source file:net.ymate.platform.mvc.web.support.FileUploadHelper.java

/**
 * ???????/*from   www.  ja  va  2 s  .  co  m*/
 * 
 * @param processer
 * @throws IOException 
 * @throws FileUploadException 
 */
private UploadFormWrapper __doUploadFileAsStream(IUploadFileItemProcesser processer)
        throws FileUploadException, IOException {
    ServletFileUpload _upload = new ServletFileUpload();
    if (this.__listener != null) {
        _upload.setProgressListener(this.__listener);
    }
    _upload.setFileSizeMax(this.__fileSizeMax);
    _upload.setSizeMax(this.__sizeMax);
    UploadFormWrapper _form = new UploadFormWrapper();
    Map<String, List<String>> tmpParams = new HashMap<String, List<String>>();
    Map<String, List<UploadFileWrapper>> tmpFiles = new HashMap<String, List<UploadFileWrapper>>();
    //
    FileItemIterator _iter = _upload.getItemIterator(this.__request);
    while (_iter.hasNext()) {
        FileItemStream _item = _iter.next();
        if (_item.isFormField()) {
            List<String> _valueList = tmpParams.get(_item.getFieldName());
            if (_valueList == null) {
                _valueList = new ArrayList<String>();
                tmpParams.put(_item.getFieldName(), _valueList);
            }
            _valueList.add(Streams.asString(_item.openStream(), WebMVC.getConfig().getCharsetEncoding()));
        } else {
            List<UploadFileWrapper> _valueList2 = tmpFiles.get(_item.getFieldName());
            if (_valueList2 == null) {
                _valueList2 = new ArrayList<UploadFileWrapper>();
                tmpFiles.put(_item.getFieldName(), _valueList2);
            }
            // ??
            _valueList2.add(processer.process(_item));
        }
    }
    //
    for (Entry<String, List<String>> entry : tmpParams.entrySet()) {
        String key = entry.getKey();
        List<String> value = entry.getValue();
        _form.getFieldMap().put(key, value.toArray(new String[value.size()]));
    }
    for (Entry<String, List<UploadFileWrapper>> entry : tmpFiles.entrySet()) {
        String key = entry.getKey();
        _form.getFileMap().put(key, entry.getValue().toArray(new UploadFileWrapper[entry.getValue().size()]));
    }
    return _form;
}

From source file:net.ymate.platform.webmvc.util.FileUploadHelper.java

/**
 * ???????//  w  w w. jav a 2 s . co m
 *
 * @param processer ?
 * @throws FileUploadException ?
 * @throws IOException         ?
 */
private UploadFormWrapper __doUploadFileAsStream(IUploadFileItemProcesser processer)
        throws FileUploadException, IOException {
    ServletFileUpload _upload = new ServletFileUpload();
    _upload.setFileSizeMax(__fileSizeMax);
    _upload.setSizeMax(__sizeMax);
    if (__listener != null) {
        _upload.setProgressListener(__listener);
    }
    Map<String, List<String>> tmpParams = new HashMap<String, List<String>>();
    Map<String, List<UploadFileWrapper>> tmpFiles = new HashMap<String, List<UploadFileWrapper>>();
    //
    FileItemIterator _fileItemIT = _upload.getItemIterator(__request);
    while (_fileItemIT.hasNext()) {
        FileItemStream _item = _fileItemIT.next();
        if (_item.isFormField()) {
            List<String> _valueList = tmpParams.get(_item.getFieldName());
            if (_valueList == null) {
                _valueList = new ArrayList<String>();
                tmpParams.put(_item.getFieldName(), _valueList);
            }
            _valueList.add(Streams.asString(_item.openStream(), __charsetEncoding));
        } else {
            List<UploadFileWrapper> _valueList = tmpFiles.get(_item.getFieldName());
            if (_valueList == null) {
                _valueList = new ArrayList<UploadFileWrapper>();
                tmpFiles.put(_item.getFieldName(), _valueList);
            }
            // ??
            _valueList.add(processer.process(_item));
        }
    }
    //
    UploadFormWrapper _form = new UploadFormWrapper();
    for (Map.Entry<String, List<String>> entry : tmpParams.entrySet()) {
        _form.getFieldMap().put(entry.getKey(), entry.getValue().toArray(new String[entry.getValue().size()]));
    }
    for (Map.Entry<String, List<UploadFileWrapper>> entry : tmpFiles.entrySet()) {
        _form.getFileMap().put(entry.getKey(),
                entry.getValue().toArray(new UploadFileWrapper[entry.getValue().size()]));
    }
    return _form;
}

From source file:ninja.servlet.NinjaServletContext.java

private void processFormFields() {
    if (formFieldsProcessed)
        return;//from ww  w .  java2 s  .  co m
    formFieldsProcessed = true;

    // return if not multipart
    if (!ServletFileUpload.isMultipartContent(httpServletRequest))
        return;

    // get fileProvider from route method/class, or defaults to an injected one
    // if none injected, then we do not process form fields this way and let the user
    // call classic getFileItemIterator() by himself
    FileProvider fileProvider = null;
    if (route != null) {
        if (fileProvider == null) {
            fileProvider = route.getControllerMethod().getAnnotation(FileProvider.class);
        }
        if (fileProvider == null) {
            fileProvider = route.getControllerClass().getAnnotation(FileProvider.class);
        }
    }

    // get file item provider from file provider or default one
    FileItemProvider fileItemProvider = null;
    if (fileProvider == null) {
        fileItemProvider = injector.getInstance(FileItemProvider.class);
    } else {
        fileItemProvider = injector.getInstance(fileProvider.value());
    }

    if (fileItemProvider instanceof NoFileItemProvider)
        return;

    // Initialize maps and other constants
    ArrayListMultimap<String, String> formMap = ArrayListMultimap.create();
    ArrayListMultimap<String, FileItem> fileMap = ArrayListMultimap.create();

    // This is the iterator we can use to iterate over the contents of the request.
    try {

        FileItemIterator fileItemIterator = getFileItemIterator();

        while (fileItemIterator.hasNext()) {

            FileItemStream item = fileItemIterator.next();

            if (item.isFormField()) {

                String charset = NinjaConstant.UTF_8;

                String contentType = item.getContentType();

                if (contentType != null) {
                    charset = HttpHeaderUtils.getCharsetOfContentTypeOrUtf8(contentType);
                }

                // save the form field for later use from getParameter
                String value = Streams.asString(item.openStream(), charset);
                formMap.put(item.getFieldName(), value);

            } else {

                // process file as input stream and save for later use in getParameterAsFile or getParameterAsInputStream
                FileItem fileItem = fileItemProvider.create(item);
                fileMap.put(item.getFieldName(), fileItem);
            }
        }
    } catch (FileUploadException | IOException e) {
        throw new RuntimeException("Failed to parse multipart request data", e);
    }

    // convert both multimap<K,V> to map<K,List<V>>
    formFieldsMap = toUnmodifiableMap(formMap);
    fileFieldsMap = toUnmodifiableMap(fileMap);
}

From source file:org.apache.jena.fuseki.servlets.Upload.java

/**  Process an HTTP upload of RDF files (triples or quads)
 *   Stream straight into a graph or dataset -- unlike SPARQL_Upload the destination
 *   is known at the start of the multipart file body
 *//*w w  w .  j  a  v a  2s .  c  o  m*/

public static UploadDetails fileUploadWorker(HttpAction action, StreamRDF dest) {
    String base = ActionLib.wholeRequestURL(action.request);
    ServletFileUpload upload = new ServletFileUpload();
    //log.info(format("[%d] Upload: Field=%s ignored", action.id, fieldName)) ;

    // Overall counting.
    StreamRDFCounting countingDest = StreamRDFLib.count(dest);

    try {
        FileItemIterator iter = upload.getItemIterator(action.request);
        while (iter.hasNext()) {
            FileItemStream fileStream = iter.next();
            if (fileStream.isFormField()) {
                // Ignore?
                String fieldName = fileStream.getFieldName();
                InputStream stream = fileStream.openStream();
                String value = Streams.asString(stream, "UTF-8");
                ServletOps.errorBadRequest(
                        format("Only files accepted in multipart file upload (got %s=%s)", fieldName, value));
            }
            //Ignore the field name.
            //String fieldName = fileStream.getFieldName();

            InputStream stream = fileStream.openStream();
            // Process the input stream
            String contentTypeHeader = fileStream.getContentType();
            ContentType ct = ContentType.create(contentTypeHeader);
            Lang lang = null;
            if (!matchContentType(ctTextPlain, ct))
                lang = RDFLanguages.contentTypeToLang(ct.getContentType());

            if (lang == null) {
                String name = fileStream.getName();
                if (name == null || name.equals(""))
                    ServletOps.errorBadRequest("No name for content - can't determine RDF syntax");
                lang = RDFLanguages.filenameToLang(name);
                if (name.endsWith(".gz"))
                    stream = new GZIPInputStream(stream);
            }
            if (lang == null)
                // Desperate.
                lang = RDFLanguages.RDFXML;

            String printfilename = fileStream.getName();
            if (printfilename == null || printfilename.equals(""))
                printfilename = "<none>";

            // Before
            // action.log.info(format("[%d] Filename: %s, Content-Type=%s, Charset=%s => %s", 
            //                        action.id, printfilename,  ct.getContentType(), ct.getCharset(), lang.getName())) ;

            // count just this step
            StreamRDFCounting countingDest2 = StreamRDFLib.count(countingDest);
            try {
                ActionSPARQL.parse(action, countingDest2, stream, lang, base);
                UploadDetails details1 = new UploadDetails(countingDest2.count(), countingDest2.countTriples(),
                        countingDest2.countQuads());
                action.log.info(format("[%d] Filename: %s, Content-Type=%s, Charset=%s => %s : %s", action.id,
                        printfilename, ct.getContentType(), ct.getCharset(), lang.getName(),
                        details1.detailsStr()));
            } catch (RiotParseException ex) {
                action.log.info(format("[%d] Filename: %s, Content-Type=%s, Charset=%s => %s : %s", action.id,
                        printfilename, ct.getContentType(), ct.getCharset(), lang.getName(), ex.getMessage()));
                throw ex;
            }
        }
    } catch (ActionErrorException ex) {
        throw ex;
    } catch (Exception ex) {
        ServletOps.errorOccurred(ex.getMessage());
    }
    // Overall results.
    UploadDetails details = new UploadDetails(countingDest.count(), countingDest.countTriples(),
            countingDest.countQuads());
    return details;
}

From source file:org.apache.jena.fuseki.system.Upload.java

/**  
 * Process an HTTP upload of RDF files (triples or quads)
 * Stream straight into the destination graph or dataset, ignoring any
 * headers in the form parts. This function is used by GSP.
 *///from w  w w.  j a  va 2s  .  c  o  m

public static UploadDetails fileUploadWorker(HttpAction action, StreamRDF dest) {
    String base = ActionLib.wholeRequestURL(action.request);
    ServletFileUpload upload = new ServletFileUpload();
    StreamRDFCounting countingDest = StreamRDFLib.count(dest);

    try {
        FileItemIterator iter = upload.getItemIterator(action.request);
        while (iter.hasNext()) {
            FileItemStream fileStream = iter.next();
            if (fileStream.isFormField()) {
                // Ignore?
                String fieldName = fileStream.getFieldName();
                InputStream stream = fileStream.openStream();
                String value = Streams.asString(stream, "UTF-8");
                // This code is currently used to put multiple files into a single destination.
                // Additonal field/values do not make sense.
                ServletOps.errorBadRequest(
                        format("Only files accepted in multipart file upload (got %s=%s)", fieldName, value));
            }
            //Ignore the field name.
            //String fieldName = fileStream.getFieldName();

            InputStream stream = fileStream.openStream();
            // Process the input stream
            String contentTypeHeader = fileStream.getContentType();
            ContentType ct = ContentType.create(contentTypeHeader);
            Lang lang = null;
            if (!matchContentType(ctTextPlain, ct))
                lang = RDFLanguages.contentTypeToLang(ct.getContentType());

            if (lang == null) {
                String name = fileStream.getName();
                if (name == null || name.equals(""))
                    ServletOps.errorBadRequest("No name for content - can't determine RDF syntax");
                lang = RDFLanguages.filenameToLang(name);
                if (name.endsWith(".gz"))
                    stream = new GZIPInputStream(stream);
            }
            if (lang == null)
                // Desperate.
                lang = RDFLanguages.RDFXML;

            String printfilename = fileStream.getName();
            if (printfilename == null || printfilename.equals(""))
                printfilename = "<none>";

            // Before
            // action.log.info(format("[%d] Filename: %s, Content-Type=%s, Charset=%s => %s", 
            //                        action.id, printfilename,  ct.getContentType(), ct.getCharset(), lang.getName())) ;

            // count just this step
            StreamRDFCounting countingDest2 = StreamRDFLib.count(countingDest);
            try {
                ActionLib.parse(action, countingDest2, stream, lang, base);
                UploadDetails details1 = new UploadDetails(countingDest2.count(), countingDest2.countTriples(),
                        countingDest2.countQuads());
                action.log.info(format("[%d] Filename: %s, Content-Type=%s, Charset=%s => %s : %s", action.id,
                        printfilename, ct.getContentType(), ct.getCharset(), lang.getName(),
                        details1.detailsStr()));
            } catch (RiotParseException ex) {
                action.log.info(format("[%d] Filename: %s, Content-Type=%s, Charset=%s => %s : %s", action.id,
                        printfilename, ct.getContentType(), ct.getCharset(), lang.getName(), ex.getMessage()));
                throw ex;
            }
        }
    } catch (ActionErrorException ex) {
        throw ex;
    } catch (Exception ex) {
        ServletOps.errorOccurred(ex.getMessage());
    }
    // Overall results.
    UploadDetails details = new UploadDetails(countingDest.count(), countingDest.countTriples(),
            countingDest.countQuads());
    return details;
}

From source file:org.apache.jena.fuseki.system.Upload.java

/** 
 * Process an HTTP file upload of RDF using the name field for the graph name destination.
 * This function is used by SPARQL_Upload for {@code fuseki:serviceUpload}.
 *///from  ww  w  . j a  v a2  s.  c  o  m
public static UploadDetailsWithName multipartUploadWorker(HttpAction action, String base) {
    DatasetGraph dsgTmp = DatasetGraphFactory.create();
    ServletFileUpload upload = new ServletFileUpload();
    String graphName = null;
    boolean isQuads = false;
    long count = -1;

    String name = null;
    ContentType ct = null;
    Lang lang = null;

    try {
        FileItemIterator iter = upload.getItemIterator(action.request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String fieldName = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                // Graph name.
                String value = Streams.asString(stream, "UTF-8");
                if (fieldName.equals(HttpNames.paramGraph)) {
                    graphName = value;
                    if (graphName != null && !graphName.equals("")
                            && !graphName.equals(HttpNames.valueDefault)) {
                        // -- Check IRI with additional checks.
                        IRI iri = IRIResolver.parseIRI(value);
                        if (iri.hasViolation(false))
                            ServletOps.errorBadRequest("Bad IRI: " + graphName);
                        if (iri.getScheme() == null)
                            ServletOps.errorBadRequest("Bad IRI: no IRI scheme name: " + graphName);
                        if (iri.getScheme().equalsIgnoreCase("http")
                                || iri.getScheme().equalsIgnoreCase("https")) {
                            // Redundant??
                            if (iri.getRawHost() == null)
                                ServletOps.errorBadRequest("Bad IRI: no host name: " + graphName);
                            if (iri.getRawPath() == null || iri.getRawPath().length() == 0)
                                ServletOps.errorBadRequest("Bad IRI: no path: " + graphName);
                            if (iri.getRawPath().charAt(0) != '/')
                                ServletOps.errorBadRequest("Bad IRI: Path does not start '/': " + graphName);
                        }
                        // End check IRI
                    }
                } else if (fieldName.equals(HttpNames.paramDefaultGraphURI))
                    graphName = null;
                else
                    // Add file type?
                    action.log.info(format("[%d] Upload: Field=%s ignored", action.id, fieldName));
            } else {
                // Process the input stream
                name = item.getName();
                if (name == null || name.equals("") || name.equals("UNSET FILE NAME"))
                    ServletOps.errorBadRequest("No name for content - can't determine RDF syntax");

                String contentTypeHeader = item.getContentType();
                ct = ContentType.create(contentTypeHeader);

                lang = RDFLanguages.contentTypeToLang(ct.getContentType());
                if (lang == null) {
                    lang = RDFLanguages.filenameToLang(name);

                    // JENA-600 filenameToLang() strips off certain
                    // extensions such as .gz and
                    // we need to ensure that if there was a .gz extension
                    // present we wrap the stream accordingly
                    if (name.endsWith(".gz"))
                        stream = new GZIPInputStream(stream);
                }

                if (lang == null)
                    // Desperate.
                    lang = RDFLanguages.RDFXML;

                isQuads = RDFLanguages.isQuads(lang);

                action.log.info(format("[%d] Upload: Filename: %s, Content-Type=%s, Charset=%s => %s",
                        action.id, name, ct.getContentType(), ct.getCharset(), lang.getName()));

                StreamRDF x = StreamRDFLib.dataset(dsgTmp);
                StreamRDFCounting dest = StreamRDFLib.count(x);
                ActionLib.parse(action, dest, stream, lang, base);
                count = dest.count();
            }
        }

        if (graphName == null || graphName.equals(""))
            graphName = HttpNames.valueDefault;
        if (isQuads)
            graphName = null;
        return new UploadDetailsWithName(graphName, dsgTmp, count);
    } catch (ActionErrorException ex) {
        throw ex;
    } catch (Exception ex) {
        ServletOps.errorOccurred(ex);
        return null;
    }
}

From source file:org.codelabor.system.file.web.servlet.FileUploadStreamServlet.java

@Override
protected void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(this.getServletContext());
    FileManager fileManager = (FileManager) ctx.getBean("fileManager");

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    if (logger.isDebugEnabled()) {
        logger.debug(paramMap.toString());
    }/*from www  .  j  a  v a 2 s . c  om*/

    String mapId = (String) paramMap.get("mapId");
    RepositoryType acceptedRepositoryType = repositoryType;
    String requestedRepositoryType = (String) paramMap.get("repositoryType");
    if (StringUtils.isNotEmpty(requestedRepositoryType)) {
        acceptedRepositoryType = RepositoryType.valueOf(requestedRepositoryType);
    }

    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileSizeMax(fileSizeMax);
        upload.setSizeMax(requestSizeMax);
        upload.setHeaderEncoding(characterEncoding);
        upload.setProgressListener(new FileUploadProgressListener());
        try {
            FileItemIterator iter = upload.getItemIterator(request);

            while (iter.hasNext()) {
                FileItemStream fileItemSteam = iter.next();
                if (logger.isDebugEnabled()) {
                    logger.debug(fileItemSteam.toString());
                }
                FileDTO fileDTO = null;
                if (fileItemSteam.isFormField()) {
                    paramMap.put(fileItemSteam.getFieldName(),
                            Streams.asString(fileItemSteam.openStream(), characterEncoding));
                } else {
                    if (fileItemSteam.getName() == null || fileItemSteam.getName().length() == 0)
                        continue;

                    // set DTO
                    fileDTO = new FileDTO();
                    fileDTO.setMapId(mapId);
                    fileDTO.setRealFilename(FilenameUtils.getName(fileItemSteam.getName()));
                    if (acceptedRepositoryType == RepositoryType.FILE_SYSTEM) {
                        fileDTO.setUniqueFilename(getUniqueFilename());
                    }
                    fileDTO.setContentType(fileItemSteam.getContentType());
                    fileDTO.setRepositoryPath(realRepositoryPath);
                    if (logger.isDebugEnabled()) {
                        logger.debug(fileDTO.toString());
                    }
                    UploadUtils.processFile(acceptedRepositoryType, fileItemSteam.openStream(), fileDTO);
                }
                if (fileDTO != null)
                    fileManager.insertFile(fileDTO);
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
    } else {
        paramMap = RequestUtils.getParameterMap(request);
    }
    try {
        processParameters(paramMap);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
    }
    dispatch(request, response, forwardPathUpload);

}