Saturday, May 25, 2013

How to Debug java Application




How to Debug java Application
------------------------------
1)Right Click Project---> Debug As---> Run/Debug/etc
set the values in Environment Tab--->
Name        :
Value
JAVA_OPTS   :
-server -XX:+UseParallelGC -Xmx768m -XX:MaxPermSize=160m -Djava.awt.headless=true
JPDA_ADDRESS:
: 8001
JPDA_TRANSPORT:
dt_socket

after this Click on   <-- Apply--> button
and  then
Window-->Preferences-->MyEclipse--->Application Servers--->Jboss and jdk jre must be configure there then click on Apply and then -->OK<--


Now Run the application and use f6 f f8 keys.... for debug process

Oracle String Functions

Oracle String Functions
Version 10.2
 
 Have you seen our new Functions page? If not ... Click Here ... for instant access to all Oracle functions
 
ASCII
Get The ASCII Value Of A Character ASCII(ch VARCHAR2 CHARACTER SET ANY_CS) RETURN PLS_INTEGER;
SELECT ASCII('A') FROM dual;
SELECT ASCII('Z') FROM dual;
SELECT ASCII('a') FROM dual;
SELECT ASCII('z') FROM dual;
SELECT ASCII(' ') FROM dual;
 
CASE Related Functions
Upper Case UPPER(ch VARCHAR2 CHARACTER SET ANY_CS)
RETURN VARCHAR2 CHARACTER SET ch%CHARSET;
SELECT UPPER('Dan Morgan') FROM dual;
Lower Case LOWER(ch VARCHAR2 CHARACTER SET ANY_CS)
RETURN VARCHAR2 CHARACTER SET ch%CHARSET;
SELECT LOWER('Dan Morgan') FROM dual;
Initial Letter Upper Case INITCAP(ch VARCHAR2 CHARACTER SET ANY_CS)
RETURN VARCHAR2 CHARACTER SET ch%CHARSET;
SELECT INITCAP('DAN MORGAN') FROM dual;
NLS Upper Case NLS_UPPER(<string_or_column>)
SELECT NLS_UPPER('Dan Morgan', 'NLS_SORT = XDanish')
FROM dual;
NLS Lower Case NLS_LOWER(<string_or_column>)
SELECT NLS_LOWER('Dan Morgan', 'NLS_SORT = XFrench')
FROM dual;
NLS Initial Letter Upper Case NLS_INITCAP(<string_or_column>)
SELECT NLS_INITCAP('DAN MORGAN', 'NLS_SORT = XGerman')
FROM dual;
 
CHR
Character CHR(n PLS_INTEGER) RETURN VARCHAR2;
SELECT(CHR(68) || CHR(65) || CHR(78)) FROM dual;

SELECT(CHR(68) || CHR(97) || CHR(110)) FROM dual;
 
COALESCE
Returns the first non-null occurrence COALESCE(<value>, <value>, <value>, ...)
CREATE TABLE test (
col1  VARCHAR2(1),
col2  VARCHAR2(1),
col3  VARCHAR2(1));

INSERT INTO test VALUES (NULL, 'B', 'C');
INSERT INTO test VALUES ('A', NULL, 'C');
INSERT INTO test VALUES (NULL, NULL, 'C');
INSERT INTO test VALUES ('A', 'B', 'C');

SELECT COALESCE(col1, col2, col3) FROM test;
 
CONCAT
Concatenate (overload 1) CONCAT(left IN VARCHAR2, right IN VARCHAR2) RETURN VARCHAR2
SELECT CONCAT('Dan ', 'Morgan') FROM dual;
Concatenate (overload 2) CONCAT(left IN CLOB, right IN CLOB) RETURN CLOB
set serveroutput on

DECLARE
 c1 CLOB := TO_CLOB('Dan ');
 c2 CLOB := TO_CLOB('Morgan');
 c3 CLOB;
BEGIN
  SELECT CONCAT('Dan ', 'Morgan')
  INTO c3
  FROM dual;

  dbms_output.put_line(c3);
END;
/
 
