Java Code Examples for javax.servlet.http.HttpServletRequest#getCharacterEncoding()

The following examples show how to use javax.servlet.http.HttpServletRequest#getCharacterEncoding() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
	log.info("encodeUrlPathSegment()");
	try{
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {log.error(uee);}
		return pathSegment;
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example 2
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
	log.info("encodeUrlPathSegment()");
	try{
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {log.error(uee);}
		return pathSegment;
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example 3
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
	log.info("encodeUrlPathSegment()");
	try{
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {log.error(uee);}
		return pathSegment;
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example 4
Source Project: odo   File: HttpRequestInfo.java    License: Apache License 2.0 6 votes vote down vote up
public HttpRequestInfo(HttpServletRequest request) {
    this.authType = request.getAuthType();
    this.contextPath = request.getContextPath();
    populateHeaders(request);
    this.method = request.getMethod();
    this.pathInfo = request.getPathInfo();
    this.queryString = request.getQueryString();
    this.requestURI = request.getRequestURI();
    this.servletPath = request.getServletPath();
    this.contentType = request.getContentType();
    this.characterEncoding = request.getCharacterEncoding();
    this.contentLength = request.getContentLength();
    this.localName = request.getLocalName();
    this.localPort = request.getLocalPort();
    populateParameters(request);
    this.protocol = request.getProtocol();
    this.remoteAddr = request.getRemoteAddr();
    this.remoteHost = request.getRemoteHost();
    this.remotePort = request.getRemotePort();
    this.serverName = request.getServerName();
    this.secure = request.isSecure();
    populateAttributes(request);
}
 
Example 5
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
	log.info("encodeUrlPathSegment()");
	try{
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {log.error(uee);}
		return pathSegment;
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example 6
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
	log.info("encodeUrlPathSegment()");
	try{
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {log.error(uee);}
		return pathSegment;
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example 7
Source Project: flower   File: Web.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get the JSON data submitted by the post method
 * 
 * @return String / null
 * @throws IOException When an error occurs while reading the InputStream,
 *         IOException is thrown
 * @throws UnsupportedEncodingException Thrown when encountering an unresolved
 *         character encoding
 * @since JDK 1.7+
 */
public String getPostJson() throws IOException {
  HttpServletRequest httpSr = (HttpServletRequest) servletRequest;
  if (!httpSr.getMethod().equalsIgnoreCase("POST") || null == httpSr.getContentType()) {
    return null;
  }
  if (!httpSr.getContentType().toLowerCase().contains("application/json")) {
    return null;
  }
  if (httpSr.getContentLength() <= 0) {
    return null;
  }
  String charsetName = httpSr.getCharacterEncoding();
  if (null == charsetName) {
    charsetName = Constant.ENCODING_UTF_8;
  }
  byte[] bytes = new byte[httpSr.getContentLength()];
  try (InputStream is = httpSr.getInputStream()) {
    int len = is.read(bytes, 0, httpSr.getContentLength());
    return len <= 0 ? null : new String(bytes, charsetName);
  } catch (UnsupportedEncodingException uee) {
    throw new UnsupportedEncodingException("UnsupportedEncoding");
  }
}
 
Example 8
/**
 * 获取 request 请求内容
 *
 * @param request request
 * @param buffer buffer
 * @return String
 * @throws IOException IOException
 */
public static String getRequestStr(HttpServletRequest request, byte[] buffer) throws IOException {
	String charEncoding = request.getCharacterEncoding();
	if (charEncoding == null) {
		charEncoding = StringPool.UTF_8;
	}
	String str = new String(buffer, charEncoding).trim();
	if (StringUtil.isBlank(str)) {
		StringBuilder sb = new StringBuilder();
		Enumeration<String> parameterNames = request.getParameterNames();
		while (parameterNames.hasMoreElements()) {
			String key = parameterNames.nextElement();
			String value = request.getParameter(key);
			StringUtil.appendBuilder(sb, key, "=", value, "&");
		}
		str = StringUtil.removeSuffix(sb.toString(), "&");
	}
	return str.replaceAll("&amp;", "&");
}
 
Example 9
@Override
protected void doFilterInternal(
		HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
		throws ServletException, IOException {

	if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
		request.setCharacterEncoding(this.encoding);
		if (this.forceEncoding) {
			response.setCharacterEncoding(this.encoding);
		}
	}
	filterChain.doFilter(request, response);
}
 
Example 10
/**
 * If the character encoding is not initialized, it will be set to UTF-8
 */
public IgnoreCharacterEncodingHttpRequestWrapper(HttpServletRequest request)
        throws UnsupportedEncodingException {

    super(request);
    if (request.getCharacterEncoding() == null) {
        request.setCharacterEncoding(Constants.CHARACTER_ENCODING_UTF8);
    }
}
 
Example 11
@SuppressWarnings("deprecation")
private String getRequestBody(HttpServletRequest request) throws IOException {
    String charset = request.getCharacterEncoding() == null ? CHARSET_UTF_8 : request.getCharacterEncoding();
    String requestBody = IOUtils.toString(request.getInputStream(), charset);
    if (StringUtils.isBlank(requestBody)) {
        throw new IllegalArgumentException("request-body is empty");
    }

    return requestBody;
}
 
Example 12
/**
 * Constructs a request object wrapping the given request.
 *
 * @param request 请求
 * @throws IOException if the request is null
 */
public WrapperRequest(HttpServletRequest request, HttpServletResponse response, HttpStandaloneListener listener)
        throws IOException {
    super(request);
    this.response = response;
    this.listener = listener;
    // application/json的方式提交,需要拦截body
    this.usingBody = StringUtils.contains(request.getContentType(), "application/json");
    StringBuilder stringBuilder = new StringBuilder();
    BufferedReader bufferedReader = null;
    if (usingBody) {
        try {
            InputStream inputStream = request.getInputStream();
            if (inputStream != null) {
                String ce = request.getCharacterEncoding();
                if (StringUtils.isNotEmpty(ce)) {
                    bufferedReader = new BufferedReader(new InputStreamReader(inputStream, ce));
                } else {
                    bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                }
                char[] charBuffer = new char[128];
                int bytesRead;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            }
        } finally {
            IOUtils.closeQuietly(bufferedReader);
        }
    }
    body = stringBuilder.toString();
}
 
Example 13
Source Project: mt-flume   File: JSONHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public List<Event> getEvents(HttpServletRequest request) throws Exception {
  BufferedReader reader = request.getReader();
  String charset = request.getCharacterEncoding();
  //UTF-8 is default for JSON. If no charset is specified, UTF-8 is to
  //be assumed.
  if (charset == null) {
    LOG.debug("Charset is null, default charset of UTF-8 will be used.");
    charset = "UTF-8";
  } else if (!(charset.equalsIgnoreCase("utf-8")
          || charset.equalsIgnoreCase("utf-16")
          || charset.equalsIgnoreCase("utf-32"))) {
    LOG.error("Unsupported character set in request {}. "
            + "JSON handler supports UTF-8, "
            + "UTF-16 and UTF-32 only.", charset);
    throw new UnsupportedCharsetException("JSON handler supports UTF-8, "
            + "UTF-16 and UTF-32 only.");
  }

  /*
   * Gson throws Exception if the data is not parseable to JSON.
   * Need not catch it since the source will catch it and return error.
   */
  List<Event> eventList = new ArrayList<Event>(0);
  try {
    eventList = gson.fromJson(reader, listType);
  } catch (JsonSyntaxException ex) {
    throw new HTTPBadRequestException("Request has invalid JSON Syntax.", ex);
  }

  for (Event e : eventList) {
    ((JSONEvent) e).setCharset(charset);
  }
  return getSimpleEvents(eventList);
}
 
Example 14
private List<ScheduleEntry> getScheduleEntryListFromParameter(HttpServletRequest request, ApplicationContext appContext, String campaign, JSONArray json) throws JSONException {
    List<ScheduleEntry> scheList = new ArrayList<>();
    IScheduleEntryService scheService = appContext.getBean(IScheduleEntryService.class);
    IFactoryScheduleEntry scheFactory = appContext.getBean(IFactoryScheduleEntry.class);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String charset = request.getCharacterEncoding() == null ? "UTF-8" : request.getCharacterEncoding();
    for (int i = 0; i < json.length(); i++) {
        JSONObject tcsaJson = json.getJSONObject(i);
        // Parameter that are already controled by GUI (no need to decode) --> We SECURE them
        boolean delete = tcsaJson.getBoolean("toDelete");
        String cronExpression = policy.sanitize(tcsaJson.getString("cronDefinition"));
        String active = policy.sanitize(tcsaJson.getString("active"));
        String strId = tcsaJson.getString("ID");
        String desc = tcsaJson.getString("description");
        String type = "CAMPAIGN";
        String name = campaign;

        int id;
        if (strId.isEmpty()) {
            id = 0;
        } else {
            try {
                id = Integer.parseInt(strId);
            } catch (NumberFormatException e) {
                LOG.warn("Unable to parse pool size: " + strId + ". Applying default value");
                id = 0;
            }
        }

        Timestamp timestampfactice = new Timestamp(System.currentTimeMillis());

        if (!delete) {
            ScheduleEntry sch = scheFactory.create(id, type, name, cronExpression, timestampfactice, active, desc, request.getRemoteUser(), timestampfactice, request.getRemoteUser(), timestampfactice);
            scheList.add(sch);
        }
    }
    return scheList;
}
 
Example 15
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String charset = request.getCharacterEncoding() == null ? "UTF-8" : request.getCharacterEncoding();

    String id = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("idName"), "", charset);
    String value = request.getParameter("value");
    String description = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("description"), "", charset);
    String veryShortDescField = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("veryShortDesc"), "", charset);
    String gp1 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp1"), "", charset);
    String gp2 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp2"), "", charset);
    String gp3 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp3"), "", charset);
    String gp4 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp4"), "", charset);
    String gp5 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp5"), "", charset);
    String gp6 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp6"), "", charset);
    String gp7 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp7"), "", charset);
    String gp8 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp8"), "", charset);
    String gp9 = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("gp9"), "", charset);

    Integer sort = 10;
    boolean sort_error = false;
    try {
        if (request.getParameter("sort") != null && !request.getParameter("sort").equals("")) {
            sort = Integer.valueOf(policy.sanitize(request.getParameter("sort")));
        }
    } catch (Exception ex) {
        sort_error = true;
    }

    /**
     * Checking all constrains before calling the services.
     */
    if (StringUtil.isNullOrEmpty(id)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Invariant")
                .replace("%OPERATION%", "Create")
                .replace("%REASON%", "Invariant name is missing!"));
        ans.setResultMessage(msg);
    } else if (sort_error) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Invariant")
                .replace("%OPERATION%", "Create")
                .replace("%REASON%", "Could not manage to convert sort to an integer value!"));
        ans.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */

        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        IInvariantService invariantService = appContext.getBean(IInvariantService.class);
        IFactoryInvariant factoryInvariant = appContext.getBean(IFactoryInvariant.class);
        Invariant invariantData = factoryInvariant.create(id, value, sort, description, veryShortDescField, gp1, gp2, gp3, gp4, gp5, gp6, gp7, gp8, gp9);

        if (invariantService.hasPermissionsCreate(invariantData, request)) {
            ans = invariantService.create(invariantData);

            if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                /**
                 * Object updated. Adding Log entry.
                 */
                ILogEventService logEventService = appContext.getBean(LogEventService.class);
                logEventService.createForPrivateCalls("/CreateInvariant", "CREATE", "Create Invariant : ['" + id + "']", request);
            }
        } else {
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "Invariant")
                    .replace("%OPERATION%", "Create")
                    .replace("%REASON%", "You are not allowed to do that or invariant is not public."));
            ans.setResultMessage(msg);
        }
    }

    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", ans.getResultMessage().getDescription());

    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}
 
