Example usage for javax.servlet.http HttpServletRequest getCharacterEncoding

List of usage examples for javax.servlet.http HttpServletRequest getCharacterEncoding

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getCharacterEncoding.

Prototype

public String getCharacterEncoding();

Source Link

Document

Returns the name of the character encoding used in the body of this request.

Usage

From source file:de.micromata.genome.logging.LogRequestDumpAttribute.java

/**
 * Gen http request dump.//from   www . j a  v a2s .  co m
 *
 * @param req the req
 * @return the string
 */
@SuppressWarnings("unchecked")
public static String genHttpRequestDump(HttpServletRequest req) {
    StringBuilder sb = new StringBuilder();

    sb.append("method: ").append(req.getMethod()).append('\n')//
            .append("requestURL: ").append(req.getRequestURL()).append('\n')//
            .append("servletPath: ").append(req.getServletPath()).append('\n')//
            .append("requestURI: ").append(req.getRequestURI()).append('\n') //
            .append("queryString: ").append(req.getQueryString()).append('\n') //
            .append("pathInfo: ").append(req.getPathInfo()).append('\n')//
            .append("contextPath: ").append(req.getContextPath()).append('\n') //
            .append("characterEncoding: ").append(req.getCharacterEncoding()).append('\n') //
            .append("localName: ").append(req.getLocalName()).append('\n') //
            .append("contentLength: ").append(req.getContentLength()).append('\n') //
    ;
    sb.append("Header:\n");
    for (Enumeration<String> en = req.getHeaderNames(); en.hasMoreElements();) {
        String hn = en.nextElement();
        sb.append("  ").append(hn).append(": ").append(req.getHeader(hn)).append("\n");
    }
    sb.append("Attr: \n");
    Enumeration en = req.getAttributeNames();
    for (; en.hasMoreElements();) {
        String k = (String) en.nextElement();
        Object v = req.getAttribute(k);
        sb.append("  ").append(k).append(": ").append(Objects.toString(v, StringUtils.EMPTY)).append('\n');
    }

    return sb.toString();
}

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 a v a2s  .  c  o 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   www .j ava2  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:org.synchronoss.cloud.nio.multipart.example.web.MultipartController.java

static MultipartContext getMultipartContext(final HttpServletRequest request) {
    String contentType = request.getContentType();
    int contentLength = request.getContentLength();
    String charEncoding = request.getCharacterEncoding();
    return new MultipartContext(contentType, contentLength, charEncoding);
}

From source file:grails.converters.JSON.java

/**
 * Parses the given request's InputStream and returns ether a JSONObject or a JSONArry
 *
 * @param request the JSON Request/*ww w .ja va 2s.c om*/
 * @return ether a JSONObject or a JSONArray - depending on the given JSON
 * @throws ConverterException when the JSON content is not valid
 */
public static Object parse(HttpServletRequest request) throws ConverterException {
    Object json = request.getAttribute(CACHED_JSON);
    if (json != null) {
        return json;
    }

    String encoding = request.getCharacterEncoding();
    if (encoding == null) {
        encoding = Converter.DEFAULT_REQUEST_ENCODING;
    }
    try {
        PushbackInputStream pushbackInputStream = null;
        int firstByte = -1;
        try {
            pushbackInputStream = new PushbackInputStream(request.getInputStream());
            firstByte = pushbackInputStream.read();
        } catch (IOException ioe) {
        }

        if (firstByte == -1) {
            return new JSONObject();
        }

        pushbackInputStream.unread(firstByte);
        json = parse(pushbackInputStream, encoding);
        request.setAttribute(CACHED_JSON, json);
        return json;
    } catch (IOException e) {
        throw new ConverterException("Error parsing JSON", e);
    }
}

From source file:fr.paris.lutece.util.http.MultipartUtil.java

/**
 * Convert a HTTP request to a {@link MultipartHttpServletRequest}
 * @param nSizeThreshold the size threshold
 * @param nRequestSizeMax the request size max
 * @param bActivateNormalizeFileName true if the file name must be normalized, false otherwise
 * @param request the HTTP request//from ww  w  . j  av  a2  s . c o m
 * @return a {@link MultipartHttpServletRequest}, null if the request does not have a multipart content
 * @throws SizeLimitExceededException exception if the file size is too big
 * @throws FileUploadException exception if an unknown error has occurred
 */
public static MultipartHttpServletRequest convert(int nSizeThreshold, long nRequestSizeMax,
        boolean bActivateNormalizeFileName, HttpServletRequest request)
        throws SizeLimitExceededException, FileUploadException {
    if (isMultipart(request)) {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Set factory constraints
        factory.setSizeThreshold(nSizeThreshold);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        upload.setSizeMax(nRequestSizeMax);

        // get encoding to be used
        String strEncoding = request.getCharacterEncoding();

        if (strEncoding == null) {
            strEncoding = EncodingService.getEncoding();
        }

        Map<String, FileItem> mapFiles = new HashMap<String, FileItem>();
        Map<String, String[]> mapParameters = new HashMap<String, String[]>();

        List<FileItem> listItems = upload.parseRequest(request);

        // Process the uploaded items
        for (FileItem item : listItems) {
            if (item.isFormField()) {
                String strValue = StringUtils.EMPTY;

                try {
                    if (item.getSize() > 0) {
                        strValue = item.getString(strEncoding);
                    }
                } catch (UnsupportedEncodingException ex) {
                    if (item.getSize() > 0) {
                        // if encoding problem, try with system encoding
                        strValue = item.getString();
                    }
                }

                // check if item of same name already in map
                String[] curParam = mapParameters.get(item.getFieldName());

                if (curParam == null) {
                    // simple form field
                    mapParameters.put(item.getFieldName(), new String[] { strValue });
                } else {
                    // array of simple form fields
                    String[] newArray = new String[curParam.length + 1];
                    System.arraycopy(curParam, 0, newArray, 0, curParam.length);
                    newArray[curParam.length] = strValue;
                    mapParameters.put(item.getFieldName(), newArray);
                }
            } else {
                // multipart file field, if the parameter filter ActivateNormalizeFileName is set to true
                //all file name will be normalize
                mapFiles.put(item.getFieldName(),
                        bActivateNormalizeFileName ? new NormalizeFileItem(item) : item);
            }
        }

        return new MultipartHttpServletRequest(request, mapFiles, mapParameters);
    }

    return null;
}

