Example usage for org.apache.commons.fileupload.portlet PortletFileUpload isMultipartContent

List of usage examples for org.apache.commons.fileupload.portlet PortletFileUpload isMultipartContent

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.portlet PortletFileUpload isMultipartContent.

Prototype

public static final boolean isMultipartContent(ActionRequest request) 

Source Link

Document

Utility method that determines whether the request contains multipart content.

Usage

From source file:it.infn.ct.mi_parallel_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/*  www  .  j  a v a2 s . c  om*/
 * @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 = "";
            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
                logstring += LS + "field name: '" + fieldName + "' - '" + item.getString() + "'";
                switch (inputControlsIds.valueOf(fieldName)) {
                case JobIdentifier:
                    appInput.jobIdentifier = item.getString();
                    break;
                case collection_type:
                    appInput.collectionType = item.getString();
                    break;
                case task_number:
                    appInput.taskNumber = item.getString();
                    break;
                case parametric_executable:
                    appInput.executable = item.getString();
                    break;
                case executables:
                    appInput.executables.add(item.getString());
                    i++;
                    break;
                case argument:
                    appInput.arguments.add(item.getString());
                    j++;
                    break;
                case final_executable:
                    appInput.finalJobExecutable = item.getString();
                    break;
                case final_argument:
                    appInput.finalJobArgument = 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.jobIdentifier = (String) request.getParameter("JobIdentifier");
        appInput.collectionType = (String) request.getParameter("collection_type");
        appInput.taskNumber = (String) request.getParameter("task_number");

    } // ! isMultipartContent

    String tmp = "";
    for (int i = 0; i < appInput.executables.size(); i++) {
        if (!appInput.collectionType.equals("JOB_PARAMETRIC")) {
            tmp += LS + "executables[" + i + "]:" + appInput.executables.get(i) + "'";
        } else {
            tmp += LS + "executable:" + appInput.executable + "'";
        }
        tmp += LS + "arguments[" + i + "]:" + appInput.arguments.get(i) + "'";
    }
    // 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 + "collectionType: '"
            + appInput.collectionType + "'" + LS + "taskNumber: '" + appInput.taskNumber + "'" + LS + tmp + LS
            + "finalJobExecutable: '" + appInput.finalJobExecutable + "'" + LS + "finalJobArgument: '"
            + appInput.finalJobArgument + "'" + LS);

}

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  a  va  2 s .  co 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:it.infn.ct.molon_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/*  ww w .  j  a  v a 2  s .com*/
 * @param request ActionRequest instance (processAction)
 * @param appInput AppInput instance storing the jobSubmission data
 */