Example 16
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String charset = request.getCharacterEncoding() == null ? "UTF-8" : request.getCharacterEncoding();

    response.setContentType("application/json");

    String id = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("idName"), "", charset);
    String value = request.getParameter("value");

    boolean userHasPermissions = request.isUserInRole("Administrator");

    /**
     * Checking all constrains before calling the services.
     */
    if (StringUtil.isNullOrEmpty(id)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Invariant")
                .replace("%OPERATION%", "Delete")
                .replace("%REASON%", "Invariant name is missing!"));
        ans.setResultMessage(msg);
    } else if (!userHasPermissions) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Invariant")
                .replace("%OPERATION%", "Delete")
                .replace("%REASON%", "You don't have the right to do that"));
        ans.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */

        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        IInvariantService invariantService = appContext.getBean(IInvariantService.class);

        Invariant invariantData = invariantService.convert(invariantService.readByKey(id, value));

        if (invariantService.hasPermissionsDelete(invariantData, request)) {
            ans = invariantService.delete(invariantData);

            if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                /**
                 * Object updated. Adding Log entry.
                 */
                ILogEventService logEventService = appContext.getBean(LogEventService.class);
                logEventService.createForPrivateCalls("/DeleteInvariant", "DELETE", "Delete Invariant : ['" + id + "']", request);
            }
        } else {
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "Invariant")
                    .replace("%OPERATION%", "Delete")
                    .replace("%REASON%", "You don't have the right to do that."));
            ans.setResultMessage(msg);
        }
    }

    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", ans.getResultMessage().getDescription());

    response.getWriter().print(jsonResponse.toString());
    response.getWriter().flush();

}
 
