Tuesday, June 14, 2011

Java Math Functions which are not available in J2ME

package com.huayu.gps;

public class Deg {

    public static final int SEC = 500;
    public static final int MIN = 60 * SEC;
    public static final int DEG = 60 * MIN;

    public static final int FORMAT_AUTO = -1;
    public static final int FORMAT_D = 0;
    public static final int FORMAT_DM = 1;
    public static final int FORMAT_DMS = 2;
    public static final int FORMAT_NMEA = 3;
    public static final int FORMAT_FIXED = 4;

    public static final int PRECISION_D = 6;
    public static final int PRECISION_M = 4;
    public static final int PRECISION_S = 2;

    // fixed decimal point = 1
    public static final int iFIXED = 1000; // Integer.MAX_VALUE;
    //public static final long FIXED = Long.MAX_VALUE;

    private static int format = FORMAT_D;

    protected int deg;

    public Deg() { this.deg = 0; }
    public Deg( int deg ) { this.deg = limitDeg( deg ); }
    public Deg( long deg ) { this.deg = limitDeg( deg ); }
    public Deg( Deg deg ) { this.deg = deg.deg; }

    public void set( int deg ) { this.deg = limitDeg( deg ); }
    public void set( long deg ) { this.deg = limitDeg( deg ); }
    public void set( Deg deg ) { this.deg = deg.deg; }

    public int get() { return deg; }
    public String toString() {
        return "";    // TODO
    }

    public static void setFormat( int f ) { format = f; }
    public static int getFormat() { return format; }

    public static int min( int a, int b ) {
        return ( a < b ) ? a : b;
    }

    public static int max( int a, int b ) {
        return ( a > b ) ? a : b;
    }

    public static int abs( int x ) {
        return ( x < 0 ) ? -x : x;
    }

    public static int limitDeg( int deg ) {
        while( deg >= 360 * DEG ) deg -= 360 * DEG;
        while( deg < 0 ) deg += 360 * DEG;
        return deg;
    }

    public static int limitDeg( long deg ) {
        while( deg >= 360 * DEG ) deg -= 360 * DEG;
        while( deg < 0 ) deg += 360 * DEG;
        return (int) deg;
    }

    public static int limitDeg( double deg ) {
        while( deg >= 360 * DEG ) deg -= 360 * DEG;
        while( deg < 0 ) deg += 360 * DEG;
        return (int) deg;
    }

    public static String degToStr( int value, int f, int n, int precision, String signPlus, String signMinus ) {
        StringBuffer tmpsb = new StringBuffer();
        if( ( ( f < 0 ) ? format : f ) != FORMAT_FIXED ) {
            tmpsb.append( ( value < 0 ) ? signMinus : signPlus );
            value = ( value < 0 ) ? -value : value;
        }
        switch( ( f < 0 ) ? format : f ) {
            case FORMAT_FIXED :
            case FORMAT_D :
                tmpsb.append( VlkText.fixToStr( value, DEG, n, ( precision < 0) ? PRECISION_D : precision ) );
                break;
            case FORMAT_DM :
                tmpsb.append( VlkText.intToStr( value / DEG, n ) );
                tmpsb.append( "°" );
                tmpsb.append( VlkText.fixToStr( value % DEG, MIN, 2, ( precision < 0) ? PRECISION_M : precision ) );
                break;
            case FORMAT_DMS :
                tmpsb.append( VlkText.intToStr( value / DEG, n ) );
                tmpsb.append( "°" );
                tmpsb.append( VlkText.intToStr( ( value % DEG ) / MIN, 2 ) );
                tmpsb.append( "'" );
                tmpsb.append( VlkText.fixToStr( value % MIN, SEC, 2, ( precision < 0) ? PRECISION_S : precision ) );
                break;
        }
        return tmpsb.toString();
    }

