Example usage for org.apache.commons.fileupload FileItemIterator next

List of usage examples for org.apache.commons.fileupload FileItemIterator next

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemIterator next.

Prototype

FileItemStream next() throws FileUploadException, IOException;

Source Link

Document

Returns the next available FileItemStream .

Usage

From source file:com.sonicle.webtop.core.app.AbstractEnvironmentService.java

public void processUpload(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    ServletFileUpload upload = null;/*from  w  w w  . j a v  a  2  s.  com*/
    WebTopSession.UploadedFile uploadedFile = null;
    HashMap<String, String> multipartParams = new HashMap<>();

    try {
        String service = ServletUtils.getStringParameter(request, "service", true);
        String cntx = ServletUtils.getStringParameter(request, "context", true);
        String tag = ServletUtils.getStringParameter(request, "tag", null);
        if (!ServletFileUpload.isMultipartContent(request))
            throw new Exception("No upload request");

        IServiceUploadStreamListener istream = getUploadStreamListener(cntx);
        if (istream != null) {
            try {
                MapItem data = new MapItem(); // Empty response data

                // Defines the upload object
                upload = new ServletFileUpload();
                FileItemIterator it = upload.getItemIterator(request);
                while (it.hasNext()) {
                    FileItemStream fis = it.next();
                    if (fis.isFormField()) {
                        InputStream is = null;
                        try {
                            is = fis.openStream();
                            String key = fis.getFieldName();
                            String value = IOUtils.toString(is, "UTF-8");
                            multipartParams.put(key, value);
                        } finally {
                            IOUtils.closeQuietly(is);
                        }
                    } else {
                        // Creates uploaded object
                        uploadedFile = new WebTopSession.UploadedFile(true, service, IdentifierUtils.getUUID(),
                                tag, fis.getName(), -1, findMediaType(fis));

                        // Fill response data
                        data.add("virtual", uploadedFile.isVirtual());
                        data.add("editable", isFileEditableInDocEditor(fis.getName()));

                        // Handle listener, its implementation can stop
                        // file upload throwing a UploadException.
                        InputStream is = null;
                        try {
                            getEnv().getSession().addUploadedFile(uploadedFile);
                            is = fis.openStream();
                            istream.onUpload(cntx, request, multipartParams, uploadedFile, is, data);
                        } finally {
                            IOUtils.closeQuietly(is);
                            getEnv().getSession().removeUploadedFile(uploadedFile, false);
                        }
                    }
                }
                new JsonResult(data).printTo(out);

            } catch (UploadException ex1) {
                new JsonResult(false, ex1.getMessage()).printTo(out);
            } catch (Exception ex1) {
                throw ex1;
            }

        } else {
            try {
                MapItem data = new MapItem(); // Empty response data
                IServiceUploadListener iupload = getUploadListener(cntx);

                // Defines the upload object
                DiskFileItemFactory factory = new DiskFileItemFactory();
                //TODO: valutare come imporre i limiti
                //factory.setSizeThreshold(yourMaxMemorySize);
                //factory.setRepository(yourTempDirectory);
                upload = new ServletFileUpload(factory);
                List<FileItem> files = upload.parseRequest(request);

                // Plupload component (client-side) will upload multiple file 
                // each in its own request. So we can skip loop on files.
                Iterator it = files.iterator();
                while (it.hasNext()) {
                    FileItem fi = (FileItem) it.next();
                    if (fi.isFormField()) {
                        InputStream is = null;
                        try {
                            is = fi.getInputStream();
                            String key = fi.getFieldName();
                            String value = IOUtils.toString(is, "UTF-8");
                            multipartParams.put(key, value);
                        } finally {
                            IOUtils.closeQuietly(is);
                        }
                    } else {
                        // Writes content into a temp file
                        File file = WT.createTempFile(UPLOAD_TEMPFILE_PREFIX);
                        fi.write(file);

                        // Creates uploaded object
                        uploadedFile = new WebTopSession.UploadedFile(false, service, file.getName(), tag,
                                fi.getName(), fi.getSize(), findMediaType(fi));
                        getEnv().getSession().addUploadedFile(uploadedFile);

                        // Fill response data
                        data.add("virtual", uploadedFile.isVirtual());
                        data.add("uploadId", uploadedFile.getUploadId());
                        data.add("editable", isFileEditableInDocEditor(fi.getName()));

                        // Handle listener (if present), its implementation can stop
                        // file upload throwing a UploadException.
                        if (iupload != null) {
                            try {
                                iupload.onUpload(cntx, request, multipartParams, uploadedFile, data);
                            } catch (UploadException ex2) {
                                getEnv().getSession().removeUploadedFile(uploadedFile, true);
                                throw ex2;
                            }
                        }
                    }
                }
                new JsonResult(data).printTo(out);

            } catch (UploadException ex1) {
                new JsonResult(ex1).printTo(out);
            }
        }

    } catch (Exception ex) {
        WebTopApp.logger.error("Error uploading", ex);
        new JsonResult(ex).printTo(out);
    }
}

