Example usage for org.apache.commons.fileupload FileItemStream getFieldName

List of usage examples for org.apache.commons.fileupload FileItemStream getFieldName

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemStream getFieldName.

Prototype

String getFieldName();

Source Link

Document

Returns the name of the field in the multipart form corresponding to this file item.

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  w ww . j av  a2  s  .  c o 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.liferay.faces.metal.component.inputfile.internal.InputFileDecoderCommonsImpl.java

@Override
public Map<String, List<UploadedFile>> decode(FacesContext facesContext, String location) {

    Map<String, List<UploadedFile>> uploadedFileMap = null;
    ExternalContext externalContext = facesContext.getExternalContext();
    String uploadedFilesFolder = getUploadedFilesFolder(externalContext, location);

    // Using the sessionId, determine a unique folder path and create the path if it does not exist.
    String sessionId = getSessionId(externalContext);

    // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be
    // created properly.
    sessionId = sessionId.replaceAll("[^A-Za-z0-9]", " ");

    File uploadedFilesPath = new File(uploadedFilesFolder, sessionId);

    if (!uploadedFilesPath.exists()) {
        uploadedFilesPath.mkdirs();/*from   ww  w  . j  a v  a  2 s  .  c o m*/
    }

    // Initialize commons-fileupload with the file upload path.
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    diskFileItemFactory.setRepository(uploadedFilesPath);

    // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted.
    diskFileItemFactory.setFileCleaningTracker(null);

    // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk
    // instead of staying in memory.
    diskFileItemFactory.setSizeThreshold(0);

    // Determine the max file upload size threshold (in bytes).
    int uploadedFileMaxSize = WebConfigParam.UploadedFileMaxSize.getIntegerValue(externalContext);

    // Parse the request parameters and save all uploaded files in a map.
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    servletFileUpload.setFileSizeMax(uploadedFileMaxSize);
    uploadedFileMap = new HashMap<String, List<UploadedFile>>();

    UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder
            .getFactory(UploadedFileFactory.class);

    // Begin parsing the request for file parts:
    try {
        FileItemIterator fileItemIterator = null;

        HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
        fileItemIterator = servletFileUpload.getItemIterator(httpServletRequest);

        if (fileItemIterator != null) {

            int totalFiles = 0;

            // For each field found in the request:
            while (fileItemIterator.hasNext()) {

                try {
                    totalFiles++;

                    // Get the stream of field data from the request.
                    FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();

                    // Get field name from the field stream.
                    String fieldName = fieldStream.getFieldName();

                    // Get the content-type, and file-name from the field stream.
                    String contentType = fieldStream.getContentType();
                    boolean formField = fieldStream.isFormField();

                    String fileName = null;

                    try {
                        fileName = fieldStream.getName();
                    } catch (InvalidFileNameException e) {
                        fileName = e.getName();
                    }

                    // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the
                    // current field is a simple form-field because the call below to diskFileItem.getString()
                    // will fail otherwise.
                    DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName,
                            contentType, formField, fileName);
                    Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);

                    // If the current field is a file, then
                    if (!diskFileItem.isFormField()) {

                        // Get the location of the temporary file that was copied from the request.
                        File tempFile = diskFileItem.getStoreLocation();

                        // If the copy was successful, then
                        if (tempFile.exists()) {

                            // Copy the commons-fileupload temporary file to a file in the same temporary
                            // location, but with the filename provided by the user in the upload. This has two
                            // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
                            // the file, the developer can have access to a semi-permanent file, because the
                            // commmons-fileupload DiskFileItem.finalize() method automatically deletes the
                            // temporary one.
                            String tempFileName = tempFile.getName();
                            String tempFileAbsolutePath = tempFile.getAbsolutePath();

                            String copiedFileName = stripIllegalCharacters(fileName);

                            String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName,
                                    copiedFileName);
                            File copiedFile = new File(copiedFileAbsolutePath);
                            FileUtils.copyFile(tempFile, copiedFile);

                            // If present, build up a map of headers.
                            Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
                            FileItemHeaders fileItemHeaders = fieldStream.getHeaders();

                            if (fileItemHeaders != null) {
                                Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();

                                if (headerNameItr != null) {

                                    while (headerNameItr.hasNext()) {
                                        String headerName = headerNameItr.next();
                                        Iterator<String> headerValuesItr = fileItemHeaders
                                                .getHeaders(headerName);
                                        List<String> headerValues = new ArrayList<String>();

                                        if (headerValuesItr != null) {

                                            while (headerValuesItr.hasNext()) {
                                                String headerValue = headerValuesItr.next();
                                                headerValues.add(headerValue);
                                            }
                                        }

                                        headersMap.put(headerName, headerValues);
                                    }
                                }
                            }

                            // Put a valid UploadedFile instance into the map that contains all of the
                            // uploaded file's attributes, along with a successful status.
                            Map<String, Object> attributeMap = new HashMap<String, Object>();
                            String id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
                            String message = null;
                            UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(
                                    copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(),
                                    diskFileItem.getContentType(), headersMap, id, message, fileName,
                                    diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED);

                            addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName,
                                    fileName);
                        } else {

                            if ((fileName != null) && (fileName.trim().length() > 0)) {
                                Exception e = new IOException("Failed to copy the stream of uploaded file=["
                                        + fileName
                                        + "] to a temporary file (possibly a zero-length uploaded file)");
                                UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                                addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e);

                    UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                    String fieldName = Integer.toString(totalFiles);
                    addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                }
            }
        }
    }

    // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in
    // the map so that the developer can have some idea that something went wrong.
    catch (Exception e) {
        logger.error(e);

        UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
        addUploadedFile(uploadedFileMap, "unknown", uploadedFile);
    }

    return uploadedFileMap;
}

