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:org.sakaiproject.tool.syllabus.SyllabusTool.java

public String processUpload(ValueChangeEvent event) {
    if (attachCaneled == false) {
        UIComponent component = event.getComponent();
        Object newValue = event.getNewValue();
        Object oldValue = event.getOldValue();
        PhaseId phaseId = event.getPhaseId();
        Object source = event.getSource();

        if (newValue instanceof String)
            return "";
        if (newValue == null)
            return "";

        try {/*from   w  w w  . j  a  v  a  2s  .  c o  m*/
            FileItem item = (FileItem) event.getNewValue();
            String fileName = item.getName();
            byte[] fileContents = item.get();

            ResourcePropertiesEdit props = contentHostingService.newResourceProperties();

            String tempS = fileName;
            //logger.info(tempS);
            int lastSlash = tempS.lastIndexOf("/") > tempS.lastIndexOf("\\") ? tempS.lastIndexOf("/")
                    : tempS.lastIndexOf("\\");
            if (lastSlash > 0)
                fileName = tempS.substring(lastSlash + 1);

            ContentResource thisAttach = contentHostingService.addAttachmentResource(fileName,
                    item.getContentType(), fileContents, props);

            SyllabusAttachment attachObj = syllabusManager.createSyllabusAttachmentObject(thisAttach.getId(),
                    fileName);
            ////////revise        syllabusManager.addSyllabusAttachToSyllabusData(getEntry().getEntry(), attachObj);
            attachments.add(attachObj);

            String ss = thisAttach.getUrl();
            String fileWithWholePath = thisAttach.getUrl();

            String s = ss;

            if (entry.justCreated != true) {
                allAttachments.add(attachObj);
            }
        } catch (Exception e) {
            logger.error(this + ".processUpload() in SyllabusTool " + e);
            e.printStackTrace();
        }
        if (entry.justCreated == true) {
            return "edit";
        } else {
            return "read";
        }
    }
    return null;
}

From source file:org.sakaiproject.util.ParameterParser.java

/**
 * Get a FileItem parameter by name.// ww w .j  a  v  a 2  s.  c  o m
 * 
 * @param name
 *        The parameter name.
 * @return The parameter FileItem value, or null if it's not defined.
 */
public FileItem getFileItem(String name) {
    // wrap the Apache FileItem in our own homegrown FileItem
    Object o = m_req.getAttribute(name);
    if (o != null && o instanceof org.apache.commons.fileupload.FileItem) {
        org.apache.commons.fileupload.FileItem item = (org.apache.commons.fileupload.FileItem) o;
        try {
            return new FileItem(Normalizer.normalize(item.getName(), Normalizer.Form.NFC),
                    item.getContentType(), item.getInputStream());
        } catch (IOException e) {
            return new FileItem(Normalizer.normalize(item.getName(), Normalizer.Form.NFC),
                    item.getContentType(), item.get());
        }
    }

    return null;
}

From source file:org.sakaiproject.yaft.tool.YaftTool.java