From source file:com.vmware.photon.controller.api.frontend.resources.image.ImagesResource.java

private void flushRequest(FileItemIterator iterator, InputStream itemStream) {
    try {//w  w w.j av  a  2s.  c  o  m
        // close any streams left open due to error.
        if (itemStream != null) {
            itemStream.close();
        }

        // iterate through the remaining fields an flush the fields that contain the file data.
        while (null != iterator && iterator.hasNext()) {
            FileItemStream item = iterator.next();
            if (!item.isFormField()) {
                item.openStream().close();
            }
        }
    } catch (IOException | FileUploadException ex) {
        logger.warn("Unexpected exception flushing upload request.", ex);
    }
}

From source file:com.github.thorqin.toolkit.web.utility.UploadManager.java

/**
 * Save upload file to disk//from   ww  w .j av a2s  .c  o  m
 * @param request HttpServletRequest
 * @param maxSize maximum size of the upload file, in bytes.
 * @return Saved file info list
 * @throws ServletException
 * @throws IOException
 * @throws FileUploadException
 */
public List<FileInfo> saveUploadFiles(HttpServletRequest request, int maxSize)
        throws ServletException, IOException, FileUploadException {
    List<FileInfo> uploadList = new LinkedList<>();
    request.setCharacterEncoding("utf-8");
    ServletFileUpload upload = new ServletFileUpload();
    upload.setHeaderEncoding("UTF-8");
    if (!ServletFileUpload.isMultipartContent(request)) {
        return uploadList;
    }
    upload.setSizeMax(maxSize);
    FileItemIterator iterator = upload.getItemIterator(request);
    while (iterator.hasNext()) {
        FileItemStream item = iterator.next();
        try (InputStream stream = item.openStream()) {
            if (!item.isFormField()) {
                FileInfo info = new FileInfo();
                info.setFileName(item.getName());
                if (pattern != null && !pattern.matcher(info.fileName).matches()) {
                    continue;
                }
                info = store(stream, info.fileName);
                uploadList.add(info);
            }
        }
    }
    return uploadList;
}

From source file:com.googlecode.npackdweb.RepUploadAction.java

