Monday, August 20, 2012

Use resource bundle messages files out of the classpath

Target audience for this post is have a little bit of experience in using resource bundle for localization in Java. Usually, you will have to put the relevant message files(Which contains key=value pairs) in the classpath and you will have to give the location when get the resource bundle object. For example, to get your Messages_en.properties file you implement following code.
Locale locale = new Locale( "en" );
String bundleBase = "myPackage.localizedMsgs.i18n.Messages";
ResourceBundle resourceBundle = ResourceBundle.getBundle( bundleBase, locale );
But in that case, if you wanted to do a change on any message you will have to rebuild the war file (if you are developing a web app) and deploy it. But I came across with a scenario where you need to keep message files out of the war and let user to do changes when necessary. Following example shows how to load such files on to the application context. Message files location is = ${catalina.base}/conf/messages/ so, the en message file will be, ${catalina.base}/conf/messages/Messages_en.properties Edit the catalina.properties file which is located in ${catalina.base}/conf/ directory. Add the folder location to the shared.loader parameter.
------file: catalina.properties-----

shared.loader=${catalina.base}/conf/messages/
Then the files in that location will be directly accessible on your application. Use following code and initialize the resource bundle with those files.
Locale locale = new Locale( "en" );
String bundleBase = "Messages";
ResourceBundle resourceBundle = ResourceBundle.getBundle( bundleBase, locale );
This was working perfectly for me. Thanks for reading.

Wednesday, September 29, 2010

Axis2 Java Web Services with NetBeans deployed on Tomcat

As we discussed earlier (previous post) you should set axis2 in to your tomcat web server.

Apply axis2 plugin

First you need to install "Axis2 Support" plugin to the net beans. Open the netbeans IDE and navigate to Tools -> Plugins. The plugins list will be displayed. If "Axis2 Support" is not showing there, please update the list.Then click the install button below and continue with installing...

Add apache web server to IDE

Ok, now our next task is to add apache to the netbeans IDE. To do that, go to the Services tab (or Window -> Services). Right click on servers and click "Add Server". It will popup following window. Select Tomcat 6.0 (according to your sever version) and continue.
You should navigate the folder which you have been placed Tomcat server. Add username and password (in my case I just used admin/admin). Then you will appear new server like this, You can simply start server by right click on tomcat and selecting start option.

Setup .aar file creating directory

Go to Tools -> Options. And now you will be able to see an separate tab for Axis2 with its logo. Click on that.
Now browse to your axis2.war file for "Target Location for axis2 .aar files:" field. And tick on use tomcat manager for deployment, enter username and password which you set earlier (in my case admin/admin). Then click ok.

Creating Web Services

Open a new project (File -> New Project). Select Java and Java Application. Add a desired project name (I used "CardValidator") and complete creating project. Then right click on newly created project and select New -> Axis2 Service From Java...
Then you will get popup window. There is nothing to change, in this case lets take this as Create Empty Web Service and click next. Then following step will visible. Give any name you wish as class name (in my case "MyClassValidator") and select package from list (in my case "cardvalidator"). And Finish it. Now its done. You will find a sample service call hello:String.
Important:You should right click on Axis2 Web Services and Deploy to Server, before test the sample program.
After that you can right click on hello:String and Test operation in browser. It will give following browser opening for your request.
Writing new methods is not a big deal.
Let's write a method to accept a card number and check whether it is valid one or not. If its starts with "1111" then its a valid card and should return true. Else should return false.
Simply write following java method on MyCardValidator class (which contains method hello as well)
public boolean validateCard(String cardNumber){

if(cardNumber.startsWith("1111")){
return true;
}else{
return false;
}
}

And now right click on MyCardValidator and deploy to server. Then your new service method will appear as a service. You can right click on it and test it.
Then your browser will open with link like this "http://localhost:8080/axis2/services/MyCardValidator/validateCard?cardNumber=XYZ". By changing XYZ you can check whether your service works properly.
Note: If your default browser is IE or Firefox, then the output will looks like a XML message. If you used chrome, the output will just be text values.

By placing the axis2.war file in any tomcat server after you creating it you can access to the web services in above manner.
Hope you got it correctly. If you got any problems pleas feel free to contact me by mailing or commenting here.
Your comments will be very useful for further writings.... :)
Thank you for visiting. :)

Setup tomcat and deploy axis2

First you better download the Apache Tomcat server from here(direct download).
Extract the zip file where ever you want. Then set an environment variable named JAVA_HOME. Right click computer -> Properties -> Advanced System Settings -> Environment Variables. Select New on "system variables" part. Then give JAVA_HOME as variable name and give the jdk directory (e.g. C:\Program Files\Java\jdk1.6.0_01) for variable value.
Now Tomcat is set properly.
Then you can download Axis2.war file containing zip from here(direct download). Extract the zip and place the .war file in apache/webapps folder(e.g. C:\apache-tomcat-6.0.29\webapps\axis2.war). Now you can start up the tomcat server and see whether axis2 has been deployed successfully. Run startup.bat file in apache-tomcat-6.0.29\bin folder. Then tomcat will start, then type "http://localhost:8080/axis2/" on your web browser and check whether following web page display to you.

Run shutdown.bat in apache-tomcat-6.0.29\bin folder and server will be shutdown.
So now lets move to write web services, in this case I ll be using netbeans IDE and the server settings and all that will be done on it. Everything will be described step by step on next post.

Wednesday, September 22, 2010

Select all friends to send facebook inivtations

When you wanted to invite your all friends to a group or a event you just have to do a simple thing.
Just select Invite button and wait for loading the friends list....
After loading that, go to the address bar and type following and press enter.

javascript:fs.select_all();

Then all of your friends will be selected and you can invite all of them at once.... :)
Enjoy it...
Cheers..

Wednesday, February 3, 2010

Live news feeds on your web site (Local news at Sri Lanka)

