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:dk.statsbiblioteket.doms.surveillance.surveyor.SurveyorServletUtils.java

/**
 * Handle actions given a servlet request on a surveyor.
 * Will handle requests to mark a log message as handled, and requests
 * never to show a given message again./*from   w  w  w.  j a  va2  s.  c  om*/
 * @param request The request containing the parameters.
 * @param surveyor The surveyor to call the actions on.
 */
public static void handlePostedParameters(HttpServletRequest request, Surveyor surveyor) {
    log.trace("Enter handlePostedParameters()");
    String applicationName;

    try {
        request.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e) {
        //UTF-8 must be supported as per spec.
        throw new Error("UTF-8 unsupported by JVM", e);
    }

    applicationName = request.getParameter("applicationname");
    if (applicationName != null) {
        Map<String, String[]> parameters = request.getParameterMap();
        for (String key : parameters.keySet()) {
            if (key.startsWith("handle:") && Arrays.equals(new String[] { "Handled" }, parameters.get(key))) {
                surveyor.markHandled(applicationName, key.substring("handle:".length()));
            }
        }
        if (request.getParameter("notagain") != null) {
            surveyor.notAgain(applicationName, request.getParameter("notagain"));
        }
    }
}

From source file:net.sourceforge.ajaxtags.servlets.AjaxActionHelper.java

/**
 * Invoke the AJAX action and setup the request and response.
 *
 * @param action/* w  w  w .j  a va  2s .  c  o m*/
 *            the BaseAjaxXmlAction implementation
 * @param request
 *            the request
 * @param response
 *            the response
 * @return the XML content from action
 * @throws ServletException
 *             for any errors
 */
public static String invoke(final BaseAjaxXmlAction action, final HttpServletRequest request,
        final HttpServletResponse response) throws ServletException {
    // prepare CALL
    try {
        request.setCharacterEncoding(action.getXMLEncoding());
        // we will use UTF-8
    } catch (UnsupportedEncodingException e) {
        throw new ServletException(e);
    }
    // Set content to XML
    response.setContentType("text/xml; charset=" + action.getXMLEncoding());

    // enable the ajaxheaders
    for (HTMLAjaxHeader header : HTMLAjaxHeader.values()) {
        header.enable(response);
    }

    try {
        return action.getXmlContent(request, response);
    } catch (IOException e) {
        throw new ServletException(e);
    }
}

From source file:com.zving.platform.SysInfo.java

