Unicode characters are being saved incorrectly - mysql

I have a mysql database with unicode text strings in it. My JSF application (running on tomcat 6) can read these unicode strings out and display them correctly in the browser. All the html charsets are set to UTF-8.
When I save my object, even having made no changes, Hibernate persists it back to the database. If I look directly in the database now, I see that characters with accents have become junk.
My database connection string is:
<property name="hibernate.connection.url"
value="jdbc:mysql://database.address.com/dbname?autoReconnect=true&zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf8"/>
Changing that characterEncoding to UTF-8 instead of utf8 makes no difference.
Actually it was working days ago for sure, but now it isn't and I'm out of ideas for what to check. Do you have any suggestions? I can provide any further info deemed relevant.

Does it only happen on certain tables? Perhaps the DEFAULT CHARSET of those tables is different than the others. (http://dev.mysql.com/doc/refman/5.1/en/charset-table.html)

Some options to resolve that come to my mind:
if using facelets, specify <?xml version="1.0" encoding="UTF-8"?> at the top of the page
if using JSP, specify <%# page pageEncoding="utf-8" %>
if that does not work, make a filter that is mapped to the faces servlet, and does request.setCharacterEncoding("utf-8")

I had the same problem as you but with PostgreSQL. You can use filter as below. It worked for me. I think that it must be better solution for that, but i haven't found yet :/
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class UnicodeFilter implements Filter {
#Override
public void destroy() {}
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
// Set the characterencoding for the request and response streams.
req.setCharacterEncoding("UTF-8");
res.setContentType("text/html; charset=UTF-8");
chain.doFilter(req, res);
}
#Override
public void init(FilterConfig arg0) throws ServletException {}
}
In web.xml:
<filter>
<filter-name>utffilter</filter-name>
<filter-class>utils.UnicodeFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>utffilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

In Spring a simplest solution i've found is CharacterEncodingFilter.
<filter>
<filter-name>encoding-filter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding-filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Ensure UTF-8 encoded pages so that certain characters are displayed
and submitted correctly...
Add this filter to web.xml.
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Related

Getting Jersey 2.x POJO JSON support to work with Jetty