From source file:com.liferay.faces.alloy.component.inputfile.internal.InputFileDecoderCommonsImpl.java

@Override
public Map<String, List<UploadedFile>> decode(FacesContext facesContext, String location) {

    Map<String, List<UploadedFile>> uploadedFileMap = null;
    ExternalContext externalContext = facesContext.getExternalContext();
    String uploadedFilesFolder = getUploadedFilesFolder(externalContext, location);

    // Using the sessionId, determine a unique folder path and create the path if it does not exist.
    String sessionId = getSessionId(externalContext);

    // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be
    // created properly.
    sessionId = sessionId.replaceAll("[^A-Za-z0-9]", " ");

    File uploadedFilesPath = new File(uploadedFilesFolder, sessionId);

    if (!uploadedFilesPath.exists()) {
        uploadedFilesPath.mkdirs();/*www. j  a v  a2 s  .  c om*/
    }

    // Initialize commons-fileupload with the file upload path.
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    diskFileItemFactory.setRepository(uploadedFilesPath);

    // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted.
    diskFileItemFactory.setFileCleaningTracker(null);

    // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk
    // instead of staying in memory.
    diskFileItemFactory.setSizeThreshold(0);

    // Determine the max file upload size threshold (in bytes).
    int uploadedFileMaxSize = WebConfigParam.UploadedFileMaxSize.getIntegerValue(externalContext);

    // Parse the request parameters and save all uploaded files in a map.
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    servletFileUpload.setFileSizeMax(uploadedFileMaxSize);
    uploadedFileMap = new HashMap<String, List<UploadedFile>>();

    UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder
            .getFactory(externalContext, UploadedFileFactory.class);

    // Begin parsing the request for file parts:
    try {
        FileItemIterator fileItemIterator = null;

        HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
        fileItemIterator = servletFileUpload.getItemIterator(httpServletRequest);

        if (fileItemIterator != null) {

            int totalFiles = 0;

            // For each field found in the request:
            while (fileItemIterator.hasNext()) {

                try {
                    totalFiles++;

                    // Get the stream of field data from the request.
                    FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();

                    // Get field name from the field stream.
                    String fieldName = fieldStream.getFieldName();

                    // Get the content-type, and file-name from the field stream.
                    String contentType = fieldStream.getContentType();
                    boolean formField = fieldStream.isFormField();

                    String fileName = null;

                    try {
                        fileName = fieldStream.getName();
                    } catch (InvalidFileNameException e) {
                        fileName = e.getName();
                    }

                    // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the
                    // current field is a simple form-field because the call below to diskFileItem.getString()
                    // will fail otherwise.
                    DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName,
                            contentType, formField, fileName);
                    Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);

                    // If the current field is a file, then
                    if (!diskFileItem.isFormField()) {

                        // Get the location of the temporary file that was copied from the request.
                        File tempFile = diskFileItem.getStoreLocation();

                        // If the copy was successful, then
                        if (tempFile.exists()) {

                            // Copy the commons-fileupload temporary file to a file in the same temporary
                            // location, but with the filename provided by the user in the upload. This has two
                            // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
                            // the file, the developer can have access to a semi-permanent file, because the
                            // commmons-fileupload DiskFileItem.finalize() method automatically deletes the
                            // temporary one.
                            String tempFileName = tempFile.getName();
                            String tempFileAbsolutePath = tempFile.getAbsolutePath();

                            String copiedFileName = stripIllegalCharacters(fileName);

                            String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName,
                                    copiedFileName);
                            File copiedFile = new File(copiedFileAbsolutePath);
                            FileUtils.copyFile(tempFile, copiedFile);

                            // If present, build up a map of headers.
                            Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
                            FileItemHeaders fileItemHeaders = fieldStream.getHeaders();

                            if (fileItemHeaders != null) {
                                Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();

                                if (headerNameItr != null) {

                                    while (headerNameItr.hasNext()) {
                                        String headerName = headerNameItr.next();
                                        Iterator<String> headerValuesItr = fileItemHeaders
                                                .getHeaders(headerName);
                                        List<String> headerValues = new ArrayList<String>();

                                        if (headerValuesItr != null) {

                                            while (headerValuesItr.hasNext()) {
                                                String headerValue = headerValuesItr.next();
                                                headerValues.add(headerValue);
                                            }
                                        }

                                        headersMap.put(headerName, headerValues);
                                    }
                                }
                            }

                            // Put a valid UploadedFile instance into the map that contains all of the
                            // uploaded file's attributes, along with a successful status.
                            Map<String, Object> attributeMap = new HashMap<String, Object>();
                            String id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
                            String message = null;
                            UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(
                                    copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(),
                                    diskFileItem.getContentType(), headersMap, id, message, fileName,
                                    diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED);

                            addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName,
                                    fileName);
                        } else {

                            if ((fileName != null) && (fileName.trim().length() > 0)) {
                                Exception e = new IOException("Failed to copy the stream of uploaded file=["
                                        + fileName
                                        + "] to a temporary file (possibly a zero-length uploaded file)");
                                UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                                addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e);

                    UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                    String fieldName = Integer.toString(totalFiles);
                    addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                }
            }
        }
    }

    // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in
    // the map so that the developer can have some idea that something went wrong.
    catch (Exception e) {
        logger.error(e);

        UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
        addUploadedFile(uploadedFileMap, "unknown", uploadedFile);
    }

    return uploadedFileMap;
}

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).
 * /*ww  w . j a  v  a 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: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  . jav a 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: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 ww  . jav a2s .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.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 {//from w  w  w  .  j  a  va 2  s .  c  o 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: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  w  w  .  j a  va 2  s  .  c om
        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.sonicle.webtop.core.app.AbstractEnvironmentService.java

public void processUpload(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    ServletFileUpload upload = null;/*from  ww  w  .ja  v a  2s . c o  m*/
    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.oprisnik.semdroid.SemdroidServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.info("doPost");
    StringBuilder sb = new StringBuilder();
    try {//from w w w  .  ja  va 2  s .  c om
        ServletFileUpload upload = new ServletFileUpload();
        // set max size (-1 for unlimited size)
        upload.setSizeMax(1024 * 1024 * 30); // 30MB
        upload.setHeaderEncoding("UTF-8");

        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                // Process regular form fields
                // String fieldname = item.getFieldName();
                // String fieldvalue = item.getString();
                // log.info("Got form field: " + fieldname + " " + fieldvalue);
            } else {
                // Process form file field (input type="file").
                String fieldname = item.getFieldName();
                String filename = FilenameUtils.getBaseName(item.getName());
                log.info("Got file: " + filename);
                InputStream filecontent = null;
                try {
                    filecontent = item.openStream();
                    // analyze
                    String txt = analyzeApk(filecontent);
                    if (txt != null) {
                        sb.append(txt);
                    } else {
                        sb.append("Error. Could not analyze ").append(filename);
                    }
                    log.info("Analysis done!");
                } finally {
                    if (filecontent != null) {
                        filecontent.close();
                    }
                }
            }
        }
        response.getWriter().print(sb.toString());
    } catch (FileUploadException e) {
        throw new ServletException("Cannot parse multipart request.", e);
    } catch (Exception ex) {
        log.warning("Exception: " + ex.getMessage());
        log.throwing(this.getClass().getName(), "doPost", ex);
    }

}