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

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

Introduction

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

Prototype

long getSize();

Source Link

Document

Returns the size of the file item.

Usage

From source file:com.darksky.seller.SellerServlet.java

/**
 *   /*from   w ww.jav a2s .  c o  m*/
 * ?
 * @param request
 * @param response
 * @throws Exception
 */
public void modifyShopInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
    System.out.println();
    System.out.println("--------------------shop modify info-----------------");
    /* ? */
    String sellerID = Seller.getSellerID();

    /* ? */

    String shopID = Shop.getShopID();
    String shopName = null;
    String shopTel = null;
    String shopIntroduction = null;
    String Notice = null;
    String shopAddress = null;
    String shopPhoto = null;

    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

    ServletFileUpload sfu = new ServletFileUpload(diskFileItemFactory);
    ServletFileUpload sfu2 = new ServletFileUpload(diskFileItemFactory);
    // ?
    sfu.setHeaderEncoding("UTF-8");
    // ?2M
    sfu.setFileSizeMax(1024 * 1024 * 2);
    // ?10M
    sfu.setSizeMax(1024 * 1024 * 10);
    List<FileItem> itemList = sfu.parseRequest(request);

    List<FileItem> itemList2 = sfu2.parseRequest(request);

    FileItem a = null;

    for (FileItem fileItem : itemList) {

        if (!fileItem.isFormField()) {
            a = fileItem;

            System.out.println("QQQQQQQQQQQQQQQQ" + fileItem.toString() + "QQQQQQQQ");

        } else {
            String fieldName = fileItem.getFieldName();
            String value = fileItem.getString("utf-8");
            switch (fieldName) {
            case "shopName":
                shopName = value;
                break;
            case "shopTel":
                shopTel = value;
                break;
            case "shopIntroduction":
                shopIntroduction = value;
                break;
            case "Notice":
                Notice = value;
                break;
            case "shopPhoto":
                shopPhoto = value;
                break;
            case "shopAddress":
                shopAddress = value;
                break;

            default:
                break;
            }

        }

    }
    double randomNum = Math.random();
    shopPhoto = "image/" + shopID + "_" + randomNum + ".jpg";
    String savePath2 = getServletContext().getRealPath("");
    System.out.println("path2=" + savePath2);
    getDish(sellerID);

    String shopSql = null;
    if (a.getSize() != 0) {
        File file2 = new File(savePath2, shopPhoto);
        a.write(file2);

        shopSql = "update shop set shopName='" + shopName + "' , shopTel='" + shopTel + "' , shopIntroduction='"
                + shopIntroduction + "' , Notice='" + Notice + "' , shopAddress='" + shopAddress
                + "',shopPhoto='" + shopPhoto + "' where shopID='" + shopID + "'";
    }

    else {

        shopSql = "update shop set shopName='" + shopName + "' , shopTel='" + shopTel + "' , shopIntroduction='"
                + shopIntroduction + "' , Notice='" + Notice + "' , shopAddress='" + shopAddress
                + "' where shopID='" + shopID + "'";
    }

    System.out.println("shopSql: " + shopSql);

    try {
        statement.executeUpdate(shopSql);
    } catch (SQLException e) {
        e.printStackTrace();
    }

    getShop(Seller.getShopID());
    request.getSession().setAttribute("shop", Shop);

    System.out.println("--------------------shop modify info-----------------");
    System.out.println();

    request.getRequestDispatcher(".jsp").forward(request, response);
}

From source file:com.afis.jx.ckfinder.connector.handlers.command.FileUploadCommand.java

/**
 * validates uploaded file./*from  w  w w. j a v a  2s  .c  om*/
 *
 * @param item uploaded item.
 * @param path file path
 * @return true if validation
 */
