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

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

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem 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:it.eng.spagobi.engines.talend.services.JobUploadService.java

private String[] processUploadedFile(FileItem item, JobDeploymentDescriptor jobDeploymentDescriptor)
        throws ZipException, IOException, SpagoBIEngineException {
    String fieldName = item.getFieldName();
    String fileName = item.getName();
    String contentType = item.getContentType();
    boolean isInMemory = item.isInMemory();
    long sizeInBytes = item.getSize();

    if (fieldName.equalsIgnoreCase("deploymentDescriptor"))
        return null;

    RuntimeRepository runtimeRepository = TalendEngine.getRuntimeRepository();
    File jobsDir = new File(runtimeRepository.getRootDir(),
            jobDeploymentDescriptor.getLanguage().toLowerCase());
    File projectDir = new File(jobsDir, jobDeploymentDescriptor.getProject());
    File tmpDir = new File(projectDir, "tmp");
    if (!tmpDir.exists())
        tmpDir.mkdirs();//from w w w.  j  a  va 2  s.c  om
    File uploadedFile = new File(tmpDir, fileName);

    try {
        item.write(uploadedFile);
    } catch (Exception e) {
        e.printStackTrace();
    }

    String[] dirNames = ZipUtils.getDirectoryNameByLevel(new ZipFile(uploadedFile), 2);
    List dirNameList = new ArrayList();
    for (int i = 0; i < dirNames.length; i++) {
        if (!dirNames[i].equalsIgnoreCase("lib"))
            dirNameList.add(dirNames[i]);
    }
    String[] jobNames = (String[]) dirNameList.toArray(new String[0]);

    runtimeRepository.deployJob(jobDeploymentDescriptor, new ZipFile(uploadedFile));
    uploadedFile.delete();
    tmpDir.delete();

    return jobNames;
}

From source file:com.github.davidcarboni.encryptedfileupload.EncryptedFileItemSerializeTest.java

/**
 * Compare FileItem's (except the byte[] content)
 *///from   w ww  .java 2 s .  c om
private void compareFileItems(FileItem origItem, FileItem newItem) {
    assertTrue("Compare: is in Memory", origItem.isInMemory() == newItem.isInMemory());
    assertTrue("Compare: is Form Field", origItem.isFormField() == newItem.isFormField());
    assertEquals("Compare: Field Name", origItem.getFieldName(), newItem.getFieldName());
    assertEquals("Compare: Content Type", origItem.getContentType(), newItem.getContentType());
    assertEquals("Compare: File Name", origItem.getName(), newItem.getName());
}

From source file:it.eng.spagobi.engines.talend.services.JobUploadService.java

