Example usage for javax.servlet.http HttpServletRequest setCharacterEncoding

List of usage examples for javax.servlet.http HttpServletRequest setCharacterEncoding

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest setCharacterEncoding.

Prototype

public void setCharacterEncoding(String env) throws UnsupportedEncodingException;

Source Link

Document

Overrides the name of the character encoding used in the body of this request.

Usage

From source file:org.codelibs.fess.filter.FessEncodingFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    final HttpServletRequest req = (HttpServletRequest) request;
    final String servletPath = req.getServletPath();
    for (final Map.Entry<String, String> entry : encodingMap.entrySet()) {
        final String path = entry.getKey();
        if (servletPath.startsWith(path)) {
            req.setCharacterEncoding(entry.getValue());
            final StringBuilder locationBuf = new StringBuilder(1000);
            final String contextPath = servletContext.getContextPath();
            if (StringUtil.isNotBlank(contextPath) && !"/".equals(contextPath)) {
                locationBuf.append(contextPath);
            }/*from ww  w. j  av a 2  s  .c o m*/
            locationBuf.append('/');
            locationBuf.append(servletPath.substring(path.length()));
            boolean append = false;
            final Map<String, String[]> parameterMap = new HashMap<>();
            parameterMap.putAll(req.getParameterMap());
            parameterMap.putAll(getParameterMapFromQueryString(req, entry.getValue()));
            for (final Map.Entry<String, String[]> paramEntry : parameterMap.entrySet()) {
                final String[] values = paramEntry.getValue();
                if (values == null) {
                    continue;
                }
                final String key = paramEntry.getKey();
                for (final String value : values) {
                    if (append) {
                        locationBuf.append('&');
                    } else {
                        locationBuf.append('?');
                        append = true;
                    }
                    locationBuf.append(urlCodec.encode(key, encoding));
                    locationBuf.append('=');
                    locationBuf.append(urlCodec.encode(value, encoding));
                }

            }
            final HttpServletResponse res = (HttpServletResponse) response;
            res.sendRedirect(locationBuf.toString());
            return;
        }
    }

    super.doFilter(request, response, chain);
}

From source file:org.codelibs.fess.filter.EncodingFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    final HttpServletRequest req = (HttpServletRequest) request;
    final String servletPath = req.getServletPath();
    for (final Map.Entry<String, String> entry : encodingMap.entrySet()) {
        final String path = entry.getKey();
        if (servletPath.startsWith(path)) {
            req.setCharacterEncoding(entry.getValue());
            final StringBuilder locationBuf = new StringBuilder(1000);
            final String contextPath = servletContext.getContextPath();
            if (StringUtil.isNotBlank(contextPath) && !"/".equals(contextPath)) {
                locationBuf.append(contextPath);
            }//from   w w w. j  a  va2  s .c  o m
            locationBuf.append('/');
            locationBuf.append(servletPath.substring(path.length()));
            boolean append = false;
            final Map<String, String[]> parameterMap = new HashMap<>();
            parameterMap.putAll(req.getParameterMap());
            parameterMap.putAll(getParameterMapFromQueryString(req, entry.getValue()));
            for (final Map.Entry<String, String[]> paramEntry : parameterMap.entrySet()) {
                final String[] values = paramEntry.getValue();
                if (values == null) {
                    continue;
                }
                final String key = paramEntry.getKey();
                for (final String value : values) {
                    if (append) {
                        locationBuf.append('&');
                    } else {
                        locationBuf.append('?');
                        append = true;
                    }
                    locationBuf.append(urlCodec.encode(key, encoding));
                    locationBuf.append('=');
                    locationBuf.append(urlCodec.encode(value, encoding));
                }

            }
            final HttpServletResponse res = (HttpServletResponse) response;
            res.sendRedirect(locationBuf.toString());
            return;
        }
    }

    chain.doFilter(request, response);
}

From source file:org.eclipse.smila.search.servlet.SMILASearchServlet.java

