neutrofoton

Science, Technology and Life

Generic Singleton Pattern in Java

| Comments

In my previous post about singleton pattern in C#, it is very nice flexible singleton code which make us be able to create a singleton instance of a non singleton class. But we can still be able to create a non singleton instance of the target class.

In this post I want to implement it in Java. As far as I know even though both C# and Java have generic feature, generic in C# quite different from the one in Java. While converting of what I did about generic singleton in C# to Java, I feel that the way I do in Java is not as elegant as in C#. The following code is the generic singleton code I write in Java.

generic singleton
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.HashMap;
import java.util.Map;

public class Singleton{

    private static final Singleton instance = new Singleton();

    @SuppressWarnings( "rawtypes")
    private Map<Class,Object> mapHolder = new HashMap<Class,Object>();

    private Singleton() {}


    @SuppressWarnings("unchecked")
    public static <T> T getInstance(Class<T> classOf) throws InstantiationException, IllegalAccessException {


        synchronized(instance){

            if(!instance.mapHolder.containsKey(classOf)){

                T obj = classOf.newInstance();

                instance.mapHolder.put(classOf, obj);
            }

            return (T)instance.mapHolder.get(classOf);

        }

    }

    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }
}

The following code show how to use the generic singleton class. It’s quite similar to the C# version.