CONVERT
Converts From One Character Set To Another CONVERT(<character>,<destination_character_set>,
<source_character_set>)
SELECT CONVERT('Ġʠ͠ՠؠA B C D E','US7ASCII','WE8ISO8859P1')
FROM dual;
 
DUMP
Returns The Number Of Bytes And Datatype Of A Value DUMP(<expression>, <return_format>, <start_position>, <length>);
8 Octal
10 Decimal
16 Hexidecimal
17 Single Characters
1008 octal notation with the character set name
1010 decimal notation with the character set name
1016 hexadecimal notation with the character set name
1017 single characters with the character set name
set linesize 121
col dmp format a50

SELECT table_name, DUMP(table_name) DMP FROM user_tables;

SELECT table_name, DUMP(table_name, 16) DMP FROM user_tables;

SELECT table_name, DUMP(table_name, 16, 7, 4) DMP FROM user_tables;
 
INSTR
See links at page bottom
 
INSTRB
Location of a string, within another string, in bytes INSTRB(
STR1 VARCHAR2 CHARACTER SET ANY_CS,        -- test string
STR2 VARCHAR2 CHARACTER SET STR1%CHARSET,  -- string to locate
POS  PLS_INTEGER := 1,                     -- position
NTH  POSITIVE := 1)                        -- occurrence number
RETURN PLS_INTEGER;
SELECT INSTRB('Dan Morgan', ' ', 1, 1) FROM dual;
 
INSTRC
Location of a string, within another string, in Unicode complete characters INSTRC(
STR1 VARCHAR2 CHARACTER SET ANY_CS,        -- test string
STR2 VARCHAR2 CHARACTER SET STR1%CHARSET,  -- string to locate
POS  PLS_INTEGER := 1,                     -- position
NTH  POSITIVE := 1)                        -- occurrence number
RETURN PLS_INTEGER;
SELECT INSTRC('Dan Morgan', ' ', 1, 1) FROM dual;
 
INSTR2
Location of a string, within another string, in UCS2 code points INSTR2(
STR1 VARCHAR2 CHARACTER SET ANY_CS,        -- test string
STR2 VARCHAR2 CHARACTER SET STR1%CHARSET,  -- string to locate
POS  PLS_INTEGER := 1,                     -- position
NTH  POSITIVE := 1)                        -- occurrence number
RETURN PLS_INTEGER;
SELECT INSTR2('Dan Morgan', ' ', 1, 1) FROM dual;
 
INSTR4
Location of a string, within another string, in UCS4 code points INSTR4(
STR1 VARCHAR2 CHARACTER SET ANY_CS,        -- test string
STR2 VARCHAR2 CHARACTER SET STR1%CHARSET,  -- string to locate
POS  PLS_INTEGER := 1,                     -- position
NTH  POSITIVE := 1)                        -- occurrence number
RETURN PLS_INTEGER;
SELECT INSTR4('Dan Morgan', ' ', 1, 1) FROM dual;
 
LENGTH
String Length LENGTH(<string_or_column>)
SELECT LENGTH('Dan Morgan') FROM dual;
 
LENGTHB
Returns length in bytes LENGTHB(<char_varchar2_or_clob_value>)
SELECT table_name, LENGTHB(table_name) FROM user_tables;
Note: Additional forms of LENGTH (LENGTHC, LENGTH2, and LENGTH4) are also available.
 
LPAD
Left Pad

Overload 1
LPAD(
str1 VARCHAR2 CHARACTER SET ANY_CS,
len  PLS_INTEGER,
PAD  VARCHAR2 CHARACTER SET STR1%CHARSET)
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
SELECT LPAD('Dan Morgan', 25, 'x') FROM dual;
Overload 2 LPAD(
str1 VARCHAR2 CHARACTER SET ANY_CS,
len  PLS_INTEGER)
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
SELECT LPAD('Dan Morgan', 25) FROM dual;
Overload 3 LPAD(
str1 CLOB CHARACTER SET ANY_CS,
len  NUMBER,
PAD  CLOB CHARACTER SET STR1%CHARSET)
RETURN CLOB CHARACTER SET STR1%CHARSET;
TBD
Overload 4 LPAD(
str1 CLOB CHARACTER SET ANY_CS,
len  INTEGER)
RETURN CLOB CHARACTER SET STR1%CHARSET;
TBD
 