public static void downloadDB(HttpServletRequest request, HttpServletResponse response) {
    try {/*from   w  w w . j  a v  a 2s.c om*/
        request.setCharacterEncoding(Constant.GlobalCharset);
        response.reset();
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition",
                "attachment; filename=DB_" + DateUtil.getCurrentDate("yyyyMMddHHmmss") + ".dat");
        OutputStream os = response.getOutputStream();

        String path = Config.getContextRealPath() + "WEB-INF/data/backup/DB_"
                + DateUtil.getCurrentDate("yyyyMMddHHmmss") + ".dat";
        new DBExport().exportDB(path);

        byte[] buffer = new byte[1024];
        int read = -1;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(path);
            while ((read = fis.read(buffer)) != -1)
                if (read > 0) {
                    byte[] chunk = (byte[]) null;
                    if (read == 1024) {
                        chunk = buffer;
                    } else {
                        chunk = new byte[read];
                        System.arraycopy(buffer, 0, chunk, 0, read);
                    }
                    os.write(chunk);
                    os.flush();
                }
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
        os.flush();
        os.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.telefonica.iot.perseo.Utils.java

/**
 * Return body as a String/*ww  w. j av a  2 s . c om*/
 *
 * @param request HttpServletRequest incomming request
 * @return String (body of the request)
 * @throws java.io.IOException
 *
 */
public static String getBodyAsString(HttpServletRequest request) throws IOException {
    logger.debug("request.getCharacterEncoding() " + request.getCharacterEncoding());
    if (request.getCharacterEncoding() == null) {
        request.setCharacterEncoding("UTF-8");
    }
    StringBuilder sb = new StringBuilder();
    BufferedReader br = request.getReader();
    String read = br.readLine();
    while (read != null) {
        sb.append(read);
        read = br.readLine();
    }
    return sb.toString();
}

From source file:com.zlfun.framework.excel.ExcelUtils.java

public static <T> void httpOutput(String name, Class<T> clazz, List<T> list, HttpServletRequest request,
        HttpServletResponse response) {//ww  w  .j a va  2s  .  c o  m
    try {
        request.setCharacterEncoding("UTF-8");//request???
        String fileName = name;//??
        String contentType = "application/vnd.ms-excel";//?
        String recommendedName = new String(fileName.getBytes(), "iso_8859_1");//????
        response.setContentType(contentType);//?
        response.setHeader("Content-Disposition", "attachment; filename=" + recommendedName + "\"");//
        response.resetBuffer();
        //?
        ServletOutputStream sos = response.getOutputStream();
        write(name, clazz, list, sos);
        sos.flush();
        sos.close();
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(ExcelUtils.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ExcelUtils.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.dspace.app.webui.util.UIUtil.java

/**
 * Obtain a new context object. If a context object has already been created
 * for this HTTP request, it is re-used, otherwise it is created. If a user
 * has authenticated with the system, the current user of the context is set
 * appropriately./*from ww w  .j ava 2  s.co  m*/
 * 
 * @param request
 *            the HTTP request
 * 
 * @return a context object
 */
public static Context obtainContext(HttpServletRequest request) throws SQLException {

    //Set encoding to UTF-8, if not set yet
    //This avoids problems of using the HttpServletRequest
    //in the getSpecialGroups() for an AuthenticationMethod,  
    //which causes the HttpServletRequest to default to 
    //non-UTF-8 encoding.
    try {
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding(Constants.DEFAULT_ENCODING);
        }
    } catch (Exception e) {
        log.error("Unable to set encoding to UTF-8.", e);
    }

    Context c = (Context) request.getAttribute("dspace.context");

    if (c == null) {
        // No context for this request yet
        c = new Context();
        HttpSession session = request.getSession();

        // See if a user has authentication
        Integer userID = (Integer) session.getAttribute("dspace.current.user.id");

        if (userID != null) {
            String remAddr = (String) session.getAttribute("dspace.current.remote.addr");
            if (remAddr != null && remAddr.equals(request.getRemoteAddr())) {
                EPerson e = EPerson.find(c, userID.intValue());

                Authenticate.loggedIn(c, request, e);
            } else {
                log.warn("POSSIBLE HIJACKED SESSION: request from " + request.getRemoteAddr()
                        + " does not match original " + "session address: " + remAddr
                        + ". Authentication rejected.");
            }
        }

        // Set any special groups - invoke the authentication mgr.
        int[] groupIDs = AuthenticationManager.getSpecialGroups(c, request);

        for (int i = 0; i < groupIDs.length; i++) {
            c.setSpecialGroup(groupIDs[i]);
            log.debug("Adding Special Group id=" + String.valueOf(groupIDs[i]));
        }

        // Set the session ID and IP address
        String ip = request.getRemoteAddr();
        if (useProxies == null) {
            useProxies = ConfigurationManager.getBooleanProperty("useProxies", false);
        }
        if (useProxies && request.getHeader("X-Forwarded-For") != null) {
            /* This header is a comma delimited list */
            for (String xfip : request.getHeader("X-Forwarded-For").split(",")) {
                if (!request.getHeader("X-Forwarded-For").contains(ip)) {
                    ip = xfip.trim();
                }
            }
        }
        c.setExtraLogInfo("session_id=" + request.getSession().getId() + ":ip_addr=" + ip);

        // Store the context in the request
        request.setAttribute("dspace.context", c);
    }

    // Set the locale to be used
    Locale sessionLocale = getSessionLocale(request);
    Config.set(request.getSession(), Config.FMT_LOCALE, sessionLocale);
    c.setCurrentLocale(sessionLocale);

    return c;
}

From source file:org.dspace.webmvc.utils.UIUtil.java

/**
 * Obtain a new context object. If a context object has already been created
 * for this HTTP request, it is re-used, otherwise it is created. If a user
 * has authenticated with the system, the current user of the context is set
 * appropriately.//from  ww  w  . j  a  va2 s. co m
 * 
 * @param request
 *            the HTTP request
 * 
 * @return a context object
 */
public static Context obtainContext(HttpServletRequest request) throws SQLException {

    //Set encoding to UTF-8, if not set yet
    //This avoids problems of using the HttpServletRequest
    //in the getSpecialGroups() for an AuthenticationMethod,  
    //which causes the HttpServletRequest to default to 
    //non-UTF-8 encoding.
    try {
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding(Constants.DEFAULT_ENCODING);
        }
    } catch (Exception e) {
        log.error("Unable to set encoding to UTF-8.", e);
    }

    Context c = (Context) request.getAttribute("dspace.context");

    if (c == null) {
        // No context for this request yet
        c = new Context();
        HttpSession session = request.getSession();

        // See if a user has authentication
        Integer userID = (Integer) session.getAttribute("dspace.current.user.id");

        if (userID != null) {
            String remAddr = (String) session.getAttribute("dspace.current.remote.addr");
            if (remAddr != null && remAddr.equals(request.getRemoteAddr())) {
                EPerson e = EPerson.find(c, userID.intValue());

                Authenticate.loggedIn(c, request, e);
            } else {
                log.warn("POSSIBLE HIJACKED SESSION: request from " + request.getRemoteAddr()
                        + " does not match original " + "session address: " + remAddr
                        + ". Authentication rejected.");
            }
        }

        // Set any special groups - invoke the authentication mgr.
        int[] groupIDs = AuthenticationManager.getSpecialGroups(c, request);

        for (int i = 0; i < groupIDs.length; i++) {
            c.setSpecialGroup(groupIDs[i]);
            log.debug("Adding Special Group id=" + String.valueOf(groupIDs[i]));
        }

        // Set the session ID and IP address
        String ip = request.getRemoteAddr();
        if (useProxies == null) {
            useProxies = ConfigurationManager.getBooleanProperty("useProxies", false);
        }
        if (useProxies && request.getHeader("X-Forwarded-For") != null) {
            /* This header is a comma delimited list */
            for (String xfip : request.getHeader("X-Forwarded-For").split(",")) {
                if (!request.getHeader("X-Forwarded-For").contains(ip)) {
                    ip = xfip.trim();
                }
            }
        }
        c.setExtraLogInfo("session_id=" + request.getSession().getId() + ":ip_addr=" + ip);

        // Store the context in the request
        request.setAttribute("dspace.context", c);
    }

    // Set the locale to be used
    Locale sessionLocale = getSessionLocale(request);
    //Config.set(request.getSession(), Config.FMT_LOCALE, sessionLocale);
    request.getSession().setAttribute("FMT_LOCALE", sessionLocale);
    c.setCurrentLocale(sessionLocale);

    return c;
}

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

/** Builds the request with data supplied by tomcat.
  * A request is in the form: srv/<language>/<service>[!]<parameters>
  *//* ww  w  .  j  a va2 s  .c  om*/

public static ServiceRequest create(HttpServletRequest req, HttpServletResponse res, String uploadDir,
        int maxUploadSize) throws Exception {
    String url = req.getPathInfo();

    // FIXME: if request character encoding is undefined set it to UTF-8

    String encoding = req.getCharacterEncoding();
    try {
        // verify that encoding is valid
        Charset.forName(encoding);
    } catch (Exception e) {
        encoding = null;
    }

    if (encoding == null) {
        try {
            req.setCharacterEncoding(Jeeves.ENCODING);
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
    }

    //--- extract basic info

    HttpServiceRequest srvReq = new HttpServiceRequest(res);

    srvReq.setDebug(extractDebug(url));
    srvReq.setLanguage(extractLanguage(url));
    srvReq.setService(extractService(url));
    srvReq.setJSONOutput(extractJSONFlag(url));
    String ip = req.getRemoteAddr();
    String forwardedFor = req.getHeader("x-forwarded-for");
    if (forwardedFor != null)
        ip = forwardedFor;
    srvReq.setAddress(ip);
    srvReq.setOutputStream(res.getOutputStream());

    //--- discover the input/output methods

    String accept = req.getHeader("Accept");

    if (accept != null) {
        int soapNDX = accept.indexOf("application/soap+xml");
        int xmlNDX = accept.indexOf("application/xml");
        int htmlNDX = accept.indexOf("html");

        if (soapNDX != -1)
            srvReq.setOutputMethod(OutputMethod.SOAP);

        else if (xmlNDX != -1 && htmlNDX == -1)
            srvReq.setOutputMethod(OutputMethod.XML);
    }

    if ("POST".equals(req.getMethod())) {
        srvReq.setInputMethod(InputMethod.POST);

        String contType = req.getContentType();

        if (contType != null) {
            if (contType.indexOf("application/soap+xml") != -1) {
                srvReq.setInputMethod(InputMethod.SOAP);
                srvReq.setOutputMethod(OutputMethod.SOAP);
            }

            else if (contType.indexOf("application/xml") != -1 || contType.indexOf("text/xml") != -1)
                srvReq.setInputMethod(InputMethod.XML);
        }
    }

    //--- retrieve input parameters

    InputMethod input = srvReq.getInputMethod();

    if ((input == InputMethod.XML) || (input == InputMethod.SOAP)) {
        if (req.getMethod().equals("GET"))
            srvReq.setParams(extractParameters(req, uploadDir, maxUploadSize));
        else
            srvReq.setParams(extractXmlParameters(req));
    } else {
        //--- GET or POST
        srvReq.setParams(extractParameters(req, uploadDir, maxUploadSize));
    }

    srvReq.setHeaders(extractHeaders(req));

    return srvReq;
}

From source file:org.ejbca.ui.web.RequestHelper.java

/** Sets the default character encoding for decoding post and get parameters. 
 * First tries to get the character encoding from the request, if the browser is so kind to tell us which it is using, which it never does...
 * Otherwise, when the browser is silent, it sets the character encoding to the same encoding that we use to display the pages.
 * //from w  w  w .  java 2  s.c o  m
 * @param request HttpServletRequest   
 * @throws UnsupportedEncodingException 
 * 
 */
public static void setDefaultCharacterEncoding(HttpServletRequest request) throws UnsupportedEncodingException {
    String encoding = request.getCharacterEncoding();
    if (StringUtils.isEmpty(encoding)) {
        encoding = org.ejbca.config.WebConfiguration.getWebContentEncoding();
        if (log.isDebugEnabled()) {
            log.debug("Setting encoding to default value: " + encoding);
        }
        request.setCharacterEncoding(encoding);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Setting encoding to value from request: " + encoding);
        }
        request.setCharacterEncoding(encoding);
    }
}

From source file:com.slience.controller.SolrController.java

@RequestMapping("/solr")
@ResponseBody/*from w w  w. j a  va  2  s  .  c  om*/
public void handSolrRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    request.setCharacterEncoding("UTF-8");
    response.setContentType("application/json;charset=UTF-8");

    //solrSimpleQueryService.service();

}