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.jxstar.service.studio.AttachBO.java

/**
 * //from  w  w  w  .  jav  a  2 s  .  com
 * @param dataId -- ?ID
 * @param dataFunId -- ?ID
 * @param requestContext
 * @return
 * @throws BoException
 */
private String insertRecord(String dataId, String dataFunId, RequestContext requestContext) throws BoException {
    //?ID
    String attachId = KeyCreator.getInstance().createKey("sys_attach");
    //???
    String attachName = requestContext.getRequestValue("attach_name");
    //?
    String attachField = requestContext.getRequestValue("attach_field");
    //??
    Map<String, String> mpFun = FunDefineDao.queryFun(dataFunId);
    //???
    String tableName = mpFun.get("table_name");
    //???
    String funName = mpFun.get("fun_name");
    //?
    String systemPath = SystemVar.getValue("upload.file.path", "D:/ATTACHDOC");

    //??
    FileItem item = getAttachItem(requestContext);
    if (item == null || item.isFormField()) {
        throw new BoException(JsMessage.getValue("systembo.attachbo.noupload"));
    }
    String fileName = FileUtil.getFileName(item.getName());
    if (fileName == null || fileName.length() == 0) {
        throw new BoException(JsMessage.getValue("systembo.attachbo.filenameerror"));
    }
    //?
    String attachPath = systemPath + "/" + tableName + "/";
    requestContext.setRequestValue("save_path", attachPath);
    attachPath += fileName;
    String contentType = item.getContentType();
    //??
    Map<String, String> mpUser = requestContext.getUserInfo();
    String userId = MapUtil.getValue(mpUser, "user_id");
    //?ID
    if (userId.length() == 0) {
        userId = requestContext.getRequestValue("user_id");
        if (userId.length() > 0) {
            mpUser = queryUser(userId);
        }
    }
    String userName = MapUtil.getValue(mpUser, "user_name");

    StringBuilder sbsql = new StringBuilder();
    sbsql.append("insert into sys_attach (");
    sbsql.append("attach_id, table_name, data_id, attach_name, content_type, attach_field, fun_id,");
    sbsql.append("fun_name, attach_path, upload_date, upload_user, add_userid, add_date");
    sbsql.append(") values (?, ?, ?, ?, ?, ?, ?,  ?, ?, ?, ?, ?, ?)");

    DaoParam param = _dao.createParam(sbsql.toString());
    param.addStringValue(attachId);
    param.addStringValue(tableName);
    param.addStringValue(dataId);
    param.addStringValue(attachName);
    param.addStringValue(contentType);
    param.addStringValue(attachField);
    param.addStringValue(dataFunId);

    param.addStringValue(funName);
    param.addStringValue(fileName);//??attachPath?
    param.addDateValue(DateUtil.getTodaySec());
    param.addStringValue(userName);
    param.addStringValue(userId);
    param.addDateValue(DateUtil.getTodaySec());

    if (!_dao.update(param)) {
        throw new BoException(JsMessage.getValue("systembo.attachbo.newerror"));
    }

    return attachId;
}

From source file:org.kuali.rice.edl.impl.components.NoteConfigComponent.java

