Example usage for org.apache.commons.fileupload FileItem get

List of usage examples for org.apache.commons.fileupload FileItem get

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem get.

Prototype

byte[] get();

Source Link

Document

Returns the contents of the file item as an array of bytes.

Usage

From source file:com.xclinical.mdr.server.DocumentServlet.java

@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    try {/*from ww w  .  jav a2  s.  com*/
        if (ServletFileUpload.isMultipartContent(req)) {
            log.debug("detected multipart content");

            final FileInfo info = new FileInfo();

            ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory());

            @SuppressWarnings("unchecked")
            List<FileItem> items = fileUpload.parseRequest(req);

            String session = null;

            for (Iterator<FileItem> i = items.iterator(); i.hasNext();) {
                log.debug("detected form field");

                FileItem item = (FileItem) i.next();

                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString();

                    if (fieldName != null) {
                        log.debug("{0}={1}", fieldName, fieldValue);
                    } else {
                        log.severe("fieldName may not be null");
                    }

                    if ("session".equals(fieldName)) {
                        session = fieldValue;
                    }
                } else {
                    log.debug("detected content");

                    info.contentName = item.getName();
                    info.contentName = new File(info.contentName).getName();
                    info.contentType = item.getContentType();
                    info.content = item.get();

                    log.debug("{0} bytes", info.content.length);
                }
            }

            if (info.content == null)
                throw new IllegalArgumentException("there is no content");
            if (info.contentType == null)
                throw new IllegalArgumentException("There is no content type");
            if (info.contentName == null)
                throw new IllegalArgumentException("There is no content name");

            Session.runInSession(session, new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    Document document = Document.create(info.contentName, info.contentType, info.content);

                    log.info("Created document " + document.getId());

                    ReferenceDocument referenceDocument = saveFile(req, document);

                    JsonCommandServlet.writeResponse(resp, FlatJsonExporter.of(referenceDocument));
                    return null;
                }
            });
        } else {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

    } catch (FileUploadException e) {
        log.severe(e);
        throw new ServletException(e);
    } catch (Exception e) {
        log.severe(e);
        throw new ServletException(e);
    }
}

From source file:com.ikon.servlet.admin.DatabaseQueryServlet.java

@Override
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);/*  w w w.j a  v  a  2  s . c  o m*/
    String user = request.getRemoteUser();
    ServletContext sc = getServletContext();
    Session session = null;

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            String type = "";
            String qs = "";
            byte[] data = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("qs")) {
                        qs = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("type")) {
                        type = item.getString("UTF-8");
                    }
                } else {
                    data = item.get();
                }
            }

            if (!qs.equals("") && !type.equals("")) {
                session = HibernateUtil.getSessionFactory().openSession();
                sc.setAttribute("qs", qs);
                sc.setAttribute("type", type);

                if (type.equals("jdbc")) {
                    executeJdbc(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_JDBC", null, null, qs);
                } else if (type.equals("hibernate")) {
                    executeHibernate(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_HIBERNATE", null, null, qs);
                } else if (type.equals("metadata")) {
                    executeMetadata(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_METADATA", null, null, qs);
                }
            } else if (data != null && data.length > 0) {
                sc.setAttribute("exception", null);
                session = HibernateUtil.getSessionFactory().openSession();
                executeUpdate(session, data, sc, request, response);

                // Activity log
                UserActivity.log(user, "ADMIN_DATABASE_QUERY_FILE", null, null, new String(data));
            } else {
                sc.setAttribute("qs", qs);
                sc.setAttribute("type", type);
                sc.setAttribute("exception", null);
                sc.setAttribute("globalResults", new ArrayList<DatabaseQueryServlet.GlobalResult>());
                sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
            }
        }
    } catch (FileUploadException e) {
        sendError(sc, request, response, e);
    } catch (SQLException e) {
        sendError(sc, request, response, e);
    } catch (HibernateException e) {
        sendError(sc, request, response, e);
    } catch (DatabaseException e) {
        sendError(sc, request, response, e);
    } catch (IllegalAccessException e) {
        sendError(sc, request, response, e);
    } catch (InvocationTargetException e) {
        sendError(sc, request, response, e);
    } catch (NoSuchMethodException e) {
        sendError(sc, request, response, e);
    } finally {
        HibernateUtil.close(session);
    }
}

