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

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

Introduction

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

Prototype

String getContentType();

Source Link

Document

Returns the content type passed by the browser or null if not defined.

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();// w w w  . j av a2s.c o  m
    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.nabla.wapp.server.basic.general.ImportService.java

@Override
public String executeAction(final HttpServletRequest request, final List<FileItem> sessionFiles)
        throws UploadActionException {
    final UserSession userSession = UserSession.load(request);
    if (userSession == null) {
        if (log.isTraceEnabled())
            log.trace("missing user session");
        throw new UploadActionException("permission denied");
    }//w ww .j a va 2  s  .c o  m
    Assert.state(sessionFiles.size() == 1);
    try {
        for (FileItem file : sessionFiles) {
            if (file.isFormField())
                continue;
            if (log.isDebugEnabled()) {
                log.debug("field '" + file.getFieldName() + "': uploading " + file.getName());
                log.debug("field: " + file.getFieldName());
                log.debug("filename: " + file.getName());
                log.debug("content_type: " + file.getContentType());
                log.debug("size: " + file.getSize());
            }
            final Connection conn = db.getConnection();
            try {
                final PreparedStatement stmt = conn.prepareStatement(
                        "INSERT INTO import_data (field_name, file_name, content_type, length, content, userSessionId) VALUES(?,?,?,?,?,?);",
                        Statement.RETURN_GENERATED_KEYS);
                try {
                    stmt.setString(1, file.getFieldName());
                    stmt.setString(2, file.getName());
                    stmt.setString(3, file.getContentType());
                    stmt.setLong(4, file.getSize());
                    stmt.setString(6, userSession.getSessionId());
                    final InputStream fs = file.getInputStream();
                    try {
                        stmt.setBinaryStream(5, fs);
                        if (stmt.executeUpdate() != 1) {
                            if (log.isErrorEnabled())
                                log.error("failed to add imported file record");
                            throw new UploadActionException("internal error");
                        }
                        final ResultSet rsKey = stmt.getGeneratedKeys();
                        try {
                            rsKey.next();
                            final Integer id = rsKey.getInt(1);
                            if (log.isDebugEnabled())
                                log.debug(
                                        "uploading " + file.getName() + " successfully completed. id = " + id);
                            return id.toString();
                        } finally {
                            rsKey.close();
                        }
                    } finally {
                        fs.close();
                    }
                } catch (IOException e) {
                    if (log.isErrorEnabled())
                        log.error("error reading file " + file.getName(), e);
                    throw new UploadActionException("internal error");
                } finally {
                    Database.close(stmt);
                }
            } finally {
                // remove any orphan import records i.e. older than 48h (beware of timezone!)
                final Calendar dt = Util.dateToCalendar(new Date());
                dt.add(GregorianCalendar.DATE, -2);
                try {
                    Database.executeUpdate(conn, "DELETE FROM import_data WHERE created < ?;",
                            Util.calendarToSqlDate(dt));
                } catch (final SQLException __) {
                }
                Database.close(conn);
            }
        }
    } catch (SQLException e) {
        if (log.isErrorEnabled())
            log.error("error uploading file", e);
        throw new UploadActionException("internal error");
    } finally {
        super.removeSessionFileItems(request);
    }
    return null;
}

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;/*from  ww  w. j  av a  2 s.c o m*/

    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.github.davidcarboni.encryptedfileupload.EncryptedFileItemSerializeTest.java

/**
 * Compare FileItem's (except the byte[] content)
 *///from  w w w. j  a  v  a2  s.  co  m
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:com.intelligentz.appointmentz.controllers.addSession.java

