StarTeam SDK New Features - Conferences

mammetlizardlickΛογισμικό & κατασκευή λογ/κού

3 Νοε 2013 (πριν από 3 χρόνια και 7 μήνες)

117 εμφανίσεις




November 4, 2013


Page
1

of
25

StarTeam SDK New Features

Borland Developer Conference 2005

Session #
3112

Randy Guck, Chief Scientist, Borland

Description

The StarTeam SDK allows you to write custom applications in Java, the Microsoft .NET Framework, and
COM languages. With the StarTeam
2005 R2 release, new SDK features have been added that make it
easier to write event
-
based applications, store credentials for auto
-
logon applications, leverage the
StarTeamMPX Cache Agent, and more. This article describes these new StarTeam SDK features a
nd
provides coding samples on how to use them.

This article is intended for SDK application developers.

Table of Contents

1. Overview

................................
................................
................................
................................
......................

1

2. Summary of New Features

................................
................................
................................
...........................

2

3. Auto Logon

................................
................................
................................
................................
...................

4

4. The CheckoutManager Family

................................
................................
................................
.....................

8

4.1. CheckoutOptions

................................
................................
................................
................................
...

8

4.2. CheckoutManager

................................
................................
................................
................................
.

9

4.3. CheckoutListener (Java)

................................
................................
................................
......................

11

4.4. CheckoutEventSource (.Net)

................................
................................
................................
...............

12

4.5. ContentFilter

................................
................................
................................
................................
........

13

4.6. CheckoutProgress

................................
................................
................................
................................

17

5. Not
-
in
-
View Folders

................................
................................
................................
................................
...

18

6. New Event Methods

................................
................................
................................
................................
...

20

6.1. FolderUpdateEvent and Item
UpdateEvent

................................
................................
..........................

20

6.2. ViewConfigurationDiffer

................................
................................
................................
....................

22

6.3. ViewPollingAgent

................................
................................
................................
...............................

23

7. References

................................
................................
................................
................................
..................

24


1.

Overview

T
he StarTeam SDK
allows

you
to
access virtually
all
StarTeam functions. This includes all artifact
operations
(
checking
-
in files, creating change requests, attaching items to

labels
)

as well as administrative
functions
(
creating new projects

and assigning security rights
)
. In fact, all of StarTeam’s
2005 R2
bundled
clients are based on the SDK,
using one of the available language interfaces: Java, .Net, or COM.

For review, you

should be aware that the SDK .Net interface provides three different development
approaches that support different application portability needs:



Pure Java applications:

These are applications written in and only compiled as Java. For these
applications,
the SDK’s functions are contained in
a standard
jar

file.


StarTeam SDK New Features





November 4, 2013


Page
2

of
25



P
ure .Net

applications
:

Th
ese are
applications written in C# or VB, for example, that expect “.Net
like” techniques for property access,
event handling, and collection management. Th
e SDK
provides a

pure .Net

interface
,

contained in the library Borland.StarTeam.dll.



Dual
-
compile

applications:

These are
applications written in Java that can also be compiled in J#.
Consequently, they can be compiled
as Java
and run in a Java VM, and they can be compile
d
as .Net
code
and run in the .Net run
-
time.

The SDK supports these applications with a Java
jar file
and
the
.Net

library Borland.StarTeam.Core.dll
.



Hybrid applications:

These are applications that have a dual
-
compile Java/J# core, but platform
-
specific “
edge” code
provided
with two variants: one in Java and one in pure .Net code. An example
hybrid
application
has a
UI that
uses
Swing
in its Java variant
and
WinForms in its

.Net variant.

The
SDK supports hybrid applications by allowing them to
be compiled
as pure Java and, for .Net,
allowing them to
use both
.Net DLLs
interfaces
simultaneously
. Furthermore, the SDK
provid
es

methods for converting between the two

.Net

libraries
.

In this article, examples
are provided
in Java and C# to illustrate the pure Jav
a and pure .Net interfaces. See
the StarTeam SDK documentation for more information about building hybrid applications, compiling and
building

techniques
, and using the COM interfaces.

2.

Summary of New Features

Below is a b
rief summary of
the
key SDK
new features and
release notes
for
the StarTeam 2005
R2

release:



Backward
c
ompatibility

The 2005 R2 release uses the internal version number “8.0”. The
8.0
SDK will connect to
StarTeam
Server
s

whose
version

is

5.2
or
later. Earlier versions of the
server are no
t
supported.



Auto
l
ogon

The
Server

class now supports an
autoLogOn()

method that logs on using credentials cached on
the local client workstation. Methods are also available to determine whether or not cached
credentials are available and to u
pdate cached credentials. These features are currently only
available
on Windows

and only when the StarTeam Toolbar is running.



New classes to perform check
-
outs

A new
CheckoutManager

class provides a convenient way to check out collections of files. It
su
pports new options such as
delta check
-
out
,
check
-
out from MPX Cache Agent
s, and the ability to
filter content during check
-
out using a
ContentFilter

object
.
The
CheckoutManager

also
uses
a
CheckoutOptions

class that provides a
rich set of
check
-
out
option
s

that can be assigned default
values or overridden on a file
-
by
-
file basis.
The
CheckoutListener

class supports e
vent
-
based
monitoring of check
-
out progress. A
CheckoutProgress

class provides statistics on check
-
out
progress
.

An overview of the

CheckoutMa
nager

is provided in this article, but see the companion

StarTeam SDK New Features





November 4, 2013


Page
3

of
25

article
Accelerating File Check
-
outs with the MPX Cache Agent

for details

on using the Cache
Agent.



Update to
EnumeratedValue

class

The values of enumerated properties are now sorted in a way that is

consistent with the Win32
client. The
EnumeratedValue

class has a new
SortOrder

property whose value is the sort order
relative to
other enumerated values. The
ServerAdministration

class has a new
updateEnumeratedField()

method that allows a client applic
ation to set the sort order
independent of the enum codes. The sorting and comparison algorithms in
ItemListManager

and
QueryInfo.evaluate()

have been updated.



Foreign
archive improvements

Support for foreign archives has been improved. It is now possible
to
refresh

the foreign files in a
project, and to
convert

a foreign project to a native StarTeam project.



Not
-
In
-
View folders

Not
-
In
-
View folders are now supported. A new method
getFolderTree()

retrieves a copy of the
Folder tree with Not
-
In
-
View folders i
ncluded and attached to the correct parent folders.
updateFolderTree()

updates all folders to a given depth, creating folders in the repository for
each Not
-
In
-
View folder in the tree.
FolderListManager

now supports Not
-
In
-
View folders, and
ItemListManager

can be used to populate them with Not
-
In
-
View files.



Update
e
vents

The StarTeam SDK now supports
FolderUpdateEvents

and
ItemUpdateEvents

for notifying the
client application when changes have been made to the Folder and Item objects it is using. These
eve
nts are similar in spirit to
FolderEvents

and
ItemEvents
; however, they are triggered by
explicit API calls made by the client application, rather than externally via StarTeamMPX. For
example, calling
View.refreshFolders()

might trigger one or more
FolderU
pdateEvents
;
calling
Item.update()

might trigger an added or changed event.



New
View.close()

method

A new
View.close()

