Thursday, June 9, 2011

CustomForm for Singleton

import com.app.gui.Midlet;
import javax.microedition.lcdui.Form;

public abstract class CustomForm extends Form{

    protected CustomForm prevForm;
    protected CustomForm thisForm;

    public CustomForm() {
        super("App Name");
        thisForm = this;
    }

    abstract protected void initComponents();

    abstract protected void addComponents();

    public boolean setAsDisplay (CustomForm prevForm) {
        thisForm.prevForm = prevForm;
        return setAsDisplay();
    }
    public boolean setAsDisplay () {
        Midlet.getDisplay().setCurrent(this);
        return true;
    }

    protected String fillIfNull (String str) {
        return fillIfNull(str, " - ");
    }

    String fillIfNull (String str, String nullString) {
        if (str == null || str.equals("null")) {
                str = nullString;
        }
        return str;
    }

}

How to access web service using J2ME code


For calling web services j2me required stub files for it. Each and every web service class is called using its stub.

This document will show sample web service and will teach you how to create stub files

Sample web service URL

http://www.webservicex.net/stockquote.asmx


Generating the Stub Class

We need the Web Service Description Language (WSDL) description for the service. Luckily, .NET services supply this for you is you append "?WSDL" to the URL.
The Java ME SDK contains a tool called "wscompile", that reads the WSDL data and generates a "stub" Java class. This class acts as a local proxy for the remote service. You call a method in the stub class, and it calls the remote method for you.
To generate the stub class, we need a config.xml file.
<?xml version="1.0"?>
<configuration xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config">
 <wsdl location="http://www.webservicex.net/stockquote.asmx?WSDL" packageName="rpcdemo" />
</configuration>
The wsdl location must match the URL for the service (with "?WSDL" tacked on the end). The packageName is the package for the generated files.
\Java_ME_platform_SDK_3.0\bin\wscompile.exe -gen -cldc1.1 config.xml
You should specify -cldc1.1 if the web service might use floats or doubles as arguments or return value.
After executing this, you should have a file (amongst others) for the class: rpcdemo.StockQuoteSoap_Stub 





Midlet for calling Web service


import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;


public class RpcDemo extends MIDlet implements CommandListener, Runnable {


    private Form form;


    public void startApp() {
        if (form == null) {
            form = new Form("RpcDemo");
            form.addCommand(new Command("Exit", Command.EXIT, 0));
            form.setCommandListener(this);

            // get the data
            (new Thread(this)).start();
        }
        Display.getDisplay(this).setCurrent(form);
    }


    public void pauseApp() {
        // empty
    }


    public void destroyApp(boolean must) {
        // empty
    }

    public void commandAction(Command c, Displayable d) {
        if (c.getCommandType() == Command.EXIT) {
            notifyDestroyed();
        }
    }


    public void run() {
        try {
            // create the stub
            StockQuoteSoap_Stub service = new StockQuoteSoap_Stub();
            // set the URL for the service
            service._setProperty(javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY, "http://www.webservicex.net/stockquote.asmx");

            println("Connecting...");
            // invoke the remote method
            String xmlResponse = service.getQuote("NOK");
            println(xmlResponse);

            println("Done.");
        } catch (Exception e) {
            println(e.toString());
        }
    }


    private void println(String s) {
        form.append(s + "\n");
    }
}

 

DateUtility Class


package com.hinduja.util;

import java.util.Calendar;
import java.util.Date;
import javax.microedition.lcdui.DateField;