@SuppressWarnings("Since15")
@Override//  w ww  . ja  v a  2  s .c om
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {
        String room_id = null;
        String doctor_id = null;
        String start_time = null;
        String date_picked = null;
        ArrayList<SessonCustomer> sessonCustomers = new ArrayList<>();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(maxMemSize);
        // Location to save data that is larger than maxMemSize.
        factory.setRepository(new File(filePath + "temp"));

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax(maxFileSize);

        // Parse the request to get file items.
        List fileItems = upload.parseRequest(req);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    filePath = filePath + fileName.substring(fileName.lastIndexOf("\\"));
                    file = new File(filePath);
                } else {
                    filePath = filePath + fileName.substring(fileName.lastIndexOf("\\") + 1);
                    file = new File(filePath);
                }
                fi.write(file);
                Files.lines(Paths.get(filePath)).forEach((line) -> {
                    String[] cust = line.split(",");
                    sessonCustomers.add(new SessonCustomer(cust[0].trim(), Integer.parseInt(cust[1].trim())));
                });
            } else {
                if (fi.getFieldName().equals("room_id"))
                    room_id = fi.getString();
                else if (fi.getFieldName().equals("doctor_id"))
                    doctor_id = fi.getString();
                else if (fi.getFieldName().equals("start_time"))
                    start_time = fi.getString();
                else if (fi.getFieldName().equals("date_picked"))
                    date_picked = fi.getString();
            }
        }

        con = new connectToDB();
        if (con.connect()) {
            Connection connection = con.getConnection();
            Class.forName("com.mysql.jdbc.Driver");
            Statement stmt = connection.createStatement();
            String SQL, SQL1, SQL2;
            SQL1 = "insert into db_bro.session ( doctor_id, room_id, date, start_time) VALUES (?,?,?,?)";
            PreparedStatement preparedStmt = connection.prepareStatement(SQL1);
            preparedStmt.setString(1, doctor_id);
            preparedStmt.setString(2, room_id);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH:mm");
            try {
                java.util.Date d = formatter.parse(date_picked + "-" + start_time);
                Date d_sql = new Date(d.getTime());
                java.util.Date N = new java.util.Date();
                if (N.compareTo(d) > 0) {
                    res.sendRedirect("./error.jsp?error=Invalid Date!");
                }
                //String [] T = start_time.split(":");
                //Time t = Time.valueOf(start_time);
                //Time t = new Time(Integer.parseInt(T[0]),Integer.parseInt(T[1]),0);

                //java.sql.Time t_sql = new java.sql.Date(d.getTime());
                preparedStmt.setString(4, start_time + ":00");
                preparedStmt.setDate(3, d_sql);
            } catch (ParseException e) {
                displayMessage(res, "Invalid Date!" + e.getLocalizedMessage());
            }

            // execute the preparedstatement
            preparedStmt.execute();

            SQL = "select * from db_bro.session ORDER BY session_id DESC limit 1";
            ResultSet rs = stmt.executeQuery(SQL);

            boolean check = false;
            while (rs.next()) {
                String db_doctor_id = rs.getString("doctor_id");
                String db_date_picked = rs.getString("date");
                String db_start_time = rs.getString("start_time");
                String db_room_id = rs.getString("room_id");

                if ((doctor_id == null ? db_doctor_id == null : doctor_id.equals(db_doctor_id))
                        && (start_time == null ? db_start_time == null
                                : (start_time + ":00").equals(db_start_time))
                        && (room_id == null ? db_room_id == null : room_id.equals(db_room_id))
                        && (date_picked == null ? db_date_picked == null
                                : date_picked.equals(db_date_picked))) {
                    check = true;
                    //displayMessage(res,"Authentication Success!");
                    SQL2 = "insert into db_bro.session_customers ( session_id, mobile, appointment_num) VALUES (?,?,?)";
                    for (SessonCustomer sessonCustomer : sessonCustomers) {
                        preparedStmt = connection.prepareStatement(SQL2);
                        preparedStmt.setString(1, rs.getString("session_id"));
                        preparedStmt.setString(2, sessonCustomer.getMobile());
                        preparedStmt.setInt(3, sessonCustomer.getAppointment_num());
                        preparedStmt.execute();
                    }
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        displayMessage(res, "SQLException");
                    }

                    res.sendRedirect("./home");

                }
            }
            if (!check) {

                try {
                    connection.close();
                } catch (SQLException e) {
                    displayMessage(res, "SQLException");
                }
                displayMessage(res, "SQL query Failed!");
            }
        } else {
            con.showErrormessage(res);
        }

        /*res.setContentType("text/html");//setting the content type
        PrintWriter pw=res.getWriter();//get the stream to write the data
                
        //writing html in the stream
        pw.println("<html><body>");
        pw.println("Welcome to servlet: "+username);
        pw.println("</body></html>");
                
        pw.close();//closing the stream
        */
    } catch (Exception ex) {
        Logger.getLogger(authenticate.class.getName()).log(Level.SEVERE, null, ex);
        displayMessage(res, "Error!" + ex.getLocalizedMessage());
    }
}