Example 17
Source Project: datax-web   File: ServletUtils.java    License: MIT License 3 votes vote down vote up
/**
 * 描述:获取 post 请求内容
 * <pre>
 * 举例:
 * </pre>
 *
 * @param request
 * @return
 * @throws IOException
 */
public static String getRequestPostStr(HttpServletRequest request) throws IOException {
    byte buffer[] = getRequestPostBytes(request);
    String charEncoding = request.getCharacterEncoding();
    if (charEncoding == null) {
        charEncoding = "UTF-8";
    }
    return new String(buffer, charEncoding);
}
 
Example 18
Source Project: lams   File: UrlPathHelper.java    License: GNU General Public License v2.0 3 votes vote down vote up
/**
 * Determine the encoding for the given request.
 * Can be overridden in subclasses.
 * <p>The default implementation checks the request encoding,
 * falling back to the default encoding specified for this resolver.
 * @param request current HTTP request
 * @return the encoding for the request (never {@code null})
 * @see javax.servlet.ServletRequest#getCharacterEncoding()
 * @see #setDefaultEncoding
 */
protected String determineEncoding(HttpServletRequest request) {
	String enc = request.getCharacterEncoding();
	if (enc == null) {
		enc = getDefaultEncoding();
	}
	return enc;
}
 
