Worldwide Smartphone Sales (Based on internet resources)

Worldwide Smartphone Sales to End Users in 2008/2009 (Thousands of Units)

                                                                            

Company                                Sales      Market Share(%)          Sales         Market Share (%)

Nokia                                14,991.2                    41.2           14,588.6                         45.1

Research In Motion              7,233.6                    19.9            4,311.8                         13.3

Apple                                  3,938.8                   10.8             1,725.3                          5.3

HTC                                     1,957.3                   5.4              1,276.9                         4.0

Fujitsu                                 1,387.0                   3.8              1,317.5                          4.1

Others                                 6,896.4                  18.8              9,094.8                        28.1

TOTAL                               36,404.4               100.0           32,314.9                    100.0

Zoom images when you go to zoom button-JavaScript

 

<script language="JavaScript1.2">
var zoomfactor=0.05 //Enter factor (0.05=5%)
function zoomhelper()
{
if (parseInt(whatcache.style.width)>10&&parseInt(whatcache.style.height)>10&&parseInt(whatcache.style.width)<555)
{
whatcache.style.width=parseInt(whatcache.style.width)+parseInt(whatcache.style.width)*zoomfactor*prefix
whatcache.style.height=parseInt(whatcache.style.height)+parseInt(whatcache.style.height)*zoomfactor*prefix
}
}

function zoom(originalW, originalH, what, state)
{

if (!document.all&&!document.getElementById)
return
whatcache=eval("document.images."+what)
prefix=(state=="in")? 1 : -1

if (whatcache.style.width==""||state=="restore")
{
whatcache.style.width=originalW+"px"
whatcache.style.height=originalH+"px"

if (state=="restore")
return
}

else
{
zoomhelper()
}
beginzoom=setInterval("zoomhelper()",10)
}

function clearzoom()
{
if (window.beginzoom)
clearInterval(beginzoom)
}
</script>

 

CHANGE 500 to your image width, 375to image height, and "img.jpg" to your image's name

<a href="#" onmouseover="zoom(500,375,'myimage','in')" onmouseout="clearzoom()">Zoom In</a> | <a href="#" onmouseover="zoom(99,100,'myimage','restore')">Normal</a> | <a href="#" onmouseover="zoom(120,60,'myimage','out')" onmouseout="clearzoom()">Zoom Out</a>
<div style="position:relative;width:99;height:100"><div style="position:absolute">
<img name="myimage" src="img.jpg">

This code taken from web and works fine for me.so i put it here

How to use Record Management Store in BlackBerry-Add new records delete them and retrieve data when need

 

The RMS is a persistent storage API in Java® ME.I found code in blackberry site and develop to store the name of record and value that need to store

This class creates object that holds data values

package rms;
import java.io.*;
public final class datastor
{
    private String name;
    private String value;
    private String fullData;
    private static final short NameD = 0;
    private static final short valueD = 1;

    public datastor(byte[] data) throws java.io.IOException
    {
        fromByteArray(data);
    }   
    datastor(String name1, String value1)
    {
        name = name1;
        value = value1;
        fullData = name + ": " + value;
    }   
    public String toString()
    {
        return fullData;
    }   
    String getName()
    {
        return name;
    }   
    String getvalue()
    {
        return value;
    }   
    byte[] toByteArray() throws java.io.IOException
    {
        byte[] data;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        dos.writeShort(NameD);
        dos.writeUTF(name);
        dos.writeShort(valueD);
        dos.writeUTF(value);
        data = baos.toByteArray();   
        return data;
    }   

    private void fromByteArray(byte[] array) throws java.io.IOException
    {
        ByteArrayInputStream bais = new ByteArrayInputStream(array);
        DataInputStream dis = new DataInputStream(bais);
        short tag;          
        try
        { 
            while(true)
            {
                tag = dis.readShort();
                if (tag == NameD)
                {
                    name = dis.readUTF();
                }
                else if (tag == valueD)
                {
                    value = dis.readUTF();
                }
                else
                {
                    dis.readUTF();
                }
            }    
        }
        catch(EOFException e)
        {
            fullData = name + ": " + value;
        }
    }
}

This class use to perform the actions such as create delete data records in rms and also use to create datastore objecs

package rms;
import java.io.*;
import javax.microedition.rms.*;

public final class dataStorAcc
{
    RecordStore _rs;

    public dataStorAcc(String name) throws RecordStoreException, java.io.IOException
    {
        _rs = RecordStore.openRecordStore(name, true, RecordStore.AUTHMODE_ANY, false);
    }   

    public dataStorAcc(String recordStoreName, String vendorName, String suiteName) throws RecordStoreException, java.io.IOException
    {
        _rs = RecordStore.openRecordStore( recordStoreName, vendorName, suiteName );
    }    

    public synchronized int add(String name, String value) throws java.io.IOException, RecordStoreNotOpenException, RecordStoreException
    {
        datastor cd = new datastor(name, value);
        //Creates object
        byte[] data = cd.toByteArray();     
        //converts to byte
        return _rs.addRecord(data, 0, data.length);
        //add to record store
    }

