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

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

Introduction

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

Prototype

String getName();

Source Link

Document

Returns the original filename in the client's filesystem, as provided by the browser (or other client software).

Usage

From source file:com.ephesoft.gxt.systemconfig.server.ImportPoolServlet.java

/**
 * Unzip the attached zipped file.//from ww w . ja  v  a2 s  .c  o m
 * 
 * @param req {@link HttpServletRequest}
 * @param resp {@link HttpServletResponse}
 * @param batchSchemaService {@link BatchSchemaService}
 * @throws IOException
 */
private void attachFile(final HttpServletRequest req, final HttpServletResponse resp,
        final BatchSchemaService batchSchemaService) throws IOException {
    final PrintWriter printWriter = resp.getWriter();
    File tempZipFile = null;
    InputStream instream = null;
    OutputStream out = null;
    String tempOutputUnZipDir = CoreCommonConstant.EMPTY_STRING;

    if (ServletFileUpload.isMultipartContent(req)) {
        final FileItemFactory factory = new DiskFileItemFactory();
        final ServletFileUpload upload = new ServletFileUpload(factory);
        final String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation();
        final File exportSerailizationFolder = new File(exportSerailizationFolderPath);
        if (!exportSerailizationFolder.exists()) {
            exportSerailizationFolder.mkdir();
        }

        String zipFileName = CoreCommonConstant.EMPTY_STRING;
        String zipPathname = CoreCommonConstant.EMPTY_STRING;
        List<FileItem> items;

        try {
            items = upload.parseRequest(req);
            for (final FileItem item : items) {

                if (!item.isFormField()) {
                    zipFileName = item.getName();
                    if (zipFileName != null) {
                        zipFileName = zipFileName.substring(zipFileName.lastIndexOf(File.separator) + 1);
                    }
                    zipPathname = exportSerailizationFolderPath + File.separator + zipFileName;
                    // get only the file name not whole path
                    if (zipFileName != null) {
                        zipFileName = FilenameUtils.getName(zipFileName);
                    }
                    try {
                        instream = item.getInputStream();
                        tempZipFile = new File(zipPathname);
                        if (tempZipFile.exists()) {
                            tempZipFile.delete();
                        }
                        out = new FileOutputStream(tempZipFile);
                        final byte buf[] = new byte[1024];
                        int len;
                        while ((len = instream.read(buf)) > 0) {
                            out.write(buf, 0, len);
                        }
                    } catch (final FileNotFoundException fileNotFoundException) {
                        log.error("Unable to create the export folder." + fileNotFoundException,
                                fileNotFoundException);
                        printWriter.write("Unable to create the export folder.Please try again.");

                    } catch (final IOException ioException) {
                        log.error("Unable to read the file." + ioException, ioException);
                        printWriter.write("Unable to read the file.Please try again.");
                    } finally {
                        if (out != null) {
                            try {
                                out.close();
                            } catch (final IOException ioException) {
                                log.info("Could not close stream for file." + tempZipFile);
                            }
                        }
                        if (instream != null) {
                            try {
                                instream.close();
                            } catch (final IOException ioException) {
                                log.info("Could not close stream for file." + zipFileName);
                            }
                        }
                    }
                }
            }
        } catch (final FileUploadException fileUploadException) {
            log.error("Unable to read the form contents." + fileUploadException, fileUploadException);
            printWriter.write("Unable to read the form contents. Please try again.");
        }
        tempOutputUnZipDir = exportSerailizationFolderPath + File.separator
                + zipFileName.substring(0, zipFileName.lastIndexOf(CoreCommonConstant.DOT)) + System.nanoTime();
        try {
            FileUtils.unzip(tempZipFile, tempOutputUnZipDir);
        } catch (final Exception exception) {
            log.error("Unable to unzip the file." + exception, exception);
            printWriter.write("Unable to unzip the file. Please try again.");
            tempZipFile.delete();
        }

    } else {
        log.error("Request contents type is not supported.");
        printWriter.write("Request contents type is not supported.");
    }
    if (tempZipFile != null) {
        tempZipFile.delete();
    }

    printWriter.append(SystemConfigSharedConstants.FILE_PATH).append(tempOutputUnZipDir);
    //printWriter.append("filePath:").append(tempOutputUnZipDir);
    printWriter.append(CoreCommonConstant.PIPE);
    printWriter.flush();

}

