Sergeonclear

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Thursday, February 7, 2008

Internationalization utility

Posted on 11:32 PM by Unknown
This uses jericho HTML parses.
This utility is just to extract static text out of a HTML/JSP and put in the property file. The static text is replaced with [spring:message key="xyz /].

Just provide input and output folders and all the i18n message are extracted to srcFolder\messages_en_US.properties file and JSP/HTML are updated.

Code is below:
/**
*
*/
package parser.htmlParser;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import au.id.jericho.lib.html.Element;
import au.id.jericho.lib.html.OutputDocument;
import au.id.jericho.lib.html.Segment;
import au.id.jericho.lib.html.Source;
import au.id.jericho.lib.html.TextExtractor;

/**
* @author Sandeep.Maloth
*
*/
public class JerichoInternationalizer {
final static String SRC_DIR_NAME = "D:\\ProjectRelated\\evaluation\\liferay4.3.2\\webapps\\cmpWeb2\\WEB-INF\\jsp";

final static String DSTN_DIR_NAME = "D:\\ProjectRelated\\evaluation\\liferay4.3.2\\webapps\\cmpWeb2\\WEB-INF\\jsp\\TEMP";

final static String FILE_NAME = "articledisplay_view.jsp";

static Map messageKeyValueHolder = new LinkedHashMap();

static Map messageValueKeyHolder = new LinkedHashMap();

static Map elementsToReplace = new LinkedHashMap();

static int counter = 1;

/**
* @param args
* @throws IOException
* @throws Exception
*/
public static void main(String[] args) throws Exception, IOException {
doProcess(SRC_DIR_NAME, DSTN_DIR_NAME );
storeMessages(SRC_DIR_NAME);
System.out.println(messageKeyValueHolder);
System.out.println(messageValueKeyHolder);

}

private static void doProcess(String srcDirName, String dstnDirName) throws IOException, FileNotFoundException, Exception {
File dir = new File(srcDirName);
String files[] = dir.list();

for (int i = 0; i < files.length; i++) {
String fileName = files[i];
final File fileObject = new File(srcDirName, fileName);
if (fileObject.isDirectory()) {
String tempSrcDir = srcDirName + "\\" + fileName;
final String tempDstnDirName = dstnDirName + "\\"+fileName;
doProcess(tempSrcDir, tempDstnDirName);
} else {
if (!(fileName.toUpperCase().endsWith("JSP") || fileName.toUpperCase().endsWith("HTML"))) {
System.out.println("Skipping " + fileName);
continue;
}

System.out.println("Parsing .... " + fileName);

Source source = new Source(new FileInputStream(fileObject));

source.fullSequentialParse();
final List childElements = source.getChildElements();
extractMessages(childElements, source, fileName);

// The extracted messages will be in elementsToReplace and need
// to be replaced in the source
Set entrySet = elementsToReplace.entrySet();
OutputDocument outputDocument = new OutputDocument(source);
for (Iterator iter = entrySet.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
Segment content = (Segment) entry.getKey();
String value = (String) entry.getValue();

outputDocument.replace(content, value);

}

final File dstnDir = new File(dstnDirName);
if (!dstnDir.exists()) {
dstnDir.mkdirs();
}
final File tempFile = new File(dstnDirName, fileName);
FileWriter fileWriter = new FileWriter(tempFile);
outputDocument.writeTo(fileWriter);
fileWriter.close();

elementsToReplace.clear();
System.out.println();
}
}
}

private static void storeMessages(String dstnDirName) throws FileNotFoundException, IOException {
Set msgsEntrySet = messageKeyValueHolder.entrySet();
FileWriter fileWriter = null;
StringBuffer sbuf = new StringBuffer();
for (Iterator iter = msgsEntrySet.iterator(); iter.hasNext();) {
final Object object = iter.next();
System.out.println(object);
Map.Entry entry = (Map.Entry) object;
String key = (String) entry.getKey();
String value = (String) entry.getValue();
sbuf.append(key).append("=").append(value).append("\r\n");
}
try {
fileWriter = new FileWriter(new File(dstnDirName + "\\messages_en_US.properties"));
fileWriter.write(sbuf.toString());
} finally {
if (fileWriter != null)
fileWriter.close();
}
}

private static void extractMessages(List childElements, Source source, String fileName) throws Exception {

for (Iterator iter = childElements.iterator(); iter.hasNext();) {
Element element = (Element) iter.next();

final List childElements2 = element.getChildElements();

if (childElements2 != null && childElements2.size() > 0) {
extractMessages(childElements2, source, fileName);
} else {
final TextExtractor textExtractor = element.getTextExtractor();

String txt = textExtractor.toString();
String key = "";
if (txt != null) {
txt = txt.trim();

if (txt.length() > 0 && !StringUtils.isNumeric(txt)) {
System.out.println(txt);
String ctrString = "";
if (counter < 10) {
ctrString = "0000" + counter;
} else if (counter < 100) {
ctrString = "000" + counter;
} else if (counter < 1000) {
ctrString = "00" + counter;
}else if(counter<10000){
ctrString = "0" + counter;
}

if (!messageValueKeyHolder.containsKey(txt)) {
key = "MESG" + ctrString;
messageKeyValueHolder.put(key, txt);
messageValueKeyHolder.put(txt, key);
elementsToReplace.put(element.getContent(), "<spring:message code=\"" + key + "\"></spring:message>");

counter++;
} else {
key = (String) messageValueKeyHolder.get(txt);
elementsToReplace.put(element.getContent(), "<spring:message code=\"" + key + "\"></spring:message>");

}
}
}
}
}
}

}

Read More
Posted in All about UK Visa HSMP VS H1 | No comments

Wednesday, February 6, 2008

internationalization support in spring -usage

Posted on 11:28 PM by Unknown

Spring Internationalization web MVC

1. Add two properties files in /WEB-INF/classes:
1) messages_zh_CN.properties Chinese message file.
2) messages_en_US.properties English message file.