    public synchronized void edit(int index, String artist, String title) throws java.io.IOException, RecordStoreNotOpenException, RecordStoreException
    {
        datastor cd = new datastor(artist, title);
        byte[] data = cd.toByteArray();       
        _rs.setRecord(index, data, 0, data.length);
    }

    public datastor getDataobj(int recordID) throws RecordStoreNotOpenException, InvalidRecordIDException, RecordStoreException, java.io.IOException
    {
        byte[] data = _rs.getRecord(recordID);
        return new datastor(data);
    }    

    public synchronized void delete(int recordId) throws RecordStoreNotOpenException, InvalidRecordIDException, RecordStoreException
    {
        _rs.deleteRecord(recordId);
    }

    RecordEnumeration enumerate() throws RecordStoreNotOpenException
    {
        return _rs.enumerateRecords(null, null, true);
    }
}

This is how we can use this within our application

01)Declare DataStorAcc object

dataStorAcc _db;      // RMS reference
RecordEnumeration _enum;

_db = new dataStorAcc("My Music");//Creates new Datastore named My Music
_enum = _db.enumerate(); //Creates enumerator

02)Add new record to rms

_db.add(“name”,”value”);

03)Delete from rms

_db.delete(tecordID);

04)Retrive data

recordId = _enum.nextRecordId();
String data=getDataobj(recordId).toString();

Display progressing bar in BlackBerry/Run and stop thread from 2 different classes/Use of volatile threads

 

 

package com.ironone.thread;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.GaugeField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.DialogFieldManager;
import net.rim.device.api.ui.container.PopupScreen;

public class service implements Runnable
{
    private volatile Thread service;
    private int maximum, timeout;
    private boolean useful;
    private PopupScreen popup;
    private GaugeField gaugeField;
    public service(int maximum, int timeout,String title)
    {
            this.maximum = maximum;
            this.timeout = timeout;
            DialogFieldManager manager = new DialogFieldManager();
            popup = new PopupScreen(manager);
            gaugeField = new GaugeField(null, 1, maximum, 1, GaugeField.NO_TEXT);
            manager.addCustomField(new LabelField(title));
            manager.addCustomField(gaugeField);       
            service = new Thread(this);
            service.start();
    }
    public void run()
    {
        Thread thisThread = Thread.currentThread();
        while ( service == thisThread )
        {            useful = true;
            UiApplication.getUiApplication().invokeLater(new Runnable()
            {
                public void run()
                {
                    UiApplication.getUiApplication().pushScreen(popup);
                }
            });
            int iterations = 0;
            while (useful)
            {
                try
                {
                    Thread.sleep(timeout);
                }
                catch (Exception e)
                {
                }
                if (++iterations > maximum)
                {
                    useful =false;
                    iterations = 1;
                }
                gaugeField.setValue(iterations);
            }

            if (popup.isDisplayed())
            {
                UiApplication.getUiApplication().invokeLater(new Runnable()
                {
                    public void run()
                    {
                        UiApplication.getUiApplication().popScreen(popup);
                    }
                });
            }
        }
    }

    public synchronized void serviceResume()
    {
        service = new Thread(this);
        service.start();
    }
    public synchronized void serviceSuspend()
    {
        service = null;
    }

}

Create class to use thread

package com.ironone.thread;
import com.ironone.thread.service;

public class dta
{
    public boolean temp=true;
    public service eeeeee=null;//new service(10,10,"Display name");
    public void dta()
    {
        eeeeee=new service(50,50,"Sending");
    }
    public void sss()
    {
        this.eeeeee.serviceSuspend();
    }
}

 

Create a global variable of dta in main class

public static dta ss=new dta();

refer that variable from anywhere and start run

Main.ss.dta();

stop it from some other location or class

Main.ss.sss();

Post method in java

public String postObject(String url,String object)
       {

          String resultsPage="";
         try{
              String urlStr=url;
              String val=object;
              URL postURL = new URL( urlStr );
              HttpURLConnection con = (HttpURLConnection) postURL.openConnection();
              con.setUseCaches(false);      
              con.setDoOutput(true);        
              con.setDoInput(true);         
              con.setRequestMethod("POST");  
              PrintWriter out = new PrintWriter(con.getOutputStream());
              String postStr = "link="+URLEncoder.encode(val);
              out.println(postStr); 
              out.close();
              String inputLine="";
        BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream()));
              while ((inputLine = in.readLine()) != null)
                   resultsPage+=inputLine;
              in.close();
              System.out.println(resultsPage); //Final output
          }
         catch(Exception ex)
          {
             System.out.println(ex);
          }

      return resultsPage;
       }

Get properties of Image programmatically / Make bitmap image from file located in any location -BlackBerry Development

Create Bitmap image as follows then

Bitmap _bitmap;
_bitmap=getBitmap("file:///SDCard/image.jpg");
int h=_bitmap.getHeight();
int w=_bitmap.getWidth();
Dialog.alert("height"+Integer.toString(h)+"width"+Integer.toString(w));

getBitmap image will be like this