From source file:Logic.UploadLogic.java

public void pictureUpload(HttpServletRequest request, UserDataBeans loginAccount, String contextPath) {
    for (int i = 0; i < 6; i++) {
    }/* w ww .j ava 2 s  .  com*/
    PictureDataBeans picture = null;

    //?
    System.out.println("" + request.getRequestURI());
    String path = "/Users/gest/NetBeansProjects/WorkSpacesProto/web/common/image/";
    File newDirectry = new File(path + loginAccount.getUserName());

    //?????
    if (!newDirectry.exists() || newDirectry == null) {
        newDirectry.mkdir();
        System.out.println("?");
    }

    //??
    String dPath = newDirectry.getPath();

    //???
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload sfu = new ServletFileUpload(factory);

    try {
        //????????
        List<FileItem> list = sfu.parseRequest(request);
        Iterator iterator = list.iterator();

        String pictureName = "";
        String extension = "";
        String comment = "????";
        int categoryID = 1;

        FileItem pictureData = null;

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

            //??
            if (!item.isFormField()) {
                pictureData = item;
                String itemName = item.getName();
                extension = itemName.substring(itemName.lastIndexOf("."));

                //()??   
            } else {
                System.out.println(item.getString("UTF-8"));
                switch (item.getFieldName()) {

                case "pictureName":
                    //?????
                    pictureName = item.getString("UTF-8");
                    //?????, [+]??
                    if (pictureName.isEmpty()) {
                        Date date = new Date();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                        String strDate = sdf.format(date);
                        pictureName = "" + strDate;
                    }
                    break;

                case "category":
                    categoryID = Integer.parseInt(item.getString("UTF-8"));
                    break;

                case "comment":
                    comment = item.getString("UTF-8");
                    break;
                }
            }
        }

        pictureData.write(new File(dPath + "/" + pictureName + extension));
        //??, DB??
        String pPath = contextPath + "/common/image/" + loginAccount.getUserName() + "/" + pictureName
                + extension;
        picture = new PictureDataBeans((pictureName + extension), pPath, comment, categoryID,
                loginAccount.getUserName());
        picture.setPictureID(picture.hashCode());

        //DB??
        PictureDataDTO dto = new PictureDataDTO();
        picture.PDB2DTOMapping(dto, loginAccount.getUserID());
        PictureDataDAO.getInstance().setPictureData(dto);

    } catch (FileUploadException ex) {
        Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.alibaba.citrus.service.requestcontext.parser.filter.UploadedFileExtensionWhitelist.java

public FileItem filter(String key, FileItem file) {
    if (file == null) {
        return null;
    }//  www .  ja  v  a 2  s. c  o  m

    boolean allowed = false;

    // ?? - null
    // ??? - null?
    // ???
    String ext = getExtension(file.getName(), "null", true);

    if (ext != null) {
        for (String allowedExtension : extensions) {
            if (allowedExtension.equals(ext)) {
                allowed = true;
                break;
            }
        }
    }

    if (!allowed) {
        log.getLogger().warn("Uploaded file type \"{}\" is denied: {}", ext, file.getName());
        return null;
    } else {
        return file;
    }
}

From source file:Control.LoadImage.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   w ww . ja  va  2  s . co  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String tempPath = "/temp";
    String absoluteTempPath = this.getServletContext().getRealPath(tempPath);
    String absoluteFilePath = this.getServletContext().getRealPath("/data/Image");
    int maxFileSize = 50 * 1024;
    int maxMemSize = 4 * 1024;

    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        File file = new File(absoluteTempPath);

        if (file == null) {
            // tao thu muc
        }

        factory.setRepository(file);
        ServletFileUpload upload = new ServletFileUpload(factory);

        //upload.setProgressListener(new MyProgressListener(out));
        List<FileItem> items = upload.parseRequest(request);

        if (items.size() > 0) {
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    if ("images".equals(item.getFieldName())) {
                        if (item.getName() != null && !item.getName().isEmpty()) {
                            String extension = null;
                            if (item.getName().endsWith("jpg")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".jpg";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".jpg");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            } else if (item.getName().endsWith("png")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".png";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".png");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            } else if (item.getName().endsWith("JPG")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".JPG";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".JPG");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            } else if (item.getName().endsWith("PNG")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".PNG";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".PNG");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            }
                        }
                    }
                } else {
                }
            }
            response.sendRedirect(request.getContextPath() + "/LoadImage.jsp");
            return;
        }

        List<Image> images = loadImages(request, response);

        request.setAttribute("images", images);
        request.setAttribute("error", "No file upload");
        RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/LoadImage.jsp");
        dispatcher.forward(request, response);
    } catch (Exception ex) {
        System.err.println(ex);
    }
}