private void publishOnSpagoBI(FileItem item, JobDeploymentDescriptor jobDeploymentDescriptor)
        throws ZipException, IOException, SpagoBIEngineException {
    String fieldName = item.getFieldName();
    String fileName = item.getName();
    String contentType = item.getContentType();
    boolean isInMemory = item.isInMemory();
    long sizeInBytes = item.getSize();

    if (fieldName.equalsIgnoreCase("deploymentDescriptor"))
        return;/* w w w  .j av a 2s  .  c  om*/

    RuntimeRepository runtimeRepository = TalendEngine.getRuntimeRepository();

    String projectName = jobDeploymentDescriptor.getProject();
    String projectLanguage = jobDeploymentDescriptor.getLanguage().toLowerCase();
    String jobName = "JOB_NAME";
    String contextName = "Default";
    String template = "";
    template += "<etl>\n";
    template += "\t<job project=\"" + projectName + "\" ";
    template += "jobName=\"" + projectName + "\" ";
    template += "context=\"" + projectName + "\" ";
    template += "language=\"" + contextName + "\" />\n";
    template += "</etl>";

    BASE64Encoder encoder = new BASE64Encoder();
    String templateBase64Coded = encoder.encode(template.getBytes());

    TalendEngineConfig config = TalendEngineConfig.getInstance();

    String user = "biadmin";
    String password = "biadmin";
    String label = "ETL_JOB";
    String name = "EtlJob";
    String description = "Etl Job";
    boolean encrypt = false;
    boolean visible = true;
    String functionalitiyCode = config.getSpagobiTargetFunctionalityLabel();
    String type = "ETL";
    String state = "DEV";

    try {

        //PublishAccessUtils.publish(spagobiurl, user, password, label, name, description, encrypt, visible, type, state, functionalitiyCode, templateBase64Coded);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.exedio.cope.live.Bar.java

void doRequest(final HttpServletRequest request, final HttpSession httpSession,
        final HttpServletResponse response, final Anchor anchor) throws IOException {
    if (!Cop.isPost(request)) {
        try {//from w w  w. j av  a 2 s  . co m
            startTransaction("redirectHome");
            anchor.redirectHome(request, response);
            model.commit();
        } finally {
            model.rollbackIfNotCommitted();
        }
        return;
    }

    final String referer;

    if (isMultipartContent(request)) {
        final HashMap<String, String> fields = new HashMap<String, String>();
        final HashMap<String, FileItem> files = new HashMap<String, FileItem>();
        final FileItemFactory factory = new DiskFileItemFactory();
        final ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding(UTF_8.name());
        try {
            for (final Iterator<?> i = upload.parseRequest(request).iterator(); i.hasNext();) {
                final FileItem item = (FileItem) i.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString(UTF_8.name()));
                else
                    files.put(item.getFieldName(), item);
            }
        } catch (final FileUploadException e) {
            throw new RuntimeException(e);
        }

        final String featureID = fields.get(FEATURE);
        if (featureID == null)
            throw new NullPointerException();

        final Media feature = (Media) model.getFeature(featureID);
        if (feature == null)
            throw new NullPointerException(featureID);

        final String itemID = fields.get(ITEM);
        if (itemID == null)
            throw new NullPointerException();

        final FileItem file = files.get(FILE);

        try {
            startTransaction("publishFile(" + featureID + ',' + itemID + ')');

            final Item item = model.getItem(itemID);

            if (fields.get(PUBLISH_NOW) != null) {
                for (final History history : History.getHistories(item.getCopeType())) {
                    final History.Event event = history.createEvent(item, anchor.getHistoryAuthor(), false);
                    event.createFeature(feature, feature.getName(),
                            feature.isNull(item) ? null
                                    : ("file type=" + feature.getContentType(item) + " size="
                                            + feature.getLength(item)),
                            "file name=" + file.getName() + " type=" + file.getContentType() + " size="
                                    + file.getSize());
                }

                // TODO use more efficient setter with File or byte[]
                feature.set(item, file.getInputStream(), file.getContentType());
            } else {
                anchor.modify(file, feature, item);
            }

            model.commit();
        } catch (final NoSuchIDException e) {
            throw new RuntimeException(e);
        } finally {
            model.rollbackIfNotCommitted();
        }

        referer = fields.get(REFERER);
    } else // isMultipartContent
    {
        if (request.getParameter(BORDERS_ON) != null || request.getParameter(BORDERS_ON_IMAGE) != null) {
            anchor.borders = true;
        } else if (request.getParameter(BORDERS_OFF) != null
                || request.getParameter(BORDERS_OFF_IMAGE) != null) {
            anchor.borders = false;
        } else if (request.getParameter(CLOSE) != null || request.getParameter(CLOSE_IMAGE) != null) {
            httpSession.removeAttribute(LoginServlet.ANCHOR);
        } else if (request.getParameter(SWITCH_TARGET) != null) {
            anchor.setTarget(servlet.getTarget(request.getParameter(SWITCH_TARGET)));
        } else if (request.getParameter(SAVE_TARGET) != null) {
            try {
                startTransaction("saveTarget");
                anchor.getTarget().save(anchor);
                model.commit();
            } finally {
                model.rollbackIfNotCommitted();
            }
            anchor.notifyPublishedAll();
        } else {
            final String featureID = request.getParameter(FEATURE);
            if (featureID == null)
                throw new NullPointerException();

            final Feature featureO = model.getFeature(featureID);
            if (featureO == null)
                throw new NullPointerException(featureID);

            final String itemID = request.getParameter(ITEM);
            if (itemID == null)
                throw new NullPointerException();

            if (featureO instanceof StringField) {
                final StringField feature = (StringField) featureO;
                final String value = request.getParameter(TEXT);

                try {
                    startTransaction("barText(" + featureID + ',' + itemID + ')');

                    final Item item = model.getItem(itemID);

                    if (request.getParameter(PUBLISH_NOW) != null) {
                        String v = value;
                        if ("".equals(v))
                            v = null;
                        for (final History history : History.getHistories(item.getCopeType())) {
                            final History.Event event = history.createEvent(item, anchor.getHistoryAuthor(),
                                    false);
                            event.createFeature(feature, feature.getName(), feature.get(item), v);
                        }
                        feature.set(item, v);
                        anchor.notifyPublished(feature, item);
                    } else {
                        anchor.modify(value, feature, item);
                    }

                    model.commit();
                } catch (final NoSuchIDException e) {
                    throw new RuntimeException(e);
                } finally {
                    model.rollbackIfNotCommitted();
                }
            } else {
                final IntegerField feature = (IntegerField) featureO;
                final String itemIDFrom = request.getParameter(ITEM_FROM);
                if (itemIDFrom == null)
                    throw new NullPointerException();

                try {
                    startTransaction("swapPosition(" + featureID + ',' + itemIDFrom + ',' + itemID + ')');

                    final Item itemFrom = model.getItem(itemIDFrom);
                    final Item itemTo = model.getItem(itemID);

                    final Integer positionFrom = feature.get(itemFrom);
                    final Integer positionTo = feature.get(itemTo);
                    feature.set(itemFrom, feature.getMinimum());
                    feature.set(itemTo, positionFrom);
                    feature.set(itemFrom, positionTo);

                    for (final History history : History.getHistories(itemFrom.getCopeType())) {
                        final History.Event event = history.createEvent(itemFrom, anchor.getHistoryAuthor(),
                                false);
                        event.createFeature(feature, feature.getName(), positionFrom, positionTo);
                    }
                    for (final History history : History.getHistories(itemTo.getCopeType())) {
                        final History.Event event = history.createEvent(itemTo, anchor.getHistoryAuthor(),
                                false);
                        event.createFeature(feature, feature.getName(), positionTo, positionFrom);
                    }

                    model.commit();
                } catch (final NoSuchIDException e) {
                    throw new RuntimeException(e);
                } finally {
                    model.rollbackIfNotCommitted();
                }
            }
        }

        referer = request.getParameter(REFERER);
    }

    if (referer != null)
        response.sendRedirect(response.encodeRedirectURL(referer));
}

From source file:com.dien.upload.server.UploadShpServlet.java

/**
 * Override executeAction to save the received files in a custom place and delete this items from session.
 *//*from  w  ww  . j av  a2  s. co m*/
@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    JSONObject obj = new JSONObject();
    HttpSession session = request.getSession();
    User users = (User) session.getAttribute("user");
    if (users != null && users.isDataAuth()) {

        for (FileItem item : sessionFiles) {
            if (false == item.isFormField()) {

                try {
                    // 1. ?
                    File file = File.createTempFile(item.getFieldName(), ".zip");
                    item.write(file);
                    FileInputStream fis = new FileInputStream(file);
                    if (fis.available() > 0) {
                        System.out.println("File has " + fis.available() + " bytes");
                        // 2.zip
                        CopyFile copyFile = new CopyFile();

                        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                        //
                        String tmpFolder = Config.getOutPath() + File.separator + item.getFieldName() + "_"
                                + df.format(new Date()) + "_" + new Random().nextInt(1000);
                        copyFile.delFolder(tmpFolder);
                        copyFile.newFolder(tmpFolder);
                        ZipUtil.unZip(file.getAbsolutePath(), tmpFolder + File.separator, true);
                        // 3.???shp
                        ArrayList<String> slist = new ArrayList<String>();
                        getAllFile(new File(tmpFolder), slist);
                        if (slist.size() > 0) {
                            ArrayList<String> msglist = new ArrayList<String>();
                            if (checkShpFileComplete(slist.get(0), msglist)) {
                                // 4. shp
                                // SDEWrapper sde = new SDEWrapper(Config.getProperties());
                                File shpFile = new File(slist.get(0));
                                String path = shpFile.getPath();
                                String layerName = shpFile.getName();
                                layerName = layerName.substring(0, layerName.indexOf("."));
                                // ???
                                // ??
                                layerName = basis.generatorTableName(layerName);
                                session.setAttribute(layerName, path);
                                // sde.shpToSde(path, layerName);
                                // 5. ?
                                // logger.info("--" + file.getAbsolutePath() + "--isexist: "+ file.exists());

                                // / Save a list with the received files
                                receivedFiles.put(item.getFieldName(), file);
                                receivedContentTypes.put(item.getFieldName(), item.getContentType());

                                /// Compose a xml message with the full file information
                                obj.put("fieldname", item.getFieldName());
                                obj.put("name", item.getName());
                                obj.put("size", item.getSize());
                                obj.put("type", item.getContentType());
                                obj.put("layerName", layerName);
                                obj.put("ret", true);
                                obj.put("msg", "??");

                            } else {
                                obj.put("ret", false);
                                obj.put("msg", Util.listToWhere(msglist, ","));
                            }
                        } else {
                            obj.put("ret", false);
                            obj.put("msg", "zipshp");
                        }
                    } else {
                        obj.put("ret", false);
                        obj.put("msg", "?");
                    }
                } catch (IOException e) {
                    obj.put("ret", false);
                    obj.put("msg", "shpshp?????");
                } catch (InterruptedException e) {
                    obj.put("ret", false);
                    obj.put("msg", "??");
                } catch (Exception e) {
                    obj.put("ret", false);
                    obj.put("msg", "??");
                }
            }
        }
    } else {
        obj.put("msg", "??");
    }
    removeSessionFileItems(request);
    return obj.toString();
}