public Bitmap getBitmap(String filepath)
{
    Bitmap bkBitmap = null;
    try {
             FileConnection fconn = (FileConnection)Connector.open(filepath );
             InputStream input = null;
             input = fconn.openInputStream();     
             int available = 0;
             available = input.available();
             int fSz = (int)fconn.fileSize();
             byte[] data = new byte[fSz];            
             input.read(data, 0, fSz);
             EncodedImage image = EncodedImage.createEncodedImage(data,0,data.length);
             bkBitmap = image.getBitmap();               
        }
    catch(Exception e)
        {
        }
    return bkBitmap;
}

“Some of the projects in the active BlackBerry configuration contain errors. Project MobileRDM contains errors (Please check the Problems view). “ or “running the rapc utility error” Errors in eclipse Blackberry development when try to add jar file

There few ways to fix this problem here i have mentioned the method that works for me

01)Select project folder and make sure that is not read only.if it is read only remove

      the read only property

02)In the eclipse project explorer window select project then go to >build path

    >Configure Build path > Then go to > libraries and add the necessary jar files

    from add jars then order and export menu select the added jar file then press ok

Then problem will be ok

Cannot find jar error2 when building BlackBerry Application in eclipse

 

We can see sometimes above error in console

Go to my computer->properties –>Advanced System properties

->Environmental variables->System variables

find path then add “;your java bin path”

Then problem will not occur again.this works for me

Create folder in BlackBerry device memory or Memory card-(How to avoid “FileIOException: File system error”)

Creates Folder inside the BlackBerry device programmatically

try
    {
FileConnection fc=(FileConnection)Connector.open

("file:///store/home/user/themes/",Connector.READ_WRITE);

//Give your path as need above path for device memory

//for Memory Card give as file:///SDCard/Themes/

//Do not forget to “/” at the end of name
           if (!fc.exists())
            {
             fc.mkdir();
             Dialog.alert("Created Folder");
            }
    }
    catch(Exception e)
    {
        Dialog.alert("ERROR");
    }

Download image or any file from URL to specific file path-BlackBerry Development

Give url and downloaad location very simple

public boolean downloadImage(String url,String path)
{
    if(saveImage(getImage(url),path))
    {
    return true;
    }
    else
    {
        return false;
    }
}
public static String getImage(String url)
{
String response = "";
try {
HttpConnection conn = (HttpConnection)Connector.open(url, Connector.READ_WRITE);
InputStream input =conn.openInputStream();
byte[] data = new byte[256];
int len = 0;
StringBuffer raw = new StringBuffer();
while( -1 != (len = input.read(data)))
{
raw.append(new String(data, 0, len));
}
response = raw.toString();
input.close();
} catch(Exception e)
{
Dialog.alert("Error");
}
return response;
}
public boolean saveImage(String txt,String path1)
    {
        boolean str = false;
        try {
            FileConnection fc1 = (FileConnection)Connector.open(path1, Connector.READ_WRITE);
            if(!fc1.exists())
            {
            fc1.create();
            }
            fc1.setWritable(true);
                byte[] size1=txt.getBytes();
                OutputStream os=fc1.openOutputStream();
                os.write(size1);
                os.close();
                return true;        
        }
        catch (Exception ioe)
        {
            System.out.println("File Sys Error"+ioe.getMessage());
        }
        return str;
    }

Copy File From one location to another-BlackBerry

This will copy the file located in “path” to “path1“.Replaces with existing file

public boolean CopyFile(String path,String path1)
    {
        boolean str = false;
        try {
            FileConnection fc = (FileConnection)Connector.open(path, Connector.READ);
            FileConnection fc1 = (FileConnection)Connector.open(path1, Connector.READ_WRITE);
            if(!fc1.exists())
            {
            fc1.create();
            }
            fc1.setWritable(true);
            if(!fc.exists())
            {
                System.out.println("Source File doesn't exist!");
            }

            else
            {
                int size = (int)fc.fileSize();
                InputStream is = fc.openInputStream();
                OutputStream os=fc1.openOutputStream();
                byte bytes[] = new byte[size];
                is.read(bytes, 0, size);
                os.write(bytes);
                os.close();
                is.close();
                return true;
            }
        }
        catch (Exception ioe)
        {
            System.out.println("File Sys Error"+ioe.getMessage());
        }
        return str;
    }

ksoap-Accessing web service with BlackBerry

Check weather given username and password are correct by connecting to remote server.returns true or false according to server response

Add ksoap jar module to your project

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransport;
import org.xmlpull.v1.XmlPullParserException;

public boolean createSoap(String username,String password)
{
    boolean ans=false;
    SoapObject request = new SoapObject("http://tempuri.org/","isValidUser");
     request.addProperty("Username",username);
     request.addProperty("Password",password);
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.bodyOut = request;
    envelope.dotNet = true;
    HttpTransport ht = new HttpTransport("http://164.49.254.143:8080/Service.asmx");
    ht.debug = true;
    try {
        ht.call("http://tempuri.org/isValidUser", envelope);     
        if((envelope.getResponse().toString()).equals("true"))
        {
            return true;   
        }
    }
    catch (XmlPullParserException ex)
    {
        Dialog.alert("ex1 "+ex.toString() );
        ex.printStackTrace();
    } catch (IOException ex) {
        Dialog.alert("ex2 " +ex.toString());
        ex.printStackTrace();
    } catch (Exception ex) {
        Dialog.alert("ex3 " + ex.toString());
    }
    return false;
}

