Example usage for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent

Introduction

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

Prototype

public static final boolean isMultipartContent(HttpServletRequest request) 

Source Link

Document

Utility method that determines whether the request contains multipart content.

Usage

From source file:com.agapsys.web.toolkit.services.UploadService.java

/**
 * Process a request to receive files./* w ww  . j a va 2s  . c o m*/
 * 
 * @param req HTTP request.
 * @param resp HTTP response.
 * @param persistReceivedFiles indicates if received files should be persisted.
 * @param onFormFieldListener listener called when a form field is received.
 * @throws IllegalArgumentException if given request if not multipart/form-data.
 * @return a list of received file by given request.
 */
public List<ReceivedFile> receiveFiles(HttpServletRequest req, HttpServletResponse resp,
        boolean persistReceivedFiles, OnFormFieldListener onFormFieldListener) throws IllegalArgumentException {
    __int();

    if (persistReceivedFiles && resp == null)
        throw new IllegalArgumentException("In order to persist information, response cannot be null");

    if (!ServletFileUpload.isMultipartContent(req))
        throw new IllegalArgumentException("Request is not multipart/form-data");

    try {
        List<ReceivedFile> recvFiles = new LinkedList<>();

        List<FileItem> fileItems = uploadServlet.parseRequest(req);

        for (FileItem fi : fileItems) {
            if (fi.isFormField()) {
                if (onFormFieldListener != null)
                    onFormFieldListener.onFormField(fi.getFieldName(), fi.getString(getFieldEncoding()));
            } else {
                boolean acceptRequest = getAllowedContentTypes().equals("*");

                if (!acceptRequest) {
                    String[] acceptedContentTypes = getAllowedContentTypes().split(Pattern.quote(","));
                    for (String acceptedContentType : acceptedContentTypes) {
                        if (fi.getContentType().equals(acceptedContentType.trim())) {
                            acceptRequest = true;
                            break;
                        }
                    }
                }

                if (!acceptRequest)
                    throw new IllegalArgumentException("Unsupported content-type: " + fi.getContentType());

                File tmpFile = ((DiskFileItem) fi).getStoreLocation();
                String filename = fi.getName();
                ReceivedFile recvFile = new ReceivedFile(tmpFile, filename);
                recvFiles.add(recvFile);
            }
        }

        if (persistReceivedFiles) {
            List<ReceivedFile> sessionRecvFiles = getSessionFiles(req, resp);
            sessionRecvFiles.addAll(recvFiles);
            persistSessionFiles(req, resp, sessionRecvFiles);
        }

        return recvFiles;

    } catch (FileUploadException ex) {
        if (ex instanceof FileUploadBase.SizeLimitExceededException)
            throw new IllegalArgumentException("Size limit exceeded");
        else
            throw new RuntimeException(ex);
    } catch (UnsupportedEncodingException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.example.webapp.filter.MultipartFilter.java

/**
 * Parse the given HttpServletRequest. If the request is a multipart
 * request, then all multipart request items will be processed, else the
 * request will be returned unchanged. During the processing of all
 * multipart request items, the name and value of each regular form field
 * will be added to the parameterMap of the HttpServletRequest. The name and
 * File object of each form file field will be added as attribute of the
 * given HttpServletRequest. If a FileUploadException has occurred when the
 * file size has exceeded the maximum file size, then the
 * FileUploadException will be added as attribute value instead of the
 * FileItem object.//  www  .jav  a2 s . com
 * 
 * @param request The HttpServletRequest to be checked and parsed as
 *            multipart request.
 * @return The parsed HttpServletRequest.
 * @throws ServletException If parsing of the given HttpServletRequest
 *             fails.
 */
@SuppressWarnings("unchecked")
// ServletFileUpload#parseRequest() does not return generic type.
private HttpServletRequest parseRequest(HttpServletRequest request) throws ServletException {

    // Check if the request is actually a multipart/form-data request.
    if (!ServletFileUpload.isMultipartContent(request)) {
        // If not, then return the request unchanged.
        return request;
    }

    // Prepare the multipart request items.
    // I'd rather call the "FileItem" class "MultipartItem" instead or so.
    // What a stupid name ;)
    List<FileItem> multipartItems = null;

    try {
        // Parse the multipart request items.
        multipartItems = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        // Note: we could use ServletFileUpload#setFileSizeMax() here, but
        // that would throw a
        // FileUploadException immediately without processing the other
        // fields. So we're
        // checking the file size only if the items are already parsed. See
        // processFileField().
    } catch (FileUploadException e) {
        throw new ServletException("Cannot parse multipart request: " + e.getMessage());
    }

    // Prepare the request parameter map.
    Map<String, String[]> parameterMap = new HashMap<String, String[]>();

    // Loop through multipart request items.
    for (FileItem multipartItem : multipartItems) {
        if (multipartItem.isFormField()) {
            // Process regular form field (input
            // type="text|radio|checkbox|etc", select, etc).
            processFormField(multipartItem, parameterMap);
        } else {
            // Process form file field (input type="file").
            processFileField(multipartItem, request);
        }
    }

    // Wrap the request with the parameter map which we just created and
    // return it.
    return wrapRequest(request, parameterMap);
}

From source file:de.ingrid.portal.portlets.ContactPortlet.java

public void processAction(ActionRequest request, ActionResponse actionResponse)
        throws PortletException, IOException {
    List<FileItem> items = null;
    File uploadFile = null;//w w  w  .  j  av  a  2  s .  c o m
    boolean uploadEnable = PortalConfig.getInstance().getBoolean(PortalConfig.PORTAL_CONTACT_UPLOAD_ENABLE,
            Boolean.FALSE);
    int uploadSize = PortalConfig.getInstance().getInt(PortalConfig.PORTAL_CONTACT_UPLOAD_SIZE, 10);

    RequestContext requestContext = (RequestContext) request.getAttribute(RequestContext.REQUEST_PORTALENV);
    HttpServletRequest servletRequest = requestContext.getRequest();
    if (ServletFileUpload.isMultipartContent(servletRequest)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Set factory constraints
        factory.setSizeThreshold(uploadSize * 1000 * 1000);
        File file = new File(".");
        factory.setRepository(file);
        ServletFileUpload.isMultipartContent(servletRequest);
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        upload.setSizeMax(uploadSize * 1000 * 1000);

        // Parse the request
        try {
            items = upload.parseRequest(servletRequest);
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
        }
    }
    if (items != null) {
        // check form input
        if (request.getParameter(PARAMV_ACTION_DB_DO_REFRESH) != null) {

            ContactForm cf = (ContactForm) Utils.getActionForm(request, ContactForm.SESSION_KEY,
                    ContactForm.class);
            cf.populate(items);

            String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE);
            actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam));
            return;
        } else {
            Boolean isResponseCorrect = false;

            ContactForm cf = (ContactForm) Utils.getActionForm(request, ContactForm.SESSION_KEY,
                    ContactForm.class);
            cf.populate(items);
            if (!cf.validate()) {
                // add URL parameter indicating that portlet action was called
                // before render request

                String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE);
                actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam));

                return;
            }

            //remenber that we need an id to validate!
            String sessionId = request.getPortletSession().getId();
            //retrieve the response
            boolean enableCaptcha = PortalConfig.getInstance().getBoolean("portal.contact.enable.captcha",
                    Boolean.TRUE);

            if (enableCaptcha) {
                String response = request.getParameter("jcaptcha");
                for (FileItem item : items) {
                    if (item.getFieldName() != null) {
                        if (item.getFieldName().equals("jcaptcha")) {
                            response = item.getString();
                            break;
                        }
                    }
                }
                // Call the Service method
                try {
                    isResponseCorrect = CaptchaServiceSingleton.getInstance().validateResponseForID(sessionId,
                            response);
                } catch (CaptchaServiceException e) {
                    //should not happen, may be thrown if the id is not valid
                }
            }

            if (isResponseCorrect || !enableCaptcha) {
                try {
                    IngridResourceBundle messages = new IngridResourceBundle(
                            getPortletConfig().getResourceBundle(request.getLocale()), request.getLocale());

                    HashMap mailData = new HashMap();
                    mailData.put("user.name.given", cf.getInput(ContactForm.FIELD_FIRSTNAME));
                    mailData.put("user.name.family", cf.getInput(ContactForm.FIELD_LASTNAME));
                    mailData.put("user.employer", cf.getInput(ContactForm.FIELD_COMPANY));
                    mailData.put("user.business-info.telecom.telephone", cf.getInput(ContactForm.FIELD_PHONE));
                    mailData.put("user.business-info.online.email", cf.getInput(ContactForm.FIELD_EMAIL));
                    mailData.put("user.area.of.profession",
                            messages.getString("contact.report.email.area.of.profession."
                                    + cf.getInput(ContactForm.FIELD_ACTIVITY)));
                    mailData.put("user.interest.in.enviroment.info",
                            messages.getString("contact.report.email.interest.in.enviroment.info."
                                    + cf.getInput(ContactForm.FIELD_INTEREST)));
                    if (cf.hasInput(ContactForm.FIELD_NEWSLETTER)) {
                        Session session = HibernateUtil.currentSession();
                        Transaction tx = null;

                        try {

                            mailData.put("user.subscribed.to.newsletter", "yes");
                            // check for email address in newsletter list
                            tx = session.beginTransaction();
                            List newsletterDataList = session.createCriteria(IngridNewsletterData.class)
                                    .add(Restrictions.eq("emailAddress", cf.getInput(ContactForm.FIELD_EMAIL)))
                                    .list();
                            tx.commit();
                            // register for newsletter if not already registered
                            if (newsletterDataList.isEmpty()) {
                                IngridNewsletterData data = new IngridNewsletterData();
                                data.setFirstName(cf.getInput(ContactForm.FIELD_FIRSTNAME));
                                data.setLastName(cf.getInput(ContactForm.FIELD_LASTNAME));
                                data.setEmailAddress(cf.getInput(ContactForm.FIELD_EMAIL));
                                data.setDateCreated(new Date());

                                tx = session.beginTransaction();
                                session.save(data);
                                tx.commit();
                            }
                        } catch (Throwable t) {
                            if (tx != null) {
                                tx.rollback();
                            }
                            throw new PortletException(t.getMessage());
                        } finally {
                            HibernateUtil.closeSession();
                        }
                    } else {
                        mailData.put("user.subscribed.to.newsletter", "no");
                    }
                    mailData.put("message.body", cf.getInput(ContactForm.FIELD_MESSAGE));

                    Locale locale = request.getLocale();

                    String language = locale.getLanguage();
                    String localizedTemplatePath = EMAIL_TEMPLATE;
                    int period = localizedTemplatePath.lastIndexOf(".");
                    if (period > 0) {
                        String fixedTempl = localizedTemplatePath.substring(0, period) + "_" + language + "."
                                + localizedTemplatePath.substring(period + 1);
                        if (new File(getPortletContext().getRealPath(fixedTempl)).exists()) {
                            localizedTemplatePath = fixedTempl;
                        }
                    }

                    String emailSubject = messages.getString("contact.report.email.subject");

                    if (PortalConfig.getInstance().getBoolean("email.contact.subject.add.topic",
                            Boolean.FALSE)) {
                        if (cf.getInput(ContactForm.FIELD_ACTIVITY) != null
                                && !cf.getInput(ContactForm.FIELD_ACTIVITY).equals("none")) {
                            emailSubject = emailSubject + " - "
                                    + messages.getString("contact.report.email.area.of.profession."
                                            + cf.getInput(ContactForm.FIELD_ACTIVITY));
                        }
                    }

                    String from = cf.getInput(ContactForm.FIELD_EMAIL);
                    String to = PortalConfig.getInstance().getString(PortalConfig.EMAIL_CONTACT_FORM_RECEIVER,
                            "foo@bar.com");

                    String text = Utils.mergeTemplate(getPortletConfig(), mailData, "map",
                            localizedTemplatePath);
                    if (uploadEnable) {
                        if (uploadEnable) {
                            for (FileItem item : items) {
                                if (item.getFieldName() != null) {
                                    if (item.getFieldName().equals("upload")) {
                                        uploadFile = new File(sessionId + "_" + item.getName());
                                        // read this file into InputStream
                                        InputStream inputStream = item.getInputStream();

                                        // write the inputStream to a FileOutputStream
                                        OutputStream out = new FileOutputStream(uploadFile);
                                        int read = 0;
                                        byte[] bytes = new byte[1024];

                                        while ((read = inputStream.read(bytes)) != -1) {
                                            out.write(bytes, 0, read);
                                        }

                                        inputStream.close();
                                        out.flush();
                                        out.close();
                                        break;
                                    }
                                }
                            }
                        }
                        Utils.sendEmail(from, emailSubject, new String[] { to }, text, null, uploadFile);
                    } else {
                        Utils.sendEmail(from, emailSubject, new String[] { to }, text, null);
                    }
                } catch (Throwable t) {
                    cf.setError("", "Error sending mail from contact form.");
                    log.error("Error sending mail from contact form.", t);
                }

                // temporarily show same page with content
                String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, PARAMV_ACTION_SUCCESS);
                actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam));
            } else {
                cf.setErrorCaptcha();
                String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE);
                actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam));
                return;
            }
        }
    } else {
        ContactForm cf = (ContactForm) Utils.getActionForm(request, ContactForm.SESSION_KEY, ContactForm.class);
        cf.setErrorUpload();
        String urlViewParam = "?" + Utils.toURLParam(Settings.PARAM_ACTION, Settings.MSGV_TRUE);
        actionResponse.sendRedirect(actionResponse.encodeURL(Settings.PAGE_CONTACT + urlViewParam));
        return;
    }
}

