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:de.betterform.agent.web.servlet.XFormsRepeater.java

/**
 * Starts a new form-editing session.<br>
 * <p/>//from   ww  w  . jav  a2  s  .  co  m
 * The default value of a number of settings can be overridden as follows:
 * <p/>
 * 1. The uru of the xform to be displayed can be specified by using a param name of 'form' and a param value
 * of the location of the xform file as follows, which will attempt to load the current xforms file.
 * <p/>
 * http://localhost:8080/betterform/XFormsServlet?form=/forms/hello.xhtml
 * <p/>
 * 2. The uri of the XSLT file used to generate the form can be specified using a param name of 'xslt' as follows:
 * <p/>
 * http://localhost:8080/betterform/XFormsServlet?form=/forms/hello.xhtml&xslt=/betterform/my.xslt
 * <p/>
 * 3. Besides these special params arbitrary other params can be passed via the GET-string and will be available
 * in the context map of XFormsProcessorImpl. This means they can be used as instance data (with the help of ContextResolver)
 * or to set params for URI resolution.
 *
 * @param request  servlet request
 * @param response servlet response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");
    WebUtil.nonCachingResponse(response);
    HttpSession session = null;

    if (request.getAttribute("Session") != null) {
        session = (HttpSession) request.getAttribute("Session");
    } else {
        session = request.getSession(true);
    }

    request.setAttribute(WebFactory.USER_AGENT, useragent);
    System.out.println("request: " + request.getRequestURL().toString());

    if ("GET".equalsIgnoreCase(request.getMethod())
            && request.getParameter(BetterFORMConstants.SUBMISSION_RESPONSE) != null) {
        doSubmissionReplaceAll(request, response);
    } else {
        processForm(request, response, session);
    }
}

From source file:com.francelabs.datafari.servlets.URL.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)/*from  www.ja  v  a  2s .  c o m*/
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");

    final String protocol = request.getScheme() + ":";

    final Map<String, String[]> requestMap = new HashMap<>();
    requestMap.putAll(request.getParameterMap());
    final IndexerQuery query = IndexerServerManager.createQuery();
    query.addParams(requestMap);
    // get the AD domain
    String domain = "";
    HashMap<String, String> h;
    try {
        h = RealmLdapConfiguration.getConfig(request);

        if (h.get(RealmLdapConfiguration.ATTR_CONNECTION_NAME) != null) {
            final String userBase = h.get(RealmLdapConfiguration.ATTR_DOMAIN_NAME).toLowerCase();
            final String[] parts = userBase.split(",");
            domain = "";
            for (int i = 0; i < parts.length; i++) {
                if (parts[i].indexOf("dc=") != -1) { // Check if the current
                    // part is a domain
                    // component
                    if (!domain.isEmpty()) {
                        domain += ".";
                    }
                    domain += parts[i].substring(parts[i].indexOf('=') + 1);
                }
            }
        }

        // Add authentication
        if (request.getUserPrincipal() != null) {
            String AuthenticatedUserName = request.getUserPrincipal().getName().replaceAll("[^\\\\]*\\\\", "");
            if (AuthenticatedUserName.contains("@")) {
                AuthenticatedUserName = AuthenticatedUserName.substring(0, AuthenticatedUserName.indexOf("@"));
            }
            if (!domain.equals("")) {
                AuthenticatedUserName += "@" + domain;
            }
            query.setParam("AuthenticatedUserName", AuthenticatedUserName);
        }
    } catch (final Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    StatsPusher.pushDocument(query, protocol);

    // String surl = URLDecoder.decode(request.getParameter("url"),
    // "ISO-8859-1");
    final String surl = request.getParameter("url");

    if (ScriptConfiguration.getProperty("ALLOWLOCALFILEREADING").equals("true")
            && !surl.startsWith("file://///")) {

        final int BUFSIZE = 4096;
        String fileName = null;

        /**
         * File Display/Download --> <!-- Written by Rick Garcia -->
         */
        if (SystemUtils.IS_OS_LINUX) {
            // try to open the file locally
            final String fileNameA[] = surl.split(":");
            fileName = URLDecoder.decode(fileNameA[1], "UTF-8");

        } else if (SystemUtils.IS_OS_WINDOWS) {
            fileName = URLDecoder.decode(surl, "UTF-8").replaceFirst("file:/", "");
        }

        final File file = new File(fileName);
        int length = 0;
        final ServletOutputStream outStream = response.getOutputStream();
        final ServletContext context = getServletConfig().getServletContext();
        String mimetype = context.getMimeType(fileName);

        // sets response content type
        if (mimetype == null) {
            mimetype = "application/octet-stream";

        }
        response.setContentType(mimetype);
        response.setContentLength((int) file.length());

        // sets HTTP header
        response.setHeader("Content-Disposition", "inline; fileName=\"" + fileName + "\"");

        final byte[] byteBuffer = new byte[BUFSIZE];
        final DataInputStream in = new DataInputStream(new FileInputStream(file));

        // reads the file's bytes and writes them to the response stream
        while (in != null && (length = in.read(byteBuffer)) != -1) {
            outStream.write(byteBuffer, 0, length);
        }

        in.close();
        outStream.close();
    } else {

        final RequestDispatcher rd = request.getRequestDispatcher(redirectUrl);
        rd.forward(request, response);
    }
}