Lanka News papers website http://www.lankanewspapers.com provides a simple and nice tool to publish news on your website. Add the following piece of code on your website to add this feature.
 <script language="javascript" src="http://www.lankanewspapers.com/news/RSS_Java.jsp">
</script>

<script language='JavaScript'>
SL_News_Display(
'10', // Number of headlines to show (Max 20)
'200', // Width of the news table
'font-family: helvetica, impact, sans-serif;font-size: 10pt;', // Font
'#FFFFFF', // Background color of news table
'1' // Border width
);
</script>


Reference:

Friday, January 1, 2010

Sony Ericsson Information Web Synchronize (Store, Edit, share your mobile life)

Hi all....
This will be really helpful you guyz for save your valuable information on you phone. For instance if you lost your phone all the information on your phone will be lost with this. But Sony Ericsson has introduce nice web synchronizing tool which creates a clone of the information on your phone with them. It will help you to get back your information.
It keeps,
  • Contacts
  • Calendar
  • Bookmarks
  • Notes
  • Tasks


What you have to do is visit http://www.sonyericsson.com/wportal/uss/promotion?cc=lk&lc=en and create your own account. And according to the instructions giving by the application setup your synchronizing account of your mobile phone. To that, go in your phone, Menu > Settings >Connectivity >Synchronization. Create new account and add settings For example synchronizing server will be http://sync.sonyericsson.com/sync/server. Like wise set your settings according to the instructions giving.
Then go to the created profile and start synchronizing.
It's still on Beta version. But it is working properly.

Thursday, December 24, 2009

Snow fall on your website

You can add snow storm for your web site easily.....
Copy the following code to a new javascript file....

var snowStorm = null;