method frees all cached resources associated with a view, and closes the
associated view session. Many view
-
related resources, such as th
e folder tree, item lists and so on,
can be freed separately via existing APIs. Some resources, however, were previously freed only by
a call to
Server.disconnect()
.



New
ViewConfigurationDiffer

class

A new
ViewConfigurationDiffer

class compares two configu
rations of a given view, generating
FolderUpdateEvents

and
ItemUpdateEvents

that describe the differences between the two.



New
ViewPollingAgent

class


StarTeam SDK New Features





November 4, 2013


Page
4

of
25

A new
ViewPollingAgent

class determines the changes that have been made to a given view since
a known poin
t in time, generating
FolderUpdateEvents

and
ItemUpdateEvents

that describe the
changes. The client application can use a single
ViewPollingAgent

to poll at regular intervals, or
can save the latest timestamp to construct a new
ViewPollingAgent

at some fut
ure time.

The following sections explore the key new features for the StarTeam 2005 R2 SDK release.

3.

Auto

L
ogon

Auto logon allows SDK application
s

to cache and reuse credentials for specific StarTeam
S
erver
configuration
s
. Currently, auto log
on is implemented using the StarTeam Toolbar as the credential cache
,
but

l
ater it may use an alternate credential mechanism.

Credential caching via the StarTeam Toolbar is use
d

by various bundled StarTeam clients, but it was not previously available to SD
K developers. With the R2
release, the SDK allows you to detect if the Toolbar

is installed, store credentials,

and log onto a server
automatically when credentials are already cached.

Note that credential caching is system
-

and user
-
specific: cached crede
ntials can not be accessed from another system nor by other user sessions on the same
system.

Auto logon operates through the
Server

object with the following methods
,
listed in the order you’d
probably use them
:



public static boolean
isCredentialCachingAv
ailable
()

This method d
etermines whether or not the credential caching feature is available on this
workstation. Currently, credential caching is available only when the StarTeam
T
oolbar is
installed
.
Note that credential caching may be available, but not
enabled
, which means that the toolbar may
be
installed but
not running.



public static boolean
isCredentialCachingEnabled
()

Determines whether or not credential caching is enabled on this workstation. Currently, credential
caching is enabled only when the S
tarTeam Toolbar is
running
.

This command causes the
application to attempt a connection to the Toolbar and ping it. Note that multiple copies of the
Toolbar could be running on a multi
-
session Windows machine (i.e., Windows XP with multiple
active sessions
.)
But each copy is dedicated to a specific windows user session. This method returns
“true” only if it finds a copy running for the
current

user.




public static void
enableCredentialCaching
()

Enables credential caching on this workstation, if it is availa
ble and not already enabled. Currently,
this
starts

the StarTeam Toolbar.

The Toolbar may take a few seconds to respond, so, after calling
this method,
isCredentialCachingEnabled()

might not return “true” right away.



public void
cacheLogOnCredentials
(Strin
g username, String password)

Saves logon credentials for
this

server
(notice that it is a member method, not static)
so that they
may be used in future calls to
autoLogOn()
.

After calling this method, you should see the cached
server/user appear in the Too
lbar’s display.


StarTeam SDK New Features





November 4, 2013


Page
5

of
25



public boolean
isAutoLogOnAvailable
()

Determines whether or not logon credentials for this server have been cached on this workstation. If
so, then the
auto
L
ogon
()

can
be
called
to logon using the cached credentials.



public int
autoLogOn
()

Log on to this server using credentials that have been cached on this workstation.

When t
his method
is called,
the credentials cached by the Toolbar (for this server
)

are fetched, and
logOn()

is then
called with the fetched credentials.

The result of the
l
ogOn()

call is returned as the result of the
autoLogOn()

call. Note, also, that
logOn()

throws an exception if the logon attempt fails,
in which
case

autoLogOn()

simply passes on that exception.

The auto logon feature can not be used if other logon variant
s are needed such as
logOnForWorkstation()

or
logOnWithClientContext()
.

Below is an example Java method that attempts to logon automatically when possible to a certain StarTeam
server. If the appropriate credentials are not available, the user is prompted
for credentials, which are then
cached, if possible.

// Demonstrate SDK auto
-
logon feature

void

logOnDemo() {


// Create the Server object we want to connect to.


Server server =
new

Server(
"localhost"
,
49201
);



// See if credential caching is av
ailable and enabled.


boolean

bCanCacheCredentials =
false
;


if

(Server.isCredentialCachingAvailable()) {


// Credential caching is available; is it enabled?


System.out.println(
"Credential caching is available."
);


if

(Server.is
CredentialCachingEnabled()) {


// Credential caching is available and enabled.


System.out.println(
"Credential caching is enabled."
);


bCanCacheCredentials =
true
;


}
else

{


// Attempt to enable credentia
l caching. Wait 1 second to let Toolbar


// initialize.


System.out.println(
"Enabling credential caching."
);


Server.enableCredentialCaching();


try

{Thread.sleep(
1000
);}
catch

(InterruptedException ex) {}



if

(Server.isCredentialCachingEnabled()) {


System.out.println(
"Credential caching is enabled."
);


bCanCacheCredentials =
true
;


}
else

{


System.out.println(
"Credential caching could not be ena
bled."
);


}


}


}



// If credential caching is working, see if we can auto
-
logon to server.


try

{


// logOn throws an exception is the logon fails


if

(bCanCacheCredentials) {


StarTeam SDK New Features





November 4, 2013


Page
6

of
25


// See if credentials are

already cached for this server.


if

(server.isAutoLogOnAvailable()) {


// Credentials are available for this server; attempt auto
-
logon.


System.out.println(
"Attempting auto
-
logon."
);


server.autoLog
On();


System.out.println(
"Auto
-
logon successful."
);


}
else

{


// Credentials are not available for this server; get them from the


// user and cache them if they work.


System.out.pri
ntln(
"No credentials cached for server."
);


Credentials credentials = promptForCredentials();


System.out.println(
"Logged on."
);


server.logOn(credentials.userid, credentials.password);


server.ca
cheLogOnCredentials(credentials.userid,


credentials.password);


System.out.println(
"Credentials cached."
);


}


}
else

{


// Credential caching is not available, just p
rompt for credentials.


Credentials credentials = promptForCredentials();


server.logOn(credentials.userid, credentials.password);


System.out.println(
"Logged on."
);


}




// Here, we're logged
-
on.



System.out.println(
"Server has "

+ server.getProjects().length +


" projects."
);


server.disconnect();


}
catch

(RuntimeException ex) {


// StarTeam logon failed.


System.out.println(
"Logon failed: "

+
ex);


}

}
// logOnDemo

Below is the same example in C#.

// Demonstrate SDK auto
-
logon feature.

void

LogonDemo()