Example 19
/**
 * Determine the encoding for the given request. Can be overridden in
 * subclasses.
 * <p>
 * The default implementation checks the request encoding, falling back to
 * the default encoding specified for this resolver.
 * 
 * @param request
 *            current HTTP request
 * @return the encoding for the request (never <code>null</code>)
 * @see javax.servlet.ServletRequest#getCharacterEncoding
 * @see #setDefaultEncoding
 */
protected String determineEncoding(HttpServletRequest request) {
	String enc = request.getCharacterEncoding();
	if (enc == null) {
		enc = this.defaultEncoding;
	}
	return enc;
}
 
Example 20
Source Project: j360-dubbo-app-all   File: WebUtils.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Determine the encoding for the given request.
 * Can be overridden in subclasses.
 * <p>The default implementation checks the request's
 * {@link ServletRequest#getCharacterEncoding() character encoding}, and if that
 * <code>null</code>, falls back to the {@link #DEFAULT_CHARACTER_ENCODING}.
 *
 * @param request current HTTP request
 * @return the encoding for the request (never <code>null</code>)
 * @see javax.servlet.ServletRequest#getCharacterEncoding()
 */
protected static String determineEncoding(HttpServletRequest request) {
    String enc = request.getCharacterEncoding();
    if (enc == null) {
        enc = DEFAULT_CHARACTER_ENCODING;
    }
    return enc;
}