    public static int strToDeg( String value ) {
        int idp = value.indexOf( '.' );
        int idk = value.indexOf( ',' );              
        int igr = value.indexOf( "°" );
        int imn = value.indexOf( "'" );
        if( imn > igr ) {
            // FORMAT_DMS // DDD°MM'SS.ss // TODO rewrite to int
            int tmpi = Integer.parseInt( value.substring( 0, igr ) ) * DEG;
            tmpi += Integer.parseInt( value.substring( igr + 1, imn ) ) * MIN;
            tmpi += (int) ( Double.parseDouble( value.substring( imn + 1 ) ) * SEC );
            return tmpi;
        }
        if( igr > 0 ) {
            // FORMAT_DM // DDD°MM.mmmm // TODO rewrite to int
            int tmpi = Integer.parseInt( value.substring( 0, igr ) ) * DEG;
            tmpi += (int) ( Double.parseDouble( value.substring( igr + 1 ) ) * MIN );
            return tmpi;
        }
        if( ( idp == 4 ) || ( idp == 5 ) ) {
            // FORMAT_NMEA // DDDMM.mmmm
            int tmpi = Integer.parseInt( value.substring( 0, idp - 2 ) ) * DEG;
            tmpi += (int) ( Double.parseDouble( value.substring( idp - 2 ) ) * MIN );
//            tmpi += Integer.parseInt( value.substring( idp - 2, idp ) ) * MIN;
//            tmpi += Integer.parseInt( value.substring( idp + 1 ) ) * ( MIN / 10000 );
            return tmpi;
        }
        if( ( idp >= 0 ) && ( idp <= 3 ) ) {
            // FORMAT_D // DDD.dddddd
            double tmpd = Double.parseDouble( value );
            return degToInt( tmpd );
        }
        if( ( idk >= 0 ) && ( idk <= 3 ) ) {
            // FORMAT_D // DDD,dddddd
            double tmpd = Double.parseDouble( value.replace(',','.') );
            return degToInt( tmpd );
        }
        // FORMAT_ERROR
        return 0; // make exception!
    }

    public static int degToInt( double deg ) {
        return( (int) ( deg * DEG ) );
    }

    public static double sqr( double x ) {
        return ( x * x );
    }

    public static int asin( double x ) {
        return (int)( (double)DEG * Math.toDegrees( Float11.asin( x ) ) );
    }

//    public static int asin( long x ) {
//        return (int)( (double)DEG * Math.toDegrees( Float11.asin( ( (double)x ) / FIXED ) ) );
//    }

    public static int acos( double x ) {
        return (int)( (double)DEG * Math.toDegrees( Float11.acos( x ) ) );
    }

//    public static int acos( long x ) {
//        return (int)( (double)DEG * Math.toDegrees( Float11.acos( ( (double)x ) / FIXED ) ) );
//    }

    public static int atan( double x ) {
        return (int)( (double)DEG * Math.toDegrees( Float11.atan( x ) ) );
    }

    public static int atan2( double y, double x ) {
        return (int)( (double)DEG * Math.toDegrees( Float11.atan2( y, x ) ) );
    }

    public static double sin( int x ) {
        return Math.sin( Math.toRadians( ( (double) x ) / DEG ) );
    }

    public static double cos( int x ) {
        return Math.cos( Math.toRadians( ( (double) x ) / DEG ) );
    }

    private static int[] tabSin = new int[ 720 ];
    private static boolean mathTablesCreated = false;

    public static int fastSin( int x ) {
        return( tabSin[ limitDeg( x ) / ( DEG / 2 ) ] );
    }

    public static int fastCos( int x ) {
        x += 90 * DEG;
        return( tabSin[ limitDeg( x ) / ( DEG / 2 ) ] );
    }

    public static void initFastMath() {
        if( ! mathTablesCreated ) {
            //Debug.debug( "Generating fast math tables" );
            for( int i = 0; i < 720; i++ ) {
                tabSin[ i ] = ( int ) ( iFIXED * Math.sin( Math.toRadians( i / 2 ) ) );
            }
            mathTablesCreated = true;
        }
    }

