Parsing KML in Java using JavaApiForKml.jar

KML(Keyhole markup language)

KML(Keyhole markup language) is a file format used to display geographic data in an Earth browser such as Google Earth, Google Maps, and Google Maps for mobile. KML uses a tag-based structure with nested elements and attributes and is based on the XML standard. All tags are case-sensitive and must be appear exactly as they are listed in the KML Reference. The Reference indicates which tags are optional. Within a given element, tags must appear in the order shown in the Reference.(From google doc: https://developers.google.com/kml/documentation/kml_tut)

Sample kml file:

<?xml version="1.0"?>
<kml xmlns="http://earth.google.com/kml/2.1">
<Document>
<name>Images from 2012-04-19T03:00:00Z UTC to 2012-04-19T03:00:00Z UTC</name>
<open>1</open>
<Folder>
<name>Channel 1</name>
<GroundOverlay>
<LookAt>
<heading>0</heading>
<latitude>10.00</latitude>
<longitude>96.00</longitude>
<tilt>0</tilt>
</LookAt>
<name>2012-04-19T03:00:00Z</name>
<visibility>0</visibility>
<Icon>
<href>http://tt.jpg</href>
</Icon>
<LatLonBox>
<north>25</north>
<south>-5</south>
<east>116</east>
<west>76</west>
</LatLonBox>
<TimeSpan>
<begin>2012-04-19T02:00:00Z</begin>
<end>2012-04-19T03:00:00Z</end>
</TimeSpan>
</GroundOverlay>
</Folder>
</Document>

Parsing KML using JavaApiForKml:
1. Download JavaApiForKml.jar from: http://code.google.com/p/javaapiforkml/
2. Add JavaApiForKml.jar in your java project
3. Check out following code to parsing KML

package com.kml;

import de.micromata.opengis.kml.v_2_2_0.Document;
import de.micromata.opengis.kml.v_2_2_0.Feature;
import de.micromata.opengis.kml.v_2_2_0.Folder;
import de.micromata.opengis.kml.v_2_2_0.GroundOverlay;
import de.micromata.opengis.kml.v_2_2_0.Kml;
import de.micromata.opengis.kml.v_2_2_0.LatLonBox;
import de.micromata.opengis.kml.v_2_2_0.LookAt;
import java.io.File;
import java.util.List;

/**
 *
 * @author Shaiful Isalam(palash)
 */
public class KMLTest {

    public static void main(String[] args) {
        System.out.println("This is KML test");
        final Kml kml = Kml.unmarshal(new File("F:\\Custom.kml"));
        final Document document = (Document)kml.getFeature();
        System.out.println(document.getName());
        List<Feature> t = document.getFeature();
        for(Object o : t){
            Folder f = (Folder)o;
            List<Feature> tg = f.getFeature();
            for(Object ftg : tg){
                GroundOverlay g = (GroundOverlay) ftg;
                LatLonBox l = g.getLatLonBox();
                System.out.println(l.getNorth() );
                LookAt lk = (LookAt)g.getAbstractView();
                System.out.println(lk.getLatitude());                
            }
        }
        

    }
}

Registry 32-bit dll file in 64-bit OS(windows7)

To registry dll file into windows 7, at first you have to open command prompt(cmd) with administrative power. To gain administrative power please follow the screen shot

Registry 32-bit dll file in 32-bit OS/Registry dll file in OS:
  • Go to c:\windows\system32 folder using Command prompt.
  • Write regsvr32 yourdll.dll

Registry 32-bit dll file in 64-bit OS:
  • Go to c:\windows\SysWOW64 folder using Command prompt.
  • Write regsvr32 yourdll.dll

 

How to override hashCode() in ideal way #Java

Following steps can be followed to override java hashCode() in ideal way

1. Store some constant nonzero value, say 17, in an int variable called result

2. For each significant field f in your object (each field taken into account by the equals method, that is), do the following:

a. Compute an int hash code c for the field:

i) If the field is a boolean, compute (f ? 0 : 1)
ii) If the field is a byte, char, short, or int, compute (int)f.
iii) If the field is long, compute (int)(f^(f>>>32)).
iv) If the field is a float compute Float.floatToIntBits(f).
v) If the field is a double, compute Double.doubleToLongBits(f), and then hash the resulting long as in step 2.a.iii.
vi) If the field is an object reference and this class’s equals method compares the field by recursively invoking equals, recursively invoke hashCode on the field. If a more complex comparison is required, compute a “canonical representation” for this field and invoke hashCode on the canonical representation. If the value of the field is null, return 0.
vii) If the field is an array, treat it as if each element were a separate field. That is, compute a hash code for each significant element by applying these rules recursively, and combine these values as described in step 2.b.