From source file:com.baobao121.baby.common.SimpleUploaderServlet.java

/**
 * Manage the Upload requests.<br>
 * //from www .  j a  va 2 s .  c o  m
 * The servlet accepts commands sent in the following format:<br>
 * simpleUploader?Type=ResourceType<br>
 * <br>
 * It store the file (renaming it in case a file with the same name exists)
 * and then return an HTML file with a javascript command in it.
 * 
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (debug)
        System.out.println("--- BEGIN DOPOST ---");

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();
    String currentPath = "";
    String currentDirPath = "";
    String typeStr = request.getParameter("Type");
    UserCommonInfo info = null;
    info = (UserCommonInfo) request.getSession().getAttribute(SystemConstant.USER_COMMON_INFO);
    if (info == null) {
        info = (UserCommonInfo) request.getSession().getAttribute(SystemConstant.ADMIN_INFO);
    }
    currentPath = baseDir + "images/";
    currentDirPath = getServletContext().getRealPath(currentPath);
    if (!(new File(currentDirPath).isDirectory())) {
        new File(currentDirPath).mkdir();
    }
    if (info.getObjectTableName() == null || info.getObjectTableName().equals("")) {
        currentPath += "admin/";
    } else {
        if (info.getObjectTableName().equals(SystemConstant.BABY_INFO_TABLE_NAME)) {
            currentPath += "babyInfo/";
        }
        if (info.getObjectTableName().equals(SystemConstant.KG_TEACHER_INFO_TABLE_NAME)) {
            currentPath += "teacherInfo/";
        }
    }
    currentDirPath = getServletContext().getRealPath(currentPath);
    if (!(new File(currentDirPath).isDirectory())) {
        new File(currentDirPath).mkdir();
    }
    currentPath += info.getId();
    currentDirPath = getServletContext().getRealPath(currentPath);
    if (!(new File(currentDirPath).isDirectory())) {
        new File(currentDirPath).mkdir();
    }
    if (debug)
        System.out.println(currentDirPath);

    String retVal = "0";
    String newName = "";
    String fileUrl = "";
    String errorMessage = "";

    if (enabled) {
        DiskFileUpload upload = new DiskFileUpload();
        try {
            upload.setHeaderEncoding("utf-8");
            List items = upload.parseRequest(request);

            Map fields = new HashMap();

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }
            FileItem uplFile = (FileItem) fields.get("NewFile");

            String fileNameLong = uplFile.getName();
            InputStream is = uplFile.getInputStream();
            fileNameLong = fileNameLong.replace('\\', '/');
            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];
            Calendar calendar = Calendar.getInstance();
            String nameWithoutExt = String.valueOf(calendar.getTimeInMillis());
            ;
            String ext = getExtension(fileName);
            fileName = nameWithoutExt + "." + ext;
            fileUrl = currentPath + "/" + fileName;
            if (extIsAllowed(typeStr, ext)) {
                FileOutputStream desc = new FileOutputStream(currentDirPath + "/" + fileName);
                changeDimension(is, desc, 450, 1000);
                if (info.getObjectTableName() != null && !info.getObjectTableName().equals("")) {
                    Photo photo = new Photo();
                    photo.setPhotoName(fileName);
                    PhotoAlbum album = babyAlbumDao.getMAlbumByUser(info.getId(), info.getObjectTableName());
                    if (album.getId() != null) {
                        Long albumId = album.getId();
                        photo.setPhotoAlbumId(albumId);
                        photo.setPhotoLink(fileUrl);
                        photo.setDescription("");
                        photo.setReadCount(0L);
                        photo.setCommentCount(0L);
                        photo.setReadPopedom("1");
                        photo.setCreateTime(DateUtil.getCurrentDateTimestamp());
                        photo.setModifyTime(DateUtil.getCurrentDateTimestamp());
                        babyPhotoDao.save(photo);
                        babyAlbumDao.updateAlbumCount(albumId);
                    }
                }
            } else {
                retVal = "202";
                errorMessage = "";
                if (debug)
                    System.out.println("?: " + ext);
            }
        } catch (Exception ex) {
            if (debug)
                ex.printStackTrace();
            retVal = "203";
        }
    } else {
        retVal = "1";
        errorMessage = "??";
    }

    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + request.getContextPath() + fileUrl + "','"
            + newName + "','" + errorMessage + "');");
    out.println("</script>");
    out.flush();
    out.close();

    if (debug)
        System.out.println("--- END DOPOST ---");

}

From source file:com.skin.taurus.http.servlet.UploadServlet.java

/**
 * @param item//from www .  j av  a 2s. c o  m
 * @throws Exception
 */