private boolean validateUploadItem(final FileItem item, final String path) {

    if (item.getName() != null && item.getName().length() > 0) {
        this.fileName = getFileItemName(item);
    } else {
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_INVALID;
        return false;
    }
    this.newFileName = this.fileName;

    for (char c : UNSAFE_FILE_NAME_CHARS) {
        this.newFileName = this.newFileName.replace(c, '_');
    }

    if (configuration.isDisallowUnsafeCharacters()) {
        this.newFileName = this.newFileName.replace(';', '_');
    }
    if (configuration.forceASCII()) {
        this.newFileName = FileUtils.convertToASCII(this.newFileName);
    }
    if (!this.newFileName.equals(this.fileName)) {
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_INVALID_NAME_RENAMED;
    }

    if (FileUtils.checkIfDirIsHidden(this.currentFolder, configuration)) {
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST;
        return false;
    }
    if (!FileUtils.checkFileName(this.newFileName)
            || FileUtils.checkIfFileIsHidden(this.newFileName, configuration)) {
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_NAME;
        return false;
    }
    final ResourceType resourceType = configuration.getTypes().get(this.type);
    int checkFileExt = FileUtils.checkFileExtension(this.newFileName, resourceType);
    if (checkFileExt == 1) {
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_EXTENSION;
        return false;
    }
    if (configuration.ckeckDoubleFileExtensions()) {
        this.newFileName = FileUtils.renameFileWithBadExt(resourceType, this.newFileName);
    }

    try {
        File file = new File(path, getFinalFileName(path, this.newFileName));
        if (!(ImageUtils.isImage(file) && configuration.checkSizeAfterScaling())
                && !FileUtils.checkFileSize(resourceType, item.getSize())) {
            this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG;
            return false;
        }

        if (configuration.getSecureImageUploads() && ImageUtils.isImage(file)
                && !ImageUtils.checkImageFile(item)) {
            this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_CORRUPT;
            return false;
        }

        if (!FileUtils.checkIfFileIsHtmlFile(file.getName(), configuration) && FileUtils.detectHtml(item)) {
            this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_WRONG_HTML_FILE;
            return false;
        }
    } catch (SecurityException e) {
        if (configuration.isDebugMode()) {
            this.exception = e;
        }
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
        return false;
    } catch (IOException e) {
        if (configuration.isDebugMode()) {
            this.exception = e;
        }
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
        return false;
    }

    return true;
}

From source file:com.ecyrd.jspwiki.attachment.AttachmentServlet.java

/**
 *  Uploads a specific mime multipart input set, intercepts exceptions.
 *
 *  @param req The servlet request/*from w  w  w . j a v  a  2 s. c  o m*/
 *  @return The page to which we should go next.
 *  @throws RedirectException If there's an error and a redirection is needed
 *  @throws IOException If upload fails
 * @throws FileUploadException 
 */
@SuppressWarnings("unchecked")
protected String upload(HttpServletRequest req) throws RedirectException, IOException {
    String msg = "";
    String attName = "(unknown)";
    String errorPage = m_engine.getURL(WikiContext.ERROR, "", null, false); // If something bad happened, Upload should be able to take care of most stuff
    String nextPage = errorPage;

    String progressId = req.getParameter("progressid");

    // Check that we have a file upload request
    if (!ServletFileUpload.isMultipartContent(req)) {
        throw new RedirectException("Not a file upload", errorPage);
    }

    try {
        FileItemFactory factory = new DiskFileItemFactory();

        // Create the context _before_ Multipart operations, otherwise
        // strict servlet containers may fail when setting encoding.
        WikiContext context = m_engine.createContext(req, WikiContext.ATTACH);

        UploadListener pl = new UploadListener();

        m_engine.getProgressManager().startProgress(pl, progressId);

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        if (!context.hasAdminPermissions()) {
            upload.setFileSizeMax(m_maxSize);
        }
        upload.setProgressListener(pl);
        List<FileItem> items = upload.parseRequest(req);

        String wikipage = null;
        String changeNote = null;
        FileItem actualFile = null;

        for (FileItem item : items) {
            if (item.isFormField()) {
                if (item.getFieldName().equals("page")) {
                    //
                    // FIXME: Kludge alert.  We must end up with the parent page name,
                    //        if this is an upload of a new revision
                    //

                    wikipage = item.getString("UTF-8");
                    int x = wikipage.indexOf("/");

                    if (x != -1)
                        wikipage = wikipage.substring(0, x);
                } else if (item.getFieldName().equals("changenote")) {
                    changeNote = item.getString("UTF-8");
                    if (changeNote != null) {
                        changeNote = TextUtil.replaceEntities(changeNote);
                    }
                } else if (item.getFieldName().equals("nextpage")) {
                    nextPage = validateNextPage(item.getString("UTF-8"), errorPage);
                }
            } else {
                actualFile = item;
            }
        }

        if (actualFile == null)
            throw new RedirectException("Broken file upload", errorPage);

        //
        // FIXME: Unfortunately, with Apache fileupload we will get the form fields in
        //        order.  This means that we have to gather all the metadata from the
        //        request prior to actually touching the uploaded file itself.  This
        //        is because the changenote appears after the file upload box, and we
        //        would not have this information when uploading.  This also means
        //        that with current structure we can only support a single file upload
        //        at a time.
        //
        String filename = actualFile.getName();
        long fileSize = actualFile.getSize();
        InputStream in = actualFile.getInputStream();

        try {
            executeUpload(context, in, filename, nextPage, wikipage, changeNote, fileSize);
        } finally {
            in.close();
        }

    } catch (ProviderException e) {
        msg = "Upload failed because the provider failed: " + e.getMessage();
        log.warn(msg + " (attachment: " + attName + ")", e);

        throw new IOException(msg);
    } catch (IOException e) {
        // Show the submit page again, but with a bit more
        // intimidating output.
        msg = "Upload failure: " + e.getMessage();
        log.warn(msg + " (attachment: " + attName + ")", e);

        throw e;
    } catch (FileUploadException e) {
        // Show the submit page again, but with a bit more
        // intimidating output.
        msg = "Upload failure: " + e.getMessage();
        log.warn(msg + " (attachment: " + attName + ")", e);

        throw new IOException(msg);
    } finally {
        m_engine.getProgressManager().stopProgress(progressId);
        // FIXME: In case of exceptions should absolutely
        //        remove the uploaded file.
    }

    return nextPage;
}