b. Combine the hash code c computed in step a into result as follows: result = 37 * result + c;

3. Return result

4. When you done writing the hashCode method, ask yourself whether equal instances have equal hash codes. If not, figure out why and fix the problem.

An example of hashCode():

    @Override
    public int hashCode(){
        int result = 17 + Float.floatToIntBits(re);
        result = 37 * result + Float.floatToIntBits(im);
        return  result;
    }

How to make a immutable class in Java

To make a class immutable, follow these five rules:

1. Don’t provide any methods that modify the object(known as mutators)
2. Ensure that no methods may be overridden. – Preventing method overrides is generally done by making the class final
3. Make all fields final
4. Make all fields private
5. Ensure exclusive access to any mutable components

Example of immutable class:

package com.study.effectivejava.secondchapter;

public final class Complex {
    
    private final float re;
    private final float im;
    
    public Complex(float re, float im){
        this.re = re;
        this.im = im;               
    }
    
    public float realPart(){
        return re;
    }
    
    public float imaginaryPart(){
        return im;
    }
    
    public Complex add(Complex c){
        return new Complex(re + c.re, im + c.im);
    }
    
    public Complex subtract(Complex c){
        return new Complex(re - c.re, im - c.im);
    }
    
    public Complex multiply(Complex c){
        return new Complex(re * c.re - im * c.im, re * c.im + im * c.re);
    }
    
    public Complex divide(Complex c){
        float tmp = c.re * c.re + c.im * c.im;
        return new Complex((re*c.re + im*c.im)/tmp, (im*c.re - re*c.im)/tmp);
    }
    
    @Override
    public boolean equals(Object o){
        if(o == this) return true;
        if(!(o instanceof Complex)) return false;
        Complex c = (Complex)o;
        return (Float.floatToIntBits(re) ==
                Float.floatToIntBits(c.re)) &amp;&amp;
                (Float.floatToIntBits(im)==
                Float.floatToIntBits(c.im));
    }
    
    @Override
    public int hashCode(){
        int result = 17 + Float.floatToIntBits(re);
        result = 37 * result + Float.floatToIntBits(im);
        return  result;
    }
    
    @Override
    public String toString(){
        return "(" + re + "+ " + im + "i)";
    }       
}

Application server@ejb

An application server is an application program that accepts connections in order to service requests, by sending back responses. An application server can run remotely(connected to client through a computer network) or can exist on the same computer where the client application is running.

Examples:

      File server
      Database server
      Backup server
      Web server
      FTP server
      Application server
      VPN server
      DHCP server
      DNS server
      WINS server
      Logon server
      Security server
      Domain controller
      Backup domain controller
      Proxy server
      Firewall

Application server are developed to support the quick development of the enterprise model. They provide security and state maintenance with the database persistence.

An application server may be a part of a three tier architecture model. A three tier architecture includes the client tier, Middle tier and the EIS(Enterprise information system) tier.

The view tier: is nothing but the web based graphical user interface to interact with the clients.
Middle tier: is the combination of web containers and the ejb containers.
EIS tier: EIS contains persistence and the database management system to support the applications.

J2EE platform requires database to store the business data. This database is accessible by means of JDBC, JDO or SQLJ APIs. We can also access the database through enterprise beans, we components and the application client components.

session_bean:stateful&stateless@ejb

A session bean represents a single client inside the J2EE server. To access an application that is deployed on the server, the client invokes the session bean’s methods. The session bean performs work for its client, shielding the client from complexity by executing business tasks inside the server.