From source file:Controller.ControllerImageCustomerIndex.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*w  w w  .j  a  v a  2s .c  om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {

    } else {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Iterator iter = items.iterator();
        Hashtable params = new Hashtable();
        String fileName = null;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), item.getString());
            } else {

                try {
                    String itemName = item.getName();
                    fileName = itemName.substring(itemName.lastIndexOf("\\") + 1);
                    System.out.println("path" + fileName);
                    String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName;
                    System.out.println("Rpath" + RealPath);
                    File savedFile = new File(RealPath);
                    item.write(savedFile);
                    String username = (String) params.get("txtusername");
                    String password = (String) params.get("txpassword");
                    String hoten = (String) params.get("txthoten");
                    String gioitinh = (String) params.get("txtgioitinh");
                    String email = (String) params.get("txtemail");
                    String role = "false";
                    Customer cus = new Customer(username, password, hoten, gioitinh, email, role,
                            "upload\\" + fileName);

                    CustomerDAO.ThemKhachHang(cus);
                    RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
                    rd.forward(request, response);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

    }

}

From source file:controller.insertProduct.java

private void insertProduct(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();

    String productType = null;//from w  w w.  j  a  v  a 2  s  .c  om
    String resolution = null;
    String hdmi = null;
    String usb = null;
    String model = null;
    String size = null;
    String warranty = null;

    String productName = null;
    int price = 0;
    String description = null;
    Integer quantity = null;
    String produceID = null;
    String image = null;

    String uploadDirectory = "/Product/Images";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);
    File uploadDir;
    File storeFile;
    try {
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);
        if (formItems != null && formItems.size() > 0) {
            for (FileItem item : formItems) {
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadDirectory + File.separator + fileName;
                    storeFile = new File(filePath);
                    item.write(storeFile);
                    image = produceID + "/" + fileName;
                    System.out.println(storeFile.getPath());
                } else {
                    switch (item.getFieldName()) {
                    case "productName":
                        productName = item.getString("UTF-8");
                        break;
                    case "produceID": {
                        produceID = item.getString("UTF-8");
                        uploadDir = new File(uploadPath + uploadDirectory + "/" + produceID);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdir();
                        }
                        uploadDirectory = uploadPath + uploadDirectory + "/" + produceID;
                        break;
                    }
                    case "price":
                        price = (Integer.parseInt(item.getString("UTF-8")));
                        break;
                    case "quantity":
                        quantity = (Integer.parseInt(item.getString("UTF-8")));
                        break;
                    case "productType":
                        productType = item.getString("UTF-8");
                        break;
                    case "resolution":
                        resolution = item.getString("UTF-8");
                        break;
                    case "hdmi":
                        hdmi = item.getString("UTF-8");
                        break;
                    case "usb":
                        usb = item.getString("UTF-8");
                        break;
                    case "Model":
                        model = item.getString("UTF-8");
                        break;
                    case "size":
                        size = item.getString("UTF-8");
                        break;
                    case "warranty":
                        warranty = item.getString("UTF-8");
                        break;
                    case "description": {
                        description = item.getString("UTF-8");
                        System.out.println(description);
                        break;
                    }
                    }
                }
            }
        }
    } catch (Exception ex) {
        System.out.println(ex);
    }

    @SuppressWarnings("null")
    ProductInfo prinfo = new ProductInfo(productType, resolution, hdmi, usb, model, size, warranty);
    Products product = new Products(productName, price, description, quantity, image, prinfo, produceID);

    if (ProductsDAO.insertProduct(product)) {
        out.print(
                "<center><b><font color='red'>thm thnh cng! </font> <a href = './WEB/admin/showProduct.jsp'>quay v?</a></b></center>");
    } else {
        out.print(
                "<center><b><font color='red'>Thm tht bi! </font> <a href = './WEB/admin/showProduct.jsp'>quay v?</a></b></center>");
    }
}

