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:com.ikon.servlet.admin.DatabaseQueryServlet.java

@Override
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);/*w  ww. j a  va  2s .  c  om*/
    String user = request.getRemoteUser();
    ServletContext sc = getServletContext();
    Session session = null;

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            String type = "";
            String qs = "";
            byte[] data = null;

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

                if (item.isFormField()) {
                    if (item.getFieldName().equals("qs")) {
                        qs = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("type")) {
                        type = item.getString("UTF-8");
                    }
                } else {
                    data = item.get();
                }
            }

            if (!qs.equals("") && !type.equals("")) {
                session = HibernateUtil.getSessionFactory().openSession();
                sc.setAttribute("qs", qs);
                sc.setAttribute("type", type);

                if (type.equals("jdbc")) {
                    executeJdbc(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_JDBC", null, null, qs);
                } else if (type.equals("hibernate")) {
                    executeHibernate(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_HIBERNATE", null, null, qs);
                } else if (type.equals("metadata")) {
                    executeMetadata(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_METADATA", null, null, qs);
                }
            } else if (data != null && data.length > 0) {
                sc.setAttribute("exception", null);
                session = HibernateUtil.getSessionFactory().openSession();
                executeUpdate(session, data, sc, request, response);

                // Activity log
                UserActivity.log(user, "ADMIN_DATABASE_QUERY_FILE", null, null, new String(data));
            } else {
                sc.setAttribute("qs", qs);
                sc.setAttribute("type", type);
                sc.setAttribute("exception", null);
                sc.setAttribute("globalResults", new ArrayList<DatabaseQueryServlet.GlobalResult>());
                sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
            }
        }
    } catch (FileUploadException e) {
        sendError(sc, request, response, e);
    } catch (SQLException e) {
        sendError(sc, request, response, e);
    } catch (HibernateException e) {
        sendError(sc, request, response, e);
    } catch (DatabaseException e) {
        sendError(sc, request, response, e);
    } catch (IllegalAccessException e) {
        sendError(sc, request, response, e);
    } catch (InvocationTargetException e) {
        sendError(sc, request, response, e);
    } catch (NoSuchMethodException e) {
        sendError(sc, request, response, e);
    } finally {
        HibernateUtil.close(session);
    }
}

From source file:com.openkm.servlet.admin.BenchmarkServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    String action = request.getParameter("action") != null ? request.getParameter("action") : "";
    updateSessionManager(request);//w  w  w. j a va2s .co m

    if (action.equals("okmImport")) {
        okmImport(request, response, BM_FOLDER + "_okm_import");
    } else if (action.equals("okmCopy")) {
        okmCopy(request, response);
    } else if (action.equals("okmApiHighGenerate")) {
        okmApiHighGenerate(request, response, BM_FOLDER + "_okm_api_high");
    } else if (action.equals("okmApiLowGenerate")) {
        okmApiLowGenerate(request, response, BM_FOLDER + "_okm_api_low");
    } else if (action.equals("okmRawGenerate")) {
        okmRawGenerate(request, response, BM_FOLDER + "_okm_raw");
    } else if (action.equals("jcrGenerate")) {
        jcrGenerate(request, response, BM_FOLDER + "_jcr");
    } else {
        ServletContext sc = getServletContext();
        sc.getRequestDispatcher("/admin/benchmark.jsp").forward(request, response);
    }
}

From source file:com.juicioenlinea.application.servlets.particular.DemandaServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*from  w w  w  . j av  a 2  s .c o  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 {
    response.setContentType("text/html;charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");

    String action = request.getParameter("action");

    if (action == null) {
        response.sendRedirect("indexParticular.jsp");
    } else {
        switch (action) {
        case "create":
            create(request, response);
            break;

        case "create2":
            create2(request, response);
            break;

        case "read":
            read(request, response);
            break;

        case "readNumero":
            readNumero(request, response);
            break;

        case "update":
            update(request, response);
            break;

        case "demandasHechas":
            demandasHechas(request, response);
            break;

        case "demandasRecibidas":
            demandasRecibidas(request, response);
            break;

        case "agregarDocumentos":
            agregarDocumentos(request, response);
            break;

        case "agregarDocumentosD":
            agregarDocumentosD(request, response);
            break;

        case "readRecibida":
            readRecibida(request, response);
            break;

        case "apelarDemanda":
            apelarDemanda(request, response);
            break;

        case "form":
            form(request, response);
            break;

        default:
            response.sendRedirect("indexParticular.jsp");
            break;
        }
    }
}

