Updates from October, 2010 Toggle Comment Threads | Keyboard Shortcuts

  • Subinkrishna Gopi 11:11 am on October 28, 2010 Permalink |
    Tags: , , , guide, how-to, , simple, tutorial   

    Today’s read: Get Started Developing for Android with Eclipse 

    This one is pretty good. Perhaps one of the very useful how-tos! I read this article in smashingmagazine.com a few days back. I was thinking of sharing it from that moment. It’s better late than never. The article talks a lot of things. From about installing the Android SDK, configuring it and even about writing a sample application.

    There’s a lot to get excited about in mobile application development today. With increasingly sophisticated hardware, tablet PCs and a variety of software platforms (Symbian OS, iOS, WebOS, Windows Phone 7…), the landscape for mobile developers is full of opportunities — and a little complex as well.

    So much choice can be overwhelming when you just want to get started building mobile applications. Which platform should you choose? What programming language should you learn? What kit do you need for your planned project? In this tutorial, you’ll learn how to start writing applications for Android, the open-source mobile operating system popularized by Google.

    Source: Smashing Magazine

    Read the article | http://developer.android.com

     
  • Subinkrishna Gopi 5:56 pm on October 18, 2010 Permalink |
    Tags: , DBMS, , ejb3, entity, hibernate, , ORM, query, , session   

    How-to: Write a named query for an entity bean with composite key 

    I was working on an EJB3 project where I had to write an entity bean with a composite primary key. And I needed to write a named query to which had to use a sub set of the composite key. And this is what I did.

    The entity bean and the composite key:

    import javax.persistence.Column;
    import javax.persistence.EmbeddedId;
    import javax.persistence.Entity;
    import javax.persistence.NamedQueries;
    import javax.persistence.NamedQuery;
    import javax.persistence.Table;
    
    @Entity
    @Table (name = "myTable")
    public class MyEntityBean implements Serializable
    {
        @EmbeddedId
        private MyCompositeKey key;
    
        // Other instance members
    
        @Column (name = "value")
        private String value;
    
        // Getters & setters
        ...
    }
    
    import java.io.Serializable;
    import javax.persistence.Column;
    import javax.persistence.Embeddable;
    
    @Embeddable
    public class MyCompositeKey implements Serializable
    {
        @Column (name = "key1", nullable = false)
        private String key1;
    
        @Column (name = "key2", nullable = false)
        private String key2;
    
        // Getters & setters
        ....
    }
    

    The equivalent database table will look like:

    +---------------+--------------+------+-----+---------+-------+
    | Field         | Type         | Null | Key | Default | Extra |
    +---------------+--------------+------+-----+---------+-------+
    | key1          | varchar(255) | NO   | PRI |         |       |
    | key2          | varchar(255) | NO   | PRI |         |       |
    | value         | varchar(255) | YES  |     |         |       |
    +---------------+--------------+------+-----+---------+-------+
    

    Writing a named query which makes use of the elements of the composite key is a li’l tricky. Take a look at the following SQL statement which tries to fetch all the records from the table for a matching key1.

    SELECT * FROM myTable WHERE key1='some value';
    

    Embedding the named query in MyEntityBean.

    @Entity
    @Table (name = "myTable")
    @NamedQueries
    ({
        @NamedQuery(
            name = "myQuery",
            query = "SELECT FROM MyEntityBean b WHERE key.key1 = :key1" )
    })
    public class MyEntityBean implements Serializable
    {
        ...
    }
    

    We should be careful about the use of the variable name in the named query. In the named query, we are supposed to use the name of the composite key exactly the same as what we have specified in the bean.

    This query can be accessed from a session bean with the help of EntityManager.

    import javax.ejb.Remote;
    import javax.ejb.Stateless;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import javax.persistence.Query;
    
    @Remote
    @Stateless (name = "MySessionBean")
    public class MySessionBeanImpl implements SessionBean
    {
        @PersistenceContext
        private EntityManager entityManager;
    
        public void myMethod(String key)
        {
        	Query aQuery = null;
    
        	aQuery = this.entityManager.createNamedQuery("myQuery");
            aQuery.setParameter("key1", key);
    
            List resultList = aQuery.getResultList();
    
            .....
        }
    }
    

    Hope this helps. Have a good day 🙂

     
  • Subinkrishna Gopi 3:28 pm on March 25, 2010 Permalink |
    Tags: authentication, base 64, encoding, , , security,   

    Handling HTTP authentication in Java 

    Google Chrome (Ubuntu 9.10)

    Microsoft IE 8 (Windows XP)

    Most of us might have got this pop up when we browse through some websites – especially in intranets. And it’s perfectly fine for the administrator (a.k.a. webmaster) to put such restrictions on users to enhance the information security. Because that’s what a security engineer is expected to do !

    But what if we have to access the resource through our Java code? How to we handle that? I have faced this issue when I was writing a module to crawl through a secured website using HTTPunit.

    We just need to set the Authorization header with the Base64 encoded username and password. Here is a sample code:

    String usernameAndPassword = "myUsername" + ":" + "myPa$$word";
    String encodedString = new sun.misc.BASE64Encoder().encode (usernameAndPassword.getBytes());
    httpConnection.setRequestProperty("Authorization", "Basic " + encodedString);
    

    How Base 64 encoding works?

     
  • Subinkrishna Gopi 2:57 pm on March 20, 2010 Permalink |
    Tags: , , serialization   

    Today’s read: How Java serialization works ! 

    Have you ever wondered what is happening behind the scenes of Java serialization ? If your answer is YES, this one is for you. This is a really good one. I will recommend all to read this.

    Read the article: http://www.javaworld.com/community/node/2915

    If you are interested in more details, you can read Sun’s Java object serialization specification. You can get the specification from here: http://java.sun.com/j2se/1.4/pdf/serial-spec.pdf

     
  • Subinkrishna Gopi 3:12 pm on February 19, 2010 Permalink |
    Tags: , executor, , , , thread pool, threadpoolexecutor   

    ThreadPoolExecutor – basics 

    ThreadPoolExecutor is an implementation of the ExecutorService, which can be used to execute the submitted tasks using the available Thread pool. Read the Sun Java API docs for more information.

    The buzz words

    1. Core & max pool size
    This is the size of the core (minimam) and maximum possible thread that need to be in the thread pool every time. We can even specify the keep-alive time limit for the threads.

    2. Work queue
    Work queue is a BlockingQueue, which is used to hold the work/task which is being sent to the executor when all the threads in the pool are busy executing the tasks. Read more about the BlockingQueue in Sun Java API docs.

    3. RejectedExecutionHandler
    So we have a limited number of threads in the pool to execute the tasks and a fixed sized work queue to hold the additional tasks. But what if the work queue overflows! RejectedExecutionHandler can help us in such situations. Read the Sun Java API docs for more.

    Some sample code

    Initializing the ThreadPoolExecutor and sending the task. Here we’ve defined a worksQueue with size 2, core & max pool size is 3 and the threads will expire after 10 seconds. We are also starting a daemon thread to monitor the executor status.

    BlockingQueue<Runnable> worksQueue = new ArrayBlockingQueue<Runnable>(2);
    RejectedExecutionHandler executionHandler = new MyRejectedExecutionHandelerImpl();
    
    // Create the ThreadPoolExecutor
    ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 3, 10,
            TimeUnit.SECONDS, worksQueue, executionHandler);
    executor.allowCoreThreadTimeOut(true);
    
    // Starting the monitor thread as a daemon
    Thread monitor = new Thread(new MyMonitorThread(executor));
    monitor.setDaemon(true);
    monitor.start();
    
    // Adding the tasks
    executor.execute(new MyWork("1"));
    executor.execute(new MyWork("2"));
    executor.execute(new MyWork("3"));
    executor.execute(new MyWork("4"));
    executor.execute(new MyWork("5"));
    executor.execute(new MyWork("6"));
    executor.execute(new MyWork("7"));
    executor.execute(new MyWork("8"));
    
    try
    {
        Thread.sleep(30000);
        executor.execute(new MyWork("9"));
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    

    RejectedExecutionHandler implementation.

    /**
     * The custom {@link RejectedExecutionHandler} to handle the rejected
     * tasks / {@link Runnable}
     */
    public class MyRejectedExecutionHandelerImpl
    implements RejectedExecutionHandler
    {
        @Override
        public void rejectedExecution(Runnable runnable,
                ThreadPoolExecutor executor)
        {
            System.out.println(runnable.toString() + " : I've been rejected ! ");
        }
    }
    

    My task (implements Runnable).

    /**
     * My {@link Runnable} class. Represents a task which need to be executed.
     */
    public class MyWork implements Runnable
    {
        String name;
    
        public MyWork(String name)
        {
            this.name = name;
        }
    
        @Override
        public void run()
        {
            System.out.println(this.name + " : I'm running ! ");
    
            try
            {
                Thread.sleep(5000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
    
            System.out.println(this.name + " : I'm done ! ");
        }
    
        @Override
        public String toString()
        {
            return (this.name);
        }
    }
    

    And the monitor thread.

    /**
     * My monitor thread. To monitor the status of {@link ThreadPoolExecutor}
     * and its status.
     */
    public class MyMonitorThread implements Runnable
    {
        ThreadPoolExecutor executor;
    
        public MyMonitorThread(ThreadPoolExecutor executor)
        {
            this.executor = executor;
        }
    
        @Override
        public void run()
        {
            try
            {
                do
                {
                    System.out.println(
                        String.format("[monitor] [%d/%d] Active: %d, Completed: %d, Task: %d, isShutdown: %s, isTerminated: %s",
                            this.executor.getPoolSize(),
                            this.executor.getCorePoolSize(),
                            this.executor.getActiveCount(),
                            this.executor.getCompletedTaskCount(),
                            this.executor.getTaskCount(),
                            this.executor.isShutdown(),
                            this.executor.isTerminated()));
                    Thread.sleep(3000);
                }
                while (true);
            }
            catch (Exception e)
            {
            }
        }
    }
    

    So we have all necessary code blocks in place. If we execute the above code we may get something like this.

    1 : I'm running !
    2 : I'm running !
    3 : I'm running !
    6 : I've been rejected !
    7 : I've been rejected !
    8 : I've been rejected !
    [monitor] [0/3] Active: 1, Completed: 0, Task: 1, isShutdown: false, isTerminated: false
    [monitor] [3/3] Active: 3, Completed: 0, Task: 5, isShutdown: false, isTerminated: false
    1 : I'm done !
    4 : I'm running !
    2 : I'm done !
    5 : I'm running !
    3 : I'm done !
    [monitor] [3/3] Active: 2, Completed: 3, Task: 5, isShutdown: false, isTerminated: false
    [monitor] [3/3] Active: 2, Completed: 3, Task: 5, isShutdown: false, isTerminated: false
    4 : I'm done !
    5 : I'm done !
    [monitor] [3/3] Active: 0, Completed: 5, Task: 5, isShutdown: false, isTerminated: false
    [monitor] [2/3] Active: 0, Completed: 5, Task: 5, isShutdown: false, isTerminated: false
    [monitor] [2/3] Active: 0, Completed: 5, Task: 5, isShutdown: false, isTerminated: false
    [monitor] [0/3] Active: 0, Completed: 5, Task: 5, isShutdown: false, isTerminated: false
    [monitor] [0/3] Active: 0, Completed: 5, Task: 5, isShutdown: false, isTerminated: false
    [monitor] [0/3] Active: 0, Completed: 5, Task: 5, isShutdown: false, isTerminated: false
    9 : I'm running !
    [monitor] [1/3] Active: 1, Completed: 5, Task: 6, isShutdown: false, isTerminated: false
    [monitor] [1/3] Active: 1, Completed: 5, Task: 6, isShutdown: false, isTerminated: false
    9 : I'm done !
    [monitor] [1/3] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
    [monitor] [1/3] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
    [monitor] [1/3] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
    

     
    • nguyenhuuquan 9:28 pm on April 29, 2013 Permalink

      thanks, it’s helpful. I have a question: if a task take a long time to execute, how to terminate it?

c
Compose new post
j
Next post/Next comment
k
Previous post/Previous comment
r
Reply
e
Edit
o
Show/Hide comments
t
Go to top
l
Go to login
h
Show/Hide help
shift + esc
Cancel