From source file:axiom.servlet.AbstractServletClient.java

/**
 * Handle a request./*from w w  w. ja v a2  s .  co m*/
 *
 * @param request ...
 * @param response ...
 *
 * @throws ServletException ...
 * @throws IOException ...
 */
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final String httpMethod = request.getMethod();
    if (!"POST".equalsIgnoreCase(httpMethod) && !"GET".equalsIgnoreCase(httpMethod)) {
        sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "HTTP Method " + httpMethod + " not supported.");
        return;
    }

    RequestTrans reqtrans = new RequestTrans(request, response, getPathInfo(request));

    try {
        // get the character encoding
        String encoding = request.getCharacterEncoding();

        if (encoding == null) {
            // no encoding from request, use the application's charset
            encoding = getApplication().getCharset();
        }

        // read and set http parameters
        parseParameters(request, reqtrans, encoding);

        List uploads = null;
        ServletRequestContext reqcx = new ServletRequestContext(request);

        if (ServletFileUpload.isMultipartContent(reqcx)) {
            // get session for upload progress monitoring
            UploadStatus uploadStatus = getApplication().getUploadStatus(reqtrans);
            try {
                uploads = parseUploads(reqcx, reqtrans, uploadStatus, encoding);
            } catch (Exception upx) {
                System.err.println("Error in file upload: " + upx);
                if (uploadSoftfail) {
                    String msg = upx.getMessage();
                    if (msg == null || msg.length() == 0) {
                        msg = upx.toString();
                    }
                    reqtrans.set("axiom_upload_error", msg);
                } else if (upx instanceof FileUploadBase.SizeLimitExceededException) {
                    sendError(response, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                            "File upload size exceeds limit of " + uploadLimit + "kB");
                    return;
                } else {
                    sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "Error in file upload: " + upx);
                    return;
                }
            }
        }

        parseCookies(request, reqtrans, encoding);

        // do standard HTTP variables
        String host = request.getHeader("Host");

        if (host != null) {
            host = host.toLowerCase();
            reqtrans.set("http_host", host);
        }

        String referer = request.getHeader("Referer");

        if (referer != null) {
            reqtrans.set("http_referer", referer);
        }

        try {
            long ifModifiedSince = request.getDateHeader("If-Modified-Since");

            if (ifModifiedSince > -1) {
                reqtrans.setIfModifiedSince(ifModifiedSince);
            }
        } catch (IllegalArgumentException ignore) {
        }

        String ifNoneMatch = request.getHeader("If-None-Match");

        if (ifNoneMatch != null) {
            reqtrans.setETags(ifNoneMatch);
        }

        String remotehost = request.getRemoteAddr();

        if (remotehost != null) {
            reqtrans.set("http_remotehost", remotehost);
        }

        // get the cookie domain to use for this response, if any.
        String resCookieDomain = cookieDomain;

        if (resCookieDomain != null) {
            // check if cookieDomain is valid for this response.
            // (note: cookieDomain is guaranteed to be lower case)
            // check for x-forwarded-for header, fix for bug 443
            String proxiedHost = request.getHeader("x-forwarded-host");
            if (proxiedHost != null) {
                if (proxiedHost.toLowerCase().indexOf(cookieDomain) == -1) {
                    resCookieDomain = null;
                }
            } else if ((host != null) && host.toLowerCase().indexOf(cookieDomain) == -1) {
                resCookieDomain = null;
            }
        }

        // check if session cookie is present and valid, creating it if not.
        checkSessionCookie(request, response, reqtrans, resCookieDomain);

        String browser = request.getHeader("User-Agent");

        if (browser != null) {
            reqtrans.set("http_browser", browser);
        }

        String language = request.getHeader("Accept-Language");

        if (language != null) {
            reqtrans.set("http_language", language);
        }

        String authorization = request.getHeader("authorization");

        if (authorization != null) {
            reqtrans.set("authorization", authorization);
        }

        ResponseTrans restrans = getApplication().execute(reqtrans);

        // if the response was already written and committed by the application
        // we can skip this part and return
        if (response.isCommitted()) {
            return;
        }

        // set cookies
        if (restrans.countCookies() > 0) {
            CookieTrans[] resCookies = restrans.getCookies();

            for (int i = 0; i < resCookies.length; i++)
                try {
                    Cookie c = resCookies[i].getCookie("/", resCookieDomain);

                    response.addCookie(c);
                } catch (Exception ignore) {
                    ignore.printStackTrace();
                }
        }

        // write response
        writeResponse(request, response, reqtrans, restrans);

    } catch (Exception x) {
        try {
            if (debug) {
                sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server error: " + x);
                x.printStackTrace();
            } else {
                sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "The server encountered an error while processing your request. "
                                + "Please check back later.");
            }

            log("Exception in execute: " + x);
        } catch (IOException io_e) {
            log("Exception in sendError: " + io_e);
        }
    }
}