LTRIM
Left Trim

Overload 1
LTRIM(
str1 VARCHAR2 CHARACTER SET ANY_CS := ' ',
tset VARCHAR2 CHARACTER SET STR1%CHARSET)
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
SELECT '->' || LTRIM('   Dan Morgan   ') || '<-' FROM dual;
Overload 2 LTRIM(
STR1 VARCHAR2 CHARACTER SET ANY_CS := ' ')
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
SELECT '->' || LTRIM('xxx Dan Morgan   ') || '<-' FROM dual;

SELECT '->' || LTRIM('xxxDan Morgan   ', 'x') || '<-' FROM dual;
 
MAX
The Maximum String based on the current sort parameter MAX(<character_string>)
SELECT MAX(table_name)
FROM user_tables;
 
MIN
The Minimum String based on the current sort parameter MIN(<character_string>)
SELECT MIN(table_name)
FROM user_tables
 
NLSSORT
Returns the string of bytes used to sort a string.

The string returned is of RAW data type
NLSSORT(<column_name>, 'NLS_SORT = <NLS Parameter>);
CREATE TABLE test (name VARCHAR2(15));
INSERT INTO test VALUES ('Gaardiner');
INSERT INTO test VALUES ('Gaberd');
INSERT INTO test VALUES ('G⢥rd');
COMMIT;

SELECT * FROM test ORDER BY name;

SELECT * FROM test
ORDER BY NLSSORT(name, 'NLS_SORT = XDanish');

SELECT * FROM test
ORDER BY NLSSORT(name, 'NLS_SORT = BINARY_CI');
 
Quote Delimiters
q used to define a quote delimiter for PL/SQL q'<delimiter><string><delimiter>';
set serveroutput on

DECLARE
 s1 VARCHAR2(20);
 s2 VARCHAR2(20);
 s3 VARCHAR2(20);
BEGIN
  s1 := q'[Isn't this cool]';
  s2 := q'"Isn't this cool"';
  s3 := q'|Isn't this cool|';

  dbms_output.put_line(s1);
  dbms_output.put_line(s2);
  dbms_output.put_line(s3);
END;
/
 
REPLACE
See links at page bottom
 
REVERSE
Reverse REVERSE(<string_or_column>)
SELECT REVERSE('Dan Morgan') FROM dual;

SELECT DUMP('Dan Morgan') FROM dual;
SELECT DUMP(REVERSE('Dan Morgan')) FROM dual;
 
RPAD
Right Pad

Overload 1
RPAD(str1 VARCHAR2 CHARACTER SET ANY_CS, len PLS_INTEGER,
pad VARCHAR2 CHARACTER SET STR1%CHARSET)
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
SELECT RPAD('Dan Morgan', 25, 'x') FROM dual;
Overload 2 RPAD(str1 VARCHAR2 CHARACTER SET ANY_CS, len PLS_INTEGER)
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
SELECT RPAD('Dan Morgan', 25) ||'<-' FROM dual;
 
RTRIM
Right Trim

Overload 1
RTRIM(
str1 VARCHAR2 CHARACTER SET ANY_CS := ' ',
tset VARCHAR2 CHARACTER SET STR1%CHARSET)
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
SELECT '->' || RTRIM('   Dan Morganxxx') || '<-' FROM dual;
SELECT '->' || RTRIM('   Dan Morganxxx', 'xxx') || '<-' FROM dual;
Overload 2 RTRIM(
str1 VARCHAR2 CHARACTER SET ANY_CS := ' ')
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
SELECT '->' || RTRIM('   Dan Morgan   ') || '<-' FROM dual;
 
SOUNDEX

Returns Character String Containing The Phonetic Representation Of Another String
Rules:
  • Retain the first letter of the string and remove all other occurrences of the following letters: a, e, h, i, o, u, w, y
  • Assign numbers to the remaining letters (after the first) as
    follows:
    b, f, p, v = 1
    c, g, j, k, q, s, x, z = 2
    d, t = 3
    l = 4
    m, n = 5
    r = 6
  • If two or more letters with the same number were adjacent in the original name (before step 1), or adjacent except for any intervening h and w, then omit all but the first.
  • Return the first four bytes padded with 0.