public class DateUtility {
    static Calendar calendar;
    static {
        calendar = Calendar.getInstance();
        calendar.setTime(new Date());
    }
    public static Calendar setDate(String date){
        return  calendar;
    }
    public static String getDate(){

        Date today = new Date(System.currentTimeMillis());
        DateField date = new DateField("", DateField.DATE_TIME);
        date.setDate(today);

        Calendar cal = Calendar.getInstance();
        cal.setTime(today);

        String dateStr = "" +  getTwoDigitStr(cal.get(Calendar.DATE)) + "." +
            getTwoDigitStr(cal.get(Calendar.MONTH)+1) + "." +
            cal.get(Calendar.YEAR) + " " +
            getTwoDigitStr(cal.get(Calendar.HOUR_OF_DAY)) + ":" +
            getTwoDigitStr(cal.get(Calendar.MINUTE)) + ":" +
            getTwoDigitStr(cal.get(Calendar.SECOND));

                return dateStr;
    }

    public static String convertDate(Date fromDate){

        Date today = fromDate;
        DateField date = new DateField("", DateField.DATE_TIME);
        date.setDate(today);

        Calendar cal = Calendar.getInstance();
        cal.setTime(today);

        String toDate = "" +  getTwoDigitStr(cal.get(Calendar.DATE)) + "." +
            getTwoDigitStr(cal.get(Calendar.MONTH)+1) + "." +
            cal.get(Calendar.YEAR) + " " +
            getTwoDigitStr(cal.get(Calendar.HOUR_OF_DAY)) + ":" +
            getTwoDigitStr(cal.get(Calendar.MINUTE)) + ":" +
            getTwoDigitStr(cal.get(Calendar.SECOND));

        return toDate;
    }

    public static String getTwoDigitStr (int number) {
        if (number < 10) {
            return ("0" + number);
        }
        else {
            return String.valueOf(number);
        }
    }

    public static int getDay() {
        return calendar.get(Calendar.DATE);
    }

    public static int getMonth() {
        return calendar.get(Calendar.MONTH)+1;
    }

    public static int getYear() {
        return calendar.get(Calendar.YEAR);
    }

    public static int compareDate (String dateStr) {

        Calendar readingCal = null;
        try {
            readingCal = parseDate(dateStr);
        }
        catch (Exception e) {
            return 12;
        }
        Calendar currCal = Calendar.getInstance();
        Date date = new Date(System.currentTimeMillis());
        currCal.setTime(date);

        int readingMonths = readingCal.get(Calendar.YEAR) * 12 + readingCal.get(Calendar.MONTH);
        int currMonths = currCal.get(Calendar.YEAR) * 12 + currCal.get(Calendar.MONTH);

        return currMonths - readingMonths;
    }


        public static boolean to_from_date_compare(String to_date,String from_date,String db_date)
        {
            int diff_year;
            int diff_month;

            int to_date_day = Integer.parseInt(to_date.substring(0,2));
            int from_date_day = Integer.parseInt(from_date.substring(0,2));
            int db_date_day = Integer.parseInt(db_date.substring(0,2));

            int to_date_month = Integer.parseInt(to_date.substring(3,5));
            int from_date_month = Integer.parseInt(from_date.substring(3,5));
            int db_date_month = Integer.parseInt(db_date.substring(3,5));

            int to_date_year = Integer.parseInt(to_date.substring(6,10));
            int from_date_year = Integer.parseInt(from_date.substring(6,10));
            int db_date_year = Integer.parseInt(db_date.substring(6,10));

            if((to_date_year <= db_date_year) && (db_date_year <= from_date_year))
            {
                if((to_date_month <= db_date_month) && (db_date_month <= from_date_month))
                {
                    if((to_date_day <= db_date_day) && (db_date_day <= from_date_day))
                    {
                        return true;
                    }
                    else
                    {
                        if(((db_date_day > from_date_day) && (db_date_month >= from_date_month) && (db_date_year >= from_date_year)) || ((db_date_day <= to_date_day) && (db_date_month <= to_date_month) && db_date_year <= to_date_year))
                        {
                            return false;
                        }
                        diff_month = from_date_month - to_date_month;
                        diff_year = from_date_year - to_date_year;
                        if(diff_month > 0 || diff_year > 0)
                            return true;
                    }
                    return false;
                }
                else
                {
                    if(((db_date_month >= from_date_month) && (db_date_year >= from_date_year)) || ((db_date_month <= to_date_month) && (db_date_year <= to_date_year)))
                    {
                          return false;
                    }
                    diff_year = from_date_year - to_date_year;
                    if(diff_year > 0)
                        return true;
                }
                return false;
            }
            return false;
        }


