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:seava.j4e.web.controller.ui.extjs.UiExtjsFrameController.java

/**
 * Handler to return the cached js file with the dependent components.
 * /*from w ww.j  a va2  s . c om*/
 * @param bundle
 * @param frame
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/{bundle}/{frame}.js", method = RequestMethod.GET)
@ResponseBody
public String frameCmpJs(@PathVariable("bundle") String bundle, @PathVariable("frame") String frame,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    try {
        @SuppressWarnings("unused")
        ISessionUser su = (ISessionUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    } catch (java.lang.ClassCastException e) {
        throw new NotAuthorizedRequestException("Not authenticated");
    }

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");

    String fileName = frame + ".js";
    File f = new File(this.cacheFolder + "/" + bundle + "." + fileName);

    if (!f.exists()) {
        DependencyLoader loader = this.getDependencyLoader(request);
        loader.packFrameCmp(bundle, frame, f);
    }

    this.sendFile(f, response.getOutputStream());

    return null;
}

From source file:com.wx.CoacherWXServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  ww w .  ja  v  a 2s.c  o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String sToken = "testToken1";
    String sCorpID = "wxe706b25abb1216c0";
    String sEncodingAESKey = "R5zQRNXirEIQsSGL5Hs5ydZdSuu7EkRLWLViul1P7si";
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    String msg_signature = request.getParameter("msg_signature");
    String timestamp = request.getParameter("timestamp");
    String nonce = request.getParameter("nonce");
    InputStream inputStream = request.getInputStream();
    String postData = IOUtils.toString(inputStream, "UTF-8");
    System.out.println(postData);
    String msg = "";
    WXBizMsgCrypt wxcpt = null;
    try {
        wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);
        //?
        msg = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, postData);
    } catch (AesException e) {
        e.printStackTrace();
    }
    System.out.println("msg=" + msg);
    BaseMessage respMessage = CoreService.processRequest(msg, classService);
    String resMsg = null;
    /** if (request.getSession().getAttribute("accessToken") == null) {
    try {
        String accessToken = CoreService.getAccessToken(config.getInitParameter("corpid"), config.getInitParameter("corpsecret"));
        request.getSession().setAttribute("accessToken", accessToken);
        QyWxURLUtil.applyAccessToken(accessToken);
    } catch (Exception ex) {
        Logger.getLogger(TestWXServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
     }
     **/
    /**
     * UploadMediaReturnMessage uploadMediaReturnMsg; try {
     * uploadMediaReturnMsg = WXUtils.send("image",
     * "/root/WXMedia/anranhui520/1.jpg");
     * if("null".equals(uploadMediaReturnMsg.getErrcode())){
     * System.out.println("Media_id:"+uploadMediaReturnMsg.getMedia_id());
     * }else{ System.out.println("Upload error
     * message:"+uploadMediaReturnMsg.getErrmsg()+" error
     * code:"+uploadMediaReturnMsg.getErrcode());
     *
     * }
     * } catch (Exception ex) {
     * Logger.getLogger(TestWXServlet.class.getName()).log(Level.SEVERE,
     * null, ex); }
    *
     */
    if (respMessage instanceof TextMessage) {
        /*try {
        TextMessage txtMsg = (TextMessage) respMessage;
                
        String command = txtMsg.getContent();
                
        CheckCommandReturnMessage ccReturnMsg = CMDService.processCheckingCommand(command);
        Set<UserInfo> userInfoSet = ccReturnMsg.getUserInfos();
        UserInfo userif = null;
        for (UserInfo userInfo : userInfoSet) {
            userif = userInfo;
        }
                
        System.out.println("msgContent:" + ccReturnMsg.getContent());
        System.out.println("weixinid:" + userif.getWeixinid());
                
        try {
                
            UploadMediaReturnMessage uploadMediaReturnMsg = null;
            try {
                QRCodeGenerator.encode(ccReturnMsg.getContent(), "/root/WXMedia/"+userif.getWeixinid());
                        
                uploadMediaReturnMsg = WXUtils.send("image", "/root/WXMedia/"+userif.getWeixinid()+"/qrcode.jpg");
                if ("null".equals(uploadMediaReturnMsg.getErrcode())) {
                    System.out.println("Media_id:" + uploadMediaReturnMsg.getMedia_id());
                } else {
                    System.out.println("Upload error message:" + uploadMediaReturnMsg.getErrmsg() + " error code:" + uploadMediaReturnMsg.getErrcode());
                
                }
            } catch (Exception ex) {
                Logger.getLogger(CustomerWXServlet.class.getName()).log(Level.SEVERE, null, ex);
            }*/

        /**
         * TextSendMessage textMsg = new TextSendMessage(); String
         * msgtxt = ccReturnMsg.getContent();
         * textMsg.setTextContent(msgtxt);
         * textMsg.setMsgtype("text");
         * textMsg.setTouser(userif.getWeixinid());
         * textMsg.setAgentid(Long.parseLong(config.getInitParameter("checkingAgentId"))); *
         */
        /*  ImageSendMessage imgMsg = new ImageSendMessage();
          imgMsg.setImageMedia(uploadMediaReturnMsg.getMedia_id());
          imgMsg.setMsgtype("image");
          imgMsg.setTouser(userif.getWeixinid());
          imgMsg.setAgentid(Long.parseLong(config.getInitParameter("checkingAgentId")));
                
          AccessTokenReturnMessage returnMsg = CoreService.sendMessage(imgMsg);
        } catch (Exception ex) {
          Logger.getLogger(CustomerWXServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        } catch (Exception ex) {
        Logger.getLogger(CustomerWXServlet.class.getName()).log(Level.SEVERE, null, ex);
        }*/
    } else if (respMessage instanceof NewsMessage) {
        System.out.println("enter NewsMessage.");
        NewsMessage newsMsg = (NewsMessage) respMessage;
        resMsg = MessageUtil.newsMessageToXml(newsMsg);
        System.out.println("ResMsg:" + resMsg);
    }
    PrintWriter out = response.getWriter();
    out.print(resMsg);
    out.flush();
    out.close();
}

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

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    // explicitly set character encoding
    req.setCharacterEncoding("UTF-8");
    res.setCharacterEncoding("UTF-8");

    if (!isAuthorized(req)) {
        BasicAuth.setRequestAuthorizationHeaders(res, "LoggingServlet");
        return;/*  w  w w. ja va2 s. c  o  m*/
    }

    String requestURI = req.getRequestURI();

    if (!requestURI.endsWith("/")) {
        res.sendRedirect(requestURI + "/");
        return;
    }

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

    try {
        if (isJDK14Log) {
            templateParams.put("logLevels", Arrays.asList(jdk14Levels));
        } else if (isLog4jLog) {
            templateParams.put("logLevels", Arrays.asList(log4jLevels));
        }

        templateParams.put("loggerInUse", log);
        Map<String, LoggerLevelInfo> loggerLevelInfosMap = getLoggerLevelInfosMap();
        templateParams.put("loggerLevelInfosMap", loggerLevelInfosMap);
    } catch (Exception ex) {
        templateParams.put("exception", ex);
    } finally {
        try {
            renderTemplatePage(req, res, getRenderTemplate(req), templateParams);
        } catch (Exception te) {
            log.warn("Failed to render freemarker template.", te);
        }
    }
}