function SnowStorm() {

// --- PROPERTIES ---

this.flakesMax = 128; // Limit total amount of snow made (falling + sticking)
this.flakesMaxActive = 64; // Limit amount of snow falling at once (less = lower CPU use)
this.animationInterval = 35; // Theoretical "miliseconds per frame" measurement. 20 = fast + smooth, but high CPU use. 50 = more conservative, but slower
this.flakeBottom = null; // Integer for Y axis snow limit, 0 or null for "full-screen" snow effect
this.targetElement = null; // element which snow will be appended to (document body if null/undefined) - can be an element ID string, or a DOM node reference
this.followMouse = true; // Snow will change movement with the user's mouse
this.snowColor = '#fff'; // Don't eat (or use?) yellow snow.
this.snowCharacter = '*'; // • = bullet, · is square on some systems etc.
this.snowStick = false; // Whether or not snow should "stick" at the bottom. When off, will never collect.
this.useMeltEffect = true; // When recycling fallen snow (or rarely, when falling), have it "melt" and fade out if browser supports it
this.useTwinkleEffect = false; // Allow snow to randomly "flicker" in and out of view while falling
this.usePositionFixed = false; // true = snow not affected by window scroll. may increase CPU load, disabled by default - if enabled, used only where supported

// --- less-used bits ---

this.flakeLeftOffset = 0; // amount to subtract from edges of container
this.flakeRightOffset = 0; // amount to subtract from edges of container
this.flakeWidth = 8; // max pixel width for snow element
this.flakeHeight = 8; // max pixel height for snow element
this.vMaxX = 5; // Maximum X velocity range for snow
this.vMaxY = 4; // Maximum Y velocity range
this.zIndex = 0; // CSS stacking order applied to each snowflake

// --- End of user section ---

// jslint global declarations
/*global window, document, navigator, clearInterval, setInterval */

var addEvent = (typeof(window.attachEvent)=='undefined'?function(o,evtName,evtHandler) {
return o.addEventListener(evtName,evtHandler,false);
}:function(o,evtName,evtHandler) {
return o.attachEvent('on'+evtName,evtHandler);
});

var removeEvent = (typeof(window.attachEvent)=='undefined'?function(o,evtName,evtHandler) {
return o.removeEventListener(evtName,evtHandler,false);
}:function(o,evtName,evtHandler) {
return o.detachEvent('on'+evtName,evtHandler);
});

function rnd(n,min) {
if (isNaN(min)) {
min = 0;
}
return (Math.random()*n)+min;
}

function plusMinus(n) {
return (parseInt(rnd(2),10)==1?n*-1:n);
}

var s = this;
var storm = this;
this.timers = [];
this.flakes = [];
this.disabled = false;
this.active = false;

var isIE = navigator.userAgent.match(/msie/i);
var isIE6 = navigator.userAgent.match(/msie 6/i);
var isOldIE = (isIE && (isIE6 || navigator.userAgent.match(/msie 5/i)));
var isWin9X = navigator.appVersion.match(/windows 98/i);
var isiPhone = navigator.userAgent.match(/iphone/i);
var isBackCompatIE = (isIE && document.compatMode == 'BackCompat');
var noFixed = ((isBackCompatIE || isIE6 || isiPhone)?true:false);
var screenX = null;
var screenX2 = null;
var screenY = null;
var scrollY = null;
var vRndX = null;
var vRndY = null;
var windOffset = 1;
var windMultiplier = 2;
var flakeTypes = 6;
var fixedForEverything = false;
var opacitySupported = (function(){
try {
document.createElement('div').style.opacity = '0.5';
} catch (e) {
return false;
}
return true;
})();
var docFrag = document.createDocumentFragment();
if (s.flakeLeftOffset === null) {
s.flakeLeftOffset = 0;
}
if (s.flakeRightOffset === null) {
s.flakeRightOffset = 0;
}

this.meltFrameCount = 20;
this.meltFrames = [];
for (var i=0; i this.meltFrames.push(1-(i/this.meltFrameCount));
}

this.randomizeWind = function() {
vRndX = plusMinus(rnd(s.vMaxX,0.2));
vRndY = rnd(s.vMaxY,0.2);
if (this.flakes) {
for (var i=0; i if (this.flakes[i].active) {
this.flakes[i].setVelocities();
}
}
}
};

this.scrollHandler = function() {
// "attach" snowflakes to bottom of window if no absolute bottom value was given
scrollY = (s.flakeBottom?0:parseInt(window.scrollY||document.documentElement.scrollTop||document.body.scrollTop,10));
if (isNaN(scrollY)) {
scrollY = 0; // Netscape 6 scroll fix
}
if (!fixedForEverything && !s.flakeBottom && s.flakes) {
for (var i=s.flakes.length; i--;) {
if (s.flakes[i].active === 0) {
s.flakes[i].stick();
}
}
}
};

this.resizeHandler = function() {
if (window.innerWidth || window.innerHeight) {
screenX = window.innerWidth-(!isIE?16:2)-s.flakeRightOffset;
screenY = (s.flakeBottom?s.flakeBottom:window.innerHeight);
} else {
screenX = (document.documentElement.clientWidth||document.body.clientWidth||document.body.scrollWidth)-(!isIE?8:0)-s.flakeRightOffset;
screenY = s.flakeBottom?s.flakeBottom:(document.documentElement.clientHeight||document.body.clientHeight||document.body.scrollHeight);
}
screenX2 = parseInt(screenX/2,10);
};

this.resizeHandlerAlt = function() {
screenX = s.targetElement.offsetLeft+s.targetElement.offsetWidth-s.flakeRightOffset;
screenY = s.flakeBottom?s.flakeBottom:s.targetElement.offsetTop+s.targetElement.offsetHeight;
screenX2 = parseInt(screenX/2,10);
};

this.freeze = function() {
// pause animation
if (!s.disabled) {
s.disabled = 1;
} else {
return false;
}
for (var i=s.timers.length; i--;) {
clearInterval(s.timers[i]);
}
};

this.resume = function() {
if (s.disabled) {
s.disabled = 0;
} else {
return false;
}
s.timerInit();
};

this.toggleSnow = function() {
if (!s.flakes.length) {
// first run
s.start();
} else {
s.active = !s.active;
if (s.active) {
s.show();
s.resume();
} else {
s.stop();
s.freeze();
}
}
};

this.stop = function() {
this.freeze();
for (var i=this.flakes.length; i--;) {
this.flakes[i].o.style.display = 'none';
}
removeEvent(window,'scroll',s.scrollHandler);
removeEvent(window,'resize',s.resizeHandler);
if (!isOldIE) {
removeEvent(window,'blur',s.freeze);
removeEvent(window,'focus',s.resume);
}
};

this.show = function() {
for (var i=this.flakes.length; i--;) {
this.flakes[i].o.style.display = 'block';
}
};

this.SnowFlake = function(parent,type,x,y) {
var s = this;
var storm = parent;
this.type = type;
this.x = x||parseInt(rnd(screenX-20),10);
this.y = (!isNaN(y)?y:-rnd(screenY)-12);
this.vX = null;
this.vY = null;
this.vAmpTypes = [1,1.2,1.4,1.6,1.8]; // "amplification" for vX/vY (based on flake size/type)
this.vAmp = this.vAmpTypes[this.type];
this.melting = false;
this.meltFrameCount = storm.meltFrameCount;
this.meltFrames = storm.meltFrames;
this.meltFrame = 0;
this.twinkleFrame = 0;
this.active = 1;
this.fontSize = (10+(this.type/5)*10);
this.o = document.createElement('div');
this.o.innerHTML = storm.snowCharacter;
this.o.style.color = storm.snowColor;
this.o.style.position = (fixedForEverything?'fixed':'absolute');
this.o.style.width = storm.flakeWidth+'px';
this.o.style.height = storm.flakeHeight+'px';
this.o.style.fontFamily = 'arial,verdana';
this.o.style.overflow = 'hidden';
this.o.style.fontWeight = 'normal';
this.o.style.zIndex = storm.zIndex;
docFrag.appendChild(this.o);

this.refresh = function() {
if (isNaN(s.x) || isNaN(s.y)) {
// safety check
return false;
}
s.o.style.left = s.x+'px';
s.o.style.top = s.y+'px';
};

this.stick = function() {
if (noFixed || (storm.targetElement != document.documentElement && storm.targetElement != document.body)) {
s.o.style.top = (screenY+scrollY-storm.flakeHeight)+'px';
} else if (storm.flakeBottom) {
s.o.style.top = storm.flakeBottom+'px';
} else {
s.o.style.display = 'none';
s.o.style.top = 'auto';
s.o.style.bottom = '0px';
s.o.style.position = 'fixed';
s.o.style.display = 'block';
}
};

this.vCheck = function() {
if (s.vX>=0 && s.vX<0.2) {
s.vX = 0.2;
} else if (s.vX<0 && s.vX>-0.2) {
s.vX = -0.2;
}
if (s.vY>=0 && s.vY<0.2) {
s.vY = 0.2;
}
};

this.move = function() {
var vX = s.vX*windOffset;
s.x += vX;
s.y += (s.vY*s.vAmp);
if (s.x >= screenX || screenX-s.x < storm.flakeWidth) { // X-axis scroll check
s.x = 0;
} else if (vX < 0 && s.x-storm.flakeLeftOffset<0-storm.flakeWidth) {
s.x = screenX-storm.flakeWidth-1; // flakeWidth;
}
s.refresh();
var yDiff = screenY+scrollY-s.y;
if (yDiff s.active = 0;
if (storm.snowStick) {
s.stick();
} else {
s.recycle();
}
} else {
if (storm.useMeltEffect && s.active && s.type < 3 && !s.melting && Math.random()>0.998) {
// ~1/1000 chance of melting mid-air, with each frame
s.melting = true;
s.melt();
// only incrementally melt one frame
// s.melting = false;
}
if (storm.useTwinkleEffect) {
if (!s.twinkleFrame) {
if (Math.random()>0.9) {
s.twinkleFrame = parseInt(Math.random()*20,10);
}
} else {
s.twinkleFrame--;
s.o.style.visibility = (s.twinkleFrame && s.twinkleFrame%2===0?'hidden':'visible');
}
}
}
};

this.animate = function() {
// main animation loop
// move, check status, die etc.
s.move();
};

this.setVelocities = function() {
s.vX = vRndX+rnd(storm.vMaxX*0.12,0.1);
s.vY = vRndY+rnd(storm.vMaxY*0.12,0.1);
};

this.setOpacity = function(o,opacity) {
if (!opacitySupported) {
return false;
}
o.style.opacity = opacity;
};

this.melt = function() {
if (!storm.useMeltEffect || !s.melting) {
s.recycle();
} else {
if (s.meltFrame < s.meltFrameCount) {
s.meltFrame++;
s.setOpacity(s.o,s.meltFrames[s.meltFrame]);
s.o.style.fontSize = s.fontSize-(s.fontSize*(s.meltFrame/s.meltFrameCount))+'px';
s.o.style.lineHeight = storm.flakeHeight+2+(storm.flakeHeight*0.75*(s.meltFrame/s.meltFrameCount))+'px';
} else {
s.recycle();
}
}
};

this.recycle = function() {
s.o.style.display = 'none';
s.o.style.position = (fixedForEverything?'fixed':'absolute');
s.o.style.bottom = 'auto';
s.setVelocities();
s.vCheck();
s.meltFrame = 0;
s.melting = false;
s.setOpacity(s.o,1);
s.o.style.padding = '0px';
s.o.style.margin = '0px';
s.o.style.fontSize = s.fontSize+'px';
s.o.style.lineHeight = (storm.flakeHeight+2)+'px';
s.o.style.textAlign = 'center';
s.o.style.verticalAlign = 'baseline';
s.x = parseInt(rnd(screenX-storm.flakeWidth-20),10);
s.y = parseInt(rnd(screenY)*-1,10)-storm.flakeHeight;
s.refresh();
s.o.style.display = 'block';
s.active = 1;
};

this.recycle(); // set up x/y coords etc.
this.refresh();

};

this.snow = function() {
var active = 0;
var used = 0;
var waiting = 0;
var flake = null;
for (var i=s.flakes.length; i--;) {
if (s.flakes[i].active == 1) {
s.flakes[i].move();
active++;
} else if (s.flakes[i].active === 0) {
used++;
} else {
waiting++;
}
if (s.flakes[i].melting) {
s.flakes[i].melt();
}
}
if (active flake = s.flakes[parseInt(rnd(s.flakes.length),10)];
if (flake.active === 0) {
flake.melting = true;
}
}
};

this.mouseMove = function(e) {
if (!s.followMouse) {
return true;
}
var x = parseInt(e.clientX,10);
if (x windOffset = -windMultiplier+(x/screenX2*windMultiplier);
} else {
x -= screenX2;
windOffset = (x/screenX2)*windMultiplier;
}
};

this.createSnow = function(limit,allowInactive) {
for (var i=0; i s.flakes[s.flakes.length] = new s.SnowFlake(s,parseInt(rnd(flakeTypes),10));
if (allowInactive || i>s.flakesMaxActive) {
s.flakes[s.flakes.length-1].active = -1;
}
}
storm.targetElement.appendChild(docFrag);
};

this.timerInit = function() {
s.timers = (!isWin9X?[setInterval(s.snow,s.animationInterval)]:[setInterval(s.snow,s.animationInterval*3),setInterval(s.snow,s.animationInterval)]);
};

this.init = function() {
s.randomizeWind();
s.createSnow(s.flakesMax); // create initial batch
addEvent(window,'resize',s.resizeHandler);
addEvent(window,'scroll',s.scrollHandler);
if (!isOldIE) {
addEvent(window,'blur',s.freeze);
addEvent(window,'focus',s.resume);
}
s.resizeHandler();
s.scrollHandler();
if (s.followMouse) {
addEvent(document,'mousemove',s.mouseMove);
}
s.animationInterval = Math.max(20,s.animationInterval);
s.timerInit();
};

var didInit = false;

this.start = function(bFromOnLoad) {
if (!didInit) {
didInit = true;
} else if (bFromOnLoad) {
// already loaded and running
return true;
}
if (typeof s.targetElement == 'string') {
var targetID = s.targetElement;
s.targetElement = document.getElementById(targetID);
if (!s.targetElement) {
throw new Error('Snowstorm: Unable to get targetElement "'+targetID+'"');
}
}
if (!s.targetElement) {
s.targetElement = (!isIE?(document.documentElement?document.documentElement:document.body):document.body);
}
if (s.targetElement != document.documentElement && s.targetElement != document.body) {
s.resizeHandler = s.resizeHandlerAlt; // re-map handler to get element instead of screen dimensions
}
s.resizeHandler(); // get bounding box elements
s.usePositionFixed = (s.usePositionFixed && !noFixed); // whether or not position:fixed is supported
fixedForEverything = s.usePositionFixed;
if (screenX && screenY && !s.disabled) {
s.init();
s.active = true;
}
};

function doStart() {
s.start(true);
}

if (document.addEventListener) {
// safari 3.0.4 doesn't do DOMContentLoaded, maybe others - use a fallback to be safe.
document.addEventListener('DOMContentLoaded',doStart,false);
window.addEventListener('load',doStart,false);
} else {
addEvent(window,'load',doStart);
}

}

