Upload
dominion
View
2.026
Download
0
Embed Size (px)
Citation preview
®
"It Takes Two to Tango" - Learning Java Using the Eclipse Development PlatformJMP-202
Paul T. Calhoun – NetNotes Solutions Unlimited, Inc.
John Kidd – Kiddcorp, L.P.
Your Presenters – This Is Us!
Paul T. CalhounChief Technology OfficerNetNotes Solutions Unlimited
Paul Calhoun, ND 6 & 7 PCLI and PCLP,is a highly rated speaker who provides customer-focused Java classroom instruction and consulting to Fortune 100 and 500 companies, as well as many SMBs. Paul currently builds Domino, Web, Java, and XML applications for hiscustomers using Domino and WebSphere.
He co-authored the IBM Redbook “XML Powered by Domino,” and has developed several online XML and Java programming courses. He has written articles for both “The View” and “The Sphere”technical publications.
Your Presenters – This Is Us!
John KiddPresidentKiddcorp, L.P.
John Kidd is a recognized strategist, speaker and author in the area of Java and J2EE technologies. John has more than 15 years experience in architecting and delivering line of business applications for companies such as Belo, IBM/Lotus, Texas Instruments, and Advanced PCS.
John has been an early adopter in delivering key technologies and delivery methods. He is a frequent speaker and trainer on advanced technologies and a consultant for organizations developing open source strategies.
Agenda
Roadmap
Eclipse, The Tool
Java language Fundamentals
Developing Java code In Eclipse
Develop and Deploy Lotus Domino Java code using the Eclipse development platform
Develop plug-ins in Eclipse
Wrap Up
Agenda
Roadmap
Eclipse, The Tool
Java language Fundamentals
Developing Java code In Eclipse
Develop and Deploy Lotus Domino Java code using the Eclipse development platform
Develop plug-ins in Eclipse
Wrap Up
Roadmap
Learning Java is like eating an Elephant !!
It’s a big job and there’s no clear place where to start !!
Roadmap
Start Here! J2SE
Servlets, JSPs & JSFs
J2EE, XML
Roadmap
Start with J2SE (Java 2 STANDARD Edition)This covers core Java functionality
SyntaxData TypesConstructsCore Classes– java.lang– java.io– java.net– etc.
Allow 3-6 Months
http://java.sun.com/j2se/index.jsp
Roadmap
Learn XML (not part of Sun Certification)XML SyntaxDTD/XML SchemaXSL
XSLTXSL:FO
Finally jump on the J2EE bandwagon (In this order)ServletsJSPsJSFs Allow another 3-6 months
Then the rest of the J2EE specificationAllow another 3-6 months
Roadmap
Start smallJava Agents in Domino
Graduate to ServletsAgent Code transitioned to Servlets running on Domino
Incorporate an external Servlet/JSP engineApache w/Tomcat add-inJBOSSWebSphere Application Server
Write JSP/JSF applications that access Domino data
Roadmap
What NOT to doStart Learning Java with J2EE applications (Servlets, JSPs)Try and start with a EJBsLearn Java in conjunction with a HUGE Mission critical project
Agenda
Roadmap
Eclipse, The Tool
Java language Fundamentals
Developing Java code In Eclipse
Develop and Deploy Lotus Domino Java code using the Eclipse development platform
Develop plug-ins in Eclipse
Wrap Up
Eclipse, The Tool
Installing Eclipse
Updating Eclipse
Configuring Eclipse
Navigating Eclipse
Creating Projects
Installing Eclipse
Steps to Install EclipseDownload a Java SDK FIRST
Level 1.4.2 or higherInstall Java SDK
Download Eclipse 3.2.xwww.eclipse.org/downloads/Supported Platforms– Windows– Linux– Solaris 8– AIX– HP-UX– Max OSX
Installing Eclipse
You must have at least one Java SDK installed on your machine BEFORE installing the Eclipse workbench
Must be version 1.4.2 or above (J2SE 5 or 6)
If supporting multiple installed SDKsInstall oldest to newest
Installing Java 5 or 6 will allow you to write code that conforms to older JRE
http://java.sun.com/javase/downloads/index.jsp
Installing Eclipse
Download Eclipse 3.2.xIt will be .zip fileUnzip the contents to a directory on the hard drive
Start EclipseEclipse.exe (Windows)First time Eclipse starts it will search for an installed SDK and add it to the workbench configuration
Only the currently configured JRE will be added to the workbenchconfigurationOthers can be added (See configuration slides)
Installing Eclipse
Eclipse start up screen
Installing Eclipse
The Eclipse Workbench with the default Java Perspective
Updating Eclipse
The first thing after the Eclipse workbench is started is to check for software updates
From the “Help” menu choose “Software Updates > Find and Install…”
Updating Eclipse
In the Feature Updates Dialog box there are two optionsSearch for updates of the currently installed features
Allows you to update all currently installed feature functionalitySearch for new features to install
Allows you to add additional functionality to the Eclipse Workbench– Like the Web Tools Plug-in
Updating Eclipse
If “Search for new features to install” is selected you will see the following dialog box
Updating Eclipse
The Callistro Discovery Site is a combination of Eclipse projects in one Site installation site
Check the values for the functionality you want to install and click the Next button
Updating Eclipse
You will need to run Software updateAfter every newly installed featureAt least once a QuarterPreferably once a month
Configuring Eclipse
Configuration changes that affect the entire workbench are done via the “Preferences” dialog box
From the “Window” menu choose “Preferences”
Configuring Eclipse
Expand the preferences in the column on the left to access the preferences for that category
Configuring Eclipse
Common preference changesChange Font for editors and dialogs
General > Appearance > Colors and Fonts– Choose “Basic” select “Text Font”
Prompt for workspace on startupGeneral > Startup and Shutdown
Default Web Browser to useGeneral > Web Browser
Enable HTTP Proxy ConnectionInstall/Update– Proxy Settings
Internet Proxy SettingsInternet > Proxy Settings
Configuring Eclipse
Common preference changes (Cont)Configure additional JREs
Java > Installed JREs– Click the Add button and navigate to install directory– You can add the Domino 6.x or 7.x JVM to the Installed JREs in Eclipse
to use on Domino only projects
Configuring Eclipse
Common preference changes (Cont)Add Runtime Test Server
Server > Installed Runtimes– Click “Add” and browse to installation of runtime test server
– IBM WebSphere Application Server– Apache w/Tomcat add-in– JBOSS– Oracle– BEA WebLogic
Navigating Eclipse
Eclipse is made up ofPerspectives
Allows developer to focus on particular development type– Java– J2EE– Debug– Plug-in– Resource
ViewsDisplays functionality with-in a perspective– Package Explorer– Problems
EditorsAllows for development of a particular code type– Java– HTML, CSS, JavaScript, XML, etc.
Navigating Eclipse
Switch between perspectives using the Perspective bar in the upper right hand corner of the workbench
Views in Perspectives can be dragged/dropped to any area of the perspective
Additional views can be added via the menu “Window > Show View”
Views can be removed from a perspective by click on the “X” in the upper right corner of a view
Any View (Including Editor Windows) can be Maximized/Restored by double clicking on the tab that displays the view/editor title
If you totally FUBAR a perspective you can always restore it to the original via the menu “Window > Reset Perspective”
Navigating Eclipse
The default Java Perspective
Perspective Bar
Views
Editor Window
Creating Projects
The type of Project that can be created in Eclipse is based upon the features that have been added
“Out of the Box” Eclipse can only create the following project typesJavaPlug-inResourceCVS
With Additional Features from the Callistro or other Eclipse/Third Party add ins
Web Static Web ProjectDynamic Web Project
J2EEEnterprise Application ProjectApplication Client Project
Creating Projects
All projects are created via the New Project WizardFile > New Project
Eclipse Workbench
Agenda
Roadmap
Eclipse, The Tool
Java language Fundamentals
Developing Java code In Eclipse
Develop and Deploy Lotus Domino Java code using the Eclipse development platform
Develop plug-ins in Eclipse
Wrap Up
Java History
Originally was called the “Oak”
Was intended to be used in consumer electronicsPlatform independence was one of the requirementsBased on C++, with influences from other OO languages (Smalltalk, Eiffel …)
Started gaining popularity in 1995Renamed to “Java”Was a good fit for the Internet applications
Portability
Java is a platform independent languageJava code can run on any platformPromotes the idea of writing the code on one platform and running it on any other
Java source code is stored in .java files
Compiler compiles code into .class filesThe compiled code is the bytecode that can run on any platformBytecode is what makes Java platform independent
Bytecode is not machine code
Java Virtual Machine (JVM)Platform specific - Processes bytecode at runtime by translating bytecode into machine code
Memory Management
Automatic garbage collection is built into the languageNo explicit memory management is requiredOccurs whenever memory is requiredCan be forced programmaticallyGarbage collector frees memory from objects that areno longer in use
Distributed Systems
Java provides low level networkingTCP/IP support, HTTP, and sockets
Java also provides higher level networkingRemote Method Invocation (RMI) is Java’s distributed protocol
Used for communication between objects that reside in different Virtual MachinesCommonly used in J2EE (Java 2 Enterprise Edition) Application Server
CORBA could also be used with Java
Identifiers
Used for naming classes, interfaces, methods, variables, fields, and parameters
Can contain letters, digits, underscores, or dollar-signs
There are some rules that apply:First character in the identifier cannot be a digit
Can be a letter, underscore, or dollar signLiterals true, false, and null cannot be usedReserved words cannot be used
And it is Case Sensitive!
Expressions
Statements are the basic Java expressionsSemicolon (;) indicates the end of a statement
HomePolicy homePolicy;double premium; premium = 100.00;homePolicy = new HomePolicy();homePolicy.setAnnualPremium(premium);
variable declaration
variable assignment
object creation
message sending
Comments
/** Javadoc example comment.* Used for generation of the documentation.*/
/* Multiple line comment.**/
// Single line comment.
Literals
Represent hardcoded values that do not change
Typical example are string literalsWhen used, compiler creates an instance of String class
String one = "One";String two = "Two";
String one = new String("One");String two = new String("Two");
Java and Types
There are two different types in JavaPrimitive data typeReference type
It is said that Java is a strongly typed languageFields, variables, method parameters, and returns musthave a type
double premium; HomePolicy homePolicy;
variable type
variable name
Primitives
Primitives represent simple data in Java
Primitives are not objects in JavaMessages cannot be sent to primitivesMessages can be sent to other Java objects thatrepresent primitives
These are known as wrapper objects in Java (such as Double, Integer, and Boolean)
Primitive Types
Keyword Size Min value Max value
boolean true/false
8-bit
16-bit
16-bit Unicode
32-bit
32-bit
64-bit
64-bit
byte -128
-32768
-2147483648
127
short 32767
char
int 2147483647
float
double
long - 9223372036854775808 9223372036854775807
Manipulating Numeric Types
A lesser type is promoted to greater type and then the operation is performed
A greater type cannot be promoted to lesser typeAssigning double value to int type variable would result in a compile error
12 + 24.56 //int + double = double
int i = 12;double d = 23.4;i = d; Type mismatch
Type Casting
Values of greater precision cannot be assigned to variables declared as lower precision types
Type casting makes primitives change their typeUsed to assign values of greater precision to variables declared as lower precision
e.g., It’s possible to type cast double to int type
int i = 34.5; //compiler error - type mismatchint i = (int)34.5; //explicit type casting
Reference Types
Reference types in Java are class or interfaceThey are also known as object types
If a variable is declared as a type of classAn instance of that class can be assigned to itAn instance of any subclass of that class can be assigned to it
If a variable is declared as a type of interfaceAn instance of any class that implements the interface can be assigned to it
Reference Types (cont.)
Reference type names are uniquely identified by:Name of the package where type is defined (class or interface)Type name
This is full qualifier for the type and it is full qualifier for class or interface
java.lang.Objectcom.kiddcorp.demo.models.Policy
Object Operators
Keyword Descriptioninstanceof object type
not identical
identical
assignment
!=
==
=
Creating Objects in Java
In Java, objects are created by using constructors
Constructors are methods that have the same name asthe class
They may accept arguments mainly used for fields initializationIf constructor is not defined, the default constructor is used
Use “new” before class name to create an instanceof a class
HomePolicy firstPolicy = new HomePolicy();HomePolicy secondPolicy = new HomePolicy(1200);
Assignment
Assigning an object to a variable binds the variable to the object
HomePolicy firstPolicy = new HomePolicy(1200);
HomePolicy firstPolicy = new HomePolicy(1200);
HomePolicy secondPolicy = new HomePolicy(1200);
firstPolicy = secondPolicy;
1200aHomePolicy
1200aHomePolicy
1200aHomePolicy
1200aHomePolicy
Identical Objects
Operand == is used for checking if two objectsare identical
Objects are identical if they occupy the same memory space
int x = 3;int y = 3;x == y; //true
HomePolicy firstPolicy = new HomePolicy(1200);
HomePolicy secondPolicy = new HomePolicy(1200);
firstPolicy == secondPolicy; //false
3
1200aHomePolicy
1200aHomePolicy
Identical Objects (cont.)
Variables that reference objects are compared by valueObjects are identical if their memory addresses are the same
Variables are identical if they refer to the exact same instance of the class
HomePolicy firstPolicy = new HomePolicy(1200);HomePolicy secondPolicy = firstPolicy;firstPolicy == secondPolicy; //true
1200aHomePolicy
Equal Objects
Determined by implementation of the equals() methodDefault implementation is in the Object class anduses == (identity)Usually overridden in subclasses to provide criteriafor equality
HomePolicy firstPolicy = new HomePolicy(1200,1);
HomePolicy secondPolicy = new HomePolicy(1200,1);
firstPolicy.equals(secondPolicy); //false
Null
Used to un-assign object from a variableObject is automatically garbage collected if it does nothave references
When a variable of object type is declared, it is assigned “null” as a value
String one = "One";one = null;one = "1";
HomePolicy policy;policy = new HomePolicy(1200);…if (policy != null)
System.out.println(policy.toString());
Arrays
Arrays store objects of specific typeOne array cannot store objects of different types – String and int, for example
When creating an array explicitly, its size mustbe specified
This indicates the desired number of elements in the arrayElements in the array are initialized to default values
Creating and initializing arrays at declaration
int arrayOfIntegers[];arrayOfIntegers = new int[5];
int[] arrayOfIntegers = {1,2,3,4,5};
The first element in the array is at the zero index
Arrays (cont:)
If not using initializer, an array can be initialized by storingelements at the proper index
An element of the array is accessed by accessing the index wherethe element is stored
int[] arrayOfIntegers;arrayOfIntegers = new int[3];arrayOfIntegers[0] = 1;arrayOfIntegers[1] = 2;arrayOfIntegers[2] = 3;
int[] arrayOfIntegers = {1,2,3,4,5};System.out.println(arrayOfIntegers[2]);
3Console
The length property will return the number of elements in the array
Conditional Statements
x ? y : zx must be type boolean, y and z can be of any typeEvaluates to y if x is true, otherwise evaluates to z
if, if-elseCan be nestedCan omit braces if only one statment
(1 == 1) ? 7 : 4 //evaluates to 7
if(condition){statement1;
}else{statement2;
}
Conditional Statements (cont:)
Switch StatementBreak Allows you to stop after executing an expression
switch(expression){case value1:
expression1;case value2:
expression2;expression3;
default:expression4;
}
switch(expression){case value1:
expression1;break;
case value2:expression2;break;
default:expression3;
}
Looping
for loop
while() and doWhile()
for(int i=1; i<5; i++){System.out.println("Index is equal to " + i);}
Index is equal to 1Index is equal to 2Index is equal to 3Index is equal to 4
Console
int i=1;while(i < 5){
System.out.println(i);i++;}
int i=1;do{
System.out.println(i);i++;
}while(i < 5);
Java Fundamentals
How to Define a Java Class?
Java class is defined by using the “class” keywordClass name follows the keyword, and by convention starts with capital letter
For example Policy, Client, House, etc.
Class access level must be specified before theclass keyword
PublicIdentifies that any other class can reference defined class
Not specifiedIdentifies that only classes defined in the same package can reference defined classIt is the default access level modifier
public class Policy{…
}
.java Files
Java classes are contained in .java filesOne file can contain one public classOne file can contain more than one non-public class
The file name is the same as the class name contained in the file
package com.kiddcorp.demo.models;
public class Policy{…
} Policy.java
PackagePackage groups related classes
Classes are usually related by their functionality, for example, domain classes, testing classes, etc.
Package is identified using “package” keyword
Package is a unique identifier for a classTwo classes with a same name cannot be in the same packageDifferent packages can contain the same class names
Compiled Java classes from the same package are compiled into the same directory
The directory name matched the package name
package com.kiddcorp.demo.models;
Referencing Classes
A class must be fully referenced every time when used outside of its package
Full qualifier for a class is usedpackage name + class name
package com.kiddcorp.demo.tests;
public class PolicyTester{com.kiddcorp.demo.models.Policy policy;…policy = new com.kiddcorp.demo.models.Policy();
}
Import Statement
Used to identify which classes can be referenced without fully identifying them
Specified with “import” keywordCan specify a class, or all classes from a package
package com.kiddcorp.demo.tests;import com.kiddcorp.demo.models.Policy;
public class PolicyTester{Policy policy;…policy = new Policy();
}
Classpath and .jar Files
Classpath allows Java Virtual Machine to find the codeCLASSPATH environment variable is used to indicate the root of where packages are
Packages are subdirectories under the root
Compiled Java classes can be packaged and distributed in Java Archive (.jar) files
Packages in the .jar file are replaced with directoriesEssentially a zip file with a different extension
Defining Fields
A field definition consists of:Access modifierField typeField name
package com.kiddcorp.demo.models;
public class Policy {private Client client;private String policyNumber;private double premium;
}
Initializing Fields
Fields are initialized when a new instance of a classis created
Primitive type fields get a default valueNumeric primitives are initialized to 0 or 0.0Boolean primitives are initialized to falseReference type fields are initialized to null, as they do not yet reference any object
Fields can also be explicitly initialized when declared
Initializing Fields Explicitly
Possible when declaring fields
Not commonly usedConstructors are generally used for initializing fields
package com.kiddcorp.demo.models;
public class Policy {private Client client = new Client();private String policyNumber = "PN123";private double premium = 1200.00;
}
Field Access Modifier
There are four different modifiers:Public
Allows direct access to fields from outside the package where the class is defined
ProtectedAllows direct access to fields from within the package where the class is defined
DefaultAllows direct access to fields from within the package where class the is defined and all subclasses of the class
PrivateAllows direct access to fields from the class only
Defining Methods
Methods are defined with:Access modifier – same as for fieldsReturn typeMethod nameParameters – identified with type and name
To allow access to private fields, getter and setter methods arecommonly used
package com.kiddcorp.demo.models;
public class Policy {…public void setClient(Client aClient){…}
}
Constructors
Special methods used for creating instances of a class:Access modifierSame name as the classManipulate new instance
package com.kiddcorp.demo.models;
public class Policy {…public Policy(){
setClient(new Client());setPolicyNumber("PN123");setPremium(1200.00);
}}
What Are Static Fields?
Static fields represent data shared across all instances of a classThere is only one copy of the field for the class
Static fields are also known as class variables
Java constants are declared as static final fieldsModifier final indicates that field value cannot be changed
public class Count{public static String INFO = "Sample Count Class";public final static int ONE = 1;public final static int TWO = 2;
}
System.out.println(Count.ONE);1
Console
Static Methods
Define behavior related to the class, not individual instancesDefined by using the “static” keywordCommonly utilitarian in nature (See the Wrapper Classes)
public class Count{private static String INFO = "Sample Count Class";public final static int ONE = 1;public final static int TWO = 2;public final static int THREE = 3;public static String getInfo(){
return INFO;}
}
System.out.println(Count.getInfo()); Sample Count Class
Console
Defining InheritanceIn Java, inheritance is supported by usingkeyword “extends”
It is said that subclass extends superclassIf class definition does not specify explicit superclass,its superclass is Object class
Multiple inheritance is not supported in java
public class Policy{…public class HomePolicy extends Policy{…public class AutoPolicy extends Policy{…public class LifePolicy extends Policy{…
public class Policy{… public class Policy extends Object{…
Specialization and Generalization
ItemTextDateTimeValue
parseXMLcontainsValue…
RichTextItemEmbeddedObjects
embedObjectendSection…
Gen
eral
izat
ion
Specialization
What Is Inherited?
In general, all subclasses inherit from superclass:DataBehavior
When we map these to Java, it means that subclasses inherit:Fields (instance variables)Methods
Method Overriding
If a class defines the same method as its superclass, it is said that the method is overridden
Method signatures must match
Consider Animal class:Dog and Cat as subclasses
All Animal objects should know how to talk
Animal aCat;aCat.talk();
Animal aDog;aDog.talk();
meows
barks
Animal
talk()
Dog
talk()
Cattalk()
Interfaces
Interfaces define a type and protocol, but do not provide implementation of that protocol
Classes that implement interfaces must provide implementation for defined protocolInterfaces capture common behavior of the classes that implement them
Commonly used to:Impose protocol on set of classes that implement interfaceIndicate certain Java type (marker interfaces)
Interfaces are also stored in .java filespublic interface Animal{
public void speak();}
public interface Mammal{}
Interface Rules
Interfaces can containOnly method signaturesOnly final static fields
Interfaces cannot containAny fields other than final static fieldsAny static methodsAny method implementationAny constructors
It is possible that one interface extends other interfacesMultiple inheritance is allowed with interfaces
Inheritance works the same as with classes
Implementing Interfaces
Classes implement interfacesKeyword “implements” is usedThey must define all methods that the interface they implement declares
public class House extends Building implements Policyable{public Policy createPolicy(){
HomePolicy policy = new HomePolicy(this);return policy;
}}
What Are Collections?
Collections are Java objects used to store, retrieve, and manipulate other Java objects
Any Java object may be part of a collection, so collection can contain other collections
Unlike arrays, collections do not store primitives
Unlike arrays, collections can store different objectsNot all objects in a collection must be the same Java type
Most Commonly Used Collections
The most commonly used collections include:Collection framework collections:
ArrayListHashMapHashSet
Legacy collections re-implemented with the collection framework:VectorHashtable
What Is an Exception?
Exceptions are unexpected conditions in a programLike Opening a file that does not existOr Sending a message to an object that object doesnot understand
In Java, there are two different types of exceptionsUnchecked exceptions
Runtime exceptions and errorsChecked exceptions
All others exceptions
Exceptions are objects in Java, and they are all of the Throwabletype
Try – Catch and Finally Blocks
Exceptions are handled in a try-catch block
Finally Always executes at the end after the last catch blockCommonly used for cleaning up resources (closing files, streams, etc.)
public void myMethod(){try{
//code that throws exception e1//code that throws exception e2
}catch(MyException e1){//code that handles exception e1
}catch(Exception e2){//code that handles exception e2
}finally{//clean up code, close resources
}}
Java OO Fundamentals
Agenda
Roadmap
Eclipse, The Tool
Java language Fundamentals
Developing Java code In Eclipse
Develop and Deploy Lotus Domino Java code using the Eclipse development platform
Develop plug-ins in Eclipse
Wrap Up
Java Development Tooling – JDT
Eclipse’s Java Development Environment is often referred to as Java Development Tooling (JDT)
Using the JDT you can do the following things with Java programs:
WriteCompileTestDebug
Remember the right click menu!
Perspectives
When developing Java code, commonly used perspectives include:Java Perspective
Designed for working with Java projectsJava Browsing Perspective
Designed for browsing the structure of Java projectsJava Type Hierarchy Perspective
Designed for exploring type hierarchyDebug Perspective
Designed for debugging Java programs
Java Perspective
Contains:Outline ViewEditor areaPackage Explorer ViewHierarchy ViewTasks View
Java Browsing Perspective
Contains:Editor areaProjects ViewPackages ViewTypes ViewMembers View
Java Type Hierarchy Perspective
Contains editor area and Hierarchy View
Build Path Project Preferences
You can set global preferences for a project
Select Window → Preferences to get Preferences ViewGood idea to separate your Java files into source and compiled directories (src and bin)This action only needs to be done onceDone for all subsequent projects
Tip
Creating a Java Project
Projects are used to organize resources (source, class, icons) for a project
To create a Java project:Select Window → New → Project … from the menuThe New Project wizard comes upSelect Java → Java ProjectClick Next
New Project Wizard
Specify a Project name
Click Next
New Project Wizard: Java Settings
Specify Java SettingsOutput folder (where compiled files will be stored)Any external JAR files the project depends onClasses from other projects that are referenced in the project
Click Finish
Project Properties
You can change the Java build path at any timeChoose Properties from the context menu on the project
Creating Packages
A package contains Java class files
To create a package for a project:
Select the projectChoose New → Package from the context menuSpecify package NameClick Finish
Creating Classes
To create a class in a package:Select the packageChoose New → Class from the context menuThe Class wizard comes upSpecify class detailsClick Finish
Using Code Assist
When activated, code assist opens a list of available code completions
Code Assist activates by Crtl+SpaceActivates automatically when a message needs to be sent to an object (after the dot is typed)
Using Quick Fix (Ctrl + 1)
Useful if Java compiler shows errorsGives options for fixing the errorsActivated through Edit → Quick Fix menu option
Error indication
Searching for Java Classes
When developing Java applications, a good search mechanism is very important
You often search for class, method declarations, and referencesIt is important to be able to find things quickly
Eclipse Java Search mechanism is very extensive
It allows you to search for:Types, methods, constructors, packages, and fieldsDeclarations, Implementers, ReferencesIn the scope of Workspace, Working Set, or Selected Resources
Organizing Java Code
Eclipse comes with extensive support for organizing and refactoring Java code
It is possible to:Generate getters and setters for the fieldsOrganize missing import statementsMove fields, methods, classesRename methods, classes, packages
Generating Getters and Setters
Available for creating get and set methods on the fieldsIt supports encapsulation activated by choosing Source → Generate Getter and Setter from the editor’s context menu
Source NavigationF3
Navigate to a type, method, or field at the current cursor location
Ctrl+Shift+TOpen an editor for any Java type that is available in your workspace. Also via menu Navigate → Open Type … or using a toolbar icon
Ctrl+OOpen a lookup dialog containing a list of members in the current Java editor. Start typing characters to limit the list and press Enter to go to the selected member. A quick alternative to the Outline view.
Ctrl+F3Open a member lookup dialog for the class name at the current cursor location, e.g., position on Date and press Ctrl+F3 to review and lookup one of its methods
Source Code Templates
Provides a “shorthand” for common programming tasks
Eclipse JDT
Agenda
Roadmap
Eclipse, The Tool
Java language Fundamentals
Developing Java code In Eclipse
Develop and Deploy Lotus Domino Java code using the Eclipse development platform
Develop plug-ins in Eclipse
Wrap Up
Develop and Deploy Lotus Domino Java Code
Steps for Developing and Deploying Domino Java CodeCreate a Java Project in EclipseCreate Agent source code in ProjectCreate a new Agent in the Designer ClientImport source code from Eclipse into new Agent
Develop and Deploy Lotus Domino Java Code
Create a New Java Project in EclipseFile > New Project > Java Project
Provide a Project NameSelect the JRE– If you have configured Domino as one of your JREs in the workbench
preferences you can select it hereProject Layout– Keep separate source and output folders
Click “Next”
Develop and Deploy Lotus Domino Java Code
In the Java Settings DialogClick on the “Libraries” tab. This is your projects “Classpath”
This will allow you to add additional libraries to your project– If you are NOT using the Domino 7 JRE you will need to add the
“Notes.jar” file hereClick “Add External Jars”– Navigate to the proper Domino Directory
Domino 6– C:\installdir\notes
Domino 7– C:\installdir\jvm\lib\ext
Click “Finish”
Develop and Deploy Lotus Domino Java Code
The majority of Java Agents are created without a package reference
Although it’s a good idea to start getting in the habit of using them
In the “src” folder of your Java Project
Create a package or use the “default package”
Create a new Java ClassRight click package or folder and choose “New > Class” from context menuThis will open the “Java Class” wizard
Develop and Deploy Lotus Domino Java Code
Provide a Class name in the Name field
Do not use the value of “JavaAgent” that is used by default in all new Java Agents in the Domino Designer ClientChoose a name that is indicative of the
agent functionalityDo not worry about any of the other
settingsClick the “Finish” button to create the
class and open the source code in the Java Editor
Develop and Deploy Lotus Domino Java Code
The code created by the wizard will need to be replaced with template code created from a new agent in the Designer Client
You can cut / paste the new agent template code from the Designer ClientCreate a “Snippet” in Eclipse that stores the new agent template codeUse Plug-in provided (See resources at end of presentation)
import lotus.domino.*;
public class JavaAgent extends AgentBase {
public void NotesMain() {
try {Session session = getSession();AgentContext agentContext = session.getAgentContext();
// (Your code goes here)
} catch(Exception e) {e.printStackTrace();
}}
}
Develop and Deploy Lotus Domino Java Code
Every newly created agent in the Designer Client creates a new source file with a class name of “JavaAgent”
When the template code is added in eclipse this name will need to be “re-factored” to the name of the class created in Eclipse
Click on the “light bulb” and choose “Rename type to…”
Develop and Deploy Lotus Domino Java Code
Write the Java code in Eclipse to complete the agent functionality
Save the source code and ensure that there are no compile errors
Toggle back to the Designer Client Create a new Java Agent and give it the same name as the class in EclipseClick the “Edit Project” button on the bottom of the agent IDE in the Notes designer clientChange the “Base Directory” to point to the source folder of your eclipse projectAdd the source (.java NOT the .class) file to the Current Agent filesOne time only
Change the “Base Class” to the new source file nameDelete “JavaAgent.java” from the file list
Click “OK” to import the source code
Develop and Deploy Lotus Domino Java Code
Develop and Deploy Lotus Domino Java Code
The first time the source code is imported the code block will be collapsed
Click the “+” to expand it
If changes are made to the source code in EclipseClick the “Edit Project” buttonClick on the “Refresh All” buttonClick “OK”
You will be prompted that the source code will be replaced with the new code
Click “Yes” to accept the new code changes
Develop and Deploy Lotus Domino Java Code
Using this procedureMake sure you ALWAYS make your code edits in EclipseImport the changes to Existing/New agents in the Notes Designer Client
Develop and Deploy Lotus Domino Java Code
Develop and Deploy Lotus Domino Java Code
Java Domino ObjectsOnly implements the “Back End” objectsExposed via:
lotus.domino.*No Notes Client UI accessYou (the Domino Developer) already know 98.67 percent of all of the Java class names for the Domino Back End Objects
Drop “Notes” from the front of the LotusScript class names and you have the Java class names
LotusScript Class Name Java Class Name
NotesSession Session
NotesDatabase Database
NotesView View
NotesDocument Document
NotesItem Item
Develop and Deploy Lotus Domino Java Code
PerformanceJava Agent vs. LotusScript Agents
Java Agents and LotusScript Agents call the same C++ code baseOn an “Apples to Apples” comparison they will perform equitably
Classes the don’t exist in LotusScriptAgentBaseAppletBase and JAppletBaseNotesErrorNotesExceptionNotesFactoryNotesThread
Develop and Deploy Lotus Domino Java Code
AgentBaseJava Agents must extend AgentBaseJava Agents must use the NotesMain() method as the entry point for their functional codeThe getSession() method creates a Session object
import lotus.domino.*;
public class MyFirstAgent extends AgentBase {
public void NotesMain() {try {
Session session = getSession();AgentContext agentContext = session.getAgentContext();
// (Your code goes here)
}catch(NotesException ne){ne.printStackTrace();
} catch(Exception e) {e.printStackTrace();
}}
}
Develop and Deploy Lotus Domino Java Code
Primary problems LotusScript Developers have transitioning to JavaCompile Errors
Java is Case Sensitive– Yes, it’s always going to be case sensitive
Data typing errors– Java has no “Variant” data type
Runtime ErrorsNull Pointer exceptionClass not found exception
Develop and Deploy Lotus Domino Java Code
Domino Java agents have no access to the Notes UI
Output from agents is written to the “Debug Console” via the Java System.out.println() command inserted in the code
Access the Debug Console via the menu “File > Tools > Show Java Debug Console” from the Notes/Designer client
Develop and Deploy Lotus Domino Java Code
Code Walk ThroughSessionAgentContextDatabaseViewDocuments – Read
Help Doc Count AgentsDocuments – CreateItems – ReadItems – CreateRun on ServerJava Network I/OHTML OutputXML OutputWeb Query Save
Agenda
Roadmap
Eclipse, The Tool
Java language Fundamentals
Developing Java code In Eclipse
Develop and Deploy Lotus Domino Java code using the Eclipse development platform
Develop plug-ins in Eclipse
Wrap Up
Eclipse Architecture
Flexible, structured around:Extension pointsPlug-ins
This architecture allows for:Other tools to be used within the platformOther tools to be further extendedIntegration between tools and the platform
No need to wait for new product releases for the integration
Think “Hannover”
Eclipse Architecture
Eclipse Platform
Platform Runtime
…
Tool(plug-in)
Tool(plug-in)
Tool(plug-in)
Workbench
Workspace
Help
Team
JFaceSWT
Plug-in Developer
Environment(PDE)
Java Development
Tooling(JDT)
Eclipse SDK
Platform Runtime
In the Eclipse, everything is plug-in except the Platform RuntimeIt is a small kernel that represents base of the platform
All other subsystems build up on the Platform Runtime following the rules of plug-ins
They are plug-ins themselves
Basic platform includes:Resources ManagementWorkbenchTeamDebugHelp
Extension Points
Describe additional functionality that could be integrated with the platform
External tools extend the platform to bring specific functionalityJava Development Tooling (JDT) and Plug-in Development Environment (PDE) are external tools integrated with the platform
There are two levels of extending in Eclipse:Extending core platformExtending existing extensions
Extension points may have corresponding API interfaceDescribes what should be provided in the extension
Plug-ins
External tools that provide additional functionality to the platformFully integrated with the platform
Plug-ins:Define extension points
Each plug-in defines its own set of extension pointsImplement specialized functionality
Usually key functionality that does not already exist in the platformProvide their own set of APIs
Used for further extension of their functionalities
Plug-ins
Plug-ins implement behavior defined through extension point API interface
Plug-in can extend:Named extension pointsExtension points of other plug-ins
Plug-in can also declare an extension point and can provide an extension to it
Plug-ins are developed in Java programming language
What Makes Up a Plug-in?
Plug-in consists of:JAR file
Archive that contains plug-in codeplugin.xml
describes extension pointsabout.html
Textual description of the plug-inplugin.properties
Plugin-in propertiesMETA-INF\manifest.mf
describes the plug-in
Describing Plug-ins
An extension to the platform has to be registered somewhere
Each plug-in has a manifest file that describes:Location of the plug-in codeExtensions added by the plug-in
Manifest file is META-INF\MANIFEST.MFCan be edited with Eclipse toolsUsually describes:
Name, id, and version of the plug-inList of other plug-ins required by the plug-in describedWhere the plug-in code is located
Plugin file is plugin.xmldescribes extension points
Packaging Plug-ins
Plug-ins are packaged as Java Archives – JAR files
Archives are named using naming convention:<id>_<version>.jar
<id> is identifier<version> is full version from the manifest file
For example: org.eclipse.demo.plugin.simple_1.0
Publishing Plug-ins
Used for preparing plug-in for deployment on a specific platform
Manual publishing makes use of Ant scriptsAnt is a open source build tool, commonly used in building processes with Java codeAnt scripts are Java based (platform independent) with XML configurationAnt is supported in Eclipse
Automatic publishing is available by using Eclipse wizardsIt shields from using Ant scripts Wizards allow publishing in a single zip file
The zip file contains multiple plug-ins
Installing Plug-ins
Plug-ins are installed under \plugins\ directory off the Eclipse installation directory, e.g:
c:\eclipse\plugins
Creating a Basic Plug-in
Create a new Projectselect “Plug-in Project”
Plug-in Project Definitions
The main item on this screen is the target version of the Eclipse runtime.
Plug-in Content
The id of your plug-in is how it will be packaged
The Activator is the plug-in class itself
If your select that this plug-in will make a contribution to the UI you will have access to the UI oriented eclipse dependencies
Plug-in Templates
Using an existing template makes sure all the infrastructure needed for the plug-in is in place
Everything begins with “Hello World”Tip
Defining Sample Actions
Actions are where you code the “behavior” of your plug-in
The wizard will provide a template for you to follow
Plug-in Fragments
Used for extending existing plug-insProvide an additional functionality to existing plug-insIdeal for providing add-on functionality to plug-ins
Packaged in separate filesFragment content is treated as it was original plug-in archiveDuring the runtime platform detects fragments and merges their content with original plug-in
Described in the fragment.xml filesSimilar to plug-in manifest filesPlug-in archive can contain plug-ins or fragments
plug-in3 plug-in4
plug-in1 plug-in2
feature
Features
An Eclipse feature is a collection of plug-ins
Represents smallest unit of separately downloadable and installable functionalityNew notion in Eclipse since version 2.0
Replaces notion of “component” in Eclipse 1.0
Update Manager
Can be used with features and plug-ins for:DiscoveringDownloadingInstalling
Supported by modular nature of EclipseMakes it easy to install additional features and plug-ins, and to update existing ones
Installing or updating features and plug-ins requires adding files to Eclipse
Deleting files is never required as different version can co-exist in Eclipse
Developing a “Hello World” Plug-in
Wrap Up
Follow the “Roadmap”J2SEServlets, JSPs, JSFsXMLRest of J2EE Specification
Start with Java Agents in Domino
Transition to Servlets running on the Domino Server
Transition to external Servlet/JSP – J2EE server
Introduce yourself to Plug-ins and Eclipse RCP
Wrap Up
References and ResourcesTLCC (Booth Number 611)
Java Computer based training via Notes Databaseswww.tlcc.com
The View (Booth Number xxx)www.eview.com
O’Reilly PublishingHead First… Series
SUN Developer Networkjava.sun.com
Eclipse Projectwww.eclipse.org
Wrap Up
References and Resources (cont)Apache Jakarta Project
Jakarta.apache.orgDeveloper Works
www.ibm.com/developerworkswww.ibm.com/developerworks/javawww.ibm.com/developerworks/lotus
© IBM Corporation 2007. All Rights Reserved.
The workshops, sessions and materials have been prepared by IBM or the session speakers and reflect their own views. They are provided for informational purposes only, and are neither intended to, nor shall have the effect of being, legal or other guidance or advice to any participant. While efforts were made to verify the completeness and accuracy of the information contained in this presentation, it is provided AS IS without warranty of any kind, express or implied. IBM shall not be responsible for any damages arising out of the use of, or otherwise related to, this presentation or any other materials. Nothing contained in this presentation is intended to, nor shall have the effect of, creating any warranties or representations from IBM or its suppliers or licensors, or altering the terms and conditions of the applicable license agreement governing the use of IBM software.
References in this presentation to IBM products, programs, or services do not imply that they will be available in all countries in which IBM operates. Product release dates and/or capabilities referenced in this presentation may change at any time at IBM’s sole discretion based on market opportunities or other factors, and are not intended to be a commitment to future product or feature availability in any way. Nothing contained in these materials is intended to, nor shall have the effect of, stating or implying that any activities undertaken by you will result in any specific sales, revenue growth or other results.
Performance is based on measurements and projections using standard IBM benchmarks in a controlled environment. The actual throughput or performance that any user will experience will vary depending upon many factors, including considerations such as the amount of multiprogramming in the user's job stream, the I/O configuration, the storage configuration, and the workload processed. Therefore, no assurance can be given that an individual user will achieve results similar to those stated here.
All customer examples described are presented as illustrations of how those customers have used IBM products and the results they may have achieved. Actual environmental costs and performance characteristics may vary by customer.
IBM, the IBM logo, Lotus, Lotus Notes, Notes, Domino, Domino.Doc, Domino Designer, Lotus Enterprise Integrator, Lotus Workflow, Lotusphere, QuickPlace, Sametime, WebSphere, Workplace, Workplace Forms, Workplace Managed Client, Workplace Web Content Management, AIX, AS/400, DB2, DB2 Universal Database, developerWorks, eServer, EasySync, i5/OS, IBM Virtual Innovation Center, iSeries, OS/400, Passport Advantage, PartnerWorld, Rational, Redbooks, Software as Services, System z, Tivoli, xSeries, z/OS and zSeries are trademarks of International Business Machines Corporation in the United States, other countries, or both.
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both.
Microsoft and Windows are trademarks of Microsoft Corporation in the United States, other countries, or both.
Intel and Pentium are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States and other countries.
UNIX is a registered trademark of The Open Group in the United States and other countries.
Linux is a registered trademark of Linus Torbvalds in the United States, other countries, or both.
Other company, product, or service names may be trademarks or service marks of others.
All references to Acme, Renovations and Zeta Bank refer to a fictitious company and are used for illustration purposes only.