From source file:adminShop.registraProducto.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w  w w.j a  va  2 s.  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 {
    String message = "Error";
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items;
        HashMap hm = new HashMap();
        ArrayList<Imagen> imgs = new ArrayList<>();
        Producto prod = new Producto();
        Imagen img = null;
        try {
            items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    String value = item.getString();
                    hm.put(name, value);
                } else {
                    img = new Imagen();
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeBytes = item.getSize();
                    File file = new File("/home/gama/Escritorio/adoo/" + fileName + ".jpg");
                    item.write(file);
                    Path path = Paths.get("/home/gama/Escritorio/adoo/" + fileName + ".jpg");
                    byte[] data = Files.readAllBytes(path);
                    byte[] encode = org.apache.commons.codec.binary.Base64.encodeBase64(data);
                    img.setUrl(new javax.sql.rowset.serial.SerialBlob(encode));
                    imgs.add(img);
                    //file.delete();
                }
            }
            prod.setNombre((String) hm.get("nombre"));
            prod.setProdNum((String) hm.get("prodNum"));
            prod.setDesc((String) hm.get("desc"));
            prod.setIva(Double.parseDouble((String) hm.get("iva")));
            prod.setPrecio(Double.parseDouble((String) hm.get("precio")));
            prod.setPiezas(Integer.parseInt((String) hm.get("piezas")));
            prod.setEstatus("A");
            prod.setImagenes(imgs);
            ProductoDAO prodDAO = new ProductoDAO();
            if (prodDAO.registraProducto(prod)) {
                message = "Exito";
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    response.sendRedirect("index.jsp");
}

From source file:com.tasktop.c2c.server.tasks.web.service.AttachmentUploadController.java

@RequestMapping(value = "", method = RequestMethod.POST)
public void upload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, TextHtmlContentExceptionWrapper {
    try {/*from   ww w.j ava 2  s.c  o  m*/
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<Attachment> attachments = new ArrayList<Attachment>();
        Map<String, String> formValues = new HashMap<String, String>();

        try {
            List<FileItem> items = upload.parseRequest(request);

            for (FileItem item : items) {

                if (item.isFormField()) {
                    formValues.put(item.getFieldName(), item.getString());
                } else {
                    Attachment attachment = new Attachment();
                    attachment.setAttachmentData(readInputStream(item.getInputStream()));
                    attachment.setFilename(item.getName());
                    attachment.setMimeType(item.getContentType());
                    attachments.add(attachment);
                }

            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); // FIXME better code
            return;
        }

        for (int i = 0; i < attachments.size(); i++) {
            String description = formValues
                    .get(AttachmentUploadUtil.ATTACHMENT_DESCRIPTION_FORM_NAME_PREFIX + i);
            if (description == null) {
                throw new IllegalArgumentException(
                        "Missing description " + i + 1 + " of " + attachments.size());
            }
            attachments.get(0).setDescription(description);
        }

        TaskHandle taskHandle = getTaskHandle(formValues);

        UploadResult result = doUpload(response, attachments, taskHandle);

        response.setContentType("text/html");
        response.getWriter()
                .write(jsonMapper.writeValueAsString(Collections.singletonMap("uploadResult", result)));
    } catch (Exception e) {
        throw new TextHtmlContentExceptionWrapper(e.getMessage(), e);
    }
}

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

/**
 * Processes an uploaded file and stores it in MongoDB.
 * @param item file item from the parsed servlet request
 * @param currentId ID for the current MongoDB object for the advice
 * @return file name//from w  ww .j a  v  a2  s  .c  o m
 * @throws IOException 
 */
private String processUploadedFile(FileItem item, String currentId) throws IOException {
    System.out.println("file: size=" + item.getSize() + " name:" + item.getName());
    GridFS gridfs = mi.getImagesFS();
    String filename = currentId + ":" + item.getFieldName() + "_" + item.getName();
    gridfs.remove(filename);
    GridFSInputFile gfsFile = gridfs.createFile(item.getInputStream());
    gfsFile.setFilename(filename);
    gfsFile.setContentType(item.getContentType());
    gfsFile.save();
    return filename;
}

From source file:edu.stanford.epad.epadws.handlers.HandlerUtil.java

