الاثنين، 7 فبراير 2011

adapter pattern

TeaBag.java - the class which the adapter will make the adaptee adapt to
public class TeaBag { 
   boolean teaBagIsSteeped;
   
   public TeaBag() {
       teaBagIsSteeped = false;
   }
  
   public void steepTeaInCup() {
       teaBagIsSteeped = true;
       System.out.println("tea bag is steeping in cup");
   }
}
////////////////////////////////////
TeaBall.java - the adapter
public class TeaBall extends TeaBag { 
   LooseLeafTea looseLeafTea;
  
   public TeaBall(LooseLeafTea looseLeafTeaIn) {
       looseLeafTea = looseLeafTeaIn;
       teaBagIsSteeped = looseLeafTea.teaIsSteeped;
   }
   
   public void steepTeaInCup() {
       looseLeafTea.steepTea();
       teaBagIsSteeped = true;
   }
}//////////////////////////////////////
LooseLeafTea.java - the adaptee
public class LooseLeafTea { 
   boolean teaIsSteeped;
   
   public LooseLeafTea() {
       teaIsSteeped = false;
   }
  
   public void steepTea() {
       teaIsSteeped = true;
       System.out.println("tea is steeping");
   }
}
///////////////////////////////////////
TeaCup.java - the class that accepts class TeaBag in it's steepTeaBag() method, and so is being adapted for.

public class TeaCup { 
   public void steepTeaBag(TeaBag teaBag) {
       teaBag.steepTeaInCup();
   }
}
//////////////////////////////////////////
TestTeaBagAdaptation.java - testing the adapter

class TestTeaBagAdaptation {


   public static void main(String[] args) {
       TeaCup teaCup = new TeaCup();


       System.out.println("Steeping tea bag");
       TeaBag teaBag = new TeaBag();      
       teaCup.steepTeaBag(teaBag);


       System.out.println("Steeping loose leaf tea");
       LooseLeafTea looseLeafTea = new LooseLeafTea();
       TeaBall teaBall = new TeaBall(looseLeafTea);
       teaCup.steepTeaBag(teaBall);
   }
}
//////////////////////////////////////////
Test Results

Steeping tea bag
tea bag is steeping in cup
Steeping loose leaf tea
tea is steeping
/////////////////////////////////////////
Notes
The basic premise of the adapter is that you either can not or do not want to change the adaptee.
This might be because you purchased the adaptee, and do not have the source code.

There are two GoF versions of the adapter.

The First is the inheriting version, in which the adapter inherits from both "the adaptee" and
 "the class that adapter will make the adaptee adapt to".

The Second is the object version, which is shown here.

ref
http://www.fluffycat.com/Java-Design-Patterns/Adapter/

builder pattern

Factory , builder --> helpful for Decorator
============================================
as : composite --> uesd to build a complex object
as : iterator
see: bridge
============================================
builder --> construct complex object from simple objects step by step
        --> Make and return one object various ways.
       
       

ex: http://www.fluffycat.com/Java-Design-Patterns/Builder/       
run       
At the Boston Soup Buffet Today's Soups!  
Chicken Soup: ChickenSoup
Clam Chowder: QuahogChowder-----------------
Fish Chowder: ScrodFishChowder --------------
Minnestrone: Minestrone
Pasta Fazul: Pasta Fazul
Tofu Soup: Tofu Soup Vegetable
Soup: Vegetable Soup

At the Honolulu Soup Buffet Today's Soups!  
Chicken Soup: ChickenSoup
Clam Chowder: PacificClamChowder
Fish Chowder: OpakapakaFishChowder
Minnestrone: Minestrone
Pasta Fazul: Pasta Fazul
Tofu Soup: Tofu Soup Vegetable
Soup: Vegetable Soup


====
another example from head first
==> you have to build a vacation planner for Patternsland, a new them park just outside of objectville.
Park guests can choose a hotel and various typ ... lsa kamel elmara el gaya ISA

connect to foxpro DB

 try { // load driver ...
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();

// create connection...
//      String url = "jdbcdbc:TestDBF";
      String url = "jdbc:odbc:FoxProDS";
      Connection con = DriverManager.getConnection(url);

// test sql prepared statement...
      String sql = "SELECT Trkline FROM T1E1INFO";
      PreparedStatement stmt = con.prepareStatement(sql);
      ResultSet rs = stmt.executeQuery();
      String count = "";
      while (rs.next()) {
        count = rs.getString("Trkline");
        System.out.println(count);
      }

      rs.close();
      stmt.close();
      con.close();
    }

    catch (Exception exc) {
      exc.printStackTrace();
    }