From source file:com.primeleaf.krystal.web.action.console.UpdateProfilePictureAction.java

@SuppressWarnings("rawtypes")
public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    request.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING);
    HttpSession session = request.getSession();
    User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL);
    if (request.getMethod().equalsIgnoreCase("POST")) {
        try {//from www  .j av  a2  s. co  m
            String userName = loggedInUser.getUserName();
            String sessionid = (String) session.getId();

            String tempFilePath = System.getProperty("java.io.tmpdir");

            if (!(tempFilePath.endsWith("/") || tempFilePath.endsWith("\\"))) {
                tempFilePath += System.getProperty("file.separator");
            }
            tempFilePath += userName + "_" + sessionid;

            //variables
            String fileName = "", ext = "";
            File file = null;
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            request.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING);
            upload.setHeaderEncoding(HTTPConstants.CHARACTER_ENCODING);
            List listItems = upload.parseRequest((HttpServletRequest) request);

            Iterator iter = listItems.iterator();
            FileItem fileItem = null;
            while (iter.hasNext()) {
                fileItem = (FileItem) iter.next();
                if (!fileItem.isFormField()) {
                    try {
                        fileName = fileItem.getName();
                        file = new File(fileName);
                        fileName = file.getName();
                        ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
                        if (!"JPEG".equalsIgnoreCase(ext) && !"JPG".equalsIgnoreCase(ext)
                                && !"PNG".equalsIgnoreCase(ext)) {
                            request.setAttribute(HTTPConstants.REQUEST_ERROR,
                                    "Invalid image. Please upload JPG or PNG file");
                            return (new MyProfileAction().execute(request, response));
                        }
                        file = new File(tempFilePath + "." + ext);
                        fileItem.write(file);
                    } catch (Exception ex) {
                        session.setAttribute("UPLOAD_ERROR", ex.getLocalizedMessage());
                        return (new MyProfileAction().execute(request, response));
                    }
                }
            } //if

            if (file.length() <= 0) { //code for checking minimum size of file
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Zero length document");
                return (new MyProfileAction().execute(request, response));
            }
            if (file.length() > (1024 * 1024 * 2)) { //code for checking minimum size of file
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Image size too large. Upload upto 2MB file");
                return (new MyProfileAction().execute(request, response));
            }

            User user = loggedInUser;
            user.setProfilePicture(file);
            UserDAO.getInstance().setProfilePicture(user);

            AuditLogManager.log(new AuditLogRecord(user.getUserId(), AuditLogRecord.OBJECT_USER,
                    AuditLogRecord.ACTION_EDITED, loggedInUser.getUserName(), request.getRemoteAddr(),
                    AuditLogRecord.LEVEL_INFO, "", "Profile picture update"));
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }
    request.setAttribute(HTTPConstants.REQUEST_MESSAGE, "Profile picture uploaded successfully");
    return (new MyProfileAction().execute(request, response));
}

From source file:it.geosolutions.servicebox.FileUploadCallback.java