snowStorm = new SnowStorm();
Assume that we saved this code in a javascript file called snow.js....
Then import that file on your master page.
 <script type="text/javascript" src="snow.js"></script>

Monday, November 23, 2009

Change Proxy Settings on linux using shell commands

You can change the proxy settings for current session by executing following command. Which changes the environment variable "http_proxy". If you want, you can do it for ftp as well (ftp_proxy).
export http_proxy="http://NewProxy_address:Port"

Assume my proxy run on 192.168.0.1 machine on port 808, then this settings will be
export http_proxy="http://192.168.0.1:808"

Personal Experience


Recently, I installed Ubuntu server 8.04 and while the installation I set proxy settings wrong manner. In that case, installation guide give the format of "http://[[[user]:[passowrd]@serverIP]:[port]]" to enter proxy settings. Since I was using my proxy server in a windows machine, I had problem of giving username@server:port format. I gave it http://janaka@192.168.0.1:808, but it is only necessary to give http://192.168.0.1:808. So I needed to permanently change it. If you only used above command, it will not be there when you reboot the linux os. Because it is just changing the current environmental variable "http_proxy".
Using following changes you could permanently change the settings.
If you wanted to add it for any user add export http_proxy="http://192.168.0.1:808" on ~/.bashrc file.
 vi ~/.bashrc