a session bean is similar to an interactive session. A session bean is not shared–it may have just one client, in the same way that an interactive session may have just one user. Like an interactive session, a session bean is not persistent. (That is, its data is not saved to a database.) When the client terminates, its session bean appears to terminate and is no longer associated with the client.

Stateful Session Beans:
The state of an object consists of the values of its instance variables. In a stateful session bean, the instance variables represent the state of a unique client-bean session. Because the client interacts (“talks”) with its bean, this state is often called the conversational state.The state is retained for the duration of the client-bean session. If the client removes the bean or terminates, the session ends and the state disappears. This transient nature of the state is not a problem, however, because when the conversation between the client and the bean ends there is no need to retain the state.

Stateless Session Beans:
A stateless session bean does not maintain a conversational state for a particular client. When a client invokes the method of a stateless bean, the bean’s instance variables may contain a state, but only for the duration of the invocation. When the method is finished, the state is no longer retained. Except during method invocation, all instances of a stateless bean are equivalent, allowing the EJB container to assign an instance to any client.

Because stateless session beans can support multiple clients, they can offer better scalability for applications that require large numbers of clients. Typically, an application requires fewer stateless session beans than stateful session beans to support the same number of clients.

At times, the EJB container may write a stateful session bean to secondary storage. However, stateless session beans are never written to secondary storage. Therefore, stateless beans may offer better performance than stateful beans

Things are important:

>> General Session bean
>>> At any given time, only one client has access to the bean instance.
>>> The state of the bean is not persistent, existing only for a short period of time (perhaps a few hours).

>>Stateful session bean
>>> The bean’s state represents the interaction between the bean and a specific client.
>>> The bean needs to hold information about the client across method invocations.
>>> The bean mediates between the client and the other components of the application, presenting a simplified view to the client.
>>> Behind the scenes, the bean manages the work flow of several enterprise beans.

>> To improve performance, you might choose a stateless session bean
>>> The bean’s state has no data for a specific client.
>>> In a single method invocation, the bean performs a generic task for all clients. For example, you might use a stateless session bean to send an e-mail that confirms an online order.
>>> The bean fetches from a database a set of read-only data that is often used by clients. Such a bean, for example, could retrieve the table rows that represent the products that are on sale this month.

@intro_ejb

Enterprise JavaBeans are server-side, moduler, and reusable components that comprise specific units of functionality. They are similar to the classes we create every day, but are subject to special restrictions and must provide specific interfaces for container and client use and access. In addition, they can only run properly in an EJB container, which manages and invokes specific life cycle behavior. You should consider using EJB components when the application design requires scalability, transactional processing, or availability to multiple client types.

EJB components come in three varieties, each with its own defined role and life cycle:
1. Session beans: These may be either stateful or stateless, and are primarily used to encapsulate business logic, carry out tasks on behalf of a client, and act as controllers or managers for other beans.
2. Entity beans: Entity beans represents persistent objects or business concepts that exist beyond a specific application’s lifetime; they are typically stored in a relational database. Entity beans can be developed using bean-managed persistence, which is implemented by the developer, or container-managed persistence, implemented by the container.
3. Message- driven beans: Message-driven beans listen asynchronously for Java Message Service(JMS) messages from any client or component and are used for loosely coupled, typically batch-type, processing.

EJB Programming Restrictions
1. An enterprise Bean must not use read/write static fields. Using read-only static fields is allowed. Therefore, it is recommended that all static fields in the enterprise bean class be declared as final.

2. An enterprise Bean must not use thread sychronization primitives to synchronize execution of multiple instances.

3. An enterprise Bean must not use the AWT functionality to attempt to output information to a display, or to input information from a keyboard.

4. An enterprise Bean must not use the java.io package to attempt to access files and directories in the file system.

5. An enterprise bean must not use attempt to listen on a socket, accept connections on a socket, or use a socket for multicast.

6. The enterprise bean must not attempt to query a class to obtain information about the declared members that are not otherwise accessible to the enterprise bean because of the security rules of the java language. The enterprise bean must nto attempt to use the Reflection API to access information that the security rules of the java programming language make unavailable.

