Thursday, August 6, 2009

JavaScript instance methods vs Class methods

Javascript instance methods are those that start with the "this" keyword where as class methods start with the prototype keyword. The difference between the two is that given an object instance methods are created per object whereas class methods are only one per class and not per instance so you will avoid creating duplicate object methods. Examples of the two are as follows;
 
1. Instance method example
 
    this.getName = function(){return this.name;}
 
2. Class method example
    //ObjName is the name of your object
    ObjName.prototype.getName = function(){return this.name;}
 
There is another method which is a class only method. The only difference with that is that it cannot access instance variables like the class method above but can only access class only variable. Example is as follows;
 
//this is a class only variable
ObjName.prototype.name = 'test';
/*Note that to get the class variable you have to drill down to the prototype object and you cannot access instance variables in class only methods. Only difference between this and the previous method as you can see is that it does not include prototype keyword.*/
 
ObjName.getName = function(){return ObjName.protype.name;}
 
But one thing to keep in mind is that the fact that the prototype keyword is not sometimes supported by older browsers.

Wednesday, August 5, 2009

Java Script Date Object

Java script consist of a Date object which is kind of similar to the Java Date object where as it uses the time since the epoch but some utility method available in the Java language are not available in the JS Date object version. Some of the utility method which i cared to share are as follows;

getDate() - Get the day of month e.g 1-31
getMonth() - Gets the month of the year. Note that it starts with 0-11 So Jan is basically 0.
getFullYear() - Gets the current year as a four digit character

Also we can pass the date as a string literal to the date object as new Date("08/09/2007") which it will convert to the intended date time. It also consists of a toString method which is a bit too cryptic and should not be used when showing specific date objects. The above in-built methods should be used instead to show the user a properly formatted date.

How do you get teh number of days between two days;

This can be done as follows;

//Assuming that date 2 is after date 1
function(date1,date2){

return Math.round( (date2-date1)/(1000*60*60*24));

}

Java Script Array Sorting


Java scripts have intrigued me!!!As so far as me going to the book store and selecting java script books to learn it the old fashioned "Off the shelf" way ;) ... So some of my posts from here onwards will contain a mix and match of java scirpt/java so any anti javascript ppl please dnt take it personally :D.... I never knew java script had array sorting like whats available for us java developers. Two ways this can be accomplished..

Method 1:

//Sorts values in descending order
function compare(val1,val2){
return val2-val1;
}

var myarray = new Array([1,3,7,10,32,45]);
myarray.sort(compare);

Thats about it to do sorting using arrays. Of course you could have just used myarray.sort() which would have used the default sorting mechanism and sorted the array in ascending order. You could debate here saying why do we need to define a new method just to get the sorting done. Bit too much code to do a single sorting function. Well look no further method 2 below shows how to do the same thing as above with just one line of code using the function literal capability of Javascript.

Behold Method 2!!!!!!! (Drum roll please)
Method 2:
myarray.sort(function(val1,val2){val2-val1});


Thats about it for now. But more to come very soon guys. So stay on the look out for all those Java script newbies like myself :).

Cheers

Sunday, August 2, 2009

String concatenation and String builder confusions resolved


There was a very hot debate going on about String vs String builder and doing string concatenation within the append method of the String builder. I then researched this topic on the net because i had to prove a point in my work area ;) ... Then i stumbled upon this great blog post which i thought i should share with all of you which clearly explains when and how to use these String concatenation methodologies. And thankfully i was right in my assumptions :D.... The blog post can be found at http://www.znetdevelopment.com/blogs/2009/04/06/java-string-concatenation/

Friday, July 31, 2009

@BatchSize() Annotation in hibernate

While searching on the net on how to gain perfomance in JPA/Hibernate i stumbled upon an article written on hibernate annotation batchsize and it intrigued me on how it really works. After reading on and going through the algorythm defined by Hibernated on how it works i understood that this adds a sufficient perfomance gain in the event of you having large collections within your entities.

 --------Updated on 07/30/2012 according to the clarification given by Jeremy---------

For example lets consider an Airport parent containing a collection of airlines as such;

    @OneToMany()
    List<Airlines> airlines = new ArrayList<Airlines>();
Imagine you had such a statement in one of your entities. Assume there can be 100 Airport objects at any given time.Without the BatchSize annotation, Hibernate will first retrieve the Airports separately and for each airport it will retrieve the airlines separately. Now consider the following code snippet;
    @OneToMany
    @BatchSize(size=16)
   List<Airlines> airlines = new ArrayList<Airlines>();
When you use the batch size annotation what hibernate does is it divides the number of elements that would come in the resulting query by the batch size defined. In this case its 100 / 16 so you get 6 and remainder 4. What this implies is hibernate will go to the database 6 times to fetch 16 Airport objects' with their Airlines collection initialized and then go again another time to retrieve the remaining 4 Airports again with their Airlines collection initialized. So what the @BatchSize does is decide how many collections should be initialized.

Thursday, June 18, 2009

Concurrent HashMap vs HashMap

So today i looked into these two Map types to use in the multi threaded application im working on. It was really confusing to understand the exact differences between the two but after some research this is my vedict;

Use ConcurrentHashMap if you only want to concurrently add and remove values and do not want to access the map while concurrent additions and modifications go on. But if you do want to access data while concurrent additions and modifications are going on then its better to use Collections.synchronizedHashMap() and make the iteration code block thread safe in order to avoid race conditions.

Wednesday, June 17, 2009

Simple Java Mail SMTP Client

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

class SimpleMail {
static Message emailMessage;

public static void main(String[] args) {

try {

emailMessage = new MimeMessage(createSession());
// replace this with the TO mail address
InternetAddress add = new InternetAddress("receipeicnt@abc.com");
InternetAddress[] addresses = new InternetAddress[1];
addresses[0] = new InternetAddress("d");
emailMessage.setFrom(add);
emailMessage.setRecipients(javax.mail.Message.RecipientType.TO,
addresses);
emailMessage.setSubject("My Subject ");
emailMessage.setContent("My First Mail", "text/plain");
emailMessage.saveChanges();

Transport.send(emailMessage);

} catch (AddressException e) {

e.printStackTrace();
} catch (MessagingException e) {

e.printStackTrace();
}

}

private static Session createSession() {

Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "your_mail_server_IP");

// If your sending multiple mails and even if one mail fails this by
// setting
// this property all the other mails except that mail will still be
// delievered
props.put("mail.smtp.sendpartial", "true");

Authenticator authenticator = null;

props.put("mail.smtp.auth", "true");
// enter your mail address and password here
authenticator = new MessagingAuthenticator("xxx@abc.com", "password");

return Session.getDefaultInstance(props, authenticator);
}
}

class MessagingAuthenticator extends Authenticator {
private String userName;
private String password;

public MessagingAuthenticator(String userName, String password) {
this.userName = userName;
this.password = password;
}

public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
}