From source file:com.openkm.servlet.admin.DatabaseQueryServlet.java

@Override
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);//from  ww w. j a  v  a2 s .  c  o m
    String user = request.getRemoteUser();
    ServletContext sc = getServletContext();
    Session session = null;

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            boolean showSql = false;
            String vtable = "";
            String type = "";
            String qs = "";
            byte[] data = null;

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

                if (item.isFormField()) {
                    if (item.getFieldName().equals("qs")) {
                        qs = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("type")) {
                        type = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("showSql")) {
                        showSql = true;
                    } else if (item.getFieldName().equals("vtables")) {
                        vtable = item.getString("UTF-8");
                    }
                } else {
                    data = item.get();
                }
            }

            if (!qs.equals("") && !type.equals("")) {
                session = HibernateUtil.getSessionFactory().openSession();
                sc.setAttribute("qs", qs);
                sc.setAttribute("type", type);

                if (type.equals("jdbc")) {
                    executeJdbc(session, qs, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_JDBC", null, null, qs);
                } else if (type.equals("hibernate")) {
                    executeHibernate(session, qs, showSql, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_HIBERNATE", null, null, qs);
                } else if (type.equals("metadata")) {
                    sc.setAttribute("vtable", vtable);
                    executeMetadata(session, qs, false, sc, request, response);

                    // Activity log
                    UserActivity.log(user, "ADMIN_DATABASE_QUERY_METADATA", null, null, qs);
                }
            } else if (data != null && data.length > 0) {
                sc.setAttribute("exception", null);
                session = HibernateUtil.getSessionFactory().openSession();
                executeUpdate(session, data, sc, request, response);

                // Activity log
                UserActivity.log(user, "ADMIN_DATABASE_QUERY_FILE", null, null, new String(data));
            } else {
                sc.setAttribute("qs", qs);
                sc.setAttribute("type", type);
                sc.setAttribute("showSql", showSql);
                sc.setAttribute("exception", null);
                sc.setAttribute("globalResults", new ArrayList<DbQueryGlobalResult>());
                sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
            }
        } else {
            // Edit table cell value
            String action = request.getParameter("action");
            String vtable = request.getParameter("vtable");
            String column = request.getParameter("column");
            String value = request.getParameter("value");
            String id = request.getParameter("id");

            if (action.equals("edit")) {
                int idx = column.indexOf('(');

                if (idx > 0) {
                    column = column.substring(idx + 1, idx + 6);
                }

                String hql = "update DatabaseMetadataValue dmv set dmv." + column + "='" + value
                        + "' where dmv.table='" + vtable + "' and dmv.id=" + id;
                log.info("HQL: {}", hql);
                session = HibernateUtil.getSessionFactory().openSession();
                int rows = session.createQuery(hql).executeUpdate();
                log.info("Rows affected: {}", rows);
            }
        }
    } catch (FileUploadException e) {
        sendError(sc, request, response, e);
    } catch (SQLException e) {
        sendError(sc, request, response, e);
    } catch (HibernateException e) {
        sendError(sc, request, response, e);
    } catch (DatabaseException e) {
        sendError(sc, request, response, e);
    } catch (IllegalAccessException e) {
        sendError(sc, request, response, e);
    } catch (InvocationTargetException e) {
        sendError(sc, request, response, e);
    } catch (NoSuchMethodException e) {
        sendError(sc, request, response, e);
    } finally {
        HibernateUtil.close(session);
    }
}

From source file:com.w20e.socrates.servlet.WebsurveyServlet.java