From source file:com.primeleaf.krystal.web.view.WebView.java

public void init(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws Exception {
    httpRequest.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING);
    httpResponse.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING);
    request = httpRequest;/*w w w .j  a  va 2 s  .  c  om*/
    response = httpResponse;
    request.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING);
    response.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING);

    response.setContentType("text/html; charset=utf-8");
    response.setHeader("Cache-Control", "no-cache");
    out = httpResponse.getWriter();
    session = (HttpSession) httpRequest.getSession();
    out = httpResponse.getWriter();

    loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL);

}

From source file:org.infoscoop.admin.web.UploadGadgetServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");

    response.setStatus(200);//from  ww w  .  j  av  a  2 s.c  o  m

    Writer writer = response.getWriter();

    UploadFileInfo info;
    try {
        info = extractUploadFileInfo(request);
        if (info.isModuleMode()) {
            uploadResources(info);
        } else {
            uploadResource(info);
        }
    } catch (GadgetResourceException ex) {
        log.error("", ex);

        writeMessage(writer, null, ex.toJSON().toString());
        return;
    } catch (Throwable ex) {
        log.error("", ex);

        String message = ex.getMessage();
        if (ex.getCause() != null)
            message = ex.getCause().getMessage();

        writeMessage(writer, null, message);
        return;
    }

    writeMessage(writer, info.type, "success");
    writer.flush();
}

From source file:com.happyuno.controller.StartGame.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *//*from   ww w . j av a  2  s . co m*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/html;charset=utf-8");
    request.setCharacterEncoding("utf-8");

    //?tableId
    String tableId = (String) request.getParameter("tableId");

    System.out.println(tableId);
    //?userId
    String userId = (String) request.getSession().getAttribute("userId");

    //
    ServletContext application = request.getSession().getServletContext();
    HashMap<Integer, GameTable> gameTableMap = (HashMap<Integer, GameTable>) application
            .getAttribute("gameTableMap");

    String resultMessage = "??";

    //User??Player
    ArrayList<Player> players = new ArrayList<Player>();

    int tindex = Integer.parseInt(tableId);
    GameTable gt = gameTableMap.get(tindex);
    ArrayList<User> userList = gt.getUserList();

    resultMessage = "??";
    //????
    gt.setStateStart(true);
    System.out.println(userList.size() + "changdu");
    for (int i = 0; i < userList.size(); i++) {
        //Playerid,nameUser?
        System.out.println(i + "position");
        String curUserId = ((User) userList.get(i)).getId();
        System.out.println("UserId" + curUserId);
        int cUserId = Integer.parseInt(curUserId);
        String curUserName = ((User) userList.get(i)).getName();
        Player curPlayer = new Player(cUserId, curUserName);
        players.add(curPlayer);
    }
    gt.getCurrentGame().initGame(players);

    HttpSession session = request.getSession();
    session.setAttribute("tableId", tindex);
    session.setAttribute("players", players);
    session.setAttribute("curPlayerId", Integer.parseInt(userId));

    //
    application.setAttribute("gameTableMap", gameTableMap);

    //tableMap?
    application.setAttribute("tatoNum", gameTableMap.size());

    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/table.jsp");
    dispatcher.forward(request, response);

}

From source file:org.nuxeo.ecm.webengine.app.WebEngineFilter.java

public void preRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    // need to set the encoding of characters manually
    if (null == request.getCharacterEncoding()) {
        request.setCharacterEncoding("UTF-8");
    }//  w  w  w  .  j a  va  2s  .com
    // response.setCharacterEncoding("UTF-8");
}