If you want to do it for current user, add export http_proxy="http://192.168.0.1:808" on /etc/rc.local.
vi /etc/rc.local
The File will look like below.
And then change the execution bit to execute this script while loading.
chmod u+x /etc/rc.local

Now it should be working.

Sunday, November 22, 2009

Log4j - Logging package

Log4j is a package which supports to do logging very easily. This logging outputs can be taken in many ways.

There are many more types can be used,
AsyncAppender, JDBCAppender, JMSAppender, LF5Appender, NTEventLogAppender,
NullAppender, NullAppender, SMTPAppender, SocketAppender, SocketHubAppender,
SyslogAppender, TelnetAppender, DailyRollingFileAppender, RollingFileAppender.
To begin with log4j, you should first download the log4j package. Here is a sample link to download it.

Log Levels

There are some log levels defined in log4j.
  1. all - All levels including custom levels
  2. trace (since log4j 1.2.12) - Developing only, can be used to follow the program execution.
  3. debug - Developing only, for debugging purpose
  4. info - Production optionally, Course grained (rarely written information), I use it to print that a configuration is initialized, a long running import job is starting and ending.
  5. warn - Production, simple application error or unexpected behaviour. Application can continue. I warn for example in case of bad logging attempts, unexpected data during import jobs
  6. error - Production, application error/exception but
    application can continue. Part of the application is probably not working
  7. fatal - Production, fatal application error/exception, application cannot continue, for example database is down.
  8. no - Do not log at all.

A simple example

First you better add downloaded jar package to the project using your IDE. Then you have to setup the log4j properties through property file or, xml file.... In this case, let's check with log4j.properties file. In your IDE, as other property files add your log4j properties file. For example create new file called "log4j.properties" It should be look like this.
log4j.rootLogger=debug, file
log4j.appender.file=org.apache.log4j.RollingFileAppender #logging Type
log4j.appender.file.maxFileSize=100KB #Max file size of a log file
log4j.appender.file.maxBackupIndex=5 #keeping backups of
log4j.appender.file.File=C://myprogram_logs/test.log #Location which saving log file
log4j.appender.file.threshold=debug #Log Level
log4j.appender.file.layout=org.apache.log4j.PatternLayout #Layout of the log file
log4j.appender.file.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n #Layout of the log file
I am using RollingFileAppender here. Max file size is 100KB, kind of all the properties related to Log4j is stated here.
At your java file, load the property file and put it into the PropertyConfigurator on log4j package. Example code snipped here,
Improte packages

import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.Logger;
import java.util.Properties;
On the relevant class, define the Logger type global variable(in my case "logger").
private static Logger logger = Logger.getLogger(MyProgram.class);
On main method,
   public static void main(String[] args){
Properties properties = new Properties();
InputStream inputStream = MyProgram.class.getClassLoader().getResourceAsStream("log4j.properties");
properties.load(inputStream);
PropertyConfigurator.configure(properties);
logger.info("My program Begins");
}
When you catch an exception, write it on log as follows
     try {
//Your code here
} catch (Exception e) {
logger.error("Found the exception here");
}

Now you will find logs on C://myprogram_logs/test.log location file.
When you need to use it in ubuntu, you just have to change the file location only from the properties file (i.e. /var/myprogram_logs/test.log).
See how easy logging you programming status with Log4j........
Here is a nice pdf to follow.
Cheers......

Tuesday, November 17, 2009

"The Twilight Saga: New Moon" for Sri Lankans...


Hay sri lankan Twilight fans, you all will be able to watch Twilight at MC soon...............
Yaaahooooooooooooo..........
You can buy tickets from TicketsLK.
Frnz itz movie time.....


Sunday, November 15, 2009

Windows TortoiseGit client for a linux Gitosis server

Tortoise git is really nice Graphical tool to handle git repository. You need to download TortoiseGit from here. First of all as we discussed earlier you need to install msysgit first. Then install the Tortoisegit and install it. While installing it Select open ssh client option for authentication method.
And completely install it and restart your computer. First of all you should add the msysgit path for this system. Tortoisegit gets the git options from msysgit. Right click on your desktop and go to settings,Set the path to the bin of the msysgit. Now setting your authentication on the server should be set. For that TortoiseGit has shipped putty Keygen for generate keys. But in this case, since we are connecting with a linux server the private keys which generate by putty key gen won't be recognize by the server. Since that you will not recognized correctly at the server end. To avoid this inconvenience you can create ssh keys through ssh-keygen. On your command prompt.

Do not use puttyGen in this case to create key pairs.

Go to your account on the windows os(i.e. C:\Documents and Settings\Janaka), check whether there is a folder called ".ssh" if not, create it using command prompts "mkdir .ssh" command. This is the place we keep your key pairs. keys you generated (id_rsa.pub, id_rsa) copy to this folder. Now follow the usual users adding mechanism on git server.Click here for more info.
Now you can go to any location on your computer and right click select option git clone... or git zync you will receive following screen. Put the remote URL as to your git repository. git@192.168.4.90:my_first_repo It will import the repository to your local folder. Like wise all the operations can be done through GUI. You don't have to type git commands on doing this.
Any comments........???