/**
 * Do the thing... If there is no runner (context) in the session, create a
 * new session based on the given id parameter. If there is also no id
 * parameter, it's an error. If the id parameter is given, create a new
 * runner context anyway. If a parameter called regkey is given, this
 * parameter is used for storage and possibly retrieval of the instance.
 * This way, a user may provide it's own key.
 * /*  www .j  a  v  a  2  s. co m*/
 * @param req
 *            The request
 * @param res
 *            The response
 * @throws IOException
 *             when some io error occurs
 * @throws ServletException
 *             when the servlet fails
 */
public final void doPost(final HttpServletRequest req, final HttpServletResponse res)
        throws IOException, ServletException {

    // Always use UTF!
    res.setContentType("text/html;charset=UTF-8");
    req.setCharacterEncoding("UTF-8");

    // Thou shalst not cache...
    res.addHeader("Cache-Control", "no-cache");
    res.addHeader("Pragma", "No-Cache");

    HttpSession session = this.sessionMgr.getSession(req);

    // If we don't have a session now, we might as well call it a day...
    if (session == null) {

        if (ServletHelper.getCookie(req, "JSESSIONID") != null) {
            LOGGER.warning("Session timeout");
            res.sendRedirect("session-timeout.html");
            res.getOutputStream().flush();
            return;
        } else {
            LOGGER.severe("No session created");
            res.sendRedirect("session-creation-error.html");
            res.getOutputStream().flush();
            return;
        }
    }

    // Hold all enable/disable options
    //
    Map<String, String> options = ServletHelper.determineOptions(req);

    // If no runner yet for this session, create one. We should have
    // startup param's for the runner, like the questionnaire to run, and
    // the locale. If these are not available, check for regkey. Else, all fails.
    //
    if (session.getAttribute("runnerCtx") == null) {

        LOGGER.finer("Session instantiated with id " + session.getId());
        LOGGER.fine("No runner context available in session; creating one");

        if (req.getParameter("id") == null && req.getParameter("regkey") == null) {
            LOGGER.warning("No id nor regkey parameter in request");
            try {
                res.sendRedirect("session-creation-error.html");
                this.sessionMgr.invalidateSession(req);
                res.getOutputStream().flush();
            } catch (IOException e) {
                LOGGER.severe("Couldn't even send error message..." + e.getMessage());
            }
            return;
        }

        if (!initializeRunner(req, res, session, options)) {
            LOGGER.severe("Could not create runner context. Bye for now.");
            return;
        }
    }

    // Okido, by now we should have a session, and a valid runner context
    // stored in the session.
    //
    try {
        WebsurveyContext wwCtx = (WebsurveyContext) session.getAttribute("runnerCtx");

        // Now let's see whether this session was deserialized.
        //
        if (wwCtx.isInvalid()) {
            LOGGER.info("Serialized session found!");
            // Re-create the context, and attach to WoliWeb context.
            LOGGER.finer("Model id: " + wwCtx.getModelId());
            LOGGER.finer("State id: " + wwCtx.getStateId());
            LOGGER.finer("Locale: " + wwCtx.getLocale());

            URI qUri = QuestionnaireURIFactory.getInstance().determineURI(this.rootDir, wwCtx.getModelId());

            RunnerContextImpl ctx = this.runnerFactory.createContext(qUri, null);
            ctx.setLocale(wwCtx.getLocale());
            ctx.setQuestionnaireId(qUri);
            ctx.getStateManager().setStateById(wwCtx.getStateId());
            ctx.setInstance(wwCtx.getInstance());
            wwCtx.setRunnerContext(ctx);
        }

        RunnerContextImpl ctx = (RunnerContextImpl) wwCtx.getRunnerContext();

        LOGGER.finer("Session id " + session.getId());
        LOGGER.finer("Context id " + ctx.getInstance().getMetaData().get("key"));

        // set locale if requested later on, when the survey is well under way...
        if (req.getParameter("locale") != null && req.getParameter("id") == null) {
            ctx.setLocale(LocaleUtility.getLocale(req.getParameter("locale"), false));
            LOGGER.fine("Locale change requested; set to "
                    + LocaleUtility.getLocale(req.getParameter("locale"), false));
        }

        // even check on locale in instance data...
        try {
            Locale instanceLocale = LocaleUtility
                    .getLocale(ctx.getInstance().getNode("locale").getValue().toString(), false);

            if (instanceLocale != null && instanceLocale != ctx.getLocale()) {
                LOGGER.fine("Locale is set in instance data: " + instanceLocale);
                ctx.setLocale(instanceLocale);
            }
        } catch (Exception ex) {
            // not a problem...
        }

        // Add specific options
        // @todo This should move to the runner creation options.
        if (ctx.getProperty("renderOptions") == null) {
            ctx.setProperty("renderOptions", options);
        } else {
            ((Map<String, String>) ctx.getProperty("renderOptions")).putAll(options);
        }

        Map<String, Object> params = ParameterParser.parseParams(req);

        ctx.setData(params);

        // Do we have initial data already?
        if ("true".equals(options.get("enable_preload_params"))) {
            Node node;
            for (String key : params.keySet()) {
                node = ctx.getInstance().getNode(key);
                if (node != null) {
                    LOGGER.fine("Preloading node value " + params.get(key) + " for node " + node.getName());
                    node.setValue(params.get(key));
                }
            }
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        ctx.setOutputStream(output);

        // @todo: I really don't see why we should re-create the runner for
        // every post. Actually, the factory holds a reference to existing
        // runners, so it is not really bad, but I reckon the context should
        // hold the runner?
        //
        URI qUri = QuestionnaireURIFactory.getInstance().determineURI(this.rootDir, wwCtx.getModelId());

        Runner runner = this.runnerFactory.createRunner(qUri);

        if (req.getParameter("previous") == null) {
            Map<String, Object> meta = ctx.getInstance().getMetaData();
            meta.put("time_" + req.getParameter("stateId"), new Date());
        }

        // Always store stateId in instance, for retrieval of state after
        // serialization.
        //
        if (req.getParameter("stateId") != null) {
            LOGGER.fine("Setting state id to " + req.getParameter("stateId"));
            ctx.getInstance().getMetaData().put("stateId", req.getParameter("stateId"));
            if (!ctx.getStateManager().setStateById(req.getParameter("stateId"))) {
                LOGGER.warning("Couldn't set stateId to " + req.getParameter("stateId"));
            }
        }

        // Go two states back if 'previous' request, and simply execute
        // 'next'.
        if (req.getParameter("previous") != null) {
            ctx.getStateManager().previous();
            RenderState state = ctx.getStateManager().previous();

            LOGGER.finest("Fill data from instance");

            ctx.setProperty("previous", "true");

            if (state != null) {

                // Make sure to fill in existing data, otherwise we'll get
                // an error
                //
                for (Iterator<Renderable> i = state.getItems().iterator(); i.hasNext();) {
                    Renderable r = i.next();
                    if (r instanceof Control) {
                        String name = ((Control) r).getBind();
                        params.put(name, ctx.getInstance().getNode(name).getValue());
                        LOGGER.finest("Set node " + name + " to " + params.get(name));
                    }
                }
            }
        } else {
            ctx.setProperty("previous", "false");
        }

        next(ctx, runner);

        LOGGER.fine("Are we stored yet? " + ctx.getInstance().getMetaData().get("storage-type"));

        // If we submitted, destroy long session
        if ("submit".equals(ctx.getInstance().getMetaData().get("storage-type"))) {
            LOGGER.fine("Invalidating long session");

            String surveyId = ctx.getInstance().getMetaData().get("qId").toString();

            this.sessionMgr.invalidateLongSession(surveyId, req, res);
        }

        // If this was the last action, destroy session.
        if (!runner.hasNext(ctx)) {
            this.sessionMgr.invalidateSession(req);
        }

        res.getOutputStream().write(output.toByteArray());
        res.getOutputStream().flush();

        // free resources...
        ctx.setOutputStream(null);

    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "No runner created", e);
        throw new ServletException("Runner could not be created: " + e.getMessage());
    }
}