@Override
public Page perform(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    List<String> messages = new ArrayList<String>();

    Found f = null;//w  w w. j av a2s .  com
    String tag = "unknown";
    boolean overwrite = false;
    if (ServletFileUpload.isMultipartContent(req)) {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator;
        try {
            iterator = upload.getItemIterator(req);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                InputStream stream = item.openStream();

                try {
                    if (item.isFormField()) {
                        if (item.getFieldName().equals("tag")) {
                            BufferedReader r = new BufferedReader(new InputStreamReader(stream));
                            tag = r.readLine();
                        } else if (item.getFieldName().equals("overwrite")) {
                            overwrite = true;
                        }
                    } else {
                        f = process(stream);
                    }
                } finally {
                    stream.close();
                }
            }
        } catch (FileUploadException e) {
            throw (IOException) new IOException(e.getMessage()).initCause(e);
        }
    } else {
        tag = req.getParameter("tag");
        String rep = req.getParameter("repository");
        overwrite = req.getParameter("overwrite") != null;
        f = process(new ByteArrayInputStream(rep.getBytes("UTF-8")));
    }

    if (f != null) {
        boolean isAdmin = NWUtils.isAdminLoggedIn();

        for (PackageVersion pv : f.pvs) {
            pv.tags.add(tag);
        }

        Objectify ofy = DefaultServlet.getObjectify();
        List<Key<?>> keys = new ArrayList<Key<?>>();
        for (License lic : f.lics) {
            keys.add(lic.createKey());
        }
        for (PackageVersion pv : f.pvs) {
            keys.add(pv.createKey());
        }
        for (Package p : f.ps) {
            keys.add(p.createKey());
        }

        Map<Key<Object>, Object> existing = ofy.get(keys);

        Stats stats = new Stats();
        Iterator<PackageVersion> it = f.pvs.iterator();
        while (it.hasNext()) {
            PackageVersion pv = it.next();
            PackageVersion found = (PackageVersion) existing.get(pv.createKey());
            if (found != null) {
                stats.pvExisting++;
                if (!overwrite)
                    it.remove();
            }
        }

        Iterator<License> itLic = f.lics.iterator();
        while (itLic.hasNext()) {
            License pv = itLic.next();
            License found = (License) existing.get(pv.createKey());
            if (found != null) {
                stats.licExisting++;
                if (!overwrite)
                    itLic.remove();
            }
        }

        Iterator<Package> itP = f.ps.iterator();
        while (itP.hasNext()) {
            Package p = itP.next();
            Package found = (Package) existing.get(p.createKey());
            if (found != null) {
                stats.pExisting++;
                if (!overwrite)
                    itP.remove();
            }
        }

        for (PackageVersion pv : f.pvs) {
            Package p = ofy.find(new Key<Package>(Package.class, pv.package_));
            if (p != null && !p.isCurrentUserPermittedToModify())
                messages.add("You do not have permission to modify this package: " + pv.package_);
        }

        for (Package p : f.ps) {
            Package p_ = ofy.find(new Key<Package>(Package.class, p.name));
            if (p_ != null && !p_.isCurrentUserPermittedToModify())
                messages.add("You do not have permission to modify this package: " + p.name);
        }

        if (f.lics.size() > 0) {
            if (isAdmin)
                ofy.put(f.lics);
            else
                messages.add("Only an administrator can change licenses");
        }

        ofy.put(f.pvs);

        for (Package p : f.ps) {
            NWUtils.savePackage(ofy, p, true);
        }

        if (overwrite) {
            stats.pOverwritten = stats.pExisting;
            stats.pvOverwritten = stats.pvExisting;
            stats.licOverwritten = stats.licExisting;
            stats.pAppended = f.ps.size() - stats.pOverwritten;
            stats.pvAppended = f.pvs.size() - stats.pvOverwritten;
            stats.licAppended = f.lics.size() - stats.licOverwritten;
        } else {
            stats.pAppended = f.ps.size();
            stats.pvAppended = f.pvs.size();
            stats.licAppended = f.lics.size();
        }
        messages.add(stats.pOverwritten + " packages overwritten, " + stats.pvOverwritten
                + " package versions overwritten, " + stats.licOverwritten + " licenses overwritten, "
                + stats.pAppended + " packages appended, " + stats.pvAppended + " package versions appended, "
                + stats.licAppended + " licenses appended");
    } else {
        messages.add("No data found");
    }

    return new MessagePage(messages);
}

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  . j ava  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:cn.webwheel.ActionSetter.java