2. Add bean in action-servlet.xml:
[bean id="localeResolver" class="org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver"/]

Spring will set UI language locale and message according to the client-side browser locale configuration.

3. JSP files

1. [fmt:message key="key1"/]

2. Error message
[spring:bind path="account.password"]
[input type="password" name="${status.expression}" value="${status.value}"/]
[span class="fieldError"]${status.errorMessage}[/span]
[/spring:bind]

3. button
[input type="submit" class="button" name="prev" value="[fmt:message key="prev"/]" /]

Spring Internationalization for portlet MVC

1. Add two properties files in /WEB-INF/classes:

1) messages_zh_CN.properties -Chinese message file.

The Java properties files are created using a native encoding or in UTF-8. This must be converted to an ascii format for Java. This is done as part of the extraction process on the translation website but if you have a manually created file in UTF-8 that needs to be encoded, then use the native2ascii command that comes with with Java JDK.

Call native2ascii to ascii encoding, specifying the original file has UTF-8 encoding:

Eg: native2ascii.exe -encoding UTF-8 chinese_zh.txt ApplicationResource_zh_CN.properties

2) messages_en_US.properties -English message file.

2. Update applicationContext.xml file as below:

/WEB-INF/classes/messages " style="position: absolute; margin-left: 0pt; margin-top: 0pt; width: 451.5pt; height: 96pt; z-index: 1;" o:allowoverlap="f"> Spring will set UI language locale and message according to the client-side browser locale configuration.For guest user liferay creates a cookie called GUEST_LANGUAGE_ID with the language based on the browser configured locale.

  1. Replace the static text in JSP files with

[spring:message code=”key1”/] where key1 is the key available in message_xx.properties file

Note :The Java properties files are created using a native encoding or in
UTF-8. This must be converted to an ascii format for Java. This is done
as part of the extraction process on the translation website but if you
have a manually created file in UTF-8 that needs to be encoded, then
use the native2ascii command that comes with with Java JDK.
Call native2ascii to ascii encoding, specifying the original file has UTF-8 encoding:

native2ascii.exe -encoding UTF-8 chinese_zh.txt ApplicationResource_zh_CN.properties

Ref: http://wiki.lamsfoundation.org/display/lams/LAMS+i18n

The below JSP is Useful to troubleshoot locale related issues:

[%

//java.util.Locale locale = (java.util.Locale)request.getSession().getAttribute

("org.apache.struts.action.LOCALE");

Locale locale = renderRequest.getLocale();

String language = locale.getLanguage();

String country = locale.getCountry();

out.println(language +" "+country);

// Remember, messagesis the fully qualified name of a bundle in the classpath

// e.g. WEB-INF/classes/messages_*.properties

ResourceBundle res = ResourceBundle.getBundle("messages", new java.util.Locale(language, country));

java.util.Enumeration en=res.getKeys();

while(en.hasMoreElements())

{

out.println(en.nextElement());

}

out.print(res.getString("key1"));

%]

Read More
Posted in i18n locale localization internationalization spring liferay portlet locale | No comments
Newer Posts Older Posts Home
Subscribe to: Comments (Atom)

Popular Posts

  • LinuxPerformance Tuning(apache,tomcat,linux) and related
    Web profiling -- HTTPAnalyzer -- -- YSlow --CSS,Javascript report , time/size measurement for individual component is good. -- F...
  • (no title)
    Hardware/Software stack:  iPhone 3Gs having iOS 5.1.1(latest as of today).  The Xcdode 4.2 failed to detect this iphone as it has support on...
  • Spring interceptor ordering
    SimpleUrlHandlerMapping uses a hashMap to hold the interceptors. Ordering can only be guaranteed by setting  order property.. By default it ...
  • SVN/ Subversion Tips and traps
    SVN could be tricky and waste a hell lot of time. Case Issue : Normally we run SVN server in linux. Our dev env will be in windows NT. Windo...
  • Liferay CMS/ web content management/ workflow/ staging
    Liferay out of the box has a web content management system. The web pages can mostly have these web content (articles) as web pages. The web...
  • Cobertura- junit coverage tool
    First, you need to add a task definition to the build.xml file. This top-level taskdef element specifies that the cobertura.jar file is i...
  • XSLT caching Transformers
     The usage of cached transformer objects is recommended here A sample implementation of CachingTransformerFactory is here The above code abs...
  • Rewrite rules in apache and IIS
    Well we can control how the server serves stuff to clients by defining rewrite rules. As servers are dumb, its important to explain well abo...
  • Real-Time Tracking and Tuning for Busy Tomcat Servers
    A very nice article which details on possible options for tomcat server monitoring to tweak its performance. http://www.devx.com/Java/Articl...
  • External Javascript from Java Servlets
    Copied from http://myappsecurity.blogspot.com/2007/01 Like to thank anurag for the content. /breaking-same-origin-barrier-of.html External ...

