Wednesday, October 26, 2011

Call by reference program in java

package org.learn.callbyreference;

public class CallByReferenceTest {

    String val = new String("Test");

    public static void main(String[] args) {
        CallByReferenceTest cTest = new CallByReferenceTest();
       
         String s= new String("test this string");
         cTest.changeString(s);
         System.out.println(s);
        

        System.out.println(cTest.val);
        cTest.chagngeVal("Test1111");
        System.out.println(cTest.val);

    }

    public void changeString(String s) {
        s = "test 89898989";
    }

    public void chagngeVal(String s) {
        val = "Test43323243242";
    }

}

Java program on Command design pattern


Save each class in a separate file with the class name and execute the Main.java program. Some classes are not used in the main execution. In later versions of this design I will include them.

----------------------------------------------------------------------------------------------------------
package org.learn.designpatterns.command;

//This class(Main.java) is client part of command design pattern
public class Main {

    public static void main(String args[]) {
        CommandManager mgr = new CommandManager();
        // CommandManager is Invoker part of command design pattern
        Command tomcat = new TomcatStartCommand();
        // In TomcatStartCommand class I used Tomcat class. Here Tomcat class is
        // the receiver part of command design pattern
        Command serviceMix = new ServiceMixStartCommand();
        mgr.addCommand(tomcat);
        mgr.addCommand(serviceMix);
        mgr.runCommands();
    }

}
-----------------------------------------------------------------------------------------------------------
package org.learn.designpatterns.command;

public interface Command {
   
    public void execute();

}
-----------------------------------------------------------------------------------------------------------
package org.learn.designpatterns.command;

public class CommandException extends Exception {
   
    private String message;
   
    public CommandException(String message){
        super(message);
        this.message=message;
    }
   
    public CommandException(){
        super();
    }
   
    public void setMessage(String message){
        this.message = message;
    }
   
    public String getMessage(){
        return message;
    }
   
}
-----------------------------------------------------------------------------------------------------------
package org.learn.designpatterns.command;

import java.util.ArrayList;

public class CommandManager {

    private List<Command> commandList = new ArrayList();

    public void runCommands() {
        for (Command c : commandList) {
            c.execute();
        }
    }

    public void addCommand(Command command) {
        commandList.add(command);
    }
}

class TomcatStartCommand implements Command {

    Tomcat tomcat = new Tomcat();

    @Override
    public void execute() {
        tomcat.startTomcat();
    }
}

class TomcatStopCommand implements Command {

    Tomcat tomcat = new Tomcat();

    @Override
    public void execute() {
        tomcat.stopTomcat();
    }
}

class ServiceMixStopCommand implements Command {
    ServiceMix serviceMix = new ServiceMix();

    @Override
    public void execute() {
        serviceMix.stopServiceMix();
    }

}

class ServiceMixStartCommand implements Command {
    ServiceMix serviceMix = new ServiceMix();

    @Override
    public void execute() {
        serviceMix.startServiceMix();
    }

}
----------------------------------------------------------------------------------------------------------


package org.learn.designpatterns.command;

public class ServiceMix {
   
    public boolean stopServiceMix(){
        System.out.println("Service Mix is stopped");
        return true;
    }
   
    public boolean startServiceMix(){
        System.out.println("Service Mix is started");
        return true;
    }

}
------------------------------------------------------------------------------------------------------------
package org.learn.designpatterns.command;

public class Status {
    private String status;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
   
   
}
------------------------------------------------------------------------------------------------------------
package org.learn.designpatterns.command;

public class Tomcat {
   
    public boolean stopTomcat(){
        System.out.println("Tomcat Stopped");
        return true;
    }
   
    public boolean startTomcat(){
        System.out.println("Tomcat Started");
        return true;
    }

}
------------------------------------------------------------------------------------------------------------

Simple Binary Tree implementaion in java

package org.learn.datastructures.tree.binary;

public class BinaryTree {