private String save(FileItem item) throws Exception {
    String fileName = this.getFileName(item.getName());
    String extension = this.getFileExtensionName(fileName);

    if (logger.isDebugEnabled()) {
        logger.debug("Client File: " + item.getName());
        logger.debug("ContentType: " + item.getContentType());
        logger.debug("Field Name : " + item.getFieldName());
        logger.debug("File Name  : " + fileName);
        logger.debug("Extension  : " + extension);
    }

    int i = 1;
    String shortName = fileName.substring(0, fileName.length() - extension.length());
    File file = null;

    do {
        file = new File("./upload/" + shortName + "_" + (i) + extension);
        i++;
    } while (file.exists());

    if (logger.isDebugEnabled()) {
        logger.debug("Save " + fileName + " To " + file.getAbsolutePath());
    }

    item.write(file);

    return file.getCanonicalPath();
}

From source file:com.recipes.controller.AdminP.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from ww w .  j a v  a2s  . c o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    HttpSession session = request.getSession(true);
    DAO dao = new DAO();
    if (request.getParameter("createUser") != null) {

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> fields = upload.parseRequest(request);

            Iterator<FileItem> it = fields.iterator();
            if (!it.hasNext()) {
                // fayl yoxdur mesaj
                return;
            }

            String firstname = "";//String deyiwenleri gotururuy
            String lastname = "";
            String email = "";
            String password = "";
            String image = "";
            String address = "";
            String gender = "";
            String admin = "";

            while (it.hasNext()) { // eger file varsa
                FileItem fileItem = it.next(); // iteratorun next metodu cagrilir
                boolean isFormField = fileItem.isFormField(); // isformField-input yoxlanilirki 
                if (isFormField) { // eger isFormFIelddise
                    switch (fileItem.getFieldName()) {
                    case "name":
                        firstname = fileItem.getString("UTF-8").trim();
                        break;
                    case "surname":
                        lastname = fileItem.getString("UTF-8").trim();
                        break;
                    case "address":
                        address = fileItem.getString("UTF-8").trim();
                        break;
                    case "email":
                        email = fileItem.getString("UTF-8").trim();
                        break;
                    case "password":
                        password = fileItem.getString("UTF-8").trim();
                        break;
                    case "gender":
                        gender = fileItem.getString("UTF-8").trim();
                        break;
                    case "admin":
                        admin = fileItem.getString("UTF-8").trim();
                        break;
                    }
                } else {
                    if (fileItem.getFieldName().equals("image")) {
                        if (!fileItem.getString("UTF-8").trim().equals("")) {
                            image = fileItem.getName();
                            image = dao.generateCode() + image;
                            String relativeWebPath = "photos";
                            String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
                            File file = new File(absoluteDiskPath + "/", image);
                            fileItem.write(file);
                        }
                    }
                }
            }

            User up = new User();
            up.setAddress(address);
            up.setEmail(email);
            up.setFirstname(firstname);
            up.setLastname(lastname);
            up.setGender(gender);
            up.setPassword(password);
            up.setImage("photos/" + image);
            if (admin.equals("on"))
                up.setAdmin(1);
            else
                up.setAdmin(0);

            dao.insertUser(up);

            response.sendRedirect("admin/users.jsp");
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }

    } else if (request.getParameter("delete") != null) {
        dao.deleteUser(request.getParameter("id"));
        response.sendRedirect("admin/users.jsp");
    } else if (request.getParameter("approveRecipe") != null) {
        String id = request.getParameter("approveRecipe");
        dao.approveRecipe(id);
        response.sendRedirect("admin/recipes.jsp");
    } else if (request.getParameter("deleteRecipe") != null) {
        String id = request.getParameter("deleteRecipe");
        dao.deleteRecipe(id);
        response.sendRedirect("admin/recipes.jsp");
    } else if (request.getParameter("deleteDictionary") != null) {
        dao.deleteDictionary(request.getParameter("deleteDictionary"));
        response.sendRedirect("admin/dictionary.jsp");
    } else if (request.getParameter("createWord") != null) {
        Dictionary dic = new Dictionary();
        dic.setWord(request.getParameter("word"));
        dic.setAbout(request.getParameter("about"));
        dao.insertDictionary(dic);
        response.sendRedirect("admin/dictionary.jsp");
    } else if (request.getParameter("createTips") != null) {
        Tips tips = new Tips();
        tips.setFrom(request.getParameter("from"));
        tips.setTips(request.getParameter("tips"));
        dao.insertTips(tips);
        response.sendRedirect("admin/tips.jsp");
    } else if (request.getParameter("deleteTips") != null) {
        dao.deleteTips(request.getParameter("deleteTips"));
        response.sendRedirect("admin/tips.jsp");
    } else {
        response.sendRedirect("admin/users.jsp");
    }

}