public void saveNote(NoteForm form, EDLContext edlContext, Document dom) throws Exception {
    Note noteToSave = null;//from  w  ww  . ja va 2s.  c o  m
    if (form.getShowEdit() != null && form.getShowEdit().equals("yes")) {
        //LOG.debug(form.getNoteIdNumber());
        noteToSave = getNoteService().getNoteByNoteId(form.getNoteIdNumber());
        String noteText = form.getNoteText();
        if (noteText != null) {
            noteToSave.setNoteText(noteText);
        }
        //LOG.debug(noteToSave);
        //LOG.debug(noteToSave.getNoteCreateDate());
        //noteToSave.setNoteCreateDate(new Timestamp(noteToSave.getNoteCreateLongDate().longValue()));
    } else {
        noteToSave = new Note();
        noteToSave.setNoteId(null);
        noteToSave.setDocumentId(form.getDocId());
        noteToSave.setNoteCreateDate(new Timestamp((new Date()).getTime()));
        noteToSave.setNoteAuthorWorkflowId(edlContext.getUserSession().getPrincipalId());
        noteToSave.setNoteText(form.getAddText());
    }
    CustomNoteAttribute customNoteAttribute = null;
    DocumentRouteHeaderValue routeHeader = getRouteHeaderService().getRouteHeader(noteToSave.getDocumentId());
    boolean canEditNote = false;
    boolean canAddNotes = false;
    if (routeHeader != null) {
        customNoteAttribute = routeHeader.getCustomNoteAttribute();
        if (customNoteAttribute != null) {
            customNoteAttribute.setUserSession(edlContext.getUserSession());
            canAddNotes = customNoteAttribute.isAuthorizedToAddNotes();
            canEditNote = customNoteAttribute.isAuthorizedToEditNote(noteToSave);
        }
    }
    if ((form.getShowEdit() != null && form.getShowEdit().equals("yes") && canEditNote)
            || ((form.getShowEdit() == null || !form.getShowEdit().equals("yes")) && canAddNotes)) {
        FileItem uploadedFile = (FileItem) form.getFile();
        if (uploadedFile != null && org.apache.commons.lang.StringUtils.isNotBlank(uploadedFile.getName())) {
            Attachment attachment = new Attachment();
            attachment.setAttachedObject(uploadedFile.getInputStream());
            String internalFileIndicator = uploadedFile.getName();
            int indexOfSlash = internalFileIndicator.lastIndexOf("/");
            int indexOfBackSlash = internalFileIndicator.lastIndexOf("\\");
            if (indexOfSlash >= 0) {
                internalFileIndicator = internalFileIndicator.substring(indexOfSlash + 1);
            } else {
                if (indexOfBackSlash >= 0) {
                    internalFileIndicator = internalFileIndicator.substring(indexOfBackSlash + 1);
                }
            }
            attachment.setFileName(internalFileIndicator);
            LOG.debug(internalFileIndicator);
            attachment.setMimeType(uploadedFile.getContentType());
            attachment.setNote(noteToSave);
            noteToSave.getAttachments().add(attachment);
        }
        if (org.apache.commons.lang.StringUtils.isEmpty(noteToSave.getNoteText())
                && noteToSave.getAttachments().size() == 0) {
            if (form.getShowEdit() != null && form.getShowEdit().equals("yes")) {
                form.setNote(new Note());
            } else {
                form.setAddText(null);
            }
            form.setShowEdit("no");
            form.setNoteIdNumber(null);
            //              throw new Exception("Note has empty content");
            EDLXmlUtils.addGlobalErrorMessage(dom, "Note has empty content");
            return;
        }
        getNoteService().saveNote(noteToSave);

        // add ability to send emails when a note is saved. 
        boolean sendEmailOnNoteSave = false;
        // Check if edoclite specifies <param name="sendEmailOnNoteSave">
        Document edlDom = EdlServiceLocator.getEDocLiteService()
                .getDefinitionXml(edlContext.getEdocLiteAssociation());
        XPath xpath = edlContext.getXpath();
        String xpathExpression = "//config/param[@name='sendEmailOnNoteSave']";
        try {
            String match = (String) xpath.evaluate(xpathExpression, edlDom, XPathConstants.STRING);
            if (!StringUtils.isBlank(match) && match.equals("true")) {
                sendEmailOnNoteSave = true;
            }
        } catch (XPathExpressionException e) {
            throw new WorkflowRuntimeException(
                    "Unable to evaluate sendEmailOnNoteSave xpath expression in NoteConfigComponent saveNote method"
                            + xpathExpression,
                    e);
        }

        if (sendEmailOnNoteSave) {
            xpathExpression = "//data/version[@current='true']/field[@name='emailTo']/value";
            String emailTo = xpath.evaluate(xpathExpression, dom);
            if (StringUtils.isBlank(emailTo)) {
                EDLXmlUtils.addGlobalErrorMessage(dom,
                        "No email notifications were sent because EmailTo field was empty.");
                return;
            }
            // Actually send the emails.
            if (isProduction()) {
                this.to = stringToList(emailTo);
            } else {
                String testAddress = getTestAddress(edlDom);
                if (StringUtils.isBlank(testAddress)) {
                    EDLXmlUtils.addGlobalErrorMessage(dom,
                            "No email notifications were sent because testAddress edl param was empty or not specified in a non production environment");
                    return;
                }
                this.to = stringToList(getTestAddress(edlDom));
            }
            if (!isEmailListValid(this.to)) {
                EDLXmlUtils.addGlobalErrorMessage(dom,
                        "No email notifications were sent because emailTo field contains invalid email address.");
                return;
            }
            String noteEmailStylesheet = "";
            xpathExpression = "//config/param[@name='noteEmailStylesheet']";
            try {
                noteEmailStylesheet = (String) xpath.evaluate(xpathExpression, edlDom, XPathConstants.STRING);
                if (StringUtils.isBlank(noteEmailStylesheet)) {
                    EDLXmlUtils.addGlobalErrorMessage(dom,
                            "No email notifications were sent because noteEmailStylesheet edl param was empty or not specified.");
                    return;
                }
            } catch (XPathExpressionException e) {
                throw new WorkflowRuntimeException(
                        "Unable to evaluate noteEmailStylesheet xpath expression in NoteConfigComponent method"
                                + xpathExpression,
                        e);
            }
            this.styleName = noteEmailStylesheet;
            this.from = DEFAULT_EMAIL_FROM_ADDRESS;
            Document document = generateXmlInput(form, edlContext, edlDom);
            if (LOG.isDebugEnabled()) {
                LOG.debug("XML input for email tranformation:\n" + XmlJotter.jotNode(document));
            }
            Templates style = loadStyleSheet(styleName);
            EmailContent emailContent = emailStyleHelper.generateEmailContent(style, document);
            if (!this.to.isEmpty()) {
                CoreApiServiceLocator.getMailer().sendEmail(new EmailFrom(from), new EmailToList(this.to),
                        new EmailSubject(emailContent.getSubject()), new EmailBody(emailContent.getBody()),
                        new EmailCcList(this.cc), new EmailBcList(this.bc), emailContent.isHtml());
            }
        }

    }
    if (form.getShowEdit() != null && form.getShowEdit().equals("yes")) {
        form.setNote(new Note());
    } else {
        form.setAddText(null);
    }
    form.setShowEdit("no");
    form.setNoteIdNumber(null);
}

