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

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

Introduction

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

Prototype

boolean hasNext() throws FileUploadException, IOException;

Source Link

Document

Returns, whether another instance of FileItemStream is available.

Usage

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;/*from  ww  w .  java  2 s. c  om*/
    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.github.thorqin.toolkit.web.utility.UploadManager.java

/**
 * Save upload file to disk//from  ww  w.  ja  v a  2  s .com
 * @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.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 {//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);/*from  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: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 {//  w  w w .j  a v a  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: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).
 * /*from  w  ww . j  av a  2 s.  c om*/
 * @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: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;/*from   w  w w  . j  ava 2 s .co  m*/

    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 www.  j  a  v a2s . c o  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 {
    }

}

From source file:com.google.livingstories.servlet.DataImportServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    startTime = System.currentTimeMillis();

    message = "";

    if (req.getContentType().contains("multipart/form-data")) {
        try {//  w ww. ja  v a 2  s.  co m
            ServletFileUpload upload = new ServletFileUpload();
            JSONObject data = null;
            boolean override = false;
            FileItemIterator iter = upload.getItemIterator(req);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                if (item.getFieldName().equals("override")) {
                    override = true;
                } else if (item.getFieldName().equals("data")) {
                    data = new JSONObject(Streams.asString(item.openStream()));
                }
            }
            checkRunState(override);
            inputData = data;
            setUp();
        } catch (FileUploadException ex) {
            throw new RuntimeException(ex);
        } catch (JSONException ex) {
            throw new RuntimeException(ex);
        }
    }

    try {
        process();
    } catch (Exception ex) {
        Writer result = new StringWriter();
        PrintWriter printWriter = new PrintWriter(result);
        ex.printStackTrace(printWriter);
        message = result.toString();
        runState = RunState.ERROR;
    } finally {
        if (runState != RunState.RUNNING) {
            tearDown();
        }
        Caches.clearAll();
    }

    resp.setContentType("text/html");
    resp.getWriter().append(message + "<br>" + runState.name());
}

From source file:fi.helsinki.lib.simplerest.RootCommunitiesResource.java

@Post
public Representation addCommunity(InputRepresentation rep) {
    Context c = null;/*from  w w w.  j  a v  a  2s . com*/
    Community community;
    try {
        c = getAuthenticatedContext();
        community = Community.create(null, c);

        RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory());
        FileItemIterator iter = rfu.getItemIterator(rep);

        String name = null;
        String shortDescription = null;
        String introductoryText = null;
        String copyrightText = null;
        String sideBarText = null;
        Bitstream bitstream = null;
        String bitstreamMimeType = null;
        while (iter.hasNext()) {
            FileItemStream fileItemStream = iter.next();
            if (fileItemStream.isFormField()) {
                String key = fileItemStream.getFieldName();
                String value = IOUtils.toString(fileItemStream.openStream(), "UTF-8");

                if (key.equals("name")) {
                    name = value;
                } else if (key.equals("short_description")) {
                    shortDescription = value;
                } else if (key.equals("introductory_text")) {
                    introductoryText = value;
                } else if (key.equals("copyright_text")) {
                    copyrightText = value;
                } else if (key.equals("side_bar_text")) {
                    sideBarText = value;
                } else {
                    return error(c, "Unexpected attribute: " + key, Status.CLIENT_ERROR_BAD_REQUEST);
                }
            } else {
                if (bitstream != null) {
                    return error(c, "The community can have only one logo.", Status.CLIENT_ERROR_BAD_REQUEST);
                }

                // I did not manage to use FormatIdentifier.guessFormat
                // here, so let's do it by ourselves... I would prefer to
                // use the actual file content and not its name, but let's
                // keep the code simple...
                String fileName = fileItemStream.getName();
                if (fileName.length() == 0) {
                    continue;
                }
                int lastDot = fileName.lastIndexOf('.');
                if (lastDot != -1) {
                    String extension = fileName.substring(lastDot + 1);
                    extension = extension.toLowerCase();
                    if (extension.equals("jpg") || extension.equals("jpeg")) {
                        bitstreamMimeType = "image/jpeg";
                    } else if (extension.equals("png")) {
                        bitstreamMimeType = "image/png";
                    } else if (extension.equals("gif")) {
                        bitstreamMimeType = "image/gif";
                    }
                }
                if (bitstreamMimeType == null) {
                    String err = "The logo filename extension was not recognised.";
                    return error(c, err, Status.CLIENT_ERROR_BAD_REQUEST);
                }

                bitstream = community.setLogo(fileItemStream.openStream());
                // We don't set the format of the logo (bitstream) here,
                // it's done in the code below...
            }
        }

        community.setMetadata("name", name);
        community.setMetadata("short_description", shortDescription);
        community.setMetadata("introductory_text", introductoryText);
        community.setMetadata("copyright_text", copyrightText);
        community.setMetadata("side_bar_text", sideBarText);

        community.update();

        // Set the format (jpeg, png, or gif) of logo:
        Bitstream logo = community.getLogo();
        if (logo != null) {
            BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, bitstreamMimeType);
            logo.setFormat(bf);
            logo.update();
        }

        c.complete();
    } catch (AuthorizeException ae) {
        return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED);
    } catch (Exception e) {
        return errorInternal(c, e.toString());
    }

    return successCreated("Community created.", baseUrl() + CommunityResource.relativeUrl(community.getID()));
}