        public static boolean validateDate(String to_date,String from_date)
        {
             int to_date_day = Integer.parseInt(to_date.substring(0,2));
            int from_date_day = Integer.parseInt(from_date.substring(0,2));


            int to_date_month = Integer.parseInt(to_date.substring(3,5));
            int from_date_month = Integer.parseInt(from_date.substring(3,5));


            int to_date_year = Integer.parseInt(to_date.substring(6,10));
            int from_date_year = Integer.parseInt(from_date.substring(6,10));

            if(to_date_year < from_date_year)
            {
                return false;
            }
            else
            {
                if(to_date_month < from_date_month)
                {
                    return false;
                }
                else
                {
                    if(to_date_day < from_date_day)
                    return false;
                }
            }
            return true;
        }

    /*
    Accepted Format:
    01234567890123456789012
    "YYYY MM DD HH mm ss SSS"
    ex. 1960-07-31 00:00:00.0
    Assumptions:
    - there is at exactly 1 character (any character) between each field
    (which will be ignored during parsing)
    */


    public static Calendar parseDate(String dateString) {
        Date date = new Date(0);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);

        if (dateString == null || dateString.equals("")) {
            throw new IllegalArgumentException(
                    "Invalid String to Parse as Date - dateString was null or empty");
        }

        int strSize = dateString.length();

        if (strSize < 16) {
            throw new IllegalArgumentException(
                    "Invalid String to Parse as Date - dateString invalid string length ("+strSize+")");
        }

        String dayStr = dateString.substring(0,2);
        String monthStr = dateString.substring(3,5);
        String yearStr = dateString.substring(6,10);
        String hourStr = dateString.substring(11,13);
        String minuteStr = dateString.substring(14,16);
        String secondsStr = dateString.substring(17,19);

        int year = 0;
        int day = 0;
        int month = 0;
        int hour = 0;
        int minute = 0;
        int seconds = 0;

        try {
            year = Integer.parseInt(yearStr);
            day = Integer.parseInt(dayStr);
            month = Integer.parseInt(monthStr) - 1; //Zero Based Months
            hour = Integer.parseInt(hourStr);
            minute = Integer.parseInt(minuteStr);
            seconds = Integer.parseInt(secondsStr);
        }
        catch (Exception e) {}

        cal.set(Calendar.MONTH,month);
        cal.set(Calendar.DATE,day);
        cal.set(Calendar.YEAR,year);
        cal.set(Calendar.HOUR_OF_DAY,hour);
        cal.set(Calendar.MINUTE,minute);
        cal.set(Calendar.SECOND,seconds);
        return cal;
    }

    public static int compareTime (String dateStr1, String dateStr2) {

        long differance = timeDifferance(dateStr1, dateStr2);
        if (differance > 0) {
            return 1;
        }
        else if (differance < 0) {
            return -1;
        }
        else {
            return 0;
        }
    }

    public static long timeDifferance (String dateStr1, String dateStr2) {
        Calendar cal1 = parseDate(dateStr1);
        Calendar cal2 = parseDate(dateStr2);

        return cal1.getTime().getTime() - cal2.getTime().getTime();
    }

    public static long millsPassed (String dateStr) {
        Calendar cal = parseDate(dateStr);
        return System.currentTimeMillis() - cal.getTime().getTime();
    }

    public static void main(String[] args) {
        System.out.println("Long Data = "+System.currentTimeMillis());
        //long threeMonthMills = 24L*60L*60L*1000L;
        //long millsPassed = millsPassed("12.03.2010 08:10:00");
        //System.out.println("Mills passed: " + (millsPassed > threeMonthMills) + " : " +  threeMonthMills);
        //System.out.println(">> " + millsPassed/(60*60*1000));
/*        String dateStr = "2009-12-31 00:00:00.0";
        //System.out.println(">> " + compareDate("12.03.2010 08:21:45"));
        //System.out.println("## " + compareTime("12.03.2010 08:21:45", "12.03.2010 08:21:45"));
        //System.out.println("Current date: " + getDate());
*/    }
}