From source file:mx.org.cedn.avisosconagua.engine.processors.Init.java

@Override
public void processForm(HttpServletRequest request, String[] parts, String currentId)
        throws ServletException, IOException {
    HashMap<String, String> parametros = new HashMap<>();
    boolean fileflag = false;
    AvisosException aex = null;// w  w w  .j a v a  2s. c o m
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(MAX_SIZE);
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setSizeMax(MAX_SIZE);
            List<FileItem> items = upload.parseRequest(request);
            String filename = null;
            for (FileItem item : items) {
                if (!item.isFormField() && item.getSize() > 0) {
                    filename = processUploadedFile(item, currentId);
                    //System.out.println("poniendo: "+ item.getFieldName() + "=" +filename);
                    parametros.put(item.getFieldName(), filename);
                } else {
                    //                    System.out.println("item:" + item.getFieldName() + "=" + new String(item.getString().getBytes("ISO8859-1")));
                    //                    parametros.put(item.getFieldName(), new String(item.getString().getBytes("ISO8859-1")));
                    //                    System.out.println("item:" + item.getFieldName() + "=" + item.getString());
                    //                    System.out.println("item:" + item.getFieldName() + "=" + new String(item.getString().getBytes("ISO8859-1"),"UTF-8"));
                    //                    System.out.println("item:" + item.getFieldName() + "=" + new String(item.getString().getBytes("ISO8859-1")));
                    //                    System.out.println("item:" + item.getFieldName() + "=" + new String(item.getString().getBytes("UTF-8"),"UTF-8"));
                    parametros.put(item.getFieldName(),
                            new String(item.getString().getBytes("ISO8859-1"), "UTF-8"));
                }
            }
        } catch (FileUploadException fue) {
            fue.printStackTrace();
            fileflag = true;
            aex = new AvisosException("El archivo sobrepasa el tamao de " + MAX_SIZE + " bytes", fue);
        }
    } else {
        for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
            //                try {
            //                    parametros.put(entry.getKey(), new String(request.getParameter(entry.getKey()).getBytes("ISO8859-1")));
            //                } catch (UnsupportedEncodingException ue) {
            //                    //No debe llegar a este punto
            //                    assert false;
            //                }
            parametros.put(entry.getKey(), request.getParameter(entry.getKey()));
        }
    }
    BasicDBObject anterior = (BasicDBObject) mi.getAdvice(currentId).get(parts[3]);
    procesaAreas(parametros, anterior);
    procesaImagen(parametros, anterior);
    MongoInterface.getInstance().savePlainData(currentId, parts[3], parametros);

    if (fileflag) {
        throw aex;
    }
}