From source file:org.hippoecm.repository.RepositoryServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String currentNodePath = req.getRequestURI();

    if (!currentNodePath.endsWith("/")) {
        res.sendRedirect(currentNodePath + "/");
        return;// w  w  w . j ava2  s  . c o m
    }

    // explicitly set character encoding
    req.setCharacterEncoding("UTF-8");
    res.setCharacterEncoding("UTF-8");

    if (req.getParameter("logout") != null) {
        FormAuth.logout(req);
        // redirect to current URL without ?logout
        res.sendRedirect("./");
        return;
    }

    Session jcrSession = FormAuth.authorize(req, repository);
    if (jcrSession == null) {
        FormAuth.showLoginPage(req, res, "");
        return;
    }

    if (currentNodePath.startsWith(req.getContextPath())) {
        currentNodePath = currentNodePath.substring(req.getContextPath().length());
    }

    if (currentNodePath.startsWith(req.getServletPath())) {
        currentNodePath = currentNodePath.substring(req.getServletPath().length());
    }

    Map<String, Object> templateParams = new HashMap<String, Object>();

    try {

        templateParams.put("jcrSession", jcrSession);

        // parse path
        while (currentNodePath.startsWith("/")) {
            currentNodePath = currentNodePath.substring(1);
        }

        templateParams.put("rootRelativePath", StringUtils.isEmpty(currentNodePath) ? ""
                : StringUtils.join(new String[currentNodePath.split("/").length + 1], "../"));

        currentNodePath = URLDecoder.decode(currentNodePath, "UTF-8");
        Node rootNode = jcrSession.getRootNode();
        Node currentNode = rootNode;
        if (!"".equals(currentNodePath)) {
            currentNode = currentNode.getNode(currentNodePath);
        }

        templateParams.put("rootNode", rootNode);
        templateParams.put("currentNode", currentNode);

        if (currentNode.isSame(rootNode)) {
            templateParams.put("ancestorNodes", Collections.emptyList());
        } else {
            List<Node> ancestorNodes = new LinkedList<Node>();
            for (Node ancestor = currentNode.getParent(); ancestor != null
                    && !ancestor.isSame(rootNode); ancestor = ancestor.getParent()) {
                ancestorNodes.add(0, ancestor);
            }
            templateParams.put("ancestorNodes", ancestorNodes);
        }

        String searchType = req.getParameter("search-type");

        if (searchType != null && !"uuid".equals(searchType)) {

            String limit = "1000";
            boolean isXPathQuery = false;
            String queryString = "";

            if ("text".equals(searchType)) {
                limit = req.getParameter("text-limit");
                isXPathQuery = true;
                queryString = req.getParameter("text");
                templateParams.put("originalQuery", queryString);
                if (StringUtils.isNotBlank(queryString)) {
                    queryString = "//*[jcr:contains(* , '" + queryString + "') ]";
                }
                queryString = addOrderbyClause(queryString, true);

            } else if ("xpath".equals(searchType)) {
                limit = req.getParameter("xpath-limit");
                isXPathQuery = true;
                queryString = req.getParameter("xpath").trim();
                templateParams.put("originalQuery", queryString);
                queryString = addOrderbyClause(queryString, true);

            } else if ("sql".equals(searchType)) {
                limit = req.getParameter("sql-limit");
                isXPathQuery = false;
                queryString = req.getParameter("sql").trim();
                templateParams.put("originalQuery", queryString);
                queryString = addOrderbyClause(queryString, false);
            }

            QueryManager qmgr = jcrSession.getWorkspace().getQueryManager();
            String language = (isXPathQuery ? Query.XPATH : Query.SQL);
            Query query;

            if (isXPathQuery) {
                // we encode xpath queries to support queries like /jcr:root/7_8//*
                // the 7 needs to be encode
                query = qmgr.createQuery(RepoUtils.encodeXpath(queryString), language);
            } else {
                query = qmgr.createQuery(queryString, language);
            }

            if (limit != null && !limit.isEmpty()) {
                query.setLimit(Long.parseLong(limit));
            }

            QueryResult queryResult = query.execute();
            templateParams.put("queryResult", queryResult);
            templateParams.put("queryResultTotalSize",
                    ((HippoNodeIterator) queryResult.getNodes()).getTotalSize());
        }

        if (req.getParameter("map") != null) {
            Map repositoryMap = repository.getRepositoryMap(currentNode);
            String param = req.getParameter("map");
            if (!"".equals(param)) {
                StringTokenizer st = new StringTokenizer(param, ".");
                while (st.hasMoreTokens()) {
                    repositoryMap = (Map) repositoryMap.get(st.nextToken());
                }
            }
            templateParams.put("repositoryMap", repositoryMap);
        }

        if ("uuid".equals(searchType)) {
            Node nodeById = jcrSession.getNodeByIdentifier(req.getParameter("uuid"));
            templateParams.put("nodeById", nodeById);
        } else if (req.getParameter("deref") != null) {
            Node nodeById = jcrSession.getNodeByIdentifier(req.getParameter("deref"));
            templateParams.put("nodeById", nodeById);
        }

    } catch (LoginException ex) {
        BasicAuth.setRequestAuthorizationHeaders(res, "Repository");
    } catch (Exception ex) {
        templateParams.put("exception", ex);
    } finally {
        try {
            if (jcrSession != null) {
                renderTemplatePage(req, res, getRenderTemplate(req), templateParams);
            }
        } catch (Exception te) {
            log.warn("Failed to render freemarker template.", te);
        } finally {
            if (jcrSession != null) {
                jcrSession.logout();
            }
        }
    }
}