From source file:net.i2cat.csade.life2.backoffice.servlet.UserManagementService.java

/**
 * Funcin que se ejecuta cuando el servlet recibe los datos
 *///from w ww .j  a va 2  s.  co  m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ChangablePropertiesManager cpm = new ChangablePropertiesManager(this.getServletContext());
    String operation = request.getParameter("operation");
    PlatformUserManager pum = new PlatformUserManager();
    String data = "";
    if (operation != null && !"".equals(operation)) {
        if (operation.equals("savePicturePreference")) {
            String photo_hor = request.getParameter("photo_hor");
            cpm.saveProperty("photo_hor", photo_hor);

            data = "{ \"message\": \"preferences saved.\" }";
        }
        if (operation.equals("getPicturePreference")) {
            String photo_hor = cpm.getProperty("photo_hor");

            data = "{ \"photo_hor\": \"" + photo_hor + "\"}";
        }

        if (operation.equals("getPlatformUser")) {
            String login = request.getParameter("login");
            try {
                data = pum.getUser(login).toJSON().toString();
            } catch (RemoteException re) {
                data = "{ \"message\": \"Could not not retrieve user with login=" + login + " Reason:"
                        + re.getMessage() + ".\" }";
            } catch (ServiceException se) {
                data = "{ \"message\": \"Could not not retrieve user with login=" + login + " Reason:"
                        + se.getMessage() + ".\" }";
            }
        }
        if (operation.equals("delPlatformUser")) {
            String login = request.getParameter("login");
            try {
                if (!request.isUserInRole("admin"))
                    throw new ServiceException("You are not allowed to delete users");
                if (login != null && login.equals(request.getUserPrincipal().getName()))
                    throw new ServiceException("You cannot delete your own user");
                pum.deleteUser(login);
                data = "{ \"message\": \"User with login " + login + " deleted.\" }";
            } catch (RemoteException re) {
                data = "{ \"message\": \"Could not not delete user with login=" + login + " Reason:"
                        + re.getMessage() + ".\" }";
            } catch (ServiceException se) {
                data = "{ \"message\": \"Could not not delete user with login=" + login + " Reason:"
                        + se.getMessage() + ".\" }";
            }
        }
        if (operation.equals("savePlatformUser")) {
            FileItem uploadedFile = null;
            PlatformUser user = null;
            int res = 0;
            byte[] foto = null;
            try {
                if (!request.isUserInRole("admin"))
                    throw new ServiceException("You are not allowed to upadte users");
                user = new PlatformUser();
                user.setNew(false);
                ServletFileUpload sfu = new ServletFileUpload(new DiskFileItemFactory());
                sfu.setFileSizeMax(329000);
                sfu.setHeaderEncoding("UTF-8");
                @SuppressWarnings("unchecked")
                List<FileItem> items = sfu.parseRequest(request);

                for (FileItem item : items) {
                    if (item.isFormField()) {
                        if (item.getFieldName().equals("login"))
                            user.setLogin(item.getString());
                        if (item.getFieldName().equals("username"))
                            user.setLogin(item.getString());
                        if (item.getFieldName().equals("password")) {
                            user.setPass(item.getString());
                        }
                        if (item.getFieldName().equals("idUser")) {
                            if (item.getString() == null || "".equals(item.getString()))
                                user.setNew(true);
                        }
                        if (item.getFieldName().equals("name")) {
                            byte[] fnb = item.get();
                            String text = PasswordGenerator.utf8Decoder(fnb);
                            user.setName(text);
                        }
                        if (item.getFieldName().equals("email")) {
                            String mail = item.getString();
                            if (MailUtils.isValidEmail(mail))
                                user.setEmail(mail);
                            else
                                throw new ServiceException("El email del usuario es incorrecto");
                        }
                        if (item.getFieldName().equals("telephonenumber"))
                            user.setTelephonenumber(item.getString());
                        if (item.getFieldName().equals("role"))
                            user.setRole(Integer.parseInt(item.getString()));
                        if (item.getFieldName().equals("language"))
                            user.setLanguage(item.getString());
                        if (item.getFieldName().equals("notification_level"))
                            user.setNotification_level(item.getString());
                        if (item.getFieldName().equals("promoter_id"))
                            user.setPromoter_id(item.getString());
                        if (item.getFieldName().equals("user_average_mark"))
                            user.setUser_average_mark(item.getString());
                        if (item.getFieldName().equals("user_votes"))
                            user.setUser_votes(item.getString());
                        if (item.getFieldName().equals("latitude"))
                            user.setHome_area_lat(item.getString());
                        if (item.getFieldName().equals("longitude"))
                            user.setHome_area_lon(item.getString());
                        if (item.getFieldName().equals("enabled"))
                            user.setEnabled(item.getString().equals("0") ? 0 : 1);
                    } else {
                        uploadedFile = item;
                        String inputExtension = FilenameUtils
                                .getExtension(uploadedFile.getName().toLowerCase());
                        if ("jpg".equals(inputExtension) || "gif".equals(inputExtension)
                                || "png".equals(inputExtension)) {
                            InputStream filecontent = item.getInputStream();
                            foto = new byte[(int) uploadedFile.getSize()];
                            filecontent.read(foto, 0, (int) uploadedFile.getSize());

                        }
                        //else
                        //   throw new FileUploadException("Extension not supported. Only jpg,gif or png files are allowed");
                    }
                }
                res = pum.saveUser(user);
                if (foto != null) {
                    //String v=cpm.getProperty("photo_hor");
                    //byte[] resizedPhoto=ImageUtil.resizeImageAsJPG(foto, (v==null || "".equals(v)) ?200:Integer.parseInt(v));
                    pum.uploadFoto(user.getLogin(), foto);
                }
                data = "{ \"message\": \"User with login " + user.getLogin() + " (id=" + res + ") saved.\" }";
            } catch (RemoteException exc) {
                data = "{ \"message\": \"Could not not save user with login=" + user.getLogin() + " Reason:"
                        + exc.getMessage() + ".\" }";
            } catch (ServiceException exc) {
                data = "{ \"message\": \"Could not not save user with login=" + user.getLogin() + " Reason:"
                        + exc.getMessage() + ".\" }";
            } catch (FileUploadException exc) {
                data = "{ \"message\": \"User with login " + user.getLogin() + " (id=" + res
                        + ") saved, but there was a problem uploading picture:" + exc.getMessage() + "\" }";
            }
        }
        if (operation.equals("listPlatformUsers")) {
            JQueryDataTableParamModel param = DataTablesParamUtility.getParam(request);
            try {
                JSONObject jsonResponse = pum.getPlatformUsersJSON(param);
                data = jsonResponse.toString();

            } catch (RemoteException re) {
                data = "{ \"message\": \"Could not not retrieve platform user listing. Reason:"
                        + re.getMessage() + ".\" }";
            } catch (ServiceException se) {
                data = "{ \"message\": \"Could not not retrieve platform user listing.  Reason:"
                        + se.getMessage() + ".\" }";
            }
        }
    }
    response.setContentType("application/json;charset=UTF-8");
    //response.setContentType("application/json");
    response.getWriter().print(data);
    response.getWriter().close();
}