7. The enterprise bean must not attempt to create a class loader; obtain the current class loader; set the context class loader; set security manager; create a new security manager; stop the JVM; or change the input, output and error steams.

8. The enterprise bean must not attempt to set the socket factory used by ServerSocket, Socket, or the stream handler factory used by URL.

9. The enterprise bean must not attempt to manage threads. The enterprise bean must not attempt to start, stop, suspend, or resume a thread; or to change a thread’s priority or name. The enterprise bean must not attempt to manage thread groups.

10. The enterprise bean must not attempt to directly read or write a file descriptor.

11. The enterprise bean must not attempt to obtain the security policy information for a particular code source.

12. The enterprise bean must not attempt to load a native library.

13. The enterprise bean must not attempt to gain access to packages and classes that the usual rules of the Java programming language maje unavailable to the enterprise bean.

14. The enterprise bean must not attempt to define a class in a package.

15. The enterprise bean must not attempt to access or modify the security configuration objects(Policy, Security, Provider, Signer, and Identity).

16. The enterprise bean must not attempt to use the subclass and object substition features of the Java serialization protocol.

17. The enterprise bean must not attempt to pass this as an argument or method result. The enterprise bean must pass the result of SessionContext.getEJBObject(), SessionContext.getEJBLocalObject(), EntityContext.getEJBObject(), or EntityContext.getEJBLocalObject() instead,

কখন বুজবেন আপনার সপ্টওয়ার থেকে দুর্গন্ধ বের হচ্ছে

কোন একটা Software project start করার আগে যদি Project এর clear picture আপনি বুজতে পারেন তাহলে আপনি খুবি ভাগ্যবান developer. খুব সহজেই Project develop করতে পারবেন এতে কোন সন্দেহ নাই। আর যদি Project অল্প অল্প বুজি এবং অল্প বুজা নিয়ে Project Start করেন তাহলে আপনার কপালে খারাপই লেখা আছে।

যাইহোক, ধরে নিলাম আপনি ভাগ্যবান developer. Project complete করলেন এবং First release ও দিলেন কিছুদিন পর Client বললো আমার এটা দরকার, এটা বাদ দেন, আরো feature দরকার, খেলাটা আসলে তখনি Start হবে, আর যদি Project এ problem ধরা পড়ে তাহলে অচিরেই আপনি বুজতে পারবেন কি অখাদ্য টাই আপনি বানিয়েছেন এবং এর দুর্গন্ধ কিভাবে ছড়াচ্ছে। চলেন দেখা যাক আপনি কিভাবে বুজবেন আপনার Software এ পচন ধরেছে।

বাজে Software এর দুর্গন্ধ:

১) Rigidity(অনমনিয়তা): Rigidity’র কারনে Software Change করা খুব কষ্টসাধ্য ব্যাপার, এমনকি যে কোন সহজ Change। একটা Software তখনি Rigid হয় যখন Single কোন Change এর কারনে Software এর অনেক জায়গা্য় অথবা অনেক মডিউলে Change করতে হয়। অধিকাংশ Developer’রাই এ situation face করে। যদি তাদেরকে Simple change করতে বলা হয়, তখন তারা Change এর requirement দেখে time estimate করে, কিন্তু কাজ করতে গিয়েই বিপত্তি ঘটে। তখন তাদের Simple change এর জন্য অনেক মডিউল change করতে হয়, স্বাভাবিক ভাবে Deadline miss করে। তখন তাদের যদি বলা হয় ভাই কি কারনে Deadline miss হলো Answer কি জানেন “আমি যা ভেবেছিলাম তা তার চেয়ে অনেক অনেক কঠিন”।

২) Fragility (ভন্গুরতা/অল্পতেই crash হয় এমন): Fragility হচ্ছে Program এ Simple change এর কারনে Software এর অনেক জায়গায় crash হওয়ার possibility. যার কারনে কোন একটা bug fix করতে গিয়ে developer রা আরও অনেক bug এর সম্মুখীন হয়। So, বোজেন অবস্থা!