private List<Attachment> getAttachments(HttpServletRequest request) {
    List<FileItem> fileItems = new ArrayList<FileItem>();

    String uploadsDone = (String) request.getAttribute(RequestFilter.ATTR_UPLOADS_DONE);

    if (uploadsDone != null && uploadsDone.equals(RequestFilter.ATTR_UPLOADS_DONE)) {
        logger.debug("UPLOAD STATUS: " + request.getAttribute("upload.status"));

        try {//from   www . j  a  va 2  s  .co m
            FileItem attachment1 = (FileItem) request.getAttribute("attachment_0");
            if (attachment1 != null && attachment1.getSize() > 0)
                fileItems.add(attachment1);
            FileItem attachment2 = (FileItem) request.getAttribute("attachment_1");
            if (attachment2 != null && attachment2.getSize() > 0)
                fileItems.add(attachment2);
            FileItem attachment3 = (FileItem) request.getAttribute("attachment_2");
            if (attachment3 != null && attachment3.getSize() > 0)
                fileItems.add(attachment3);
            FileItem attachment4 = (FileItem) request.getAttribute("attachment_3");
            if (attachment4 != null && attachment4.getSize() > 0)
                fileItems.add(attachment4);
            FileItem attachment5 = (FileItem) request.getAttribute("attachment_4");
            if (attachment5 != null && attachment5.getSize() > 0)
                fileItems.add(attachment5);
        } catch (Exception e) {

        }
    }

    List<Attachment> attachments = new ArrayList<Attachment>();
    if (fileItems.size() > 0) {
        for (Iterator i = fileItems.iterator(); i.hasNext();) {
            FileItem fileItem = (FileItem) i.next();

            String name = fileItem.getName();

            if (name.contains("/"))
                name = name.substring(name.lastIndexOf("/") + 1);
            else if (name.contains("\\"))
                name = name.substring(name.lastIndexOf("\\") + 1);

            attachments.add(new Attachment(name, fileItem.getContentType(), fileItem.get()));
        }
    }

    return attachments;
}

From source file:org.sc.probro.servlets.IndexCreatorServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from   www  .j a va  2s.com
        OBOParser parser = null;
        Map<String, String[]> params = decodedParams(request);

        UserCredentials creds = new UserCredentials();

        String ontologyName = null;

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {
            throw new BrokerException(HttpServletResponse.SC_BAD_REQUEST, "No multipart form data.");
        }

        try {
            File repository = new File(System.getProperty("java.io.tmpdir"));

            // Create a factory for disk-based file items
            //DiskFileItemFactory factory = new DiskFileItemFactory();
            DiskFileItemFactory factory = newDiskFileItemFactory(getServletContext(), repository);

            // Set factory constraints
            factory.setSizeThreshold(10 * MB);
            //factory.setRepository(yourTempDirectory);

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setSizeMax(50 * MB);

            // Parse the request
            List<FileItem> items = upload.parseRequest(request);

            for (FileItem item : items) {
                if (item.isFormField()) {
                    String formName = item.getFieldName();
                    String formValue = item.getString();
                    Log.info(String.format("%s=%s", formName, formValue));

                    if (formName.equals("ontology_name")) {
                        ontologyName = formValue;
                    }

                } else {
                    String formName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();

                    if (formName.equals("ontology_file")) {

                        Log.info(String.format("fileName=%s, contentType=%s, size=%d", fileName, contentType,
                                sizeInBytes));

                        if (fileName.length() > 0) {

                            InputStream uploadedStream = item.getInputStream();
                            BufferedReader reader = new BufferedReader(new InputStreamReader(uploadedStream));

                            parser = new OBOParser();
                            parser.parse(reader);

                            reader.close();
                        }

                    } else {
                        Log.warn(String.format("unknown file: %s", formName));
                    }

                }
            }
        } catch (IOException e) {
            throw new BrokerException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        } catch (FileUploadException e) {
            throw new BrokerException(e);
        }

        if (ontologyName == null) {
            throw new BadRequestException("No ontology_name field given.");
        }

        OBOOntology ontology = null;

        try {
            if (parser != null) {
                Log.info(String.format("Retrieving OBO ontology from file."));
                // file was uploaded
                ontology = parser.getOntology();
            } else {
                // try to get it from teh sparql endpoint
                Log.info(String.format("No OBO file uploaded, reading from Sparql endpoint instead."));

                OBOBuilder builder = new OBOBuilder(oboSparql);
                ontology = builder.buildOntology(ontologyName);
            }
        } catch (IOException e) {
            throw new BrokerException(e);
        }

        Broker broker = getBroker();
        try {
            Ontology ont = broker.createOntology(creds, ontologyName, ontology);

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("text");
            response.getWriter().print(ont.id);

        } finally {
            broker.close();
        }

    } catch (BrokerException e) {
        handleException(response, e);
        return;
    }
}