    /**
     * @param args
     */
    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree();
        Node rootNode = new Node(10);
        tree.insert(rootNode, 20);
        tree.insert(rootNode, 30);
        tree.insert(rootNode, 5);
        tree.insert(rootNode, 6);
        tree.insert(rootNode, 16);
        tree.insert(rootNode, 67);
        tree.insert(rootNode, 116);
        tree.search(rootNode);
    }

    public void insert(Node node, int data) {
        if (node.data < data) {
            if (node.left != null)
                insert(node.left, data);
            else
                node.left = new Node(data);
        } else if (node.data > data) {
            if (node.right != null)
                insert(node.right, data);
            else
                node.right = new Node(data);
        }
    }

    public void search(Node node) {
        if (node == null)
            return;
        search(node.right);
        System.out.println(node.data);
        search(node.left);
    }

}

class Node {
    Node left;
    Node right;
    int data;

    public Node(int data) {
        this.data = data;
    }
}

A simple compression program in java

package org.learn.compression;

public class Compression {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String toBeCompressed = "aaaaaabbbbbcccce4uiiiioookkkkkkkkkkkkkkkkkkkkkkkk";
        String compressed = compress(toBeCompressed);
       
        System.out.println("String to Compressed="+toBeCompressed + ", length="+toBeCompressed.length());
        System.out.println("Compressed String ="+compressed+ ", length="+compressed.length());
    }
   
    public static String compress(String str){
        String compressedStr="";
        String countChar="";
        int index=0;
        int strLength = str.length();
        while(true){
            char c = str.charAt(index);
            int count=1;
            int temp=index;
            while(true){
                countChar="";
                ++temp;
                if( temp<strLength && c == str.charAt(temp)){
                    count++;
                }else{
                    countChar = c + ""+count;
                    break;
                }
            }
            compressedStr = compressedStr + countChar;
            index+=count;
            if(index>=strLength)
                break;
        }
        return compressedStr;
    }

}

Stack implementation in java

package org.learn.datastructures.stack;

/*
 * A items is an array in which elements can be retrieved and stored in Last in First Out Order
 */
public class Stack {

    private String[] items = null;
    private int top = -1;

    public Stack(int size) {
        items = new String[size];
    }

    public void pop() {
        items[top] = null;
        top--;
    }

    public void push(String element) {
        items[++top] = element;
    }

    public void printItems() {
        if (top == -1) {
            System.out.println("\nStack is empty");
        } else {
            for (int x = 0; x <= top; x++) {
                System.out.print("items[" + x + "]=" + items[x]);
                System.out.print(",");
            }
        }

    }

    public void size() {
        System.out.println("items Size=" + (top + 1));
    }

    public void empty() {
        top = -1;
    }

    public static void main(String args[]) {
        Stack s = new Stack(10);
        s.push("A");
        s.push("B");
        s.push("C");
        s.size();
        System.out.println("Before the pop the items elements are");
        s.printItems();
        s.pop();
        System.out.println("\nAfter the pop the items elements are");
        s.size();
        s.printItems();
        s.empty();
        s.printItems();
    }
}

Simple LinkedList implementation in java without iterator

package org.learn.collections.list.linkedlist;

/* a linked list is a data structure consisting of a group of nodes which together represent a sequence.
 * Under the simplest form, each node is composed of a datum and a reference (in other words, a link)
 * to the next node in the sequence; more complex variants add additional links.
 * This structure allows for efficient insertion or removal of elements from any position in the sequence.
 * But reading a particular node in a list is time consuming action because it has to travel all previous
 * nodes of the target node.
 *
*/

/*
 * This code is working perfectly without any issues. Need to handle the null pointer exceptions only.
 */
public class LinkedList {

    Node header;

    public LinkedList(int data) {
        header = new Node(data);
    }

    public void insert(Node n) {

        if (header == null) {
            header = n;
        } else {
            Node node = header;
            while (node.next != null) {
                node = node.next;
            }

            node.next = n;

        }
    }

    public void insertAt(int pos, Node newNode) {

        Node temp = null;
        if (pos == 1) {
            newNode.next = header;
            header = newNode;
        } else if (pos > 1) {
            Node node = header;
            for (int x = 2; x < pos; x++) {
                if (node != null)
                    node = node.next;
            }
            temp = node.next;
            node.next = newNode;
            newNode.next = temp;
        }
    }

    public void printLinkedList() {
        Node node1 = header;
        while (node1 != null) {
            System.out.print(node1.data);
            node1 = node1.next;
            if (node1 != null)
                System.out.print("->");
        }
    }