From source file:at.gv.egiz.pdfas.web.servlets.ExternSignServlet.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)//w  ww  .j  a v a2 s.  c o  m
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //PdfAsHelper.regenerateSession(request);

    logger.debug("Post signing request");

    String errorUrl = PdfAsParameterExtractor.getInvokeErrorURL(request);
    PdfAsHelper.setErrorURL(request, response, errorUrl);

    StatisticEvent statisticEvent = new StatisticEvent();
    statisticEvent.setStartNow();
    statisticEvent.setSource(Source.WEB);
    statisticEvent.setOperation(Operation.SIGN);
    statisticEvent.setUserAgent(UserAgentFilter.getUserAgent());

    try {
        byte[] filecontent = null;

        // checks if the request actually contains upload file
        if (!ServletFileUpload.isMultipartContent(request)) {
            // No Uploaded data!
            if (PdfAsParameterExtractor.getPdfUrl(request) != null) {
                doGet(request, response);
                return;
            } else {
                throw new PdfAsWebException("No Signature data defined!");
            }
        } else {
            // configures upload settings
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(WebConfiguration.getFilesizeThreshold());
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(WebConfiguration.getMaxFilesize());
            upload.setSizeMax(WebConfiguration.getMaxRequestsize());

            // constructs the directory path to store upload file
            String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
            // creates the directory if it does not exist
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }

            List<?> formItems = upload.parseRequest(request);
            logger.debug(formItems.size() + " Items in form data");
            if (formItems.size() < 1) {
                // No Uploaded data!
                // Try do get
                // No Uploaded data!
                if (PdfAsParameterExtractor.getPdfUrl(request) != null) {
                    doGet(request, response);
                    return;
                } else {
                    throw new PdfAsWebException("No Signature data defined!");
                }
            } else {
                for (int i = 0; i < formItems.size(); i++) {
                    Object obj = formItems.get(i);
                    if (obj instanceof FileItem) {
                        FileItem item = (FileItem) obj;
                        if (item.getFieldName().equals(UPLOAD_PDF_DATA)) {
                            filecontent = item.get();
                            try {
                                File f = new File(item.getName());
                                String name = f.getName();
                                logger.debug("Got upload: " + item.getName());
                                if (name != null) {
                                    if (!(name.endsWith(".pdf") || name.endsWith(".PDF"))) {
                                        name += ".pdf";
                                    }

                                    logger.debug("Setting Filename in session: " + name);
                                    PdfAsHelper.setPDFFileName(request, name);
                                }
                            } catch (Throwable e) {
                                logger.warn("In resolving filename", e);
                            }
                            if (filecontent.length < 10) {
                                filecontent = null;
                            } else {
                                logger.debug("Found pdf Data! Size: " + filecontent.length);
                            }
                        } else {
                            request.setAttribute(item.getFieldName(), item.getString());
                            logger.debug("Setting " + item.getFieldName() + " = " + item.getString());
                        }
                    } else {
                        logger.debug(obj.getClass().getName() + " - " + obj.toString());
                    }
                }
            }
        }

        if (filecontent == null) {
            if (PdfAsParameterExtractor.getPdfUrl(request) != null) {
                filecontent = RemotePDFFetcher.fetchPdfFile(PdfAsParameterExtractor.getPdfUrl(request));
            }
        }

        if (filecontent == null) {
            Object sourceObj = request.getAttribute("source");
            if (sourceObj != null) {
                String source = sourceObj.toString();
                if (source.equals("internal")) {
                    request.setAttribute("FILEERR", true);
                    request.getRequestDispatcher("index.jsp").forward(request, response);

                    statisticEvent.setStatus(Status.ERROR);
                    statisticEvent.setException(new Exception("No file uploaded"));
                    statisticEvent.setEndNow();
                    statisticEvent.setTimestampNow();
                    StatisticFrontend.getInstance().storeEvent(statisticEvent);
                    statisticEvent.setLogged(true);

                    return;
                }
            }
            throw new PdfAsException("No Signature data available");
        }

        doSignature(request, response, filecontent, statisticEvent);
    } catch (Exception e) {
        logger.error("Signature failed", e);
        statisticEvent.setStatus(Status.ERROR);
        statisticEvent.setException(e);
        if (e instanceof PDFASError) {
            statisticEvent.setErrorCode(((PDFASError) e).getCode());
        }
        statisticEvent.setEndNow();
        statisticEvent.setTimestampNow();
        StatisticFrontend.getInstance().storeEvent(statisticEvent);
        statisticEvent.setLogged(true);

        PdfAsHelper.setSessionException(request, response, e.getMessage(), e);
        PdfAsHelper.gotoError(getServletContext(), request, response);
    }
}