From source file:com.krawler.spring.hrms.rec.job.hrmsRecJobDAOImpl.java

@Override
public void parseRequest(HttpServletRequest request, HashMap<String, Object> arrParam, ArrayList<FileItem> fi,
        boolean fileUpload, HashMap<Integer, String> filemap) {
    DiskFileUpload fu = new DiskFileUpload();
    FileItem fi1 = null;
    List fileItems = null;/*from  www . ja va2s .  c  o  m*/
    int i = 0;
    try {
        fu.setHeaderEncoding("UTF-8");
        fileItems = fu.parseRequest(request);

    } catch (FileUploadException e) {
        //            throw ServiceException.FAILURE("Admin.createUser", e);
    }

    for (Iterator k = fileItems.iterator(); k.hasNext();) {
        fi1 = (FileItem) k.next();
        if (fi1.isFormField()) {
            try {
                arrParam.put(fi1.getFieldName(), new String(fi1.getString().getBytes("iso-8859-1"), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            try {
                String fileName = new String(fi1.getName().getBytes(), "UTF8");
                if (fi1.getSize() != 0) {
                    fi.add(fi1);
                    filemap.put(i, fi1.getFieldName());
                    i++;
                    fileUpload = true;
                }
            } catch (UnsupportedEncodingException ex) {
            }
        }
    }
}

From source file:com.kk.dic.action.Upload.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    out = response.getWriter();//from w  ww.  j a  va 2 s .c  o m
    Connection con;
    PreparedStatement pstm = null;
    String fname = "";
    String keyword = "";
    String cd = "";
    String a = (String) request.getSession().getAttribute("email");
    System.out.println("User Name : " + a);
    try {
        boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
        if (!isMultipartContent) {
            return;
        }
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        out.print("one");
        try {
            List<FileItem> fields = upload.parseRequest(request);
            Iterator<FileItem> it = fields.iterator();
            if (!it.hasNext()) {
                return;
            }

            while (it.hasNext()) {
                FileItem fileItem = it.next();
                if (fileItem.getFieldName().equals("name")) {
                    fname = fileItem.getString();
                    System.out.println("File Name" + fname);
                } else if (fileItem.getFieldName().equals("keyword")) {
                    keyword = fileItem.getString();
                    System.out.println("File Keyword" + keyword);
                } else {

                }
                boolean isFormField = fileItem.isFormField();
                if (isFormField) {
                } else {
                    out.print("one");
                    try {
                        con = Dbconnection.getConnection();
                        pstm = con.prepareStatement(
                                "insert into files (file, keyword, filetype, filename, CDate, owner, size, data, frank, file_key)values(?,?,?,?,?,?,?,?,?,?)");
                        out.println("getD " + fileItem.getName());
                        String str = getStringFromInputStream(fileItem.getInputStream());
                        // secretkey generating
                        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
                        keyGen.init(128);
                        SecretKey secretKey = keyGen.generateKey();
                        System.out.println("secret key:" + secretKey);
                        //converting secretkey to String
                        byte[] be = secretKey.getEncoded();//encoding secretkey
                        String skey = Base64.encode(be);
                        System.out.println("converted secretkey to string:" + skey);
                        String cipher = new encryption().encrypt(str, secretKey);
                        System.out.println(str);
                        //for get extension from given file
                        String b = fileItem.getName().substring(fileItem.getName().lastIndexOf('.'));
                        System.out.println("File Extension" + b);
                        pstm.setBinaryStream(1, fileItem.getInputStream());
                        pstm.setString(2, keyword);
                        pstm.setString(3, b);
                        pstm.setString(4, fname);
                        pstm.setDate(5, getCurrentDate());
                        pstm.setString(6, a);
                        pstm.setLong(7, fileItem.getSize());
                        pstm.setString(8, cipher);
                        pstm.setString(9, "0");
                        pstm.setString(10, skey);
                        /*Cloud Start*/
                        File f = new File("D:/" + fileItem.getName());
                        out.print("<br/>" + f.getName());
                        FileWriter fw = new FileWriter(f);
                        fw.write(cipher);
                        fw.close();
                        Ftpcon ftpcon = new Ftpcon();
                        ftpcon.upload(f, fname);
                        /*Cloud End*/
                        int i = pstm.executeUpdate();
                        if (i == 1) {
                            response.sendRedirect("upload.jsp?msg=success");
                        } else {
                            response.sendRedirect("upload.jsp?msgg=failed");
                        }
                        con.close();
                    } catch (Exception e) {
                        out.println(e);
                    }
                }
            }
        } catch (Exception ex) {
            out.print(ex);
            Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
        }
    } finally {
        out.close();
    }
}

From source file:it.biblio.servlets.Inserimento_pub.java

/**
 * metodo per gestire l'upload di file e inserimento pubblicazione con prima
 * ristampa/*  w  w  w. j  a v a 2 s .  c o m*/
 *
 * @param request
 * @param response
 * @param k
 * @return
 * @throws IOException
 */
private boolean upload(HttpServletRequest request) throws IOException, Exception {

    Map<String, Object> pub = new HashMap<String, Object>();
    Map<String, Object> ristampe = new HashMap<String, Object>();
    Map<String, Object> keyword = new HashMap<String, Object>();
    HttpSession s = SecurityLayer.checkSession(request);
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory fif = new DiskFileItemFactory();
        ServletFileUpload sfo = new ServletFileUpload(fif);
        List<FileItem> items = sfo.parseRequest(request);
        for (FileItem item : items) {
            String fname = item.getFieldName();
            if (item.isFormField() && fname.equals("titolo") && !item.getString().isEmpty()) {
                pub.put("titolo", item.getString());
                pub.put("utente", s.getAttribute("userid"));
            } else if (item.isFormField() && fname.equals("descrizione") && !item.getString().isEmpty()) {
                pub.put("descrizione", item.getString());
            } else if (item.isFormField() && fname.equals("autore") && !item.getString().isEmpty()) {
                pub.put("autore", item.getString());

            } else if (item.isFormField() && fname.equals("categoria") && !item.getString().isEmpty()) {
                pub.put("categoria", item.getString());

            } else if (item.isFormField() && fname.equals("ISBN") && !item.getString().isEmpty()) {
                ristampe.put("isbn", item.getString());
            } else if (item.isFormField() && fname.equals("numero_pagine") && !item.getString().isEmpty()) {
                ristampe.put("numpagine", Integer.parseInt(item.getString()));
            } else if (item.isFormField() && fname.equals("anno_pub") && !item.getString().isEmpty()) {
                ristampe.put("datapub", item.getString());
            } else if (item.isFormField() && fname.equals("editore") && !item.getString().isEmpty()) {
                ristampe.put("editore", item.getString());
            } else if (item.isFormField() && fname.equals("lingua") && !item.getString().isEmpty()) {
                ristampe.put("lingua", item.getString());
            } else if (item.isFormField() && fname.equals("indice") && !item.getString().isEmpty()) {
                ristampe.put("indice", item.getString());
            } else if (item.isFormField() && fname.equals("keyword") && !item.getString().isEmpty()) {
                keyword.put("tag1", item.getString());
            } else if (item.isFormField() && fname.equals("keyword2") && !item.getString().isEmpty()) {
                keyword.put("tag2", item.getString());
            } else if (item.isFormField() && fname.equals("keyword3") && !item.getString().isEmpty()) {
                keyword.put("tag3", item.getString());
            } else if (!item.isFormField() && fname.equals("PDF")) {
                String name = item.getName();
                long size = item.getSize();
                if (size > 0 && !name.isEmpty()) {
                    File target = new File(getServletContext().getRealPath("") + File.separatorChar + "PDF"
                            + File.separatorChar + name);
                    item.write(target);
                    ristampe.put("download", "PDF" + File.separatorChar + name);
                }
            } else if (!item.isFormField() && fname.equals("copertina")) {
                String name = item.getName();
                long size = item.getSize();
                if (size > 0 && !name.isEmpty()) {
                    File target = new File(getServletContext().getRealPath("") + File.separatorChar
                            + "Copertine" + File.separatorChar + name);
                    item.write(target);
                    ristampe.put("copertina", "Copertine" + File.separatorChar + name);
                }
            }
        }

        Database.insertRecord("keyword", keyword);
        ResultSet ss = Database.selectRecord("keyword", "tag1='" + keyword.get("tag1") + "' && " + "tag2='"
                + keyword.get("tag2") + "' && tag3='" + keyword.get("tag3") + "'");
        if (!isNull(ss)) {
            int indicek = 0;
            while (ss.next()) {
                indicek = ss.getInt("id");
            }
            pub.put("keyword", indicek);
            Database.insertRecord("pubblicazioni", pub);
            ResultSet rs = Database.selectRecord("pubblicazioni", "titolo='" + pub.get("titolo") + "'");
            while (rs.next()) {
                ristampe.put("pubblicazioni", rs.getInt("id"));
            }
            return Database.insertRecord("ristampe", ristampe);
        } else {
            return false;
        }

    }
    return false;
}

From source file:hu.sztaki.lpds.pgportal.portlets.asm.SymbolMap.java

@SuppressWarnings("empty-statement")
public void doUploadLigands(ActionRequest request, ActionResponse response) {
    String errorMessage = "";
    String userMessage = "";
    String selected_wf = "";
    int docking_type = 0;
    try {/*w  w  w .java  2 s.c o m*/
        // MULTIPART REQUEST
        ActionRequest temp_req = request;
        String userId = request.getRemoteUser();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        PortletFileUpload pfu = new PortletFileUpload(factory);

        List fileItems = pfu.parseRequest(temp_req);

        // ligands
        Iterator iter = fileItems.iterator();
        FileItem ligandFileItem = null;
        FileItem receptorFileItem = null;
        FileItem configFileItem = null;
        FileItem inputsFileItem = null;
        String vina_configuration = "";
        String vina_best_result = "";
        String docking_wu = "";
        String task_name = "";
        FileItem gpfFileItem = null;
        FileItem dpfFileItem = null;
        throwMessage("Submitting started, processing inputs & files", 1);

        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                if (!Validate.textIsAlphaNumeric(item.getString()))
                    throw new Exception(" Input parameter string is not valid from FORM " + item.getFieldName()
                            + ", value:" + item.getString());
                // TEXT FIELD
                if (item.getFieldName().equals("vina_configuration")) {
                    vina_configuration = item.getString();
                }
                if (item.getFieldName().startsWith("docking_wu")) {
                    // number
                    docking_wu = item.getString();
                }
                if (item.getFieldName().startsWith("best_result")) {
                    vina_best_result = item.getString();
                }
                if (item.getFieldName().startsWith("task_name")) {
                    task_name = item.getString();
                }
                if (item.getFieldName().startsWith("docking_type")) {
                    docking_type = Integer.parseInt(item.getString());
                }

            } else {
                // FILE UPLOAD
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                long sizeInBytes = item.getSize();
                // pdb or pdbqt
                if (!Validate.fileNameValid(fileName))
                    throw new Exception(" Input parameter file is not valid from FORM " + fieldName);
                // pdb or pdbqt
                if (fieldName.equals("receptor")) {
                    receptorFileItem = item;
                }
                if (fieldName.equals("gpfparameter")) {
                    gpfFileItem = item;
                }
                if (fieldName.equals("dpfparameter")) {
                    dpfFileItem = item;
                }
                // .zip
                if (fieldName.equals("ligands")) {
                    ligandFileItem = item;
                }
                // .pdb
                if (fieldName.equals("ligand")) {
                    ligandFileItem = item;
                }
                // inputs.zip
                if (fieldName.equals("inputs")) {
                    inputsFileItem = item;
                }

                if (fieldName.equals("vina_config_file")) {
                    configFileItem = item;
                }
            }
        }

        throwMessage("Submitting started, checking inputs & uploading files", 1);
        String selected_wf_type = WfTypeFromDockingType(docking_type);

        if (!Validate.numberIsNaturalNumber(docking_wu, 1, Maximum_WU))
            throw new Exception(" Input parameter docking_wu is not valid, value " + docking_wu + " Maximum_WU:"
                    + Maximum_WU);
        if (!Validate.numberIsNaturalNumber(vina_best_result, 1, Integer.parseInt(docking_wu)))
            throw new Exception(" Input parameter best_result is not in valid range (1," + docking_wu
                    + "), value: " + vina_best_result);

        //IMPORT NEW WORKFLOW INSTANCE
        String newWfinstanceID = selected_wf_type + "_" + task_name;
        selected_wf = importWorkflow(developerId, userId, selected_wf_type, newWfinstanceID);
        if (!Validate.wfInstanceValid(selected_wf))
            throw new Exception(" Input parameter  selected_wf is not valid, value " + selected_wf);

        String job_generator = "";
        String port_input_receptor = ""; //input-receptor.pdbqt
        String port_vina_config = ""; //vina-config.txt
        String port_input_ligands = ""; //input-ligands.zip
        String cmd_parameter_wus_nr = "" + docking_wu; // number of WUs

        String job_collector = "";
        String selected_job = "";
        String port_docking_gpf = "";
        String port_docking_dpf = "";
        String port_input_zip = "";

        // VINA
        if (docking_type == DOCKING_VINA) {
            job_generator = "Generator";
            port_input_receptor = "5"; //input-receptor.pdbqt
            port_vina_config = "4"; //vina-config.txt
            port_input_ligands = "3"; //input-ligands.zip
            job_collector = "collector.sh";
            selected_job = job_generator;
            //UPLOAD LIGAND ZIP
            File uploadedFile = asm_service.uploadFiletoPortalServer(ligandFileItem, userId,
                    ligandFileItem.getName());
            asm_service.placeUploadedFile(userId, uploadedFile, selected_wf, selected_job, port_input_ligands);
            // UPLOAD RECEPTOR PDBQT FILE
            File receptorFile = asm_service.uploadFiletoPortalServer(receptorFileItem, userId,
                    receptorFileItem.getName());
            asm_service.placeUploadedFile(userId, receptorFile, selected_wf, selected_job, port_input_receptor);
            // SETUP CONFIGURATION
            if (configFileItem == null) {
                String content = vina_configuration;
                asm_service.setInputText(userId, content, selected_wf, selected_job, port_vina_config);
            } else {
                File configFile = asm_service.uploadFiletoPortalServer(configFileItem, userId,
                        configFileItem.getName());
                asm_service.placeUploadedFile(userId, configFile, selected_wf, selected_job, port_vina_config);
            }
        }
        if (docking_type == DOCKING_AUTODOCKAUTOGRID) {
            job_generator = "AutoGrid";
            port_input_receptor = "0"; //receptor.pdb
            port_docking_gpf = "1";
            String port_exec = "2"; //executables lol
            //port_vina_config = "2";  
            port_docking_dpf = "3"; // ligand.pdb
            port_input_ligands = "4"; // ligand.pdb
            job_collector = "Collector";
            selected_job = job_generator;

            //UPLOAD LIGAND
            File uploadedFile = asm_service.uploadFiletoPortalServer(ligandFileItem, userId,
                    ligandFileItem.getName());
            asm_service.placeUploadedFile(userId, uploadedFile, selected_wf, selected_job, port_input_ligands);
            // UPLOAD RECEPTOR PDB FILE
            File receptorFile = asm_service.uploadFiletoPortalServer(receptorFileItem, userId,
                    receptorFileItem.getName());
            asm_service.placeUploadedFile(userId, receptorFile, selected_wf, selected_job, port_input_receptor);
            //
            // SHOULD NOT BE IN PUBLIC VERSION!
            //
            //UPLOAD EXEC
            //       File execFile = asm_service.uplloadFiletoPortalServer(execFileItem, userId, execFileItem.getName());
            //       asm_service.placeUploadedFile(userId, execFile , selected_wf, selected_job, port_exec);

            // UPLOAD GPF FILE
            File gpfFile = asm_service.uploadFiletoPortalServer(gpfFileItem, userId, gpfFileItem.getName());
            asm_service.placeUploadedFile(userId, gpfFile, selected_wf, selected_job, port_docking_gpf);
            // UPLOAD DPF FILE
            File dpfFile = asm_service.uploadFiletoPortalServer(dpfFileItem, userId, dpfFileItem.getName());
            asm_service.placeUploadedFile(userId, dpfFile, selected_wf, selected_job, port_docking_dpf);
        }
        if (docking_type == DOCKING_AUTODOCKNO) {
            job_generator = "Generator";
            port_input_zip = "1"; //inputs.zip
            port_docking_dpf = "3";
            job_collector = "Collector";
            selected_job = job_generator;

            //UPLOAD LIGAND
            File uploadedFile = asm_service.uploadFiletoPortalServer(inputsFileItem, userId,
                    inputsFileItem.getName());
            asm_service.placeUploadedFile(userId, uploadedFile, selected_wf, selected_job, port_input_zip);

            // UPLOAD GPF FILE
            File dpfFile = asm_service.uploadFiletoPortalServer(dpfFileItem, userId, dpfFileItem.getName());
            asm_service.placeUploadedFile(userId, dpfFile, selected_wf, selected_job, port_docking_dpf);
        }

        // setup WUs Number
        // Generator
        asm_service.setCommandLineArg(userId, selected_wf, selected_job, cmd_parameter_wus_nr);
        // setup Best result number
        // at the collector job argument
        String best_content = vina_best_result;
        selected_job = job_collector;
        asm_service.setCommandLineArg(userId, selected_wf, selected_job, best_content);

        asm_service.submit(userId, selected_wf, "", "");

        throwMessage("Task successfully submitted! Docking_type:" + docking_type + " submitted", 1);
        userMessage += throwMessage("Task successfully submitted! Wait for run, and check eventually!", 1);
        response.setRenderParameter("userMessage", userMessage);

    } catch (Exception ex) {
        errorMessage += throwError(
                Thread.currentThread().getStackTrace()[1].getMethodName() + " " + ex.getMessage(), 1);
    }
    request.setAttribute("nextJSP", DISPLAY_PAGE);
    request.setAttribute("selected_wf", selected_wf);
    request.setAttribute("docking_type", docking_type);
    response.setRenderParameter("docking_type", "" + docking_type);

    response.setRenderParameter("errorMessage", errorMessage);
}