From source file:fr.paris.lutece.portal.web.admin.AdminPageJspBean.java

/**
 * Processes of the modification of the page informations
 *
 * @param request The http request/*from www. j av  a2 s .c o m*/
 * @return The jsp url result of the process
 */
public String doModifyPage(HttpServletRequest request) {
    MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
    int nPageId = Integer.parseInt(mRequest.getParameter(Parameters.PAGE_ID));

    Page page = PageHome.getPage(nPageId);
    Integer nOldAutorisationNode = page.getIdAuthorizationNode();

    String strErrorUrl = getPageData(mRequest, page);

    if (strErrorUrl != null) {
        return strErrorUrl;
    }

    int nParentPageId = Integer.parseInt(mRequest.getParameter(Parameters.PARENT_ID));

    if (nParentPageId != page.getParentPageId()) {
        strErrorUrl = getNewParentPageId(mRequest, page, nParentPageId);

        if (strErrorUrl != null) {
            return strErrorUrl;
        }
    }

    //set the authorization node
    if (page.getNodeStatus() != 0) {
        Page parentPage = PageHome.getPage(page.getParentPageId());
        page.setIdAuthorizationNode(parentPage.getIdAuthorizationNode());
    } else {
        page.setIdAuthorizationNode(page.getId());
    }

    if ((page.getIdAuthorizationNode() == null)
            || !page.getIdAuthorizationNode().equals(nOldAutorisationNode)) {
        PageService.updateChildrenAuthorizationNode(page.getId(), page.getIdAuthorizationNode());
    }

    String strUpdatePicture = mRequest.getParameter(PARAMETER_PAGE_TEMPLATE_UPDATE_IMAGE);
    FileItem item = mRequest.getFile(PARAMETER_IMAGE_CONTENT);

    boolean bUpdatePicture = false;
    String strPictureName = FileUploadService.getFileNameOnly(item);

    if (strUpdatePicture != null) {
        if (strPictureName.equals("")) {
            return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FILE, AdminMessage.TYPE_STOP);
        } else {
            bUpdatePicture = true;
        }
    }

    if (bUpdatePicture) {
        byte[] bytes = item.get();
        String strMimeType = item.getContentType();
        page.setImageContent(bytes);
        page.setMimeType(strMimeType);
    }

    // Updates the page
    _pageService.updatePage(page);

    // Displays again the current page with the modifications
    return getUrlPage(nPageId);
}