এই ধরনের যত মডিউল Software থাকবে ততই unexpected bug এর সম্মুখীন হতে হবে সন্দেহ নাই। এই ধরনের মডিউলে সবসময় bug আসতেই থাকবে। মজার ব্যাপার কি জানেন developer রা এসব মডিউল সম্পর্কে ভালোভাবেই জানে, যে এইসব মডিউল re-design করা দরকার। কিন্তু ভয়ের কারনে করতে পারেনা, না জানি আবার কোন বড় ধরনের প্রবলেম হয়।

৩) Immobility(অসচলতা): এটা খুবি কমন ঘটনা। একটা software design তখনি immobile হবে যখন এর কোন মডিউল এর কিছু অংশ অন্য মডিউলে বা অন্য system এর জন্য useful হতে পারে, কিন্তু এইসব useful অংশ separate করা খুবি risky এবং অনেক effort এর প্রয়োজন হয়।

৪) Viscosity(লস, সান্দ্রতা): Viscosity দুই ধরনের হতে পারে-
a) viscosity of a software
b) viscosity of the environment

a) Viscosity of a software: Developer রা যখন software change করতে বসে তখন তারা অনেক way/process চিন্তা করে, এটাই স্বাভাবিক। কিছু কিছু process current design meet করে আর কিছু কিছু process crash হয়ার possibility থাকে। এখন, যে process current design meet করে তা implement করা যদি crash হয়া process এর কঠিন হয় তাহলে তখন viscosity of design high হয়। So, ভুল পথে যাওয়াটাই খুব সহজ এবং সঠিক পথে যাওয়াটা কঠিন।

Software design এমন হয়া উচিত, যাতে যে কোন change current design preserve করে সহজে করা যায়।

b) Viscosity of the environment: এখন যদি development environment এমন হয় (প্রচন্ড স্লো) simply একটা project compile/debug করতে অনেক সময় প্রয়োজন হয় তখন বোজেন developer দের মনের অবস্থা। মেজাজ খারাপ করে টেবিল থাপরানো, কিবো্র্ড থাপরানো শুরু হয়ে যাবে। এমতাবস্হায়, simple কোন change ও করতে তারা বিরক্ত হবে, সাথে যদি viscosity of software থাকে তাহলে বিপদ কারে কয়।

এই দুই ধরনের viscosity খুব dangerous। So. software environment and design এমন হয়া উচিত যাতে খুব সহজে যেকোন ধরনের change করা যায় এবং তা improve করা যায়।

৫) Needless complexity: একটা design তখনি Needless complexity এর সম্মুখীন হয় যখন system এ currently use হয়না এমন code/module থাকে। Developer দের স্বাভাবিক ভাবে project-এ এধরনের unused code রেখে দেয়ার বদঅভ্যাস থাকে। ভাবে ভবিষ্যতে কাজে লাগতেও পারে! মজার ব্যাপার হচ্ছে ভবিষ্যতে তাদের এ ভাবনা’র ঠিক উল্টোটা ঘটে। এতে করে project-এ প্রচুর unused code/module থেকে যায় পরবর্তীতে project বুজতে অনেক জামেলা পোহাতে হয়। এমতাবস্হায় যদি Developer দের নতুন কোন change দেয়া হয় তাহলে তারা নিজেরাই এই সব unused code/module দেখে হতবাক “এসব কি use হচ্ছে না হচ্ছে না, হায় হায়!”। আর যদি নতুন Developer এসব project এ কাজ করতে বসে, এই সেরেছে!

৬) Needless repetition: copy, cut, past এর সাথে আমরা সবাই পরিচিত। অনেক software আছে যেখানে একই ধরনের কোড ভিন্ন ভিন্ন মডিউলে use হয়। এধরনের কোড শত শত হতে পারে। তো developer রা just copy+past করে এবং requirement অনুযায়ী change নেয় এটা খুব স্বাভাবিক। এখন কোন কারনে যদি developer copy+past করে requirement অনুযায়ী change করতে miss করে তখন টের পাবেন কি আজিব টাইপের bug আসা শুরু হয়েছে, সেই সাথে client এর গালিগালাজ শুনতে হতে পারে। Be careful about copy+paste। এবং project এ কোড repetition যত কম করা যায় ততই ভালো।