/**
 * extract query parameters from request, create SMILA Query record and send it to a SearchService, transform the DOM
 * result to HTML using an XSLT stylesheet.
 *
 * @param request/*from w  w  w .  j  a  va 2 s . c  om*/
 *          HTTP request
 * @param response
 *          HTTP response
 * @throws ServletException
 *           error during processing
 * @throws IOException
 *           error writing result to response stream
 */
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    try {
        request.setCharacterEncoding("UTF-8");
    } catch (final UnsupportedEncodingException e) {
        throw new ServletException("unable to set request encoding to UTF-8");
    }
    final boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    QueryBuilder query = null;
    if (isMultipart) {
        try {
            final List items = getFileUploadParser().parseRequest(request);
            final MultiPartRequestParser parser = new MultiPartRequestParser(DEFAULT_PIPELINE);
            query = parser.parse(items);
        } catch (final FileUploadException ex) {
            throw new ServletException("error parsing multipart request", ex);
        }

    } else {
        // TODO: get default pipeline name from configuration
        final HttpRequestParser parser = new HttpRequestParser(DEFAULT_PIPELINE);
        query = parser.parse(request);
    }
    final String showXml = query.getMetadata().getStringValue("showXml");
    final SearchService searchService = Activator.getSearchService();
    Document resultDoc = null;
    try {
        if (searchService == null) {
            resultDoc = getErrorBuilder().buildError(new ServletException(
                    "The SearchService is not available. Please wait a moment and try again."));
        } else {
            resultDoc = query.executeRequestXml(searchService);
            appendIndexList(resultDoc);
        }
    } catch (final ParserConfigurationException ex) {
        throw new ServletException(
                "Error creating an XML result to display. Something is completely wrong in the SMILA setup.",
                ex);
    }
    String stylesheet = query.getMetadata().getStringValue("style");
    if (StringUtils.isEmpty(stylesheet)) {
        // TODO: get default stylesheet name from configuration
        stylesheet = DEFAULT_STYLESHEET;
    }
    try {
        byte[] result = null;
        if (showXml != null && Boolean.valueOf(showXml)) {
            response.setContentType("text/xml");
            result = XMLUtils.stream(resultDoc.getDocumentElement(), false);
        } else {
            response.setContentType("text/html;charset=UTF-8");
            result = transform(resultDoc, stylesheet);
        }
        response.getOutputStream().write(result);
        response.getOutputStream().flush();
    } catch (final XMLUtilsException e) {
        if (_log.isErrorEnabled()) {
            _log.error("", e);
        }
    }
}

From source file:com.sielpe.controller.GestionarCandidatos.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  w w.j a v  a2 s .  c  o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        conexion = Conexion.getInstance();
        facadeDAO = new FachadaDAO();
        dtoFactory = new FactoryDTO();
        ListarCandidatos(request, response);
    } catch (Exception ex) {
        response.sendRedirect("GestionarCandidatos?msg=" + ex.getMessage());
    }
}

From source file:gr.forth.ics.isl.x3mlEditor.upload.UploadReceiver.java