From source file:org.logomattic.portlet.LogomatticContext.java

/**
 * Saves the specified image in the repository.
 *
 * @param image the image to save/*  w ww .j a v a 2 s .c  o  m*/
 * @throws IOException any IOException
 */
public void save(FileItem image) throws IOException {
    getRoot().saveDocument(image.getName(), image.getContentType(), image.getInputStream());
    save();
}

From source file:org.logomattic.portlet.LogomatticPortlet.java

@Override
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
    LogomatticContext model = new LogomatticContext(chromattic, request, response);
    try {//from w  ww . java  2s .  co  m
        if (PortletFileUpload.isMultipartContent(request)) {
            FileItem image = null;
            try {
                FileItemFactory factory = new DiskFileItemFactory();
                PortletFileUpload fu = new PortletFileUpload(factory);
                List<FileItem> list = fu.parseRequest(request);
                for (FileItem item : list) {
                    if (item.getFieldName().equals("uploadedimage")) {
                        if (item.getContentType().startsWith("image/")) {
                            image = item;
                            break;
                        }
                    }
                }
            } catch (FileUploadException e) {
                throw new PortletException("Could not process file upload", e);
            }

            //
            if (image != null) {
                model.save(image);
            }
        } else {
            String action = request.getParameter("action");
            if ("use".equals(action)) {
                String docId = request.getParameter("docid");
                if (docId != null) {
                    PortletPreferences prefs = request.getPreferences();
                    prefs.setValue("url", docId);
                    prefs.store();
                }
            } else if ("remove".equals(action)) {
                String docId = request.getParameter("docid");
                if (docId != null) {
                    PortletPreferences prefs = request.getPreferences();
                    if (docId.equals(prefs.getValue("url", null))) {
                        prefs.reset("url");
                        prefs.store();
                    }

                    //
                    model.remove(docId);
                }
            } else if ("title".equals(action)) {
                String title = request.getParameter("title");
                if (title != null) {
                    PortletPreferences prefs = request.getPreferences();
                    prefs.setValue("title", title);
                    prefs.store();
                }
            }
        }
    } finally {
        model.close();
    }
}