الخميس، 23 ديسمبر 2010

What is different between Hibernate and iBatis?


In iBatis Java objects are mapped to the result sets.
IBatis only maps the Java bean properties to database fields and it fetches the database results in the form of Java beans based on configuration.


In Hibernate Java objects are mapped to the database tables.

iBATIS maps Java Objects to the results of SQL Queries whereas Hibernate maps Java Objects directly to
database tables traditional Object-Relational Mapping.

The benefits of Hibernate are that it automatically
generates all the SQL for your and the cache invalidation can be more fine grained.

iBATIS is more flexible
especially if we are a strong SQL query writer. We have control over exactly how the SQL queries are written.

iBATIS uses Data Mapper Pattern whereas Hibernate uses Active Record Pattern
=============================================
BATIS is very simple.
Hibernate is much more complex.

If you are a SQL expert and want to write SQL yourself, choose iBATIS.

But if you don't want to write SQL and you prefer more object-oriented query language and have much time to learn OR-mapping concepts and features, choose Hibernate.

iBATIS is so simple, it is just about XML, SQL, and plain-old objects, nothing more than that.

iBATIS is just a data mapper framework it maps fields in RDBMS tables to attributes in objects while Hibernate is an OR-mapping tool it maps objects to relational database.

Sounds similar, but OR-mapping is higher level than data mapping.
=====================================================
Use iBatis if
You want to create your own SQL's and are willing to maintain them
your environment is driven by relational data model
you have to work existing and complex schema's
Use Hibernate if
your environment is driven by object model and wants generates SQL automatically

The message is,
One size does not fit all the java persistence and the important to know there are other solutions besides the traditional ORMs, and that would be iBatis.
Both the solutions work well, given their specific domain.
Look for the opportunity where you can use both.

What is different between Hibernate and iBatis?


In iBatis Java objects are mapped to the result sets.
IBatis only maps the Java bean properties to database fields and it fetches the database results in the form of Java beans based on configuration.


In Hibernate Java objects are mapped to the database tables.

iBATIS maps Java Objects to the results of SQL Queries whereas Hibernate maps Java Objects directly to
database tables traditional Object-Relational Mapping.

The benefits of Hibernate are that it automatically
generates all the SQL for your and the cache invalidation can be more fine grained.

iBATIS is more flexible
especially if we are a strong SQL query writer. We have control over exactly how the SQL queries are written.

iBATIS uses Data Mapper Pattern whereas Hibernate uses Active Record Pattern
=============================================
BATIS is very simple.
Hibernate is much more complex.

If you are a SQL expert and want to write SQL yourself, choose iBATIS.

But if you don't want to write SQL and you prefer more object-oriented query language and have much time to learn OR-mapping concepts and features, choose Hibernate.

iBATIS is so simple, it is just about XML, SQL, and plain-old objects, nothing more than that.

iBATIS is just a data mapper framework it maps fields in RDBMS tables to attributes in objects while Hibernate is an OR-mapping tool it maps objects to relational database.

Sounds similar, but OR-mapping is higher level than data mapping.
=====================================================
Use iBatis if
You want to create your own SQL's and are willing to maintain them
your environment is driven by relational data model
you have to work existing and complex schema's
Use Hibernate if
your environment is driven by object model and wants generates SQL automatically

The message is,
One size does not fit all the java persistence and the important to know there are other solutions besides the traditional ORMs, and that would be iBatis.
Both the solutions work well, given their specific domain.
Look for the opportunity where you can use both.

الاثنين، 29 نوفمبر 2010

commserver life cycle(client-server sockets)


the basics of sockets

Open a socket.
Open an input stream and output stream to the socket.
Read from and write to the stream according to the server's protocol.
Close the streams.
Close the socket
 =======================
Server
StartServer àcreate new  memberDataObject
          Initialize static strings
memberDataObject.connect ()à do the following
read from file properties and assign values to static strings.
new ConManager (sql_url, sql_userName, sql_password) create
sql_url = "jdbc:microsoft:sqlserver:// sds-2003:1433;DatabaseName= CHILD_help";
sql_userName=sa;
sql_password=sa;
ConManager.makeConnectionPool ();à create pool of 10 connection, closed
ConManager.getConnection ();à take url, username, password, return opened connection

Parse acdconfig=D:\\TeleContact\\Server\\config\\ACDConfig.xml  using saxparse
Add the content of file in array list.
check in debugLevel àconsole or log

StartServerà create new AbstractServer(Integer.parseInt(memberDataObject.port.trim()), 100,
            "com.RequestHandelerClass",mberDataObject.maxQueueLength,
memberDataObject.maxThreads, memberDataObject.maxThreads)
AbstractServer extends Thread