From source file:org.seasr.meandre.components.tools.text.io.InputData.java

@SuppressWarnings("unchecked")
@Override//from w w w  .j  a v a  2s . c  om
public void handle(HttpServletRequest request, HttpServletResponse response) throws WebUIException {
    console.entering(getClass().getName(), "handle", response);

    console.finer("Request method:\t" + request.getMethod());
    console.finer("Request content-type:\t" + request.getContentType());
    console.finer("Request path:\t" + request.getPathInfo());
    console.finer("Request query string:\t" + request.getQueryString());

    response.setStatus(HttpServletResponse.SC_OK);

    String action = request.getParameter("action");
    console.fine("Action: " + action);

    if (action != null) {
        StreamInitiator si = new StreamInitiator(streamId);
        StreamTerminator st = new StreamTerminator(streamId);

        if (action.equals("urls")) {
            SortedMap<String, URL> urls = new TreeMap<String, URL>();
            Enumeration<String> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = paramNames.nextElement();
                if (paramName.startsWith("url_")) {
                    String sUrl = request.getParameter(paramName);
                    console.fine(paramName + ": " + sUrl);
                    try {
                        urls.put(paramName, new URL(sUrl));
                    } catch (MalformedURLException e) {
                        console.warning(sUrl + " is not a valid URL, ignoring it.");
                        continue;
                    }
                }
            }

            if (urls.size() == 0)
                throw new WebUIException("No URLs provided");

            try {
                if (_wrapAsStream) {
                    componentContext.pushDataComponentToOutput(OUT_LABEL, si);
                    componentContext.pushDataComponentToOutput(OUT_DATA, si);
                }

                for (URL url : urls.values()) {
                    componentContext.pushDataComponentToOutput(OUT_LABEL,
                            BasicDataTypesTools.stringToStrings(url.toString()));
                    componentContext.pushDataComponentToOutput(OUT_DATA, url);
                }

                if (_wrapAsStream) {
                    componentContext.pushDataComponentToOutput(OUT_LABEL, st);
                    componentContext.pushDataComponentToOutput(OUT_DATA, st);
                }
            } catch (ComponentContextException e) {
                throw new WebUIException(e);
            }
        }

        else

        if (action.equals("text")) {
            String text = request.getParameter("text");
            if (text == null || text.length() == 0)
                throw new WebUIException("No text provided");

            try {
                if (_wrapAsStream) {
                    componentContext.pushDataComponentToOutput(OUT_LABEL, si);
                    componentContext.pushDataComponentToOutput(OUT_DATA, si);
                }

                componentContext.pushDataComponentToOutput(OUT_LABEL,
                        BasicDataTypesTools.stringToStrings("text_input"));
                componentContext.pushDataComponentToOutput(OUT_DATA, text);

                if (_wrapAsStream) {
                    componentContext.pushDataComponentToOutput(OUT_LABEL, st);
                    componentContext.pushDataComponentToOutput(OUT_DATA, st);
                }
            } catch (ComponentContextException e) {
                throw new WebUIException(e);
            }
        }

        else

        if (action.equals("upload")) {
            if (!ServletFileUpload.isMultipartContent(request))
                throw new WebUIException("File upload request needs to be done using a multipart content type");

            ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List<FileItem> uploadedFiles;
            try {
                uploadedFiles = fileUpload.parseRequest(request);
            } catch (FileUploadException e) {
                throw new WebUIException(e);
            }

            try {
                if (_wrapAsStream) {
                    componentContext.pushDataComponentToOutput(OUT_LABEL, si);
                    componentContext.pushDataComponentToOutput(OUT_DATA, si);
                }

                for (FileItem file : uploadedFiles) {
                    if (file == null || !file.getFieldName().startsWith("file_"))
                        continue;

                    console.fine("isFormField:\t" + file.isFormField());
                    console.fine("fieldName:\t" + file.getFieldName());
                    console.fine("name:\t" + file.getName());
                    console.fine("contentType:\t" + file.getContentType());
                    console.fine("size:\t" + file.getSize());

                    if (file.isFormField())
                        continue;

                    Strings label = BasicDataTypesTools.stringToStrings(file.getName());
                    Bytes data = BasicDataTypesTools.byteArrayToBytes(file.get());

                    componentContext.pushDataComponentToOutput(OUT_LABEL, label);
                    componentContext.pushDataComponentToOutput(OUT_DATA, data);
                }

                if (_wrapAsStream) {
                    componentContext.pushDataComponentToOutput(OUT_LABEL, st);
                    componentContext.pushDataComponentToOutput(OUT_DATA, st);
                }
            } catch (ComponentContextException e) {
                throw new WebUIException(e);
            }
        }

        else
            throw new WebUIException("Unknown action: " + action);

        _done = true;
        try {
            response.getWriter().println(
                    "<html><head><meta http-equiv='REFRESH' content='1;url=/'></head><body></body></html>");
        } catch (IOException e) {
            throw new WebUIException(e);
        }
    } else
        emptyRequest(response);

    console.exiting(getClass().getName(), "handle");
}

