Saturday, October 15, 2011

Adding 3G model support to Kyros 7024 tablet

Now it is very much easy and safe to enable 3G on kyros 7024. What you need to do is get the latest official kyros firmware update for kyros 7024 and modify a configuration file.

• You can download kyros firmware upgrade by this link,
o http://www.cobyusa.com/files/software/MID7024-Firmware.zip
• Extract the downloaded MID7024-Firmware.zip file
o Then you need to modify the file "init.smdkv210.rc" which is inside "board.7024.tgz"
• Open "board.7024.tgz" with 7zip tool (http://www.7-zip.org/download.html). And drag and drop the "init.smdkv210.rc" to the desktop and modify
• What to modify?
o Open "init.smdkv210.rc" file with notepad and add true instead of false for following properties,
o Setprop au.ui.enable_3g, setprop au.ui.enable_apn.
• Then update your drag and drop changed file into the 7zip and it will update your original file reside in "board.7024.tgz"
• After that upgrade your firmware according to the step on
o http://www.cobyusa.com/files/software/MID7024-Firmware-Update-Instructions.pdf
• Then connect your 3G modem to the kyros and go to the Settings --> Advanced Settings --> Ubs Bus mode --> select Usb host mode. This should light up your modems LED.
• Then go to the Settings --> Wireless Networks --> 3G NW settings --> New 3G NW.
• Make sure system list down your modem. Most of the Huwawei and Zte modems are available.
• Create the connection with default settings and connect to it. Now you can browse internet. :P

Note:
My Modem is Huwawei E220 and it worked perfectly.

Saturday, July 31, 2010

Creating Message Driven Bean with NetBeans/GlassFish

This is an example for Simple message driven bean with GlassFish server and NetBeans. We can use message driven bean to asynchronously process messages. Although you can use session bean to synchronously process messages but it is bit expensive to block message processing with synchronization since it is eating server resources. Following are the summery of steps for this example.

· Creating web application with NetBeans

· Creative required JMS connection factory and queue in the GlassFish server.

· Creating Servlet (MessageProducerServlet) to put messages into the JMS queue.

· Creating message driven bean (SimpleMessageBean) to process messages from JMS queue

The architecture of the example

With the MessageProducerServlet we are producing messages and put them into the JMS queue. The SimpleMessageBean is listing to the JMS queue and ones the message arrived the onMassage() on SimpleMessageBean is invoked.

Creating web application with NetBeans

Open NetBeans IDE and File à New Project à Java Web à Web Application

Creative required JMS connection factory and queue in the GlassFish server.

Open the browser for url http://localhost:4848/ and you will directed to the GlassFish administrator UI. First we need to create JMS ConnectionFactory in the server. Go to resources à JMS resources à Connection Factories à New, give name as jms/MyConnectionFactory and select resource type as ‘javax.jms.ConnectionFactory’.

Then we need to create JMS queue and go to resources à JMS resources à Destination Resources à New, give name as jms/MyQueue and select resource type as ‘javax.jms.Queue’ and Destination name as ‘PhysicalQueue’.

We need to create the ConnectionFactory and queue on the GlassFish server. Since server to server default ConnectionFactory and queue is changing I am not using the defaults.

Creating Servlet (MessageProducerServlet) to put messages into the JMS queue.

I choose servlet to put messages into the JMS queue because it is very easy when reffering ConnectionFactory and Queue. We are referring ConnectionFactory and Queue with resource annotation (dependency injection) so we need to run this on the GlassFish server. If we are using outside GlassFish server we should do JNDI lookup.

To create Servlet for the project right click the project and create Servlet and add following code into it. When creating the servlet remember to add servlet information to the web.xml.



package org.sun.exam.message.producer;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MessageProducerServlet extends HttpServlet {
@Resource(mappedName = "jms/MyConnectionFactory")
private ConnectionFactory connectionFactory;
@Resource(mappedName = "jms/MyQueue")
private Queue queue;

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
sendMessages();
} catch (Exception ex) {
Logger.getLogger(MessageProducerServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}

private int NUM_MSGS = 3;

public void sendMessages() throws Exception {
Connection connection = connectionFactory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(queue);
TextMessage message = session.createTextMessage();

for (int i = 0; i < NUM_MSGS; i++) {
message.setText("This is message " + (i + 1));
System.out.println("Sending message: " + message.getText());
messageProducer.send(message);
}
}



Creating message driven bean (SimpleMessageBean) to process messages from JMS queue

Our message driven bean does not directly communicate with Servlet, it is using JMS queue to listen to messages. To create message driven bean for the project right click the project and create new message driven bean and add following code into it.


package org.sun.exam.message.bean;

import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

@MessageDriven(mappedName = "jms/MyQueue", activationConfig = {
@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class SimpleMessageBean implements MessageListener {

@Resource
private MessageDrivenContext mdc;

public SimpleMessageBean() {
}

public void onMessage(Message inMessage) {
TextMessage msg = null;
try {
if (inMessage instanceof TextMessage) {
msg = (TextMessage) inMessage;
System.out.println("MESSAGE BEAN: Message received: " + msg.getText());
//logger.info("MESSAGE BEAN: Message received: " + msg.getText());
} else {
System.out.println("Message of wrong type: " + inMessage.getClass().getName());
//logger.warning("Message of wrong type: " + inMessage.getClass().getName());
}
} catch (JMSException e) {
e.printStackTrace();
mdc.setRollbackOnly();
} catch (Throwable te) {
te.printStackTrace();
}
}
}

In this example with the message driven bean we have used asynchronous message consumption. When is comes to JMS there are two types of consumers,
  • Synchronously: A subscriber or a receiver explicitly fetches the message from the destination by calling the receive method. The receive method can block until a message arrives or can time out if a message does not arrive within a specified time limit.

  • Asynchronously: A client can register a message listener with a consumer. A message listener is similar to an event listener. Whenever a message arrives at the destination, the JMS provider delivers the message by calling the listener’s onMessage method, which acts on the contents of the message


  • Note:

    This example based on Java EE6 tutorial and in the reference you can find the link.

    Reference:

    http://download-llnw.oracle.com/javaee/6/tutorial/doc/bnbpk.html

    EJB 3 - Tutorial

    Enterprise Java bean is a server-side component that encapsulates the business logic of an application. EJB can be be used when you need a scalability, data/transaction integrity and if you need to add thin clients for your application.
    EJB container provides system-level services to enterprise beans, the bean developer can concentrate on solving business problems. The EJB container, rather than the bean developer, is responsible for system-level services such as transaction management and security authorization.

    There are two types of EJBs in EJB3
    • Session Bean : Performs a task for a client; optionally may implement a web service
    • Message-Driven Bean : Acts as a listener for a particular messaging type, such as the Java Message Service API
    There three types of Session beans as well,


    • Stateful Session Beans : The instance variables of this kind of bean represent the state of a unique client-bean session. A session bean is not shared; it can have only one client,

    • Stateless Session Beans : When a client invokes the methods of a stateless bean, the bean’s instance variables may contain a state specific to that client, but only for the duration of the invocation. Can be shared across multiple clients.

    • Singleton Session Beans : A singleton session bean is instantiated once per application, and exists for the life cycle of the application
    A message-driven bean is an enterprise bean that allows Java EE applications to process messages asynchronously. It normally acts as a JMS message listener. Messages can be sent by any Java EE component or by a JMS application or system that does not use Java EE technology. Message-driven beans can process JMS messages or other kinds of messages. The most visible difference between message-driven beans and session beans is that clients do not access message-driven beans through interfaces.

    Creating a stateless Enterprise Bean with NetBeans

    We can create and deploy simple EJB with NetBeans and deploy it on glassfish server.


    • First create web application with NetBeans (File --> New Project --> Java Web --> Web Application).

    • Right click the project and add a Session Bean to it (New --> Session bean). This is a slateless session bean and you can add following code into it.
      package com.sun.tutorial.javaee.ejb;
      
      import java.math.BigDecimal;
      import javax.ejb.Stateless;
      
      @Stateless
      public class ConverterBean {
      
      private BigDecimal yenRate = new BigDecimal("115.3100");
      private BigDecimal euroRate = new BigDecimal("0.0071");
      
      public BigDecimal dollarToYen(BigDecimal dollars) {
        BigDecimal result = dollars.multiply(yenRate);
        return result.setScale(2, BigDecimal.ROUND_UP);
      }
      
      public BigDecimal yenToEuro(BigDecimal yen) {
        BigDecimal result = yen.multiply(euroRate);
        return result.setScale(2, BigDecimal.ROUND_UP);
      }
      
      }

    • Add a Servelt to the project (New --> Servlet).We use this servlet to call our EJB and to display result in the web browser. Add following code into the servlet.
      package converter.web;
      
      import com.sun.tutorial.javaee.ejb.ConverterBean;
      import java.io.IOException;
      import java.io.PrintWriter;
      import java.math.BigDecimal;
      import javax.ejb.EJB;
      import javax.servlet.ServletException;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      
      public class ConverterServlet extends HttpServlet {
      
       @EJB
       ConverterBean converterBean ;
      
       public void doGet(HttpServletRequest request, HttpServletResponse response)
               throws ServletException, IOException {
      
           BigDecimal euroAmount = performOperation(request);
      
           response.setContentType("text/html");
           PrintWriter pw = response.getWriter();
           pw.println(euroAmount);
       }
      
       public BigDecimal performOperation(HttpServletRequest request) {
           try {
               String amount = request.getParameter("amount");
               if (amount != null && amount.length() > 0) {
                   BigDecimal d = new BigDecimal(amount);
                   BigDecimal yenAmount = converterBean.dollarToYen(d);
      
                   // call the ConverterBean.yenToEuro() method to get the amount in Euros
                   BigDecimal euroAmount = converterBean.yenToEuro(yenAmount);
                   return euroAmount;
               }
           } catch (Exception e){
               System.out.println(e.getMessage());
           }
           return new BigDecimal(0);
       }
      }
      
      Here we are referring ConverterBean with @EJB annotation and it uses dependency injection to obtain a reference to ConverterBean .

    • Change the index.jsp to add text box and set form action to the Servlet. Modify Index.jsp as follows.
        <body>
            <form id="form1" action="ConverterServlet">
                < div >
                    <input id="amount" name="amount" type="text" />
                    <input id="Submit1" type="submit" value="submit"/>
                </div>
            </form>
        </body>
    • Changing the web.xml to route appropriate request to servlet. Add following content to web.xml inside web-app tag.

      <servlet>
     <servlet-name>ConverterServlet</servlet-name>
     <servlet-class>
     SimpleServlet
     </servlet-class>
     </servlet>
     <servlet-mapping>
     <servlet-name>ConverterServlet</servlet-name>
     <url-pattern>/converterServlet</url-pattern>
     </servlet-mapping>
    

    • Running the application: Run the application and go to the url 
    http://localhost:8080/<proj_name>/converterServlet

    References:

    Sunday, July 18, 2010

    The builder pattern

    Definition
    Separate the construction of a complex object from its representation so that the same construction process can create different representations.

    The Class diagram





    The implementation

    The computer builder is an abstract class (builder). The client use this abstract class to build the product.

    public abstract class ComputerBuilder
    {
    protected Computer computer;
    public Computer Computer
    {
    get { return computer; }
    }

    public abstract void BuildDisplay();
    public abstract void BuildMotherBoard();
    public abstract void BuildKeybord();
    public abstract void BuildHardDisk();
    public abstract void BuildPowerUnit();
    }

    The LaptopBuilder and DesktopBuilder are concrete builders and they create the real product parts and store them in the part composite structure.

    public class LaptopBuilder : ComputerBuilder
    {
    public LaptopBuilder()
    {
    computer = new Computer("Laptop Computer");
    }

    public override void BuildDisplay()
    {
    computer["display"] = "LCD integrated Display";
    }

    public override void BuildMotherBoard()
    {
    computer["mother_board"] = "Motherbord with centrino processor";
    }

    public override void BuildKeybord()
    {
    computer["keybord"] = "Integrated Keybord";
    }

    public override void BuildHardDisk()
    {
    computer["hard_disk"] = "Integrated Hard Disk";
    }

    public override void BuildPowerUnit()
    {
    computer["power_unit"] = "Integrated power unit";
    }
    }



    public class DesktopBuilder : ComputerBuilder
    {
    public DesktopBuilder()
    {
    computer = new Computer("Desktop Computer");
    }
    public override void BuildDisplay()
    {
    computer["display"] = "LCD separated Display";
    }

    public override void BuildMotherBoard()
    {
    computer["mother_board"] = "Motherbord with processor";
    }

    public override void BuildKeybord()
    {
    computer["keybord"] = "Separate Keybord";
    }

    public override void BuildHardDisk()
    {
    computer["hard_disk"] = "Hard Disk";
    }

    public override void BuildPowerUnit()
    {
    computer["power_unit"] = "Power unit";
    }
    }
    This is the product and concrete builder responsible for building this by building parts.

    public class Computer
    {
    private string _computerType;
    private Dictionary _parts = new Dictionary();
    public string this[string key]
    {
    get { return _parts[key]; }
    set { _parts[key] = value; }
    }
    public Computer(string computerType)
    {
    _computerType = computerType;
    }

    public void Show()
    {
    Console.WriteLine("\n---------------------------");
    Console.WriteLine("Computer Type: {0}", _computerType);
    Console.WriteLine(" Display : {0}", _parts["display"]);
    Console.WriteLine(" Motherbord : {0}", _parts["mother_board"]);
    Console.WriteLine(" Keybord: {0}", _parts["keybord"]);
    Console.WriteLine(" Hard Disk : {0}", _parts["hard_disk"]);
    Console.WriteLine(" Power unit : {0}", _parts["power_unit"]);
    }
    }

    The Shop (Director) construct the object using the builder interface.


    public class Shop
    {
    public void Construct(ComputerBuilder computerBuilder)
    {
    computerBuilder.BuildDisplay();
    computerBuilder.BuildHardDisk();
    computerBuilder.BuildKeybord();
    computerBuilder.BuildMotherBoard();
    computerBuilder.BuildPowerUnit();
    }
    }



    class Program
    {
    static void Main(string[] args)
    {
    ComputerBuilder computerBuilder;
    Shop shop = new Shop();
    computerBuilder = new LaptopBuilder();
    shop.Construct(computerBuilder);
    computerBuilder.Computer.Show();
    Console.ReadLine();
    }
    }


    The pattern can apply:
    • If the algorithm of creating complex objects should separate parts making how they are assembled.
    • If you need control over the construction

    Saturday, July 17, 2010

    Singleton pattern with with C# code example

    Definition
    The singleton patterns ensures a class has only one instance, and provide a global point of access it.

    More information
    To assure there is one and only one instance, first we can disable the object creation by making constructor private. Then secondly we can mark instance variable/method to static to ensure only one instance and to provide access point.

    The Instance() method is the method that return the singleton instance. We can mark this method as lock (syncronized) to make thread safe. But lock (syncronized) is not good for performance. So what are the other available options,
    • No worry about the Instance method if the performance is not important :P
    This is obvious, if the performance is not a critical factor then you can use syncronization.
    • Do the instance creation as eagerly created rather than a lazy created one
    Static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain.
    • Use double check locking to reduce the use of syncronized Instance method
    C# you can easily do this but in Java you need to do this with Volatile keyword. Also you need Java 1.5 or higher version. Please see the reference for more details.


    Implementation

    This implementation is a non lazy implementation of the singleton pattern. This is a thread safe version.

    internal class Singleton
    {
    private static Singleton _instance = new Singleton();

    private string _property = "Singleton Property";

    private Singleton()
    {
    }

    public string Property
    {
    get { return _property; }
    set { _property = value; }
    }

    public static Singleton Instance
    {
    get { return _instance; }
    set { _instance = value; }
    }
    }

    This implementation is a lazy implementation of the singleton pattern. This is not a thread safe version.



    internal class SingletonLazy
    {
    private static SingletonLazy _instance;
    private string _property = "Singleton Property";

    private SingletonLazy()
    {
    }

    public string Property
    {
    get { return _property; }
    set { _property = value; }
    }

    public static SingletonLazy Instance()
    {
    if (_instance == null)
    {
    _instance = new SingletonLazy();
    }
    return _instance;
    }
    }

    This is the Main program to work with above classes.


    internal class Program
    {
    private static void Main(string[] args)
    {
    // The non lazy initialization
    Singleton nonLazySingleton1 = Singleton.Instance;
    Singleton nonLazySingleton2 = Singleton.Instance;
    nonLazySingleton1.Property = "The new Property";

    if (nonLazySingleton1.Property.Equals(nonLazySingleton2.Property))
    {
    Console.WriteLine("The non lazy singleton is successful");
    }

    // The lazy initialization
    SingletonLazy singletonLazy1 = SingletonLazy.Instance();
    SingletonLazy singletonLazy2 = SingletonLazy.Instance();
    singletonLazy2.Property = "The new Property";

    if (singletonLazy1.Property.Equals(singletonLazy2.Property))
    {
    Console.WriteLine("The lazy singleton is successful");
    }
    }
    }


    Reference:
    http://www.yoda.arachsys.com/csharp/singleton.html