SOUNDEX(ch VARCHAR2 CHARACTER SET ANY_CS)
RETURN VARCHAR2 CHARACTER SET ch%CHARSET;
CREATE TABLE test (
namecol VARCHAR2(15));

INSERT INTO test (namecol) VALUES ('Smith');
INSERT INTO test (namecol) VALUES ('Smyth');
INSERT INTO test (namecol) VALUES ('Smythe');
INSERT INTO test (namecol) VALUES ('Smither');
INSERT INTO test (namecol) VALUES ('Smidt');
INSERT INTO test (namecol) VALUES ('Smick');
INSERT INTO test (namecol) VALUES ('Smiff');
COMMIT;

SELECT name, SOUNDEX(namecol) FROM test;
-- Thanks Frank van Bortel for the idea for the above

SELECT *
FROM test
WHERE SOUNDEX(namecol) = SOUNDEX('SMITH');
 
SUBSTR
See links at page bottom
 
SUBSTRB
Returns a substring counting bytes rather than characters SUBSTRB(
STR1 VARCHAR2 CHARACTER SET ANY_CS,
POS  PLS_INTEGER,                -- starting position
LEN  PLS_INTEGER := 2147483647)  -- number of characters
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
See Demos on the Substring Page
 
SUBSTRC
Returns a substring within another string, using Unicode code points SUBSTRC(
STR1 VARCHAR2 CHARACTER SET ANY_CS,
POS  PLS_INTEGER,                -- starting position
LEN  PLS_INTEGER := 2147483647)  -- number of characters
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
See Demos on the Substring Page
 
SUBSTR2
Returns a substring within another string, using UCS2 code points SUBSTR2(
STR1 VARCHAR2 CHARACTER SET ANY_CS,
POS  PLS_INTEGER,                -- starting position
LEN  PLS_INTEGER := 2147483647)  -- number of characters
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
See Demos on the Substring Page
 
SUBSTR4
Returns a substring within another string, using UCS4 code points SUBSTR4(
STR1 VARCHAR2 CHARACTER SET ANY_CS,
POS  PLS_INTEGER,                -- starting position
LEN  PLS_INTEGER := 2147483647)  -- number of characters
RETURN VARCHAR2 CHARACTER SET STR1%CHARSET;
See Demos on the Substring Page
 
TRANSLATE
See links at page bottom
 
TREAT
Changes The Declared Type Of An Expression TREAT (<expression> AS REF schema.type)) 
SELECT name, TREAT(VALUE(p) AS employee_t).salary SALARY
FROM persons p;
 
TRIM (variations are LTRIM and RTRIM)
Trim Spaces TRIM(<string_or_column>)
SELECT '   Dan Morgan    ' FROM dual;

SELECT TRIM('   Dan Morgan   ') FROM dual;
Trim Other Characters TRIM(<character_to_trim> FROM <string_or_column>)
SELECT TRIM('D' FROM 'Dan Morgan') FROM dual;
Trim By CHR value TRIM(<string_or_column>)
SELECT ASCII(SUBSTR('Dan Morgan',1,1)) FROM dual;

SELECT TRIM(CHR(68) FROM 'Dan Morgan') FROM dual;
 
Vertical Bars
Also known as Pipes <first_string> || <second_string>
SELECT 'Dan' || ' ' || 'Morgan' FROM dual;

with alias

SELECT 'Dan' || ' ' || 'Morgan' NAME FROM dual;
or
SELECT 'Dan' || ' ' || 'Morgan' AS NAME FROM dual;
 
VSIZE
Byte Size VSIZE(e IN VARCHAR2) RETURN NUMBER
SELECT VSIZE('Dan Morgan') FROM dual;
 
Related Topics
CASE
DBMS_LOB
Decode
Instring
Miscellaneous Functions
Operators (Built-in)
Regular Expressions
Replace
Substring
Translate
XML Functions
 
