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.megaeyes.web.controller.UserController.java

/**
 * @Title: createUser// ww  w . j av a 2  s.  c o m
 * @Description: 
 * @param request
 * @param response
 *            
 * @return void 
 * @throws
 */
@ControllerDescription(description = "", isLog = true, isCheckSession = true)
@RequestMapping("/createUser.json")
public void createUser(HttpServletRequest request, HttpServletResponse response)
        throws UnsupportedEncodingException {
    BaseResponse resp = new BaseResponse();
    request.setCharacterEncoding("UTF-8");
    // License
    resp.setCode(checkUserLicence());

    String logonName = (String) request.getAttribute("logonName");
    String password = (String) request.getAttribute("password");
    String organId = (String) request.getAttribute("organId");
    String accessServerId = (String) request.getAttribute("accessServerId");
    String note = (String) request.getAttribute("note");
    String name = (String) request.getAttribute("name");
    String sex = (String) request.getAttribute("sex");
    Long age = (long) 20;
    String age1 = (String) request.getAttribute("age");
    if (StringUtils.isNotBlank(age1)) {
        try {
            age = Long.parseLong(age1);
        } catch (NumberFormatException be) {
            resp.setCode(ErrorCode.PARAMETER_VALUE_INVALIDED);
            resp.setMessage("age");
        }
    }
    String mobile = (String) request.getAttribute("mobile");
    String phone = (String) request.getAttribute("phone");
    String email = (String) request.getAttribute("email");
    Short isSuspend = 0;
    Long maxSession = (long) 4;
    String maxSession1 = (String) request.getAttribute("maxSession");
    if (StringUtils.isNotBlank(maxSession1)) {
        try {
            maxSession = Long.parseLong(maxSession1);
        } catch (NumberFormatException be) {
            resp.setCode(ErrorCode.PARAMETER_VALUE_INVALIDED);
            resp.setMessage("maxSession");
        }
    }
    String userAccount = "0";
    Short priority = 1;
    String priority1 = (String) request.getAttribute("priority");
    if (StringUtils.isNotBlank(priority1)) {
        try {
            priority = Short.parseShort(priority1);
        } catch (NumberFormatException be) {
            resp.setCode(ErrorCode.PARAMETER_VALUE_INVALIDED);
            resp.setMessage("priority");
        }
    }
    String sipCode = (String) request.getAttribute("sipCode");
    String dispatchServerId = (String) request.getAttribute("dispatchServerId");
    if ("null".equals(dispatchServerId)) {
        dispatchServerId = "";
    }
    // ?
    Short isInnerUser = 1;
    String isInnerUserString = request.getParameter("isInnerUser");
    if (StringUtils.isNotBlank(isInnerUserString)) {
        try {
            isInnerUser = Short.parseShort(isInnerUserString);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            resp.setCode(ErrorCode.PARAMETER_VALUE_INVALIDED);
            resp.setMessage("isInnerUser");
        }
    }
    if (resp.getCode().equals(ErrorCode.SUCCESS)) {
        try {
            String id = userManager.createUser(logonName, password, organId, accessServerId, note, name, sex,
                    age, mobile, phone, email, isSuspend, maxSession, userAccount, priority, sipCode,
                    dispatchServerId, isInnerUser);
            // System.out.println("---------------"+id);
            resp.setCode(ErrorCode.SUCCESS);
            resp.setMessage(id);
        } catch (BusinessException be) {
            resp.setCode(be.getCode());
            resp.setMessage(be.getMessage());
        }
    }
    writePageNoZip(response, resp);
}

From source file:com.google.sampling.experiential.server.EventServlet.java