Constructor do :
1)
port=1984
backlog=100     The number of requests to backlog if threads are busy
requestHandlerClassName= com.RequestHandelerClass
maxQueueLength=20
minThreads=20
maxThreads=20
 (2
Create new RequestQueue(requestHandlerClassName,maxQueueLength,               minThreads, maxThreads)
Create the minimum number of threads and but them(Threads) in List/pool
The thread pool that is servicing this request
// so till now for the server run 20 threads started in the background to handle the client requests

AbstractServer.startServer()

Create our Server Socket and start our Thread

In run()
Make socket Accept the next connection
// Listens for a connection to be made to this socket and accepts it. The method blocks until //    a connection is made.
// Log some debugging information

// Add the socket to the RequestQueue (add it to linked list/end of queue thread)

Adds a new object to the end of the queue
See if we have an available thread (from the 20 thread running) to process the request

Yes->notify thread(wake up)    invoke run()   RequestThread
On run()->
 Handle the request
     this.requestHandler.handleRequest(socket);         

AbstractServer->Abstract super class for creating servers
RequestQueue->accepts new requests and processes them with its associated thread pool
RequestThread->extends Thread  / handles incoming requests
agent -->implements Serializable / bean id,name,ext,password,type,user
data  -->implements Serializable / bean code,command,result


RequestHandelerClass-> handel requests from client
            it's instance fields initialized from memberDataObject class that originally loaded from the property file

then get data from objectInputStream from socket then get data.getCode()
and switch

case 1,2,4:  
int updateDatabase(sql),set send data fields
case 3:
ArrayList<bean> select(sql)
Set send instance fields
Case 5:
String getWavePath(int agent_id)
Set send instance fields
Case 6:
Check if file needed to delete is exist or not
Set send instance fields
Case 7:
Check if file exist or not, and if exist check if there are available memory to copy file if yes->
Object getwave(String path)
Set send instance fields
Case 8:
agent getXml(String agent_code)
print agent attributes
Set send instance fields
Case 9:
int fileExist(String wavePath)
Set send instance fields
Case10:
String createFile(String id)
Set send instance fields
Case 11:
int saveAdviceFile(adviceBean advice)
Set send instance fields
Case 12:
Parse url for ACD Config by sax parser and print how many agent have
Set send instance fields
Case 13:
Set send instance fields(and set result=enable)
Case 14:
Change path of file
Set send instance fields
Case 15:
String createFile(String id)               Create file voicemail at internal path
Set send instance fields
Case 16:
int transefer_smdr()
int transeferSmdrFile(String source, String desti)
String increment(String date) increament version

Set send instance fields

Case 17:
Print server time is requested from client
Set send instance fields

Case 18:
client  sent advice text file to be saved in DB advices table
int saveAdviceTextFile(adviceBean advice)
Set send instance fields

Case 19:
client  sent advice text file to be saved server directory
int saveAdviceFile1(adviceBean advice)
Set send instance fields

Case 20:
Client sent wave bean to be saved  in the server
int saveWaveBean(waveBean filewave)
Set send instance fields

Case 21:
Client    request wave file from server
Object getwave(String path)
Set send instance fields

then out.writeObject(send)

==================================
for client Test email me


الخميس، 25 نوفمبر 2010

How to convert JBuilder project files (jpx files) to Eclipse files

*Download Perl from here
setup and restart

Once you've installed perl and rebooted into Windows, bring up a DOS window. It doesn't matter what directory you are in for now. Just type in:
perl -v

Running your first Perl script: Hello World!

Use notepad or some simple text editor (not MS Word!) to create a file with this line in it. You can cut and paste it directly from here:
print "hello world\n";
Save the file as "hello.pl" and turn to your DOS session and type:
perl hello.pl
The screen should show
hello world
right underneath.
Congratulations, you've just run your first perl script!
==========================================
**Converting jpx to eclipse project files.
Place jpx2eclipse.pl into the same directory of the jpx file.
if swing project remove dbswing.jar, jbcl.jar from libraries dependency project and rebuild(from jbuilder)
open cmd --> go to project location then type
ex--> D:\Agent\ChilderenAgent.precvs>jpx2eclipse.pl ChilderenAgent.jpx

Then, in Eclipse, select File > Import... > Existing Projects into Workspace and open the directory containing the JPX file.

in eclipse
project->properties->java build path ->source->add folder ->src
project->properties->java build path -> libraries->add library->dbswing.jar,jbcl.jar
rebuild,run 
==========================================
more about Perl