/**
 * Handle a POST request//from  w w  w .  j  a va2s  . c  o m
 * 
 * @param request
 * @param response
 * 
 * @return CallbackResult
 * 
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public ServiceBoxActionParameters onPost(HttpServletRequest request, HttpServletResponse response,
        ServiceBoxActionParameters callbackResult) throws IOException {

    // Get items if already initialized
    List<FileItem> items = null;
    if (callbackResult == null) {
        callbackResult = new ServiceBoxActionParameters();
    } else {
        items = callbackResult.getItems();
    }

    String temp = callbackConfiguration.getTempFolder();
    int buffSize = callbackConfiguration.getBuffSize();
    int itemSize = 0;
    long maxSize = 0;
    String itemName = null;
    boolean fileTypeMatch = true;

    File tempDir = new File(temp);

    try {
        if (items == null && ServletFileUpload.isMultipartContent(request) && tempDir != null
                && tempDir.exists()) {
            // items are not initialized. Read it from the request

            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

            /*
             * Set the size threshold, above which content will be stored on
             * disk.
             */
            fileItemFactory.setSizeThreshold(buffSize); // 1 MB

            /*
             * Set the temporary directory to store the uploaded files of
             * size above threshold.
             */
            fileItemFactory.setRepository(tempDir);

            ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

            /*
             * Parse the request
             */
            items = uploadHandler.parseRequest(request);

        }

        // Read items
        if (items != null) {

            itemSize = items.size();
            callbackResult.setItems(items);
            if (itemSize <= this.callbackConfiguration.getMaxItems()) {
                // only if item size not exceeded max
                for (FileItem item : items) {
                    itemName = item.getName();
                    if (item.getSize() > maxSize) {
                        maxSize = item.getSize();
                        if (maxSize > this.callbackConfiguration.getMaxSize()) {
                            // max size exceeded
                            break;
                        } else if (this.callbackConfiguration.getFileTypePatterns() != null) {
                            fileTypeMatch = false;
                            int index = 0;
                            while (!fileTypeMatch
                                    && index < this.callbackConfiguration.getFileTypePatterns().size()) {
                                Pattern pattern = this.callbackConfiguration.getFileTypePatterns().get(index++);
                                fileTypeMatch = pattern.matcher(itemName).matches();
                            }
                            if (!fileTypeMatch) {
                                break;
                            }
                        }
                    }
                }
            }
        } else {
            itemSize = 1;
            maxSize = request.getContentLength();
            // TODO: Handle file type
        }

    } catch (Exception ex) {
        if (LOGGER.isLoggable(Level.SEVERE))
            LOGGER.log(Level.SEVERE, "Error encountered while parsing the request");

        response.setContentType("text/html");

        JSONObject jsonObj = new JSONObject();
        jsonObj.put("success", false);
        jsonObj.put("errorMessage", ex.getLocalizedMessage());

        Utilities.writeResponse(response, jsonObj.toString(), LOGGER);

    }

    // prepare and send error if exists
    boolean error = false;
    int errorCode = -1;
    String message = null;
    Map<String, Object> errorDetails = null;
    if (itemSize > this.callbackConfiguration.getMaxItems()) {
        errorDetails = new HashMap<String, Object>();
        error = true;
        errorDetails.put("expected", this.callbackConfiguration.getMaxItems());
        errorDetails.put("found", itemSize);
        errorCode = Utilities.JSON_MODEL.KNOWN_ERRORS.MAX_ITEMS.ordinal();
        message = "Max items size exceeded (expected: '" + this.callbackConfiguration.getMaxItems()
                + "', found: '" + itemSize + "').";
    } else if (maxSize > this.callbackConfiguration.getMaxSize()) {
        errorDetails = new HashMap<String, Object>();
        error = true;
        errorDetails.put("expected", this.callbackConfiguration.getMaxSize());
        errorDetails.put("found", maxSize);
        errorDetails.put("item", itemName);
        errorCode = Utilities.JSON_MODEL.KNOWN_ERRORS.MAX_ITEM_SIZE.ordinal();
        message = "Max item size exceeded (expected: '" + this.callbackConfiguration.getMaxSize()
                + "', found: '" + maxSize + "' on item '" + itemName + "').";
    } else if (fileTypeMatch == false) {
        errorDetails = new HashMap<String, Object>();
        error = true;
        String expected = this.callbackConfiguration.getFileTypes();
        errorDetails.put("expected", expected);
        errorDetails.put("found", itemName);
        errorDetails.put("item", itemName);
        errorCode = Utilities.JSON_MODEL.KNOWN_ERRORS.ITEM_TYPE.ordinal();
        message = "File type not maches with known file types: (expected: '" + expected + "', item '" + itemName
                + "').";
    }
    if (error) {
        callbackResult.setSuccess(false);
        Utilities.writeError(response, errorCode, errorDetails, message, LOGGER);
    } else {
        callbackResult.setSuccess(true);
    }

    return callbackResult;
}