Get Bitmap image from file located in SD Card-BlackBerry

In many GUI design purposes we need to get bitmap images from existing files in memory card.This method returns bitmap image of the given file name file must be located in path “file:///SDCard/Themes/

public Bitmap getBitmap(String fileName)
    {
        Bitmap bkBitmap = null;
        try {
                 FileConnection fconn = (FileConnection)Connector.open("file:///SDCard/Themes/"+fileName );
                 InputStream input = null;
                 input = fconn.openInputStream();     
                 int available = 0;
                 available = input.available();
                 int fSz = (int)fconn.fileSize();
                 byte[] data = new byte[fSz];            
                 input.read(data, 0, fSz);
                 EncodedImage image = EncodedImage.createEncodedImage(data,0,data.length);
                 bkBitmap = image.getBitmap();               
            }
        catch(Exception e)
            {
            }
        return bkBitmap;
    }

Run BlackBerry Application without APN -Dynamically add APN from XML file

Most time we need to connect internet and use web services without setting apn.Some times user may use different sim cards and different service providers but application must work with them all without changing

In this dialog box we will display web page content of given url.Here getpage() method and getTag() methods are in my blog so simply you can  use them

String mcc = Integer.toHexString(RadioInfo.getMCC  (RadioInfo.getCurrentNetworkIndex()));
String mnc = Integer.toHexString(RadioInfo.getMNC(RadioInfo.getCurrentNetworkIndex())); Dialog.alert(getTag(ReadFile(),mcc+","+mnc));
Dialog.alert(getPage("http://www.google.com"+";deviceside=true;apn="+getTag(ReadFile(),mcc+","+mnc)));//Dialog will display web page content

//New URL is= ("http://www.google.com"+";deviceside=true;apn="+getTag(ReadFile(),mcc+","+mnc))

 

ReadFile Method

public String ReadFile()
{
//This retturns the String in FileName.txt
//File must locate in Src Folder
try {
Class classs = Class.forName("pkgName.className");//Replace package name and class name with your parameters
//Source Package neme and Class name
InputStream is = classs.getResourceAsStream("/test.txt");//test.txt add to your package folder
byte[] data = new byte[is.available()];
is.read(data, 0, is.available());
String c =new String(data);
return c;
}
catch (Exception ioe)
{
Dialog.alert("Error");
return null;
}
}

 

test.txt

This File provides apn according to the values of mcc and mnc

<310,12></310,12>
<310,4></<310,4> verizon
<310,38></310,38>     AT&T
<310,90></310,90>
<310,150></310,150>
<310,680></310,680>
<310,410></310,410>
<310,160>wap.voicestream.com</310,160>
<310,170>wap.voicestream.com</310,170>
<310,260>wap.voicestream.com</310,260>
<310,490>wap.voicestream.com</310,490>
<310,26>wap.voicestream.com</310,26>
<890,126>wap.voicestream.com</890,126>
<413,2>dialogbb</413,2>
<302,720>internet.com</302,720>
<22e2,0></22e2,0>

Extract variable from XML String - java Blackberry

XML s are basically organize as <tagname>contentent</tagname>

some times we need to get the content of the tag.but in blackberry there no specified method to do that.so use this methods.what we have to do is pass xml string and parameter nane to gettag method then you will get the content between tags

public static String getTag(String XML,String TagName)
{
    try {
        String ans = "error";
        String front1 = "<" + TagName;
        String back1 = "=";
        String[] sssnew = split(XML, front1);
        if (sssnew.length > 1) {
            String[] sss1new = split(sssnew[1], back1);
            if ((sss1new[0]).compareTo(" i:nil") < 1) {
                ans = "";
                return ans;
            }
        }
        String front = "<" + TagName + ">";
        String back = "</" + TagName + ">";
        String[] sss = {};
        sss = split(XML, front);
        if (sssnew.length > 1) {
            String[] sss1 = {};
            sss1 = split(sss[1], back);
            ans = sss1[0];
        }
        return ans;
    } catch (Exception e) {
        return "";
    }
}
private static String[] split(String inString, String delimeter)
{
    String[] retAr = new String[0];
    try {
        Vector vec = new Vector();
        int indexA = 0;
        int indexB = inString.indexOf(delimeter);

        while (indexB != -1) {
            if (indexB > indexA)
                vec.addElement(new String(inString
                        .substring(indexA, indexB)));
            indexA = indexB + delimeter.length();
            indexB = inString.indexOf(delimeter, indexA);
        }
        vec.addElement(new String(inString.substring(indexA, inString
                .length())));
        retAr = new String[vec.size()];
        int intIteration = vec.size();
        for (int i = 0; i < intIteration; i++) {
            retAr[i] = vec.elementAt(i).toString();
        }
    } catch (Exception e)
    {

    }
    return retAr;
}