sample
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class Starter {

    /**
     * @param args
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public static void main(String[] args) throws InstantiationException, IllegalAccessException  {
        // TODO Auto-generated method stub

        Employee emp1 = new Employee();
        emp1.setName("neutro");

        Employee emp2 = new Employee();
        emp2.setName("neutro");

        boolean isEqual = emp1.equals(emp1);

        isEqual = emp1==emp2;
        System.out.println("Is Equal Test1 = "+ isEqual);

        Singleton.getInstance(Employee.class).setName("Hello");
        emp1 = Singleton.getInstance(Employee.class);
        emp2 = Singleton.getInstance(Employee.class);

        isEqual = emp1==emp2;
        System.out.println("Is Equal Test2 = "+ isEqual);

        System.out.println("emp1 = "+ emp1.getName());
        System.out.println("emp2 = "+ emp2.getName());


        Singleton.getInstance(Departement.class).setName("Information Technology");
        Departement dpt1 = Singleton.getInstance(Departement.class);
        Departement dpt2 = Singleton.getInstance(Departement.class);

        isEqual = dpt1==dpt2;
        System.out.println("Is Equal Test3 = "+ isEqual);

        System.out.println("dpt1 = "+ dpt1.getName());
        System.out.println("dpt2 = "+ dpt2.getName());

    }
}

Again, if we see from the sample code above it seems that generic singleton in C# is more elegant than in Java. The main thing that I should do is I have to use HashMap collection to hold any instance of what that want to be as singleton and reuse for the future need in the life cycle of my application.

Anyway, if you have better and much more elegant solution how to implement generic singleton pattern in Java I am very appreciate for any suggestion. Finally I would like to thank you very much for visiting and reading my blog, and have a nice day.

Update March 11, 2016

If you want to the java singleton above, please ensure you have remove / clean up method to clean up HashMap contents if the singleton objects are not needed anymore. At least at the end of application lifecycle, the HashMap and its contents should be removed completely from memory.

Generic Singleton Pattern in C#

| Comments

In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.[1]

Honestly in my daily coding activity, sometimes I need to implement singleton pattern. Jon wrote a good singleton article in C# here. Another case I want to implement singleton pattern in generic way. I convert what has been wrotten by Jon into generic.

generic singleton
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/// <summary>
    /// Generic class which makes non singleton class to be singleton.
    /// Calling singleton instance of class should be Singleton<T>.Instance, otherwise the returned class is not singleton one.    ///
    /// </summary>
    /// <typeparam name="T">Genric class type to be singletonized</typeparam>
    public sealed class Singleton<T> where T : class, new()
    {
        /// <summary>
        /// Private constuctor to avoid this class instantiated
        /// </summary>
        Singleton()
        {
        }

        /// <summary>
        /// Property to get access to singleton instance
        /// </summary>
        public static T Instance
        {
            get
            {
                return Nested.instance;
            }
        }

        /// <summary>
        /// Private nested class which acts as singleton class instantiator. This class should not be accessible outside <see cref="Singleton<T>"/>
        /// </summary>
        class Nested
        {
            /// <summary>
            /// Explicit static constructor to tell C# compiler not to mark type as beforefieldinit
            /// </summary>
            static Nested()
            {
            }

            /// <summary>
            /// Static instance variable
            /// </summary>
            internal static readonly T instance = new T()
        }
    }

The following snipped code is a sample how to use the generic singleton class.

sample
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Processor
{
    public string Name
    {
        get;
        set;
    }

    public void Execute()
    {
    }
}

public class void Main(string[] args)
{
    Singleton<Processor>.Instance.Execute();
}

From the sample above is shown that we can make a non singleton class to be singleton at runtime. But we can still create a non singleton instance as we need. That’s really nice flexible thing.

Reference

[1] http://en.wikipedia.org/wiki/Singleton_pattern

ASP.NET Session State in Database

| Comments

At some point we need to store information when dealing with web application. Storing information in web application can be implemented in some ways such as session and cookies.

Dealing with session case, previously I never got a situation where I should store the session state in persistance way till I got a condition implementing this way.

The scenario is we want to implement load balancer to our applications and services (web service, wcf) that hosted in IIS. The aim of this enhancement basically to improve availability and scalability of existing in house application without doing huge refactoring.

In this post I just want to share the short steps I did during researching implementing session state on a database. First of all open command prompt and navigate to .NET framework installation path. In this case, my installation path is C:\Windows\Microsoft.NET\Framework64\v4.0.30319>

We will use a tool called aspnet_regsql.exe that shipped with .NET framework installation to generate database that will be used to store session state. To display detail argument needed by this tool we can use the following command:

aspnet_regsql
1
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regsql.exe /?
generate session state database
1
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regsql.exe -ssadd -d {databaseName} -S {server\instance} -sstype c -U {username} -P {password}

The command will create database, tables and store procedures. In web.config, don’t forget to add session state configuration by pointing the generated database.

session state configuration
1
2
3
4
5
<system.web>
    <sessionstate mode="SQLServer" allowcustomsqldatabase="true" sqlconnectionstring="Data Source={server\instance};Initial Catalog={databaseName}; user={username}; password={password}" cookieless="false" timeout="20">

  </sessionstate>
</system.web>

To test our session storage, just create simple aspx page.

sample.aspx
1
2
3
4
5
6
<asp:button id="btnAddSession" runat="server" text="Add Session" onclick="btnAddSession_Click"/>

<asp:button id="btnRemoveSession" runat="server" text="Remove Session" onclick="btnRemoveSession_Click"/>

<br>
<asp:label id="ctlLblSessionDisplay" runat="server" text=""></asp:label>
sample.aspx.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
protected void Page_Load(object sender, EventArgs e)
{
    if (Session[Constant.SessionKey] != null)
        ctlLblSessionDisplay.Text = Session[Constant.SessionKey].ToString();
    else
        ctlLblSessionDisplay.Text = "NO Session";
}

protected void btnAddSession_Click(object sender, EventArgs e)
{
    Session.Add(Constant.SessionKey, "Hello");
}

protected void btnRemoveSession_Click(object sender, EventArgs e)
{
    Session.Remove(Constant.SessionKey);
}

Mono on OS X 10.8 Mountain Lion

| Comments

In this post I will write about setup and configure mono on OS X. I need mono on my Mac since C# is one of my favorite programming language ;)

First of all let’s download Mono SDK and MonoDevelop. The order installation is Mono SDK first then MonoDevelop. The installation of Mono SDK and MonoDevelop should be easy by following the installation wizard.

When the installation finish, open terminal :

mono version
1
mono -V

We should get info about the version of mono installed in our machine.

Try to create an ASP.NET Web Application project by selecting menu : File > New > Solution. Select C# > ASP.NET > Web Application

Click Run > Run With > Mono Soft Debugger for ASP.NET

ASP.NET on Apache Web Server

To run ASP.Net on Apache web server, we need Mod mono module. It is an Apache 2.0/2.2 module that provides ASP.Net support for Apache web server. The steps installation are :

  1. Install Apache web server. The steps for OS X Mountain Lion can be found in my previous post
  2. Install Xcode, OS X development tool. It’s free and can be downloaded via App Store. We need it to compile mod mono installation source
  3. Download Mod mono source installation here. At the time of write this article I use mod_mono-2.10.tar.bz2
  4. Install mod mono module. Open terminal
    mod mono installation
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    mkdir ~/modmono
    cp ~/Downloads/mod_mono-2.10.tar.bz2 ~/modmono
    cd ~/modmono
    tar xzf mod_mono-2.10.tar.bz2
    cd mod_mono-2.10
    ./configure
    make
    sudo make install
    sudo cp /etc/apache2/mod_mono.conf /etc/apache2/other
    
  5. Add mod_mono.conf reference in httpd.conf
    edit httpd.conf
    1
    
    sudo vi /etc/apache2/httpd.conf
    
    Add the following code at the end of httpd.conf
    httpd.conf
    1
    
    Include /etc/apache2/mod_mono.conf
    
  6. Create a web directory with the path ~/Projects/Mono/TestMonoApache/TestMonoApache/ In that directory create an index.aspx file
    index.aspx
    1
    
    <center>mod_mono is working:<%=System.DateTime.Now.ToString()%></center>
    
  7. Add an Apache configuration file for mono.
    edit mod_mono.conf
    1
    
    sudo vi /etc/apache2/mod_mono.conf
    
    Add the following line at the end of mod_mono.conf
    mod_mono.conf
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    Alias /testmono "/Users/username/Projects/Mono/TestMonoApache/TestMonoApache/"
    <Directory "/Users/username/Projects/Mono/TestMonoApache/TestMonoApache/">
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
    
        Order allow,deny
        Allow from all
    </Directory>
    AddMonoApplications default "/testmonoapache:/Users/username/Projects/Mono/TestMonoApache/TestMonoApache/"
    <Location /testmonoapache>
     SetHandler mono
    </Location>
    
  8. Restart apache server with command :
    restart apache
    1
    
    sudo /usr/sbin/apachectl restart
    
  9. Open browser and hit http://localhost/testmonoapache/index.aspx

Cool, now our apache web server can receive request for asp.net page. Thanks for reading and see you in the next post :)

References

  1. http://www.mono-project.com/Mod_mono
  2. http://blog.coultard.com/2012/04/developing-using-c-and-mono-on-mac.html
  3. http://www.ienablemuch.com/2010/10/aspnet-on-mac-os-x-snow-leopard-at-one.html

Install Tomcat in OS X 10.8 Mountain Lion

| Comments

In this blog post will show us about step installing Apache Tomcat on OS X Mountain Lion. I assume we already have Java installed on our machine. The first step is downloading Tomcat binary distribution in Tomcat website. In this case I use version 7.0.30.

Extract the downloaded binary distribution onto ~/Download/apache-tomcat-7.0.30. Create directory in /usr/local if we don’t have it yet.

tomcat installation
1
sudo mkdir /usr/local

Move ~/Download/apache-tomcat-7.0.30 to /usr/local

tomcat installation
1
sudo mv ~/Downloads/apache-tomcat-7.0.30 /usr/local

To make it easy to replace this release with future releases, we are going to create a symbolic link that we are going to use when referring to Tomcat. Then we also will change owner and make script executable

tomcat installation
1
2
3
sudo ln -s /usr/local/apache-tomcat-7.0.30/ /Library/Tomcat
sudo chown -R neutrocode /Library/Tomcat
sudo chmod +x /Library/Tomcat/bin/*.sh

The next step is creating user for tomcat admin by editing tomcat-user.xml

tomcat installation
1
vi /Library/Tomcat/conf/tomcat-users.xml
tomcat-users.xml
1
2
3
4
5
6
7
8
9
<role rolename="admin-gui"/>
<role rolename="admin-script"/>
<role rolename="manager-gui"/>
<role rolename="manager-script"/>
<role rolename="manager-jmx"/>
<role rolename="manager-status"/>

<user username="admin" password="password" roles="admin-gui,admin-script" />
<user username="manager" password="password" roles="manager-gui,manager-script,manager-jmx,manager-status" />

Add the following text in current user profile .bash_profile

.bash_profile
1
2
3
4
export CATALINA_HOME=/Library/Tomcat
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home

export PATH=$JAVA_HOME:$PATH

Start the server with the following command :

start tomcat
1
$CATALINA_HOME/bin/catalina.sh start

or

start tomcat
1
$CATALINA_HOME/bin/startup.sh

Stop the server with the following command :

start tomcat
1
$CATALINA_HOME/bin/catalina.sh stop

or

start tomcat
1
$CATALINA_HOME/bin/shutdown.sh

Install phpMyAdmin on OS X 10.8 Mountain Lion

| Comments

In the previous post, we have installed Apache, PHP and MySQL on OS X 10.8. To do administration of mySQL database we can use various app. One of the tool that usually use by programmer to do that is phpMyAdmin. It is a free opensource web app that’s used to manage MySQL database. Let’s install it now.

The first thing that we need to do is open terminal and type

symbolic link for mysql
1
2
3
sudo mkdir /var/mysql

sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock

Extract the downloaded phpMyAdmin-3.5.2.1-english.zip into web folder and rename as phpMyAdmin. So now we should have ~/Sites/phpMyAdmin directory.

On browser, open : http://localhost/~username/phpmyadmin

Now we can login and administer MySQL database.

Install MySQL on OS X 10.8 Mountain Lion

| Comments

To install mysql the first thing that we need to do is download mysql installer on the mysql website. In that web site we can see several versions of mysql. We will use Mac OS X ver. 10.6 (x86, 64-bit), DMG Archive. When we open the mysql-5.5.27-osx10.6-x86_64.dmg file, we will find 3 package installers.

Install all the three packages with the following order :

  1. mysql-5.5.27-osx10.6-x86_64.pkg
  2. MySQLStartupItem.pkg
  3. MySQL.prefPane

To start/stop MySQL we can use GUI tool from System Preferences > MySQL

We can also start/stop MySQL via terminal

start mysql
1
sudo /usr/local/mysql/support-files/mysql.server start
stop mysql
1
sudo /usr/local/mysql/support-files/mysql.server stop
get mysql version
1
sudo /usr/local/mysql/bin/mysql -v

In order to use MySQL command without have to specify MySQL installation full path, we need to add MySQL installation directory to shell path.

bash profile
1
2
cd ~
vi .bash_profile
path
1
export PATH="/usr/local/mysql/bin:$PATH"

Then reload the new PATH

1
source ~/.bash_profile
test get mysql version
1
mysql -v
set mysql password
1
2
cd ~
/usr/local/mysql/bin/mysqladmin -u root password 'yourpassword'

Install PHP on OS X 10.8 Mountain Lion

| Comments

On the previous post, we have set up apache on OS X Mountain Lion. In this post we will continue to install php module to run with apache on Mountain Lion. PHP actually is shipped in OS X 10.8. The first step is edit httpd.conf in apache directory.

httpd configuration
1
sudo vi /etc/apache2/httpd.conf

Uncommect (remove #) php module declaration

1
LoadModule php5_module libexec/apache2/libphp5.so
restart apache
1
sudo apachectl restart

To see and test PHP create a file with the content, and save in /Users/username/Sites as “test.php”. Then open in browser http://localhost/~username/test.php

test.php
1
<?php phpinfo(); ?>

Configure Apache on OS X 10.8 Mountain Lion

| Comments

After installing Mountain Lion on my Macbook, I decided to prepare and set up software development tools in it. One of it is activate web sharing feature which can be found at System Preferences > Sharing on previous version. I was very suprise that apple seems remove it from the list.

By searching some references on internet, here are the things that I did. Apache actually is pre-installed on Mountain Lion and we just need to enable it via the command line.

start apache server
1
sudo apachectl start

We will be asked to enter login password for starting it. Enter a password then open in browser localhost website. You should get the following display

stop apache server
1
sudo apachectl stop
get apache version
1
httpd -v

Historically, OSX has had 2 web roots. One at a system level and the other one at a user level. The user level one allows multiple acounts to have their own web root whilst the system one is global for all users. The location of system web document root is at

1
/Library/WebServer/Documents/

On the other hand, the user level web roots in the previous version of OSX (Lion) can be found under ~/Sites. But we can not find that directory anymore in Mountain Lion. So we need to create it manually.

In terminal type:

edit configuration
1
2
cd /etc/apache2/users
vi username.conf

Edit username.conf in vi editor as is the following code:

1
2
3
4
5
6
<Directory "/Users/username/Sites/">
Options Indexes MultiViews
AllowOverride None
Order allow,deny
Allow from all
</Directory>

Then create html page inside ~/Sites to test our user local website and save it as index.html

sample page
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta http-equiv="Content-Style-Type" content="text/css">
  <title></title>
  <meta name="Generator" content="Cocoa HTML Writer">
  <meta name="CocoaVersion" content="1187">
  <style type="text/css">
  </style>
</head>
<body>
<h1><b>It works!</h1>
<h1><b>I am on local user website</b></h1>
</body>
</html>

Congratulation your apache is running well now :)

Jomla Encryption in C#

| Comments

Couple days ago I got a task to migrate user from an existing website which build based on Jomla CMS to an ASP.NET website user. Both of them use different encryption technique. The plan was that the Jomla based website would be replaced with the .NET website. In sort the scenario was :

  1. Replace PHP website build on top Jomla CMS with .NET
  2. Migrate users from Jomla so they can login into the new .NET website using old password
  3. Migrate some roles

The first thing that come to my mind is to check whether they use the different encryption algorithm or not. And yup…they use different algorithm :( . So I decide to extend the MembershipProvider used by the .NET. In my case, thankfully I just need to override one method on that is ValidateUser. I will not talk the the detail what inside the methods is. The main point is just to validate if user login using existing password created by jomla can be validated by the .NET. To do that I create a simple class called JomlaEncryption to validate if user enter valid Jomla password.

encrypt with jomla algorithm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
public class JomlaEncryption
{
    public static bool IsValidPassword(string password, string encryptedPassword)
    {
        return EncryptUsingJomlaAlgorithm(password, encryptedPassword) == encryptedPassword;
    }

    /// <summary>
    /// Source : http://stackoverflow.com/questions/2727043/using-php-to-create-a-joomla-user-password
    ///   From joomla Forum, that's what happen behind:
    ///
    ///   1. Generate a password
    ///   2. Generate 32 random characters
    ///   3. Concatenate 1 and 2
    ///   4. md5(3)
    ///   5. store 4:2
    ///   Example:
    ///
    ///   1. Generate a password - we'll use 'password'
    ///   2. Generate 32 random characters - we'll use 'WnvTroeiBmd5bjGmmsVUnNjppadH7giK'
    ///   3. Concatenate 1 and 2 - passwordWnvTroeiBmd5bjGmmsVUnNjppadH7giK
    ///   4. md5(3) - 3c57ebfec712312f30c3fd1981979f58
    ///   5. store 4:2 - 3c57ebfec712312f30c3fd1981979f58:WnvTroeiBmd5bjGmmsVUnNjppadH7giK
    /// </summary>
    /// <param name="password">
    /// <returns></returns>
    static string EncryptUsingJomlaAlgorithm(string password, string encryptedPassword)
    {
        if (!encryptedPassword.Contains(":"))
            return null;

        string randChar32Bit = encryptedPassword.Split(':')[1];
        if (string.IsNullOrEmpty(randChar32Bit) || randChar32Bit.Length != 32)
            return null;

        string concatePassAndRandChar32Bit = password + randChar32Bit;
        string hashedConcatePassAndRandChar32Bit = MD5(concatePassAndRandChar32Bit);

        return string.Format("{0}:{1}", hashedConcatePassAndRandChar32Bit, randChar32Bit);
    }

    static string MD5(string password)
    {
        byte[] bytes = System.Text.Encoding.Default.GetBytes(password);
        try
        {
            System.Security.Cryptography.MD5CryptoServiceProvider cryptProvider;
            cryptProvider = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] hash = cryptProvider.ComputeHash(bytes);
            string ret = string.Empty;
            foreach (byte a in hash)
            {
                if (a < 16)
                    ret += "0" + a.ToString("x");
                else
                    ret += a.ToString("x");
            }
            return ret;
        }
        catch
        {
            throw;
        }
    }
}

That’s all for now and thanks for reading :)