@SuppressWarnings("unchecked")
public Object[] set(Object action, ActionInfo ai, HttpServletRequest request) throws IOException {
    SetterConfig cfg = ai.getSetterConfig();
    List<SetterInfo> setters;
    if (action != null) {
        Class cls = action.getClass();
        setters = setterMap.get(cls);//  w ww  .j  a va 2  s . c o m
        if (setters == null) {
            synchronized (this) {
                setters = setterMap.get(cls);
                if (setters == null) {
                    Map<Class, List<SetterInfo>> map = new HashMap<Class, List<SetterInfo>>(setterMap);
                    map.put(cls, setters = parseSetters(cls));
                    setterMap = map;
                }
            }
        }
    } else {
        setters = Collections.emptyList();
    }

    List<SetterInfo> args = argMap.get(ai.actionMethod);
    if (args == null) {
        synchronized (this) {
            args = argMap.get(ai.actionMethod);
            if (args == null) {
                Map<Method, List<SetterInfo>> map = new HashMap<Method, List<SetterInfo>>(argMap);
                map.put(ai.actionMethod, args = parseArgs(ai.actionMethod));
                argMap = map;
            }
        }
    }

    if (setters.isEmpty() && args.isEmpty())
        return new Object[0];

    Map<String, Object> params;
    try {
        if (cfg.getCharset() != null) {
            request.setCharacterEncoding(cfg.getCharset());
        }
    } catch (UnsupportedEncodingException e) {
        //
    }

    if (ServletFileUpload.isMultipartContent(request)) {
        params = new HashMap<String, Object>(request.getParameterMap());
        request.setAttribute(WRPName, params);
        ServletFileUpload fileUpload = new ServletFileUpload();
        if (cfg.getCharset() != null) {
            fileUpload.setHeaderEncoding(cfg.getCharset());
        }
        if (cfg.getFileUploadSizeMax() != 0) {
            fileUpload.setSizeMax(cfg.getFileUploadSizeMax());
        }
        if (cfg.getFileUploadFileSizeMax() != 0) {
            fileUpload.setFileSizeMax(cfg.getFileUploadFileSizeMax());
        }
        boolean throwe = false;
        try {
            FileItemIterator it = fileUpload.getItemIterator(request);
            while (it.hasNext()) {
                FileItemStream fis = it.next();
                if (fis.isFormField()) {
                    String s = Streams.asString(fis.openStream(), cfg.getCharset());
                    Object o = params.get(fis.getFieldName());
                    if (o == null) {
                        params.put(fis.getFieldName(), new String[] { s });
                    } else if (o instanceof String[]) {
                        String[] ss = (String[]) o;
                        String[] nss = new String[ss.length + 1];
                        System.arraycopy(ss, 0, nss, 0, ss.length);
                        nss[ss.length] = s;
                        params.put(fis.getFieldName(), nss);
                    }
                } else if (!fis.getName().isEmpty()) {
                    File tempFile;
                    try {
                        tempFile = File.createTempFile("wfu", null);
                    } catch (IOException e) {
                        throwe = true;
                        throw e;
                    }
                    FileExImpl fileEx = new FileExImpl(tempFile);
                    Object o = params.get(fis.getFieldName());
                    if (o == null) {
                        params.put(fis.getFieldName(), new FileEx[] { fileEx });
                    } else if (o instanceof FileEx[]) {
                        FileEx[] ss = (FileEx[]) o;
                        FileEx[] nss = new FileEx[ss.length + 1];
                        System.arraycopy(ss, 0, nss, 0, ss.length);
                        nss[ss.length] = fileEx;
                        params.put(fis.getFieldName(), nss);
                    }
                    Streams.copy(fis.openStream(), new FileOutputStream(fileEx.getFile()), true);
                    fileEx.fileName = fis.getName();
                    fileEx.contentType = fis.getContentType();
                }
            }
        } catch (FileUploadException e) {
            if (action instanceof FileUploadExceptionAware) {
                ((FileUploadExceptionAware) action).setFileUploadException(e);
            }
        } catch (IOException e) {
            if (throwe) {
                throw e;
            }
        }
    } else {
        params = request.getParameterMap();
    }

    if (cfg.getSetterPolicy() == SetterPolicy.ParameterAndField
            || (cfg.getSetterPolicy() == SetterPolicy.Auto && args.isEmpty())) {
        for (SetterInfo si : setters) {
            si.setter.set(action, si.member, params, si.paramName);
        }
    }

    Object[] as = new Object[args.size()];
    for (int i = 0; i < as.length; i++) {
        SetterInfo si = args.get(i);
        as[i] = si.setter.set(action, null, params, si.paramName);
    }
    return as;
}

From source file:com.ultrapower.eoms.common.plugin.ajaxupload.AjaxMultiPartRequest.java

/**
 * Creates a new request wrapper to handle multi-part data using methods
 * adapted from Jason Pell's multipart classes (see class description).
 * /*  w w  w  .j  a  va 2  s.  c o m*/
 * @param saveDir
 *            the directory to save off the file
 * @param servletRequest
 *            the request containing the multipart
 * @throws java.io.IOException
 *             is thrown if encoding fails.
 * @throws
 */