From source file:mercury.Controller.java

public void putAllRequestParametersInAttributes(HttpServletRequest request) {
    ArrayList fileBeanList = new ArrayList();
    HashMap<String, String> ht = new HashMap<String, String>();

    String fieldName = null;/*from   w  w  w.j a v a  2s.com*/
    String fieldValue = null;
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        java.util.List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        Iterator iter = items.iterator();

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

            if (item.isFormField()) {
                fieldName = item.getFieldName();
                fieldValue = item.getString();
                ht.put(fieldName, fieldValue);
            } else if (!item.isFormField()) {
                UploadedFileBean bean = new UploadedFileBean();
                bean.setFileItem(item);
                bean.setContentType(item.getContentType());
                bean.setFileName(item.getName());
                try {
                    bean.setInputStream(item.getInputStream());
                } catch (Exception e) {
                    System.out.println("=== Erro: " + e);
                }
                bean.setIsInMemory(item.isInMemory());
                bean.setSize(item.getSize());
                fileBeanList.add(bean);
                request.getSession().setAttribute("UPLOADED_FILE", bean);
            }
        }
    } else if (!isMultipart) {
        Enumeration<String> en = request.getParameterNames();

        String name = null;
        String value = null;
        while (en.hasMoreElements()) {
            name = en.nextElement();
            value = request.getParameter(name);
            ht.put(name, value);
        }
    }

    request.setAttribute("REQUEST_PARAMETERS", ht);
}