    public static void mathBench() {
        //Debug.debug( "Math speed test:" );
        int j = 0;
        long drawTime = System.currentTimeMillis();
        for( int i = 0; i < 1000; i++, j += MIN ) {
            sin( j );
        }
        //Debug.debug( "sin(): " + (int)( System.currentTimeMillis() - drawTime ) + "us" );
        j = 0;
        drawTime = System.currentTimeMillis();
        for( int i = 0; i < 1000; i++, j += MIN ) {
            cos( j );
        }
        //Debug.debug( "cos(): " + (int)( System.currentTimeMillis() - drawTime ) + "us" );
        j = 0;
        drawTime = System.currentTimeMillis();
        for( int i = 0; i < 1000; i++, j += MIN ) {
            asin( j );
        }
        //Debug.debug( "asin(): " + (int)( System.currentTimeMillis() - drawTime ) + "us" );
        j = 0;
        drawTime = System.currentTimeMillis();
        for( int i = 0; i < 1000; i++, j += MIN ) {
            acos( j );
        }
        //Debug.debug( "acos(): " + (int)( System.currentTimeMillis() - drawTime ) + "us" );
        j = 0;
        drawTime = System.currentTimeMillis();
        for( int i = 0; i < 1000; i++, j += MIN ) {
            fastSin( j );
        }
        //Debug.debug( "fastSin(): " + (int)( System.currentTimeMillis() - drawTime ) + "us" );
        j = 0;
        drawTime = System.currentTimeMillis();
        for( int i = 0; i < 1000; i++, j += MIN ) {
            fastCos( j );
        }
        //Debug.debug( "fastCos(): " + (int)( System.currentTimeMillis() - drawTime ) + "us" );
        Coords wpt1 = new Coords( 10 * DEG, 30 * DEG, 0 );
        Coords wpt2 = new Coords( 20 * DEG, 70 * DEG, 0 );
        drawTime = System.currentTimeMillis();
        for( int i = 0; i < 1000; i++ ) {
            j = wpt1.zenith( wpt2 );
        }
        //Debug.debug( "zenith(): " + (int)( System.currentTimeMillis() - drawTime ) + "us" );
        drawTime = System.currentTimeMillis();
        int k = j;
        for( int i = 0; i < 1000; i++ ) {
            j = wpt1.azimuth( wpt2, k );
        }
        //Debug.debug( "azimuth(): " + (int)( System.currentTimeMillis() - drawTime ) + "us" );
    }

}

Thursday, June 9, 2011

Compressor Decompressor Class


import java.io.IOException;
import java.io.ByteArrayOutputStream;

public class Compressor {
   
    /* Tailored to int as 32bit signed */
    private final static int FIRST_QUARTER = 0x200000;
    private final static int THIRD_QUARTER = 0x600000;
    private final static int HALF          = 0x400000;
    private final static int HIGH          = 0x7fffff;
    private final static int INITIAL_READ  = 23;
   