/**
 *
 * @param req//from ww w. ja v a 2  s.c  om
 * @param resp
 * @throws IOException
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    req.setCharacterEncoding("UTF-8");

    String targetAnalyzer = req.getParameter("targetAnalyzer");
    if (targetAnalyzer == null) {
        targetAnalyzer = targetPathSuggesterAlgorithm;
    }

    String xpath = req.getParameter("path");
    String id = req.getParameter("id");
    String filePath = "";
    RequestParser requestParser = null;
    String filename = "";
    String msg = null;

    try {
        if (ServletFileUpload.isMultipartContent(req)) {
            requestParser = RequestParser.getInstance(req,
                    new MultipartUploadParser(req, TEMP_DIR, getServletContext()));
            filename = doWriteTempFileForPostRequest(requestParser);
        } else {
            requestParser = RequestParser.getInstance(req, null);
            filename = requestParser.getFilename();
        }
    } catch (Exception e) {
        System.out.println("Problem handling upload request");
        e.printStackTrace();
        filename = requestParser.getFilename();
        msg = e.getMessage();
    }

    DBFile uploadsDBFile = new DBFile(super.DBURI, super.adminCollection, "Uploads.xml", super.DBuser,
            super.DBpassword);

    String use = "";
    if (xpath != null) {
        if (filename.endsWith("rdf") || filename.endsWith("rdfs")) {
            if (xpath.endsWith("/@rdf_link")) {
                use = "rdf_link";
            } else {
                use = "schema_file";
            }
        } else if (filename.endsWith("xml")) {
            if (xpath.endsWith("/@generator_link")) {
                use = "generator_link";
            } else {
                use = "xml_link";
            }
        }
    }
    String mime = new Utils().findMime(uploadsDBFile, filename, use);

    filename = URLEncoder.encode(filename, "UTF-8");

    TEMP_DIR = new File(uploadsFolder + "uploadsTemp");

    if (!TEMP_DIR.exists()) {
        TEMP_DIR.mkdirs();
    }

    UPLOAD_DIR = new File(uploadsFolder + mime + System.getProperty("file.separator") + filePath);

    if (!UPLOAD_DIR.exists()) {
        UPLOAD_DIR.mkdirs();
    }

    String contentLengthHeader = req.getHeader(CONTENT_LENGTH);
    Long expectedFileSize = StringUtils.isBlank(contentLengthHeader) ? null
            : Long.parseLong(contentLengthHeader);

    resp.setContentType(CONTENT_TYPE);
    resp.setStatus(RESPONSE_CODE);

    if (!ServletFileUpload.isMultipartContent(req)) {
        writeToTempFile(req.getInputStream(), new File(UPLOAD_DIR, filename), expectedFileSize);
    }

    Tidy tidy = new Tidy(DBURI, rootCollection, x3mlCollection, DBuser, DBpassword, uploadsFolder);
    String duplicate = tidy.getDuplicate(UPLOAD_DIR + System.getProperty("file.separator") + filename,
            UPLOAD_DIR.getAbsolutePath());
    boolean duplicateFound = false;

    if (duplicate != null) {
        new File(UPLOAD_DIR, filename).delete(); //Delete uploaded file!
        filename = duplicate;
        duplicateFound = true;
    }

    String xmlId = "Mapping" + id + ".xml";
    DBCollection dbc = new DBCollection(super.DBURI, applicationCollection + "/Mapping", super.DBuser,
            super.DBpassword);
    String collectionPath = getPathforFile(dbc, xmlId, id);
    DBFile mappingFile = new DBFile(DBURI, collectionPath, xmlId, DBuser, DBpassword);
    boolean isAttribute = false;
    String attributeName = "";
    if (pathIsAttribute(xpath)) { //Generic for attributes
        attributeName = xpath.substring(xpath.lastIndexOf("/") + 2);
        xpath = xpath.substring(0, xpath.lastIndexOf("/"));
        isAttribute = true;
    }
    if (isAttribute) {

        mappingFile.xAddAttribute(xpath, attributeName, filename);
        if (xpath.endsWith("/target_schema") && attributeName.equals("schema_file")
                && (filename.endsWith("rdfs") || filename.endsWith("rdf") || filename.endsWith("owl")
                        || filename.endsWith("ttl") || filename.endsWith("xml") || filename.endsWith("xsd"))) {

            //                if (!(filename.endsWith("ttl") || filename.endsWith("owl"))) {//Skip exist for owl or ttl
            if (!duplicateFound) {
                //Uploading target schema files to eXist!
                try {
                    dbc = new DBCollection(super.DBURI, x3mlCollection, super.DBuser, super.DBpassword);
                    DBFile dbf = dbc.createFile(filename, "XMLDBFile");
                    String content = readFile(new File(UPLOAD_DIR, filename), "UTF-8");
                    dbf.setXMLAsString(content);
                    dbf.store();
                } catch (Exception ex) {
                    System.out.println(ex.getMessage());
                    msg = "File was uploaded but eXist queries target analyzer failed. Try using another target analyzer or upload a different file. Failure message: "
                            + ex.getMessage().replace("\n", "").replace("\r", "").replace("\"", "'");
                    ;
                }
            }
            //                }

            try {
                OntologyReasoner ont = getOntModel(mappingFile, id);

                HttpSession session = sessionCheck(req, resp);
                if (session == null) {
                    session = req.getSession();
                }
                session.setAttribute("modelInstance_" + id, ont);
                msg = null;
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
                msg = "File was uploaded but Jena reasoner target analyzer failed. Try using another target analyzer or upload a different file. Failure message: "
                        + ex.getMessage().replace("\n", "").replace("\r", "").replace("\"", "'");
                ;
            }
            //                }

        } else if (xpath.endsWith("/generator_policy_info") && (filename.endsWith("xml"))) {

            if (!duplicateFound) {
                //Uploading generator policy files to eXist!
                dbc = new DBCollection(super.DBURI, x3mlCollection, super.DBuser, super.DBpassword);
                DBFile dbf = dbc.createFile(filename, "XMLDBFile");
                String content = readFile(new File(UPLOAD_DIR, filename), "UTF-8");
                dbf.setXMLAsString(content);
                dbf.store();
            }
        }

    } else {
        mappingFile.xUpdate(xpath, filename);
    }

    writeResponse(filename, resp.getWriter(), msg, mime);

}

From source file:com.javaweb.controller.SuaTinTucServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*w  ww .j av  a2  s . co m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, ParseException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");

    //response.setCharacterEncoding("UTF-8");
    HttpSession session = request.getSession();
    String TieuDe = "", NoiDung = "", ngaydang = "", GhiChu = "", fileName = "";
    int idloaitin = 0, idTK = 0, idtt = 0;

    TintucService tintucservice = new TintucService();

    //File upload
    String folderupload = getServletContext().getInitParameter("file-upload");
    String rootPath = getServletContext().getRealPath("/");
    filePath = rootPath + folderupload;
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("C:\\Windows\\Temp\\"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters

                String fieldName = fi.getFieldName();
                fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();

                //change file name
                fileName = FileService.ChangeFileName(fileName);

                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + "/" + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                //                    out.println("Uploaded Filename: " + fileName + "<br>");
            }

            if (fi.isFormField()) {
                if (fi.getFieldName().equalsIgnoreCase("TieuDe")) {
                    TieuDe = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("NoiDung")) {
                    NoiDung = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("NgayDang")) {
                    ngaydang = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("GhiChu")) {
                    GhiChu = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("loaitin")) {
                    idloaitin = Integer.parseInt(fi.getString("UTF-8"));
                } else if (fi.getFieldName().equalsIgnoreCase("idtaikhoan")) {
                    idTK = Integer.parseInt(fi.getString("UTF-8"));
                } else if (fi.getFieldName().equalsIgnoreCase("idtt")) {
                    idtt = Integer.parseInt(fi.getString("UTF-8"));
                }
            }
        }

    } catch (Exception ex) {
        System.out.println(ex);
    }

    Date NgayDang = new SimpleDateFormat("yyyy-MM-dd").parse(ngaydang);

    Tintuc tt = tintucservice.GetTintucID(idtt);

    tt.setIdTaiKhoan(idTK);
    tt.setTieuDe(TieuDe);
    tt.setNoiDung(NoiDung);
    tt.setNgayDang(NgayDang);
    tt.setGhiChu(GhiChu);
    if (!fileName.equals("")) {
        if (tt.getImgLink() != null) {
            if (!tt.getImgLink().equals(fileName)) {
                tt.setImgLink(fileName);
            }
        } else {
            tt.setImgLink(fileName);
        }
    }

    boolean rs = tintucservice.InsertTintuc(tt);
    if (rs) {
        session.setAttribute("kiemtra", "1");
        response.sendRedirect("SuaTinTuc.jsp?idTintuc=" + idtt);
    } else {
        session.setAttribute("kiemtra", "0");
        response.sendRedirect("SuaTinTuc.jsp?idTintuc=" + idtt);
    }

    //        try (PrintWriter out = response.getWriter()) {
    //            /* TODO output your page here. You may use following sample code. */
    //            out.println("<!DOCTYPE html>");
    //            out.println("<html>");
    //            out.println("<head>");
    //            out.println("<title>Servlet SuaTinTucServlet</title>");            
    //            out.println("</head>");
    //            out.println("<body>");
    //            out.println("<h1>Servlet SuaTinTucServlet at " + request.getContextPath() + "</h1>");
    //            out.println("</body>");
    //            out.println("</html>");
    //        }
}