From source file:com.devpia.service.DEXTUploadJController.java

@RequestMapping(value = "/dextfile/downloadFile/{filePath}/{fileName}/down.do", method = RequestMethod.GET)
public void downloadFile(@PathVariable("filePath") String filePath, @PathVariable("fileName") String fileName,
        HttpServletRequest request, HttpServletResponse res, ModelMap model) throws Exception {
    request.setCharacterEncoding("utf-8");
    res.setContentType("text/html; charset=UTF-8");

    //filePath = new String(filePath.getBytes("8859_1"), "utf-8");
    //fileName = new String(fileName.getBytes("8859_1"), "utf-8"); 
    //System.err.println(filePath);
    //System.err.println(fileName);
    System.out.println(" ?  : " + filePath);

    String repositoryPath = StringUtils.replace(filePath + fileName, "__", File.separatorChar + "");

    System.out.println(" ?: " + repositoryPath);
    //      String repositoryPath =StringUtils.replace( propertyService.getString("Globals.folderStorePath")+filePath+fileName,  "__", File.separatorChar+"");
    //       File repository = new File(repositoryPath);

    //      Collection<File> list = FileUtils.listFiles(repository, FileFilterUtils.fileFileFilter(), DirectoryFileFilter.INSTANCE);

    //      ModelAndView mav = new ModelAndView("downloadView");
    //      mav.addObject("downloadFile", new File(repositoryPath));
    //      mav.addObject("fileName", fileName);
    //      return mav;
    FileDownload dextj = new FileDownload(request, res);
    File target = new File(repositoryPath);
    if (target.exists()) {
        dextj.Download(target.getAbsolutePath(), true, false);
    } else {/* w  w  w . jav a  2s .co m*/
        res.sendError(404, fileName.concat(" not found"));
    }
}