From source file:org.silverpeas.components.kmelia.servlets.KmeliaRequestRouter.java

/**
 * Process Form Upload for publications import
 * @param kmeliaScc/*from  w  w w .j  av  a  2  s  .c om*/
 * @param request
 * @param routeDestination
 * @return destination
 */
private String processFormUpload(KmeliaSessionController kmeliaScc, HttpRequest request,
        String routeDestination, boolean isMassiveMode) {
    String destination = "";
    String topicId = "";
    String importMode;
    boolean draftMode = false;
    String logicalName;
    String message;
    boolean error = false;

    String tempFolderName;
    String tempFolderPath = null;

    String fileType;
    long fileSize;
    long processStart = new Date().getTime();
    LocalizationBundle attachmentResourceLocator = ResourceLocator.getLocalizationBundle(
            "org.silverpeas.util.attachment.multilang.attachment", kmeliaScc.getLanguage());
    FileItem fileItem;
    int versionType = DocumentVersion.TYPE_DEFAULT_VERSION;

    try {
        List<FileItem> items = request.getFileItems();
        topicId = FileUploadUtil.getParameter(items, "topicId");
        importMode = FileUploadUtil.getParameter(items, "opt_importmode");

        String sVersionType = FileUploadUtil.getParameter(items, "opt_versiontype");
        if (StringUtil.isDefined(sVersionType)) {
            versionType = Integer.parseInt(sVersionType);
        }

        String sDraftMode = FileUploadUtil.getParameter(items, "chk_draft");
        if (StringUtil.isDefined(sDraftMode)) {
            draftMode = StringUtil.getBooleanValue(sDraftMode);
        }

        fileItem = FileUploadUtil.getFile(items, "file_name");

        if (fileItem != null) {
            logicalName = fileItem.getName();
            if (logicalName != null) {
                boolean runOnUnix = !FileUtil.isWindows();
                if (runOnUnix) {
                    logicalName = logicalName.replace('\\', File.separatorChar);
                }

                logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1,
                        logicalName.length());

                // Name of temp folder: timestamp and userId
                tempFolderName = Long.toString(System.currentTimeMillis()) + "_" + kmeliaScc.getUserId();

                // Mime type of the file
                fileType = fileItem.getContentType();

                // Zip contentType not detected under Firefox !
                if (!ClientBrowserUtil.isInternetExplorer(request)) {
                    fileType = MimeTypes.ARCHIVE_MIME_TYPE;
                }

                fileSize = fileItem.getSize();

                // Directory Temp for the uploaded file
                tempFolderPath = FileRepositoryManager.getAbsolutePath(kmeliaScc.getComponentId())
                        + ResourceLocator.getGeneralSettingBundle().getString("RepositoryTypeTemp")
                        + File.separator + tempFolderName;
                if (!new File(tempFolderPath).exists()) {
                    FileRepositoryManager.createAbsolutePath(kmeliaScc.getComponentId(),
                            ResourceLocator.getGeneralSettingBundle().getString("RepositoryTypeTemp")
                                    + File.separator + tempFolderName);
                }

                // Creation of the file in the temp folder
                File fileUploaded = new File(FileRepositoryManager.getAbsolutePath(kmeliaScc.getComponentId())
                        + ResourceLocator.getGeneralSettingBundle().getString("RepositoryTypeTemp")
                        + File.separator + tempFolderName + File.separator + logicalName);
                fileItem.write(fileUploaded);

                // Is a real file ?
                if (fileSize <= 0L) {
                    // File access failed
                    message = attachmentResourceLocator.getString("liaisonInaccessible");
                    error = true;
                } else {
                    // Import !!
                    ImportReport importReport = kmeliaScc.importFile(fileUploaded, importMode, draftMode,
                            versionType);
                    long processDuration = new Date().getTime() - processStart;

                    // Compute nbPublication created
                    int nbPublication = kmeliaScc.getNbPublicationImported(importReport);

                    // nbFiles imported (only in unitary Import mode)
                    int nbFiles = importReport.getNbFilesProcessed();

                    // Title for popup report
                    String importModeTitle;
                    if (importMode.equals(KmeliaSessionController.UNITARY_IMPORT_MODE)) {
                        importModeTitle = kmeliaScc.getString("kmelia.ImportModeUnitaireTitre");
                    } else {
                        importModeTitle = kmeliaScc.getString("kmelia.ImportModeMassifTitre");
                    }
                    message = kmeliaScc.getErrorMessageImportation(importReport, importMode);

                    if (message != null && importMode.equals(KmeliaSessionController.UNITARY_IMPORT_MODE)) {
                        error = true;
                    }

                    request.setAttribute("NbPublication", nbPublication);
                    request.setAttribute("NbFiles", nbFiles);
                    request.setAttribute("ProcessDuration",
                            FileRepositoryManager.formatFileUploadTime(processDuration));
                    request.setAttribute("ImportMode", importMode);
                    request.setAttribute("DraftMode", draftMode);
                    request.setAttribute("Title", importModeTitle);
                    request.setAttribute("Context", URLUtil.getApplicationURL());
                    request.setAttribute("Message", message);

                    destination = routeDestination + "reportImportFiles.jsp";

                    String componentId = kmeliaScc.getComponentId();
                    if (kmeliaScc.isDefaultClassificationModifiable(topicId, componentId)) {
                        List<PublicationDetail> publicationDetails = kmeliaScc
                                .getListPublicationImported(importReport, importMode);
                        if (publicationDetails.size() > 0) {
                            request.setAttribute("PublicationsDetails", publicationDetails);
                            destination = routeDestination + "validateImportedFilesClassification.jsp";
                        }
                    }
                }

                // Delete temp folder
                FileFolderManager.deleteFolder(tempFolderPath);

            } else {
                // the field did not contain a file
                message = attachmentResourceLocator.getString("liaisonInaccessible");
                error = true;
            }
        } else {
            // the field did not contain a file
            message = attachmentResourceLocator.getString("liaisonInaccessible");
            error = true;
        }

        if (error) {
            request.setAttribute("Message", message);
            request.setAttribute("TopicId", topicId);
            destination = routeDestination + "importOneFile.jsp";
            if (isMassiveMode) {
                destination = routeDestination + "importMultiFiles.jsp";
            }
        }
    } catch (Exception e) {
        String exMessage = SilverpeasTransverseErrorUtil.performExceptionMessage(e, kmeliaScc.getLanguage());
        if (StringUtil.isNotDefined(exMessage)) {
            request.setAttribute("Message", e.getMessage());
        }
        // Other exception
        request.setAttribute("TopicId", topicId);
        destination = routeDestination + "importOneFile.jsp";
        if (isMassiveMode) {
            destination = routeDestination + "importMultiFiles.jsp";
        }

        SilverLogger.getLogger(this).error("Attachment upload failure", e);
    } finally {
        if (tempFolderPath != null) {
            FileFolderManager.deleteFolder(tempFolderPath);
        }
    }
    return destination;
}