From source file:com.googlecode.fascinator.portal.pages.Dispatch.java

/**
 * Entry point for Tapestry to send page requests.
 * /*from   ww w.  j  a v  a  2s. c o  m*/
 * @param params : An array of request parameters from Tapestry
 * @returns StreamResponse : Tapestry object to return streamed response
 */
public StreamResponse onActivate(Object... params) {
    // log.debug("Dispatch starting : {} {}",
    // request.getMethod(), request.getPath());

    try {
        sysConfig = new JsonSimpleConfig();
        defaultPortal = sysConfig.getString(PortalManager.DEFAULT_PORTAL_NAME, "portal", "defaultView");
    } catch (IOException ex) {
        log.error("Error accessing system config", ex);
        return new HttpStatusCodeResponse(500, "Sorry, an internal server error has occured");
    }

    // Do all our parsing
    resourceName = resourceProcessing();

    // Make sure it's valid
    if (resourceName == null) {
        if (response.isCommitted()) {
            return GenericStreamResponse.noResponse();
        }
        return new HttpStatusCodeResponse(404, "Page not found: " + requestUri);
    }

    // Initialise storage for our form data
    // if there's no persistant data found.
    prepareFormData();

    // Set session timeout (defaults to 2 hours)
    int timeoutMins = sysConfig.getInteger(120, "portal", "sessionTimeout");
    hsr.getSession().setMaxInactiveInterval(timeoutMins * 60);

    // SSO Integration - Ignore AJAX and such
    if (!isSpecial) {
        // Make sure it's not a static resource
        if (security.testForSso(sessionState, resourceName, requestUri)) {
            // Run SSO
            boolean redirected = security.runSsoIntegration(sessionState, formData);
            // Finish here if SSO redirected
            if (redirected) {
                return GenericStreamResponse.noResponse();
            }
        }
    }

    // Make static resources cacheable
    if (resourceName.indexOf(".") != -1 && !isSpecial) {
        response.setHeader("Cache-Control", "public");
        response.setDateHeader("Expires", System.currentTimeMillis() + new TimeInterval("10y").milliseconds());
    }

    // Are we doing a file upload?
    isFile = ServletFileUpload.isMultipartContent(hsr);
    if (isFile) {
        fileProcessing();
    }

    // Page render time
    renderProcessing();

    return new GenericStreamResponse(mimeType, stream);
}

