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.infn.ct.picalc_portlet.java

/**
 * This method manages the user input fields managing two cases 
 * distinguished by the type of the input <form ... statement
 * The use of upload file controls needs the use of "multipart/form-data"
 * while the else condition of the isMultipartContent check manages the 
 * standard input case. The multipart content needs a manual processing of
 * all <form items//from   ww  w.  j  a  v a2  s.c  om
 * All form' input items are identified by the 'name' input property
 * inside the jsp file
 * 
 * @param request   ActionRequest instance (processAction)
 * @param appInput  AppInput instance storing the jobSubmission data
 */
void getInputForm(ActionRequest request, AppInput appInput) {
    if (PortletFileUpload.isMultipartContent(request))
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            PortletFileUpload upload = new PortletFileUpload(factory);
            List items = upload.parseRequest(request);
            File repositoryPath = new File("/tmp");
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setRepository(repositoryPath);
            Iterator iter = items.iterator();
            String logstring = "";
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                // Prepare a log string with field list
                logstring += LS + "field name: '" + fieldName + "' - '" + item.getString() + "'";
                switch (inputControlsIds.valueOf(fieldName)) {
                case JobIdentifier:
                    appInput.jobIdentifier = item.getString();
                    break;
                case CpuNumber:
                    appInput.cpuNumber = item.getString();
                    break;
                //case notifyEmail:
                //    appInput.notifyEmail=item.getString();
                //break;
                //case notifyStart:                        
                //    if (item.getString().equalsIgnoreCase("on"))
                //        appInput.notifyStart=true;
                //break;
                //case notifyStop:                        
                //    if (item.getString().equalsIgnoreCase("on"))
                //        appInput.notifyStop=true;
                //break;
                default:
                    // Should not happen unless inputControlsIds enum is not updated
                    _log.warn("Unhandled input field: '" + fieldName + "' - '" + item.getString() + "'");
                } // switch fieldName                                                   
            } // while iter.hasNext()   
            _log.info(LS + "Reporting" + LS + "---------" + LS + logstring + LS);
        } // try
        catch (Exception e) {
            _log.info("Caught exception while processing files to upload: '" + e.toString() + "'");
        }
    // The input form do not use the "multipart/form-data" 
    else {
        // Retrieve from the input form the given application values
        appInput.cpuNumber = (String) request.getParameter("CpuNumber");
        appInput.jobIdentifier = (String) request.getParameter("JobIdentifier");
        //appInput.notifyEmail  = (String)request.getParameter("notifyEmail"  );
        //appInput.notifyStart  =((String)request.getParameter("notifyStart" )).equalsIgnoreCase("on")?true:false;
        //appInput.notifyStop   =((String)request.getParameter("notifyStop"  )).equalsIgnoreCase("on")?true:false;
    } // ! isMultipartContent

    // Show into the log the taken inputs
    _log.info(LS + "Taken input parameters:" + LS + "-----------------------" + LS + "CpuNumber    : '"
            + appInput.cpuNumber + "'" + LS + "JobIdentifier: '" + appInput.jobIdentifier + "'"
            //+LS+"notifyEmail  : '"+appInput.notifyEmail  +"'"
            //+LS+"notifyStart  : '"+appInput.notifyStart  +"'"
            //+LS+"notifyStop   : '"+appInput.notifyStop   +"'"
            + LS);
}

From source file:cn.clxy.studio.common.web.multipart.GFileUploadSupport.java

/**
 * Parse the given List of Commons FileItems into a Spring MultipartParsingResult, containing Spring MultipartFile
 * instances and a Map of multipart parameter.
 *
 * @param fileItems the Commons FileIterms to parse
 * @param encoding the encoding to use for form fields
 * @return the Spring MultipartParsingResult
 * @see GMultipartFile#CommonsMultipartFile(org.apache.commons.fileupload.FileItem)
 *//*w  ww . j a va2 s.c o  m*/
protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) {
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();
    Map<String, String> multipartParameterContentTypes = new HashMap<String, String>();

    // Extract multipart files and multipart parameters.
    for (FileItem fileItem : fileItems) {
        if (fileItem.isFormField()) {
            String value = null;
            if (encoding != null) {
                try {
                    value = fileItem.getString(encoding);
                } catch (UnsupportedEncodingException ex) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not decode multipart item '" + fileItem.getFieldName()
                                + "' with encoding '" + encoding + "': using platform default");
                    }
                    value = fileItem.getString();
                }
            } else {
                value = fileItem.getString();
            }
            String[] curParam = multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] { value });
            } else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
            multipartParameterContentTypes.put(fileItem.getFieldName(), fileItem.getContentType());
        } else {
            // multipart file field
            GMultipartFile file = new GMultipartFile(fileItem);
            multipartFiles.add(file.getName(), file);
            if (logger.isDebugEnabled()) {
                logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                        + " bytes with original filename [" + file.getOriginalFilename() + "], stored "
                        + file.getStorageDescription());
            }
        }
    }
    return new MultipartParsingResult(multipartFiles, multipartParameters, multipartParameterContentTypes);
}

From source file:it.infn.ct.code_rade_portlet.java

/**
 * This method manages the user input fields managing two cases
 * distinguished by the type of the input <form ... statement
 * The use of upload file controls needs the use of "multipart/form-data"
 * while the else condition of the isMultipartContent check manages the
 * standard input case. The multipart content needs a manual processing of
 * all <form items/*ww w  . j av a 2s  . c  o  m*/
 * All form' input items are identified by the 'name' input property
 * inside the jsp file
 *
 * @param request   ActionRequest instance (processAction)
 * @param appInput  AppInput instance storing the jobSubmission data
 */
void getInputForm(ActionRequest request, AppInput appInput) {
    if (PortletFileUpload.isMultipartContent(request))
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            PortletFileUpload upload = new PortletFileUpload(factory);
            List items = upload.parseRequest(request);
            File repositoryPath = new File("/tmp");
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setRepository(repositoryPath);
            Iterator iter = items.iterator();
            String logstring = "";
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                // Prepare a log string with field list
                logstring += LS + "field name: '" + fieldName + "' - '" + item.getString() + "'";
                switch (inputControlsIds.valueOf(fieldName)) {
                case file_inputFile:
                    appInput.inputFileName = item.getString();
                    processInputFile(item, appInput);
                    break;
                case inputFile:
                    appInput.inputFileText = item.getString();
                    break;
                case JobIdentifier:
                    appInput.jobIdentifier = item.getString();
                    break;
                default:
                    _log.warn("Unhandled input field: '" + fieldName + "' - '" + item.getString() + "'");
                } // switch fieldName
            } // while iter.hasNext()
            _log.info(LS + "Reporting" + LS + "---------" + LS + logstring + LS);
        } // try
        catch (Exception e) {
            _log.info("Caught exception while processing files to upload: '" + e.toString() + "'");
        }
    // The input form do not use the "multipart/form-data"
    else {
        // Retrieve from the input form the given application values
        appInput.inputFileName = (String) request.getParameter("file_inputFile");
        appInput.inputFileText = (String) request.getParameter("inputFile");
        appInput.jobIdentifier = (String) request.getParameter("JobIdentifier");
    } // ! isMultipartContent

    // Show into the log the taken inputs
    _log.info(LS + "Taken input parameters:" + LS + "-----------------------" + LS + "inputFileName: '"
            + appInput.inputFileName + "'" + LS + "inputFileText: '" + appInput.inputFileText + "'" + LS
            + "jobIdentifier: '" + appInput.jobIdentifier + "'" + LS);
}

From source file:net.cbtltd.server.UploadFileService.java