    public static void main(String[] args) {
        LinkedList ll = new LinkedList(10);
        ll.insert(new Node(12));
        ll.insert(new Node(13));
        ll.insert(new Node(14));
        ll.insertAt(2, new Node(11));
        ll.insertAt(1, new Node(5));
        ll.insertAt(7, new Node(59));
        ll.insertAt(5, new Node(59));
        ll.printLinkedList();
    }

}

class Node {
    int data;
    Node next;
   
    public Node(int data,Node node){
        this.data=data;
        this.next= node;
    }
    public Node(int data){
        this(data,null);
    }
}

Tuesday, October 11, 2011

Installing war support feature in apache-karaf 2.2.2

login into apache-karaf

karaf@root>features:install -v war

This will install war 2.2.2, http 2.2.2 and jetty 7.4.2.v20110526 features.

How to connect to a Dell PowerConnect 6248 Switch

To connect a switch there are two ways.
1. Type the IP address in the browser and it will displays a login page and use the credentials to login.
2. Use putty or windows hyper terminal  use the telnet to connect. In putty select telnet and type the IP of the switch this will asks you the user name and password to login into the switch.

After login into the switch use enable command to get the privilege to execute admin commands.
For example to execute a traceroute command you need privilege so use enable command.

console#script ?
This command gives the sub commands of the script command

console#script list

This command displays the scipt files which are in the switch

console#script show abc.scr

This command shows the contents of abc.scr script file

console#script delete abc.scr
deletes abc.scr file.










Monday, September 19, 2011

How to use delegateExpression in activiti

In Activiti if you want to call an existing delegate class form a work flow task use delegate expression option.

We need to add the delegate classes into the spring context (i.e. activiti context) so that it will available to activiti engine

Here is the picture of activiti (please do not confuse, I merged two service tasks properties into one diagram):



Delegate classes:

package com.example.delegate.tasks;

import org.activiti.engine.delegate.DelegateExecution;

public class TomcatDelegate implements JavaDelegate {

@Override
public void execute(DelegateExecution execution) throws Exception {
System.out.println("***TomcatDelegate***");

}

}

package com.example.delegate.tasks;

import org.activiti.engine.delegate.DelegateExecution;

public class ServiceMixDelegate implements JavaDelegate {

@Override
public void execute(DelegateExecution execution) throws Exception {
System.out.println("***ServiceMixDelegate***");

}

}


package com.example.delegate.tasks;

import org.activiti.engine.delegate.DelegateExecution;

public class UpgradeDelegate implements JavaDelegate{

@Override
public void execute(DelegateExecution execution) throws Exception {
System.out.println("***UpgradeDelegate***");

}

}

Here is activiti xml tag where you have to add the delegate classes:

BPMN Activiti 5.7 - Example - Using Single Delegate class for multiple tasks

In Activiti by using Expressions and Delegate Expressions we can use one class (no need to implement JavaDelegate interface) for multiple service tasks.

Example:
1. I have created a class called AccountDelegate.java this class contains all the required methods for the tasks in the BPMN work flow.

The major thing you have to remember is you need to pass a DelegateExecution parameter to the method which you are invoking through the activit work flow. This will allows you to get the access to the execution context but this DelegateExecution method parameter is not mandatory. You can have a method without this parameter also.

package com.example.delegate

import org.activiti.engine.delegate.DelegateExecution;

public class AccountDelgate {

AccountService service = AccountService.createAccountService();

public int getAccountBalance(DelegateExecution execution,
String accountNumber) {
int amount = service.getAccountBalance(accountNumber);
return amount;
}

public boolean transferMoney(DelegateExecution execution,
String accountNumber1, String accountNumber2, int transferAmount) {

int balance = (Integer) execution.getVariable("accountBalance");

boolean result = false;
if (balance > transferAmount) {
result = service.transferMoney(accountNumber1, accountNumber2,
transferAmount);
}
return result;
}

/*
* Without delegation parameter also it works but to get the access to the
* execution context variables we have to pass DelegateExecution
*/
public int getAccountBalance(String accountNumber) {
int amount = service.getAccountBalance(accountNumber);
return amount;
}
}

