Saturday, May 25, 2013

Singleton

Here's are two examples of creating singletons. One uses lazy loading and the other eagerly creates the instance as soon at the class is loaded. For lazy loading, we need to make sure we're thread safe and prevent two threads from creating two instances.
Also, as an interesting side trick, the two classes memoized results to make repeated calls return the result faster.

Get the code here.

import java.util.HashMap;
import java.util.Map;

/**
 * Gives the nth fibonacci number.
 * It memoizes results so that repeated calls are fast.
 *
 * @author megha
 */
public class MemoizedFibonacci {

        // This is the only instance that we will create, ever!
        private static final MemoizedFibonacci SINGLETON_INSTANCE = new MemoizedFibonacci();

        private final Map<Integer, Long> fibonacciPairs = new HashMap<Integer, Long>();

        // constructor is made private so that no one can create an instance of this class.
        private MemoizedFibonacci() {}

        /**
         * Method to access the only instance of {@link MemoizedFibonacci}.
         */
        public static MemoizedFibonacci getInstance() {
                return SINGLETON_INSTANCE;
        }

        /**
         * @return the {@code n}th fibonacci number, starting with 0 for n=0, 1 for n=1
         */
        public long getNthFibonacci(int n) {
                if (n == 0) return 0;
                if (n == 1) return 1;

                if (fibonacciPairs.containsKey(n)) {
                        return fibonacciPairs.get(n);
                }
                long nthFibonacci = getNthFibonacci(n-1) + getNthFibonacci(n-2);
                fibonacciPairs.put(n, nthFibonacci);
                return nthFibonacci;
        }
}
import java.util.HashMap;
import java.util.Map;

/**
 * Gives the Sum of squares till the nth number.
 * It memoizes the results so that repeated calls are fast.
 *
 * @author megha birmiwal
 */
public class MemoizedSumOfSquares {
// this is lazily loaded
        private static MemoizedSumOfSquares singletonInstance = null;

        private final Map<Integer, Long> sumOfSquarePairs = new HashMap<Integer, Long>();

        private MemoizedSumOfSquares() {}

        // marking it synchronized, to prevent race conditions // i.e. when multiple threads call this at the same time.
        public synchronized MemoizedSumOfSquares getInstance() { // lazy loaded here
                if  (singletonInstance == null) {
                        singletonInstance = new MemoizedSumOfSquares();
                }
                return singletonInstance;
        }

        public long getSumOfSquares(int n) {
                if (n == 0) return 0;
                if (sumOfSquarePairs.containsKey(n)) {
                        return sumOfSquarePairs.get(n);
                }
                long result = getSumOfSquares(n-1) + n*n;
                sumOfSquarePairs.put(n, result);
                return result;
        }
}


Enums in java: Another Example

Here's another example of using enums. Note that the constructor of an enum cannot be public.

checkout the code here

/**
 * An enum for various payment modes.
 * The payment mode also specifies a surcharge to be charged for making payments.
 *
 * @author megha birmiwal
 */
public enum PaymentMode {
        CASH(0),
        CHECK(0.5),
        CREDIT_CARD(1.5),
        DEBIT_CARD(1.0),
        GIFT_CARD(0),
        PAYPAL(1.5),
        MONEY_ORDER(0.3);

        private final double surcharge;

        private PaymentMode(double surcharge) {
                this.surcharge = surcharge;
        }

        public double getSurcharge() {
                return surcharge;
        }
}

/**
 * Lists all payment modes and their surcharges.
 *
 * @author megha birmiwal
 */
public class PaymentModeLister {

        public static void main(String[] args) {
                // .values() returns an array of all possible values
                PaymentMode[] values = PaymentMode.values();
                for (PaymentMode pm : PaymentMode.values()) {
                        System.out.println(pm.name() + " / " + pm.getSurcharge());
                }

                // go from string to the corresponding enum
                PaymentMode pm = PaymentMode.valueOf("PAYPAL");
                System.out.println(pm == PaymentMode.PAYPAL);

                // throws exception because there is no enum value called XYZ
                PaymentMode mode = PaymentMode.valueOf("XYZ");
        }
}

JSON

Here's an example that shows how to play around with JSON objects in java. There are a bunch of JSON libraries. This example users json.org.

checkout the code here

package org.megha.blog.example.json;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Play around with {@code json.org}'s JSON library.
 * To run this, you import the library from json.org.
 *
 * @author megha birmiwal
 */
public class JsonPrinter {
       
        public static void main(String[] args) {
               
                // create a json object from a json string
                String responseData = "{'name':'Robert','interests':['Swimming','Music',123],"
                    + "'address':{'city': 'Bangalore'}}";
                JSONObject jsonObject = new JSONObject(responseData);
               
                // convert back to "pretty-printed" string
                System.out.println(jsonObject.toString(4));

                // extract values from a json object
                String name = jsonObject.getString("name");
                System.out.println(name);
               
                JSONArray jsonArray = jsonObject.getJSONArray("interests");
                System.out.println(jsonArray.toString(2));
               
                // json array has .length() and .getXXX(index) methods to get elements
                // also has a .join() to join values into a string with the // specified separator
                String interests = jsonArray.join(" ");
                System.out.println(interests);
               
                JSONObject address = jsonObject.getJSONObject("address");
                String addressCity = address.getString("city");
                System.out.println(addressCity);

                // adding entries is trivial. just call put()
                address.put("country", "India");

                // difference between pretty-printed and condensed outputs
                System.out.println(address.toString());
                System.out.println(address.toString(2));

                // note that it prints address with the added country
                System.out.println(jsonObject.toString(4));
        }
}

Monday, November 5, 2012

Selenium and Webdriver

Here is a simple program that shows how to use selenium.
More concrete examples of webdriver/selenium and page-objects are at http://code.google.com/p/java-through-examples/source/browse/tests/org/megha/blog/example/selenium/


package org.megha.blog.example.selenium;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
/**
 * Searches for a given string on yahoo.com.
 * (just an example to show how selenium client is used.)
 */
public class YahooSearch {
        // searches for the given string and prints the top two results
        public void searchFor(String string) {
                Selenium selenium = new DefaultSelenium("LOCALHOST", 4444, "*firefox", "http://www.yahoo.com/");
                selenium.start();
                selenium.open("/");
                selenium.waitForPageToLoad("30000");
                selenium.type("name=p", string);
                selenium.click("id=search-submit");
                selenium.waitForPageToLoad("30000");
                // TODO: do something with the results
                selenium.close();
                selenium.stop();
        }
       
        public static void main(String[] args) {
                YahooSearch search = new YahooSearch();
                search.searchFor("google");
        }
}