/**
 * Handles upload file requests is in a page submitted by a HTTP POST method.
 * Form field values are extracted into a parameter list to set an associated Text instance.
 * 'File' type merely saves file and creates associated db record having code = file name.
 * Files may be rendered by reference in a browser if the browser is capable of the file type.
 * 'Image' type creates and saves thumbnail and full size jpg images and creates associated
 * text record having code = full size file name. The images may be viewed by reference in a browser.
 * 'Blob' type saves file and creates associated text instance having code = full size file name
 * and a byte array data value equal to the binary contents of the file.
 *
 * @param request the HTTP upload request.
 * @param response the HTTP response.//from w  w  w. jav a  2s  .c  om
 * @throws ServletException signals that an HTTP exception has occurred.
 * @throws IOException signals that an I/O exception has occurred.
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletRequestContext ctx = new ServletRequestContext(request);

    if (ServletFileUpload.isMultipartContent(ctx) == false) {
        sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "The servlet can only handle multipart requests."));
        return;
    }

    LOG.debug("UploadFileService doPost request " + request);

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    LOG.debug("\n doPost upload " + upload);

    SqlSession sqlSession = RazorServer.openSession();
    try {
        HashMap<String, String> params = new HashMap<String, String>();
        for (FileItem item : (List<FileItem>) upload.parseRequest(request)) {
            if (item.isFormField()) { // add for field value to parameter list
                String param = item.getFieldName();
                String value = item.getString();
                params.put(param, value);
            } else if (item.getSize() > 0) { // process uploaded file
                //               String fn = RazorServer.ROOT_DIRECTORY + item.getFieldName();    // input file path
                String fn = RazorConfig.getImageURL() + item.getFieldName(); // input file path
                LOG.debug("doPost fn " + fn);
                byte[] data = item.get();
                String mimeType = item.getContentType();

                String productId = item.getFieldName();
                Pattern p = Pattern.compile("\\d+");
                Matcher m = p.matcher(productId);
                while (m.find()) {
                    productId = m.group();
                    LOG.debug("Image uploaded for Product ID: " + productId);
                    break;
                }

                // TO DO - convert content type to mime..also check if uploaded type is image

                // getMagicMatch accepts Files or byte[],
                // which is nice if you want to test streams
                MagicMatch match = null;
                try {
                    match = parser.getMagicMatch(data, false);
                    LOG.debug("Mime type of image: " + match.getMimeType());
                } catch (MagicParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (MagicMatchNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (MagicException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                if (match != null) {
                    mimeType = match.getMimeType();
                }

                // image processor logic needs to know about the format of the image
                String contentType = RazorConfig.getMimeExtension(mimeType);

                if (StringUtils.isNotEmpty(contentType)) {
                    ImageService.uploadImages(sqlSession, productId, item.getFieldName(),
                            params.get(Text.FILE_NOTES), data, contentType);
                    LOG.debug("doPost commit params " + params);
                    sqlSession.commit();
                } else {
                    // unknown content/mime type...do not upload the file
                    sendResponse(response, new FormResponse(HttpServletResponse.SC_BAD_REQUEST,
                            "File type - " + contentType + " is not supported"));
                }
                //               File file = new File(fn);                            // output file name
                //               File tempf = File.createTempFile(Text.TEMP_FILE, "");
                //               item.write(tempf);
                //               file.delete();
                //               tempf.renameTo(file);
                //               int fullsizepixels = Integer.valueOf(params.get(Text.FULLSIZE_PIXELS));
                //               if (fullsizepixels <= 0) {fullsizepixels = Text.FULLSIZE_PIXELS_VALUE;}
                //               int thumbnailpixels = Integer.valueOf(params.get(Text.THUMBNAIL_PIXELS));
                //               if (thumbnailpixels <= 0) {thumbnailpixels = Text.THUMBNAIL_PIXELS_VALUE;}
                //
                //               setText(sqlSession, file, fn, params.get(Text.FILE_NAME), params.get(Text.FILE_TYPE), params.get(Text.FILE_NOTES), Language.EN, fullsizepixels, thumbnailpixels);
            }
        }
        sendResponse(response, new FormResponse(HttpServletResponse.SC_ACCEPTED, "OK"));
    } catch (Throwable x) {
        sqlSession.rollback();
        sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, x.getMessage()));
        LOG.error("doPost error " + x.getMessage());
    } finally {
        sqlSession.close();
    }
}

From source file:ex.fileupload.spring.GFileUploadSupport.java

/**
 * Parse the given List of Commons FileItems into a Spring
 * MultipartParsingResult, containing Spring MultipartFile instances and a
 * Map of multipart parameter./*from   w  w  w  .j av  a  2s  .c o m*/
 * 
 * @param fileItems
 *            the Commons FileIterms to parse
 * @param encoding
 *            the encoding to use for form fields
 * @return the Spring MultipartParsingResult
 * @see GMultipartFile#CommonsMultipartFile(org.apache.commons.fileupload.FileItem)
 */
protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) {
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();
    Map<String, String> multipartParameterContentTypes = new HashMap<String, String>();

    // Extract multipart files and multipart parameters.
    for (FileItem fileItem : fileItems) {
        if (fileItem.isFormField()) {
            String value = null;
            if (encoding != null) {
                try {
                    value = fileItem.getString(encoding);
                } catch (UnsupportedEncodingException ex) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not decode multipart item '" + fileItem.getFieldName()
                                + "' with encoding '" + encoding + "': using platform default");
                    }
                    value = fileItem.getString();
                }
            } else {
                value = fileItem.getString();
            }
            String[] curParam = multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] { value });
            } else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
            multipartParameterContentTypes.put(fileItem.getName(), fileItem.getContentType());
        } else {
            // multipart file field
            GMultipartFile file = new GMultipartFile(fileItem);
            multipartFiles.add(file.getName(), file);
            if (logger.isDebugEnabled()) {
                logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                        + " bytes with original filename [" + file.getOriginalFilename() + "], stored "
                        + file.getStorageDescription());
            }
        }
    }
    return new MultipartParsingResult(multipartFiles, multipartParameters, multipartParameterContentTypes);
}

From source file:axiom.servlet.AbstractServletClient.java

protected List parseUploads(ServletRequestContext reqcx, RequestTrans reqtrans, final UploadStatus uploadStatus,
        String encoding) throws FileUploadException, UnsupportedEncodingException {

    List uploads = null;//from   w w  w  .  j ava2s .  c o  m
    Context cx = Context.enter();
    ImporterTopLevel scope = new ImporterTopLevel(cx, true);

    try {
        // handle file upload
        DiskFileItemFactory factory = new DiskFileItemFactory();
        FileUpload upload = new FileUpload(factory);
        // use upload limit for individual file size, but also set a limit on overall size
        upload.setFileSizeMax(uploadLimit * 1024);
        upload.setSizeMax(totalUploadLimit * 1024);

        // register upload tracker with user's session
        if (uploadStatus != null) {
            upload.setProgressListener(new ProgressListener() {
                public void update(long bytesRead, long contentLength, int itemsRead) {
                    uploadStatus.update(bytesRead, contentLength, itemsRead);
                }
            });
        }

        uploads = upload.parseRequest(reqcx);
        Iterator it = uploads.iterator();

        while (it.hasNext()) {
            FileItem item = (FileItem) it.next();
            String name = item.getFieldName();
            Object value = null;
            // check if this is an ordinary HTML form element or a file upload
            if (item.isFormField()) {
                value = item.getString(encoding);
            } else {
                String itemName = item.getName().trim();
                if (itemName == null || itemName.equals("")) {
                    continue;
                }
                value = new MimePart(itemName, item.get(), item.getContentType());
                value = new NativeJavaObject(scope, value, value.getClass());
            }
            item.delete();
            // if multiple values exist for this name, append to _array

            // reqtrans.addPostParam(name, value); ????

            Object ret = reqtrans.get(name);
            if (ret != null && ret != Scriptable.NOT_FOUND) {
                appendFormValue(reqtrans, name, value);
            } else {
                reqtrans.set(name, value);
            }
        }
    } finally {
        Context.exit();
    }

    return uploads;
}

From source file:it.univaq.servlet.Modifica_pub.java