I'm new RESTful web services and have been playing around with Jersey and Heroku (which uses a Jetty stack). I'm writing a simple REST API which returns a Map<String,String> in JSON for a GET request.
I'm however running into a 500 eror. The error message is :
HTTP Status 500 - org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=application/json, type=class java.util.LinkedHashMap, genericType=java.util.HashMap.
Below is the code snippet for my resource :
#GET
#Produces("application/json")
public HashMap<String,String> getIt() {
HashMap<String,String> nameValue = new LinkedHashMap<String,String>();
nameValue.put("Alpha","One");
return nameValue;
}
Below is my web.xml file:
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>org.example.services</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
Here is my Main class
public class Main {
public static void main(String[] args) throws Exception{
// The port that we should run on can be set into an environment variable
// Look for that variable and default to 8080 if it isn't there.
String webPort = System.getenv("PORT");
if (webPort == null || webPort.isEmpty()) {
webPort = "8080";
}
final Server server = new Server(Integer.valueOf(webPort));
final WebAppContext root = new WebAppContext();
root.setContextPath("/");
// Parent loader priority is a class loader setting that Jetty accepts.
// By default Jetty will behave like most web containers in that it will
// allow your application to replace non-server libraries that are part of the
// container. Setting parent loader priority to true changes this behavior.
// Read more here: http://wiki.eclipse.org/Jetty/Reference/Jetty_Classloading
root.setParentLoaderPriority(true);
final String webappDirLocation = "src/main/webapp/";
root.setDescriptor(webappDirLocation + "/WEB-INF/web.xml");
root.setResourceBase(webappDirLocation);
server.setHandler(root);
server.start();
server.join();
}
}
Even after browsing through previous Stackoverflow answers like this or this, I could not find a way to solve my problem as they do not address Jersey 2.x with Jetty. I've added the following to my pom.xml file, however the problem still persists as unable to register the JSON bindings with the Jetty server.
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
Automatic registration of providers by moxy didn't work as stated by Jersey Reference.
As per what they have stated, only moxy and jackson has POJO to JSON conversion feature.
Documentation says Jackson doesn't auto register(Not a problem any way!)
1. Swap Moxy with Jackson in POM.XML
Remove :
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>${jersey.version}</version>
</dependency>
Add:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
</dependency>
2. Register Jackson Message Body Readers and Writers :
Add org.codehaus.jackson.jaxrs to provider packages list. Here is my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>Web app name</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.myorg.myproj.api;org.codehaus.jackson.jaxrs</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Web app name</servlet-name>
<url-pattern>/v1/*</url-pattern>
</servlet-mapping>
P.S.
I am not promoting jackson, just that moxy didn't work for me, its writers failed to auto register as they advertised and could not find documentation about manual registration!
If using Jackson Implementation
As per the Jersey Documentation - Note that there is a difference in namespaces between Jackson 1.x (org.codehaus.jackson) and Jackson 2.x (com.fasterxml.jackson).
If you are using jackson 2.x, you need to register com.fasterxml.jackson.jaxrs as init param to the ServletContainer in your web.xml as follows:
<servlet>
<servlet-name>RESTServlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.fasterxml.jackson.jaxrs</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

JSP Loading Incompletely on Websphere Application Server 8.5

I am planning to migrate from Websphere Application Server (WAS) 7 to version 8.5. I have deployed an application which runs fine on WAS 7 and I have not made any changes to it since migration.
However, on WAS 8.5, the JSP pages are not being getting loaded completely. When I examine these pages through "View Source," I can see that the HTML content is only half-loaded. Specifically, the HTML itself is not completed with closing tags.
In WAS 7, the result of "View Source" looks like this:
<html>
...
...
<td..../>
<td..../>
<td..../>
...
...
</html>
But the same in WAS 8.5 looks like:
<html>
...
...
<td..../>
<td..../>
<td..
I have done the following so far:
I compared the class files of compiled JSP on WAS 7 and WAS 8.5. They are almost same, so I assume that the compilation is done properly. However, displaying the page with in HTML is not getting done properly.
I tried enabling JavaScript debugging on IE, but it did not show any errors while loading.
There are no errors in application logs and server logs that I can see.
My questions:
The set of <td> tags above is generated through JSP custom tags. Should I check code of the tags?
Is there any Custom property in Web Container Settings in Websphere which control such behaviour?
Is there any timeout property which is causing page to stop loading half-way?
Please suggest what else should I check.
this is a well known behavior that happens when an Exception is thrown and Response has already been commited.
generally the exception is logged, but in some particular case it is not.
i read you workarounded removing EncodingFilter, but if you still want to find the problem you can try to code a Filter, that must be executed BEFORE EncodingFilter, wich sets response.setBufferSize to a larger size.
this can be such a filter:
public class ResponseBufferFilter implements Filter
{
private FilterConfig filterConfig;
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
try
{
// or better take the value from filterConfig.getInitParameter
response.setBufferSize(100000000);
chain.doFilter(request, response);
}
catch(Exception e)
{
e.printStackTrace();
throw new ServletException(e.getMessage(), e);
}
}
#Override
public void init(FilterConfig filterConfig) throws ServletException
{
this.filterConfig = filterConfig;
}
#Override
public void destroy()
{
filterConfig = null;
}
}
and this is the mapping:
<filter>
<filter-name>Response Buffer Filter</filter-name>
<filter-class>test.example.filter.ResponseBufferFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Response Buffer Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>SetCharacterEncoding</filter-name>
<!-- provide the class causing unwanted behavior -->
<filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SetCharacterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
this will not solve the problem, but at least it should allow log of exception, one way or another, if any.

Unable to set character encoding UTF-8 in .xhtml

I have set the xhtml to UTF-8 and at ServletRequest. But it seems that it is still unable to detect the character encoding as UTF-8. I am working with Primefaces 3.5 with WebSphere 8.
.xhtml
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
RedirectLogin
public class RedirectLogin implements Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (request.getCharacterEncoding() == null) {
request.setCharacterEncoding("UTF-8");
}
chain.doFilter(request, response);
}
}
web.xml
<filter>
<description>Redirect unauthenticated session to login page.</description>
<display-name>RedirectLogin</display-name>
<filter-name>RedirectLogin</filter-name>
<filter-class>com.belsize.servlet.filter.RedirectLogin</filter-class>
<init-param>
<param-name>login_page</param-name>
<param-value>/faces/login.xhtml</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>RedirectLogin</filter-name>
<url-pattern>/RedirectLogin</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>RedirectLogin</filter-name>
<url-pattern>*.xhtml</url-pattern>
</filter-mapping>
I guess my environment is "dirty". After I clean my project, redeploy, its working fine now.

How to use #PathParam?

I am following simple steps of tutorial and till now I cant figure out why it displays error.
I am trying to return simple JSON using a simple JAX-RS application.
The following is my code and web.xml settings:
package ws;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
#Path("/employee/{empno}")
public class EmployeeResource {
#Context
private UriInfo context;
public EmployeeResource() {
}
#GET
#Produces("application/json")
public String getJson( #PathParam("empno") int empno) {
switch(empno) {
case 1 :
return "{'name':'George Koch', 'age':58}";
case 2:
return "{'name':'Peter Norton', 'age':50}";
default:
return "{'name':'unknown', 'age':-1}";
}
}
#PUT
#Consumes("application/json")
public void putJson(String content) {
}
}
web.xml is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>ws</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/resources/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
And then I use address:
localhost:8084/restdemo/resources/employee/empno=1
but it shows 404 error.
Call
localhost:8084/restdemo/resources/employee/1
A #PathParam is not a #QueryParam. Its name is derived from its position in the query path, not by a give name like empno=1. Since your #Path is
#Path("/employee/{empno}")
the element of your URL path that is at the position of {empno} is automatically assigned to your #PathParam empno.
Edit:
If you want to call a URL like
localhost:8084/restdemo/resources/employee?empno=1
you must use
#Path("/employee")
public String getJson(#QueryParam("empno") int empno)
Note the ? that is the border between the URL path left of it and the query on the right of it.
Hint:
Your JSON is not valid. You must use double quotes " instead of single quotes ':
return "{\"name\":\"George Koch\", \"age\":58}";

encoding filter , struts working just when using html:form tag

I face this problem. I have a filter that sets the character encoding of the request according to the filter's config (for example, to UTF-8). This works with forms coded using the struts html:form tag. However, if I use the ordinary HTML form tag, the data are not encoded correctly.
This is the filter definition in the web.xml:
<filter>
<filter-name>Encoding Filter</filter-name>
<filter-class>EncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Encoding Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Here's the filter :
public class EncodingFilter implements javax.servlet.Filter {
private String encoding;
public void init(FilterConfig filterConfig) throws ServletException {
this.encoding = filterConfig.getInitParameter("encoding");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
request.setCharacterEncoding(encoding);
filterChain.doFilter(request, response);
}
public void destroy() {
}
}
If you use a Struts tag <html:form> and omit the METHOD attribute it defaults to POST.
If you use a standard HTML <form> and omit the METHOD attribute it defaults to GET.
Tomcat will process your POST and GET parameters differently:
POST: your filter will be used. Note that you should really only set the request character encoding if it has not been specified by the client (your filter is always setting it to UTF-8). Tomcat comes with a filter SetCharacterEncodingFilter.java that does this.
GET: Tomcat will use ISO-8859-1 as the default character encoding. There are two ways to specify how GET parameters are interpreted:
Set the URIEncoding attribute on the element in server.xml to something specific (e.g. URIEncoding="UTF-8").
Set the useBodyEncodingForURI attribute on the element in server.xml to true. This will cause the Connector to use the request body's encoding for GET parameters.
This is all in: http://wiki.apache.org/tomcat/FAQ/CharacterEncoding