From source file:org.opendatakit.odktables.util.ServiceUtils.java

@SuppressWarnings({ "rawtypes", "unused" })
public static void examineRequest(ServletContext sc, HttpServletRequest req) {
    Log logger = LogFactory.getLog(ServiceUtils.class);

    Enumeration headers = req.getHeaderNames();
    StringBuilder b = new StringBuilder();
    while (headers.hasMoreElements()) {
        String headerName = (String) headers.nextElement();
        Enumeration fieldValues = req.getHeaders(headerName);
        while (fieldValues.hasMoreElements()) {
            String fieldValue = (String) fieldValues.nextElement();
            b.append(headerName).append(": ").append(fieldValue).append("\n");
        }//from  www.j a v a2s  .co m
    }

    String contentType = req.getContentType();
    logger.info("Content type: " + contentType);

    String charEncoding = req.getCharacterEncoding();
    logger.info("Character encoding: " + charEncoding);

    String headerSet = b.toString();
    logger.info("Headers: " + headerSet);

    Cookie[] cookies = req.getCookies();
    logger.info("Cookies: " + cookies);

    String method = req.getMethod();
    logger.info("Method: " + method);

    String ctxtPath = req.getContextPath();
    logger.info("Context Path: " + ctxtPath);

    String pathInfo = req.getPathInfo();
    logger.info("Path Info: " + pathInfo);

    String query = req.getQueryString();
    logger.info("Query String: " + query);

    String ace = req.getHeader(ApiConstants.ACCEPT_CONTENT_ENCODING_HEADER);
    boolean sessionId = req.isRequestedSessionIdValid();
}

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

private static Element getMultipartParams(HttpServletRequest req, String uploadDir, int maxUploadSize)
        throws Exception {
    Element params = new Element("params");

    DiskFileItemFactory fif = new DiskFileItemFactory();
    ServletFileUpload sfu = new ServletFileUpload(fif);

    sfu.setSizeMax(((long) maxUploadSize) * 1024L * 1024L);

    try {/* w  w w. j a v a2s  .co  m*/
        for (Object i : sfu.parseRequest(req)) {
            FileItem item = (FileItem) i;
            String name = item.getFieldName();

            if (item.isFormField()) {
                String encoding = req.getCharacterEncoding();
                params.addContent(new Element(name).setText(item.getString(encoding)));
            } else {
                String file = item.getName();
                String type = item.getContentType();
                long size = item.getSize();

                if (Log.isDebugEnabled(Log.REQUEST))
                    Log.debug(Log.REQUEST, "Uploading file " + file + " type: " + type + " size: " + size);
                //--- remove path information from file (some browsers put it, like IE)

                file = simplifyName(file);
                if (Log.isDebugEnabled(Log.REQUEST))
                    Log.debug(Log.REQUEST, "File is called " + file + " after simplification");

                //--- we could get troubles if 2 users upload files with the same name
                item.write(new File(uploadDir, file));

                Element elem = new Element(name).setAttribute("type", "file")
                        .setAttribute("size", Long.toString(size)).setText(file);

                if (type != null)
                    elem.setAttribute("content-type", type);

                if (Log.isDebugEnabled(Log.REQUEST))
                    Log.debug(Log.REQUEST, "Adding to parameters: " + Xml.getString(elem));
                params.addContent(elem);
            }
        }
    } catch (FileUploadBase.SizeLimitExceededException e) {
        throw new FileUploadTooBigEx();
    }

    return params;
}

From source file:arena.utils.ServletUtils.java

public static String replaceWildcards(String pattern, boolean allowRequestArgs, Map<String, Object> model,
        HttpServletRequest request) {
    int firstWildcard = pattern.indexOf("###");
    if (firstWildcard == -1) {
        return pattern;
    }/*from   www  . j a v  a2 s. co  m*/
    int endOfFirstWildcard = pattern.indexOf("###", firstWildcard + 3);
    if (endOfFirstWildcard == -1) {
        return pattern;
    }
    String key = pattern.substring(firstWildcard + 3, endOfFirstWildcard);
    boolean escapeToken = key.startsWith("!");
    if (escapeToken) {
        key = key.substring(1);
    }
    Object out = model.get(key);
    if ((out == null) && allowRequestArgs) {
        out = request.getParameter(key);
    }
    if (out == null) {
        out = "";
    }
    return pattern.substring(0, firstWildcard)
            + (escapeToken ? URLUtils.encodeURLToken(out.toString(), request.getCharacterEncoding()) : out)
            + replaceWildcards(pattern.substring(endOfFirstWildcard + 3), allowRequestArgs, model, request);
}

From source file:gallery.web.controller.misc.PathController.java

@RequestMapping
@ResponseBody//  w  ww  .j av  a 2  s.c  o  m
public String hello(HttpServletRequest request) {
    logger.info("encoding=" + request.getCharacterEncoding());

    logger.info("info=" + request.getPathInfo());
    logger.info("uri=" + request.getRequestURI());
    logger.info("hello");

    return "hello world<br>" + "info=" + request.getPathInfo() + "<br>uri=" + request.getRequestURI();
}