After creating the above class go to activiti editor (use Eclipse Indigo 3.6 or Spring Source Tool Suite 2.5.1 or above. I am using STS (spring source tool suite))

Here is the diagram for this transfer money process(please do not confuse, I merged two service tasks properties into one diagram):




After completing the activiti diagram. We need to ActivitiDelegate.class file into the activiti.cfg.xml file so that it will availble to activiti engine. Basically we are adding ActivitiDelgate.class into spring context so it will available to activiti engine.

Here is the tag where you need to add.


Utitily class which I was used for creating some dummy bank accounts.

public class BankService {

public int getNumberOfAccounts(){
return 50;
}

public boolean createDummyAccounts(){
AccountService service = AccountService.createAccountService();
service.createAccount("MALLIKARJUN", 5000);
service.createAccount("RAO", 5000);
service.createAccount("MALLI", 5000);
service.depositMoney("DBN-MA-01000", 20000);
return true;
}
}

AccountService.java which has actual logic.

package com.example.delegate.service;

import java.util.ArrayList;
import java.util.List;

import com.example.delegate.util.Account;

public class AccountService {

private static AccountService accountService= null;
List accountList = new ArrayList();


public static AccountService createAccountService(){
if(accountService == null){
accountService = new AccountService();
}
return accountService;
}

public Account createAccount(String customerName,int minBalance){
Account account = new Account(customerName,minBalance);
accountList.add(account);
return account;
}
public int getAccountBalance(String accountNumber) {

Account account = findAccount(accountNumber);
int balance = 0;
if(account!=null){
balance = account.getBalance();
}
return balance;
}

public boolean transferMoney(String accountNumber1,String accountNumber2, int transferAmount) {
System.out.println("Transferring Money from "+accountNumber1 + " to "+ accountNumber2 +" an amount of Rs."+transferAmount);
Account account1 = findAccount(accountNumber1);
Account account2 = findAccount(accountNumber2);
System.out.println("accountNumber2 balance before transfer is "+account2.getBalance());
if(account1.getBalance()>transferAmount){
account1.setBalance(account1.getBalance()-transferAmount);
account2.setBalance(account2.getBalance()+transferAmount);
}else{
return false;
}
System.out.println("accountNumber2 balance after transfer is "+account2.getBalance());
return true;
}

public boolean depositMoney(String accountNumber, int amount){
Account account = findAccount(accountNumber);
account.setBalance(account.getBalance()+amount);
System.out.println("Rs."+amount+" successfully depositted in "+accountNumber);
return true;
}

public boolean withdrawMoney(String accountNumber, int amount){
Account account = findAccount(accountNumber);
account.setBalance(account.getBalance()-amount);
return true;
}

public Account findAccount(String accountNumber){

//System.out.println("accountNumber = "+accountNumber + "Size="+accountList.size());
for(Account a:accountList){
//System.out.println("Account Number = "+a.getAccountNumber());
if(a.getAccountNumber().equalsIgnoreCase(accountNumber)){
return a;
}
}
//System.out.println("Size="+accountList.size());
return null;
}

}

Account.java (POJO):

package com.example.delegate.util;

import java.io.Serializable;

public class Account implements Serializable {

private static final long serialVersionUID = 1L;

private String accountNumber;
private String customerName;
private int balance;
private String type;
private static int num;


public Account(String customerName,int minBalance){
this.accountNumber = "DBN-"+customerName.substring(0,2)+"-0100"+(num++);
this.customerName=customerName;
this.type="SA";
balance=minBalance;
}

public String getAccountNumber() {
return accountNumber;
}

public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}

public String getCustomerName() {
return customerName;
}

public void setCustomerName(String customerName) {
this.customerName = customerName;
}

public int getBalance() {
return balance;
}

public void setBalance(int balance) {
this.balance = balance;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

}

-----------------------------------------------------------------------------------
To execute the above program you can use the below main program.

package com.delegate.example.activiti;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import org.activiti.engine.RuntimeService;

import com.example.delegate.service.BankService;