From source file:fr.paris.lutece.plugins.document.web.DocumentTypeJspBean.java

/**
 * Reads stylesheet's data// w  w  w . j  av a 2 s  .  c  o  m
 * @param multipartRequest The request
 * @return An error message URL or null if no error
 */
private String getStyleSheets(MultipartHttpServletRequest multipartRequest) {
    String strErrorUrl = null;

    String strCode = multipartRequest.getParameter(PARAMETER_DOCUMENT_TYPE_CODE);
    String strUpdateStylesheetAdmin = multipartRequest.getParameter(PARAMETER_UPDATE_STYLESHEET_ADMIN);
    String strUpdateStylesheetContent = multipartRequest.getParameter(PARAMETER_UPDATE_STYLESHEET_CONTENT);

    // Gets XSL for the back office if defined
    FileItem fileXslAdmin = multipartRequest.getFile(PARAMETER_STYLESHEET_ADMIN);
    String strFilename = FileUploadService.getFileNameOnly(fileXslAdmin);

    if ((strUpdateStylesheetAdmin != null) && strUpdateStylesheetAdmin.equals(UPDATE_VALUE)
            && (strFilename != null) && (!strFilename.equals(""))) {
        byte[] baXslAdmin = fileXslAdmin.get();

        // Check the XML validity of the XSL stylesheet
        if (isValid(baXslAdmin) != null) {
            Object[] args = { isValid(baXslAdmin) };

            return AdminMessageService.getMessageUrl(multipartRequest, MESSAGE_STYLESHEET_NOT_VALID, args,
                    AdminMessage.TYPE_STOP);
        }

        DocumentTypeHome.setAdminStyleSheet(baXslAdmin, strCode);
    }

    // Gets XSL for the back office if defined
    FileItem fileXslContent = multipartRequest.getFile(PARAMETER_STYLESHEET_CONTENT);
    strFilename = FileUploadService.getFileNameOnly(fileXslContent);

    if ((strUpdateStylesheetContent != null) && strUpdateStylesheetContent.equals(UPDATE_VALUE)
            && (strFilename != null) && (!strFilename.equals(""))) {
        byte[] baXslContent = fileXslContent.get();

        // Check the XML validity of the XSL stylesheet
        if (isValid(baXslContent) != null) {
            Object[] args = { isValid(baXslContent) };

            return AdminMessageService.getMessageUrl(multipartRequest, MESSAGE_STYLESHEET_NOT_VALID, args,
                    AdminMessage.TYPE_STOP);
        }

        DocumentTypeHome.setContentStyleSheet(baXslContent, strCode);
    }

    //clear the cache
    PortalService.resetCache();

    return strErrorUrl;
}