From source file:de.kp.ames.web.function.upload.UploadServiceImpl.java

public void doSetRequest(RequestContext ctx) {

    /*/*  w ww  .  j  av  a  2s.c  om*/
     * The result of the upload request, returned
     * to the requestor; note, that the result must
     * be a text response
     */
    boolean result = false;
    HttpServletRequest request = ctx.getRequest();

    try {

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {

            /* 
             * Create new file upload handler
             */
            ServletFileUpload upload = new ServletFileUpload();

            /*
             * Parse the request
             */
            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {

                FileItemStream fileItem = iter.next();
                if (fileItem.isFormField()) {
                    // not supported

                } else {

                    /* 
                     * Hook into the upload request to some virus scanning
                     * using the scanner factory of this application
                     */

                    byte[] bytes = FileUtil.getByteArrayFromInputStream(fileItem.openStream());
                    boolean checked = MalwareScanner.scanForViruses(bytes);

                    if (checked) {

                        String item = this.method.getAttribute(MethodConstants.ATTR_ITEM);
                        String type = this.method.getAttribute(MethodConstants.ATTR_TYPE);
                        if ((item == null) || (type == null)) {
                            this.sendNotImplemented(ctx);

                        } else {

                            String fileName = FilenameUtils.getName(fileItem.getName());
                            String mimeType = fileItem.getContentType();

                            try {
                                result = upload(item, type, fileName, mimeType, bytes);

                            } catch (Exception e) {
                                sendBadRequest(ctx, e);

                            }

                        }

                    }

                }

            }

        }

        /*
         * Send html response
         */
        if (result == true) {
            this.sendHTMLResponse(createHtmlSuccess(), ctx.getResponse());

        } else {
            this.sendHTMLResponse(createHtmlFailure(), ctx.getResponse());

        }

    } catch (Exception e) {
        this.sendBadRequest(ctx, e);

    } finally {
    }

}