From source file:com.devpia.service.DEXTUploadJController.java

/**
  * ?  ? ? virtual.up  ?  ?  ?? /*from w w  w.  ja  va 2 s  .com*/
  * ??? ? ??(?) ??   ?.
  * @param req HttpServletRequest ?
  * @param res HttpServletResponse ?
  * @throws Exception
  */
@RequestMapping(value = "/virtual.up", method = RequestMethod.POST)
public void uploadVirtualDeleted(HttpServletRequest req, HttpServletResponse res) throws Exception {
    req.setCharacterEncoding("utf-8");
    res.setContentType("text/plain");
    res.setCharacterEncoding("utf-8");

    FileUpload dextj = new FileUpload(req, res);

    String appRootPath = null;
    //  ?? ??  ?  ?? ? .
    // ? OS   ?  ?  . (,   ?/  .)
    File temp = new File(getUploadDirectory());
    File repository = new File(getUploadDirectory());

    try {
        //    ?/ ?    ??  .
        if (!temp.exists() || !temp.canRead() || !temp.canWrite()) {
            throw new Exception(
                    "    ?? ?/  ? .");
        }

        //  ?   ?/ ?    ??  .
        if (!repository.exists() || !repository.canRead() || !repository.canWrite()) {
            throw new Exception(
                    "?    ?? ?/  ? .");
        }

        // DEXTUploadJ ?? ?(dextuploadj.config)?  ?? ?  ? .
        // ?     ? .
        appRootPath = req.getSession().getServletContext().getRealPath("/") + "/";
        dextj.setLicenseFilePath(appRootPath.concat("dextuploadj.config"));

        // ?    .
        //     ??    .
        dextj.UploadStart(temp.getAbsolutePath());

        //  ? ? ?? .
        // "DEXTUploadNX_VirtualDeleted"? DEXTUploadNX? ? ? ?? ?  .
        StringBuilder sb = new StringBuilder();

        res.setContentType("text/plain");

        String[] deletedVirtualFileKeys = dextj.getParameterValues("DEXTUploadNX_VirtualDeleted");
        if (deletedVirtualFileKeys != null && deletedVirtualFileKeys.length > 0) {
            boolean first = true;
            for (String value : deletedVirtualFileKeys) {
                if (first == true) {
                    sb.append(value);
                    first = false;
                } else {
                    sb.append(", ".concat(value));
                }
            }
            res.getWriter().write("Deleted files: ".concat(sb.toString()));
        } else {
            res.getWriter().write("Deleted files do not exist.");
        }
    } catch (DEXTUploadException ex) {
        throw new Exception(" ? .", ex);
    } catch (Exception ex) {
        throw new Exception(" ? .", ex);
    } finally {
        //  ?  ???  .
        //    ?? ?  ?  .
        dextj.dispose();
    }
}