From source file:com.wordpress.metaphorm.authProxy.httpClient.impl.OAuthProxyConnectionApacheHttpCommonsClientImpl.java

/**
 * Sets up the given {@link PostMethod} to send the same multipart POST
 * data as was sent in the given {@link HttpServletRequest}
 * @param postMethodProxyRequest The {@link PostMethod} that we are
 *                                configuring to send a multipart POST request
 * @param httpServletRequest The {@link HttpServletRequest} that contains
 *                            the mutlipart POST data to be sent via the {@link PostMethod}
 *///from  w  w  w. j a  v  a  2 s.c o  m
@SuppressWarnings("unchecked")
private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws IOException {

    _log.debug("handleMultipartPost()");

    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams());
        postMethodProxyRequest.setRequestEntity(multipartRequestEntity);
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        postMethodProxyRequest.setRequestHeader(HttpConstants.STRING_CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new IOException(fileUploadException);
    }
}

From source file:controllers.controller.java

private void insertarObjetoArchivo(HttpSession session, HttpServletRequest request,
        HttpServletResponse response, QUID quid, PrintWriter out, HashMap parameters, LinkedList filesToUpload,
        String FormFrom) throws Exception {
    if (parameters.get("idTipoArchivo") == null || parameters.get("idTipoArchivo").equals("")) {
        this.getServletConfig().getServletContext()
                .getRequestDispatcher("" + PageParameters.getParameter("msgUtil")
                        + "/msgNRedirect.jsp?title=Error&type=error&msg=Seleccione el tipo de archivo.&url="
                        + PageParameters.getParameter("mainContext") + PageParameters.getParameter("gui")
                        + "/Insert_ObjetoArchivo.jsp?" + WebUtil.encode(session, "imix") + "="
                        + WebUtil.encode(session, UTime.getTimeMilis()) + "_param_nombreObjeto="
                        + parameters.get("nombreObjeto") + "_param_idObjeto=" + parameters.get("idObjeto"))
                .forward(request, response);
    } else if (parameters.get("nombreArchivo") == null || parameters.get("nombreArchivo").equals("")) {
        this.getServletConfig().getServletContext()
                .getRequestDispatcher("" + PageParameters.getParameter("msgUtil")
                        + "/msgNRedirect.jsp?title=Error&type=error&msg=Escriba el nombre del archivo.&url="
                        + PageParameters.getParameter("mainContext") + PageParameters.getParameter("gui")
                        + "/Insert_ObjetoArchivo.jsp?" + WebUtil.encode(session, "imix") + "="
                        + WebUtil.encode(session, UTime.getTimeMilis()) + "_param_nombreObjeto="
                        + parameters.get("nombreObjeto") + "_param_idObjeto=" + parameters.get("idObjeto"))
                .forward(request, response);
    } else if (parameters.get("descripcion") == null
            || parameters.get("descripcion").toString().trim().equals("")) {
        this.getServletConfig().getServletContext()
                .getRequestDispatcher("" + PageParameters.getParameter("msgUtil")
                        + "/msgNRedirect.jsp?title=Error&type=error&msg=Escriba una descripcin.&url="
                        + PageParameters.getParameter("mainContext") + PageParameters.getParameter("gui")
                        + "/Insert_ObjetoArchivo.jsp?" + WebUtil.encode(session, "imix") + "="
                        + WebUtil.encode(session, UTime.getTimeMilis()) + "_param_nombreObjeto="
                        + parameters.get("nombreObjeto") + "_param_idObjeto=" + parameters.get("idObjeto"))
                .forward(request, response);
    } else if (parameters.get("tipoAcceso").equals("")) {
        this.getServletConfig().getServletContext().getRequestDispatcher(""
                + PageParameters.getParameter("msgUtil")
                + "/msgNRedirect.jsp?title=Error&type=error&msg=Seleccione el tipo de acceso para el archivo.&url="
                + PageParameters.getParameter("mainContext") + PageParameters.getParameter("gui")
                + "/Insert_ObjetoArchivo.jsp?" + WebUtil.encode(session, "imix") + "="
                + WebUtil.encode(session, UTime.getTimeMilis()) + "_param_nombreObjeto="
                + parameters.get("nombreObjeto") + "_param_idObjeto=" + parameters.get("idObjeto"))
                .forward(request, response);
    } else if (filesToUpload.isEmpty()) {
        this.getServletConfig().getServletContext().getRequestDispatcher(""
                + PageParameters.getParameter("msgUtil")
                + "/msgNRedirect.jsp?title=Error&type=error&msg=No ha seleccionado ningn archivo.&url="
                + PageParameters.getParameter("mainContext") + PageParameters.getParameter("gui")
                + "/Insert_ObjetoArchivo.jsp?" + WebUtil.encode(session, "imix") + "="
                + WebUtil.encode(session, UTime.getTimeMilis()) + "_param_nombreObjeto="
                + parameters.get("nombreObjeto") + "_param_idObjeto=" + parameters.get("idObjeto"))
                .forward(request, response);
    } else if (!filesToUpload.isEmpty()) {
        String idObjeto = WebUtil.decode(session, parameters.get("idObjeto").toString());
        String fechaActualizacion = UTime.calendar2SQLDateFormat(Calendar.getInstance());
        String descripcion = WebUtil.decode(session, parameters.get("descripcion").toString());
        String ubicacionFisica = PageParameters.getParameter("folderDocs");
        String idTipoArchivo = WebUtil.decode(session, parameters.get("idTipoArchivo").toString());
        String nombreObjeto = WebUtil.decode(session, parameters.get("nombreObjeto").toString());
        String keyWords = parameters.get("keywords").toString();
        String nombreArchivo = parameters.get("nombreArchivo").toString();
        String FK_ID_Plantel = session.getAttribute("FK_ID_Plantel").toString();

        //File verifyFolder = new File(PageParameters.getParameter("folderDocs"));
        File verifyFolder = new File(ubicacionFisica);
        if (!verifyFolder.exists()) {
            verifyFolder.mkdirs();//from   w  w  w.  ja v a  2s . com
        }
        int sucess = 0;
        for (int i = 0; i < filesToUpload.size(); i++) {
            FileItem itemToUpload = null;
            itemToUpload = (FileItem) filesToUpload.get(i);

            String extension = FileUtil.getExtension(itemToUpload.getName());
            String hashName = JHash.getFileDigest(itemToUpload.get(), "MD5") + extension;

            long tamanio = itemToUpload.getSize();

            if (this.validarDocumentExtension(session, request, response, quid, out, extension)) {
                File fileToWrite = new File(ubicacionFisica, hashName);
                Transporter tport = quid.insertArchivo4Objeto(idObjeto, nombreObjeto, idTipoArchivo,
                        nombreArchivo, descripcion, ubicacionFisica, extension, fechaActualizacion, tamanio,
                        WebUtil.decode(session, parameters.get("tipoAcceso").toString()).toLowerCase(),
                        keyWords, hashName, FK_ID_Plantel);
                if (tport.getCode() == 0) {
                    if (!fileToWrite.exists()) {
                        itemToUpload.write(fileToWrite);
                    }
                    sucess += 1;
                }
            } else {
                sucess = -1;
            }
        }
        if (sucess != -1) {
            this.getServletConfig().getServletContext()
                    .getRequestDispatcher("" + PageParameters.getParameter("msgUtil")
                            + "/msgNRedirect.jsp?title=Operacin Exitosa&type=info&msg=Se han guardado "
                            + sucess + " de " + filesToUpload.size() + " archivos.&url="
                            + PageParameters.getParameter("mainContext") + PageParameters.getParameter("gui")
                            + "/Insert_ObjetoArchivo.jsp?" + WebUtil.encode(session, "imix") + "="
                            + WebUtil.encode(session, UTime.getTimeMilis()) + "_param_nombreObjeto="
                            + parameters.get("nombreObjeto") + "_param_idObjeto=" + parameters.get("idObjeto"))
                    .forward(request, response);
        }

    }

}