    public static byte[] compress(byte[] in) {
       
        class BitOutputBuffer {
            ByteArrayOutputStream buf;
            byte[] currentByte;
            byte currentBit;
            BitOutputBuffer() {
                buf = new ByteArrayOutputStream();
                currentByte = new byte[1];
                currentByte[0] = 0;
                currentBit = 0;
            }
            void writeBit(byte bit) throws IOException {
                currentByte[0] = (byte) ((currentByte[0]) << 1);
                currentByte[0] += bit;
                currentBit+=1;
                if (currentBit==8) {
                    buf.write(currentByte);
                    currentByte[0] = 0;
                    currentBit = 0;
                }
            }
            void flush() throws IOException {
                /* Pad the buffer with zeros */
                while (currentBit!=0) {
                    writeBit((byte) 0);
                }
                buf.flush();
            }
           
            byte[] toByteArray() {
                try {
                    buf.flush();
                    return buf.toByteArray();
                }
                catch (IOException e) {
                    return null;
                }
            }
           
        }
       
        BitOutputBuffer bitBuf = new BitOutputBuffer();
       
        int low = 0, high = HIGH, total;
        int mLow = low, mHigh = high, mStep = 0;
        int mScale = 0;
        int current = 0;
       
        /* Initialize frequency table */
        int[] freq = new int[257];
        for (int i=0; i<257; i++) freq[i] = 1;
        total = 257;
       
        try {
           
            for (int i=0; i<in.length + 1; i++) {
               
                if (i == in.length) {
                    /* Encode terminator if necessary */
                    low = total - 1;
                    high = total;
                }
                else {
                    /* Otherwise retrieve cumulative freq */
                    current = in[i] & 0xff; // Get unsigned value
                    low = 0;
                    for (int j=0; j<current; j++) {
                        low += freq[j];
                    }
                    high = low + freq[current];
                }
               
                /* 2. Update the coder */
                mStep = ( mHigh - mLow + 1 ) / total;
                mHigh = (mLow + mStep * high) - 1;
                mLow = mLow + mStep * low;
               
                /* Renormalize if possible */
                while( (mHigh < HALF) || (mLow >= HALF) )
                {
                    if( mHigh < HALF )
                    {
                        bitBuf.writeBit((byte) 0);
                        mLow = mLow * 2;
                        mHigh = mHigh * 2 + 1;
                       
                        /* Perform e3 mappings */
                        for(; mScale > 0; mScale-- )
                            bitBuf.writeBit((byte) 1);
                    }
                    else if( mLow >= HALF )
                    {
                        bitBuf.writeBit((byte) 1);
                        mLow = ( mLow - HALF ) * 2;
                        mHigh = ( mHigh - HALF ) * 2 + 1;
                       
                        /* Perform e3 mappings */
                        for(; mScale > 0; mScale-- )
                            bitBuf.writeBit((byte) 0);
                    }
                }
               
                while((FIRST_QUARTER <= mLow) && (mHigh < THIRD_QUARTER)) {
                    mScale++;
                    mLow = ( mLow - FIRST_QUARTER ) * 2;
                    mHigh = ( mHigh - FIRST_QUARTER ) * 2 + 1;
                }       
               
                /* 3. Update model */
                freq[current]+=1;
                total+=1;
               
            }
            /* Finish encoding */
            if( mLow < FIRST_QUARTER ) {
                /* Case: mLow < FirstQuarter < Half <= mHigh */
                bitBuf.writeBit((byte) 0);
                /* Perform e3-scaling */
                for( int i=0; i<mScale+1; i++ )
                    bitBuf.writeBit((byte) 1);
            } else {
                /* Case: mLow < Half < ThirdQuarter <= mHigh */
                bitBuf.writeBit((byte) 1 );
            }
            bitBuf.flush();
        }
        catch (IOException e) {
            return null;
        }
        return bitBuf.toByteArray();
    }
   