Interrupt service routine handler- programmable Integrated circuit

 

When trigger switch connected to int/RB0 that will start counting 0 to 10 we can get out put from RA0 toRA3 as 0000 to 1010 use with pic = 16F84

org 0x00                     ;This is where we come on power up and reset

;*******************SETUP CONSTANTS*******************
INTCON         EQU 0x0B       ;Interrupt Control Register

PORTB           EQU 0x06       ;Port B register address

PORTA          EQU 0x05       ;Port A register address

TRISA         EQU 0x85       ;TrisA register address

TRISB            EQU 0x86       ;TrisB register address

STATUS          EQU 0X03      ;Status register address

COUNT          EQU 0x0c         ;This will be our counting variable

TEMP              EQU 0x0d      ;Temporary store for w register

  goto    main                              ;Jump over the interrupt address

;***************INTERRUPT ROUTINE***************

  org                  0x04                ;This is where PC points on an interrupt

  movwf TEMP              ;Store the value of w temporarily

incf                  COUNT,1       ;Increment COUNT by 1, and put the result

;back into COUNT

movlw 0x0A               ;Move the value 10 into w

subwf              COUNT,0       ;Subtract w from COUNT, and put the

;result in w

btfss                STATUS,0       ;Check the Carry flag. It will be set if

                                                ;COUNT is equal to, or is greater than w,

                                                ;and will be set as a result of the subwf

                                                ;instruction

goto                carry_on           ;If COUNT is <10, then we can carry on

goto                clear                 ;If COUNT is >9, then we need to clear it

carry_on

bcf                  INTCON,0x01 ;We need to clear this flag to enable

  ;more interrupts

movfw TEMP              ;Restore w to the value before the interrupt

  retfie                                      ;Come out of the interrupt routine

clear

clrf                  COUNT          ;Set COUNT back to 0

bcf                  INTCON,1      ;We need to clear this flag to enable

                                                ;more interrupts

retfie                              ;Come out of the interrupt routine

;*******************Main Program*********************

main

;*******************Set Up The Interrupt Registers****

bsf                   INTCON,7      ;GIE – Global interrupt enable (1=enable)

bsf                   INTCON,4      ;INTE - RB0 Interrupt Enable (1=enable)

bcf                  INTCON,1      ;INTF - Clear FLag Bit Just In Case

;*******************Set Up The Ports******************

  bsf                STATUS,5     ;Switch to Bank 1

movlw 0x01           

movwf TRISB              ;Set RB0 as input

movlw 0x10                       

movwf TRISA              ;Set R 0 to RA3 on PortA as output

  bcf                  STATUS,5  ;Come back to Bank 0

;*******************Now Send The Value Of COUNT To Port A           

loop

movf                 COUNT,0       ;Move the contents of Count into W

movwf              PORTA           ;Now move it to Port A

goto                 loop                 ;Keep on doing this

end                                           ;End Of Program

 

image

if you need more details go to http://www.mstracey.btinternet.co.uk

There many more things about pic and interrupt service routine .This works for me with Mplab ide and proteous 7 environment

Nuwan added this:

1. You use RC OSC and no capacitor. (R1 and OSC1) This is ok with some pic's but, some are fail. You use distributed capacitance of Rosc pin and it is better to connect 20pF cap to ground.


2. RB0 ,Int 0 RC low pass filter R2 value is too large. Use between 2K ~ 10K value.

Send text message from mobile device to computer-java mobile socket level Programming

In many projects we need to communicate mobile device and computers this code demonstrates how to communicate between them.here we have 2 codes one for mobile device and other for java server.server basically keep socket open and listen to that socket and mobile device get text from user and send them to server.this works perfectly with blackberry mobile device and if we can make few changes then able to work with any mobile device.use same host name and port number for both codes.server code add to netbeans project and run it.then mobile client project add to eclipse mobile project and run it.that's it

Server code

import java.net.*;
import java.io.IOException;
import java.io.*;
import java.util.Scanner;

public class Main {
    private static ServerSocket serverSocketin;
    private static ServerSocket serverSocketout;
    public static void main(String[] args)
    {
        try

        {
            serverSocketin = new ServerSocket(8206);
            serverSocketout = new ServerSocket(8207);
            DataSender dtsender = new DataSender();
            DataRiciver dataRiciver=new DataRiciver();
            dtsender.start();
            dataRiciver.start();
        }

         catch (IOException e)

        {
            e.printStackTrace();
        }
    }
    static class DataRiciver extends Thread
    {
        public void run(){
            while (true){
                try {
                    Socket incoming = serverSocketin.accept();
                    DataInputStream in = new DataInputStream(incoming.getInputStream());
                    String data="";
                    data = in.readLine();
                    System.out.println(data);
                    in.close();
                    incoming.close();
                     Thread.sleep(1000);
                }

                catch (Exception e)

                  {
                  }
        }

        }
    }

    static class DataSender extends Thread
    {
        public DataSender()
        {

        }