public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException {

    Integer delay = 3;
    UploadListener listener = null;
    DiskFileItemFactory fac = null;

    // Parse the request
    try {
        if (maxSize >= 0L && servletRequest.getContentLength() > maxSize) {
            servletRequest.setAttribute("error", "size");
            FileItemIterator it = new ServletFileUpload(fac).getItemIterator(servletRequest);
            // handle with each file:
            while (it.hasNext()) {
                FileItemStream item = it.next();
                if (item.isFormField()) {
                    List<String> values;
                    if (params.get(item.getFieldName()) != null) {
                        values = params.get(item.getFieldName());
                    } else {
                        values = new ArrayList<String>();
                    }
                    InputStream stream = item.openStream();
                    values.add(Streams.asString(stream));
                    params.put(item.getFieldName(), values);
                }
            }
            return;
        } else {
            listener = new UploadListener(servletRequest, delay);
            fac = new MonitoredDiskFileItemFactory(listener);
        }

        // Make sure that the data is written to file
        fac.setSizeThreshold(0);
        if (saveDir != null) {
            fac.setRepository(new File(saveDir));
        }
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setSizeMax(maxSize);
        List items = upload.parseRequest(createRequestContext(servletRequest));

        for (Object item1 : items) {
            FileItem item = (FileItem) item1;
            if (log.isDebugEnabled())
                log.debug("Found item " + item.getFieldName());
            if (item.isFormField()) {
                log.debug("Item is a normal form field");
                List<String> values;
                if (params.get(item.getFieldName()) != null) {
                    values = params.get(item.getFieldName());
                } else {
                    values = new ArrayList<String>();
                }
                String charset = servletRequest.getCharacterEncoding();
                if (charset != null) {
                    values.add(item.getString(charset));
                } else {
                    values.add(item.getString());
                }
                params.put(item.getFieldName(), values);
            } else {
                log.debug("Item is a file upload");

                // Skip file uploads that don't have a file name - meaning
                // that no file was selected.
                if (item.getName() == null || item.getName().trim().length() < 1) {
                    log.debug("No file has been uploaded for the field: " + item.getFieldName());
                    continue;
                }

                String targetFileName = item.getName();

                if (!targetFileName.contains(":"))
                    item.write(new File(targetDirectory + targetFileName));

                //?Action
                List<FileItem> values;
                if (files.get(item.getFieldName()) != null) {
                    values = files.get(item.getFieldName());
                } else {
                    values = new ArrayList<FileItem>();
                }

                values.add(item);
                files.put(item.getFieldName(), values);
            }
        }
    } catch (Exception e) {
        log.error(e);
        errors.add(e.getMessage());
    }
}

From source file:de.eorganization.hoopla.server.servlets.TemplateImportServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    DecisionTemplate newDecisionTemplate = new DecisionTemplate();
    DecisionTemplate decisionTemplate = null;
    try {/*from   w ww.j  a va 2 s.  c  o  m*/

        ServletFileUpload upload = new ServletFileUpload();
        resp.setContentType("text/plain");

        FileItemIterator itemIterator = upload.getItemIterator(req);
        while (itemIterator.hasNext()) {
            FileItemStream item = itemIterator.next();
            if (item.isFormField() && "substituteTemplateId".equals(item.getFieldName())) {
                log.warning("Got a form field: " + item.getFieldName());

                String itemContent = IOUtils.toString(item.openStream());
                try {
                    decisionTemplate = new HooplaServiceImpl()
                            .getDecisionTemplate(new Long(itemContent).longValue());
                    new HooplaServiceImpl().deleteDecisionTemplate(decisionTemplate);
                } catch (Exception e) {
                    log.log(Level.WARNING, e.getLocalizedMessage(), e);
                }
                if (decisionTemplate == null)
                    newDecisionTemplate.setKeyId(new Long(itemContent).longValue());
                else
                    newDecisionTemplate.setKeyId(decisionTemplate.getKeyId());
            } else {
                InputStream stream = item.openStream();

                log.info("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName());

                Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(stream);

                // doc.getDocumentElement().normalize();

                Element decisionElement = doc.getDocumentElement();
                String rootName = decisionElement.getNodeName();
                if (rootName.equals("decision")) {
                    isDecisionTemplate = false;
                } else if (rootName.equals("decisionTemplate")) {
                    isDecisionTemplate = true;
                } else {
                    log.warning("This XML Document has a wrong RootElement: " + rootName
                            + ". It should be <decision> or <decisionTemplate>.");
                }

                NodeList decisionNodes = decisionElement.getChildNodes();
                for (int i = 0; i < decisionNodes.getLength(); i++) {
                    Node node = decisionNodes.item(i);

                    if (node instanceof Element) {
                        Element child = (Element) node;
                        if (child.getNodeName().equals("name") && !child.getTextContent().equals("")) {
                            newDecisionTemplate.setName(child.getTextContent());
                            log.info("Parsed decision name: " + newDecisionTemplate.getName());
                        }
                        if (child.getNodeName().equals("description") && !child.getTextContent().equals("")) {
                            newDecisionTemplate.setDescription(child.getTextContent());
                            log.info("Parsed decision description: " + newDecisionTemplate.getDescription());
                        }
                        if (isDecisionTemplate && child.getNodeName().equals("templateName")) {
                            newDecisionTemplate.setTemplateName(child.getTextContent());
                            log.info("Parsed decision TemplateName: " + newDecisionTemplate.getTemplateName());
                        }
                        if (child.getNodeName().equals("alternatives")) {
                            parseAlternatives(child.getChildNodes(), newDecisionTemplate);
                        }
                        if (child.getNodeName().equals("goals")) {
                            parseGoals(child.getChildNodes(), newDecisionTemplate);
                        }
                        if (child.getNodeName().equals("importanceGoals")) {
                            parseGoalImportances(child.getChildNodes(), newDecisionTemplate);
                        }
                    }
                }

                log.info("Fully parsed XML Upload: " + newDecisionTemplate.toString());

            }
        }

    } catch (Exception ex) {
        log.log(Level.WARNING, ex.getLocalizedMessage(), ex);
        resp.sendError(400);
        return;
    }

    try {
        new HooplaServiceImpl().storeDecisionTemplate(newDecisionTemplate);
    } catch (Exception e) {
        log.log(Level.WARNING, e.getLocalizedMessage(), e);
        resp.sendError(500);
        return;
    }

    log.info("returning to referer " + req.getHeader("referer"));
    resp.sendRedirect(
            req.getHeader("referer") != null && !"".equals(req.getHeader("referer")) ? req.getHeader("referer")
                    : "localhost:8088");
}