From source file:com.ikon.servlet.admin.ReportServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = "";
    String userId = request.getRemoteUser();
    updateSessionManager(request);// ww  w. j  av a2 s.  c o m

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            InputStream is = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            Report rp = new Report();

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("action")) {
                        action = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("rp_id")) {
                        rp.setId(Integer.parseInt(item.getString("UTF-8")));
                    } else if (item.getFieldName().equals("rp_name")) {
                        rp.setName(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("rp_active")) {
                        rp.setActive(true);
                    }
                } else {
                    is = item.getInputStream();
                    rp.setFileName(FilenameUtils.getName(item.getName()));
                    rp.setFileMime(MimeTypeConfig.mimeTypes.getContentType(item.getName()));
                    rp.setFileContent(SecureStore.b64Encode(IOUtils.toByteArray(is)));
                    is.close();
                }
            }

            if (action.equals("create")) {
                long id = ReportDAO.create(rp);

                // Activity log
                UserActivity.log(userId, "ADMIN_REPORT_CREATE", Long.toString(id), null, rp.toString());
                list(userId, request, response);
            } else if (action.equals("edit")) {
                Report tmp = ReportDAO.findByPk(rp.getId());
                tmp.setActive(rp.isActive());
                tmp.setFileContent(rp.getFileContent());
                tmp.setFileMime(rp.getFileMime());
                tmp.setFileName(rp.getFileName());
                tmp.setName(rp.getName());
                ReportDAO.update(tmp);

                // Activity log
                UserActivity.log(userId, "ADMIN_REPORT_EDIT", Long.toString(rp.getId()), null, rp.toString());
                list(userId, request, response);
            } else if (action.equals("delete")) {
                ReportDAO.delete(rp.getId());

                // Activity log
                UserActivity.log(userId, "ADMIN_REPORT_DELETE", Long.toString(rp.getId()), null, null);
                list(userId, request, response);
            }
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:ua.aits.sdolyna.controller.SystemController.java

