Thursday, February 14, 2013

My Stint with SCALA - Classes and Objects


Scala is an Object Oriented Programming language just like Java. That's why, class is the building block of Scala as well.

Class

Class is defined the same way as defined in Java. Keyword class is used to define a class and this keyword is used by instance to refer itself.

Instantiating Class (Constructors)


Scala provides the default no-argument constructor just like Java does for each class. Custom constructors can be defined with class name, which is a simplified form of defining constructors in Java.


class Point(xc: Int, yc: Int) {
  var x: Int = xc;
  var y: Int = yc;


Above example shows that co-ordinates for Point class can be passed to its primary constructor and can be assigned to instance variables directly.

But does that mean we can define only one constructor for a class? No, Scala supports multiple auxiliary constructor but single primary constructor. This essentially means that the constructor defined along with definition of the class is treated as primary constructor while any other constructor defined in class body will be auxiliary constructor. Auxiliary constructor is dependent on primary constructor to define the instance variables. It has to make a call to primary constructor in order to instantiate the class.


class Point(xc: Int, yc: Int) {
  var x: Int = xc;
  var y: Int = yc;
  
  def this(x: Int){
    this(x, 0)
  }


Above code shows a auxiliary constructor which creates a point on Y -axis by passing a value for X-aixs and 0 for Y-axis.

As auxiliary constructor can only call primary constructor, so what if class is derived from another class. How auxiliary constructor will call the super constructor? It cannot do that directlywhich means it can only call primary constructor but primary constructor can make call to super constructor. That's how auxiliary constructor can make a call to super constructor through primary constructor.

So in Scala there can be only one primary constructor, rest all are dependent on that unlike Java where each constructor is a separate entity.

Validating Constructor Arguments

As primary constructor is not defined as method in Scala, how to validate the arguments passed? Here it is:


class Point(xc: Int, yc: Int) {
  var x: Int = xc;
  var y: Int = yc;
  
  require((x == -1 || y == -1), "Negative Co-ordinates are not allowed")

As shown above, method require can be used to validate the arguments passed to constructor. in above example if one of the co-ordinate is negative, an Exception will be thrown with message "Negatives Co-ordinates are not allowed".

Visibility Rules

Most of the visibility rules in Scala are same as Java only with some differences like:


  •  If inner class has a private field even outer class cannot see that variable
  • Default visibility in Scala is Public while its Default in Java.
Rest all visibility scopes like private, public, protected are applicable in Scala with same meaning as in Java.

Setters and Getters

Scala creates a public setter method with name <variable name>_= unless field is marked private. Like for class Point fields x and y setters like x_= and y_= will be created by default. Then these fields can be set by calling this method just like point.x_=(100), which is very easy and clean way of setting the instance variables.

Getter can be defined explicity as a method like:

def xVal = x which is equivalent to

def xVal = {
return x;
}

So everything like curly braces, return statement is optional. Scala identifies that method is returning something by '=' sign and the return type is interpreted by the type of returned variable.


Thursday, February 7, 2013

My Stint with SCALA - 1

In this blog, instead of trying to put everything that Scala can do, i am trying to put what all i have learnt so far in Scala.

After so many years of love with JAVA, its difficult to give same respect to a new language but good news is that SCALA runs on JVM ( though it can run on .NET platform as well ) and it has simplified many concepts of Java, similar to what Java did for C/C++ concepts.

To start with Scala, it can be downloaded from http://www.scala-lang.org/downloads. As it runs on JVM, so  Java Runtime environment is a must for Scala.

One downloaded and extracted, add <scala-home>/bin to the PATH. To check if the scala is running type below command in console. Something similar should be the result, depending upon the version which is installed:

Scala Version Test





All Scala files are stored with .scala format. Unlike Java, a file name can be different than the class name.
So lets start with the first Hello World ! program in Scala.

HelloWorld.scala


object HelloWorld {
  