protected boolean action_upload(HttpServletRequest request) throws FileUploadException, Exception {
    HttpSession s = SecurityLayer.checkSession(request);
    //dichiaro mappe 
    Map pubb = new HashMap();
    Map rist = new HashMap();
    Map key = new HashMap();
    Map files = new HashMap();
    Map modifica = new HashMap();

    int id = Integer.parseInt(request.getParameter("id"));

    if (ServletFileUpload.isMultipartContent(request)) {

        //La dimensione massima di ogni singolo file su system
        int dimensioneMassimaDelFileScrivibieSulFileSystemInByte = 10 * 1024 * 1024; // 10 MB
        //Dimensione massima della request
        int dimensioneMassimaDellaRequestInByte = 20 * 1024 * 1024; // 20 MB

        // Creo un factory per l'accesso al filesystem
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //Setto la dimensione massima di ogni file, opzionale
        factory.setSizeThreshold(dimensioneMassimaDelFileScrivibieSulFileSystemInByte);

        // Istanzio la classe per l'upload
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Setto la dimensione massima della request
        upload.setSizeMax(dimensioneMassimaDellaRequestInByte);

        // Parso la riquest della servlet, mi viene ritornata una lista di FileItem con
        // tutti i field sia di tipo file che gli altri
        List<FileItem> items = upload.parseRequest(request);

        /*// w  w w  . j a va 2 s . c om
        * La classe usata non permette di riprendere i singoli campi per
        * nome quindi dovremmo scorrere la lista che ci viene ritornata con
        * il metodo parserequest
        */
        //scorro per tutti i campi inviati
        for (int i = 0; i < items.size(); i++) {
            FileItem item = items.get(i);
            // Controllo se si tratta di un campo di input normale
            if (item.isFormField()) {
                // Prendo solo il nome e il valore
                String name = item.getFieldName();
                String value = item.getString();

                if (name.equals("titolo") || name.equals("autore") || name.equals("descrizione")) {
                    pubb.put(name, value);
                } else if (name.equals("isbn") || name.equals("editore") || name.equals("lingua")
                        || name.equals("numpagine") || name.equals("datapubbl")) {
                    rist.put(name, value);
                } else if (name.equals("key1") || name.equals("key2") || name.equals("key3")
                        || name.equals("key4")) {
                    key.put(name, value);
                } else if (name.equals("descrizionemod")) {
                    modifica.put(name, value);
                }

            } // Se si stratta invece di un file
            else {
                // Dopo aver ripreso tutti i dati disponibili name,type,size
                //String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                long sizeInBytes = item.getSize();
                //li salvo nella mappa
                files.put("name", fileName);
                files.put("type", contentType);
                files.put("size", sizeInBytes);
                //li scrivo nel db
                //Database.connect();
                Database.insertRecord("files", files);
                //Database.close();

                // Posso scriverlo direttamente su filesystem
                if (true) {
                    File uploadedFile = new File(
                            getServletContext().getInitParameter("uploads.directory") + fileName);
                    // Solo se veramente ho inviato qualcosa
                    if (item.getSize() > 0) {
                        item.write(uploadedFile);
                    }
                }
            }

        }

        pubb.put("idutente", s.getAttribute("userid"));
        modifica.put("userid", s.getAttribute("userid"));
        modifica.put("idpubb", id);

        try {
            //    if(Database.updateRecord("keyword", key, "id="+id)){

            //aggiorno ora la pubblicazione con tutti i dati
            Database.updateRecord("keyword", key, "id=" + id);
            Database.updateRecord("pubblicazione", pubb, "id=" + id);
            Database.updateRecord("ristampa", rist, "idpub=" + id);
            Database.insertRecord("storia", modifica);

            //    //vado alla pagina di corretto inserimento

            return true;
        } catch (SQLException ex) {
            Logger.getLogger(Modifica_pub.class.getName()).log(Level.SEVERE, null, ex);
        }

    } else
        return false;
    return false;
}

From source file:it.infn.ct.R_portlet.java