{


// Create the Server object we want to connect to.


Server server =
new

Server(
"localhost"
,
49201
);



// See if credential cach
ing is available and enabled.


bool

bCanCacheCredentials =
false
;


if

(Server.IsCredentialCachingAvailable)


{
// Credential caching is available; is it enabled?


System.Console.WriteLine(
"Credential caching is available."
);


if

(S
erver.IsCredentialCachingEnabled)


{
// Credential caching is available and enabled.


System.Console.WriteLine(
"Credential caching is enabled."
);


bCanCacheCredentials =
true
;


}


else


{
// Attempt to
enable credential caching; wait 1 second for Toolbar


// to initialize.


System.Console.WriteLine(
"Enabling credential caching."
);


StarTeam SDK New Features





November 4, 2013


Page
7

of
25


Server.EnableCredentialCaching();


Thread.Sleep(
1000
);


if

(Server.Is
CredentialCachingEnabled)


{
// It worked.


System.Console.WriteLine(
"Credential caching is enabled."
);


bCanCacheCredentials =
true
;


}


else


{
// Didn't work.


System.Console.WriteLine(
"Credential caching could not "

+


"be enabled."
);


}


}


}



// If credential caching is working, see if we can auto
-
logon to server.


try


{
// LogOn will th
row an exception if it fails.


if

(bCanCacheCredentials)


{
// See if credentials as cached for this server.


if

(server.IsAutoLogOnAvailable)


{
// Credentials are available for this server; attempt auto
-
logon.



System.Console.WriteLine(
"Attempting auto
-
logon."
);


server.AutoLogOn();


System.Console.WriteLine(
"Auto
-
logon successful."
);


}


else


{
// Credentials are not available for this

server; get them from the


// user and cache them if they work.


System.Console.WriteLine(
"No credentials cached for server."
);


Credentials credentials = PromptForCredentials();


server.LogOn(cr
edentials.userid, credentials.password);


System.Console.WriteLine(
"Logged on."
);


server.CacheLogOnCredentials(credentials.userid,


credentials.password);


System.Con
sole.WriteLine(
"Credentials cached."
);


}


}


else


{
// Credential caching is not available, just prompt for credentials.


Credentials credentials = PromptForCredentials();


server.LogOn(credentials.
userid, credentials.password);


System.Console.WriteLine(
"Logged on."
);


}




// Here, we're logged
-
on.


System.Console.WriteLine(
"Server has {0} projects."
,


server.Projects.Count);



server.Disconnect();


}


catch

(Exception ex)


{
// StarTeam logon failed.


System.Console.WriteLine(
"Logon failed:
{0}
"
,
ex);


}

}
// LogonDemo


StarTeam SDK New Features





November 4, 2013


Page
8

of
25

4.

The
CheckoutManager

Family

With R2, the SDK provides a

new, more fl
exible way
of checking
-
out
files. The new, mother
-
of
-
all
-
checkout
techniques
is the
CheckoutManager

class. The other members of its family are the classes:
CheckoutOptions
,
CheckoutListener

(
CheckoutEventSource

for .Net),

ContentFilter
, and
CheckoutProgres
s
. A tour of these classes is provided in the following sections. A
focused
discussion

of
using
the
CheckoutManager

with
the MPX Cache Agent is detailed in the companion article,
Accelerating
File Check
-
outs with the MPX Cache Agent
.

4.1.

Checkou
tOptions

This class provides a place to set check
-
out options that can be used for multiple check
-
out operations. The
CheckoutOptions

class is summarized below:



A
CheckoutOptions

object can
be created
to inherit

default options for a
View
, check
-
out relate
d
options from a
StarTeamClientOptions

object, or
the same options as
another
CheckoutOptions

object
.



CheckoutOptions

provides g
et/set methods for
these
check
-
out options
:



Whether or not to c
onvert
end
-
of
-
line (EOL) characters of text files during check
-
ou
t, and which
EOL pattern
to use (CR, LF, CRLF).



Whether to c
heck
-
out
current (tip) file versions or revisions
as of a specific date, label,
or
promotion state.



Whether to u
se a
ContentFilter

object (more on this later)
.



Whether or not to e
nable keyword exp
ansion
,

and
what
file encoding
should be used when
expanding keywords.



Whether or not each file’s lock status should be changed
during check
-
out

and how.



Whether or not to m
ark non
-
locked files as read
-
only
.



Whether or not
“delta check
-
out”

should be used
when possible. This option is also known as
“optimize for slow connections” and i
s only applicable to text files whose status is “out
-
of
-
date”.



Whether or not to r
estore
an
existing work file, if any, if
a
check
-
out
to that file starts but
fails

before it
completes.



Whether to s
et
each
checked
-
out file’s timestamp to “now” or the modified timestamp

of the file
revision.



Whether or not to u
pdate w
orkfile status after check
-
out.

Below are
example uses of the
CheckoutOptions

class
in Java
:


StarTeam SDK New Features





November 4, 2013


Page
9

of
25

// Create CheckoutOp
tions from a View.

View view = StarTeamFinder.openView(
"joe:pw@localhost:49201/StarDraw"
);

CheckoutOptions coOpts1 =
new

CheckoutOptions(view);


// Clone CheckoutOptions.

CheckoutOptions coOpts2 =
new

CheckoutOptions(coOpts1);


// Create CheckoutOptions fr
om default client options.

StarTeamClientOptions defaultClientOptions = StarTeamClientOptions.getDefault();

CheckoutOptions coOpts3 =
new

CheckoutOptions(defaultClientOptions);


// Enable EOL conversion and set EOL char to CRLF.

coOpts1.setEOLConversionEna
bled(
true
);

coOpts1.setEOLChars(CheckoutOptions.EOL_CRLF);


// Request each file to be locked exclusively.

coOpts1.setLockType(Item.LockType.EXCLUSIVE);

Below are the same examples in C#:

// Create CheckoutOptions from a View.

View view =
StarTeamFinder.Op
enView
(
"joe:pw@localhost:49201/StarDraw"
)
;

CheckoutOptions coOpts1 =
new

CheckoutOptions(view);


// Clone CheckoutOptions.

CheckoutOptions coOpts2 =
new

CheckoutOptions(coOpts1);


// Create CheckoutOptions from default client options.

StarTeamClientOptions

defaultClientOptions = StarTeamClientOptions.Default;

CheckoutOptions coOpts3 =
new

CheckoutOptions(defaultClientOptions);


// Enable EOL conversion and set EOL char to CRLF.

coOpts1.EOLConversionEnabled =
true
;

coOpts1.EOLChars = CheckoutOptions.EOL_CRLF
;


// Request each file to be locked exclusively.

coOpts1.LockType = Item.LockType.EXCLUSIVE;

4.2.

CheckoutManager

A
CheckoutManager

object is c
reated in the context of a specific
View
.
This means that the files it checks
-
out must be from the sam
e with which it is created. When constructed, a
CheckoutManager

object has
default options, but you override these by constructing it with

a

CheckoutOptions

object or assigning it
one after construction.

Other things you can do with a
CheckoutManager

are:



You can request check
-
out from an auto
-
located or a specific MPX Cache Agent.



You can register one or more
CheckoutListener

objects that monitor the progress of a check
-
out
request and
set the check
-
out workfile

on a per
-
file basis (described later).



You c
an
monitor

check
-
out progress

by registering
a
CheckoutProgress

object

(described later).



You can check
-
out
a single file or a set of files in a single call

with a variety of interfaces:


StarTeam SDK New Features





November 4, 2013


Page
10

of
25



A single

File

object:

to the default work file, to an alternate work
file, or to a stream
.



All files in a

Folder

object.



All files in a
Folder
, recursing to subfolders at a specify depth.



All files in an
Item

array (which are
File

objects)
.



All files in an
ItemList

(which contains
File

objects)
.



All files specified by an ob
ject you provide that implements a simple
Items

interface.

