Example usage for javax.servlet.http HttpServletResponse setLocale

List of usage examples for javax.servlet.http HttpServletResponse setLocale

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse setLocale.

Prototype

public void setLocale(Locale loc);

Source Link

Document

Sets the locale of the response, if the response has not been committed yet.

Usage

From source file:JapaneseHelloWorldServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    response.setContentType("text/html");
    response.setLocale(Locale.JAPANESE);
    PrintWriter out = response.getWriter();
    out.println("<FONT SIZE=+2>");
    out.println("\u4eca\u65e5\u306f\u4e16\u754c");
    out.println("</FONT>");
}

From source file:com.technologicaloddity.saha.util.AjaxPageRendererImpl.java

public String render(ModelAndView modelAndView, HttpServletRequest request, HttpServletResponse response) {
    String result = null;/*from   w  w w . j  a  v a  2  s.  c om*/

    StringWriter sout = new StringWriter();
    StringBuffer buffer = sout.getBuffer();

    HttpServletResponse fakeResponse = new SwallowingHttpServletResponse(response, sout,
            response.getCharacterEncoding());

    Locale locale = this.localeResolver.resolveLocale(request);
    fakeResponse.setLocale(locale);

    request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);
    try {
        View view = viewResolver.resolveViewName(modelAndView.getViewName(), locale);
        view.render(modelAndView.getModel(), request, fakeResponse);
        result = buffer.toString();
    } catch (Exception e) {
        result = "Ajax render error:" + e.getMessage();
    }
    return result;
}

From source file:org.openmrs.web.OpenmrsCookieLocaleResolver.java

public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    HttpSession session = (HttpSession) request.getSession();

    // if a user clicks on the locale change links 
    // AND their current default locale is different (so the msg isn't repeated)
    if (request.getParameter("lang") != null && Context.isAuthenticated()
            && !Context.getLocale().equals(locale)) {
        session.setAttribute(WebConstants.OPENMRS_MSG_ARGS, request.getContextPath());
        session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.localeChangeHint");
    }//from www  .  j a v  a2 s  . c o m

    Context.setLocale(locale);

    response.setLocale(locale);

    //still set the cookie for later possible use.
    super.setLocale(request, response, locale);

}

From source file:eu.comvantage.dataintegration.QueryDistributionServiceImpl.java

private void print(HttpResponse in, HttpServletResponse out) throws IOException {
    //writing binary response stream
    for (Header h : in.getAllHeaders()) {
        out.addHeader(h.getName(), h.getValue());
    }// ww  w  . j a v  a 2s .c  om
    out.setStatus(in.getStatusLine().getStatusCode());
    out.setLocale(in.getLocale());
    out.setContentType("text/html");

    ServletOutputStream outstream = out.getOutputStream();
    int c;
    while ((c = in.getEntity().getContent().read()) != -1) {
        outstream.write(c);
    }
    outstream.flush();
}

From source file:org.apache.hadoop.test.mock.MockResponseProvider.java

public void apply(HttpServletResponse response) throws IOException {
    if (statusCode != null) {
        response.setStatus(statusCode);//from   w  w  w. ja va  2 s .  c  o  m
    }
    if (errorCode != null) {
        if (errorMsg != null) {
            response.sendError(errorCode, errorMsg);
        } else {
            response.sendError(errorCode);
        }
    }
    if (redirectUrl != null) {
        response.sendRedirect(redirectUrl);
    }
    if (headers != null) {
        for (String name : headers.keySet()) {
            response.addHeader(name, headers.get(name));
        }
    }
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            response.addCookie(cookie);
        }
    }
    if (locale != null) {
        response.setLocale(locale);
    }
    if (contentType != null) {
        response.setContentType(contentType);
    }
    if (characterEncoding != null) {
        response.setCharacterEncoding(characterEncoding);
    }
    if (contentLength != null) {
        response.setContentLength(contentLength);
    }
    if (entity != null) {
        response.getOutputStream().write(entity);
        response.getOutputStream().close();
    }
}