From source file:fr.paris.lutece.plugins.directory.business.EntryTypeFile.java

/**
 * {@inheritDoc}/*  w w  w.  j av a 2  s. c om*/
 */
@Override
public void getRecordFieldData(Record record, HttpServletRequest request, boolean bTestDirectoryError,
        boolean bAddNewValue, List<RecordField> listRecordField, Locale locale) throws DirectoryErrorException {
    if (request instanceof MultipartHttpServletRequest) {
        //get asynchronous file items
        List<FileItem> fileItems = getFileSources(request);

        //if asynchronous file items is empty get the file in the multipart request
        if (CollectionUtils.isEmpty(fileItems)) {
            FileItem fileItem = ((MultipartHttpServletRequest) request)
                    .getFile(PREFIX_ENTRY_ID + this.getIdEntry());

            if (fileItem != null) {
                fileItems = new ArrayList<FileItem>();
                fileItems.add(fileItem);
            }
        }

        if ((fileItems != null) && !fileItems.isEmpty()) {
            // Checks
            if (bTestDirectoryError) {
                this.checkRecordFieldData(fileItems, locale);
            }

            for (FileItem fileItem : fileItems) {
                String strFilename = (fileItem != null) ? FileUploadService.getFileNameOnly(fileItem)
                        : StringUtils.EMPTY;

                // Add the file to the record fields list
                RecordField recordField = new RecordField();
                recordField.setEntry(this);

                if ((fileItem != null) && (fileItem.get() != null)
                        && (fileItem.getSize() < Integer.MAX_VALUE)) {
                    PhysicalFile physicalFile = new PhysicalFile();
                    physicalFile.setValue(fileItem.get());

                    File file = new File();
                    file.setPhysicalFile(physicalFile);
                    file.setTitle(strFilename);
                    file.setSize((int) fileItem.getSize());
                    file.setMimeType(FileSystemUtil.getMIMEType(strFilename));

                    recordField.setFile(file);
                }

                listRecordField.add(recordField);
            }
        } else if (bTestDirectoryError && this.isMandatory()) {
            throw new DirectoryErrorException(this.getTitle());
        }
    } else if (bTestDirectoryError) {
        throw new DirectoryErrorException(this.getTitle());
    }
}