৭) Opacity(জড়তা): যখন software এর module বুজতে অনেক কঠিন হয় তখন তা Opacity হিসেবে বিবেচিত হয়। কোড করার সময় এমন ভাবে করতে হয় যেন যে কেউ কোড দেখে সহজে বুজতে পারে।

Developer রা যখন কোড start করে তখন তাদের কাছে কোড খুব ক্লিন এবং ক্লিয়ার মনে হয়। এবং একটা সময় যাওয়ার পর অনেক কোড হয়ে যায় যা স্বাভাবিক। তো Developer রা যখন পরে আবার কোড মডিফাই কিংবা change করতে বসে তখন তো অবস্হা কাহিল “কি জন্য কি কোড করেছিলাম নিজেই তো ভুলে গেছি”! হায় হায় বলে কি?

So, senior developer দের উচিত কোড review করা otherwise ডট ডট ডট

পলাশ, ১১-০৭-১১

—————————————————————————

Dedicated to all developers

Ref: Agile Principles, Patterns, and Practices in C# – Robart C. Martin and Micah Martin

বাংলা, ইংরেজী একসাথে use করা জন্য really sorry.

বাদ দেন ফাকিবাজি পোস্ট ০১: String in reverse order using recursive method

/*-----------------------------------------------------------------------------!
! Output string in reverse order using recursive method                        !
!------------------------------------------------------------------------------!
! Notes:                                                                       !
! Original author: Md. Shaiful Islam (palash)                                  !
! Date: 01-July-2011                                                           !
===============================================================================*/

package programmingpractise;

public class ReverseString {

    private static String inputString = "Who are you?";
    private static int length=0;

    public static void main(String args[]){
        length = inputString.length();
        reversStringOutput(0);
    }


    private static void reversStringOutput(int index){
        if(index == length)
            return;
        char currentChar = inputString.charAt(index);
        reversStringOutput(index+1);
        System.out.print(currentChar);
    }

}

java properties example using singleton pattern

In java application, static data/information can be used in full application. Most of the “novice”/amateur developer as like me use hard code information into code, which is very dangerous for any project, specially client specific application. To escape unwanted disaster we can use java properties for static information and singleton pattern.

Here I am trying to figure out database information using java properties and singleton pattern which can be used in full application.

At first we should create a file named like as db.properties, and can store database information like following

# Static information
IP 000.000.0.00
PORT 1433
DATABASE test2
USER test2
PASS test-2
DRIVERNAME com.microsoft.sqlserver.jdbc.SQLServerDriver
JDBC jdbc:sqlserver
INSTANCE SQLEXPRESS

Now, we can use this file in singleton pattern

import java.io.*;
import java.util.Properties;

public class DBInfo {
    static private DBInfo _instance = null;
    public String port = null;
    public String database = null;
    public String ip = null;
    public String user = null;
    public String pass = null;
    public String jdbc = null;
    public String driver = null;
    public String instance = null;

    protected DBInfo(){
        try{
            InputStream file = new FileInputStream(new File("db.properties")) ;
            Properties props = new Properties();
            props.load(file);
            port = props.getProperty("PORT");
            ip = props.getProperty("IP");
            database = props.getProperty("DATABASE");
            user = props.getProperty("USER");
            pass = props.getProperty("PASS");
            jdbc = props.getProperty("JDBC");
            driver = props.getProperty("DRIVERNAME");
            instance = props.getProperty("INSTANCE");
        } catch(Exception e){
            System.out.println("error" + e);
        }

    }

    static public DBInfo instance(){
        if (_instance == null) {
            _instance = new DBInfo();
        }
        return _instance;
    }
}

Now, we can use this in application

DBInfo dbInfo = DBInfo.instance();
String connString = dbInfo.jdbc + "://" + dbInfo.ip + "\\" + dbInfo.instance +":" + dbInfo.port + "; databaseName=" + dbInfo.database + "; userName=" + dbInfo.user +"; passWord="+ dbInfo.pass +";";

If client want to change IP address or database port or something else then client can make this just changing db.properties file.

Follow

Get every new post delivered to your Inbox.