private void setCharacterEncoding(HttpServletRequest req, HttpServletResponse resp)
        throws UnsupportedEncodingException {
    req.setCharacterEncoding(Charsets.UTF_8.name());
    resp.setCharacterEncoding(Charsets.UTF_8.name());
}

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

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doGet({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);/*from  w w w.  j  a  v a  2s. co  m*/
    ServletContext sc = getServletContext();
    Session session = null;

    try {
        session = HibernateUtil.getSessionFactory().openSession();
        sc.setAttribute("qs", null);
        sc.setAttribute("type", null);
        sc.setAttribute("showSql", null);
        sc.setAttribute("exception", null);
        sc.setAttribute("globalResults", null);
        sc.setAttribute("tables", listTables(session));
        sc.setAttribute("vtables", listVirtualTables());
        sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
    } catch (Exception e) {
        sendError(sc, request, response, e);
    } finally {
        HibernateUtil.close(session);
    }
}

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

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doGet({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);/*from ww  w . ja v  a 2s .  c  o m*/
    ServletContext sc = getServletContext();
    Session session = null;

    try {
        session = HibernateUtil.getSessionFactory().openSession();
        sc.setAttribute("qs", null);
        //sc.setAttribute("sql", null);
        sc.setAttribute("type", null);
        sc.setAttribute("exception", null);
        sc.setAttribute("globalResults", null);
        sc.setAttribute("tables", listTables(session));
        sc.setAttribute("vtables", listVirtualTables());
        sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
    } catch (Exception e) {
        sendError(sc, request, response, e);
    } finally {
        HibernateUtil.close(session);
    }
}

From source file:org.niord.proxy.web.MessageDetailsServlet.java

/**
 * Main GET method/*from   w w w  . j  a va 2  s  .c o m*/
 * @param request servlet request
 * @param response servlet response
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // Determine whether to return HTML or PDF
    boolean pdf = request.getServletPath().endsWith("pdf");

    // Never cache the response
    response = WebUtils.nocache(response);

    // Read the request parameters
    String language = settings.language(request.getParameter("language"));

    // Force the encoding and the locale based on the lang parameter
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    final Locale locale = new Locale(language);
    request = new HttpServletRequestWrapper(request) {
        @Override
        public Locale getLocale() {
            return locale;
        }
    };

    try {
        // Get the messages in the given language for the requested provider
        List<MessageVo> messages = getMessages(request, language);
        String searchText = getSearchText(request, language, messages);

        // Register the attributes to be used on the JSP page
        request.setAttribute("messages", messages);
        request.setAttribute("searchText", searchText);
        request.setAttribute("lang", language);
        request.setAttribute("languages", Arrays.asList(settings.getLanguages()));
        request.setAttribute("language", language);
        request.setAttribute("locale", locale);
        request.setAttribute("timeZone", settings.getTimeZone());
        request.setAttribute("now", new Date());
        request.setAttribute("pdf", pdf);

        if (pdf) {
            generatePdfFile(request, response);
        } else {
            generateHtmlPage(request, response);
        }

    } catch (Exception e) {
        log.log(Level.SEVERE, "Error generating file " + request.getServletPath(), e);
        throw new ServletException("Error generating file " + request.getServletPath(), e);
    }
}