From source file:com.gwtcx.server.servlet.FileUploadServlet.java

@SuppressWarnings("rawtypes")
private void processFiles(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // set the size threshold, above which content will be stored on disk
    factory.setSizeThreshold(1 * 1024 * 1024); // 1 MB

    // set the temporary directory (this is where files that exceed the threshold will be stored)
    factory.setRepository(tmpDir);//w ww. j  a v  a 2 s  . c o  m

    // create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        String recordType = "Account";

        // parse the request
        List items = upload.parseRequest(request);

        // process the uploaded items
        Iterator itr = items.iterator();

        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();

            // process a regular form field
            if (item.isFormField()) {
                Log.debug("Field Name: " + item.getFieldName() + ", Value: " + item.getString());

                if (item.getFieldName().equals("recordType")) {
                    recordType = item.getString();
                }
            } else { // process a file upload

                Log.debug("Field Name: " + item.getFieldName() + ", Value: " + item.getName()
                        + ", Content Type: " + item.getContentType() + ", In Memory: " + item.isInMemory()
                        + ", File Size: " + item.getSize());

                // write the uploaded file to the application's file staging area
                File file = new File(destinationDir, item.getName());
                item.write(file);

                // import the CSV file
                importCsvFile(recordType, file.getPath());

                // file.delete();  // TO DO
            }
        }
    } catch (FileUploadException e) {
        Log.error("Error encountered while parsing the request", e);
    } catch (Exception e) {
        Log.error("Error encountered while uploading file", e);
    }
}