        public void run()
        {
            while (true)
            {
                try {
                    Scanner reader = new Scanner(System.in);
                    String data = reader.nextLine();
                    Socket outgoing = serverSocketout.accept();
                    PrintStream out = new PrintStream(outgoing.getOutputStream());
                    data=data+ "\n";
                    out.write(data.getBytes());
                    out.flush();
                    out.close();
                    outgoing.close();
                    Thread.sleep(1000);
                }
                catch (Exception ioe)
                {
                }
            }
        }
    }

}

 

Mobile client Code-BlackBerry

import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.MainScreen;
import javax.microedition.io.*;
import java.io.*;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
public class sss extends UiApplication
{
    public static void main(String[] args)
    {
        sss theApp = new sss();
        theApp.enterEventDispatcher();
    }
    public sss()
    {
        pushScreen(new UserInterfaceScreen());
    }
}

final class UserInterfaceScreen extends MainScreen
{
HorizontalFieldManager _fieldManagerTop;
VerticalFieldManager _fieldManagerMiddle;
HorizontalFieldManager _fieldManagerBottom;
BitmapField _bitmap;
Bitmap _canadaImage;
LabelField _label;
BasicEditField _input;
String _canadaCapital;
int displayed = 0;
    public UserInterfaceScreen()
    {
        super();
        LabelField title = new LabelField("Send Text To server",
        LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH);
        setTitle(title);
        _fieldManagerTop = new HorizontalFieldManager();
        _fieldManagerMiddle = new VerticalFieldManager();
        _fieldManagerBottom = new HorizontalFieldManager();
        add(_fieldManagerTop);
        add(new SeparatorField());
        add(_fieldManagerMiddle);
        add(new SeparatorField());
        add(_fieldManagerBottom);
        _canadaImage = Bitmap.getBitmapResource("canada.png");
        _bitmap = new BitmapField();
        _bitmap.setBitmap(_canadaImage);
        _fieldManagerTop.add(_bitmap);
        _canadaCapital = "txt";
        _label = new LabelField("Please press a button!");
        _input = new BasicEditField("Enter text here: ","ssss");
        _fieldManagerMiddle.add(_label);
        _fieldManagerMiddle.add(_input);
FieldChangeListener listenerCanada = new FieldChangeListener()
        {
            public void fieldChanged(Field field, int context)
            {
                _bitmap.setBitmap(_canadaImage);
                _input.setText(_canadaCapital);
                displayed = 0;
            }
        };
//add button
ButtonField canadaButton = new ButtonField("send");
canadaButton.setChangeListener(listenerCanada);
_fieldManagerBottom.add(canadaButton);

};
protected void makeMenu(Menu menu, int instance) {
menu.add(_changeCapital);
menu.add(_close);
}

private MenuItem _changeCapital = new MenuItem("Send to Server", 110,10)
{
public void run()
{
//=====================================================
//This code block do client task this part can use with any mobile device
//with few changes
try {
    StreamConnection conn;
    conn = (StreamConnection)Connector.open("socket://localhost:8206;deviceside=true");
    //open and connect to server socket use your host name and socket here
    PrintStream output = new PrintStream(conn.openOutputStream());
    String data=_input.getText();;
    //get input text from the user
    output.write(data.getBytes());
    //write to out put
    output.flush();
    output.close();
    conn.close();
    }
catch (Exception e)
    {
    }
//===================================================
}
};

private MenuItem _close = new MenuItem("Close", 110, 10)
{
    public void run()
    {
        onClose();
    }
};

public boolean onClose()
{
    Dialog.alert("Goodbye!");
    System.exit(0);
    return true;
}

}

Mobile Code –java Mobile

package client;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;

public class MobileClient extends MIDlet implements CommandListener {
    private Display display;
    private Command exit;
    private Command send;
    //private Command back;
    private TextBox textBox;

    ServerListner serverListner = new ServerListner();

    public MobileClient() {

        display = Display.getDisplay(this);
        send=new Command("Send",Command.SCREEN,1);
        exit = new Command("Exit", Command.EXIT, 2);

        textBox = new TextBox("Recived massage", "no massage", 81, 0);
        textBox.addCommand(send);
        textBox.addCommand(exit);
        textBox.setCommandListener(this);

        //output=new PrintStream(connection.openOutputStream());

    }

    protected void startApp() throws MIDletStateChangeException {
        display.setCurrent(textBox);
        serverListner.start();

    }