From source file:com.jsmartframework.web.manager.FilterControl.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    httpRequest.setCharacterEncoding(ENCODING);
    httpResponse.setCharacterEncoding(ENCODING);

    // Initiate bean context based on current thread instance
    WebContext.initCurrentInstance(httpRequest, httpResponse);

    // Instantiate request scoped authentication bean
    HANDLER.instantiateAuthBean(httpRequest);

    // Instantiate web security for request extra validation
    HANDLER.instantiateWebSecurity(httpRequest);

    // Anonymous subclass to wrap HTTP response to print output
    WebFilterResponseWrapper responseWrapper = new WebFilterResponseWrapper(httpResponse);

    Throwable throwable = null;//ww w  .  j a  va  2s  .  c  o  m
    try {
        filterChain.doFilter(request, responseWrapper);
    } catch (Throwable thrown) {
        throwable = thrown;
        thrown.printStackTrace();
    }

    // Finalize request scoped web and auth beans
    HANDLER.finalizeBeans(httpRequest, responseWrapper);

    // Check if response was written before closing the WebContext
    boolean responseWritten = WebContext.isResponseWritten();

    // Close bean context based on current thread instance
    WebContext.closeCurrentInstance();

    // Case AsyncBean or RequestPath process was started it cannot proceed because it will not provide HTML via framework
    if (httpRequest.isAsyncStarted() || responseWritten) {

        // Generate response value after flushing the response wrapper buffer
        responseWrapper.flushBuffer();
        String responseVal = responseWrapper.toString();

        // Close current outputStream on responseWrapper
        responseWrapper.close();

        // Write the response value on real response object
        if (!httpResponse.isCommitted()) {
            httpResponse.getWriter().write(responseVal);
        }

        // Case internal server error
        if (throwable != null) {
            if (throwable instanceof IOException) {
                throw new IOException(throwable);
            }
            throw new ServletException(throwable);
        }
        return;
    }

    // Add Ajax headers to control redirect and reset
    addAjaxHeaders(httpRequest, responseWrapper);

    // Generate HTML after flushing the response wrapper buffer
    responseWrapper.flushBuffer();
    String html = completeHtml(httpRequest, responseWrapper);

    // Close current outputStream on responseWrapper
    responseWrapper.close();

    // Case internal server error
    if (throwable != null) {
        responseWrapper.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        if (throwable instanceof IOException) {
            throw new IOException(throwable);
        }
        throw new ServletException(throwable);
    }

    if (StringUtils.isBlank(html)) {
        return;
    }

    if (CONFIG.getContent().isPrintHtml()) {
        LOGGER.log(Level.INFO, html);
    }

    // Compress html to better load performance
    HtmlCompress compressHtml = CONFIG.getContent().getCompressHtml();
    if (compressHtml.isCompressHtml()) {
        HtmlCompressor compressor = new HtmlCompressor();
        compressor.setRemoveComments(!compressHtml.isSkipComments());
        html = compressor.compress(html);
    }

    // Write our modified text to the real response
    if (!httpResponse.isCommitted()) {
        httpResponse.setContentLength(html.getBytes().length);
        httpResponse.getWriter().write(html);
    }
}

From source file:com.mobileman.projecth.web.controller.patient.MedikamenteController.java