  def main(args : Array[String]){
    println("HEllo World!!")
  }

}

Above code looks somewhat similar to HelloWorld in Java. Lets see the details,

First of all, instead of defining a class ( which is the building block in Java ), we are creating a object, object is also a class but a Singleton class in Scala. So we are creating a singleton object. Its worth noticing that defining singleton class in Scala is very easy compared to Java where we have to do much more to make a class Singleton.

After that we are defining main method, which is same as we do in Java to run a standalone class.

In Scala, method definition is recognized with the keyword def, which is followed by name of method. Similar to Java, main method in Scala also takes Array of String as argument.

Input parameter is defined as args: Array[String] which is Scala way to define the variable. args is name of variable and after colon (:) is the type of variable. Notice the way Array of String is defined which is Array[String] as compared to String[] in Java. Array is also a class in class in Scala.

Last we are printing the Hello World using println method, which is similar to System.out.println in Java.

Running Scala

In order to run above class, like Java, Classpath should be set for class. Then run below command to execute:

scala HelloWorld.scala

Output would be as printed in program:

HEllo World!!

Scala share many similarities with Java, still its a different language as one would need to write very less code  for same problem statement.

Thursday, August 23, 2012

Resolving Maven dependencies in eclipse

In order to resolve Maven dependencies in eclipse variable M2_REPO should be added to the classpath variables of the eclipse.

We can check the list classpath variables in eclipse at

Window ->Preferences->Java->Build Path ->Classpath Variables

In this view new classpath variable M2_REPO can be added directly. It should point to the location of Maven repository and not the home location of Maven



Other way is to do through console.

Run command:

mvn -Declipse.workspace="Your Workspace" eclipse:configure-workspace

It will add the variable in eclipse workspace.

mvn -Declipse.workspace="C:\Users\aggara4\SpringWorkSpace" eclipse:configure-workspace


[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building SampleWebProject Maven Webapp 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-eclipse-plugin:2.9:configure-workspace (default-cli) @ SampleWebProject ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.015s
[INFO] Finished at: Thu Aug 23 13:47:12 IST 2012
[INFO] Final Memory: 5M/9M
[INFO] ------------------------------------------------------------------------



Monday, February 20, 2012

Creating Foreign Key RelationShip in Hibernate

I am just starting exploring Hibernate in detail. I always wanted to see how just writing pojo classes make DB operations fun.

For my recent exploration i wanted to create Foreign Key relation between two tables. Here is a simple approach i tired:

Create two tables : Person and Person_Email.
As one person can have multiple emails, so these two tables have a one-to-many relation which means one entity of Person can have amy entities of Person_Email dependent on it.

Here is the schema of two tables ( i am using MYSQL DB as its a freeware).

Person:

PERSON_ID               int(10),
AGE                            smallint(6),
FIRSTNAME              varchar(10),
LASTNAME               varchar(10)

Person_Email:

PERSON_ID               int(10),

EMAIL_ADDRESS    varchar(255) 

Here is the corresponding POJO class. Note we dont have any POJO class for Person_Email table, as i will be taken care in Person.hbm.xml which we will see later

public class Person {


private long id;
private int age;
private String firstName;
private String lastName;
private Set emails;

......
......

public Set getEmails() {
    return emails;
}


public void setEmails(Set emails) {
   this.emails = emails;
}

}

Here I have ommitted the getters and setters of fields of Person tables. One thing to notice is that we have defined a Set of emails. In normal java concept, it means that Person class will have a Set object which holds all the email addresses associated with particular peron entity.

Below is the mapping class of Person Table:



<hibernate-mapping package="com.hibernate.tutorial.bean">

        <class name="Person" table="PERSON">
                <id column="PERSON_ID" name="id"></id>
                       <generator class="increment">
               
                <property name="firstName">
                <property name="lastName">
               
                <set name="emails" table="PERSON_EMAIL"></set>
                        <key column="PERSON_ID"></key>
                        <element column="email_address" type="string"></element>
....
....
....      


In mapping file we will define the relationship between two tables.

<set name="emails" table="PERSON_EMAIL"></set>

It shows that instance property emails defined in Person class is related to table Person_Email.

<key column="PERSON_ID"></key> 

Key property shows the coolumn of Person class which is used to create the relation between two entities. We can see that PERSON_ID is a foreign key in Person_Email table.

<element column="email_address" type="string"></element>


Element property shows the rest of the columns present in Person_email table and the type of those columns.

Below is the test code to see how the values will be inserted in both the tables.

Person person = (Person)session.load(Person.class, 1001);
person.getEmails().add(xyz@gmail.com);
session.save(person);

Here i have loaded the existing person entity from database and then adding the email address to the Set.

session.save will save the person entity and because person_email table is mapped to person table (as defined in mapping file), so new row will be inserted in Person_Email table

Wednesday, January 4, 2012

Convert XML to Java Objects

Starting from java 5, JDK has inbuilt support for JAXB. JAXB (Java Architecture for XML Binding) is an efficient way of converting xml to Java objects.

JDK provides a class javax.xml.bind.JAXBContext to create java objects from xml.

Below is the code to demonstrate it:


JAXBContext jaxbContext = JAXBContext.newInstance("com.test.jaxb.xngevents.dtd.cable:"
+"com.test.jaxb.xngevents.dtd.equipment");

Unmarshaller unMarshaller = jaxbContext.createUnmarshaller();

com.test.jaxb.xngevents.dtd.equipment.XngEvent xngEvent = (com.test.jaxb.xngevents.dtd.equipment.XngEvent)unMarshaller.unmarshal(new File("Q1.xml"));




JAXBContext.newInstance method takes list of packages separated by colon. These packages must contain ObjectFactory class or jaxb.index file. When an xsd is converted to JAXB object then ObjectFactory class is automatically created. This means that classes contained in the packages must be schema derived classes. If the classes are not derived then exception like below will be thrown:


javax.xml.bind.JAXBException: doesnt contain ObjectFactory.class or jaxb.index


There is one more overloaded newInstance method in JAXBContext which takes the Class arguments:


Once the JAXBContext is initialized, Unmarshaller is created. Unmarshaller.unmarshal will read the xml file or xml as String and create the java objects.




Friday, December 2, 2011

Set backspace key for erasure on unix

Sometimes when we try to use backspace key on a unix terminal, it does not work as expected. Instead it prints caret and some special characters on command prompt.

There are two ways to handle it:
  • Add below command in .profile of the user account.
                          stty erase ^?
  • Run the following command. It will only set the backspace key for current session.
                          stty erase "press backspace key to print special characters"
          OR           stty erase ^?

stty command is used to set the terminal options. For detailed information, you can check its manual on unix by running command man stty

Thursday, November 10, 2011

Update contacts/DL in outlook using Jacob

Yesterday i blogged about how to access contacts ( Distribution list as well) using Jacob here. Today i will explain how to create new contacts in outlook.
Its same except few deviations:

Creating contact or DL is fairly simple.

Here we are creating a simple contact. Defining variant(2) ensures that item created is a contact item and not DL.

Dispatch createItem = Dispatch.call((Dispatch)oOutlook, "CreateItem", new Variant(2)).toDispatch(); 

We can add values to different attributes. Here i am just adding FullName. We can add other values as well in similar fashion.
Dispatch.put(createItem, "FullName", "NEW CONTACT");  

Saving the item in outlook.
Dispatch.call(createItem, "Save");


in order to create DL, change required is that we need to use Variant(7),
Dispatch createItem = Dispatch.call((Dispatch)oOutlook, "CreateItem", new Variant(7)).toDispatch(); 


then we can set DL specific properties as below:
Dispatch.put(createItem, "DLName", "NEW DL");  


So we are now done with creating contacts. In case we are creating DL, just creating empty DL wont suffice. We need to add members to it.
There are two approaches which can be followed to add member:

  • one is adding single member
  • or adding bulk members together
Here is the code snippet to add single member in DL:

We are creating a recipient in DL,
Dispatch recepient = Dispatch.call((Dispatch)oNameSpace, "CreateRecipient", "abc@gmail.com").toDispatch(); 

Its mandatory to resolve the recipient otherwise it wont be added in DL. resolving means that the address given should be a valid email address, it might not be an existing address but it should compile to the rules of a valid email address
Dispatch.call(recepient,"Resolve");

Now we are adding recipient just created to the DL and saving it.
Dispatch.call(createItem, "AddMember", recepient);
Dispatch.call(createItem, "Save");

We can also add multiple members together to a DL:

Here we are creating a new Item which will hold a list of all recipients:

Dispatch createItem1 = Dispatch.call((Dispatch)oOutlook, "CreateItem", new Variant(0)).toDispatch(); 
Dispatch recepients = Dispatch.call(createItem1, "Recipients").toDispatch();

Add members to the recipient list:
Dispatch.call(recepients,"Add", "xyz@yahoo.com");

Dispatch.call(recepients,"Add", "abc@gmail.com");


Now as we added multiple members to list, we need to resolve all of them so instead of simple "Resolve" we will use "ResolveAll". it does the same job which resolve does for single item.
Dispatch.call(recepients,"ResolveAll");
Add all members to DL and save it.
Dispatch.call(createItem, "AddMembers", recepients);
Dispatch.call(createItem, "Save");

So this way we can create new items in outlook. Jacob is very powerful tool to access different Microsoft applications and work with them. Dispatch class provides the method to call native vba methods.