    public static byte[] decompress(byte[] in) {
       
        class BitInputBuffer {
            byte[] source;
            int bytep = 0, bitp = 0;
            byte currentByte = 0;
            BitInputBuffer(byte [] source) {
                this.source = source;
                currentByte = source[0];// & 0xff;
            }
            int readBit() {
                int result = (currentByte >> 7) & 1;
                currentByte = (byte) (currentByte << 1);
                if (bitp++==7) {
                    bytep++;
                    if (bytep > source.length - 1) {
                        currentByte = 0;
                    }
                    else {
                        currentByte = source[bytep];
                        bitp = 0;
                    }
                }
                return result;
            }
        }
       
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        /* Initialise frequency table */
       
        int[] freq = new int[257];
        for (int i=0; i<257; i++) freq[i] = 1;
        int total = 257;
        int current = 0;
        int value;
        int low = 0, high = HIGH;
        int mLow = low, mHigh = high, mStep = 0, mScale = 0, mBuffer = 0;
        BitInputBuffer inbuf = new BitInputBuffer(in);
        /*    Fill buffer with bits from the input stream */

        for( int i=0; i<INITIAL_READ; i++ ) {
            mBuffer = 2 * mBuffer;
            mBuffer += inbuf.readBit();
        }
           
        while(true) {
            /* 1. Retrieve current byte */
            mStep = ( mHigh - mLow + 1 ) / total;
            value = ( mBuffer - mLow ) / mStep;
            low = 0;
            for (current=0; current<256 && low + freq[current] <= value; current++)
                low += freq[current];
           
            if (current==256) break;
           
            buf.write(current);
            high = low + freq[current];
           
            /* 2. Update the decoder */
            mHigh = mLow + mStep * high - 1; // interval open at the top => -1
           
            /* Update lower bound */
            mLow = mLow + mStep * low;
           
            /* e1/e2 mapping */
            while( ( mHigh < HALF ) || ( mLow >= HALF ) )
            {
                if( mHigh < HALF )
                {
                    mLow = mLow * 2;
                    mHigh = ((mHigh * 2) + 1);
                    mBuffer = (2 * mBuffer);
                }
                else if( mLow >= HALF )
                {
                    mLow = 2 * ( mLow - HALF );
                    mHigh = 2 * ( mHigh - HALF ) + 1;
                    mBuffer = 2 * ( mBuffer - HALF );
                }
   
                mBuffer += inbuf.readBit();
                mScale = 0;
            }
           
            /* e3 mapping */
            while( ( FIRST_QUARTER <= mLow ) && ( mHigh < THIRD_QUARTER ) )
            {
                mScale++;
                mLow = 2 * ( mLow - FIRST_QUARTER );
                mHigh = 2 * ( mHigh - FIRST_QUARTER ) + 1;
                mBuffer = 2 * ( mBuffer - FIRST_QUARTER ) ;
                mBuffer += inbuf.readBit();
            }
           
            /* 3. Update frequency table */
            freq[current]+=1;
            total+=1;
        }
       
        return buf.toByteArray();
    }
}

Push Registry (Calling one application from other)

Code for Midlet 1 which will call Midlet2

import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.*;

/**
 * @author root
 */
public class pushmid extends MIDlet {
    public void startApp() {

        Form f = new Form("Hii");
        Display d = Display.getDisplay(this);

        try {
            f.append("PushApp");
            d.setCurrent(f);
            Connector.open("socket://127.0.0.1:7777");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
       
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }
}





.Jad file attributes for Midlet 2

MIDlet-1: newApp, , newApp
MIDlet-Jar-Size: 1066
MIDlet-Jar-URL: PushSample2.jar
MIDlet-Name: PushSample2
MIDlet-Push-1: socket://:7777,newApp,*
MIDlet-Vendor: Vendor
MIDlet-Version: 1.0
MicroEdition-Configuration: CLDC-1.1
MicroEdition-Profile: MIDP-2.0





and code in Midlet 2

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.*;

/**
 * @author root
 */
public class newApp extends MIDlet {
    Form f = new Form("Hii");
    Display d = Display.getDisplay(this);
    public void startApp() {
        f.append("newApp");
        d.setCurrent(f);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }
}


This way Midlet 2 will be invoke when starting Midlet 1

XML Parsing With SAXParser


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


public class LocalDataObject {

    private int noOfFields;
    private Vector recordValues = null;
    private int tblCode = 0;
    private String tblName;
    private static SAXParserFactory factory = null;
    private SAXParser saxParser = null;

    public LocalDataObject(int tblCode) {
        this.tblCode = tblCode;
        tblName = ConstantCodes.TBL_NAMES[tblCode];
        this.noOfFields = ConstantCodes.FLD_NAMES[this.tblCode].length;
        recordValues = new Vector();
        recordValues.setSize(noOfFields);

    }