From source file:com.ikon.servlet.admin.LanguageServlet.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 userId = request.getRemoteUser();
    updateSessionManager(request);/*w  w  w.j  ava 2 s.  co  m*/

    try {
        if (action.equals("edit")) {
            edit(userId, request, response);
        } else if (action.equals("delete")) {
            delete(userId, request, response);
        } else if (action.equals("create")) {
            create(userId, request, response);
        } else if (action.equals("translate")) {
            translate(userId, request, response);
        } else if (action.equals("flag")) {
            flag(userId, request, response);
        } else if (action.equals("export")) {
            export(userId, request, response);
        } else if (action.equals("addTranslation")) {
            addTranslation(userId, request, response);
        }

        if (action.equals("") || WebUtils.getBoolean(request, "persist")) {
            list(userId, request, response);
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:be.fedict.eid.idp.sp.protocol.openid.AuthenticationResponseServlet.java

@SuppressWarnings("unchecked")
private void doIdRes(HttpServletRequest request, HttpServletResponse response)
        throws MessageException, DiscoveryException, AssociationException, IOException, ServletException {
    LOG.debug("id_res");
    LOG.debug("request URL: " + request.getRequestURL());

    // force UTF-8 encoding
    try {//w ww.  ja  v a  2 s .  c  om
        request.setCharacterEncoding("UTF8");
        response.setCharacterEncoding("UTF8");
    } catch (UnsupportedEncodingException e) {
        throw new MessageException(e);
    }

    ParameterList parameterList = new ParameterList(request.getParameterMap());
    DiscoveryInformation discovered = (DiscoveryInformation) request.getSession().getAttribute("openid-disc");
    LOG.debug("request context path: " + request.getContextPath());
    LOG.debug("request URI: " + request.getRequestURI());
    String receivingUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getLocalPort()
            + request.getRequestURI();
    String queryString = request.getQueryString();
    if (queryString != null && queryString.length() > 0) {
        receivingUrl += "?" + queryString;
    }
    LOG.debug("receiving url: " + receivingUrl);
    ConsumerManager consumerManager = AuthenticationRequestServlet.getConsumerManager(request);
    VerificationResult verificationResult = consumerManager.verify(receivingUrl, parameterList, discovered);
    Identifier identifier = verificationResult.getVerifiedId();
    if (null != identifier) {

        Date authenticationTime = null;
        String userId = identifier.getIdentifier();
        List<String> authnPolicies = new LinkedList<String>();
        Map<String, Object> attributeMap = new HashMap<String, Object>();
        LOG.debug("userId: " + userId);
        Message authResponse = verificationResult.getAuthResponse();

        // verify return_to nonce
        AuthSuccess authResp = AuthSuccess.createAuthSuccess(parameterList);

        String returnTo = authResp.getReturnTo();
        String requestReturnTo = (String) request.getSession()
                .getAttribute(AuthenticationRequestServlet.RETURN_TO_SESSION_ATTRIBUTE);
        if (null == returnTo || null == requestReturnTo) {
            showErrorPage("Insufficient args for validation of " + " \"openid.return_to\".", null, request,
                    response);
            return;
        }
        if (!consumerManager.verifyReturnTo(requestReturnTo, authResp)) {
            showErrorPage("Invalid \"return_to\" in response!", null, request, response);
            return;
        }
        // cleanup
        request.getSession().removeAttribute(AuthenticationRequestServlet.RETURN_TO_SESSION_ATTRIBUTE);

        // AX
        if (authResponse.hasExtension(AxMessage.OPENID_NS_AX)) {

            MessageExtension messageExtension = authResponse.getExtension(AxMessage.OPENID_NS_AX);
            if (messageExtension instanceof FetchResponse) {

                FetchResponse fetchResponse = (FetchResponse) messageExtension;

                Map<String, String> attributeTypes = fetchResponse.getAttributeTypes();
                for (Map.Entry<String, String> entry : attributeTypes.entrySet()) {
                    attributeMap.put(entry.getValue(), fetchResponse.getAttributeValue(entry.getKey()));
                }

            }

        }

        // PAPE
        if (authResponse.hasExtension(PapeResponse.OPENID_NS_PAPE)) {

            MessageExtension messageExtension = authResponse.getExtension(PapeResponse.OPENID_NS_PAPE);
            if (messageExtension instanceof PapeResponse) {

                PapeResponse papeResponse = (PapeResponse) messageExtension;

                authnPolicies = papeResponse.getAuthPoliciesList();
                authenticationTime = papeResponse.getAuthDate();

            }
        }

        OpenIDAuthenticationResponse openIDAuthenticationResponse = new OpenIDAuthenticationResponse(
                authenticationTime, userId, authnPolicies, attributeMap);
        request.getSession().setAttribute(this.responseSessionAttribute, openIDAuthenticationResponse);

        response.sendRedirect(request.getContextPath() + this.redirectPage);
    } else {
        showErrorPage("No verified identifier", null, request, response);
    }
}

From source file:seava.j4e.web.controller.ui.extjs.UiExtjsFrameController.java

/**
 * Handler to return the cached js file with the dependent translations.
 * //  w ww.  j a v  a2 s .  com
 * @param bundle
 * @param frame
 * @param language
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/{bundle}/{language}/{frame}.js", method = RequestMethod.GET)
@ResponseBody
public String frameTrlJs(@PathVariable("bundle") String bundle, @PathVariable("frame") String frame,
        @PathVariable("language") String language, HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    try {
        @SuppressWarnings("unused")
        ISessionUser su = (ISessionUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    } catch (java.lang.ClassCastException e) {
        throw new NotAuthorizedRequestException("Not authenticated");
    }

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");

    String fileName = frame + "-" + language + ".js";
    File f = new File(this.cacheFolder + "/" + bundle + "." + fileName);
    if (!f.exists()) {
        DependencyLoader loader = this.getDependencyLoader(request);
        loader.packFrameTrl(bundle, frame, language, f);
    }

    this.sendFile(f, response.getOutputStream());
    return null;
}

From source file:com.github.thorqin.toolkit.web.utility.UploadManager.java

/**
 * Save upload file to disk/*from ww  w.  j  a  v a  2s. c o  m*/
 * @param request HttpServletRequest
 * @param maxSize maximum size of the upload file, in bytes.
 * @return Saved file info list
 * @throws ServletException
 * @throws IOException
 * @throws FileUploadException
 */
public List<FileInfo> saveUploadFiles(HttpServletRequest request, int maxSize)
        throws ServletException, IOException, FileUploadException {
    List<FileInfo> uploadList = new LinkedList<>();
    request.setCharacterEncoding("utf-8");
    ServletFileUpload upload = new ServletFileUpload();
    upload.setHeaderEncoding("UTF-8");
    if (!ServletFileUpload.isMultipartContent(request)) {
        return uploadList;
    }
    upload.setSizeMax(maxSize);
    FileItemIterator iterator = upload.getItemIterator(request);
    while (iterator.hasNext()) {
        FileItemStream item = iterator.next();
        try (InputStream stream = item.openStream()) {
            if (!item.isFormField()) {
                FileInfo info = new FileInfo();
                info.setFileName(item.getName());
                if (pattern != null && !pattern.matcher(info.fileName).matches()) {
                    continue;
                }
                info = store(stream, info.fileName);
                uploadList.add(info);
            }
        }
    }
    return uploadList;
}

From source file:org.jboss.dashboard.ui.controller.ControllerServlet.java

/**
 * Process incoming HTTP requests/* w  w w .  j  av a 2s  .c  o  m*/
 *
 * @param request  Object that encapsulates the request to the servlet.
 * @param response Object that encapsulates the response from the servlet.
 */
public final void service(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    if (initSuccess) {
        Factory.doWork(new FactoryWork() {
            public void doWork() {
                try {
                    HTTPSettings webSettings = HTTPSettings.lookup();
                    request.setCharacterEncoding(webSettings.getEncoding());
                } catch (UnsupportedEncodingException e) {
                    log.error("Error: ", e);
                }

                // Init the request context.
                ControllerServletHelper helper = ControllerServletHelper.lookup();
                CommandRequest cmdRq = helper.initThreadLocal(request, response);
                ControllerStatus.lookup().setRequest(cmdRq);

                // Begin the profiling trace.
                CodeBlockTrace trace = new RequestTrace().begin(request);
                try {
                    // Process the request (control layer)
                    processTheRequest(request, response);

                    // Render the view (presentation layer)
                    processTheView(request, response);
                } finally {
                    // End the profiling trace.
                    trace.end();

                    // Clear the request context.
                    helper.clearThreadLocal(request, response);
                }
            }
        });
    } else {
        log.error("Received request, but application servlet hasn't been properly initialized. Ignoring.");
        response.sendError(500, "Application incorrectly initialized.");
    }
}

From source file:org.guvnor.common.services.backend.file.upload.AbstractFileServlet.java

/**
 * Get the form data from the inbound request.
 *//*  w  ww .j  av a2 s .  co  m*/
@SuppressWarnings("rawtypes")
private FormData getFormData(final HttpServletRequest request) throws IOException {
    final FileItemFactory factory = new DiskFileItemFactory();
    final ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");

    //See https://code.google.com/p/google-web-toolkit/issues/detail?id=4682
    request.setCharacterEncoding("UTF-8");

    final FormData data = new FormData();
    try {
        final List items = upload.parseRequest(request);
        final Iterator it = items.iterator();

        FileOperation operation = null;
        String fileName = null;
        String contextPath = null;
        String fullPath = null;

        while (it.hasNext()) {
            final FileItem item = (FileItem) it.next();
            if (!item.isFormField()) {
                data.setFile(item);
            } else if (item.getFieldName().equals(FileManagerFields.FORM_FIELD_PATH)) {
                contextPath = item.getString("UTF-8");
                log.debug("path:" + contextPath);
            } else if (item.getFieldName().equals(FileManagerFields.FORM_FIELD_NAME)) {
                fileName = item.getString("UTF-8");
                log.debug("name:" + fileName);
            } else if (item.getFieldName().equals(FileManagerFields.FORM_FIELD_FULL_PATH)) {
                fullPath = item.getString("UTF-8");
                log.debug("full path:" + fullPath);
            } else if (item.getFieldName().equals(FileManagerFields.FORM_FIELD_OPERATION)) {
                operation = FileOperation.valueOf(item.getString("UTF-8"));
                log.debug("operation:" + operation);
            }
        }

        if (operation == null) {
            throw new IllegalArgumentException("FORM_FIELD_OPERATION is null. Cannot process upload.");
        }

        org.uberfire.java.nio.file.Path path;
        switch (operation) {
        case CREATE:
            if (fileName == null) {
                throw new IllegalArgumentException("FORM_FIELD_NAME is null. Cannot process upload.");
            }
            if (contextPath == null) {
                throw new IllegalArgumentException("FORM_FIELD_PATH is null. Cannot process upload.");
            }
            data.setOperation(operation);
            data.setTargetPath(convertPath(fileName, contextPath));
            break;
        case UPDATE:
            if (fullPath == null) {
                throw new IllegalArgumentException("FORM_FIELD_FULL_PATH is null. Cannot process upload.");
            }
            data.setOperation(operation);
            data.setTargetPath(convertPath(fullPath));
        }

        return data;

    } catch (Exception e) {
        throw new org.uberfire.java.nio.IOException(e.getMessage());
    }
}

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

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from  ww  w  .j av  a  2  s. c o m*/
        request.setCharacterEncoding(StandardCharsets.UTF_8.name());

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

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

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

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

        Long users_id = getBean(SessiondataDao.class).check(sid);
        Set<Right> rights = getBean(UserDao.class).getRights(users_id);

        if (rights != null && !rights.isEmpty()) {
            String room_id = request.getParameter("room_id");
            if (room_id == null) {
                room_id = "default";
            }

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

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

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

            String fileIdParam = request.getParameter("fileId");
            Long fileId = null;
            if (fileIdParam != null) {
                fileId = Long.valueOf(fileIdParam);
            }

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

            // Get the current User-Directory

            File working_dir;

            // Add the Folder for the Room
            if (moduleName.equals("lzRecorderApp")) {
                working_dir = OmFileHelper.getStreamsHibernateDir();
            } else if (moduleName.equals("videoconf1")) {
                working_dir = OmFileHelper.getUploadRoomDir(roomName);
                if (parentPath.length() != 0 && !parentPath.equals("/")) {
                    working_dir = new File(working_dir, parentPath);
                }
            } else if (moduleName.equals("userprofile")) {
                working_dir = OmFileHelper.getUploadProfilesUserDir(users_id);
                logNonExistentFolder(working_dir);
            } else if (moduleName.equals("remoteuserprofile")) {
                String remoteUser_id = request.getParameter("remoteUserid");
                working_dir = OmFileHelper
                        .getUploadProfilesUserDir(remoteUser_id == null ? "0" : remoteUser_id);
                logNonExistentFolder(working_dir);
            } else if (moduleName.equals("remoteuserprofilebig")) {
                String remoteUser_id = request.getParameter("remoteUserid");
                working_dir = OmFileHelper
                        .getUploadProfilesUserDir(remoteUser_id == null ? "0" : remoteUser_id);
                logNonExistentFolder(working_dir);

                requestedFile = getBigProfileUserName(working_dir);
            } else if (moduleName.equals("chat")) {
                String remoteUser_id = request.getParameter("remoteUserid");
                working_dir = OmFileHelper
                        .getUploadProfilesUserDir(remoteUser_id == null ? "0" : remoteUser_id);
                logNonExistentFolder(working_dir);

                requestedFile = getChatUserName(working_dir);
            } else {
                working_dir = OmFileHelper.getUploadRoomDir(roomName);
            }

            if (!moduleName.equals("nomodule")) {
                log.debug("requestedFile: " + requestedFile + " current_dir: " + working_dir);

                File full_path = new File(working_dir, requestedFile);

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

                if (!full_path.exists() || !full_path.canRead()) {
                    if (!full_path.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 = defaultImageName;
                        if (moduleName.equals("remoteuserprofile")) {
                            requestedFile = defaultProfileImageName;
                        } else if (moduleName.equals("remoteuserprofilebig")) {
                            requestedFile = defaultProfileImageNameBig;
                        } else if (moduleName.equals("userprofile")) {
                            requestedFile = defaultProfileImageName;
                        } else if (moduleName.equals("chat")) {
                            requestedFile = defaultChatImageName;
                        }
                    } else if (requestedFile.endsWith(".swf")) {
                        requestedFile = defaultSWFName;
                    } else {
                        requestedFile = defaultImageName;
                    }
                    full_path = new File(OmFileHelper.getDefaultDir(), requestedFile);
                }

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

                if (!full_path.exists() || !full_path.canRead()) {
                    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 = OmFileHelper.getOmHome();
                if (!full_path.getCanonicalPath().startsWith(curDirFile.getCanonicalPath())) {
                    throw new Exception("Invalid file requested: f2.cp == " + full_path.getCanonicalPath()
                            + "; curDir.cp == " + curDirFile.getCanonicalPath());
                }

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

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

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

                response.reset();
                response.resetBuffer();
                try (OutputStream out = response.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
                        response.setContentType("application/x-shockwave-flash");
                        response.setHeader("Content-Length", "" + full_path.length());
                    } else {
                        response.setContentType("APPLICATION/OCTET-STREAM");

                        String fileNameResult = requestedFile;
                        if (fileId != null && fileId > 0) {
                            FileExplorerItem fileExplorerItem = getBean(FileExplorerItemDao.class).get(fileId);
                            if (fileExplorerItem != null) {

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

                            }
                        }

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

                        response.setHeader("Content-Length", "" + full_path.length());
                    }

                    OmFileHelper.copyFile(full_path, out);
                    out.flush();
                }
            }
        } else {
            log.error("ERROR DownloadHandler: not authorized FileDownload ");
        }

    } catch (ServerNotInitializedException e) {
        return;
    } catch (Exception er) {
        log.error("Error downloading: ", er);
    }
}