From source file:org.silverpeas.core.web.http.RequestParameterDecoderTest.java

@BeforeEach
public void setup() throws ParseException {
    httpRequestMock = mock(HttpRequest.class);

    when(httpRequestMock.getParameter(anyString())).then(invocation -> {
        String parameterName = (String) invocation.getArguments()[0];
        if (StringUtil.isDefined(parameterName)) {
            switch (parameterName) {
            case "aString":
                return "&lt;a&gt;aStringValue&lt;/a&gt;";
            case "aStringToUnescape":
                return "&lt;a&gt;aStringValueToUnescape&lt;/a&gt;";
            case "anUri":
                return "/an/uri/";
            case "anOffsetDateTime":
                return "2009-01-02T23:54:26Z";
            case "anInteger":
                return "1";
            case "anIntegerFromAnnotation":
                return "2";
            case "aLongFromAnnotation":
                return "20";
            case "aLong":
                return "10";
            case "aBoolean":
                return "true";
            case "aBooleanFromAnnotation":
                return "false";
            case "anEnum":
                return EnumWithoutCreationAnnotation.VALUE_A.name();
            }/*from   w  w  w.  j av  a  2s  . co  m*/
        }
        return null;
    });
    when(httpRequestMock.getParameterAsRequestFile(anyString())).then(invocation -> {
        String parameterName = (String) invocation.getArguments()[0];
        if (StringUtil.isDefined(parameterName)) {
            if (parameterName.equals("aRequestFile")) {
                FileItem fileItem = mock(FileItem.class);
                when(fileItem.getName()).thenReturn("fileName");
                when(fileItem.getSize()).thenReturn(26L);
                when(fileItem.getContentType()).thenReturn(MediaType.TEXT_PLAIN);
                when(fileItem.getInputStream()).thenReturn(FileUtils.openInputStream(getImageResource()));
                return new RequestFile(fileItem);
            }
        }
        return null;
    });
    when(httpRequestMock.getParameterAsDate(anyString())).then(invocation -> {
        String parameterName = (String) invocation.getArguments()[0];
        if (StringUtil.isDefined(parameterName)) {
            if (parameterName.equals("aDate")) {
                return TODAY;
            }
        }
        return null;
    });
    when(httpRequestMock.getParameterValues(anyString())).then((Answer<String[]>) invocation -> {
        String parameterName = (String) invocation.getArguments()[0];
        if (StringUtil.isDefined(parameterName)) {
            if (parameterName.equals("strings")) {
                return new String[] { "string_1", "string_2", "string_2" };
            } else if (parameterName.equals("integers")) {
                return new String[] { "1", "2", "2" };
            }
        }
        return null;
    });
}