    protected void pauseApp() {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    protected void destroyApp(boolean b) throws MIDletStateChangeException {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void commandAction(Command command, Displayable displayable) {
        if (command == exit) {
            try {
                destroyApp(false);
                notifyDestroyed();
            } catch (MIDletStateChangeException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
        else if(command ==send)
        {
            String data=textBox.getString();
            sendData(data);
        }
    }

    public void sendData(String data) {
        try {
            StreamConnection connection = (StreamConnection) Connector.open("socket://localhost:8206");
            PrintStream output = new PrintStream(connection.openOutputStream());
            data=data +"\n";
            output.write(data.getBytes());
            output.flush();
            output.close();
            connection.close();

        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    class ServerListner extends Thread {

        public void run() {
            try {
                while (true) {
                    StreamConnection connection = (StreamConnection) Connector.open("socket://localhost:8206");
                    InputStream in = connection.openInputStream();
                    StringBuffer buffer = new StringBuffer();
                    int ch;
                    while ((ch = in.read()) != -1) {
                        if (ch != '\n') {
                            buffer.append((char)ch);
                        } else {

                        }
                    }
                    textBox.setString(buffer.toString());
                    display.setCurrent(textBox);

                    // connection.close();
                    in.close();
                    connection.close();
                     Thread.sleep(1000);
                }
            } catch (Exception ie) {
                ie.printStackTrace();
            }
        }
    }
}

Add APN to your Application in BlackBerry Device-you can access to network from anywhere in the world with any service provider without resetting APN

This Method returns Correct APN to user at run time

public String Getapn()
{

String apn=””;

//is there any other apns add them to following array by replacing empty strings

String[] arr= {"","internet.com","blackberry.net","internet2.voicestream.com","wap.voicestream.com","dialogbb",""};
int i=0;
int j=0;
while(i==1&&j<6)
{
j=j+1;
try
{

//test sending request to google.com here get page method you will find in

//my blog that basically returns page of given address
getPage("http://www.google.com"+";trustAll;deviceside=true;apn="+arr[j]);
i=1;
}
catch (Exception e)
{
}
}
apn=arr[j];

return apn;
}

Simplest Way to VOIP Set Up

This document is about setup voip using open source packages

Building your own corporate phone system using the Asterisk open source telephony suite could result in massive cost savings for your company

Downloading Asterisk/Dahdi/LibPRI

Go to http://www.asterisk.org/downloads and download Asterisk/Dahdi/LibPRI (Look for Asterisk downloads  on right-hand side) .
You can use wget command to download sources (tar ball) on your local directory.
For example:

#>wget http://downloads.digium.com/pub/telephony/dahdi-linux/dahdi-linux-2.0.0.tar.gz
#>wget http://downloads.digium.com/pub/telephony/dahdi-tools/dahdi-tools-2.0.0.tar.gz
#>wget http://downloads.digium.com/pub/libpri/releases/libpri-1.4.7.tar.gz
#>wget http://downloads.digium.com/pub/asterisk/releases/asterisk-1.6.0.1.tar.gz

Installing Asterisk/Dahdi/Libpri

  1. Dahdi Installation
    Download Dahdi into arbitrary directory (/usr/src) and  untar it.
    #>tar xvfz dahdi-linux-<version>
    #>tar xvfz dahdi-tools-<version>
    #>cd dahdi-<version>
    #>make
    #>make install
    #>cd ..
    #>
    cd dahdi-tools-<version>
    #>./configure
    #>make
    #>make install
  2. LibPRI Installation
    Download libpri into arbitrary directory (/usr/src) and untar it.
    #>tar xvfz libpri-<version>
    #>cd libpri-<version>
    #>make
    #>make install
  3. Asterisk Installation

    If you are upgrading Asterisk make sure that old asterisk modules are removed from /usr/lib/asterisk/modules
    #> cd /usr/lib/asterisk
    #> mv modules modules.old
    Download Asterisk into arbirary directory  (/usr/src/) and untar it.
    Untar Asterisk and proceed with installation
    #>tar xvfz asterisk-<version>.tgz
    #>cd asterisk-<version>
    #>./configure
    #>make
    #>make install
    #>make samples (in case of very first install)

Please note: <version> refers to the specific release of your program. For instance, dahdi-linux-2.0.0.tar.gz, once untarred will create the folder dahdi-linux-2.0.0.

When the system comes back up, Asterisk should start automatically. To check that everything is working, check DAHDI is loaded by opening a terminal window and, with root privileges, typing:

# lsmod | grep dahdi

You should see references to several dahdi modules, including dahdi_dummy, dahdi_transcode, crc_ccitt, and dahdi_voicebus.

Check Asterisk is running and log on to the Asterisk command line with:

#asterisk –r

You should see some version and license information along with a "Connected to Asterisk" message and prompt.

To stop asterisk from the Asterisk command line type

CLI> stop now

or from the Linux command prompt type

# service asterisk stop


Setting up an X-Lite client on Asterisk

X-Lite and Asterisk Ver 1.00 Page 1
1) Adding a client entry to Asterisk’s SIP configuration
* edit the SIP configuration file /etc/asterisk/sip.conf
% sudo vi /etc/asterisk/sip.conf
*enter an entry for each X-Lite client, for example
[12345] ; X-Lite client 12345
type=friend
secret=blah
auth=md5
nat=yes ; we assume clients are behind NAT
host=dynamic ; and have dynamic IP addresses
reinvite=no ; if so, we need to make them
canreinvite=no ; always go through Asterisk
qualify=1000
dtmfmode=inband
callerid="Fred Flintstone" <12345>
disallow=all
allow=gsm ; add whatever other codecs we fancy
context=theflintstones ; use a context that exists ;-)
*save the changes
2) Adding extensions for X-Lite clients
* edit the Extensions configuration file /etc/asterisk/extensions.conf
% sudo vi /etc/asterisk/extensions.conf
*enter one catch-all extension, for example
[theflintstones] ; Our context for X-Lite clients
;
; Catch all five digit numbers, no leading zeroes
exten => _[123456789]XXXX,1,NoOp(“call for “${EXTEN})
exten => _[123456789]XXXX,2,Dial(SIP/${EXTEN},60,tr)
exten => _[123456789]XXXX,3,Congestion
* alternatively, enter one specific extension for each client
* save the changes
3) Reload the new configuration
* on the Asterisk console, reload the configuration files
switch1*CLI> reload

Add APN to http request automatically for BlackBerry device

Add this to the url As follows
you can add this part to url
URL+";trustAll;deviceside=true;apn=APN"

ex: get APN from mobile service provider
and add to above code

Find Distance Between 2 Cities Using Google Map

Copy This Code to file named main.html and save it

Then open with any web browser

//===========================================================

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  <head>
<title>Google Maps Find Distance</title>
<script src="http://maps.google.com/maps?file=api&;v=2&key=ABQIAAAA7j_Q-rshuWkc8HyFI4V2HxQYPm-xtd00hTQOC0OXpAMO40FHAxT29dNBGfxqMPq5zwdeiDSHEPL89A" type="text/javascript"></script>
<script type="text/javascript">
   var geocoder, city1, city2;
    function initialize()
    {
      geocoder = new GClientGeocoder();
      //Creates a new instance of a geocoder that talks directly to Google servers.
    }
    function showLocation()
    {
       geocoder.getLocations(document.forms[0].address1.value, set1);
      //set1 method calls then get the address 1.if only location 1 get correct way
      //then only we can get the second address.else display error message
       //getLocations(java.lang.String address, GGeocodeAdvancedResultListener result)
      //getLocations(address, callback) none Sends a request to Google servers to geocode the specified address.
      //getLatLng(address, callback) none Sends a request to Google servers to geocode the specified address. If the
      //address was successfully located, the user-specified callback function is invoked with a GLatLng point. Otherwise,
      //the callback function is given a null point. In case of ambiguous addresses, only the point for the best match is passed to the callback function.
   }
   function calculateDistance()
    {
        try
        {
           var glatlng1 = new GLatLng(city1.lat, city1.lon);
          var glatlng2 = new GLatLng(city2.lat, city2.lon);
           var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1);
            var kmdistance = (miledistance * 1.609344).toFixed(1);
           document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + city1.address + '<br /><strong>Address 2: </strong>' + city2.address + '<br /><strong>Distance: </strong>' + miledistance + ' miles (or ' + kmdistance + ' kilometers)';
        }
        catch (error)
        {
            alert(error);
        }
   }
  