If you want to check
-
out files from an
MPX Cache Agent
, you specify the relevant options in the
CheckoutManager

object

(not the
CheckoutOptions

object)
. This includes enabling Cache Agent check
-
out
, choosing auto
-
locate or setting the Cache Agent’s address and port, and setting the number of fetch
threads to use for parallel check
-
out. Note that when
a
Cache Agent
is requested but
cannot be located or
a
Cache Agent can
not fetch

some files
, the
Check
outManager

object automatically switches to “command
API” check
-
out
. This means that you don’t have to worry about where the files come from
:

you just get
them. Also, be aware that keyword expansion is mutually exclusive with Cache Agent usage: if you requ
est
keyword expansion, a Cache Agent is never used, even if you request it.

Below are some
example
s

using the new
CheckoutManager

class in Java:

// Create a CheckoutManager from a View with the options from above.

CheckoutManager

coMgr1 =
new

CheckoutManag
er(view, coOpts3);


// Create a CheckoutManager from a View with default options.

CheckoutManager coMgr2 =
new

CheckoutManager(view);


// Clone a CheckoutManager.

CheckoutManager coMgr3 =
new

CheckoutManager(view, coMgr2);


// Check
-
out a single file to it
s default location from an auto
-
located

// MPX Cache Agent.

coMgr1.setMPXCacheAgentEnabled(
true
);
// default is auto
-
locate

Folder rootFolder = view.getRootFolder();

File file = StarTeamFinder.findFile(rootFolder,
"index.htm"
,
false
);

coMgr1.checkout(fil
e);


//
C
heckout all files in a folder, re
cursively (still Cache Agent
-
enabled)

coMgr1.checkout(rootFolder,
-
1
);
//
-
1 means "all descendents"

Below are similar examples in C#:

// Create a CheckoutManager from a View with the options from above.

Checkou
tManager coMgr1 =
new

CheckoutManager(view, coOpts3);


// Create a CheckoutManager from a View with default options.

CheckoutManager coMgr2 =
new

CheckoutManager(view);


// Clone a CheckoutManager.

CheckoutManager coMgr3 =
new

CheckoutManager(view, coMgr2)
;


StarTeam SDK New Features





November 4, 2013


Page
11

of
25


// Check
-
out a single file to its default location from an auto
-
located

// MPX Cache Agent.

coMgr1.MPXCacheAgentEnabled =
true
; // default is auto
-
locate

Folder rootFolder = view.RootFolder;

Borland.StarTeam.
File file =


StarTeamFinder.FindFile(r
ootFolder,
"index.htm"
,
false
);

coMgr1.Checkout(file);


// Check
-
out all files from the root folder and its descendents.


coMgr1.Checkout(rootFolder,
-
1
);
//
-
1 means "all descendents"

4.3.

CheckoutListener

(Java)

The
CheckoutManager