public static Map<String, Object> parsePostedData(String uploadDirPath, HttpServletRequest httpRequest,
        PrintWriter responseStream) throws Exception {
    File uploadDir = new File(uploadDirPath);
    if (!uploadDir.exists())
        uploadDir.mkdirs();/*  w  w  w.ja  va  2s  . co  m*/

    Map<String, Object> params = new HashMap<String, Object>();
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = upload.parseRequest(httpRequest);
    Iterator<FileItem> fileItemIterator = items.iterator();
    int fileCount = 0;
    while (fileItemIterator.hasNext()) {
        FileItem fileItem = fileItemIterator.next();
        if (fileItem.isFormField()) {
            if (params.get(fileItem.getFieldName()) == null)
                params.put(fileItem.getFieldName(), fileItem.getString());
            List values = (List) params.get(fileItem.getFieldName() + "_List");
            if (values == null) {
                values = new ArrayList();
                params.put(fileItem.getFieldName() + "_List", values);
            }
            values.add(fileItem.getString());
        } else {
            fileCount++;
            String fieldName = fileItem.getFieldName();
            if (fieldName.trim().length() == 0)
                fieldName = "File" + fileCount;
            String fileName = fileItem.getName();
            log.debug("Uploading file number " + fileCount);
            log.debug("FieldName: " + fieldName);
            log.debug("File Name: " + fileName);
            log.debug("ContentType: " + fileItem.getContentType());
            log.debug("Size (Bytes): " + fileItem.getSize());
            if (fileItem.getSize() != 0) {
                try {
                    String tempFileName = "temp" + System.currentTimeMillis() + "-" + fileName;
                    File file = new File(uploadDirPath + "/" + tempFileName);
                    log.debug("FileName: " + file.getAbsolutePath());
                    // write the file
                    fileItem.write(file);
                    if (params.get(fileItem.getFieldName()) == null)
                        params.put(fileItem.getFieldName(), file);
                    else
                        params.put(fileItem.getFieldName() + fileCount, file);
                    List values = (List) params.get(fileItem.getFieldName() + "_List");
                    if (values == null) {
                        values = new ArrayList();
                        params.put(fileItem.getFieldName() + "_List", values);
                    }
                    values.add(file);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.warning("Error receiving file:" + e);
                    responseStream.print("error reading (" + fileCount + "): " + fileItem.getName());
                    continue;
                }
            }
        }
    }
    return params;
}

From source file:com.finedo.base.utils.upload.FileUploadUtils.java

public static final List<FileInfo> saveFiles(String uploadDir, List<FileItem> list) {

    List filelist = new ArrayList();

    if (list == null) {
        return filelist;
    }/*from www .j av  a 2  s. c o m*/

    File dir = new File(uploadDir);
    if (!(dir.isDirectory())) {
        dir.mkdirs();
    }

    String uploadPath = uploadDir;

    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("utf-8");
    Iterator it = list.iterator();
    String name = "";
    String extName = "";

    while (it.hasNext()) {
        FileItem item = (FileItem) it.next();
        if (!(item.isFormField())) {
            name = item.getName();
            logger.info("saveFiles name=============" + name);

            if (name == null)
                continue;
            if (name.trim().equals("")) {
                continue;
            }

            if (name.lastIndexOf(".") >= 0) {
                extName = name.substring(name.lastIndexOf("."));
            }

            File file = null;
            do {
                name = UUID.randomUUID().toString();
                file = new File(uploadPath + name + extName);
            } while (file.exists());

            File saveFile = new File(uploadPath + name + extName);
            try {
                item.write(saveFile);
            } catch (Exception e) {
                e.printStackTrace();
            }

            String fileName = item.getName().replace("\\", "/");

            String[] ss = fileName.split("/");
            fileName = trimExtension(ss[(ss.length - 1)]);

            FileInfo fileinfo = new FileInfo();
            fileinfo.setName(fileName);
            fileinfo.setUname(name);
            fileinfo.setFilePath(uploadDir);
            fileinfo.setFileExt(extName);
            fileinfo.setSize(String.valueOf(item.getSize()));
            fileinfo.setContentType(item.getContentType());
            fileinfo.setFieldname(item.getFieldName());
            filelist.add(fileinfo);
        }
    }
    return filelist;
}