From source file:com.devpia.service.DEXTUploadJController.java

/**
  * ?  ? ? virtual.up  ?  ?  ?? /*from  w  w w  .ja va2 s.co  m*/
  * ??? ? ??(?) ??   ?.
  * @param req HttpServletRequest ?
  * @param res HttpServletResponse ?
  * @throws Exception
  */
@RequestMapping(value = "/virtual2.up", method = RequestMethod.POST)
public void uploadVirtualDeleted2(HttpServletRequest req, HttpServletResponse res) throws Exception {
    req.setCharacterEncoding("utf-8");
    res.setContentType("text/plain");
    res.setCharacterEncoding("utf-8");

    FileUpload dextj = new FileUpload(req, res);

    String appRootPath = null;
    //  ?? ??  ?  ?? ? .
    // ? OS   ?  ?  . (,   ?/  .)
    File temp = new File(getUploadDirectory());
    File repository = new File(getUploadDirectory());

    try {
        //    ?/ ?    ??  .
        if (!temp.exists() || !temp.canRead() || !temp.canWrite()) {
            throw new Exception(
                    "    ?? ?/  ? .");
        }

        //  ?   ?/ ?    ??  .
        if (!repository.exists() || !repository.canRead() || !repository.canWrite()) {
            throw new Exception(
                    "?    ?? ?/  ? .");
        }

        // DEXTUploadJ ?? ?(dextuploadj.config)?  ?? ?  ? .
        // ?     ? .
        appRootPath = req.getSession().getServletContext().getRealPath("/") + "/";
        dextj.setLicenseFilePath(appRootPath.concat("dextuploadj.config"));

        // ?    .
        //     ??    .
        dextj.UploadStart(temp.getAbsolutePath());

        //  ? ? ?? .
        // "DEXTUploadNX_VirtualDeleted"? DEXTUploadNX? ? ? ?? ?  .
        StringBuilder sb = new StringBuilder();

        res.setContentType("text/plain");

        String[] deletedVirtualFileKeys = dextj.getParameterValues("DEXTUploadNX_VirtualDeleted");
        if (deletedVirtualFileKeys != null && deletedVirtualFileKeys.length > 0) {
            boolean first = true;
            for (String value : deletedVirtualFileKeys) {
                if (first == true) {
                    sb.append(value);
                    first = false;
                } else {
                    sb.append(", ".concat(value));
                }
            }
            res.getWriter().write("Deleted files: ".concat(sb.toString()));
        } else {
            res.getWriter().write("Deleted files do not exist.");
        }
    } catch (DEXTUploadException ex) {
        throw new Exception(" ? .", ex);
    } catch (Exception ex) {
        throw new Exception(" ? .", ex);
    } finally {
        //  ?  ???  .
        //    ?? ?  ?  .
        dextj.dispose();
    }
}