void getInputForm(ActionRequest request, App_Input appInput) {
    if (PortletFileUpload.isMultipartContent(request))
        try {//from w w  w .j a  v  a2s . c  om
            FileItemFactory factory = new DiskFileItemFactory();
            PortletFileUpload upload = new PortletFileUpload(factory);
            List items = upload.parseRequest(request);
            File repositoryPath = new File("/tmp");
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setRepository(repositoryPath);
            Iterator iter = items.iterator();
            String logstring = "";
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                // Prepare a log string with field list
                logstring += LS + "field name: '" + fieldName + "' - '" + item.getString() + "'";
                switch (inputControlsIds.valueOf(fieldName)) {
                case file_inputFile:
                    appInput.inputFileName = item.getString();
                    processInputFile(item, appInput);
                    break;
                case inputFile:
                    appInput.inputFileText = item.getString();
                    break;
                case JobIdentifier:
                    appInput.jobIdentifier = item.getString();
                    break;
                default:
                    _log.warn("Unhandled input field: '" + fieldName + "' - '" + item.getString() + "'");
                } // switch fieldName                                                   
            } // while iter.hasNext()   
            _log.info(LS + "Reporting" + LS + "---------" + LS + logstring + LS);
        } // try
        catch (Exception e) {
            _log.info("Caught exception while processing files to upload: '" + e.toString() + "'");
        }
    // The input form do not use the "multipart/form-data" 
    else {
        // Retrieve from the input form the given application values
        appInput.inputFileName = (String) request.getParameter("file_inputFile");
        appInput.inputFileText = (String) request.getParameter("inputFile");
        appInput.jobIdentifier = (String) request.getParameter("JobIdentifier");
    } // ! isMultipartContent

    // Show into the log the taken inputs
    _log.info(LS + "Taken input parameters:" + LS + "-----------------------" + LS + "inputFileName: '"
            + appInput.inputFileName + "'" + LS + "inputFileText: '" + appInput.inputFileText + "'" + LS
            + "jobIdentifier: '" + appInput.jobIdentifier + "'" + LS);
}

From source file:it.infn.ct.corsika_portlet.java

/**
 * This method manages the user input fields managing two cases
 * distinguished by the type of the input <form ... statement The use of
 * upload file controls needs the use of "multipart/form-data" while the
 * else condition of the isMultipartContent check manages the standard input
 * case. The multipart content needs a manual processing of all <form items
 * All form' input items are identified by the 'name' input property inside
 * the jsp file// w w  w  . ja v  a2s  .  c  om
 * @param request ActionRequest instance (processAction)
 * @param appInput AppInput instance storing the jobSubmission data
 */

void getInputForm(ActionRequest request, corsika_portlet.AppInput appInput) {

    if (PortletFileUpload.isMultipartContent(request)) {
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            PortletFileUpload upload = new PortletFileUpload(factory);
            List items = upload.parseRequest(request);
            File repositoryPath = new File("/tmp");
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setRepository(repositoryPath);
            Iterator iter = items.iterator();
            String logstring = "";
            int i = 0;
            int j = 0;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                String fieldName = item.getFieldName();

                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                // Prepare a log string with field list
                switch (corsika_portlet.inputControlsIds.valueOf(fieldName)) {

                case jobPID:
                    logstring += LS + "FIELD IS A JOB PID  WITH NAME : '" + item.getString() + "'";
                    appInput.jobPID = item.getString();
                    break;
                case JobIdentifier:
                    logstring += LS + "FIELD IS A JOB IDENTIFIER  WITH NAME : '" + item.getString() + "'";
                    appInput.jobIdentifier = item.getString();
                    break;
                case file_inputFile:
                    if (fileName == "")
                        break;
                    logstring += LS + "FIELD IS A FILE WITH NAME : '" + fileName + "'";
                    appInput.inputFile = appInput.path + "/" + fileName;
                    logstring += LS + "COPYING IT TO PATH : '" + appInput.path + "'";
                    copyFile(item, appInput.inputFile);
                    break;
                case corsikaVersion:
                    appInput.corsikaVersion = item.getString();
                    logstring += LS + "FIELD IS A CORSIKA VERSION WITH NAME : '" + appInput.corsikaVersion
                            + "'";
                    break;
                case parametricJob:
                    if (item.getString().trim().equals("yes"))
                        appInput.parametricJob = true;
                    else
                        appInput.parametricJob = false;
                    logstring += LS + "FIELD IS A PARAMETRIC JOB SPECIFICATION : '"
                            + appInput.parametricJob.toString() + "'";
                    break;
                case emailWhenFinished:
                    if (item.getString().trim().equals("yes"))
                        appInput.emailWhenFinished = true;
                    else
                        appInput.emailWhenFinished = false;
                    logstring += LS + "FIELD IS A EMAIL WHEN FINISHED SPECIFICATION : '"
                            + appInput.emailWhenFinished.toString() + "'";
                    break;
                case useStorageElement:
                    if (item.getString().trim().equals("yes"))
                        appInput.useStorageElement = true;
                    else
                        appInput.useStorageElement = false;
                    logstring += LS + "FIELD IS A STORAGE ELEMENT SPECIFICATION : '"
                            + appInput.useStorageElement.toString() + "'";
                    break;
                default:
                    _log.warn("Unhandled input field: '" + fieldName + "' - '" + item.getString() + "'");
                } // switch fieldName
            } // while iter.hasNext()   
            _log.info(LS + "Reporting" + LS + "---------" + LS + logstring + LS);
        } // try
        catch (Exception e) {
            _log.info("Caught exception while processing files to upload: '" + e.toString() + "'");
        }
    } // The input form do not use the "multipart/form-data" 
    else {
        // Retrieve from the input form the given application values
        //            appInput.inputFileName = (String) request.getParameter("file_inputFile");
        //            appInput.inputFileText = (String) request.getParameter("inputFile");
        appInput.jobIdentifier = (String) request.getParameter("JobIdentifier");

    } // ! isMultipartContent

    // Show into the log the taken inputs
    _log.info(LS + "Taken input parameters:" + LS + "-----------------------"
    //                + LS + "inputFileName: '" + appInput.inputFileName + "'"
    //                + LS + "inputFileText: '" + appInput.inputFileText + "'"
            + LS + "jobIdentifier: '" + appInput.jobIdentifier + "'" + LS + "jobPID: '" + appInput.jobPID + "'"
            + LS + "inputFile: '" + appInput.inputFile + "'" + LS);

}