From source file:ca.nrc.cadc.beacon.web.resources.FileItemServerResource.java

protected void upload(final FileItemIterator fileItemIterator)
        throws IOException, IllegalArgumentException, NodeNotFoundException, NodeAlreadyExistsException {
    boolean inheritParentPermissions = false;
    VOSURI newNodeURI = null;//  w w  w  .  j  av a2 s . com

    try {
        while (fileItemIterator.hasNext()) {
            final FileItemStream nextFileItemStream = fileItemIterator.next();

            if (nextFileItemStream.getFieldName().startsWith(UPLOAD_FILE_KEY)) {
                newNodeURI = upload(nextFileItemStream);

            } else if (nextFileItemStream.getFieldName().equals("inheritPermissionsCheckBox")) {
                inheritParentPermissions = true;
            }
        }
    } catch (FileUploadException e) {
        throw new IOException(e);
    }

    if (inheritParentPermissions) {
        setInheritedPermissions(newNodeURI);
    }
}

From source file:de.kp.ames.web.function.upload.UploadServiceImpl.java

public void doSetRequest(RequestContext ctx) {

    /*/*from w w  w. ja v  a 2  s  .co  m*/
     * The result of the upload request, returned
     * to the requestor; note, that the result must
     * be a text response
     */
    boolean result = false;
    HttpServletRequest request = ctx.getRequest();

    try {

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {

            /* 
             * Create new file upload handler
             */
            ServletFileUpload upload = new ServletFileUpload();

            /*
             * Parse the request
             */
            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {

                FileItemStream fileItem = iter.next();
                if (fileItem.isFormField()) {
                    // not supported

                } else {

                    /* 
                     * Hook into the upload request to some virus scanning
                     * using the scanner factory of this application
                     */

                    byte[] bytes = FileUtil.getByteArrayFromInputStream(fileItem.openStream());
                    boolean checked = MalwareScanner.scanForViruses(bytes);

                    if (checked) {

                        String item = this.method.getAttribute(MethodConstants.ATTR_ITEM);
                        String type = this.method.getAttribute(MethodConstants.ATTR_TYPE);
                        if ((item == null) || (type == null)) {
                            this.sendNotImplemented(ctx);

                        } else {

                            String fileName = FilenameUtils.getName(fileItem.getName());
                            String mimeType = fileItem.getContentType();

                            try {
                                result = upload(item, type, fileName, mimeType, bytes);

                            } catch (Exception e) {
                                sendBadRequest(ctx, e);

                            }

                        }

                    }

                }

            }

        }

        /*
         * Send html response
         */
        if (result == true) {
            this.sendHTMLResponse(createHtmlSuccess(), ctx.getResponse());

        } else {
            this.sendHTMLResponse(createHtmlFailure(), ctx.getResponse());

        }

    } catch (Exception e) {
        this.sendBadRequest(ctx, e);

    } finally {
    }

}