@RequestMapping(value = "/Sdolyna/system/do/insertdata", method = RequestMethod.POST)
public ModelAndView addArticle(HttpServletRequest request) throws SQLException, ClassNotFoundException,
        InstantiationException, IllegalAccessException, UnsupportedEncodingException, IOException {
    request.setCharacterEncoding("UTF-8");
    String titleEN = request.getParameter("titleEN");
    String titleRU = request.getParameter("titleRU");
    String textEN = request.getParameter("textEN");
    String textRU = request.getParameter("textRU");
    String date = request.getParameter("date");
    String date_end = request.getParameter("act-date");
    String category = request.getParameter("category");
    String files_data = request.getParameter("gallery-items");
    String id = Articles.insertArticle(titleEN, titleRU, textEN, textRU, category, date, date_end);
    if (files_data != "" && files_data != null) {

        List<GalleryModel> items = new LinkedList<>();
        String[] itm = files_data.split("\\|");
        for (String i : itm) {
            String[] row = i.split("\\,");
            GalleryModel imag = Articles.new GalleryModel();
            imag.setImage_url(row[0].replace("path:", ""));
            imag.setImage_title_ru(row[1].replace("textRU:", ""));
            imag.setImage_title_en(row[2].replace("textEN:", ""));
            imag.setImage_article_id(Integer.parseInt(id));
            items.add(imag);/*  ww  w  .  ja  va 2  s .c om*/
        }
        Articles.insertGalImages(items);
    }
    return new ModelAndView("redirect:" + "/system/index/" + category);
}