class giv
es you a way to monitor and act on check
-
out events. In Java applications
(and dual
-
compile applications using J#), the SDK uses
the Java
-
style listener model in the form of the
CheckoutListener

interface
.
To use it, create a
n object
that
implement
s

this i
nterface
and
pass

it

to
CheckOutManager.addCheckoutListener()
. Note that if you enable Cache Agent check
-
out and allow
more than one check
-
out thread (
CheckoutManager.setMPXCacheAgentThreadCount()
)
, requests
with
than a few files will be divided into multi
ple batches and fetched in parallel in separate threads. Your thread
that calls
CheckoutManager.checkout()

is always the first request thread; additional threads are spawned
internally by the SDK. The implications are that, if you register a
CheckoutListen
er

object, it should be
thread safe since it will be invoked simultaneously on each fetch thread.

The

two
CheckoutListener

concrete
methods
you must implement are
:



public void onStartFile(CheckoutEvent event)

T
his method is called
once per file, at the sta
rt of the checkout operation for that file.
The most
useful things you can do in this
callback are:



Get details about the file about to start by calling
event.getCurrentFile()
.



O
verride the
workfile
to which the file will be checked
-
out by calling
event.se
tCurrentWorkingFile()
.



Determine if the callback is being
invoked
on a secondary MPX fetch thread
(
event.isMPXCacheAgentThread()
) and if so,
determine the thread’s index
(
event.getCheckoutThreadIndex()
).

This could be useful if you’re application is displa
ying
a sophisticated, per
-
thread progress meter.



Get a snapshot of overall check
-
out progress so far (
event.getProgress()
).



Decide that the check
-
out is a bust and cancel it, for example if requested by the end
-
user
(
event.getCheckoutManager().setCancel()
)
.



public void onNotifyProgress(CheckoutEvent event)


StarTeam SDK New Features





November 4, 2013


Page
12

of
25

T
his method is called
during the checkout operation, to provide the client application with updated
information about the progress of the operation
.

It is called for every file once, whether that file
suc
ceeds or fails.



If the checkout of a given file completes successfully, then the
event
.isFinished()

and
event
.isSuccessful()

will
both
be “
true

.

In this case only, you can call
event.getCheckoutResults()

to get the checked
-
out file’s final lock state and
any keywords
that were used during the check
-
out.



If the checkout of a given file terminates abnormally

(e.g., due to an I/O error on the workfile)
,
then
event
.isFinished()

will be “true” but
event
.isSuccessful()

will be “false”.



If the checkout operation
is canceled, then the
onNotifyProgress
()

event for
each unfinished
file
will see

event
.isCanceled()

as “
true

.

Below is an example using the
CheckoutListener

interface, implemented as an in
-
line
,

anonymous class.
The two callback methods (
onStartFile
()

and

onNotifyProgress
()
) merely display
messages that show
the progress of the check
-
out:

// Create an in
-
line anoynymous CheckoutListener object
.

CheckoutListener

listener =
new

CheckoutListener() {


public

void

on
StartFile
(CheckoutEvent checkoutEvent) {



String fileName = checkoutEvent.getCurrentFile().getFullName();


System.out.println(
"Starting file: "

+ fileName);


}
// onStartFile



public

void

on
NotifyProgress
(CheckoutEvent checkoutEvent) {


String fileName = checkoutEvent
.getCurrentFile().getFullName();


if

(checkoutEvent.isFinished()) {


// File is finished, successfully or cancelled


if

(checkoutEvent.isCanceled()) {


System.out.println(
"File canceled: "

+ fileName);



}
else

if

(checkoutEvent.isSuccessful()) {


System.out.println(
"File finished: "

+ fileName);


}
else

{


System.out.println(
"File failed: "

+ fileName);


}


}


}
// onNotifyProgress

};


// R
egister the CheckoutListener and then check
-
out all files in a folder,

//
recursively.

coMgr1.addCheckoutListener(listener);

coMgr1.checkout(rootFolder,
-
1
);
//
-
1 means "all descendents"

4.4.

CheckoutEventSource (.Net)

For pure .Net applicati
ons, the SDK uses the .Net event model to implement check
-
out events. Specifically,
the
CheckoutManager

provides a factory that creates a
CheckoutEventSource

object,
which provides
OnStartFile

and
OnNotifyProgress

events. To use these events, you create
ha
ndler methods
that
implement the
CheckoutEventSource.Handler

delegate interface and register them
using the “+=”

StarTeam SDK New Features





November 4, 2013


Page
13

of
25

operator.

The delegate interface has two parameters: the
CheckoutEventSource

that is generating the
event and the

CheckoutEventArgs

object that

contains the accessible event
-
related properties.

Below is
an example in C# that is functionally equivalent to the Java
CheckoutListener

example shown
in the previous section:

// Create a CheckoutEventSource from a CheckoutManager, and register callbacks

// for OnStartFile and OnNotifyProgress.

CheckoutEventSource

eventSource = coMgr1.NewCheckoutEventSource();

eventSource.OnStartFile +=
new

CheckoutEventSource.Handler(OnStartFile);

eventSource.OnNotifyProgress +=
new

CheckoutEventSource.Handler(OnNotifyPro
gress);


// Check
-
out all files from the root folder and its descendents. This will

// generate events that our handlers will receive.

coMgr1.Checkout(rootFolder,
-
1
);
//
-
1 means "all descendents"

...


/////
Below are the
methods registered by the "+="

calls above.


// Callback for CheckoutEventSource.OnStartFile

void

OnStartFile(CheckoutEventSource source, CheckoutEventArgs args)

{


s
tring

fileName = args.CurrentFile.FullName;


System.Console.WriteLine(
"Starting file: {0}"
, fileName);

}
// OnS
tartFile


// Callback for CheckoutEventSource.OnNotifyProgress

void

OnNotifyProgress(CheckoutEventSource source, CheckoutEventArgs args)

{


string

fileName = args.CurrentFile.FullName;


if

(args.IsFinished)


{ // File is finished, successfully
or cancelled


if

(args.IsCanceled)


System.Console.WriteLine(
"File canceled: {0}"
, fileName);


else



if

(args.IsSuccessful)


System.Console.WriteLine(
"File finished: {0}"
, fileName);


else



Syst
em.Console.WriteLine(
"File failed: {0}"
, fileName);


}

}
// OnNotifyProgress

4.5.

ContentFilter

Th
e
ContentFilter

interface allows
you
to hook into the checkout process at a low level.

It is “contained”
by a specific set of check
-
out options
, hence it is set via
CheckoutOptions.setContentFilter()

in Java,
or

the
CheckoutOptions.ContentFilter

property in .Net
.

When the
ContentFilter

is in effect, the
CheckoutManager

calls the interface’s sole method for each file checked
-
out. In Java:

java.io.
OutputStream
getOutputStream
(File file,

java.io.OutputStream stream)

When this method
is called
,

the StarTeam SDK
File

object for which content is being checked
-
out is
passed

as well as the
OutputStream
. I
t must return a

Java

OutputStream
, to which the che
cked
-
out
content will be
written
. T
he application may wrap this stream to transform content as it sees fit.


StarTeam SDK New Features





November 4, 2013


Page
14

of
25

In .Net, the interface’s method
uses a
Stream

object
:

Stream

GetOutputStream(File

file,

Stream

stream)

You can use

a
ContentFilter

to perform
your o
wn
EOL conversion

or other content conversion
, perform
statistical analysis of each file,
“beautify” the file’s content, and so forth. Below is a Java example that
counts all the bytes and spaces of each contained file. (No, this isn’t exquisite Java, but
it allows us to show
the whole process in one sample.)

// Create a ContentFilter object that counts spaces of each file whose check
-
out

// it hooks.

ContentFilter spaceCounter =
new

ContentFilter ()

{


// Method we're required to implement for the Conte
ntFilter interface.


public

OutputStream getOutputStream(File file, OutputStream outputStream) {


// Create a CounterStream specific for this file and return it. Since we


// create a new stream for each file, this technique is thread
-
safe
.


CounterStream counterStream =
new

CounterStream(file, outputStream);


return

counterStream;


}




// Embedded OutputStream subclass that counts total bytes and spaces that


// flow through the stream.


class

CounterStream
ex
tends

OutputStream {


int

nSpaces;


int

nBytes
;


OutputStream
wrappedStream
;


File wrappedFile;




// Constructor


CounterStream(File file, OutputStream outputStream) {


nBytes

=
0
;


nS
paces =
0
;


wrappedFile = file;


wrappedStream

= outputStream;


}




//
Typically, you should o
verride the single
-
byte
and
byte
-
array write


//
method
s, though they are not called in this example.




// Override the partial byte array write method.


public

void

write(
byte
[] b,
int

off,
int

len)
throws

IOException {


int

tempLen = len;


for

(
int

i = off; i < b.length && tempLen >
0
; i++) {


nBytes
++;



if

(b[i] ==
' '
) nSpaces++;


tempLen
--
;


}


wrappedStream
.write(b, off, len);


}




// Pass
-
through the flush call.


public

void

flush()
throws

IOException {


wrappe
dStream
.flush();


}




StarTeam SDK New Features





November 4, 2013


Page
15

of
25


// Pass
-
through Close and display spaces counted.


public

void

close()
throws

IOException {


wrappedStream
.close();


System.out.println(
"File '"

+ wrappedFile.getName() +



"' contains "

+ nSpaces +
" spaces out of "

+


nBytes

+
" total bytes"
);


}


}
// embedded class CounterStream

};
// anonymous ContentFilter object


// Check
-
out all files from the root folder d
own using a ContentFilter so we can

// count the number of bytes and spaces in each file.

CheckoutOptions coOpts =
new

CheckoutOptions(view);

coOpts.setContentFilter(spaceCounter);

CheckoutManager coMgr =
new

CheckoutManager(view, coOpts);

coMgr.setMPXCach
eAgentEnabled(
true
);

coMgr.checkout(view.getRootFolder(),
-
1
);

For a C# example, let’s make this a little cleaner by using separate classes for the
ContentFilter

and
Stream

objects used for a check
-
out.

// CounterFil
t
er implements the ContentFilter interfa
ce. Each object creates a new

// CounterStream object each time its GetOutputStream is called.

class

CounterFilter : ContentFilter

{


// Method we're required to implement for the ContentFilter interface.


public

Stream GetOutputStream(Borland.StarTe
am.File file, Stream stream)


{


// Create a CounterStream specific for this file and return it. Since we


// create a new stream for each file, this technique is thread
-
safe.


CounterStream counterStream = new CounterStream(file,
stream);


return

counterStream;


}

}
// class CounterFilter


// CounterStream is a Stream subclass that counts total bytes and spaces that flow

// through the stream. It displays its results when Close() is called.

class

CounterStream : Stream

{


// Member variables:


int

nSpaces;


int

nBytes;


Stream wrappedStream;


Borland.StarTeam.File wrappedFile;



// Constructor


public

CounterStream(Borland.StarTeam.File file, Stream stream)


{


nBytes =
0
;


nSpaces
=
0
;


wrappedFile = file;


wrappedStream = stream;


}



// Override the properties and methods required for a Stream

class


public

override

bool

CanWrite {
get

{
return true
;}}


StarTeam SDK New Features





November 4, 2013


Page
16

of
25



// Also overridden but not shown here are the propert
ies

CanRead, CanSeek,


//
Length
,
Position

and the m
ethods

Read
,
Seek
, and
SetLength
. We just throw


// exceptions for these since we don't support them.



// Override the buffer Write method.


public

override

void

Write(byte[] buffer,
int

offs
et,
int

count)


{


int

tempCount = count;


for

(
int

i = offset; i < buffer.Length && tempCount >
0
; i++)


{


nBytes++;


if

(buffer[i] ==
' '
) nSpaces++;


tempCount
--
;


}


wrappedStream
.Write(buffer, offset, count);


}



// Override the single
-
byte write method.


public

override

void

WriteByte(
byte

value)


{


nBytes++;


if

(
value

==
' '
) nSpaces++;


wrappedStream.WriteByte(value);


}



// Pass
-
throu
gh the
F
lush call.


public

override

void

Flush()


{


wrappedStream.Flush();


}



// Pass
-
through Close and display spaces counted.


public

override

void

Close()


{


wrappedStream.Close();


System.Console.WriteLine(
"Fi
le '{0}' contains {1} spaces out of {2}
"

+


"
total bytes"
,

wrappedFile.Name, nSpaces, nBytes);


}

}
// class CounterStream


// Example of how to use these classes:


// Create a ContentFilter object that will count bytes and spaces of each
that

// it is passed.

CounterFilter spaceCounter =
new

CounterFilter();


// Check
-
out all files from the root folder down using a ContentFilter so we can

// count the number of bytes and spaces in each file.

CheckoutOptions coOpts =
new

CheckoutOptions(vie
w);

coOpts.ContentFilter = spaceCounter;

CheckoutManager coMgr =
new

CheckoutManager(view, coOpts);

coMgr.MPXCacheAgentEnabled =
true
;

coMgr.Checkout(view.RootFolder,
-
1
);


StarTeam SDK New Features





November 4, 2013


Page
17

of
25

4.6.

CheckoutProgress

The
CheckoutManager

class provides a method that all
ows you to monitor the overall progress of the
check
-
out as a whole. Specifically,
CheckoutManager
.getProgress()

returns a
CheckoutProgress

object, which has
“get” methods to obtain the following metrics:



General check
-
out command information:



The number o
f threads in use by the check
-
out operation (numbered 0 through (n
-
1)).



The last error that occurred, if any, during the check
-
out operation



Per check
-
out thread statistics:



Whether or not the thread is a Cache Agent thread



Current bytes expected for the t
hread



Current bytes returned so far for the thread



Total files checked
-
out so far for the thread



Check
-
out command totals:



Total number of files check
ed
-
out so far



Total number of files skipped so far (e.g., due to merge conflicts, aborted by the user)



Tot
al number of files
whose
check
-
out

has failed so far (e.g., file can’t be checked
-
out
of an I/O
error on the work file
)



Total number of
files

remaining to be checked
-
out



Total bytes checked
-
out so far overall



Total elapsed time in milliseconds for the curr
ent check
-
out operation so far



Statistics specific to using an MPX Cache Agent:



Total command time by the MPX Cache Agent so far



Total files checked
-
out by the MPX Cache Agent so far



Total files skipped by the MPX Cache Agent so far (e.g., that got a “miss
”)



Total bytes checked
-
out by the MPX Cache Agent so far


StarTeam SDK New Features





November 4, 2013


Page
18

of
25

The
CheckoutProgress

object’s metrics methods can be called, for example, on a separate thread to
display a progress bar for the check
-
out operation.

The example below summarizes a check
-
out requests

results after it completes:

//
C
heck
-
out
all files from a view’s root folder via the Cache Agent.

Checkout
Manager coMgr = new CheckoutManager(view);

coMgr.setMPXCacheAgentEnabled(
true
);

coMgr.checkout(view.getRootFolder(),
-
1
);


// Display final check
-
out

statistics

CheckoutProgress stats = coMgr
.getProgress();

System.out.println(
"Final check
-
out statistics"
);

System.out.println(
" Total files: "

+ stats.getTotalFilesCheckedOut());

System.out.println(
" Total bytes: "

+ stats.getTotalBytesCheckedOut());

float

caTimeSecs = (
float
)stats.getTotalCommandTimeByMPXCacheAgent() /
1000
;

System.out.println(
" CA c/o time: "

+ caTimeSecs +
" seconds"
);

float

totalTimeSecs = (
float
)stats.getTotalCommandTime() /
1000
;

System.out.println(
" Total time: "

+ totalTim
eSecs +
" seconds"
);

float

bytesPerSec = stats.getTotalBytesCheckedOut() / totalTimeSecs;

System.out.println(
" Bytes/sec : "

+ bytesPerSec);

And in C#:

//
C
heck
-
out
all files from a view’s root folder via the Cache Agent.

CheckoutManager coMgr =
new

Che
ckoutManager(view);

coMgr.MPXCacheAgentEnabled =
true
;

coMgr.Checkout(view.RootFolder,
-
1
);


// Display final check
-
out statistics

CheckoutProgress stats = coMgr1.Progress;

System.Console.WriteLine(
"Final check
-
out statistics"
);

System.Console.WriteLine(
"

Total files: {0}"
, stats.TotalFilesCheckedOut);

System.Console.WriteLine(
" Total bytes: {0}"
, stats.TotalBytesCheckedOut);

float

caTimeSecs = ((
float
)stats.TotalCommandTimeByMPXCacheAgent /
1000
);

System.Console.WriteLine(
" CA c/o time: {0} seconds"
,

caTimeSecs);

float

totalTimeSecs = ((
float
)stats.TotalCommandTime /
1000
);

System.Console.WriteLine(
" Total time: {0} seconds"
, totalTimeSecs);

float

bytesPerSec = stats.TotalBytesCheckedOut / totalTimeSecs;

System.Console.WriteLine(
" Bytes/sec : {0
}"
, bytesPerSec);