From source file:jeeves.server.sources.ServiceRequestFactory.java

@SuppressWarnings("unchecked")
private static Element extractParameters(HttpServletRequest req, String uploadDir, int maxUploadSize)
        throws Exception {
    //--- set parameters from multipart request

    if (ServletFileUpload.isMultipartContent(req))
        return getMultipartParams(req, uploadDir, maxUploadSize);

    Element params = new Element(Jeeves.Elem.REQUEST);

    //--- add parameters from POST request

    for (Enumeration<String> e = req.getParameterNames(); e.hasMoreElements();) {
        String name = e.nextElement();
        String values[] = req.getParameterValues(name);

        //--- we don't overwrite params given in the url

        if (!name.equals(""))
            if (params.getChild(name) == null)
                for (int i = 0; i < values.length; i++)
                    params.addContent(new Element(name).setText(values[i]));
    }//w  ww .  j av a 2  s .  com

    return params;
}

From source file:io.fabric8.gateway.servlet.ProxyServlet.java

/**
 * Performs an HTTP POST request//from   w w  w .ja v  a  2 s .co  m
 *
 * @param httpServletRequest  The {@link javax.servlet.http.HttpServletRequest} object passed
 *                            in by the servlet engine representing the
 *                            client request to be proxied
 * @param httpServletResponse The {@link javax.servlet.http.HttpServletResponse} object by which
 *                            we can send a proxied response to the client
 */
@Override
public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws IOException, ServletException {
    // Create a standard POST request
    ProxyDetails proxyDetails = createProxyDetails(httpServletRequest, httpServletResponse);
    if (!proxyDetails.isValid()) {
        noMappingFound(httpServletRequest, httpServletResponse);
    } else {
        PostMethod postMethodProxyRequest = new PostMethod(proxyDetails.getStringProxyURL());
        // Forward the request headers
        setProxyRequestHeaders(proxyDetails, httpServletRequest, postMethodProxyRequest);
        // Check if this is a mulitpart (file upload) POST
        if (ServletFileUpload.isMultipartContent(httpServletRequest)) {
            this.handleMultipartPost(postMethodProxyRequest, httpServletRequest);
        } else {
            this.handleEntity(postMethodProxyRequest, httpServletRequest);
        }
        // Execute the proxy request
        this.executeProxyRequest(proxyDetails, postMethodProxyRequest, httpServletRequest, httpServletResponse);
    }
}