From source file:com.example.app.ui.vtcrop.VTCropPictureEditor.java

@Nullable
private FileItem _getUIValue(@Nullable FileItem uiValue) {
    if (uiValue == null) {
        return null;
    }//from  ww w. j a v a 2 s .com

    Dimension origDim, newDim;
    try {
        origDim = ImageFileUtil.getDimension(uiValue);
    } catch (IOException e) {
        _logger.error("Skipping scaling because an error occurred.", e);
        return uiValue;
    }

    if (origDim == null) {
        _logger.warn("Skipping scaling because retrieved dimension for ui value was null.");
        return uiValue;
    }

    VTCropPictureEditorConfig.ImageScaleOption option = _config.getImageScaleOptionForName(_uiValue.getName());
    int newDimWidth = option != null && option.scale != null
            ? Double.valueOf(_config.getCropWidth() * option.scale).intValue()
            : _config.getCropWidth();
    int newDimHeight = option != null && option.scale != null
            ? Double.valueOf(_config.getCropHeight() * option.scale).intValue()
            : _config.getCropHeight();

    newDim = ImageFileUtil.getScaledDimension(origDim, newDimWidth, newDimHeight);

    if (!newDim.equals(origDim)) {
        _logger.debug("Scale to " + newDim.getWidthMetric() + " x " + newDim.getHeightMetric());
        FileItem scaledFileItem = _fileItemFactory.createItem(uiValue.getFieldName(), uiValue.getContentType(),
                uiValue.isFormField(), uiValue.getName());
        try (InputStream is = uiValue.getInputStream(); OutputStream os = scaledFileItem.getOutputStream()) {
            Thumbnailer tn = Thumbnailer.getInstance(is);
            BufferedImage scaledImg = tn.getQualityThumbnail(newDim.getWidthMetric().intValue(),
                    newDim.getHeightMetric().intValue());
            String extension = StringFactory.getExtension(uiValue.getName());
            ImageIO.write(scaledImg, extension, os);
            uiValue.delete();
            uiValue = scaledFileItem;
        } catch (Throwable e) {
            _logger.warn("Skipping scaling due to:", e);
        }
    }

    return uiValue;
}