5.

Not
-
in
-
View Folders

Previously, the SDK provided a way to determine not
-
in
-
view files, but you had to devise your own way to
detect not
-
in
-
view folders. With the R2 release, it’s a little easier to find both not
-
in
-
view fol
ders and files.
The new methods provided on the
Folder

object are:



Folder getFolderTree(int context, int depth)

This method copies the folder tree starting at the current folder, returning a new one with the
specified context.
The
context

value
Filter.CONT
EXT_LOCAL_AND_SERVER

is the one that fetches
not
-
in
-
view folders along with current folders, allowing you to distinguish one from the other. A
tree
depth

val
ue of
-
1 retrieves the entire folder tree.


StarTeam SDK New Features





November 4, 2013


Page
19

of
25



File[] getNotInViewFiles()

This is method has been aroun
d for a while, but it works in conjunction with
getFolderTree()

to
get not
-
in
-
view files. It r
eturn
s an array of local files that are not in
the current
view as defined by
the server within the working folder tree matching this
Folder

object
. Files are fil
tered according to
the folder exclusion list, if any.



void updateFolderTree(int depth)

This is a new method that u
pdates all folders to a
the specified
depth, creating folders in the
repository for each
not
-
in
-
view
folder in the tree.



FolderListManager

Thi
s existing class
now supports
not
-
in
-
view
folders
.

If you call
getFolderID(Folder)

for a not
-
in
-
view folder, it’s ID will be negative.



ItemListManager

This existing class
can be populate
d

with
not
-
in
-
view

File

objects
.

So, for example, your could call
Fold
er.getNotInViewFiles()

and add each File object in the resulting array to an
ItemListManager
. In conjunction with
Folder.
updateFolderTree
()
, this is one way to build a
list of files that need to be added to the repository.

Below is a Java example that show
s how you could find and display all not
-
in
-
view folders and files in a
given view:

// Demonstrate how to find all not
-
in
-
view folders and files in a given view.

void

notInViewFilesDemo(Server server) {


// Get the root folder for the StarDraw main view
.


View view = findView(server,
"StarDraw"
);


Folder rootFolder = view.getRootFolder();


try

{


// Get the same folder, populated with "local and server" context, which


// means that non
-
in
-
view folders will be included in the tree,

and display


// them recursively.


Folder rootFolderWithNIVs =


rootFolder.getFolderTree(Filter.CONTEXT_LOCAL_AND_SERVER,
-
1
);


displayNIVFoldersAndFiles(rootFolderWithNIVs);


}
catch

(IOException ex) {


System.ou
t.println(
"Couldn't get NIV Folders: "

+ ex);


}

}
// notInViewFilesDemo


// Find and display all non
-
in
-
view folders and files in the given folder,

// recursively descending the folder tree.

void

displayNIVFoldersAndFiles(Folder folder) {


//
F
old
er is
not
-
in
-
view
if isNew() is true
.


if

(folder.
isNew()
) {


System.out.println(
"Folder not in view: "

+ folder.getPath());


}
else

{


StarTeam SDK New Features





November 4, 2013


Page
20

of
25


System.out.println(
"Folder: "

+ folder.getPath());


}




// Display not
-
in
-
view files in th
is folder.


try

{


// Get not
-
in
-
view files as an array.


File[] nivFiles = folder.getNotInViewFiles();


if

(nivFiles.length >
0
) {


System.out.println(
" Files not in view:"
);


}


for

(
int

i =
0
; i < nivFi
les.length; i++) {


if

(nivFiles[i].
isNew()
) {


System.out.println(
" "

+ nivFiles[i].getName());


}


}


}
catch

(IOException ex) {


System.out.println(
"Couldn't get NIV files: "

+ ex);


}



/
/ Recurse to call subfolders other than those that start with a ".", which we


// consider hidden/invisible.


Folder[] childFolders = folder.getSubFolders();


for

(
int

i =
0
; i < childFolders.length; i++) {


// Get this folder's name; skip
"." subfolders.


if

(childFolders[i].getName().charAt(0) !=
'.'
) {


displayNIVFoldersAndFiles(childFolders[i]);


}


}

}
// displayNIVFoldersAndFiles

6.

New Event Methods

For several releases now, SDK applications h
ave been able to
receive
update events when MPX was
available and enabled
.
To use MPX
-
generated events, you register listeners such as
FolderListener

or
ItemListener
, which receive
FolderEvent

or
ItemEvent

event objects.

With
Item
-
related events
, you
have

a choice of event listener “granularity”, each interface
yield
ing a trade
-
off between detail and
overhead.
Specifically
,
ItemListener

provides
detailed
event

information
as old
and
new
Item

objects;
ItemIDListener

provides only the ID of each item change;

and
ItemListListener

provides only the
folder and item
Type

of an item
-
related update event.

Although this event facility is powerful, it requires MPX.

6.1.

FolderUpdateEvent and ItemUpdateEvent

With
the StarTeam
2005 R2

release
, it is now possi
ble to detect changes to folders and items without MPX
via poll techniques: refresh, view comparison, and view polling
. Changes detected are reported to the
application with similar events as MPX
-
based events
.

T
he new events
introduce two new event objects
:
FolderUpdateEvent

and
ItemUpdateEvent
. The key difference with these events compared to their
FolderEvent

and
ItemEvent

counterparts is that
they are triggered by explicit API calls made by
your
application rather than externally via MPX. For example, ca
lling
View.refreshFolders()

might trigger
one or more
FolderUpdateEvents
; calling
Item.update()

might trigger an added or changed event.


StarTeam SDK New Features





November 4, 2013


Page
21

of
25

You can create objects that directly implement the
FolderUpdateEvent

and
ItemUpdateEvent

interfaces
.
Alternatively, you

can subclass the
FolderUpdateAdapter

and
ItemUpdateAdapter

classes, respectively,
which provide dummy (stub) implementations of each interface method. That way, you only have to
override the methods you’re interested in.

A

Java

example showing
an in
-
line
implementation of an item update listener is shown below
:

// Demonstrate the new non
-
MPX event methods.

void

newEventsDemo(Server server)
throws

IOException {


// Create an anonymous class to handle an ItemUpdateEvent.


ItemUpdateListener itemCrier =

new

ItemUpdateListener() {


// Called for item additions; only contains a "new item".


public

void

itemAdded(ItemUpdateEvent event) {


Item newItem = event.getNewItem();


String itemType = newItem.getType().getName();



String itemName = newItem.toString();


if

(newItem
instanceof

ChangeRequest) {


itemName =
""

+ ((ChangeRequest)newItem).getNumber();


}


System.out.println(
"New "

+ itemType +
" added: "

+ itemNam
e);


}



// Called for item moves; contains both old and new items.


public

void

itemMoved(ItemUpdateEvent event) {


Item oldItem = event.getOldItem();


Item newItem = event.getNewItem();


String itemTy
pe = newItem.getType().getName();


String itemName = newItem.toString();


if (newItem
instanceof

ChangeRequest) {


itemName =
""

+ ((ChangeRequest)newItem).getNumber();


}


System.out.println(itemT
ype +
" "

+ itemName +
" moved from "

+


oldItem.getParentFolder().getName() +
" to "

+


newItem.getParentFolder().getName());


}



// Called for item updates; contains both old and
new items.


public

void

itemChanged(ItemUpdateEvent event) {


if

(event.getNewItem()
instanceof

ChangeRequest) {


ChangeRequest oldCR = (ChangeRequest)event.getOldItem();


ChangeRequest newCR = (ChangeRequest
)event.getNewItem();


System.out.println(
"ChangeRequest "

+ newCR.getNumber() +


" was modified:"
);


System.out.println(
" Old synopsis: "

+ oldCR.getSynopsis());


System.out.p
rintln(
" New synopsis: "

+ newCR.getSynopsis());


}
else

{


Item newItem = event.getNewItem();


String itemType = newItem.getType().getName();


System.out.println(itemType +
" "

+ newItem.toString()

+


" was modified"
);


}


}



// Called for item deletes; only contains an "old item".


public

void

itemRemoved(ItemUpdateEvent event) {


StarTeam SDK New Features





November 4, 2013


Page
22

of
25


Item oldItem = event.getOldItem();



String itemType = oldItem.getType().getName();


String itemName = oldItem.toString();


if

(oldItem instanceof ChangeRequest) {


itemName =
""

+ ((ChangeRequest)oldItem).getNumber();


}


Syste
m.out.println(itemType +
" "

+ itemName +
" was deleted"
);


}


};




// Now, open a view and register the item update listener created above for


//
file

and CR changes.


View view = findView(server,
"StarDraw"
);


view.addItemUpdat
eListener(itemCrier,


server.typeForName(server.getTypeNames().FILE));


view.addItemUpdateListener(itemCrier,


server.typeForName(server.getTypeNames().CHANGEREQUEST));




// Now make some changes.


Folder rootFolder = view.getRoo
tFolder();


File newFile =
new

File(rootFolder);


newFile.setName(
"TestFile.txt"
);


String workfileName = newFile.getFullName();


java.io.File workFile =
new

java.io.File(workfileName);


if

(!workFile.exists()) {


workFile.createNewFi
le();


}


newFile.update();


Folder srcFolder = StarTeamFinder.findFolder(rootFolder,
"Source Code"
);


newFile.move(srcFolder);


newFile.remove();


ChangeRequest testCR =
new

ChangeRequest(rootFolder);


testCR.setSynopsis(
"Just testing
"
);


testCR.update();


testCR.move(srcFolder);


testCR.setSynopsis(
"Just testing an update"
);


testCR.update();

}
// newEventsDemo