Contact Us ? Legal Notices and Terms of Use ? Privacy Statement

string-methods.doc


·         Hi Java Guys,

Read this article, its worth it.

Writing toString Methods

One of the standard methods defined in java.lang.Object is toString. This method is used to obtain a string representation of an object. You can (and normally should) override this method for classes that you write. This tip examines some of the issues around using toString.
Let's first consider some sample code:

class MyPoint {

private final int x, y;

public MyPoint(int x, int y) {

this.x = x;

this.y = y;

}

}

public class TSDemo1 {

public static void main(String args[]) {

MyPoint mp = new MyPoint(37, 47);

// use default Object.toString( )

System.out.println( mp);

// same as previous, showing the

// function of the default toString()

System.out.println( mp.getClass( ).getName( )

+ "@"

+ Integer.toHexString (mp.hashCode( )));

// implicitly call toString() on object

// as part of string concatenation

String s = mp + " testing";

System.out.println( s);

// same as previous, except object

// reference is null

mp = null;

s = mp + " testing";

System.out.println( s);

}

}
The TSDemo1 program defines a class MyPoint to represent X,Y points. It does not define a toString method for the class. The program creates an instance of the class and then prints it. When you run TSDemo1, you should see a result that looks something like this:

MyPoint@111f71

MyPoint@111f71

MyPoint@111f71 testing

null testing
You might wonder how it's possible to print an arbitrary class object. The library methods such as System.out.println know nothing about the MyPoint class or its objects. So how is it possible to convert such an object to string form and then print it, as the first output statement in TSDemo1 does?
The answer is that println calls the java.io.PrintStream .print(Object) method, which then calls the String.valueOf method. The String.valueOf method is very simple:

public static String valueOf(Object obj) {

return (obj == null) ? "null" : obj.toString( );

}
When println is called with a MyPoint object reference, the String.valueOf method converts the object to a string. String.valueOf first checks to make sure that the reference is not null. It then calls the toString method for the object. Since the MyPoint class has no toString method, the default one in java.lang.Object is used instead.
What does the default toString method actually return as a string value? The format is illustrated in the second print statement above. The name of the class, an "@", and the hex version of the object's hashcode are concatenated into a string and returned. The default hashCode method in Object is typically implemented by converting the memory address of the object into an integer. So your results might vary from those shown above.
The third and fourth parts of the TSDemo1 example illustrate a related idea: when you use "+" to concatenate a string to an object, toString is called to convert the object to a string form. You need to look at the bytecode expansion for TSDemo1 to see that. You can look at the bytecode for TSDemo1 (that is, in a human-readable form) by issuing the javap command as follows:
javap -c . TSDemo1
If you look at the bytecode, you'll notice that part of it involves creating a StringBuffer object, and then using StringBuffer. append(Object) to append the mp object to it. StringBuffer. append(Object) is implemented very simply:

public synchronized StringBuffer append(Object obj) {

return append(String. valueOf(obj) );

}
As mentioned earlier, String.valueOf calls toString on the object to get its string value.
O.K., so much for invoking the default toString method. How do you write your own toString methods? It's really very simple. Here's an example:

class MyPoint {

private final int x, y;

public MyPoint(int x, int y) {

this.x = x;

this.y = y;

}

public String toString() {

return x + " " + y;

}

}

public class TSDemo2 {

public static void main(String args[]) {

MyPoint mp = new MyPoint(37, 47);

// call MyPoint.toString( )

System.out.println( mp);

// call toString() and

// extract the X value from it

String s = mp.toString( );

String t = s.substring( 0, s.indexOf(' '));

int x = Integer.parseInt( t);

System.out.println( t);

}

}
When you run the TSDemo2 program, the output is: 37 47 37
The toString method in this example does indeed work, but there are a couple of problems with it. One is that there is no descriptive text displayed in the toString output. All you see is a cryptic "37 47". The other problem is that the X,Y values in MyPoint objects are private. There is no other way to get at them except by picking apart the string returned from toString. The second part of the TSDemo2 example shows the code required to extract the X value from the string. Doing it this way is error-prone and inefficient.
Here's another approach to writing a toString method, one that clears up the problems in the previous example:

class MyPoint {

private final int x, y;

public MyPoint(int x, int y) {

this.x = x;

this.y = y;

}

public String toString() {

return "X=" + x + " " + "Y=" + y;

}

public int getX() {

return x;

}

public int getY() {

return y;

}

}

public class TSDemo3 {

public static void main(String args[]) {

MyPoint mp = new MyPoint(37, 47);

// call MyPoint.toString( )

System.out.println( mp);

// get X,Y values via accessor methods

int x = mp.getX();

int y = mp.getY();

System.out.println( x);

System.out.println( y);

}

}

The output is:

X=37 Y=47

37

47
This example adds some descriptive text to the output format, and defines a couple of accessor methods to get at the X,Y values. In general, when you write a toString method, the format of the string that is returned should cover all of the object contents. Your toString method should also contain descriptive labels for each field. And there should be a way to get at the object field values without having to pick apart the string. Note that using "+" within toString to build up the return value is not necessarily the most efficient approach. You might want to use StringBuffer instead.
Primitive types in the Java programming language, such as int, also have toString methods, for example Integer.toString( int). What about arrays? How can you convert an array to a string? You can assign an array reference to an Object reference, but arrays are not really classes. However, it is possible to use reflection to implement a toString method for arrays. The code looks like this:

import java.lang.reflect. *;