From source file:com.devpia.service.DEXTUploadJController.java

/**
 * ?  ? ? exifdata.up  ?  ?  ?? //from  w  w w  .  ja  v a 2s .  c  o  m
 * ??? ? ??(?) ?? .
 * @param req HttpServletRequest ?
 * @param res HttpServletResponse ?
 * @throws Exception
 */
@RequestMapping(value = "/exifdata.up", method = RequestMethod.POST)
public void uploadExifData(HttpServletRequest req, HttpServletResponse res) throws Exception {
    req.setCharacterEncoding("utf-8");
    res.setContentType("text/plain");
    res.setCharacterEncoding("utf-8");

    FileUpload dextj = new FileUpload(req, res);

    String appRootPath = null;
    //  ?? ??  ?  ?? ? .
    // ? OS   ?  ?  . (,   ?/  .)
    File temp = new File(getUploadDirectory());
    File repository = new File(getUploadDirectory());

    try {
        //    ?/ ?    ??  .
        if (!temp.exists() || !temp.canRead() || !temp.canWrite()) {
            throw new Exception(
                    "    ?? ?/  ? .");
        }

        //  ?   ?/ ?    ??  .
        if (!repository.exists() || !repository.canRead() || !repository.canWrite()) {
            throw new Exception(
                    "?    ?? ?/  ? .");
        }

        // DEXTUploadJ ?? ?(dextuploadj.config)?  ?? ?  ? .
        // ?     ? .
        appRootPath = req.getSession().getServletContext().getRealPath("/") + "/";
        dextj.setLicenseFilePath(appRootPath.concat("dextuploadj.config"));

        // ?    .
        //     ??    .
        dextj.UploadStart(temp.getAbsolutePath());

        // "DEXTUploadNX"? DEXTUploadNX? ?  ? ??  .
        FileItem[] fileItems = dextj.getFileItemValues("DEXTUploadNX");
        if (fileItems == null)
            fileItems = new FileItem[0];

        // "DEXTUploadNX_ExifData"? DEXTUploadNX? ? EXIF ??  .
        String[] exifData = dextj.getParameterValues("DEXTUploadNX_ExifData");
        if (exifData == null)
            exifData = new String[0];

        // ? ?? .
        for (int i = 0; i < fileItems.length; i++) {
            if (fileItems[i].IsUploaded()) {
                fileItems[i].Save(repository.getAbsolutePath(), true);
                res.getWriter().write("Save : ".concat(fileItems[i].getFileName()));
            }

            if (exifData[i] != null && exifData[i].length() > 0) {
                res.getWriter().write("[SPLIT]");
                res.getWriter().write(exifData[i]);
            }

            res.getWriter().write("[SPLIT]");
        }

    } catch (DEXTUploadException ex) {
        throw new Exception(" ? .", ex);
    } catch (Exception ex) {
        throw new Exception(" ? .", ex);
    } finally {
        //  ?  ???  .
        //    ?? ?  ?  .
        dextj.dispose();
    }
}