    public LocalDataObject(int tblCode, String socId) {
        this(tblCode);
        if (tblCode == ConstantCodes.TBL_CUSTOMERDETAILS_CODE) {
            tblName = ConstantCodes.TBL_NAMES[ConstantCodes.TBL_CUSTOMERDETAILS_CODE];
        }
        tblName += socId;
    }

    public void setValue(int fieldIndex, String value) {
        if (fieldIndex < noOfFields) {
            recordValues.setElementAt(value, fieldIndex);
        }
    }

    public String getValue(int fieldValue) {
        return (String) recordValues.elementAt(fieldValue);
    }

    public boolean loadDataFromID(int rmsID) {
        RMSStore tempStore = new RMSStore();
        tempStore.openRecordStore(tblName);

        boolean dataLoaded = false;

        try {
            String xmlString = new String(tempStore.getRecordByteFromId(rmsID));
            if (xmlString != null) {
                dataLoaded = setValuesFromXML(xmlString);
            } else {
                dataLoaded = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            dataLoaded = false;
        } finally {
            tempStore.closeRecordStore();
        }
        return dataLoaded;
    }

    static {
        try {
            factory = SAXParserFactory.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean setValuesFromXML(String xml) {
        InputStream is = null;
        try {
            XMLHandler handler = new XMLHandler();
            handler.setParameters(noOfFields, recordValues);
            is = new ByteArrayInputStream(xml.getBytes());
            InputSource inputSource = new InputSource(is);
            saxParser = factory.newSAXParser();
            saxParser.parse(inputSource, handler);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String toString() {
        StringBuffer buffer = new StringBuffer();

        buffer.append("<ROW>");
        for (int i = 0; i < noOfFields; i++) {

            buffer.append("<");
            buffer.append(ConstantCodes.FLD_NAMES[tblCode][i]);
            buffer.append(">");

            buffer.append(getValue(i));

            buffer.append("</");
            buffer.append(ConstantCodes.FLD_NAMES[tblCode][i]);
            buffer.append(">");
        }
        buffer.append("</ROW>");

        return buffer.toString();
    }

    public static Vector getXMLRecords(String xml) {
        String record = null;
        String rec = "</ROW>";
        Vector vRec = new Vector();
        int index = 0;
        while (true) {
            index = xml.indexOf(rec);
            if (index == -1) {
                break;
            }
            record = xml.substring(0, index + rec.length());
            vRec.addElement(record);
            xml = xml.substring(record.length());
        }
        record = null;

        return vRec;
    }


    static class XMLHandler extends DefaultHandler {

        Vector xmlRecord = null;
        int count = 0;
        int noOfFields;

        private void setParameters(int noOfFields, Vector recordValues) {
            this.noOfFields = noOfFields;
            this.xmlRecord = recordValues;
        }

        public void startDocument() throws SAXException {

            xmlRecord.removeAllElements();
            xmlRecord.setSize(noOfFields);
        }

        public void startElement(String uri, String localName, String qName,
                Attributes attributes) throws SAXException {
        }

        public void characters(char[] ch, int start, int length)
                throws SAXException {

            xmlRecord.setElementAt(new String(ch, start, length).trim(), count);
            count += 1;
        }

        public void endElement(String uri, String localName, String qName)
                throws SAXException {
        }

        public void endDocument() throws SAXException {
        }
    }
}

RMS Management


import java.util.Enumeration;
import java.util.Vector;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreFullException;
import javax.microedition.rms.RecordStoreNotOpenException;


public class RMSStore {

    private RecordStore rs = null;

    public void openRecordStore(String str) {
        try {
            if (rs == null) {
                rs = RecordStore.openRecordStore(str, true);
                //Modified by Mihir
                //rs = RecordStore.openRecordStore(str, true,RecordStore.AUTHMODE_ANY,true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void closeRecordStore() {
        try {
            if (rs != null) {
                rs.closeRecordStore();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void deleteRecordStore(String storenName) {
        try {
            RecordStore.deleteRecordStore(storenName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String[] listAllRecordStore() {
        return RecordStore.listRecordStores();
    }

    public int writeRecord(String str) {
        int id = 0;
        try {
            id = rs.addRecord(str.getBytes(), 0, str.getBytes().length);
        } catch (RecordStoreFullException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return id;
    }

    public int writeByteRecord(byte[] data) {
        int id = -1;

        try {
            id = rs.addRecord(data, 0, data.length);
        } catch (RecordStoreFullException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return id;
    }

    public int getRecordCount() {
        try {
            return rs.getNumRecords();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public byte[] getRecordDataFromId(int id) {
        byte[] data = null;
        try {
            data = rs.getRecord(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    public String getRecordFromId(int id) {
        return new String(getRecordDataFromId(id));
    }

    public byte[] getRecordByteFromId(int id) {
        return getRecordDataFromId(id);
    }

    public void deleteRecord(int id) {
        try {
            rs.deleteRecord(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean checkRecordExists(String compare) {
        for (int i = 0; i < getRecordCount(); i++) {
            if (compare.equals(getRecordFromId(i + 1))) {
                return true;
            }
        }
        return false;
    }

    public int getMaxRMSSize() {
        int size = 0;
        try {
            size = rs.getSizeAvailable() + rs.getSize();
        } catch (RecordStoreNotOpenException e) {
            e.printStackTrace();
        }

        return size;
    }

    public void setRecordById(String str, int id) {
        try {
            rs.setRecord(id, str.getBytes(), 0, str.getBytes().length);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int getNextRecordId() {
        int id = 0;
        try {
            id = rs.getNextRecordID();
        } catch (RecordStoreException re) {
            re.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return id;
    }

    public RecordEnumeration getRecordEnumData() {
        try {
            return rs.enumerateRecords(null, null, false);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public String[] getRecordData() {

        String[] str = null;
        int counter = 0;
        try {
            RecordEnumeration enumeration = rs.enumerateRecords(null, null, false);
            str = new String[rs.getNumRecords()];

            while (enumeration.hasNextElement()) {
                try {
                    str[counter] = (new String(enumeration.nextRecord()));
                    counter++;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

}

Sample Form Singleton


import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextField;


public class RFIDVerificationForm extends CustomForm {

    private TextField txtRFIDNo = null;
    private Command cmdVerify = null;
    private Command cmdBack = null;

    private static RFIDVerificationForm thisForm;
    private static RFIDVerificationFormListener listener;

    public RFIDVerificationForm() {
        super();
        thisForm = this;
        initComponents();
        addComponents();
    }

    protected void initComponents() {

        txtRFIDNo = new TextField("Enter RFID No", "", 20, TextField.ANY);
        cmdVerify = new Command("OK", Command.ITEM, 1);
        cmdBack = new Command("Back", Command.BACK, 1);

    }

    protected void addComponents() {

        append(txtRFIDNo);
        addCommand(cmdVerify);
        addCommand(cmdBack);
        setCommandListener(getListener());
    }

    private RFIDVerificationFormListener getListener() {
        if (listener == null) {
                listener = new RFIDVerificationFormListener();
        }
        return listener;
    }

    public static RFIDVerificationForm getInstance() {

        if (thisForm == null) {
                thisForm = new RFIDVerificationForm();
        }
        thisForm.txtRFIDNo.setString("");
        return thisForm;
    }

    private class RFIDVerificationFormListener implements CommandListener {
        public void commandAction(Command cmd, Displayable displayable) {

            if (cmd.getLabel().equals("Back")) {
                thisForm.prevForm.setAsDisplay();
            }
            else if (cmd.getLabel().equals("OK")) {                   
               
           }
        }
    }
}

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());
*/    }
}