From source file:com.ikon.servlet.admin.PropertyGroupsServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doGet({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = WebUtils.getString(request, "action");
    String pgLabel = WebUtils.getString(request, "label");
    String label = WebUtils.getString(request, "value");
    Session session = null;/*from  w  ww. j  a  va  2  s .c  o  m*/
    updateSessionManager(request);

    try {
        // session = JCRUtils.getSession();
        if (action.equals("validatepgName")) {
            validatePropertyGroupName(label, request, response);
        } else if (action.equals("register")) {
            register(session, request, response);
        } else if (action.equals("edit")) {
            edit(pgLabel, request, response);
        } else if (action.equals("delete")) {
            XMLUtils xmlUtils = new XMLUtils(PROPERTY_GROUPS_XML);
            xmlUtils.deletePropertyGroup(pgLabel);
            list(request, response);
        }

        if (action.equals("") || action.equals("register")) {
            list(request, response);
        }
    } catch (LoginException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (RepositoryException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (javax.jcr.RepositoryException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (org.apache.jackrabbit.core.nodetype.compact.ParseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (InvalidNodeTypeDefException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        // JCRUtils.logout(session);
    }
}

From source file:cn.vlabs.duckling.vwb.ui.servlet.SimpleUploaderServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("--- BEGIN DOPOST ---");

    request.setCharacterEncoding("UTF-8");
    request.setAttribute(RETVAL, "0");
    request.setAttribute(FILEURL, "");
    request.setAttribute(ERRORMESSAGE, "");
    String newName = "";
    String hash = "";
    // ???/* w  w  w .  j a v a  2  s  .c om*/
    VWBContext context = VWBContext.createContext(request, VWBCommand.ATTACH, null);
    rb = context.getBundle("templates/default");

    if (!context.getVWBSession().isAuthenticated()) {
        request.setAttribute(RETVAL, "212");
        request.setAttribute(ERRORMESSAGE, rb.getString("uploader.nopermission"));
    } else {
        if (enabled) {
            try {
                Map<String, Object> fields = parseFileItem(request);

                FileItem uplFile = (FileItem) fields.get("NewFile");
                String fileNameLong = uplFile.getName();
                fileNameLong = fileNameLong.replace('\\', '/');
                String[] pathParts = fileNameLong.split("/");
                String fileName = pathParts[pathParts.length - 1];

                long fileSize = uplFile.getSize();
                InputStream in = uplFile.getInputStream();

                if (fileSize == 0 || in == null) {
                    if (debug)
                        log.error("The upload file size is 0 or inputstream is null!");
                    request.setAttribute(RETVAL, "211");
                    request.setAttribute(ERRORMESSAGE, rb.getString("error.doc.zerolength"));
                } else {
                    HashMap<String, String> hashMap = new HashMap<String, String>();
                    hashMap.put("title", fileName);
                    hashMap.put("summary", "");
                    hashMap.put("page", (String) fields.get("pageName"));
                    hashMap.put("signature", (String) fields.get("signature"));
                    hashMap.put("rightType", (String) fields.get("rightType"));
                    hashMap.put("cachable", (String) fields.get("cachable"));
                    hash = executeUpload(request, context, in, fileName, fileSize, hashMap, response);
                }
                newName = fileName;
            } catch (Exception ex) {
                log.debug("Error on upload picture", ex);
                request.setAttribute(RETVAL, "203");
                request.setAttribute(ERRORMESSAGE, rb.getString("uploader.parsepara"));
            }
        } else {
            request.setAttribute(RETVAL, "1");
            request.setAttribute(ERRORMESSAGE, rb.getString("uploader.invalidxml"));
        }
    }

    printScript(request, response, newName, hash);

    log.debug("--- END DOPOST ---");
}