From source file:at.ac.tuwien.dsg.depic.depictool.uploader.InputSpecificationUploader.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*www.j  a  v  a  2  s  . c om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //process only if its multipart content

    String eDaaSName = "";
    DBType dbType = null;
    String qor = "";
    String daw = "";

    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    // item.write( new File(UPLOAD_DIRECTORY + File.separator + name));

                    InputStream filecontent = item.getInputStream();

                    StringWriter writer = new StringWriter();
                    IOUtils.copy(filecontent, writer, "UTF-8");
                    String str = writer.toString();

                    //     String log = "item: " + item.getFieldName() + " - file name: " + name + " - content: " + str;

                    if (item.getFieldName().equals("qor")) {

                        qor = str;
                    }

                    if (item.getFieldName().equals("dataAnalyticsFunction")) {

                        daw = str;
                    }

                    //    Logger.getLogger(InputSpecificationUploader.class.getName()).log(Level.INFO, log);

                } else {

                    String fieldname = item.getFieldName();
                    String fieldvalue = item.getString();
                    if (fieldname.equals("edaas")) {
                        eDaaSName = fieldvalue;
                    }

                    if (fieldname.equals("dbtype")) {
                        String typeStr = fieldvalue;

                        if (typeStr.equals(DBType.MYSQL.getDBType())) {
                            dbType = DBType.MYSQL;
                        } else if (typeStr.equals(DBType.CASSANDRA.getDBType())) {
                            dbType = DBType.CASSANDRA;
                        }
                    }

                }
            }

            //File uploaded successfully
            request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to " + ex);
        }

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }

    String log = "edaas: " + eDaaSName;
    log = log + "dbType: " + dbType + "\n";
    log = log + "qor: " + qor + "\n";
    log = log + "daf: " + daw + "\n";
    log = log + "" + "\n";

    QoRModel qoRModel = YamlUtils.unmarshallYaml(QoRModel.class, qor);
    DataAnalyticsFunction dataAnalyticsFunction = new DataAnalyticsFunction(eDaaSName,
            qoRModel.getDataAssetForm(), dbType, daw);

    Logger.getLogger(InputSpecificationUploader.class.getName()).log(Level.INFO, log);

    ElasticProcessRepositoryManager eprm = new ElasticProcessRepositoryManager(
            getClass().getProtectionDomain().getCodeSource().getLocation().getPath());

    String dafStr = "";

    try {
        dafStr = JAXBUtils.marshal(dataAnalyticsFunction, DataAnalyticsFunction.class);
    } catch (JAXBException ex) {
        Logger.getLogger(InputSpecificationUploader.class.getName()).log(Level.SEVERE, null, ex);
    }

    eprm.insertDaaS(eDaaSName);
    eprm.storeDAF(eDaaSName, dafStr);
    eprm.storeQoR(eDaaSName, qor);
    eprm.storeDBType(eDaaSName, dbType.getDBType());

    Generator generator = new Generator(dataAnalyticsFunction, qoRModel);
    generator.startGenerator();

    //  

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

From source file:com.sic.plugins.kpp.provider.KPPBaseProvider.java

/**
 * Store uploaded file inside upload directory.
 * @param fileItemToUpload//  ww w.  j a v a  2s.  c o  m
 * @throws FileNotFoundException
 * @throws IOException 
 */
public void upload(FileItem fileItemToUpload) throws FileNotFoundException, IOException {
    // save uploaded file
    byte[] fileData = fileItemToUpload.get();
    File toUploadFile = new File(getUploadDirectoryPath(), fileItemToUpload.getName());
    OutputStream os = new FileOutputStream(toUploadFile);
    os.write(fileData);
}