From source file:org.silverpeas.servlet.RequestParameterDecoderTest.java

@Before
public void setup() throws ParseException {
    httpRequestMock = mock(HttpRequest.class);
    when(httpRequestMock.getParameter(anyString())).then(new Answer<Object>() {
        @Override//  ww w  . ja v a2 s. c  o  m
        public Object answer(final InvocationOnMock invocation) throws Throwable {
            String parameterName = (String) invocation.getArguments()[0];
            if (StringUtil.isDefined(parameterName)) {
                if (parameterName.equals("aString")) {
                    return "aStringValue";
                }
            }
            return null;
        }
    });
    when(httpRequestMock.getParameterAsRequestFile(anyString())).then(new Answer<Object>() {
        @Override
        public Object answer(final InvocationOnMock invocation) throws Throwable {
            String parameterName = (String) invocation.getArguments()[0];
            if (StringUtil.isDefined(parameterName)) {
                if (parameterName.equals("aRequestFile")) {
                    FileItem fileItem = mock(FileItem.class);
                    when(fileItem.getName()).thenReturn("fileName");
                    when(fileItem.getSize()).thenReturn(26L);
                    when(fileItem.getContentType()).thenReturn(MediaType.TEXT_PLAIN);
                    when(fileItem.getInputStream()).thenReturn(FileUtils.openInputStream(getImageResource()));
                    return new RequestFile(fileItem);
                }
            }
            return null;
        }
    });
    when(httpRequestMock.getParameterAsInteger(anyString())).then(new Answer<Object>() {
        @Override
        public Object answer(final InvocationOnMock invocation) throws Throwable {
            String parameterName = (String) invocation.getArguments()[0];
            if (StringUtil.isDefined(parameterName)) {
                if (parameterName.equals("anInteger")) {
                    return 1;
                } else if (parameterName.equals("anIntegerFromAnnotation")) {
                    return 2;
                }
            }
            return null;
        }
    });
    when(httpRequestMock.getParameterAsLong(anyString())).then(new Answer<Object>() {
        @Override
        public Object answer(final InvocationOnMock invocation) throws Throwable {
            String parameterName = (String) invocation.getArguments()[0];
            if (StringUtil.isDefined(parameterName)) {
                if (parameterName.equals("aLongFromAnnotation")) {
                    return 20L;
                } else if (parameterName.equals("aLong")) {
                    return 10L;
                }
            }
            return null;
        }
    });
    when(httpRequestMock.getParameterAsBoolean(anyString())).then(new Answer<Object>() {
        @Override
        public Object answer(final InvocationOnMock invocation) throws Throwable {
            String parameterName = (String) invocation.getArguments()[0];
            if (StringUtil.isDefined(parameterName)) {
                if (parameterName.equals("aBoolean")) {
                    return true;
                } else if (parameterName.equals("aBooleanFromAnnotation")) {
                    return false;
                }
            }
            return null;
        }
    });
    when(httpRequestMock.getParameterAsDate(anyString())).then(new Answer<Object>() {
        @Override
        public Object answer(final InvocationOnMock invocation) throws Throwable {
            String parameterName = (String) invocation.getArguments()[0];
            if (StringUtil.isDefined(parameterName)) {
                if (parameterName.equals("aDate")) {
                    return TODAY;
                }
            }
            return null;
        }
    });
}