Creating gitosis repository and adding users to projects

Cont from, Previous post

Adding new repo(gitosis.conf)


Administrator is the only authenticated user for this (In according to previous posts in my case it's janaka). First administrator can log to the server which runs git.First it is better to add the repository on the conf file. And you can add users for this repository.
janaka@versioncontrol~/gitosis-admin $ vi gitosis.conf

Your conf file look like this,
[gitosis]                  

[group gitosis-admin]
writable = gitosis-admin
members = janaka@versioncontrol

Edit it and add new repo, Now it will looks like,
[gitosis]                  

[group gitosis-admin]
writable = gitosis-admin
members = janaka@versioncontrol

[repo my_first_repo]
gitweb = no
description = This could be my first repo
owner = No one else thats me,
daemon = no

Creating a user group


Your conf file look like this,
[gitosis]                  

[group gitosis-admin]
writable = gitosis-admin
members = janaka@versioncontrol

[repo my_first_repo]
gitweb = no
description = This could be my first repo
owner = No one else thats me,
daemon = no

Edit this file and add new group,

[gitosis]                  

[group gitosis-admin]
writable = gitosis-admin
members = janaka@versioncontrol

[group my_users]
writable = my_first_repo
members = janaka@versioncontrol gituser1

[repo my_first_repo]
gitweb = no
description = This could be my first repo
owner = No one else thats me,
daemon = no

gituser1 is the newly added user, his key is named as gituser1.pub on keydir/ directory.
Now you should add this changed gitosis.conf file and update gitosis-admin repository. You can do it by executing following commands.
janaka@versioncontrol~/gitosis-admin$ git add gitosis.conf
janaka@versioncontrol~/gitosis-admin$ git commit -m "Added new repo on conf file"
janaka@versioncontrol~/gitosis-admin$ git push

Then you can create the directory you want and create physical repository.

Creating new repository


Create a directory with naming it on your wish.
janaka@versioncontrol~$ mkdir my_first_repo
Now go into it, Don't forget to add some files before initialize this repo. Otherwise it will not be added as a repository,
janaka@versioncontrol/my_first_repo~$ touch readme
then follow the given commands to initialize the repository,
cd my_first_repo
git init
git remote add origin git@192.168.4.90:my_first_repo.git
git add .
git commit -m "Hai buddies, we added my_first_repo"
git push origin master:refs/heads/master
192.168.4.90-is the server which runs git on it. Now the new repository is created.
This is it, now gituser1 can use the my_first_repo repository. You can check on client machine,
git clone git@192.168.4.90:my_first_repo

On windows client side, If you'r only using command prompt, why don't you go for TortoiseGit to make life easier. TortoiseGit is a graphical tool to access git repository. Follow

"Graphical controls for Git windows clients"

link and study it.

Saturday, November 14, 2009

(Tortoisegit + Gitosis + msysgit) configuring - Adding windows users and creating repo

Cont. from previous post
Now you are ready to add users to the server.
It is not that much hard to add ubuntu users.
You just have to install git-core and by adding keys to the key directory. You can add users. If you are a windows user you have to do some installations. There are few ways to access repositories as windows user.

Clients using who use command prompt


First you should download msysgit from here and run the exe. Assume you downloaded the full version.

Give the path as your wish.
To run git commands at anywhere from your command prompt, define a path variable on environment variables Right Click on My Computer => Properties => Advanced => Environemnt Variables => Edit or New give the variable name as "PATH", and variable value "C:\msysgit\msysgit\bin", the bin folder of the msysgit installed. And add the "C:\msysgit\msysgit\mingw\bin" path also, that means, variable value will looks like, "C:\msysgit\msysgit\bin;C:\msysgit\msysgit\mingw\bin"

Then go to start => run => cmd type git and press enter. You will get result like,

Now you are ready to use git.

Adding user


First of all you have to create a key pair for your self. Get the command prompt and navigate to the msysgit folder to create .ssh directory.
C:\msysgit\msysgit\> mkdir .ssh

You are not allowed to create folders beginning with "." by right click => New => folder. So that it should be created this way.

Now navigate into the .ssh folder. We are going to create key pair.
C:\msysgit\msysgit\.ssh> ssh-keygen 
give id_rsa for the key name.
Following result will be shown.
C:\msysgit\msysgit\.ssh>ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (//.ssh/id_rsa): id_rsa
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in id_rsa.
Your public key has been saved in id_rsa.pub.
The key fingerprint is:
92:0c:83:16:16:14:04:51:30:42:da:5d:df:fd:fb:15 Janaka@XPWINDOWS7

Now you need to transfer the public key to the server where your gitosis administrator belongs. With previous posts, you might remember my username at version control is janaka. Following command will carry your key to that server's keydir directory.On my command prompt,
C:\msysgit\msysgit\.ssh>scp id_rsa.pub janaka@192.168.4.90:gitosis-admin/keydir/gituser1.pub
(Assume 192.168.4.90 is the server that installed gitosis) using this command or anyhow you can copy your key to keydir/ directory.
Don't change the names of the public and private keys of the(id_rsa,id_rsa.pub) on your local machine. Keep it as it is on .ssh folder.
Now the administrators part,
Admin should allow this key to copy to server and rename it. When renaming, keep remember to give the same name that you are planing to add in .conf file. If new user is gituser1, then public key should be renamed to gituser1.pub on server.
On the server, admin should enter the this user into a user list of gitosis.conf file. You can see how to create new repository and work groups in this link.
On gitosis.conf,
[group myteam]
members = gituser1
writable = my_current_project
member should be the name of the added public key(without .pub) and writable is the repository which are writable by this team. Group name is myteam.
Now administrator should add these key file and changed gitosis.conf file and push it to git user. Actually administrator just cloning the gitosis-admin part from the "git" user and after changes pushing it back. Here are the commands for admin,
janaka@versioncontrol~$ git clone git@192.168.4.90:gitosis-admin
janaka@versioncontrol~$ cd gitosis-admin
janaka@versioncontrol~/gitosis-admin $ git add keydir/gituser1.pub
janaka@versioncontrol~/gitosis-admin $ git add gitosis.conf
janaka@versioncontrol~/gitosis-admin $ git commit -a -m "Added gituser1 as a new user"
janaka@versioncontrol~/gitosis-admin $ git push
Now on the client side (gituser1) can check whether he had successfully added. On command prompt he can try to add a clone.
 
C:\MyFolder> git clone git@192.168.4.90:my_current_project

If it imported my_current_project folder without asking any password for git user it is successfully worked. Issued can be occured,
  • Ask a password for git user- your keys are not matching recreate the key pairs and install keys accurately.

  • Giving no permissions error- You have not been added successfully for that group on gitosis.conf file. Reedit the conf file.

Widows clients using Gitosis

You can find post regarding this from here

Creating new repository and adding permission groups

will be discussed here

Setting up Gitosis(version control system) on Linux server and adding windows clients

Git is a kind of a version control system which allows users to keep their project information safely in repositories. In this case, I will be using Gitosis for this setup, Gitosis is a tool written for Git that helps in the setup of secure access controlled repositories. It will manage multiple repositories under one user account on the host machine. Using SSH keys to identify users, your repositories will be securely accessed and controlled. One large advantage to Gitosis is that your users will not need shell accounts on the machine to access repositories, they will however speak to a singular account what will not allow arbitrary commands. Now let's see how gitosis can install in to your Ubuntu server.

Installing Gitosis


First of all you should have installed Git.
sudo apt-get install git-core

By cloning the gitosis directory from "eagain.net" you will get the gitosis directory on your home page. Follow these lines to do it,
   cd ~/
git clone git://eagain.net/gitosis.git

Now you better move that folder to /usr/local
   sudo mv gitosis/ /usr/local

Now go to Gitosis folder.
   cd /usr/local/gitosis/

If you haven't installed python in your computer get it installed.
   sudo apt-get install python-setuptools

Then, you can run the setup.py file which is in this directory.
   sudo python setup.py install

Now you are successfully installed Gitosis on your Linux server.
Next, you have to create user called "git". "git" is the repositories holding real user. It creates in a way that users to identify through ssh-keys. Anyone can't login through entering password.
 sudo adduser \
--system \
--shell /bin/sh \
--gecos 'git version control' \
--group \
--disabled-password \
--home /home/git \
git

gitosis-admin


Now let's initialize the gitosis and begin with adding an administrator to git repository. As a convention we used to create administrator account on the same server/computer. Because administrator has the super power of creating new repository, users and so on.
To identify administrator, you need to create create ssh key and initialize gitosis with that key. So you will add as the administrator.(janaka is the user, versioncontrol is the name of the linux server)
janaka@versioncontrol~$ ssh-keygen -t rsa

Keep blank for the parse phrase of the key. Found this generated key pair at /home/janaka/.ssh/ as id_rsa(private key) and id_rsa.pub(public key).
Since janaka@versioncontrol wants to the admin and versioncontrol is the git server itself. You can directly initialize with this key.
sudo -H -u git gitosis-init < /home/janaka/.ssh/id_rsa.pub 

If your admin wants to be another user, generate this kind of key pair and copy it some where at versioncontrol(i.e. /tmp/id_rsa.pub). In this case,
sudo -H -u git gitosis-init < /tmp/id_rsa.pub 

If you are success then it will give,
Initialized empty Git repository in ./
Initialized empty Git repository in ./

Congratz, Now you are the gitosis-admin....!!!!
Now you need to make executable the post-update hook. Run following command.
sudo chmod 755 /home/git/repositories/gitosis-admin.git/hooks/post-update

Its ready to take your admin clone..............
git clone git@YOUR_SERVER_HOSTNAME:gitosis-admin.git

In my case YOUR_SERVER_NAME is "localhost". If you (admin) from another host, give the ip of the linux server/machine(versioncontrol).
Now have go to cloned gitosis-admin directory.
janaka@versioncontrol~$ cd gitosis-admin 

Have a look at the list,
You will found "gitosis.conf" file and "keydir" directory.
Have a look at the gitosis.conf file,
vi gitosis.conf

 [gitosis]                  

[group gitosis-admin]
writable = gitosis-admin
members = janaka@versioncontrol

Now lets see how to add users and creating new repositories.
Since this post getting longer, Follow Next post. click here

Adding Windows users to the gitosis and Many more

Thursday, November 12, 2009

Change Locale ubuntu server UTF-8 to ISO-8859-1

I was trying to get some sinhala words from database using java. It was nicely working at on windows. When I moved java program to ubuntu server, it returned some unexpected characters.
That happened because of ubuntu using itz default Locale as UTF-8. But some characters at UTF-8 doesn't support for it. Since that it can't give the real output. Since that you should update your Locale for "ISO-8859-1".
To do that you can update your Locale using

locale-gen en_GB
update-locale LANG=en_GB.ISO-8859-1


Then it you won't be getting any bad character expect you entered ones.
Have fun on developing.

Have fun with jQuery - Tutorial 2

As we discussed earlier, jQuery is a powerful javascript API on developing web applications. Here lets consider, how jQuery actions can be applied on specified elements.

Suppose you have got two buttons which we call ButtonA and ButtonB,


<script type="text/javascript" src="jquery-1.3.1.min.js"> </script>

<script type="text/javascript">
$(document).ready(function(){
$("#btnA").click(function(event){
alert("Clicked ButtonA...!!!");
});
$("#btnB").click(function(event){
alert("Clicked ButtonB...!!!")
});
});

</script>
<body>
<p>
<input id="btnA" value="ButtonA" type="button">
<input id="btnB" value="ButtonB" type="button">
</p>
</body>

When you click on Buttons, it will pop up two different alert boxes as we defined in script.



That is how we define actions for a given element. To make it easy to understand, I displayed just popping up an alert box. It is useful in various applications.

Now lets see, how jQuery can be used with styling elements. First you better create some style classes like I have mentioned below.

<style type="text/css">
label.test { font-style: italic; }
label.test2 { color:#FF0033; }
</style>

Very easily you can apply your style class to an element using ELEMENT.addClass("CLASSNAME") function. If you want to remove it, you can call ELEMENT.removeClass("CLASSNAME") funciton. jQuery call for applying or removing class will receive the priority.
Example,

<script type="text/javascript" src="jquery.js"> </script>

<script type="text/javascript">
$(document).ready(function(){
$("#myLabel").addClass("test");
});
</script>
</head>
<body>
<h1>
<label id="myLabel">
Testing jQuery
</label>
</h1>
</body>

This will Present,

Now Lets remove an applied class and add another class,

<script type="text/javascript" src="jquery.js"> </script>

<script type="text/javascript">
$(document).ready(function(){
$("#myLabel").removeClass("test");
$("#myLabel").addClass("test2");
});
</script>
</head>
<body>
<h1>
<label class="test" id="myLabel">
Testing jQuery
</label>
</h1>
</body>

Now it will present,

Many more interesting things are coming.....
KIT.....

Have fun with jQuery - Tutorial 1

jQuery is a simple javascript API which can be used in many ways to improve your web application or Web site.
First of all you have to download the jQuery javascript file from here (jquery-1.3.1.min.js). Then you can add it to your project like this way,

 <script type="text/javascript" src="jquery-1.3.1.min.js"></script>


Else you can use refer this link "http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" on development.
Then you will import js file this manner,
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>



Now your are ready to start develop with jQuery.
Let's begin with a simple example.
Create a simple html file which is having a html component. You can use any component. In this case, Let's get a <a> tag. It can be a button, submit, label or any thing.


<html>
<head>

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript">

</script>
</head>

<body>
<a href="http://www.google.com/">My test link</a>
</body>
</html>


We are going to use ready status of the page loading. Since that, we used to write as following simple code,

 $(document).ready(function(){
// Your code content here
});


Assume you want to give a pop up when you clicked on the "My test link". It is very simple.
 $(document).ready(function(){
$("a").click(function(event){
alert("We are going to visit google....!!!");
});
});


It will give you a popup and will direct to google.com.

Let's assume that you don't need to visit to google.com. Then there is a jQuery functionality for disable default functions of the element. What you have to do is add preventDefault() method to onclick function event. It can be achieved easily following way.

 $(document).ready(function(){
$("a").click(function(event){
alert("We are going to visit google....!!!");
event.preventDefault();
});
});



Now you will receive the popup, but you will not forward to google.com.
According to above code, it will be applied for all places where <a> tags are available. It is possible to write this kind of event handling and many more things using jQuery. Let's meet on next tutorial to see how the things can be applied for specified (specified by the id) elements.
Thank you.
See you soon...

Closure Tools



Millions of Google users worldwide use JavaScript-intensive applications such as Gmail, Google Docs, and Google Maps. Like developers everywhere, Googlers want great web apps to be easier to create, so we've built many tools to help us develop these (and many other) apps. We're happy to announce the open sourcing of these tools, and proud to make them available to the web development community.

Closure Compiler
Closure Compiler is a JavaScript optimizer that compiles web apps down into compact, high-performance JavaScript code. The compiler removes dead code, then rewrites and minimizes what's left so that it will run fast on browsers' JavaScript engines. The compiler also checks syntax, variable references, and types, and warns about other common JavaScript pitfalls. These checks and optimizations help you write apps that are less buggy and easier to maintain. You can use the compiler with Closure Inspector, a Firebug extension that makes debugging the obfuscated code almost as easy as debugging the human-readable source.

Because JavaScript developers are a diverse bunch, we've set up a number of ways to run the Closure Compiler. We've open-sourced a command-line tool. We've created a web application that accepts your code for compilation through a text box or a RESTful API. We are also offering a Firefox extension that you can use with Page Speed to conveniently see the performance benefits for your web pages.

Closure Library
Closure Library is a broad, well-tested, modular, and cross-browser JavaScript library. Web developers can pull just what they need from a wide set of reusable UI widgets and controls, as well as lower-level utilities for the DOM, server communication, animation, data structures, unit testing, rich-text editing, and much, much more. (Seriously. Check the docs.)

JavaScript lacks a standard class library like the STL or JDK. At Google, Closure Library serves as our "standard JavaScript library" for creating large, complex web applications. It's purposely server-agnostic and intended for use with the Closure Compiler. You can make your project big and complex (with namespacing and type checking), yet small and fast over the wire (with compilation). The Closure Library provides clean utilities for common tasks so that you spend your time writing your app rather than writing utilities and browser abstractions.

Closure Templates
Closure Templates grew out of a desire for web templates that are precompiled to efficient JavaScript.  Closure Templates have a simple syntax that is natural for programmers.  Unlike traditional templating systems, you can think of Closure Templates as small components that you compose to form your user interface, instead of having to create one big template per page.

Closure Templates are implemented for both JavaScript and Java, so you can use the same templates both on the server and client side.


Closure Compiler, Closure Library, Closure Templates, and Closure Inspector all started as 20% projects and hundreds of Googlers have contributed thousands of patches. Today, each Closure Tool has grown to be a key part of the JavaScript infrastructure behind web apps at Google.  That's why we're particularly excited (and humbled) to open source them to encourage and support web development outside Google. We want to hear what you think, but more importantly, we want to see what you make. So have at it and have fun!



Reference: Introducing Closure Tools

Speed up your web browsing

Google has introduced an application called PAGE SPEED which increase your browsing speed.

Best Practices

If you have got installed firebug with your firefox browser, you can directly downloaded and installed Page Speed with this link.