public class TSDemo4 {

public static String toString(Object arr) {

// if object reference is null or not

// an array, call String.valueOf( )

if (arr == null ||

!arr.getClass( ).isArray( )) {

return String.valueOf( arr);

}

// set up a string buffer and

// get length of array

StringBuffer sb = new StringBuffer( );

int len = Array.getLength( arr);

sb.append('[ ');

// iterate across array elements

for (int i = 0; i < len; i++) {

if (i > 0) {

sb.append(', ');

}

// get the i-th element

Object obj = Array.get(arr, i);

// convert it to a string by

// recursive toString() call

sb.append(toString( obj));

}

sb.append('] ');

return sb.toString( );

}

public static void main(String args[]) {

// example #1

System.out.println( toString( "testing" ));

// example #2

System.out.println( toString( null));

// example #3

int arr3[] = new int[]{

1,

2,

3

};

System.out.println( toString( arr3));

// example #4

long arr4[][] = new long[][]{

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

System.out.println( toString( arr4));

// example #5

double arr5[] = new double[0];

System.out.println( toString( arr5));

// example #6

String arr6[] = new String[]{

"testing",

null,

"123"

};

System.out.println( toString( arr6));

// example #7

Object arr7[] = new Object[]{

new Object[]{null, new Object(), null},

new int[]{1, 2, 3},

null

};

System.out.println( toString( arr7));

}

}
The TSDemo4 program creates a toString method, and then passes the toString method an arbitrary Object reference. If the reference is null or does not refer to an array, the program calls the String.valueOf method. Otherwise, the Object refers to an array. In that case, TSDemo4 uses reflection to access the array elements. Array.getLength and Array.get are the key methods that operate on the array. After an element is retrieved, the program calls toString recursively to obtain the string for the element. Doing it this way ensures that multidimensional arrays are handled properly.
The output of the TSDemo4 program is:

testing

null

[1,2,3]

[[1,2,3],[4, 5,6],[7,8, 9]]

[]

[testing,null, 123]

[[null,java. lang.Object@ 111f71,null] ,[1,2,3], null]
Obviously, if you have a huge array, and you call toString, it will use a lot of memory, and the resulting string might not be particularly useful or readable by a human.


All The Best

Have a Nice Day .

Thanks&Regards
Vamsikrishna Venigalla
9949127050

The Solution for every problem is to begin



Implementing Session Facade - Session Bean

Example 8.15 Implementing Session Facade - Session Bean

package corepatterns.apps.psa.ejb;

import java.util.*;
import java.rmi.RemoteException;
import javax.ejb.*;
import javax.naming.*;
import corepatterns.apps.psa.core.*;
import corepatterns.util.ServiceLocator;
import corepatterns.util.ServiceLocatorException;

// Note: all try/catch details not shown for brevity.

public class ProjectResourceManagerSession
  implements SessionBean {

  private SessionContext context;

  // Remote references for the
  // entity Beans encapsulated by this facade
  private Resource resourceEntity = null;
  private Project projectEntity = null;
  ...

  // default create
  public void ejbCreate()
  throws CreateException {
  }

  // create method to create this facade and to
  // establish connections to the required entity
  // beans
  // using primary key values
  public void ejbCreate(
    String resourceId, String projectId, ...)
  throws CreateException, ResourceException {

    try {
      // locate and connect to entity beans
      connectToEntities(resourceId, projectId, ...);
    } catch(...) {
      // Handle exceptions
    }
  }

  // method to connect the session facade to its
  // entity beans using the primary key values
  private void connectToEntities (
    String resourceId, String projectId)
  throws ResourceException {
    resourceEntity = getResourceEntity(resourceId);
    projectEntity = getProjectEntity(projectId);
    ...
  }

  // method to reconnect the session facade to a
  // different set of entity beans using primary key
  // values
  public resetEntities(String resourceId,
    String projectId, ...)
  throws PSAException {

    connectToEntities(resourceId, projectId, ...);
  }

  // private method to get Home for Resource
  private ResourceHome getResourceHome()
  throws ServiceLocatorException {
    return ServiceLocator.      getInstance().getHome(
        "ResourceEntity", ResourceHome.class);
  }

  // private method to get Home for Project
  private ProjectHome getProjectHome()
  throws ServiceLocatorException {
    return ServiceLocator.      getInstance().getHome(
        "ProjectEntity", ProjectHome.class); 
  }

  // private method to get Resource entity
  private Resource getResourceEntity(
    String resourceId)   throws ResourceException {
    try {
      ResourceHome home = getResourceHome();
      return (Resource)
        home.findByPrimaryKey(resourceId);
    } catch(...) {
      // Handle exceptions
    }
  }

  // private method to get Project entity
  private Project getProjectEntity(String projectId)
  throws ProjectException {
    // similar to getResourceEntity
    ...
  }

  // Method to encapsulate workflow related
  // to assigning a resource to a project.
  // It deals with Project and Resource Entity beans
  public void assignResourceToProject(int numHours)
  throws PSAException {

    try {
      if ((projectEntity == null) ||
          (resourceEntity == null)) {

        // SessionFacade not connected to entities
        throw new PSAException(...);
      }

      // Get Resource data
      ResourceTO resourceTO =
          resourceEntity.getResourceData();

      // Get Project data
      ProjectTO projectTO =
        projectEntity.getProjectData();
      // first add Resource to Project
      projectEntity.addResource(resourceTO);
      // Create a new Commitment for the Project
      CommitmentTO commitment = new
        CommitmentTO(  ...);

      // add the commitment to the Resource
      projectEntity.addCommitment(commitment);

    } catch(...) {
      // Handle exceptions
    }
  }

  // Similarly implement other business methods to
  // facilitate various use cases/interactions
  public void unassignResourceFromProject()
  throws PSAException {
    ...
  }

  // Methods working with ResourceEntity
  public ResourceTO getResourceData()
  throws ResourceException {
    ...
  }

  // Update Resource Entity Bean
  public void setResourceData(ResourceTO resource)
  throws ResourceException {
    ...
  }

  // Create new Resource Entity bean
  public ResourceTO createNewResource(ResourceTO
    resource)   throws ResourceException {
    ...
  }

  // Methods for managing resource's blockout time
  public void addBlockoutTime(Collection blockoutTime)
  throws RemoteException,BlockoutTimeException {
    ...
  }
 
  public void updateBlockoutTime(
    Collection blockoutTime)  
  throws RemoteException, BlockoutTimeException {
    ...
  }
 
  public Collection getResourceCommitments()
  throws RemoteException, ResourceException {
    ...
  }

  // Methods working with ProjectEntity
  public ProjectTO getProjectData()
  throws ProjectException {
    ...
  }

  // Update Project Entity Bean
  public void setProjectData(ProjectTO project)
  throws ProjectException {
    ...
  }

  // Create new Project Entity bean
  public ProjectTO createNewProject(ProjectTO project)
  throws ProjectException {
    ...
  }

  ...

  // Other session facade method examples

  // This proxies a call to a Transfer Object Assembler
  // to obtain a composite Transfer Object.
  // See Transfer Object Assembler pattern
  public ProjectCTO getProjectDetailsData()
  throws PSAException {
    try {
      ProjectTOAHome projectTOAHome = (ProjectTOAHome)
        ServiceLocator.getInstance().getHome(
          "ProjectTOA", ProjectTOAHome.class);
      // Transfer Object Assembler session bean
      ProjectTOA projectTOA =
          projectTOAHome.create(...);
      return projectTOA.getData(...);
    } catch (...) {
        // Handle / throw exceptions
    }
  }

  // These method proxies a call to a ValueListHandler
  // to get a list of projects. See Value List Handler
  // pattern.
  public Collection getProjectsList(Date start,
  Date end) throws PSAException {
    try {
      ProjectListHandlerHome projectVLHHome =
        (ProjectVLHHome)
          ServiceLocator.getInstance().getHome(
            "ProjectListHandler",
            ProjectVLHHome.class);
      // Value List Handler session bean
      ProjectListHandler projectListHandler =
        projectVLHHome.create();
      return projectListHandler.getProjects(
                    start, end);
    } catch (...) {
        // Handle / throw exceptions
    }
  }

  ...

  public void ejbActivate() {
    ...
  }

  public void ejbPassivate() {
    context = null;
  }

  public void setSessionContext(SessionContext ctx) {
       this.context = ctx;
  }

  public void ejbRemove() {
    ...
  }
}


The remote interface for the Session Facade is listed in Example 8.16.

Example 8.16 Implementing Session Facade - Remote Interface

package corepatterns.apps.psa.ejb;

import java.rmi.RemoteException;
import javax.ejb.*;
import corepatterns.apps.psa.core.*;

// Note: all try/catch details not shown for brevity.

public interface ProjectResourceManager
  extends EJBObject {

  public resetEntities(String resourceId,
  String projectId, ...)
  throws RemoteException, ResourceException ;

  public void assignResourceToProject(int numHours)
  throws RemoteException, ResourceException ;

  public void unassignResourceFromProject()
  throws RemoteException, ResourceException ;

  ...

  public ResourceTO getResourceData()
  throws RemoteException, ResourceException ;

  public void setResourceData(ResourceTO resource)
  throws RemoteException, ResourceException ;

  public ResourceTO createNewResource(ResourceTO resource)
  throws ResourceException ;

  public void addBlockoutTime(Collection blockoutTime)
  throws RemoteException,BlockoutTimeException ;
 
  public void updateBlockoutTime(Collection blockoutTime)
  throws RemoteException,BlockoutTimeException ;
 
  public Collection getResourceCommitments()
  throws RemoteException, ResourceException;

  public ProjectTO getProjectData()
  throws RemoteException, ProjectException ;
 
  public void setProjectData(ProjectTO project)
  throws RemoteException, ProjectException ;

  public ProjectTO createNewProject(ProjectTO project)
  throws RemoteException, ProjectException ;

  ...

  public ProjectCTO getProjectDetailsData()
  throws RemoteException, PSAException ;

  public Collection getProjectsList(Date start,
  Date end) throws RemoteException, PSAException ;

  ...
}


The Home interface for the Session Facade is shown in Example 8.17.

Example 8.17 Implementing Session Facade - Home Interface

package corepatterns.apps.psa.ejb;

import javax.ejb.EJBHome;
import java.rmi.RemoteException;
import corepatterns.apps.psa.core.ResourceException;
import javax.ejb.*;

public interface ProjectResourceManagerHome
extends EJBHome {
   
    public ProjectResourceManager create()
            throws RemoteException,CreateException;
    public ProjectResourceManager create(String
        resourceId, String projectId, ...)
            throws RemoteException,CreateException;
}