public class ActivitiEngine {

public static void main(String args[]) {

ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"classpath:activiti.cfg.xml");

BankService bankService = (BankService)applicationContext.getBean("bankService");
bankService.createDummyAccounts();

RuntimeService runtimeService = (RuntimeService) applicationContext
.getBean("runtimeService");

try {
runtimeService.startProcessInstanceByKey("TransferMoneyProcess");
} catch (Exception e) {
System.out.println("Error in TransferMoney Process ");
e.printStackTrace();
}

}
}
-------------------------------------------------------------------------------------

Tuesday, September 6, 2011

Install a file in maven repo from your local file system

mvn install:install-file -Dfile=C://softwares/ibatis-sqlmap-3.0-beta-4.jar -DgroupId=org.apache.ibatis -DartifactId=ibatis-core -Dversion=3.0 -Dpackaging=jar

To get groupId and artifactIds just add the required dependency entry then execute mvn eclipse:eclipse then it won't be able to install the file but it gives the entire mvn install:install-file command along with the required parameters.

mvn install:install-file -DgroupId=org.activiti -DartifactId=activiti-spring -Dversion=5.7-sources -Dpackaging=jar -Dfile=C:\softwares\activiti-5.7\setup\files\dependencies\libs\activiti-spring-5.7-sources.jar


mvn install:install-file -DgroupId=org.activiti -DartifactId=activiti-engine -Dversion=5.7-sources -Dpackaging=jar -Dfile=C:\softwares\activiti-5.7\setup\files\dependencies\libs\activiti-engine-5.7-sources.jar

Sunday, August 28, 2011

Setting up Apache Felix and installing a sample war or jar osgi bundle

Steps:
1. Download the org.apache.felix.main.distribution-3.2.2.zip file from apache-felix web site.
2. Unzip the above zip file into a folder.
3. Open a command prompt and change the directory to felix home folder.
4. Type java -jar ./bin/felix.jar

Now you will get a prompt like g!
Type lb to list the bundles
To install any OSGi-fied bundle jar/war use the below command
install file:

By default Apache felix loads the bundles which are in bundle folder.
In 3.2.2 version there are four bundles.
org.apache.felix.bundlerepository-1.6.2.jar
org.apache.felix.gogo.command-0.8.0.jar
org.apache.felix.gogo.runtime-0.8.0.jar
org.apache.felix.gogo.shell-0.8.0.jar

So whatever the bundles required to your bundle you need to install them manually or place them in the bundle folder.

For Example:
You need to install Jetty then you have to install them manually.
g!install file:./mysampleapp/web/lib/jetty-6.1.7.jar
g!install file:./mysampleapp/web/lib/jetty-util-6.1.7.jar

After installing all required bundles you need to start them by using start command and bundle id (lb command gives the bundle id)

g!start 12
here 12 is bundle id

Some times felix might not start the bundles properly so use felix:refresh or stop and start the bundles. I don't know why some times felix is not starting the bundles properly.








Saturday, August 27, 2011

If you are getting generics are not supported in -source 1.3 in maven

When you execute maven clean install if you are getting "generics not supported in -source 1.3" then add the below plugin into the pom.xml then execute the maven eclipse:eclipse then refresh your project in eclipse.
<plugin>
<groupid>org.apache.maven.plugins</groupid>
<artifactid>maven-compile-plugin</artifactid>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>

Thursday, August 18, 2011

Useful commands of karaf OSGI server console

Installing an OSGi bundle from your local file system or local repository. Type the below command on the karaf console.
karaf@root> osgi:install -s file:C:/myrepo/org/apache/camel/camel-osgi/1.5.0/camel-osgi-1.5.0.jar
List OSGi bundles
karaf@root> osgi:list
Search for a specific or gorup of osgi bundle. Below example lists all camel osgi bundles
karaf@root> osgi:list grep camel
Stopping an OSGi bundle
karaf@root> osgi:stop bundle id

Installing featues in servicemix or karaf OSGI server:
First add the url of the feature but make sure that this feature is already installed in your maven repository otherwise you will not be able to install.
karaf@root> featues:addUrl -s mvn:org.apache.camel.karaf/apache-camel/2.7.1/xml/features
-s option starts all features listed in the descriptor file.
karaf@root> features:install camel-http
To list all features installed in servicemix or karaf
karaf@root> features:list
karaf@root> features:list grep feature name