From source file:org.silverpeas.web.agenda.servlets.AgendaRequestRouter.java

private File processFormUpload(AgendaSessionController agendaSc, HttpServletRequest request) {
    String logicalName = "";
    String tempFolderName = "";
    String tempFolderPath = "";
    String fileType = "";
    long fileSize = 0;
    File fileUploaded = null;// w ww .  j ava  2s  .  com
    try {
        List<FileItem> items = HttpRequest.decorate(request).getFileItems();
        FileItem fileItem = FileUploadUtil.getFile(items, "fileCalendar");
        if (fileItem != null) {
            logicalName = fileItem.getName();
            if (logicalName != null) {
                logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1,
                        logicalName.length());

                // Name of temp folder: timestamp and userId
                tempFolderName = new Long(new Date().getTime()).toString() + "_" + agendaSc.getUserId();

                // Mime type of the file
                fileType = fileItem.getContentType();
                fileSize = fileItem.getSize();

                // Directory Temp for the uploaded file
                tempFolderPath = FileRepositoryManager.getAbsolutePath(agendaSc.getComponentId())
                        + ResourceLocator.getGeneralSettingBundle().getString("RepositoryTypeTemp")
                        + File.separator + tempFolderName;
                if (!new File(tempFolderPath).exists()) {
                    FileRepositoryManager.createAbsolutePath(agendaSc.getComponentId(),
                            ResourceLocator.getGeneralSettingBundle().getString("RepositoryTypeTemp")
                                    + File.separator + tempFolderName);
                }

                // Creation of the file in the temp folder
                fileUploaded = new File(FileRepositoryManager.getAbsolutePath(agendaSc.getComponentId())
                        + ResourceLocator.getGeneralSettingBundle().getString("RepositoryTypeTemp")
                        + File.separator + tempFolderName + File.separator + logicalName);
                fileItem.write(fileUploaded);
            }
        }
    } catch (Exception e) {
        // Other exception
        SilverTrace.warn("agenda", "AgendaRequestRouter.processFormUpload()", "root.EX_LOAD_ATTACHMENT_FAILED",
                e);
    }
    return fileUploaded;
}