From source file:io.fabric8.gateway.servlet.ProxyServlet.java

/**
 * Sets up the given {@link EntityEnclosingMethod} to send the same multipart
 * data as was sent in the given {@link javax.servlet.http.HttpServletRequest}
 *
 * @param entityEnclosingMethod The {@link EntityEnclosingMethod} that we are
 *                               configuring to send a multipart request
 * @param httpServletRequest     The {@link javax.servlet.http.HttpServletRequest} that contains
 *                               the mutlipart data to be sent via the {@link EntityEnclosingMethod}
 *//*w  w w .j ava2s  .co  m*/
private void handleMultipartPost(EntityEnclosingMethod entityEnclosingMethod,
        HttpServletRequest httpServletRequest) throws ServletException {
    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[] {}), entityEnclosingMethod.getParams());
        entityEnclosingMethod.setRequestEntity(multipartRequestEntity);
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        entityEnclosingMethod.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}

From source file:fina.usuario.servlet.usuarioServlet.java

private void modificarUsu(HttpServletRequest request, HttpServletResponse response,
        boolean modificarUsuarioSession) {

    JSONObject jsonResult = new JSONObject();
    Mensaje mensaje = new Mensaje(true, Mensaje.INFORMACION);
    boolean guardar = false;
    try {/*from   w w w . ja va 2s  . c o m*/
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> listField = upload.parseRequest(request);
        Usuario usuario = new Usuario();
        UsuarioDao usuarioDao = new UsuarioDao();
        for (FileItem file : listField) {
            if (file.getFieldName().equals("txtNombres")) {
                usuario.setNombres(file.getString().trim());
            } else if (file.getFieldName().equals("txtApellidos")) {
                usuario.setApellidos(file.getString().trim());
            } else if (file.getFieldName().equals("txtFechaNacimiento")) {
                usuario.setFechaNacimiento(format.parse(file.getString().trim()));
            } else if (file.getFieldName().equals("txtUsuario")) {
                usuario.setUsername(file.getString().trim());
            } else if (file.getFieldName().equals("txtContrasenia")) {
                usuario.setContrasenia(file.getString());
            } else if (file.getFieldName().equals("rbSexo")) {
                usuario.setSexo("M".equals(file.getString()));
            } else if (file.getFieldName().equals("txtFoto")) {
                byte[] imagen = file.get();
                if (imagen != null && imagen.length > 0) {
                    usuario.setFoto(imagen);
                    usuario.setNombreFoto(file.getName());
                } else {
                    Usuario actual = usuarioDao.Obtener(usuario.getIdUSUARIO());
                    if (actual != null) {
                        usuario.setFoto(actual.getFoto());
                        usuario.setNombreFoto(actual.getNombreFoto());
                    }
                }
            } else if (file.getFieldName().equals("txtDNI")) {
                usuario.setDni(file.getString().trim());
            } else if (file.getFieldName().equals("tipoUsuario")) {
                Tipousuario tipou = usuarioDao.getTipousuarioById(file.getString().trim());
                usuario.setIdTipoUsuario(tipou);
            } else if (file.getFieldName().equals("txtIdUsuario")) {
                usuario.setIdUSUARIO(Integer.valueOf(file.getString().isEmpty() ? "-1" : file.getString()));
            } else if (file.getFieldName().equals("txtEstado")) {
                usuario.setEliminado(Boolean.valueOf(file.getString()));
            } else if (file.getFieldName().equals("txtGuardarUsuario")) {
                guardar = Boolean.valueOf(file.getString());
            }
        }
        if (usuario.getSexo() == null) {
            usuario.setSexo(true);
        }
        if (guardar) {
            usuario.setIdUSUARIO(null);
            usuarioDao.Insertar(usuario);
        } else {
            usuarioDao.Actualizar(usuario);
        }

        if (modificarUsuarioSession) {
            request.getSession().setAttribute("usuarioLogeado", usuario);
        }
        mensaje.setMensaje("Se registro correctamente.");

    } catch (Exception ex) {
        mensaje.establecerError(ex);
    }
    try {
        JSONObject jsonMensaje = new JSONObject(mensaje);
        jsonResult.put("msj", jsonMensaje);
        enviarDatos(response, jsonResult.toString());
    } catch (Exception ex) {
    }
}