Sunday, May 1, 2011

Write Multiple Data in File

public void Saveinfile(Vector v){
       
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos= new DataOutputStream(baos);
       
        try {
        FileConnection fileConn =(FileConnection)Connector.open("file:///e:/bkp.txt", Connector.READ_WRITE);
        if(!fileConn.exists()){
        fileConn.create();}
        else{
        System.out.println("file already found");
        }
        dos = fileConn.openDataOutputStream();
       
        Enumeration enumResults = v.elements();
       
        while (enumResults.hasMoreElements()) {           
            dos.writeUTF("\n");
            dos.writeUTF(String.valueOf(enumResults.nextElement()));
         }   
       
       
        dos.close();
        fileConn.close();
        System.out.println("file saved");
        } catch (IOException ex) {
        ex.printStackTrace();
        }
        }

File Connection Read Write

private synchronized String readDataFromFile(String path) {
        String fileData = null;
      try {
         FileConnection fc = (FileConnection) Connector.open(path);
         if(!fc.exists()){
             fc.mkdir();
         }
         InputStream is = fc.openInputStream();
         byte b[] = new byte[1024];
         int length = is.read(b, 0, 1024);
         fileData = new String(b, 0, length);
         System.out.println("Content in File : "+ new String(b, 0, length));
         is.close();
         fc.close();

         }
      catch(Exception e){
         e.printStackTrace();
         }
      return fileData;
    }





public void WriteFile(String data){
       

                try {                   
                    FileConnection fconn = (FileConnection)Connector.open("file:///e:/Data.txt", Connector.READ_WRITE);                   

                    if(!fconn.exists())
                        fconn.create();

                    OutputStream os = fconn.openOutputStream(fconn.fileSize());
                    DataOutputStream dos = new DataOutputStream(os);
                    dos.write(data.getBytes("UTF8"));
                    dos.write("\n".getBytes("UTF8"));
                    //dos.writeUTF(meterReading);
                    dos.close();
                    os.close();
                    fconn.close();
                }
                catch (IOException ex) {
                        ex.printStackTrace();
               }
          
      }

Saturday, April 30, 2011

Setting JAVA_HOME in Ubuntu

I have read lots of user posting at various pages and none of them would work. Finally, I found a way to do this correctly and hope this will help to some of you.

Follow the simple steps:

1. To set the environment variables :
    echo ‘export JAVA_HOME=/opt/jdk1.5.0_12′ > /etc/profile.d/jdk.sh
    echo ‘export PATH=$JAVA_HOME/bin:$PATH’ >> /etc/profile.d/jdk.sh

2. You have to source the file you just created by typing:
    source /etc/profile.d/jdk.sh

3. Test if Java environment is successfully installed by typing in this in the shell:
    java -version

Thursday, April 14, 2011

Append String to file

 In may samples of file connection i found people facing problem when they are trying to append any string to file.

In normal case it is overwriting string to file.
use following function to solve that problem.


 public void WriteFile(String s){


        try {
                FileConnection fconn = (FileConnection)Connector.open("file:///e:/Test2.txt", Connector.READ_WRITE);

                if(!fconn.exists())
                    fconn.create();

                OutputStream os = fconn.openOutputStream(fconn.fileSize());
                DataOutputStream dos = new DataOutputStream(os);
                dos.writeUTF("Mihir");
                System.out.println("file saved");
                dos.close();
                os.close();
                fconn.close();
            }
        catch (IOException ex) {
                ex.printStackTrace();
            }
      }