From source file:org.springframework.http.converter.FormHttpMessageConverterTests.java

@Test
public void writeMultipart() throws Exception {
    MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
    parts.add("name 1", "value 1");
    parts.add("name 2", "value 2+1");
    parts.add("name 2", "value 2+2");
    parts.add("name 3", null);

    Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg");
    parts.add("logo", logo);

    // SPR-12108//w  w w.  ja va 2s.  c  o m
    Resource utf8 = new ClassPathResource("/org/springframework/http/converter/logo.jpg") {
        @Override
        public String getFilename() {
            return "Hall\u00F6le.jpg";
        }
    };
    parts.add("utf8", utf8);

    Source xml = new StreamSource(new StringReader("<root><child/></root>"));
    HttpHeaders entityHeaders = new HttpHeaders();
    entityHeaders.setContentType(MediaType.TEXT_XML);
    HttpEntity<Source> entity = new HttpEntity<>(xml, entityHeaders);
    parts.add("xml", entity);

    MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
    this.converter.write(parts, new MediaType("multipart", "form-data", StandardCharsets.UTF_8), outputMessage);

    final MediaType contentType = outputMessage.getHeaders().getContentType();
    assertNotNull("No boundary found", contentType.getParameter("boundary"));

    // see if Commons FileUpload can read what we wrote
    FileItemFactory fileItemFactory = new DiskFileItemFactory();
    FileUpload fileUpload = new FileUpload(fileItemFactory);
    RequestContext requestContext = new MockHttpOutputMessageRequestContext(outputMessage);
    List<FileItem> items = fileUpload.parseRequest(requestContext);
    assertEquals(6, items.size());
    FileItem item = items.get(0);
    assertTrue(item.isFormField());
    assertEquals("name 1", item.getFieldName());
    assertEquals("value 1", item.getString());

    item = items.get(1);
    assertTrue(item.isFormField());
    assertEquals("name 2", item.getFieldName());
    assertEquals("value 2+1", item.getString());

    item = items.get(2);
    assertTrue(item.isFormField());
    assertEquals("name 2", item.getFieldName());
    assertEquals("value 2+2", item.getString());

    item = items.get(3);
    assertFalse(item.isFormField());
    assertEquals("logo", item.getFieldName());
    assertEquals("logo.jpg", item.getName());
    assertEquals("image/jpeg", item.getContentType());
    assertEquals(logo.getFile().length(), item.getSize());

    item = items.get(4);
    assertFalse(item.isFormField());
    assertEquals("utf8", item.getFieldName());
    assertEquals("Hall\u00F6le.jpg", item.getName());
    assertEquals("image/jpeg", item.getContentType());
    assertEquals(logo.getFile().length(), item.getSize());

    item = items.get(5);
    assertEquals("xml", item.getFieldName());
    assertEquals("text/xml", item.getContentType());
    verify(outputMessage.getBody(), never()).close();
}