@Transactional
@RequestMapping(method = RequestMethod.POST, value = "/patient/medikamente_eingeben")
public String medicamentePost(HttpServletRequest request, HttpServletResponse response, Model model)
        throws UnsupportedEncodingException {
    KeepScroll.save(request, model);/* w ww. java 2  s  .  c o m*/
    // save request parameters into map
    request.setCharacterEncoding("UTF-8");
    ViewState.copyViewState(request, model);
    String diseaseCode = request.getParameter("selectdisease");
    model.addAttribute("selected_disease_code", diseaseCode);

    String selectunits = request.getParameter("selectunits");
    model.addAttribute("selectedUnits", selectunits);

    String takingFrequnecyStr = request.getParameter("select_taking_frequency");
    model.addAttribute("select_taking_frequency", takingFrequnecyStr);
    MedicationFrequency medicationFrequency = (takingFrequnecyStr == null || takingFrequnecyStr.equals("0"))
            ? null
            : MedicationFrequency.valueOf(takingFrequnecyStr);

    String selectedHistoryMedication = request.getParameter("selecthistory");
    model.addAttribute("selected_history_medication", selectedHistoryMedication);

    Long patientMedicationId = NumUtils.convert2long(request.getParameter("patientMedicationId"));
    if (patientMedicationId != null) {
        return medicamenteEditPost(request, response, model, patientMedicationId);
    }

    boolean error = false;

    if (StringUtils.isNotBlank(request.getParameter("search.x"))) {
        model.addAttribute("wasSearch", true);
        // search
        //
        String filter = request.getParameter("filter");
        List<Medication> medications = null;
        try {
            if (StringUtils.isNotBlank(filter)) {
                medications = medicationService.findAllByNameOrPzn(filter, Locale.GERMANY);
            } else {
                // error
                model.addAttribute("errorsearchnodata", true);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            model.addAttribute("errorsearch", true);
        }
        // clear fields
        setupFields(model, null, null, null);
        if (medications != null) {
            // store result
            // if zero clear text boxes
            // if only one save into text boxes
            // if more fill list
            if (medications.size() == 0) {
                model.addAttribute("infosearchnotfound", true);
            } else if (medications.size() == 1) {
                Medication tmp = medications.get(0);
                setupFields(model, tmp.getName(), tmp.getPzn(), tmp.getStandardUnitSize());
                // setup fields
            } else if (medications.size() > 1) {
                // fill combo
                model.addAttribute("searchresult", medications);
            }
        }
    } else {

        model.addAttribute("wasEnter", true);
        Long medid = null;
        // find for mednumer
        String pzn = request.getParameter("pzn");
        try {

            Medication med = medicationService.findByPzn(pzn, Locale.GERMANY);
            if (med != null) {
                medid = med.getId();
            }
        } catch (Exception e) {
        }

        if (medid == null) {
            // insert new medicine
            String name = request.getParameter("name");
            String units = request.getParameter("unitssize");

            if (StringUtils.isBlank(name)) {
                error = true;
                model.addAttribute("errorname", true);
            }
            if (StringUtils.isBlank(units)) {
                error = true;
                model.addAttribute("errorunits", true);
            }

            if (!error) {
                try {
                    Medication med = new Medication();
                    med.setLocale(Locale.GERMANY);
                    med.setName(name);
                    if (pzn != null && pzn.trim().length() > 0) {
                        med.setPzn(new PznBarcode());
                        med.getPzn().setNumber(pzn);
                    }

                    med.setCreatedatetime(new Date());
                    med.setStandardUnitSize(units);
                    medid = medicationService.save(med);
                } catch (Exception e) {
                    // show error
                    model.addAttribute("erroraddmed", true);
                }
            }
        }

        Double units = NumUtils.convert2double(selectunits);
        if (units == null) {
            model.addAttribute("errorselectunits", true);
            error = true;
        }

        if (StringUtils.isBlank(diseaseCode) || "0".equals(diseaseCode)) {
            model.addAttribute("errordisease", true);
            error = true;
        }

        if (medicationFrequency == null) {
            model.addAttribute("error_taking_frequency", true);
            error = true;
        }

        String startDateStr = request.getParameter("consum_start_date");
        String endDateStr = request.getParameter("consum_end_date");

        Date dateStart = DateUtils.normalStr2date(startDateStr);
        Date endDate = DateUtils.normalStr2date(endDateStr);
        if (dateStart == null) {
            model.addAttribute("error_consum_start_date", true);
            error = true;
        }

        if (endDate == null) {
            model.addAttribute("error_consum_end_date", true);
            error = true;
        }

        if (dateStart != null && endDate != null) {
            if (endDate.before(dateStart)) {
                model.addAttribute("error_consum_end_date", true);
                error = true;
            }
        }

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

        if (!error && medid != null) {
            Disease disease = diseasService.findByCode(diseaseCode);
            Patient patient = new DataHolder(request).getPatient();

            try {
                patientMedicationService.addConsumedMedication(patient.getId(), disease.getId(), medid, units,
                        medicationFrequency, dateStart, endDate, comment);

                model.addAttribute("infoconsume", true);
            } catch (Exception ex) {
                model.addAttribute("errorconsume", true);
            }
        }
    }

    String result = medicamenteEingebenGet(request, response, model);
    if (!error) {
        setupFields(model, null, null, null);
    }

    return result;
}

From source file:isl.FIMS.servlet.export.ExportSchema.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w  w w . j  av a 2  s . c  om*/
 *
 * @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 {
    this.initVars(request);
    String username = getUsername(request);

    boolean isGuest = this.getRights(username).equals("guest");
    if (!isGuest) {
        try {
            String filePath = this.export_import_Folder;
            java.util.Date date = new java.util.Date();
            Timestamp t = new Timestamp(date.getTime());
            String currentDir = filePath + t.toString().replaceAll(":", "").replaceAll("\\s", "");
            File saveDir = new File(currentDir);
            saveDir.mkdir();
            Config conf = new Config("ExportSchema");
            String type = request.getParameter("type");
            request.setCharacterEncoding("UTF-8");

            ServletOutputStream outStream = response.getOutputStream();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=\"" + "Schema_" + type + ".zip\"");
            File schemaFile = new File(this.schemaFolder + type + ".xsd");
            FileUtils.copyFile(schemaFile,
                    new File(currentDir + System.getProperty("file.separator") + type + ".xsd"));
            Utils.copySchemaReferences(this.schemaFolder + type + ".xsd", currentDir);

            File f = new File(currentDir + System.getProperty("file.separator") + "zip");
            f.mkdir();
            String zip = f.getAbsolutePath() + System.getProperty("file.separator") + "Schema_" + type + ".zip";

            Utils.createZip(zip, currentDir);
            Utils.downloadZip(outStream, new File(zip));

            Utils.deleteDir(currentDir);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.exilant.exility.core.HttpRequestHandler.java

/***
 * We accept only POST requests./*from   ww  w  .  j ava2 s  .c  o  m*/
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // set the character encoding...
    request.setCharacterEncoding(CommonFieldNames.CHAR_ENCODING);
    response.setCharacterEncoding(CommonFieldNames.CHAR_ENCODING);
    response.setHeader(CACHE_CONTROL, NO_CACHE);
    try {
        MyAssistant assistant = new MyAssistant(request, response);
        String log = assistant.processRequest();
        System.out.println("Log \n" + log);
    } catch (Exception e) {

        /**
         * TODO : we have to use error reporting infrastructure and probably
         * create a ticket...
         */
        System.out.println("Server exception " + e.getMessage());
        e.printStackTrace();
        response.getWriter().write(
                "Sorry, we are unable to service your request due to an internal error on the server. Some one is looking at the issue right away. Please retry your request after some time.");
    }
}

From source file:org.openmeetings.servlet.outputhandler.DownloadHandler.java

@Override
protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    try {//from   www  .  j av a 2 s  .com

        if (getUserManagement() == null || getSessionManagement() == null) {
            return;
        }

        httpServletRequest.setCharacterEncoding("UTF-8");

        log.debug("\nquery = " + httpServletRequest.getQueryString());
        log.debug("\n\nfileName = " + httpServletRequest.getParameter("fileName"));
        log.debug("\n\nparentPath = " + httpServletRequest.getParameter("parentPath"));

        String queryString = httpServletRequest.getQueryString();
        if (queryString == null) {
            queryString = "";
        }

        String sid = httpServletRequest.getParameter("sid");

        if (sid == null) {
            sid = "default";
        }
        log.debug("sid: " + sid);

        Long users_id = getSessionManagement().checkSession(sid);
        Long user_level = getUserManagement().getUserLevelByID(users_id);

        if (user_level != null && user_level > 0) {
            String room_id = httpServletRequest.getParameter("room_id");
            if (room_id == null) {
                room_id = "default";
            }

            String moduleName = httpServletRequest.getParameter("moduleName");
            if (moduleName == null) {
                moduleName = "nomodule";
            }

            String parentPath = httpServletRequest.getParameter("parentPath");
            if (parentPath == null) {
                parentPath = "nomodule";
            }

            String requestedFile = httpServletRequest.getParameter("fileName");
            if (requestedFile == null) {
                requestedFile = "";
            }

            String fileExplorerItemIdParam = httpServletRequest.getParameter("fileExplorerItemId");
            Long fileExplorerItemId = null;
            if (fileExplorerItemIdParam != null) {
                fileExplorerItemId = Long.parseLong(fileExplorerItemIdParam);
            }

            // make a complete name out of domain(organisation) + roomname
            String roomName = room_id;
            // trim whitespaces cause it is a directory name
            roomName = StringUtils.deleteWhitespace(roomName);

            // Get the current User-Directory

            String current_dir = getServletContext().getRealPath("/");

            String working_dir = "";

            working_dir = current_dir + OpenmeetingsVariables.UPLOAD_DIR + File.separatorChar;

            // Add the Folder for the Room
            if (moduleName.equals("lzRecorderApp")) {
                working_dir = current_dir + OpenmeetingsVariables.STREAMS_DIR + File.separatorChar + "hibernate"
                        + File.separatorChar;
            } else if (moduleName.equals("videoconf1")) {
                if (parentPath.length() != 0) {
                    if (parentPath.equals("/")) {
                        working_dir = working_dir + roomName + File.separatorChar;
                    } else {
                        working_dir = working_dir + roomName + File.separatorChar + parentPath
                                + File.separatorChar;
                    }
                } else {
                    working_dir = current_dir + roomName + File.separatorChar;
                }
            } else if (moduleName.equals("userprofile")) {
                working_dir += "profiles" + File.separatorChar;
                logNonExistentFolder(working_dir);

                working_dir += ScopeApplicationAdapter.profilesPrefix + users_id + File.separatorChar;
                logNonExistentFolder(working_dir);
            } else if (moduleName.equals("remoteuserprofile")) {
                working_dir += "profiles" + File.separatorChar;
                logNonExistentFolder(working_dir);

                String remoteUser_id = httpServletRequest.getParameter("remoteUserid");
                if (remoteUser_id == null) {
                    remoteUser_id = "0";
                }

                working_dir += ScopeApplicationAdapter.profilesPrefix + remoteUser_id + File.separatorChar;
                logNonExistentFolder(working_dir);
            } else if (moduleName.equals("remoteuserprofilebig")) {
                working_dir += "profiles" + File.separatorChar;
                logNonExistentFolder(working_dir);

                String remoteUser_id = httpServletRequest.getParameter("remoteUserid");
                if (remoteUser_id == null) {
                    remoteUser_id = "0";
                }

                working_dir += ScopeApplicationAdapter.profilesPrefix + remoteUser_id + File.separatorChar;
                logNonExistentFolder(working_dir);

                requestedFile = this.getBigProfileUserName(working_dir);

            } else if (moduleName.equals("chat")) {

                working_dir += "profiles" + File.separatorChar;
                logNonExistentFolder(working_dir);

                String remoteUser_id = httpServletRequest.getParameter("remoteUserid");
                if (remoteUser_id == null) {
                    remoteUser_id = "0";
                }

                working_dir += ScopeApplicationAdapter.profilesPrefix + remoteUser_id + File.separatorChar;
                logNonExistentFolder(working_dir);

                requestedFile = this.getChatUserName(working_dir);
            } else {
                working_dir = working_dir + roomName + File.separatorChar;
            }

            if (!moduleName.equals("nomodule")) {

                log.debug("requestedFile: " + requestedFile + " current_dir: " + working_dir);

                String full_path = working_dir + requestedFile;

                File f = new File(full_path);

                // If the File does not exist or is not readable show/load a
                // place-holder picture

                if (!f.exists() || !f.canRead()) {
                    if (!f.canRead()) {
                        log.debug("LOG DownloadHandler: The request file is not readable");
                    } else {
                        log.debug(
                                "LOG DownloadHandler: The request file does not exist / has already been deleted");
                    }
                    log.debug("LOG ERROR requestedFile: " + requestedFile);
                    // replace the path with the default picture/document

                    if (requestedFile.endsWith(".jpg")) {
                        log.debug("LOG endsWith d.jpg");

                        log.debug("LOG moduleName: " + moduleName);

                        requestedFile = DownloadHandler.defaultImageName;
                        if (moduleName.equals("remoteuserprofile")) {
                            requestedFile = DownloadHandler.defaultProfileImageName;
                        } else if (moduleName.equals("remoteuserprofilebig")) {
                            requestedFile = DownloadHandler.defaultProfileImageNameBig;
                        } else if (moduleName.equals("userprofile")) {
                            requestedFile = DownloadHandler.defaultProfileImageName;
                        } else if (moduleName.equals("chat")) {
                            requestedFile = DownloadHandler.defaultChatImageName;
                        }
                        // request for an image
                        full_path = current_dir + "default" + File.separatorChar + requestedFile;
                    } else if (requestedFile.endsWith(".swf")) {
                        requestedFile = DownloadHandler.defaultSWFName;
                        // request for a SWFPresentation
                        full_path = current_dir + "default" + File.separatorChar
                                + DownloadHandler.defaultSWFName;
                    } else {
                        // Any document, must be a download request
                        // OR a Moodle Loggedin User
                        requestedFile = DownloadHandler.defaultImageName;
                        full_path = current_dir + "default" + File.separatorChar
                                + DownloadHandler.defaultImageName;
                    }
                }

                log.debug("full_path: " + full_path);

                File f2 = new File(full_path);
                if (!f2.exists() || !f2.canRead()) {
                    if (!f2.canRead()) {
                        log.debug(
                                "DownloadHandler: The request DEFAULT-file does not exist / has already been deleted");
                    } else {
                        log.debug(
                                "DownloadHandler: The request DEFAULT-file does not exist / has already been deleted");
                    }
                    // no file to handle abort processing
                    return;
                }
                // Requested file is outside OM webapp folder
                File curDirFile = new File(current_dir);
                if (!f2.getCanonicalPath().startsWith(curDirFile.getCanonicalPath())) {
                    throw new Exception("Invalid file requested: f2.cp == " + f2.getCanonicalPath()
                            + "; curDir.cp == " + curDirFile.getCanonicalPath());
                }

                // Get file and handle download
                RandomAccessFile rf = new RandomAccessFile(full_path, "r");

                // Default type - Explorer, Chrome and others
                int browserType = 0;

                // Firefox and Opera browsers
                if (httpServletRequest.getHeader("User-Agent") != null) {
                    if ((httpServletRequest.getHeader("User-Agent").contains("Firefox"))
                            || (httpServletRequest.getHeader("User-Agent").contains("Opera"))) {
                        browserType = 1;
                    }
                }

                log.debug("Detected browser type:" + browserType);

                httpServletResponse.reset();
                httpServletResponse.resetBuffer();
                OutputStream out = httpServletResponse.getOutputStream();

                if (requestedFile.endsWith(".swf")) {
                    // trigger download to SWF => THIS is a workaround for
                    // Flash Player 10, FP 10 does not seem
                    // to accept SWF-Downloads with the Content-Disposition
                    // in the Header
                    httpServletResponse.setContentType("application/x-shockwave-flash");
                    httpServletResponse.setHeader("Content-Length", "" + rf.length());
                } else {
                    httpServletResponse.setContentType("APPLICATION/OCTET-STREAM");

                    String fileNameResult = requestedFile;
                    if (fileExplorerItemId != null && fileExplorerItemId > 0) {
                        FileExplorerItem fileExplorerItem = getFileExplorerItemDaoImpl()
                                .getFileExplorerItemsById(fileExplorerItemId);
                        if (fileExplorerItem != null) {

                            fileNameResult = fileExplorerItem.getFileName().substring(0,
                                    fileExplorerItem.getFileName().length() - 4)
                                    + fileNameResult.substring(fileNameResult.length() - 4,
                                            fileNameResult.length());

                        }
                    }

                    if (browserType == 0) {
                        httpServletResponse.setHeader("Content-Disposition",
                                "attachment; filename=" + java.net.URLEncoder.encode(fileNameResult, "UTF-8"));
                    } else {
                        httpServletResponse.setHeader("Content-Disposition", "attachment; filename*=UTF-8'en'"
                                + java.net.URLEncoder.encode(fileNameResult, "UTF-8"));
                    }

                    httpServletResponse.setHeader("Content-Length", "" + rf.length());
                }

                byte[] buffer = new byte[1024];
                int readed = -1;

                while ((readed = rf.read(buffer, 0, buffer.length)) > -1) {
                    out.write(buffer, 0, readed);
                }

                rf.close();

                out.flush();
                out.close();

            }
        } else {
            System.out.println("ERROR DownloadHandler: not authorized FileDownload " + (new Date()));
        }

    } catch (Exception er) {
        log.error("Error downloading: ", er);
        // er.printStackTrace();
    }
}