void getInputForm(ActionRequest request, molon_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 (molon_portlet.inputControlsIds.valueOf(fieldName)) {

                case jobPID:
                    logstring += LS + "FIELD IS A JOB PID  WITH NAME : '" + item.getString() + "'";
                    appInput.jobPID = item.getString();
                    break;
                case inputURL:
                    logstring += LS + "FIELD IS AN INPUT URL  WITH NAME : '" + item.getString() + "'";
                    appInput.inputURL = 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;
                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 + "inputURL: '" + appInput.inputURL + "'" + LS + "inputFile: '" + appInput.inputFile + "'"
            + 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  ww. ja va  2  s.  c  o  m
 * @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:it.infn.ct.ParallelSemanticSearch_portlet.java

public void getInputForm(ActionRequest request, App_Input appInput) {
    if (PortletFileUpload.isMultipartContent(request)) {
        try {//from ww w. j  a  v  a  2s .c o  m
            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;
                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.search_word = (String) request.getParameter("search_word");
        appInput.jobIdentifier = (String) request.getParameter("JobIdentifier");
        appInput.nameSubject = (String) request.getParameter("nameSubject");

        appInput.idResouce = (String) request.getParameter("idResource");
        appInput.selected_language = (String) request.getParameter("selLanguage");
        appInput.numberPage = (String) request.getParameter("numberOfPage");
        appInput.numberPageOpenAgris = (String) request.getParameter("numberOfPageOpenAgris");
        appInput.numRecordsForPage = (String) request.getParameter("numberOfRecords");
        appInput.moreResourceCHAIN = (String) request.getParameter("moreResourceCHAIN");
        appInput.moreResourceOpenAgris = (String) request.getParameter("moreResourceOpenAgris");
        appInput.idResourceOpenAgris = (String) request.getParameter("idResourceOpenAgris");
        appInput.moreInfoOpenAgris = (String) request.getParameter("moreInfoOpenAgris");
        appInput.moreInfo = (String) request.getParameter("moreInfo");
        appInput.numberPageCulturaItalia = (String) request.getParameter("numberOfPageCulturaItalia");
        appInput.moreResourceCulturaItalia = (String) request.getParameter("moreResourceCulturaItalia");
        appInput.moreInfoCulturaItalia = (String) request.getParameter("moreInfoCulturaItalia");
        appInput.numResource = (String) request.getParameter("numResource");
        appInput.numResourceFromDetails = (String) request.getParameter("numResourceFromDetails");
        appInput.numResourceOpenAgris = (String) request.getParameter("numResourceOpenAgris");
        appInput.numResourceOpenAgrisFromDetails = (String) request
                .getParameter("numResourceOpenAgrisFromDetails");
        appInput.numResourceCulturaItalia = (String) request.getParameter("numResourceCulturaItalia");
        appInput.numResourceCulturaItaliaFromDetails = (String) request
                .getParameter("numResourceCulturaItaliaFromDetails");
        appInput.idResourceCulturaItalia = (String) request.getParameter("idResourceCulturaItalia");

        appInput.numberPageIsidore = (String) request.getParameter("numberOfPageIsidore");
        appInput.moreResourceIsidore = (String) request.getParameter("moreResourceIsidore");
        appInput.idResourceIsidore = (String) request.getParameter("idResourceIsidore");
        appInput.numResourceIsidore = (String) request.getParameter("numResourceIsidore");
        appInput.numResourceIsidoreFromDetails = (String) request.getParameter("numResourceIsidoreFromDetails");
        appInput.numberPageIsidore = (String) request.getParameter("numberOfPageIsidore");
        appInput.moreInfoIsidore = (String) request.getParameter("moreInfoIsidore");

        appInput.idResourceEuropeana = (String) request.getParameter("idResourceEuropeana");
        appInput.moreResourceEuropeana = (String) request.getParameter("moreResourceEuropeana");
        appInput.numberPageEuropeana = (String) request.getParameter("numberOfPageEuropeana");
        appInput.numResourceEuropeana = (String) request.getParameter("numResourceEuropeana");
        appInput.numResourceEuropeanaFromDetails = (String) request
                .getParameter("numResourceEuropeanaFromDetails");
        appInput.numberPageEuropeana = (String) request.getParameter("numberOfPageEuropeana");
        appInput.moreInfoEuropeana = (String) request.getParameter("moreInfoEuropeana");

        appInput.idResourcePubmed = (String) request.getParameter("idResourcePubmed");
        appInput.moreResourcePubmed = (String) request.getParameter("moreResourcePubmed");
        appInput.numberPagePubmed = (String) request.getParameter("numberOfPagePubmed");
        appInput.numResourcePubmed = (String) request.getParameter("numResourcePubmed");
        appInput.numResourcePubmedFromDetails = (String) request.getParameter("numResourcePubmedFromDetails");
        appInput.moreInfoPubmed = (String) request.getParameter("moreInfoPubmed");

        appInput.idResourceEngage = (String) request.getParameter("idResourceEngage");
        appInput.moreResourceEngage = (String) request.getParameter("moreResourceEngage");
        appInput.numberPageEngage = (String) request.getParameter("numberOfPageEngage");
        appInput.numResourceEngage = (String) request.getParameter("numResourceEngage");
        appInput.numResourceEngageFromDetails = (String) request.getParameter("numResourceEngageFromDetails");
        appInput.moreInfoEngage = (String) request.getParameter("moreInfoEngage");
        appInput.title_GS = (String) request.getParameter("title_GS");

    } // ! isMultipartContent

    // Show into the log the taken inputs
    _log.info(LS + "Taken input parameters:" + LS + "-----------------------" + LS + "Search Word: '"
            + appInput.search_word + "'" + LS + "jobIdentifier: '" + appInput.jobIdentifier + "'" + LS
            + "subject: '" + appInput.nameSubject + "'" + LS + "idResource: '" + appInput.idResouce + "'" + LS
            + "language selected: '" + appInput.selected_language + "'" + LS + "number page selected: '"
            + appInput.numberPage + "'" + LS + "number record for page: '" + appInput.numRecordsForPage + "'"
            + LS + "number page selected OpenAgris: '" + appInput.numberPageOpenAgris + "'" + LS
            + "moreResourceCHAIN: '" + appInput.moreResourceCHAIN + "'" + LS + "moreInfo: '" + appInput.moreInfo
            + "'" + LS + "moreResourceOpenAgris: '" + appInput.moreResourceOpenAgris + "'" + LS
            + "idResourceOpenAgris: '" + appInput.idResourceOpenAgris + "'" + LS + "moreInfoOpenAgris: '"
            + appInput.moreInfoOpenAgris + "'" + LS + "number page selected CulturaItalia: '"
            + appInput.numberPageCulturaItalia + "'" + LS + "moreResourceCulturaItalia: '"
            + appInput.moreResourceCulturaItalia + "'" + LS + "moreInfoCulturaItalia: '"
            + appInput.moreInfoCulturaItalia + "'" + LS + "NumResource: '" + appInput.numResource + "'" + LS
            + "NumResourceFromDetails: '" + appInput.numResourceFromDetails + "'" + LS
            + "NumResourceOpenAgris: '" + appInput.numResourceOpenAgris + "'" + LS
            + "NumResourceOpenAgrisFromDetails: '" + appInput.numResourceOpenAgrisFromDetails + "'" + LS
            + "NumResourceCulturaItalia: '" + appInput.numResourceCulturaItalia + "'" + LS
            + "NumResourceCulturaItaliaFromDetails: '" + appInput.numResourceCulturaItaliaFromDetails + "'" + LS
            + "idResourceCulturaItalia: '" + appInput.idResourceCulturaItalia + "'" + LS
            + "moreResourceEuropeana: '" + appInput.moreResourceEuropeana + "'" + LS);
}

From source file:it.infn.ct.nuclemd.Nuclemd.java

public String[] uploadNuclemdSettings(ActionRequest actionRequest, ActionResponse actionResponse,
        String username) {/*from   ww w .j a  va2s  .  c  o  m*/
    String[] NUCLEMD_Parameters = new String[9];
    boolean status;

    // Check that we have a file upload request
    boolean isMultipart = PortletFileUpload.isMultipartContent(actionRequest);

    if (isMultipart) {
        // Create a factory for disk-based file items.
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Set factory constrains
        File NUCLEMD_Repository = new File("/tmp");
        if (!NUCLEMD_Repository.exists())
            status = NUCLEMD_Repository.mkdirs();
        factory.setRepository(NUCLEMD_Repository);

        // Create a new file upload handler.
        PortletFileUpload upload = new PortletFileUpload(factory);

        try {
            // Parse the request
            List items = upload.parseRequest(actionRequest);
            // Processing items
            Iterator iter = items.iterator();

            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                String fieldName = item.getFieldName();

                DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                String timeStamp = dateFormat.format(Calendar.getInstance().getTime());

                // Processing a regular form field
                if (item.isFormField()) {
                    if (fieldName.equals("nuclemd_release"))
                        NUCLEMD_Parameters[8] = item.getString();

                    if (fieldName.equals("nuclemd_desc"))
                        if (item.getString().equals("Please, insert here a description"))
                            NUCLEMD_Parameters[0] = "NUCLEMD Simulation Started";
                        else
                            NUCLEMD_Parameters[0] = item.getString();

                    if (fieldName.equals("nuclemd_CE"))
                        NUCLEMD_Parameters[1] = item.getString();

                } else {
                    // Processing a file upload
                    if (fieldName.equals("nuclemd_fileinp")) {
                        log.info("\n- Uploading the input file: " + "\n[ " + item.getName() + " ]" + "\n[ "
                                + item.getContentType() + " ]" + "\n[ " + item.getSize() + "KBytes ]");

                        // Writing the file to disk
                        String uploadNuclemdFile = NUCLEMD_Repository + "/" + timeStamp + "_" + username + "_"
                                + item.getName();

                        log.info("\n- Writing the file: [ " + uploadNuclemdFile.toString() + " ] to disk");

                        item.write(new File(uploadNuclemdFile));

                        // Writing the file to disk
                        String uploadNuclemdFile_stripped = NUCLEMD_Repository + "/" + timeStamp + "_"
                                + username + "_" + item.getName() + "_stripped";

                        NUCLEMD_Parameters[2] = RemoveCarriageReturn(uploadNuclemdFile,
                                uploadNuclemdFile_stripped);
                    }

                    if (fieldName.equals("nuclemd_fileconf_1")) {
                        log.info("\n- Uploading the input file: " + "\n[ " + item.getName() + " ]" + "\n[ "
                                + item.getContentType() + " ]" + "\n[ " + item.getSize() + "KBytes ]");

                        // Writing the file to disk
                        String uploadNuclemdFile = NUCLEMD_Repository + "/" + timeStamp + "_" + username + "_"
                                + item.getName();

                        log.info("\n- Writing the file: [ " + uploadNuclemdFile.toString() + " ] to disk");

                        item.write(new File(uploadNuclemdFile));

                        // Writing the file to disk
                        String uploadNuclemdFile_stripped = NUCLEMD_Repository + "/" + timeStamp + "_"
                                + username + "_" + item.getName() + "_stripped";

                        NUCLEMD_Parameters[3] = RemoveCarriageReturn(uploadNuclemdFile,
                                uploadNuclemdFile_stripped);
                    }

                    if (fieldName.equals("nuclemd_fileconf_2")) {
                        log.info("\n- Uploading the input file: " + "\n[ " + item.getName() + " ]" + "\n[ "
                                + item.getContentType() + " ]" + "\n[ " + item.getSize() + "KBytes ]");

                        // Writing the file to disk
                        String uploadNuclemdFile = NUCLEMD_Repository + "/" + timeStamp + "_" + username + "_"
                                + item.getName();

                        log.info("\n- Writing the file: [ " + uploadNuclemdFile.toString() + " ] to disk");

                        item.write(new File(uploadNuclemdFile));

                        // Writing the file to disk
                        String uploadNuclemdFile_stripped = NUCLEMD_Repository + "/" + timeStamp + "_"
                                + username + "_" + item.getName() + "_stripped";

                        NUCLEMD_Parameters[4] = RemoveCarriageReturn(uploadNuclemdFile,
                                uploadNuclemdFile_stripped);
                    }
                }

                if (fieldName.equals("EnableNotification"))
                    NUCLEMD_Parameters[5] = item.getString();

                if (fieldName.equals("nuclemd_maxwallclocktime"))
                    NUCLEMD_Parameters[6] = item.getString();

                if (fieldName.equals("EnableDemo"))
                    NUCLEMD_Parameters[7] = item.getString();

            } // end while
        } catch (FileUploadException ex) {
            Logger.getLogger(Nuclemd.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(Nuclemd.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return NUCLEMD_Parameters;
}

From source file:it.infn.ct.wrf.Wrf.java

public String[] uploadSettings(ActionRequest actionRequest, ActionResponse actionResponse, String username) {
    String[] _Parameters = new String[7];
    boolean status;

    // Check that we have a file upload request
    boolean isMultipart = PortletFileUpload.isMultipartContent(actionRequest);

    if (isMultipart) {
        // Create a factory for disk-based file items.
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Set factory constrains
        File _Repository = new File("/tmp");
        if (!_Repository.exists())
            status = _Repository.mkdirs();
        factory.setRepository(_Repository);

        // Create a new file upload handler.
        PortletFileUpload upload = new PortletFileUpload(factory);

        try {//  w w  w .  j ava  2s . co m
            // Parse the request
            List items = upload.parseRequest(actionRequest);

            // Processing items
            Iterator iter = items.iterator();

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

                String fieldName = item.getFieldName();

                DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                String timeStamp = dateFormat.format(Calendar.getInstance().getTime());

                // Processing a regular form field
                if (item.isFormField()) {
                    if (fieldName.equals("wrf_textarea_OCTAVE")) {
                        _Parameters[0] = _Repository + "/" + timeStamp + "_" + username + ".m";

                        // Store the textarea in a ASCII file
                        storeString(_Parameters[0], item.getString());
                    }

                    if (fieldName.equals("wrf_textarea_R")) {
                        _Parameters[0] = _Repository + "/" + timeStamp + "_" + username + ".r";

                        // Store the textarea in a ASCII file
                        storeString(_Parameters[0], item.getString());
                    }

                    if (fieldName.equals("wrftype"))
                        _Parameters[1] = item.getString();

                    if (fieldName.equals("wrf_CR"))
                        _Parameters[2] = item.getString();

                    if (fieldName.equals("wrfvmtemplate"))
                        _Parameters[5] = item.getString();

                    if (fieldName.equals("wrf_vmname"))
                        _Parameters[6] = item.getString();

                } else {
                    // Processing a file upload
                    if (fieldName.equals("wrf_file_OCTAVE") || fieldName.equals("wrf_file_R")) {
                        log.info("\n- Uploading the following user's file: " + "\n[ " + item.getName() + " ]"
                                + "\n[ " + item.getContentType() + " ]" + "\n[ " + item.getSize() + "KBytes ]");

                        // Writing the file to disk
                        String uploadFile = _Repository + "/" + timeStamp + "_" + username + "_"
                                + item.getName();

                        log.info("\n- Writing the user's file: [ " + uploadFile.toString() + " ] to disk");

                        item.write(new File(uploadFile));

                        _Parameters[0] = uploadFile;
                    }
                }

                if (fieldName.equals("EnableNotification"))
                    _Parameters[3] = item.getString();

                if (fieldName.equals("wrf_desc"))
                    if (item.getString().equals("Please, insert here a description for your run"))
                        _Parameters[4] = "Cloud Simulation Started";
                    else
                        _Parameters[4] = item.getString();

            } // end while
        } catch (FileUploadException ex) {
            Logger.getLogger(Wrf.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(Wrf.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return _Parameters;
}

From source file:org.alfresco.web.app.portlet.AlfrescoFacesPortlet.java

/**
 * Called by the portlet container to allow the portlet to process an action request.
 *///from  w w w. j  av  a  2s.c  o  m
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
    Application.setInPortalServer(true);
    try {
        // Set the current locale
        I18NUtil.setLocale(getLanguage(request.getPortletSession()));

        boolean isMultipart = PortletFileUpload.isMultipartContent(request);

        // NOTE: Due to filters not being called within portlets we can not make use
        //       of the MyFaces file upload support, therefore we are using a pure
        //       portlet request/action to handle file uploads until there is a 
        //       solution.

        if (isMultipart) {
            if (logger.isDebugEnabled())
                logger.debug("Handling multipart request...");

            PortletSession session = request.getPortletSession();

            // get the file from the request and put it in the session
            DiskFileItemFactory factory = new DiskFileItemFactory();
            PortletFileUpload upload = new PortletFileUpload(factory);
            List<FileItem> fileItems = upload.parseRequest(request);
            Iterator<FileItem> iter = fileItems.iterator();
            FileUploadBean bean = new FileUploadBean();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                String filename = item.getName();
                if (item.isFormField() == false) {
                    if (logger.isDebugEnabled())
                        logger.debug("Processing uploaded file: " + filename);

                    // workaround a bug in IE where the full path is returned
                    // IE is only available for Windows so only check for the Windows path separator
                    int idx = filename.lastIndexOf('\\');

                    if (idx == -1) {
                        // if there is no windows path separator check for *nix
                        idx = filename.lastIndexOf('/');
                    }

                    if (idx != -1) {
                        filename = filename.substring(idx + File.separator.length());
                    }

                    File tempFile = TempFileProvider.createTempFile("alfresco", ".upload");
                    item.write(tempFile);
                    bean.setFile(tempFile);
                    bean.setFileName(filename);
                    bean.setFilePath(tempFile.getAbsolutePath());
                    session.setAttribute(FileUploadBean.FILE_UPLOAD_BEAN_NAME, bean,
                            PortletSession.PORTLET_SCOPE);
                }
            }

            // Set the VIEW_ID parameter to tell the faces portlet bridge to treat the request
            // as a JSF request, this will send us back to the previous page we came from.
            String lastViewId = (String) request.getPortletSession().getAttribute(SESSION_LAST_VIEW_ID);
            if (lastViewId != null) {
                response.setRenderParameter(VIEW_ID, lastViewId);
            }
        } else {
            SessionUser sessionUser = (SessionUser) request.getPortletSession()
                    .getAttribute(AuthenticationHelper.AUTHENTICATION_USER, PortletSession.APPLICATION_SCOPE);
            User user = sessionUser instanceof User ? (User) sessionUser : null;
            if (user != null) {
                // setup the authentication context
                try {
                    WebApplicationContext ctx = (WebApplicationContext) getPortletContext()
                            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
                    AuthenticationService auth = (AuthenticationService) ctx.getBean("AuthenticationService");
                    auth.validate(user.getTicket());

                    // save last username into portlet preferences, get from LoginBean state
                    LoginBean loginBean = (LoginBean) request.getPortletSession()
                            .getAttribute(AuthenticationHelper.LOGIN_BEAN);
                    if (loginBean != null) {
                        // TODO: Need to login to the Portal to get a user here to store prefs against
                        //       so not really a suitable solution as they get thrown away at present!
                        //       Also would need to store prefs PER user - so auto login for each...?
                        String oldValue = request.getPreferences().getValue(PREF_ALF_USERNAME, null);
                        if (oldValue == null || oldValue.equals(loginBean.getUsernameInternal()) == false) {
                            if (request.getPreferences().isReadOnly(PREF_ALF_USERNAME) == false) {
                                request.getPreferences().setValue(PREF_ALF_USERNAME,
                                        loginBean.getUsernameInternal());
                                request.getPreferences().store();
                            }
                        }
                    }

                    // do the normal JSF processing
                    super.processAction(request, response);
                } catch (AuthenticationException authErr) {
                    // remove User object as it's now useless
                    request.getPortletSession().removeAttribute(AuthenticationHelper.AUTHENTICATION_USER,
                            PortletSession.APPLICATION_SCOPE);
                }
            } else {
                // do the normal JSF processing as we may be on the login page
                super.processAction(request, response);
            }
        }
    } catch (Throwable e) {
        if (getErrorPage() != null) {
            handleError(request, response, e);
        } else {
            logger.warn("No error page configured, re-throwing exception");

            if (e instanceof PortletException) {
                throw (PortletException) e;
            } else if (e instanceof IOException) {
                throw (IOException) e;
            } else {
                throw new PortletException(e);
            }
        }
    } finally {
        Application.setInPortalServer(false);
    }
}

From source file:org.apache.geronimo.console.bundlemanager.BundleManagerPortlet.java

/******************************
 * Install Action/* w  ww. j a  va 2s.c om*/
 ******************************/
private void processInstallAction(ActionRequest request, BundleContext bundleContext,
        StartLevel startLevelService) throws PortletException, IOException {
    if (!PortletFileUpload.isMultipartContent(request)) {
        throw new PortletException("Expected file upload");
    }

    // use commons-fileupload to process the request
    File rootDir = new File(System.getProperty("java.io.tmpdir"));
    PortletFileUpload uploader = new PortletFileUpload(new DiskFileItemFactory(10240, rootDir));

    File bundleFile = null;
    String startAfterInstalled = null;
    String str_startLevel = null;

    List<?> items;
    try {
        items = uploader.parseRequest(request);
    } catch (FileUploadException e) {
        addErrorMessage(request, getLocalizedString(request, "consolebase.bundlemanager.err.file.uploadError"));
        logger.error("FileUploadException", e);
        return;
    }

    // deal with the multipart form data items;
    for (Iterator<?> i = items.iterator(); i.hasNext();) {
        FileItem item = (FileItem) i.next();
        if (!item.isFormField()) {
            String fieldName = item.getFieldName();
            String fileName = item.getName().trim();
            if (fileName.length() != 0) {
                int index = fileName.lastIndexOf('\\');
                if (index != -1) {
                    fileName = fileName.substring(index + 1);
                }
                if ("bundleFile".equals(fieldName)) {
                    bundleFile = new File(rootDir, fileName);
                }
            }
            if (bundleFile != null) {
                try {
                    item.write(bundleFile);
                } catch (Exception e) {
                    addErrorMessage(request,
                            getLocalizedString(request, "consolebase.bundlemanager.err.file.writeError"));
                    logger.error("Exception", e);
                    return;
                }
            } else {
                //should never happen
                addErrorMessage(request,
                        getLocalizedString(request, "consolebase.bundlemanager.err.file.nullError"));
                logger.error("The uploaded file is null!");
                return;
            }
        } else {
            if ("startAfterInstalled".equalsIgnoreCase(item.getFieldName())) {
                startAfterInstalled = item.getString();
            } else if ("startLevel".equalsIgnoreCase(item.getFieldName())) {
                str_startLevel = item.getString();
            }
        }
    }

    // install the uploaded bundle file
    String url = "file:///" + bundleFile.getCanonicalPath();

    Bundle installedBundle;
    try {
        installedBundle = bundleContext.installBundle(url);
        addInfoMessage(request, getLocalizedString(request, "consolebase.bundlemanager.info.install",
                installedBundle.getSymbolicName(), installedBundle.getBundleId()));
    } catch (BundleException e) {
        addErrorMessage(request,
                getLocalizedString(request, "consolebase.bundlemanager.err.actionError") + "install",
                e.getMessage());
        logger.error("BundleException", e);
        return;
    }

    // set start level for the installed bundle
    int startLevel = -1;
    try {
        startLevel = Integer.parseInt(str_startLevel);
    } catch (NumberFormatException e) {
        // if can't generated, use the default initialBundleStartLevel
    }
    int defaultStartLevel = startLevelService.getInitialBundleStartLevel();
    if (startLevel != defaultStartLevel && startLevel >= 0) {
        startLevelService.setBundleStartLevel(installedBundle, startLevel);
    }

    // if check box "Start" checked, then start the bundle
    if ("yes".equals(startAfterInstalled)) {
        try {
            installedBundle.start();
            addInfoMessage(request, getLocalizedString(request, "consolebase.bundlemanager.info.start",
                    installedBundle.getSymbolicName(), installedBundle.getBundleId()));
        } catch (BundleException e) {
            addErrorMessage(request,
                    getLocalizedString(request, "consolebase.bundlemanager.err.actionError") + "start",
                    e.getMessage());
            logger.error("BundleException", e);
            return;
        }

    }
}

From source file:org.apache.geronimo.console.configmanager.DeploymentPortlet.java

public void processAction(ActionRequest actionRequest, ActionResponse actionResponse)
        throws PortletException, IOException {
    if (!PortletFileUpload.isMultipartContent(actionRequest)) {
        throw new PortletException("Expected file upload");
    }/*from  w  ww . j  a v  a  2  s .  c o m*/

    File rootDir = new File(System.getProperty("java.io.tmpdir"));
    PortletFileUpload uploader = new PortletFileUpload(new DiskFileItemFactory(10240, rootDir));
    File moduleFile = null;
    File planFile = null;
    String startApp = null;
    String redeploy = null;
    try {
        List items = uploader.parseRequest(actionRequest);
        for (Iterator i = items.iterator(); i.hasNext();) {
            FileItem item = (FileItem) i.next();
            if (!item.isFormField()) {
                String fieldName = item.getFieldName();
                String name = item.getName().trim();
                File file;
                if (name.length() == 0) {
                    file = null;
                } else {
                    // Firefox sends basename, IE sends full path
                    int index = name.lastIndexOf('\\');
                    if (index != -1) {
                        name = name.substring(index + 1);
                    }
                    file = new File(rootDir, name);
                }
                if ("module".equals(fieldName)) {
                    moduleFile = file;
                } else if ("plan".equals(fieldName)) {
                    planFile = file;
                }
                if (file != null) {
                    try {
                        item.write(file);
                    } catch (Exception e) {
                        throw new PortletException(e);
                    }
                }
            } else {
                // retrieve 'startApp' form field value
                if ("startApp".equalsIgnoreCase(item.getFieldName())) {
                    startApp = item.getString();
                } else if ("redeploy".equalsIgnoreCase(item.getFieldName())) {
                    redeploy = item.getString();
                }
            }
        }
    } catch (FileUploadException e) {
        throw new PortletException(e);
    }
    DeploymentFactoryManager dfm = DeploymentFactoryManager.getInstance();
    FileInputStream fis = null;
    try {
        DeploymentManager mgr = dfm.getDeploymentManager("deployer:geronimo:inVM", null, null);
        try {
            boolean isRedeploy = redeploy != null && !redeploy.equals("");
            if (mgr instanceof JMXDeploymentManager) {
                ((JMXDeploymentManager) mgr).setLogConfiguration(false, true);
            }
            Target[] all = mgr.getTargets();
            if (null == all) {
                throw new IllegalStateException("No target to distribute to");
            }

            ProgressObject progress;
            if (isRedeploy) {
                TargetModuleID[] targets = identifyTargets(moduleFile, planFile,
                        mgr.getAvailableModules(null, all));
                if (targets.length == 0) {
                    addErrorMessage(actionRequest, getLocalizedString(actionRequest, "plugin.errorMsg04"),
                            null);
                    log.error(getLocalizedString(actionRequest, "plugin.errorMsg04"));
                    return;
                }
                progress = mgr.redeploy(targets, moduleFile, planFile);
            } else {
                progress = mgr.distribute(new Target[] { all[0] }, moduleFile, planFile);
            }
            while (progress.getDeploymentStatus().isRunning()) {
                Thread.sleep(100);
            }

            String abbrStatusMessage;
            String fullStatusMessage = null;
            if (progress.getDeploymentStatus().isCompleted()) {
                abbrStatusMessage = getLocalizedString(actionRequest,
                        !isRedeploy ? "plugin.infoMsg01" : "plugin.infoMsg02");
                addInfoMessage(actionRequest, abbrStatusMessage);
                // start installed app/s
                if (!isRedeploy && startApp != null && !startApp.equals("")) {
                    progress = mgr.start(progress.getResultTargetModuleIDs());
                    while (progress.getDeploymentStatus().isRunning()) {
                        Thread.sleep(100);
                    }
                    if (progress.getDeploymentStatus().isCompleted()) {
                        abbrStatusMessage = getLocalizedString(actionRequest, "plugin.infoMsg03");
                        addInfoMessage(actionRequest, abbrStatusMessage);
                    } else {
                        abbrStatusMessage = getLocalizedString(actionRequest, "plugin.errorMsg02");
                        fullStatusMessage = progress.getDeploymentStatus().getMessage();
                        addErrorMessage(actionRequest, abbrStatusMessage, fullStatusMessage);
                        log.error(abbrStatusMessage + "\n" + fullStatusMessage);
                    }
                }
            } else {
                fullStatusMessage = progress.getDeploymentStatus().getMessage();
                // for the abbreviated status message clip off everything
                // after the first line, which in most cases means the gnarly stacktrace
                abbrStatusMessage = getLocalizedString(actionRequest, "plugin.errorMsg01");
                addErrorMessage(actionRequest, abbrStatusMessage, fullStatusMessage);
                log.error(abbrStatusMessage + "\n" + fullStatusMessage);
            }
        } finally {
            mgr.release();
            if (fis != null)
                fis.close();
            if (moduleFile != null && moduleFile.exists()) {
                if (!moduleFile.delete()) {
                    log.debug("Unable to delete temporary file " + moduleFile);
                    moduleFile.deleteOnExit();
                }
            }
            if (planFile != null && planFile.exists()) {
                if (!planFile.delete()) {
                    log.debug("Unable to delete temporary file " + planFile);
                    planFile.deleteOnExit();
                }
            }
        }
    } catch (Exception e) {
        throw new PortletException(e);
    }
}