From source file:com.darksky.seller.SellerServlet.java

/**
 * * ? /*from   w  w w . j av a 2  s.  c  om*/
 * @param request
 * @param response
 * @throws Exception
 */
public void modifyDish(HttpServletRequest request, HttpServletResponse response) throws Exception {

    System.out.println("-----------modify dish--------------");
    String sellerID = Seller.getSellerID();
    String dishType = null;
    String dishName = null;
    String dishPrice = null;
    String dishID = null;
    String dishIntroduction = null;
    String dishStock = null;

    if (ServletFileUpload.isMultipartContent(request)) {
        // String savePath = getServletContext().getRealPath("image");

        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

        ServletFileUpload sfu = new ServletFileUpload(diskFileItemFactory);
        ServletFileUpload sfu2 = new ServletFileUpload(diskFileItemFactory);
        // ?
        sfu.setHeaderEncoding("UTF-8");
        // ?2M
        sfu.setFileSizeMax(1024 * 1024 * 2);
        // ?10M
        sfu.setSizeMax(1024 * 1024 * 10);
        List<FileItem> itemList = sfu.parseRequest(request);

        List<FileItem> itemList2 = sfu2.parseRequest(request);

        FileItem a = null;

        for (FileItem fileItem : itemList) {

            if (!fileItem.isFormField()) {
                a = fileItem;

            } else {
                String fieldName = fileItem.getFieldName();
                String value = fileItem.getString("utf-8");
                switch (fieldName) {
                case "dishName":
                    dishName = value;
                    System.out.println("!!!!!!!!!!!!!!!!!dishName=     " + dishName);
                    break;
                case "dishPrice":
                    dishPrice = value;
                    break;
                case "dishIntroduction":
                    dishIntroduction = value;
                    break;
                case "dishStock":
                    dishStock = value;
                    break;
                case "dishID":
                    dishID = value;
                    break;
                case "dishType":
                    dishType = value;
                    break;
                default:
                    break;
                }

            }

        }
        // ?
        double randomNum = Math.random();
        // request.setAttribute("randomNum", randomNum);

        String dishPhoto = "image/" + sellerID + "_" + dishName + "_" + randomNum + ".jpg";

        String savePath2 = getServletContext().getRealPath("");
        System.out.println("path2=" + savePath2);
        getDish(sellerID);
        File file1 = new File(savePath2, dishPhoto);

        String sql = null;
        if (a.getSize() != 0) {
            a.write(file1);

            sql = "update dishinfo set dishType='" + dishType + "',dishName='" + dishName + "',dishPrice='"
                    + dishPrice + "',dishPrice='" + dishPrice + "',dishIntroduction='" + dishIntroduction
                    + "',dishStock='" + dishStock + "',dishPhoto='" + dishPhoto + "' where dishID='" + dishID
                    + "'";
        } else {
            sql = "update dishinfo set dishType='" + dishType + "',dishName='" + dishName + "',dishPrice='"
                    + dishPrice + "',dishPrice='" + dishPrice + "',dishIntroduction='" + dishIntroduction
                    + "',dishStock='" + dishStock + "' where dishID='" + dishID + "'";
        }

        System.out.println(sql);

        try {
            statement.execute(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    getDish(sellerID);

    request.getSession().setAttribute("dish", DishList);
    request.getSession().setAttribute("sellerID", sellerID);
    System.out.println("**********************     sellerID=    " + sellerID + "**************");
    // this.sellerDish(request, response);

    request.getRequestDispatcher("?.jsp").forward(request, response);

}

From source file:com.cognitivabrasil.repositorio.web.FileController.java

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody//from  www  .  j a  va 2  s .  com
public String upload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, org.apache.commons.fileupload.FileUploadException {
    if (file == null) {
        file = new Files();
        file.setSizeInBytes(0L);
    }

    Integer docId = null;
    String docPath = null;
    String responseString = RESP_SUCCESS;
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        try {
            ServletFileUpload x = new ServletFileUpload(new DiskFileItemFactory());
            List<FileItem> items = x.parseRequest(request);

            for (FileItem item : items) {
                InputStream input = item.getInputStream();

                // Handle a form field.
                if (item.isFormField()) {
                    String attribute = item.getFieldName();
                    String value = Streams.asString(input);

                    switch (attribute) {
                    case "chunks":
                        this.chunks = Integer.parseInt(value);
                        break;
                    case "chunk":
                        this.chunk = Integer.parseInt(value);
                        break;
                    case "filename":
                        file.setName(value);
                        break;
                    case "docId":
                        if (value.isEmpty()) {
                            throw new org.apache.commons.fileupload.FileUploadException(
                                    "No foi informado o id do documento.");
                        }
                        docId = Integer.parseInt(value);
                        docPath = Config.FILE_PATH + "/" + docId;
                        File documentPath = new File(docPath);
                        // cria o diretorio
                        documentPath.mkdirs();

                        break;
                    default:
                        break;
                    }

                } // Handle a multi-part MIME encoded file.
                else {
                    try {

                        File uploadFile = new File(docPath, item.getName());
                        BufferedOutputStream bufferedOutput;
                        bufferedOutput = new BufferedOutputStream(new FileOutputStream(uploadFile, true));

                        byte[] data = item.get();
                        bufferedOutput.write(data);
                        bufferedOutput.close();
                    } catch (Exception e) {
                        LOG.error("Erro ao salvar o arquivo.", e);
                        file = null;
                        throw e;
                    } finally {
                        if (input != null) {
                            try {
                                input.close();
                            } catch (IOException e) {
                                LOG.error("Erro ao fechar o ImputStream", e);
                            }
                        }

                        file.setName(item.getName());
                        file.setContentType(item.getContentType());
                        file.setPartialSize(item.getSize());
                    }
                }
            }

            if ((this.chunk == this.chunks - 1) || this.chunks == 0) {
                file.setLocation(docPath + "/" + file.getName());
                if (docId != null) {
                    file.setDocument(documentsService.get(docId));
                }
                fileService.save(file);
                file = null;
            }
        } catch (org.apache.commons.fileupload.FileUploadException | IOException | NumberFormatException e) {
            responseString = RESP_ERROR;
            LOG.error("Erro ao salvar o arquivo", e);
            file = null;
            throw e;
        }
    } // Not a multi-part MIME request.
    else {
        responseString = RESP_ERROR;
    }

    response.setContentType("application/json");
    byte[] responseBytes = responseString.getBytes();
    response.setContentLength(responseBytes.length);
    ServletOutputStream output = response.getOutputStream();
    output.write(responseBytes);
    output.flush();
    return responseString;
}

From source file:com.krawler.spring.crm.emailMarketing.crmEmailMarketingController.java

public ModelAndView saveEmailTemplateFiles(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    JSONObject result = new JSONObject();
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("JE_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    TransactionStatus status = txnManager.getTransaction(def);
    try {/*  www . ja  va2  s.  c  o  m*/
        result.put("success", false);
        int file_type = 1;
        String fType = request.getParameter("type");
        if (fType != null && fType.compareTo("img") == 0) {
            file_type = 0;
        }
        String companyid = sessionHandlerImpl.getCompanyid(request);
        String filename = "";
        ServletFileUpload fu = new ServletFileUpload(
                new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, new File("/tmp")));
        if (fu.isMultipartContent(request)) {
            List<FileItem> fileItems = fu.parseRequest(request);
            for (FileItem field : fileItems) {
                if (!field.isFormField()) {
                    String fname = new String(field.getName().getBytes(), "UTF8");
                    String file_id = java.util.UUID.randomUUID().toString();
                    String file_extn = fname.substring(fname.lastIndexOf("."));
                    filename = file_id.concat(file_extn);
                    boolean isUploaded = false;
                    fname = fname.substring(fname.lastIndexOf("\\") + 1);
                    if (field.getSize() != 0) {
                        String basePath = StorageHandler.GetDocStorePath() + companyid + "/" + fType;
                        File destDir = new File(basePath);
                        if (!destDir.exists()) {
                            destDir.mkdirs();
                        }
                        File uploadFile = new File(basePath + "/" + filename);
                        field.write(uploadFile);
                        isUploaded = true;
                        String id = request.getParameter("fileid");
                        if (StringUtil.isNullOrEmpty(id)) {
                            id = file_id;
                        }

                        crmEmailMarketingDAOObj.saveEmailTemplateFile(id, fname, file_extn, new Date(),
                                file_type, sessionHandlerImplObj.getUserid());
                    }
                }
            }
        }
        txnManager.commit(status);
        result.put("success", true);
    } catch (ServiceException e) {
        logger.warn(e.getMessage(), e);
        txnManager.rollback(status);
        try {
            result.put("msg", e.getMessage());
        } catch (Exception je) {
        }
    } catch (UnsupportedEncodingException ex) {
        logger.warn(ex.getMessage(), ex);
        txnManager.rollback(status);
        try {
            result.put("msg", ex.getMessage());
        } catch (Exception je) {
        }
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        txnManager.rollback(status);
        try {
            result.put("msg", e.getMessage());
        } catch (Exception je) {
        }
    }
    return new ModelAndView("jsonView", "model", result.toString());
}