Categories

  • AJAX javascript
  • All about UK Visa HSMP VS H1
  • All about UK Visa HSMP VS H1 hsmp assistance
  • amazon
  • android apps ship control radio hindi
  • Apache 2.x setup Quick guide for Linux
  • apache commons configurator usage
  • apache commons usage
  • arsenals for developers
  • article
  • Batch script to load developer environment
  • Blind folded chess
  • Castor castor convert dtd to xsd
  • cloud comparision price
  • cloud comparison blog
  • cloud computing monthly price
  • cloud usage
  • Cobertura- junit coverage tool
  • Code generators
  • cron jobs expressions
  • cruisecontrol cruise control
  • debugging eclipse tips
  • developer tools
  • document library
  • easy mock jmock vs mocking java tdd
  • External Javascript from Java Servlets
  • fedora 9 lenovo 3000 n200 windows xp dual boot problem
  • Fire fox plugins and tweaks
  • Free PHP hosting
  • gods debris the religion war scott adams dilbert
  • google app engine
  • gwt javascript
  • hibernate second level cache
  • i18n locale localization internationalization spring liferay portlet locale
  • ibatis sybase mapping
  • image gallery
  • iphone apps bri8 apple
  • iphone shsh 3gs ipsw downgrade ifaith tinyumbrella ios5.1.1 to ios5.0
  • java
  • java JDBC
  • javascript junit testing
  • Javascript trouble shooting tool
  • Jboss overview
  • jmeter load testing custom java sampler javasamplerclient xml test
  • JNDI test JSP page
  • Joomla CMS
  • JProfiler setup jprofiler on linux
  • jquery IE AJAX issues
  • jquery spring AJAX
  • keyboard music java typing soothing notes auto suggest
  • liferay kids version
  • liferay web 2.0 java/j2ee
  • linux - the difference between hard and soft links
  • linux mysql
  • linux mysql setup quick start
  • Linux ssh autologin with putty
  • LINUX usefuls
  • linux)
  • LinuxPerformance Tuning(apache
  • log4j setup useful
  • lucene solr
  • mac m701 android skype not working crash
  • maven
  • maven cut reduce build time
  • microsoft ODBC oracle dll connection issues
  • Mobile Ad Services (adwhirl)
  • opsourcecloud
  • oracle connect by hierarchy
  • oracle table previlege
  • Oracle thin vs OCI(type II/thick) drivers
  • pdf 2 text
  • Pega PRPC
  • php
  • rackspacecloud
  • Rewrite rules in apache and IIS
  • scaffold
  • setting up a static ip on SKY broadband
  • setup quick start
  • Single Sign on - OpenSSO with Liferay
  • smart gwt
  • smtp email test mock server james
  • SMTP MAIL telnet windows
  • Software tools mind map freemind j2ee tools
  • Speed typing tips.
  • Spring + Hibernate Usefuls BaseDAOHibernate
  • Spring annotations with spring-mock not working 2.0 2.5.6
  • spring jndi datasource lookup
  • Spring portlet mvc and spring servlet mvc validation
  • Spyware trojan and virus removal tools
  • struts magic
  • SVN/ Subversion Tips and traps
  • tabbed ms dos console cygwin console
  • Texter - An auto text expander autotyper
  • Textpad tricks
  • The art of debugging
  • tomcat
  • Tomcat Exploded war - cut deployment time
  • Tomcat on linux tips
  • Tomcat on linux tips commands
  • TypeIt4Me
  • Typinator
  • Useful Eclipse Plugins
  • Useful Eclipse Plugins eclipse shortcuts keys
  • Useful tools
  • web content
  • xcode cocos2d iphone box2d
  • xpath xml xquery

Blog Archive

  • ►  2013 (19)
    • ►  August (17)
    • ►  July (1)
    • ►  January (1)
  • ►  2012 (7)
    • ►  August (1)
    • ►  June (4)
    • ►  April (2)
  • ►  2011 (20)
    • ►  November (1)
    • ►  October (1)
    • ►  August (1)
    • ►  July (3)
    • ►  June (1)
    • ►  April (2)
    • ►  March (4)
    • ►  February (1)
    • ►  January (6)
  • ►  2010 (27)
    • ►  December (3)
    • ►  July (2)
    • ►  May (3)
    • ►  April (2)
    • ►  March (5)
    • ►  February (10)
    • ►  January (2)
  • ►  2009 (32)
    • ►  December (5)
    • ►  November (2)
    • ►  September (3)
    • ►  August (6)
    • ►  June (4)
    • ►  May (4)
    • ►  April (3)
    • ►  March (2)
    • ►  February (3)
  • ▼  2008 (28)
    • ►  December (1)
    • ►  October (2)
    • ►  September (2)
    • ►  August (4)
    • ►  July (7)
    • ►  June (1)
    • ►  April (2)
    • ►  March (2)
    • ▼  February (2)
      • Internationalization utility
      • internationalization support in spring -usage
    • ►  January (5)
  • ►  2007 (24)
    • ►  December (3)
    • ►  November (2)
    • ►  October (6)
    • ►  September (1)
    • ►  August (3)
    • ►  July (8)
    • ►  June (1)
Powered by Blogger.

About Me

Unknown
View my complete profile