From source file:org.mentawai.rule.FileRule.java

public boolean check(String field, Action action) {

    Input input = action.getInput();//from   ww w  .  ja v  a2s.c o  m

    Object value = input.getValue(field);

    if (value == null || value.toString().trim().equals("")) {

        // if we got to this point, it means that there is no RequiredRule
        // in front of this rule. Therefore this field is probably an OPTIONAL
        // field, so if it is NULL or EMPTY we don't want to do any
        // futher validation and return true to allow it.

        return true; // may be optional
    }

    if (value instanceof FileItem) {

        FileItem item = (FileItem) value;

        if (item.getContentType().matches(pattern))
            return true;

        return false;

    } else {

        throw new org.mentawai.util.RuntimeException("Bad type for file upload: " + value.getClass());
    }
}

From source file:org.mhi.imageutilities.FileHandler.java

public InputStream getFile(String file_field) throws IOException {
    InputStream blob = null;//from w  ww.j a va 2s. c  o m
    Iterator<FileItem> iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = iter.next();
        if (item.getFieldName().equals(file_field)) {
            blob = item.getInputStream();
            setContentType(item.getContentType());
            setFileSize(item.getSize());
            setFileName(item.getName());

        }
    }
    return blob;
}

From source file:org.mikha.utils.web.examples.FormsServlet.java

/**
 * Parses "file" form.//  www  . j ava2s  .  com
 * @param req request
 * @param rsp response
 * @throws ServletException if failed to forward
 * @throws IOException if failed to forward
 */
@ControllerMethodMapping(paths = "/file")
public String parseFileForm(HttpParamsRequest req, HttpServletResponse rsp)
        throws ServletException, IOException {
    String submit = req.getParameter("submit");

    if (submit != null) {
        FileItem file = req.getFile("file");
        if (!req.hasRecentErrors()) {
            rsp.setContentType(file.getContentType());
            rsp.setContentLength((int) file.getSize());
            rsp.getOutputStream().write(file.get());
            return null;
        }
    }

    return "fileform.jsp";
}

From source file:org.mikha.utils.web.examples.MultipartServlet.java

protected void doPost(HttpParamsRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    FileItem file = request.getFile("myfile");
    if (file == null) {
        throw new ServletException("File \"myfile\" is not found in uploaded data");
    }/*w  ww. j  a  v a  2s  .  c  om*/

    response.setContentType(file.getContentType());
    response.setContentLength((int) file.getSize());
    response.getOutputStream().write(file.get());
}

From source file:org.mitre.medj.WebUtils.java

public static List<ContinuityOfCareRecord> translateFiles(List<FileItem> items, String pathName) {

    try {//from  w  ww  . j  a v a 2s.  c  o m
        ArrayList<ContinuityOfCareRecord> ccrs = new ArrayList<ContinuityOfCareRecord>();
        System.out.println("WebUtils uploadFile : got items " + items);
        boolean writeToFile = true;
        System.out.println("WebUtils uploadFile : got items " + items.size());

        for (FileItem fileSetItem : items) {
            String itemName = fileSetItem.getFieldName();
            System.out.println("WebUtils: first file item  " + itemName);

            String fileName = "";
            if (!fileSetItem.isFormField()) {
                String fieldName = fileSetItem.getFieldName();
                fileName = fileSetItem.getName();

                String contentType = fileSetItem.getContentType();
                boolean isInMemory = fileSetItem.isInMemory();
                long sizeInBytes = fileSetItem.getSize();

                ContinuityOfCareRecord ccr = translate(fileSetItem.getString());
                String patientId = getPatientId(ccr);

                uploadFile(fileSetItem, pathName, fileName, patientId);
                if (ccr != null)
                    ccrs.add(ccr);

            }

        }
        return ccrs;

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
}

From source file:org.modeshape.web.BinaryContentUploadServlet.java

/**
 * Determines content-type of the uploaded file.
 * //  w ww  . j  a v a2s.  c om
 * @param items
 * @return the content type
 */
private String getContentType(List<FileItem> items) {
    for (FileItem i : items) {
        if (!i.isFormField() && i.getFieldName().equals(CONTENT_PARAMETER)) {
            return i.getContentType();
        }
    }
    return null;
}