From source file:com.haulmont.cuba.restapi.DataServiceController.java

@RequestMapping(value = "/api/printDomain", method = RequestMethod.GET)
public void printDomain(@RequestParam(value = "s") String sessionId, HttpServletRequest request,
        HttpServletResponse response) throws IOException, InvocationTargetException, NoSuchMethodException,
        IllegalAccessException, TemplateException {

    if (!connect(sessionId, response))
        return;// w  w  w .ja v  a  2  s . c  o  m

    try {
        response.setContentType("text/html");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setLocale(userSessionSource.getLocale());

        String domainDescription = domainDescriptionService.getDomainDescription();
        response.getWriter().write(domainDescription);

    } catch (Throwable e) {
        sendError(request, response, e);
    } finally {
        authentication.end();
    }
}

From source file:org.apache.catalina.servlets.HTMLManagerServlet.java

/**
 * Process a POST request for the specified resource.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet-specified error occurs
 *//*from  w ww  .  j av a  2 s. c  om*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // Identify the request parameters that we need
    String command = request.getPathInfo();

    if (command == null || !command.equals("/upload")) {
        doGet(request, response);
        return;
    }

    // Prepare our output writer to generate the response message
    Locale locale = Locale.getDefault();
    String charset = context.getCharsetMapper().getCharset(locale);
    response.setLocale(locale);
    response.setContentType("text/html; charset=" + charset);

    String message = "";

    // Create a new file upload handler
    DiskFileUpload upload = new DiskFileUpload();

    // Get the tempdir
    File tempdir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir");
    // Set upload parameters
    upload.setSizeMax(-1);
    upload.setRepositoryPath(tempdir.getCanonicalPath());

    // Parse the request
    String war = null;
    FileItem warUpload = null;
    try {
        List items = upload.parseRequest(request);

        // Process the uploaded fields
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                if (item.getFieldName().equals("installWar") && warUpload == null) {
                    warUpload = item;
                } else {
                    item.delete();
                }
            }
        }
        while (true) {
            if (warUpload == null) {
                message = sm.getString("htmlManagerServlet.installUploadNoFile");
                break;
            }
            war = warUpload.getName();
            if (!war.toLowerCase().endsWith(".war")) {
                message = sm.getString("htmlManagerServlet.installUploadNotWar", war);
                break;
            }
            // Get the filename if uploaded name includes a path
            if (war.lastIndexOf('\\') >= 0) {
                war = war.substring(war.lastIndexOf('\\') + 1);
            }
            if (war.lastIndexOf('/') >= 0) {
                war = war.substring(war.lastIndexOf('/') + 1);
            }
            // Identify the appBase of the owning Host of this Context
            // (if any)
            String appBase = null;
            File appBaseDir = null;
            appBase = ((Host) context.getParent()).getAppBase();
            appBaseDir = new File(appBase);
            if (!appBaseDir.isAbsolute()) {
                appBaseDir = new File(System.getProperty("catalina.base"), appBase);
            }
            File file = new File(appBaseDir, war);
            if (file.exists()) {
                message = sm.getString("htmlManagerServlet.installUploadWarExists", war);
                break;
            }
            warUpload.write(file);
            try {
                URL url = file.toURL();
                war = url.toString();
                war = "jar:" + war + "!/";
            } catch (MalformedURLException e) {
                file.delete();
                throw e;
            }
            break;
        }
    } catch (Exception e) {
        message = sm.getString("htmlManagerServlet.installUploadFail", e.getMessage());
        log(message, e);
    } finally {
        if (warUpload != null) {
            warUpload.delete();
        }
        warUpload = null;
    }

    // If there were no errors, install the WAR
    if (message.length() == 0) {
        message = install(null, null, war);
    }

    list(request, response, message);
}

From source file:org.apache.catalina.servlets.HTMLManagerServlet.java

/**
 * Process a GET request for the specified resource.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet-specified error occurs
 *///from   w w  w  .  j  a va2  s .  co m
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // Identify the request parameters that we need
    String command = request.getPathInfo();

    String path = request.getParameter("path");
    String installPath = request.getParameter("installPath");
    String installConfig = request.getParameter("installConfig");
    String installWar = request.getParameter("installWar");

    // Prepare our output writer to generate the response message
    Locale locale = Locale.getDefault();
    String charset = context.getCharsetMapper().getCharset(locale);
    response.setLocale(locale);
    response.setContentType("text/html; charset=" + charset);

    String message = "";
    // Process the requested command
    if (command == null || command.equals("/")) {
    } else if (command.equals("/install")) {
        message = install(installConfig, installPath, installWar);
    } else if (command.equals("/list")) {
    } else if (command.equals("/reload")) {
        message = reload(path);
    } else if (command.equals("/remove")) {
        message = remove(path);
    } else if (command.equals("/sessions")) {
        message = sessions(path);
    } else if (command.equals("/start")) {
        message = start(path);
    } else if (command.equals("/stop")) {
        message = stop(path);
    } else {
        message = sm.getString("managerServlet.unknownCommand", command);
    }

    list(request, response, message);
}