In this example, item update events are fired by specific item update commands:
update()
,
move()
, and
remove()
.

Note, however, that various refresh commands that your application calls such as
View.refreshFolders()

could also trigger item and folder update events.

6.2.

ViewConfigurationDiffer

The
R2
SK
also adds a
ViewConfigurationDiffer

class, which
comp
ares two configurations of a given
view, generating

FolderUpdateEvents

and
ItemUpdateEvents

that
“replay”
the differences between the
two.

A
ViewConfigurationDiffer

object is created in the context of a
View
, but what it
compares

are two
ViewConfiguration

objects,
each
which
represent
s

a
different snapshot of the same view. Note that only
differences detectable by comparing are reported. For example, if an item is added but then deleted
between the two snapshots, the item will not be reported.

Suppose for e
xample, you want to
“replay”
all the changes between
a snapshot of a view as of a label and
the current (tip)
version of the
view. Below is an example of how to do this in Java:


StarTeam SDK New Features





November 4, 2013


Page
23

of
25

// Demonstrate the new ViewConfigurationDiffer object.

void

viewConfigDifferDe
mo(Server server) {


// Open the StarDraw main view.


View view = findView(server,
"StarDraw"
);




// Create item and folder update listeners

(these methods are defined elsewhere)
.


ItemUpdateListener itemCrier = createItemUpdateListener();


FolderUpdateListener folderCrier = createFolderUpdateListener();



// Create a view configuration differ, and register update listeners for all item


// types (except Audits) and for folders.


ViewConfigurationDiffer viewDiffer = new ViewConfi
gurationDiffer(view);


Type[] types = server.getTypes();


for

(
int

i =
0
; i < types.length; i++) {


if

(types[i].isItemType() && !types[i].getName().equals(
"Audit"
)) {


viewDiffer.addItemUpdateListener(itemCrier, types[i]);



System.out.println(
"Update listener registered for type: "

+


types[i].toString());


}


}


view.addFolderUpdateListener(folderCrier);


System.out.println(
"Update listener registered for folders"
);




// Create view configuration objects based on the labels "Build 1" and tip.


int

label
ID = findViewLabel(view,
"Build 1"
);


ViewConfiguration config1 = ViewConfiguration.createFromLabel(
label
ID);


ViewConfiguration config2 = ViewConfiguration.crea
teTip();



// Compare the two configurations, which will fire ItemUpdateEvents and


// FolderUpdateEvents for differences between the two configurations.


viewDiffer.compare(config1, config2);

}
// viewConfigDifferDemo

6.3.

ViewPolling
Agent

The R2 S
D
K also provides a

new
ViewPollingAgent

class
, which
determines the changes that have been
made to a given view since a known point in time, generating

the same

FolderUpdateEvents

and
ItemUpdateEvents

described in the previous sections
. The e
vents represent a replay of
the changes

that
occurred between the two snapshots
.
There are two basic ways to
use
a
ViewPollingAgent
:



You
can
create
a single
ViewPollingAgent

and call
refresh()
at regular intervals
. Each refresh
causes the agent to trigger e
vents for changes that occurred since the last refresh. Note that this
technique
consumes more resources (mostly SDK memory), but refreshes are quicker.



Alternatively, you can create a
ViewPollingAgent
,
save the timestamp returned by
refresh()
, and
close t
he view or server.

Later, possibly in another application instance, create a new
ViewPollingAgent

initialized with the timestamp you saved, and call
refresh()

again. This
technique uses less memory (especially if you actually close the server connection),
but it takes
longer to perform each
refresh()

call.

In both cases, the
ViewPollingAgent

can not detect
changes that are “undone” between refreshes such as
an item being added and then deleted. Also, currently the exact time items are deleted cannot be dete
rmined
,

StarTeam SDK New Features





November 4, 2013


Page
24

of
25

hence

these events are always triggered last. Finally, if you use the
ViewPollingAgent

to connect to older
StarTeam Servers, it cannot detect item moves.

The
Java
example below uses a
ViewPollingAgent

to poll for changes
each time the user presses
Enter
:

// Demonstrate the new ViewPollingAgent class.

void

viewPollingAgentDemo(Server server) {


// Open the StarDraw main view.


View view = findView(server,
"StarDraw"
);




// Create a ViewPollingAgent object whose first timestamp is "now".


OLEDate timestamp =
new

OLEDate();
// sets
timestamp
to "now"


ViewPollingAgent viewPoller =
new

ViewPollingAgent(view, timestamp);




// Register item and folder update listeners.


ItemUpdateListener itemCrier = createItemUpdateListener()
;


FolderUpdateListener folderCrier = createFolderUpdateListener();


Type[] types = server.getTypes();


for

(
int

i =
0
; i < types.length; i++) {


if

(types[i].isItemType() && !types[i].getName().equals(
"Audit"
)) {


viewPoller.add
ItemUpdateListener(itemCrier, types[i]);


}


}


view.addFolderUpdateListener(folderCrier);



// Ask the user when to take successive snapshots.


String prompt = null;


do

{


System.out.println(
"Last view snapshot taken at: "

+


timestamp.localString(DateFormat.MEDIUM, DateFormat.MEDIUM));


prompt = prompt(
"Press Enter for next snapshot; Q to quit"
);


if

(!prompt.regionMatches(
true
,
0
,
"q"
,
0
,
1
)) {


timestamp = viewPoller.refresh();


}


}
while

(!prompt.regionMatches(
true
,
0
,
"q"
,
0
,
1
));

}
// viewPollingAgentDemo

7.

References



Writing StarTeam Utilities with Delphi and the StarTeam SDK
,
Jon Robertson
, Borland Developer
Conference 2005
Session
#
2128
.



Accelerating File Ch
eck
-
outs with the StarTeamMPX Cache Agent
, Randy Guck,
Borland Developer
Conference 2005

Session
#3138.



StarTeam URLs: Creating and Using Persistent Links to StarTeam Artifacts
, Jim Wogulis,
Borland
Developer Conference 2005

Session
#9204.



StarTeam SDK Adv
anced Programming Topics
, Ron Sauers, BorCon 2004,
http://bdn.borland.com/borcon2004/article/paper/0,1963,32231,00.html



Targeting Java, COM, and .NET with the StarTeam SD
K
, Ron Sauers, BorCon 2004,
http://bdn.borland.com/borcon2004/article/paper/0,1963,32232,00.html


StarTeam SDK New Features





November 4, 2013


Page
25

of
25

All Borland brand and product names are trademarks or registered trademar
ks of Borland Software
Corporation in the United States and other countries. Microsoft, Windows, and other Microsoft product
names are trademarks or registered trademarks of Microsoft Corporation in the U.S. and other countries.
All other marks are the pro
perty of their respective owners.