From source file:com.eufar.asmm.server.DownloadFunction.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("DownloadFunction - the function started");
    ServletContext context = getServletConfig().getServletContext();
    request.setCharacterEncoding("UTF-8");
    String dir = context.getRealPath("/tmp");
    ;/* w ww .  ja  va 2s .  com*/
    String filename = "";
    File fileDir = new File(dir);
    try {
        System.out.println("DownloadFunction - create the file on server");
        filename = request.getParameterValues("filename")[0];
        String xmltree = request.getParameterValues("xmltree")[0];

        // format xml code to pretty xml code
        Document doc = DocumentHelper.parseText(xmltree);
        StringWriter sw = new StringWriter();
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setIndent(true);
        format.setIndentSize(4);
        XMLWriter xw = new XMLWriter(sw, format);
        xw.write(doc);

        Writer out = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(dir + "/" + filename), "UTF-8"));
        out.append(sw.toString());
        out.flush();
        out.close();
    } catch (Exception ex) {
        System.out.println("ERROR during rendering: " + ex);
    }
    try {
        System.out.println("DownloadFunction - send file to user");
        ServletOutputStream out = response.getOutputStream();
        File file = new File(dir + "/" + filename);
        String mimetype = context.getMimeType(filename);
        response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        response.setHeader("Pragma", "private");
        response.setHeader("Cache-Control", "private, must-revalidate");
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int length;
        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            out.write(bbuf, 0, length);
        }
        in.close();
        out.flush();
        out.close();
        FileUtils.cleanDirectory(fileDir);
    } catch (Exception ex) {
        System.out.println("ERROR during downloading: " + ex);
    }
    System.out.println("DownloadFunction - file ready to be donwloaded");
}

From source file:org.geowe.server.upload.FileUploadServlet.java

@Override
public void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    final ServletFileUpload upload = new ServletFileUpload();
    response.setContentType("text/plain; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_FILE_SIZE);//from www .ja va  2s.co  m

    try {
        final FileItemIterator iter = upload.getItemIterator(request);
        final StringWriter writer = new StringWriter();
        while (iter.hasNext()) {
            final FileItemStream item = iter.next();
            IOUtils.copy(item.openStream(), writer, "UTF-8");
            final String content = writer.toString();
            response.setStatus(HttpStatus.SC_OK);
            response.getWriter().printf(content);
        }
    } catch (SizeLimitExceededException e) {
        response.setStatus(HttpStatus.SC_REQUEST_TOO_LONG);
        response.getWriter().printf(HttpStatus.SC_REQUEST_TOO_LONG + ":" + e.getMessage());
        LOG.error(e.getMessage());
    } catch (Exception e) {
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().printf(HttpStatus.SC_INTERNAL_SERVER_ERROR + ": ups! something went wrong.");
        LOG.error(e.getMessage());
    }
}

From source file:de.mpg.escidoc.services.fledgeddata.webservice.oaiServlet.java

/**
 * Peform the http GET action. Note that POST is shunted to here as well.
 * The verb widget is taken from the request and used to invoke an
 * OAIVerb object of the corresponding kind to do the actual work of the verb.
 *
 * @param request the servlet's request information
 * @param response the servlet's response information
 * @exception IOException an I/O error occurred
 *///  w  w w .  j a  va 2s .co m
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    boolean serviceUnavailable = isServiceUnavailable();
    HashMap serverVerbs = ServerVerb.getVerbs();
    request.setCharacterEncoding("UTF-8");

    if (serviceUnavailable) {
        LOGGER.info("[FDS] oai servcice set to 'unavailable' in properties file.");
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                "[FDS] Sorry. This server is down for maintenance");
    } else {
        try {
            String result = getResult(request, response, serverVerbs);
            Writer out = getWriter(request, response);
            out.write(result);
            out.close();

        } catch (OAIInternalServerError e) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } catch (SocketException e) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } catch (Throwable e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
}

From source file:nl.strohalm.cyclos.http.EncodingFilter.java

@Override
protected void execute(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) throws IOException, ServletException {
    try {/*from  w w w  . ja v  a 2 s. c  o  m*/
        final String requestEncoding = request.getCharacterEncoding();
        if (StringUtils.isEmpty(requestEncoding)) {
            request.setCharacterEncoding(encoding);
        }
        response.setCharacterEncoding(encoding);
    } catch (final Exception e) {
    }
    chain.doFilter(request, response);
}