From source file:org.springframework.web.servlet.SimpleDispatcherServlet.java

/**
 * Render the given ModelAndView.//  w w w. jav  a  2s  . co m
 * <p>This is the last stage in handling a request. It may involve resolving the view by name.
 * @param mv the ModelAndView to render
 * @param request current HTTP servlet request
 * @param response current HTTP servlet response
 * @throws Exception if there's a problem rendering the view
 */
protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    // Determine locale for request and apply it to the response.
    Locale locale = this.localeResolver.resolveLocale(request);
    response.setLocale(locale);

    View view;
    if (mv.isReference()) {
        // We need to resolve the view name.
        view = resolveViewName(mv.getViewName(), mv.getModelInternal(), locale, request);
        if (view == null) {
            throw new ServletException("Could not resolve view with name '" + mv.getViewName()
                    + "' in servlet with name '" + getServletName() + "'");
        }
    } else {
        // No need to lookup: the ModelAndView object contains the actual View object.
        view = mv.getView();
        if (view == null) {
            throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a "
                    + "View object in servlet with name '" + getServletName() + "'");
        }
    }

    //DEBUG
    Map<String, Object> modelInternal = mv.getModelInternal();
    for (String modelName : modelInternal.keySet()) {
        System.out.println("modelKey: " + modelName);
        System.out.println("modelValue: " + modelInternal.get(modelName));
    }

    // Delegate to the View object for rendering.
    if (logger.isDebugEnabled()) {
        logger.debug("Rendering view [" + view + "] in DispatcherServlet with name '" + getServletName() + "'");
    }
    view.render(mv.getModelInternal(), request, response);
}

From source file:org.apache.struts2.dispatcher.Dispatcher.java

/**
 * Prepare a request, including setting the encoding and locale.
 *
 * @param request The request/*w  ww  . j a  va2  s . co m*/
 * @param response The response
 */
public void prepare(HttpServletRequest request, HttpServletResponse response) {
    String encoding = null;
    if (defaultEncoding != null) {
        encoding = defaultEncoding;
    }
    // check for Ajax request to use UTF-8 encoding strictly http://www.w3.org/TR/XMLHttpRequest/#the-send-method
    if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
        encoding = "UTF-8";
    }

    Locale locale = getLocale(request);

    if (encoding != null) {
        applyEncoding(request, encoding);
    }

    if (locale != null) {
        response.setLocale(locale);
    }

    if (paramsWorkaroundEnabled) {
        request.getParameter("foo"); // simply read any parameter (existing or not) to "prime" the request
    }
}