      function set1(response)
       {
    //200 OK
       //Standard response for successful HTTP requests. The actual response will depend on the request method used. In a GET request,
    //the response will contain an entity corresponding to the requested resource. In a POST request the response will contain an entity
    //describing or containing the result of the action.
           if (!response || response.Status.code != 200)
        {
            alert("Sorry, we were unable to geocode the first address");
            //messages
        }
          else
        {
            //set the 1st location only get correct response
            city1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
             //.if only location 1 get correct way then only we can get the second address.else display error message
             geocoder.getLocations(document.forms[0].address2.value, set2);
        }
        }
  
    function set2(response)
            {
                if (!response || response.Status.code != 200)
                {
                    alert("Sorry, we were unable to geocode the second address");
                }
                else
                {
                    //set the 2nd location coordinates
                    city2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
                    //when both address get in correct way then we can calculate the distance
                    calculateDistance();
                    load();
                    addToMap(response);
                }
            }
function GoToNext()
{
window.location.href = 'map.html';
//go to next page
}

function help()
{
window.location.href = 'help.html';
//go to next page
}
   </script>
  </head>

  <body onload="initialize()">

    <form action="#" onsubmit="showLocation(); return false;">
  <h1 align="center"><font color="#CC0033" size="5" face="Geneva, Arial, Helvetica, sans-serif">Find
    Distance Between 2 Cities Using Google Map</font></h1>
  <h1><font color="#00FF33" size="4" face="Courier New, Courier, mono"></font></h1>
  <p><font color="#0066CC" size="4" face="Verdana, Arial, Helvetica, sans-serif">by:S.R.B.
    Malalgoda</font><font color="#00FF33" size="4" face="Courier New, Courier, mono">
    </font></p>
  <p>
    <input type="text" name="address1" value="" class="address_input" size="40" />
    <input type="text" name="address2" value="" class="address_input" size="40" />
  </p>
  <p>
    <input type="submit" name="find" value="Calculate Distance" /><p><input type="submit" value="View Map" onClick="GoToNext()"
  <p>
  </p>
   </form>
    <p id="results"></p>

</body>
</html>

Empowering the Future of API Management: Unveiling the Journey of WSO2 API Platform for Kubernetes (APK) Project and the Anticipated Alpha Release

  Introduction In the ever-evolving realm of API management, our journey embarked on the APK project eight months ago, and now, with great a...