public int getWidth() {
        int width = 0;

        for ( final Iterator<Row> rowIter = this.rows.iterator(); rowIter.hasNext(); ) {
            final Row row = rowIter.next();
            final int rowWidth = row.getWidth();

            if ( rowWidth > width ) {
                width = rowWidth;
            }
        }

        return width;
    }

public int getWidth ( ) { int width = 0 ; for ( final Iterator < Row > rowIter = this . rows . iterator ( ) ; rowIter . hasNext ( ) ; ) { final Row row = rowIter . next ( ) ; final int rowWidth = row . getWidth ( ) ; if ( rowWidth > width ) { width = rowWidth ; } } return width ; }

Finds the longest row width.

@return width of the longest row


public void dump() {
        final int numRows = this.rows.size();

        for ( int i = 0; i < numRows; ++i ) {
            System.err.println( i + ": " + get( i ).getVertices() );
        }
    }

public
void
dump
(
)
{
final
int
numRows
=
this
.
rows
.
size
(
)
;
for
(
int
i
=
0
;
i
<
numRows
;
++
i
)
{
System
.
err
.
println
(
i
+
": "
+
get
(
i
)
.
getVertices
(
)
)
;
}
}


public void optimize() {
        final int numRows = this.rows.size();

        for ( int i = 0; i < numRows; ++i ) {
            get( i ).optimize();
        }
    }

public void optimize ( ) { final int numRows = this . rows . size ( ) ; for ( int i = 0 ; i < numRows ; ++ i ) { get ( i ) . optimize ( ) ; } }

Optimizes all rows for optimal presentation


public ReteGraph loadReteModel(IProgressMonitor monitor,
                                   String contents) throws Throwable {
        if ( relayoutRequired == false ) {
            return diagram;
        }

        ReteGraph newDiagram = new ReteGraph();

        try {

            monitor.beginTask( "Loading RETE Tree",
                               100 );

            monitor.subTask( "Loading Rule Base" );
            InternalKnowledgeBase ruleBase = null;
            try {
                IResource resource = drlEditor.getResource();
                ClassLoader newLoader = DroolsBuilder.class.getClassLoader();
                if ( resource.getProject().getNature( "org.eclipse.jdt.core.javanature" ) != null ) {
                    IJavaProject project = JavaCore.create( resource.getProject() );
                    newLoader = ProjectClassLoader.getProjectClassLoader( project );
                }
                DRLInfo drlInfo = DroolsEclipsePlugin.getDefault().parseResource(drlEditor, true, true);
                if (drlInfo == null) {
                    throw new Exception( "Could not find DRL info" );
                }
                if (drlInfo.getBuilderErrors().length > 0) {
                    throw new Exception( drlInfo.getBuilderErrors().length + " build errors" );
                }
                if (drlInfo.getParserErrors().size() > 0) {
                    throw new Exception( drlInfo.getParserErrors().size() + " parser errors" );
                }

                InternalKnowledgePackage pkg = drlInfo.getPackage();
                RuleBaseConfiguration config = new RuleBaseConfiguration();
                config.setClassLoader(newLoader);
                ruleBase = KnowledgeBaseFactory.newKnowledgeBase(config);
                if (pkg != null) {
                    ruleBase.addPackage(pkg);
                }
            } catch ( Throwable t ) {
                DroolsEclipsePlugin.log( t );
                throw new Exception( MSG_PARSE_ERROR + " " + t.getMessage());
            }

            monitor.worked( 50 );
            if ( monitor.isCanceled() ) {
                throw new InterruptedException();
            }

            monitor.subTask( "Building RETE Tree" );
            final ReteooVisitor visitor = new ReteooVisitor( newDiagram );
            visitor.visitInternalKnowledgeBase( ruleBase );
            monitor.worked( 30 );
            if ( monitor.isCanceled() ) {
                throw new InterruptedException();
            }

            monitor.subTask( "Calculating RETE Tree Layout" );
            BaseVertex rootVertex = visitor.getRootVertex();
            RowList rowList = ReteooLayoutFactory.calculateReteRows( rootVertex );
            ReteooLayoutFactory.layoutRowList( newDiagram,
                                               rowList );
            zeroBaseDiagram( newDiagram );
            monitor.worked( 20 );
            if ( monitor.isCanceled() ) {
                throw new InterruptedException();
            }
            monitor.done();

        } catch ( Throwable t ) {
            if ( !(t instanceof InterruptedException) ) {
                DroolsEclipsePlugin.log( t );
            }
            throw t;
        }
        relayoutRequired = false;
        return newDiagram;
    }

public
ReteGraph
loadReteModel
(
IProgressMonitor
monitor
,
String
contents
)
throws
Throwable
{
if
(
relayoutRequired
==
false
)
{
return
diagram
;
}
ReteGraph
newDiagram
=
new
ReteGraph
(
)
;
try
{
monitor
.
beginTask
(
"Loading RETE Tree"
,
100
)
;
monitor
.
subTask
(
"Loading Rule Base"
)
;
InternalKnowledgeBase
ruleBase
=
;
try
{
IResource
resource
=
drlEditor
.
getResource
(
)
;
ClassLoader
newLoader
=
DroolsBuilder
.
class
.
getClassLoader
(
)
;
if
(
resource
.
getProject
(
)
.
getNature
(
"org.eclipse.jdt.core.javanature"
)
!=
)
{
IJavaProject
project
=
JavaCore
.
create
(
resource
.
getProject
(
)
)
;
newLoader
=
ProjectClassLoader
.
getProjectClassLoader
(
project
)
;
}
DRLInfo
drlInfo
=
DroolsEclipsePlugin
.
getDefault
(
)
.
parseResource
(
drlEditor
,
true
,
true
)
;
if
(
drlInfo
==
)
{
throw
new
Exception
(
"Could not find DRL info"
)
;
}
if
(
drlInfo
.
getBuilderErrors
(
)
.
length
>
0
)
{
throw
new
Exception
(
drlInfo
.
getBuilderErrors
(
)
.
length
+
" build errors"
)
;
}
if
(
drlInfo
.
getParserErrors
(
)
.
size
(
)
>
0
)
{
throw
new
Exception
(
drlInfo
.
getParserErrors
(
)
.
size
(
)
+
" parser errors"
)
;
}
InternalKnowledgePackage
pkg
=
drlInfo
.
getPackage
(
)
;
RuleBaseConfiguration
config
=
new
RuleBaseConfiguration
(
)
;
config
.
setClassLoader
(
newLoader
)
;
ruleBase
=
KnowledgeBaseFactory
.
newKnowledgeBase
(
config
)
;
if
(
pkg
!=
)
{
ruleBase
.
addPackage
(
pkg
)
;
}
}
catch
(
Throwable
t
)
{
DroolsEclipsePlugin
.
log
(
t
)
;
throw
new
Exception
(
MSG_PARSE_ERROR
+
" "
+
t
.
getMessage
(
)
)
;
}
monitor
.
worked
(
50
)
;
if
(
monitor
.
isCanceled
(
)
)
{
throw
new
InterruptedException
(
)
;
}
monitor
.
subTask
(
"Building RETE Tree"
)
;
final
ReteooVisitor
visitor
=
new
ReteooVisitor
(
newDiagram
)
;
visitor
.
visitInternalKnowledgeBase
(
ruleBase
)
;
monitor
.
worked
(
30
)
;
if
(
monitor
.
isCanceled
(
)
)
{
throw
new
InterruptedException
(
)
;
}
monitor
.
subTask
(
"Calculating RETE Tree Layout"
)
;
BaseVertex
rootVertex
=
visitor
.
getRootVertex
(
)
;
RowList
rowList
=
ReteooLayoutFactory
.
calculateReteRows
(
rootVertex
)
;
ReteooLayoutFactory
.
layoutRowList
(
newDiagram
,
rowList
)
;
zeroBaseDiagram
(
newDiagram
)
;
monitor
.
worked
(
20
)
;
if
(
monitor
.
isCanceled
(
)
)
{
throw
new
InterruptedException
(
)
;
}
monitor
.
done
(
)
;
}
catch
(
Throwable
t
)
{
if
(
!
(
t
instanceof
InterruptedException
)
)
{
DroolsEclipsePlugin
.
log
(
t
)
;
}
throw
t
;
}
relayoutRequired
=
false
;
return
newDiagram
;
}

Loads model from rule base,
calculates rete view and initializes diagram model.
@param monitor
@param contents
@return

Loads model from rule base calculates rete view and initializes diagram model .


protected void initializeGraphicalViewer() {
        ZoomManager zoomManager = rootEditPart.getZoomManager();

        //List<String>
        List<String> zoomLevels = new ArrayList<String>(3);

        zoomLevels.add( ZoomManager.FIT_ALL );
        zoomLevels.add( ZoomManager.FIT_HEIGHT );
        zoomLevels.add( ZoomManager.FIT_WIDTH );

        zoomManager.setZoomLevelContributions( zoomLevels );

        // Zoom mousewheel - Ctrl+Mousewheel for zoom in/out
        getGraphicalViewer().setProperty( MouseWheelHandler.KeyGenerator.getKey( SWT.MOD1 ),
                                          MouseWheelZoomHandler.SINGLETON );

    }

Loads Rete model and initializes zoom manager.

Loads Rete model and initializes zoom manager .


public void drawGraph(ReteGraph newGraph) {

        LayerManager manager = (LayerManager) getGraphicalViewer().getEditPartRegistry().get( LayerManager.ID );
        ConnectionLayer connLayer = (ConnectionLayer) manager.getLayer( LayerConstants.CONNECTION_LAYER );

        // Lazy-init model initialization
        if ( getGraphicalViewer().getContents() == null ) {
            getGraphicalViewer().setContents( getModel() );
        }

        final boolean isNewDiagram = newGraph != null && newGraph != diagram;

        if ( isNewDiagram ) {
            diagram.removeAll();
        }

        // Update connection router according to new model size
        ConnectionRouter router;
        if ( (isNewDiagram && newGraph.getChildren().size() < SIMPLE_ROUTER_MIN_NODES) || (!isNewDiagram && getModel().getChildren().size() < SIMPLE_ROUTER_MIN_NODES) ) {
            router = new ShortestPathConnectionRouter( (IFigure) rootEditPart.getContentPane().getChildren().get( 0 ) );
        } else {
            router = ConnectionRouter.NULL;
        }
        connLayer.setConnectionRouter( router );

        if ( newGraph != null && newGraph != diagram ) {
            diagram.addAll( newGraph.getChildren() );
        }

    }

Draws graph.

@param newGraph used to replace existing graph. if null then existing graph is simply redrawn.


public DroolsLineBreakpoint getDroolsBreakpoint(String source) {

        if ( source == null ) {
            return null;
        }

        Iterator<IBreakpoint> iterator = getBreakpoints().iterator();
        while ( iterator.hasNext() ) {
            IJavaBreakpoint element = (IJavaBreakpoint) iterator.next();
            if ( element instanceof DroolsLineBreakpoint && ((DroolsLineBreakpoint) element).getDialectName().equals( "mvel" ) ) {
                DroolsLineBreakpoint l = (DroolsLineBreakpoint) element;
                try {

                    int matchLine = l.getLineNumber();
                    String matchSource = l.getRuleName();

                    if ( source.equals( matchSource ) || l.getFileRuleMappings().containsKey( source ) ) {
                        return l;
                    }

                } catch ( CoreException e ) {
                    logError( e );
                }
            }
        }

        return null;
    }

public DroolsLineBreakpoint getDroolsBreakpoint ( String source ) { if ( source == null ) { return null ; } Iterator < IBreakpoint > iterator = getBreakpoints ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { IJavaBreakpoint element = ( IJavaBreakpoint ) iterator . next ( ) ; if ( element instanceof DroolsLineBreakpoint && ( ( DroolsLineBreakpoint ) element ) . getDialectName ( ) . equals ( "mvel" ) ) { DroolsLineBreakpoint l = ( DroolsLineBreakpoint ) element ; try { int matchLine = l . getLineNumber ( ) ; String matchSource = l . getRuleName ( ) ; if ( source . equals ( matchSource ) || l . getFileRuleMappings ( ) . containsKey ( source ) ) { return l ; } } catch ( CoreException e ) { logError ( e ) ; } } } return null ; }

Tries to find a match for the provided breakpoint information from the list of registered breakpoints.
For stepping and possibly other purposes it returns also a breakpoint for cases where exactly the same line was not found.

If breakpoint is not found for line at source then it takes the first line that is above the
specified line at the same file.

@param source
@param line
@return

Tries to find a match for the provided breakpoint information from the list of registered breakpoints . For stepping and possibly other purposes it returns also a breakpoint for cases where exactly the same line was not found .


public void setHref(String href) {
        Assert.isNotNull(href);
        setChild(root, "href", encodeHref(href), childNames, true); //$NON-NLS-1$
    }

public void setHref ( String href ) { Assert . isNotNull ( href ) ; setChild ( root , "href" , encodeHref ( href ) , childNames , true ) ; //$NON-NLS-1$ }

Sets this baseline control elment description to the given href.

@param href the href of the baseline.

Sets this baseline control elment description to the given href .


public boolean canTalkDAV() throws DAVException {
        IResponse response = null;
        try {
            // Send an options request.
            response = davClient.options(locator, newContext());
            examineResponse(response);

            // Check for at least DAV level 1.
            String davHeader = response.getContext().getDAV();
            return !((davHeader == null) || (davHeader.indexOf("1") == -1)); //$NON-NLS-1$
        } catch (IOException exception) {
            throw new SystemException(exception);
        } finally {
            closeResponse(response);
        }
    }

public
boolean
canTalkDAV
(
)
throws
DAVException
{
IResponse
response
=
;
try
{
// Send an options request.
response
=
davClient
.
options
(
locator
,
newContext
(
)
)
;
examineResponse
(
response
)
;
// Check for at least DAV level 1.
String
davHeader
=
response
.
getContext
(
)
.
getDAV
(
)
;
return
!
(
(
davHeader
==
)
||
(
davHeader
.
indexOf
(
"1"
)
==
1
)
)
;
//$NON-NLS-1$
}
catch
(
IOException
exception
)
{
throw
new
SystemException
(
exception
)
;
}
finally
{
closeResponse
(
response
)
;
}
}

Return a boolean value indicating whether or not the server for this resource
is DAV compliant.

@return boolean true if the server can respond to DAV
requests, or false otherwise.
@exception DAVException if there was a problem checking for DAV compliance

Return a boolean value indicating whether or not the server for this resource is DAV compliant .


public void copy(ILocator destination, String depth, boolean overwrite, Collection propertyNames) throws DAVException {
        // Define the request context.
        IContext context = newContext();
        context.setDepth(depth);
        context.setOverwrite(overwrite);

        // Set up the request body to specify which properties should be kept alive.
        Document document = newDocument();
        PropertyBehavior propertyBehavior = PropertyBehavior.create(document);

        if (propertyNames == null)
            propertyBehavior.setIsKeepAllAlive(true);
        else {
            Iterator namesItr = propertyNames.iterator();
            while (namesItr.hasNext()) {
                QualifiedName name = (QualifiedName) namesItr.next();
                String nameURI = name.getQualifier() + "/" + name.getLocalName(); //$NON-NLS-1$
                propertyBehavior.addProperty(nameURI);
            } // end-while
        } // end-if

        // Call the server to perform the copy.
        IResponse response = null;
        try {
            response = davClient.copy(locator, destination, context, document);
            examineResponse(response);
            examineMultiStatusResponse(response);
        } catch (IOException e) {
            throw new SystemException(e);
        } finally {
            closeResponse(response);
        }
    }

Make a copy of this resource and place it at the location specified
by the given destination locator.

@param destination the location to put the copy.
@param depth how deep to make the copy.
@param overwrite how to react if a resource already exists at the destination.
@param propertyNames Collection of QualifiedNames
of properties that MUST be copied as live properties.  Specifying null
mean that all properties must be kept alive; specifying an empty collection allows for
no properties to be kept live. (ref http://andrew2.andrew.cmu.edu/rfc/rfc2518.html#sec-12.12.1)
@exception DAVException if there was a problem copying this resource.
@see IServer#copy(ILocator, ILocator, IContext, Document)

Make a copy of this resource and place it at the location specified by the given destination locator .


protected void examineMultiStatusResponse(IResponse response) throws DAVException {
        // If it is not a multistatus we don't look at it.
        if (response.getStatusCode() != IResponse.SC_MULTI_STATUS)
            return;

        // It is declared a multistatus, so if there is no response body
        // then that is a problem.
        if (!response.hasDocumentBody())
            throw new DAVException(Policy.bind("exception.responseMustHaveDocBody")); //$NON-NLS-1$

        // Extract the XML document from the response.
        Element documentElement;
        try {
            documentElement = response.getDocumentBody().getDocumentElement();
            if (documentElement == null)
                throw new DAVException(Policy.bind("exception.invalidDoc")); //$NON-NLS-1$
        } catch (IOException exception) {
            throw new SystemException(exception);
        }

        // Enumerate all the responses in the multistat and check that
        // they are indicating success (i.e. are 200-series response codes).
        try {
            MultiStatus multistatus = new MultiStatus(documentElement);
            Enumeration responseEnum = multistatus.getResponses();
            while (responseEnum.hasMoreElements()) {
                ResponseBody responseBody = (ResponseBody) responseEnum.nextElement();
                Enumeration propstatEnum = responseBody.getPropStats();
                while (propstatEnum.hasMoreElements()) {
                    PropStat propstat = (PropStat) propstatEnum.nextElement();
                    examineStatusCode(propstat.getStatusCode(), propstat.getResponseDescription());
                } // end-while
            } // end-while
        } catch (MalformedElementException e) {
            throw new SystemException(e);
        }
    }

If the given response contains a multistatus body, the bodies status'
are checked for errors. If an error is found, an exception is thrown.

@param response the response from the server to examine.
@throws DAVException if the given response contains a multistatus
body that contains a status code signalling an error.

If the given response contains a multistatus body the bodies status are checked for errors . If an error is found an exception is thrown .


protected URLTable extractPropStats(MultiStatus multiStatus) throws IOException, MalformedElementException {
        // Construct a URLTable to return to the user.
        URLTable reply = new URLTable();

        // For each response (resource).
        Enumeration responses = multiStatus.getResponses();
        while (responses.hasMoreElements()) {
            ResponseBody responseBody = (ResponseBody) responses.nextElement();
            String href = responseBody.getHref();

            // The href may be relative to the request URL.
            URL resourceURL = new URL(new URL(locator.getResourceURL()), href);
            Hashtable properties = new Hashtable();
            reply.put(resourceURL, properties);

            // For each property status grouping.
            Enumeration propstats = responseBody.getPropStats();
            while (propstats.hasMoreElements()) {
                PropStat propstat = (PropStat) propstats.nextElement();
                org.eclipse.webdav.dom.Status status = new org.eclipse.webdav.dom.Status(propstat.getStatus());

                // For each property with this status.
                Enumeration elements = propstat.getProp().getProperties();
                while (elements.hasMoreElements()) {
                    Element element = (Element) elements.nextElement();
                    QualifiedName name = ElementEditor.getQualifiedName(element);
                    // Add a property status object to the result set.
                    PropertyStatus propertyStatus = new PropertyStatus(element, status.getStatusCode(), status.getStatusMessage());
                    properties.put(name, propertyStatus);
                } // end-while
            } // end-while
        } // end-while

        return reply;
    }

Helper method to extract the property status response from
a multi status reponse, and populate a URLTable with the
results.

@param multiStatus an editor on the response from the server.
@return all the property status in a URLTable.
@throws IOException if there is a problem parsing the resource URLs.
@throws MalformedElementException if the XML is badly formed.

Helper method to extract the property status response from a multi status reponse and populate a URLTable with the results .


public ResponseInputStream getContent() throws DAVException {
        IResponse response = null;
        try {
            response = davClient.get(locator, newContext());
            examineResponse(response);
        } catch (IOException e) {
            closeResponse(response);
            throw new SystemException(e);
        }
        return new ResponseInputStream(response);
    }

public ResponseInputStream getContent ( ) throws DAVException { IResponse response = null ; try { response = davClient . get ( locator , newContext ( ) ) ; examineResponse ( response ) ; } catch ( IOException e ) { closeResponse ( response ) ; throw new SystemException ( e ) ; } return new ResponseInputStream ( response ) ; }

Return the content of this resource as an input stream. The input
stream should be closed by the user.

@return the input stream
@exception DAVException if there was a problem getting the contents
@see IServer#get(Locator, Context)

Return the content of this resource as an input stream . The input stream should be closed by the user .


public Enumeration getLocks() throws DAVException {
        LockDiscovery lockdiscovery = null;
        try {
            Element element = getProperty(DAV_LOCK_DISCOVERY).getProperty();
            lockdiscovery = new LockDiscovery(element);
            return lockdiscovery.getActiveLocks();
        } catch (WebDAVException exception) {
            if (exception.getStatusCode() == IResponse.SC_NOT_FOUND)
                return new EmptyEnumeration();
            throw exception;
        } catch (MalformedElementException elemException) {
            throw new SystemException(elemException);
        }
    }

public Enumeration getLocks ( ) throws DAVException { LockDiscovery lockdiscovery = null ; try { Element element = getProperty ( DAV_LOCK_DISCOVERY ) . getProperty ( ) ; lockdiscovery = new LockDiscovery ( element ) ; return lockdiscovery . getActiveLocks ( ) ; } catch ( WebDAVException exception ) { if ( exception . getStatusCode ( ) == IResponse . SC_NOT_FOUND ) return new EmptyEnumeration ( ) ; throw exception ; } catch ( MalformedElementException elemException ) { throw new SystemException ( elemException ) ; } }

Return an Enumeration over ActiveLocks which lists the locks currently
held on this resource. Return an empty enumeration if the lock discovery
property is not found on the resource.

@return the enumeration of active locks
@exception DAVException if there was a problem getting the locks
@see #getProperty(QualifiedName)

Return an Enumeration over ActiveLocks which lists the locks currently held on this resource . Return an empty enumeration if the lock discovery property is not found on the resource .


public PropertyStatus getProperty(QualifiedName propertyName) throws DAVException {
        Collection names = new HashSet();
        names.add(propertyName);
        URLTable result = getProperties(names, IContext.DEPTH_ZERO);

        URL url = null;
        try {
            url = new URL(locator.getResourceURL());
        } catch (MalformedURLException e) {
            throw new SystemException(e);
        }

        Hashtable propTable = (Hashtable) result.get(url);
        if (propTable == null)
            throw new DAVException(Policy.bind("exception.lookup", url.toExternalForm())); //$NON-NLS-1$
        return (PropertyStatus) propTable.get(propertyName);
    }

public PropertyStatus getProperty ( QualifiedName propertyName ) throws DAVException { Collection names = new HashSet ( ) ; names . add ( propertyName ) ; URLTable result = getProperties ( names , IContext . DEPTH_ZERO ) ; URL url = null ; try { url = new URL ( locator . getResourceURL ( ) ) ; } catch ( MalformedURLException e ) { throw new SystemException ( e ) ; } Hashtable propTable = ( Hashtable ) result . get ( url ) ; if ( propTable == null ) throw new DAVException ( Policy . bind ( "exception.lookup" , url . toExternalForm ( ) ) ) ; //$NON-NLS-1$ return ( PropertyStatus ) propTable . get ( propertyName ) ; }

Return the property status for the property with the given name.

@param propertyName the name of the property
@return the property status
@exception DAVException if there was a problem getting the property
@see #getProperties(Collection, String)

Return the property status for the property with the given name .


public IContext head() throws DAVException {
        IResponse response = null;
        try {
            response = davClient.head(locator, newContext());
            examineResponse(response);
            return response.getContext();
        } catch (IOException exception) {
            throw new SystemException(exception);
        } finally {
            closeResponse(response);
        }
    }

public IContext head ( ) throws DAVException { IResponse response = null ; try { response = davClient . head ( locator , newContext ( ) ) ; examineResponse ( response ) ; return response . getContext ( ) ; } catch ( IOException exception ) { throw new SystemException ( exception ) ; } finally { closeResponse ( response ) ; } }

Return the header from a message send to the server.

@return a context with the message header contents
@exception DAVException if there was a problem sending the message
@see IServer#head(Locator, Context)

Return the header from a message send to the server .


public LockToken lock(boolean isShared, String depth, int timeout, String owner) throws DAVException {

        // Define the request context.
        IContext context = newContext();
        context.setDepth(depth);
        context.setTimeout(timeout);

        // Create the request body.
        Document document = newDocument();
        LockInfo lockinfo = LockInfo.create(document);
        lockinfo.setIsShared(isShared);

        // Add the owner if it is given.
        if (owner != null) {
            Owner ownerEditor = lockinfo.setOwner();
            ownerEditor.getElement().appendChild(document.createTextNode(owner));
        }

        // Send the lock request.
        IResponse response = null;
        try {
            response = davClient.lock(locator, context, document);
            examineResponse(response);
        } catch (IOException e) {
            throw new SystemException(e);
        } finally {
            closeResponse(response);
        }

        // Extract the token from the resulting context.
        LockToken token = new LockToken(response.getContext().getLockToken());
        //fServerManager.addLock(newURL(fLocator.getResourceURL()), token, depth);
        return token;
    }

Lock this resource using the specified parameters.

@param isShared true if the lock is shared, false if the lock is exclusive
@param depth eg. Context.DEPTH_ZERO
@param timeout the timeout value for the lock
@param owner the owner of the lock
@return the lock token
@exception DAVException if there was a problem locking this resource
@see IServer#lock(Locator, Context, Document)

Lock this resource using the specified parameters .


public void move(ILocator destination, boolean overwrite, Enumeration names) throws DAVException {
        IContext context = newContext();
        context.setOverwrite(overwrite);

        Document document = newDocument();
        PropertyBehavior propertyBehavior = PropertyBehavior.create(document);

        if (names == null) {
            propertyBehavior.setIsKeepAllAlive(true);
        } else {
            while (names.hasMoreElements()) {
                Object obj = names.nextElement();
                Assert.isTrue(obj instanceof QualifiedName, Policy.bind("assert.propNameMustBeEnumOverQual")); //$NON-NLS-1$
                // fix this...can we really add property names to href elements?
                propertyBehavior.addProperty(((QualifiedName) obj).getLocalName());
            }
        }

        IResponse response = null;
        try {
            response = davClient.move(locator, destination, context, document);
            examineResponse(response);
            examineMultiStatusResponse(response);
        } catch (IOException e) {
            throw new SystemException(e);
        } finally {
            closeResponse(response);
        }
    }

Move this resource to the location specified by the given locator.
If a resource already exists at the destination and the overwrite
boolean is true, then write over top of the existing resource. Otherwise
do not. The enumeration is over qualified names which are the names of
the properties to move.

@param destination the location to move to
@param overwrite how to react if a resource already exists at the
destination
@param names Enumeration over QualifiedNames
@exception DAVException if there was a problem moving this resource
@see IServer#move(Locator, Locator, Context, Document)

Move this resource to the location specified by the given locator . If a resource already exists at the destination and the overwrite boolean is true then write over top of the existing resource . Otherwise do not . The enumeration is over qualified names which are the names of the properties to move .


protected ILocator protectedCheckIn() throws DAVException {
        IResponse response = null;
        try {
            response = davClient.checkin(locator, newContext(), null);
            examineResponse(response);
            String versionUrl = response.getContext().getLocation();
            return davClient.getDAVFactory().newStableLocator(versionUrl);
        } catch (IOException e) {
            throw new SystemException(e);
        } finally {
            closeResponse(response);
        }
    }

protected ILocator protectedCheckIn ( ) throws DAVException { IResponse response = null ; try { response = davClient . checkin ( locator , newContext ( ) , null ) ; examineResponse ( response ) ; String versionUrl = response . getContext ( ) . getLocation ( ) ; return davClient . getDAVFactory ( ) . newStableLocator ( versionUrl ) ; } catch ( IOException e ) { throw new SystemException ( e ) ; } finally { closeResponse ( response ) ; } }

Check in the receiver and answer a new Locator on the
resulting version resource.

@return the Locator to the receiver's version.
@throws DAVException if a problem occurs with the check in request.

Check in the receiver and answer a new Locator on the resulting version resource .


public void refreshLock(LockToken lockToken, int timeout) throws DAVException {
        // Set up the request in the context.
        IContext context = newContext();
        context.setTimeout(timeout);
        context.setLockToken(lockToken.getToken());

        // Send the request to the server.
        IResponse response = null;
        try {
            response = davClient.lock(locator, context, null);
            examineResponse(response);
        } catch (IOException e) {
            throw new SystemException(e);
        } finally {
            closeResponse(response);
        }
    }

public
void
refreshLock
(
LockToken
lockToken
,
int
timeout
)
throws
DAVException
{
// Set up the request in the context.
IContext
context
=
newContext
(
)
;
context
.
setTimeout
(
timeout
)
;
context
.
setLockToken
(
lockToken
.
getToken
(
)
)
;
// Send the request to the server.
IResponse
response
=
;
try
{
response
=
davClient
.
lock
(
locator
,
context
,
)
;
examineResponse
(
response
)
;
}
catch
(
IOException
e
)
{
throw
new
SystemException
(
e
)
;
}
finally
{
closeResponse
(
response
)
;
}
}

Refresh the lock on this resource with the given lock token. Use
the specified timeout value.

@param lockToken the lock token to refresh
@param timeout the new timeout value to use
@exception DAVException if there was a problem refreshing the lock

Refresh the lock on this resource with the given lock token . Use the specified timeout value .


public void removeProperties(Collection propertyNames) throws DAVException {
        Assert.isNotNull(propertyNames);

        // Removing no properties is easy.
        if (propertyNames.isEmpty())
            return;

        // Add the names of the properties to remove to the request body.
        Document document = newDocument();
        PropertyUpdate propertyUpdate = PropertyUpdate.create(document);
        Prop prop = propertyUpdate.addRemove();
        Iterator namesItr = propertyNames.iterator();
        while (namesItr.hasNext())
            prop.addPropertyName((QualifiedName) namesItr.next());

        // Send the PROPPATCH request.
        IResponse response = null;
        try {
            response = davClient.proppatch(locator, newContext(), document);
            examineResponse(response);
            examineMultiStatusResponse(response);
        } catch (IOException e) {
            throw new SystemException(e);
        } finally {
            closeResponse(response);
        }
    }

Remove the properties with the given names, from this resource.

@param propertyNames Enumeration over
QualifiedNames
@exception DAVException if there was a problem removing the
properties
@see IServer#proppatch(Locator, Context, Document)

Remove the properties with the given names from this resource .


public void removeProperty(QualifiedName propertyName) throws DAVException {
        Collection propertyNames = new Vector(1);
        propertyNames.add(propertyName);
        removeProperties(propertyNames);
    }

public void removeProperty ( QualifiedName propertyName ) throws DAVException { Collection propertyNames = new Vector ( 1 ) ; propertyNames . add ( propertyName ) ; removeProperties ( propertyNames ) ; }

Remove the property with the given name from this resource.

@param propertyName the name of the property to remove
@exception DAVException if there was a problem removing the property
@see #removeProperties(Collection)

Remove the property with the given name from this resource .


public void setContent(String contentType, InputStream input) throws DAVException {
        IResponse response = null;
        try {
            IContext context = newContext();
            context.setContentType(contentType);
            response = davClient.put(locator, context, input);
            examineResponse(response);
        } catch (IOException e) {
            throw new SystemException(e);
        } finally {
            closeResponse(response);
        }
    }

public void setContent ( String contentType , InputStream input ) throws DAVException { IResponse response = null ; try { IContext context = newContext ( ) ; context . setContentType ( contentType ) ; response = davClient . put ( locator , context , input ) ; examineResponse ( response ) ; } catch ( IOException e ) { throw new SystemException ( e ) ; } finally { closeResponse ( response ) ; } }

Set the content of this resource to be the data stored in the given
input stream. The type encoding is given in the content type argument, and
should be in the media format described by RFC2616 Sec 3.7.
The stream will automatically be closed after the data
is consumed.  If the resource does not exist it is created with the
given content.

@param contentType the media type for the data on the input stream.
@param input the inputstream containing the resource contents.
@exception DAVException if there was a problem setting the contents.
@see IServer#put(Locator, Context, InputStream)

Set the content of this resource to be the data stored in the given input stream . The type encoding is given in the content type argument and should be in the media format described by RFC2616 Sec 3 . 7 . The stream will automatically be closed after the data is consumed . If the resource does not exist it is created with the given content .


public void setProperties(Collection properties) throws DAVException {
        Assert.isNotNull(properties);

        // Setting no properties is a no-op.
        if (properties.isEmpty())
            return;

        // Build the request body to describe the properties to set.
        Document document = newDocument();
        PropertyUpdate propertyUpdate = PropertyUpdate.create(document);
        Prop prop = propertyUpdate.addSet();

        Iterator propertiesItr = properties.iterator();
        while (propertiesItr.hasNext()) {
            Element element = (Element) propertiesItr.next();
            try {
                prop.addProperty(element);
            } catch (MalformedElementException exception) {
                throw new SystemException(exception);
            }
        } // end-while

        // Send the request to the server and examine the response for failures.
        IResponse response = null;
        try {
            response = davClient.proppatch(locator, newContext(), document);
            examineResponse(response);
            examineMultiStatusResponse(response);
        } catch (IOException e) {
            throw new SystemException(e);
        } finally {
            closeResponse(response);
        }
    }

Set the given properties on this resource.

@param properties a Collection of property Elements.
@exception DAVException if there was a problem setting the properties.
@see IServer#proppatch(Locator, Context, Document)

Set the given properties on this resource .


public void setProperty(Element property) throws DAVException {
        Collection properties = new Vector(1);
        properties.add(property);
        setProperties(properties);
    }

public void setProperty ( Element property ) throws DAVException { Collection properties = new Vector ( 1 ) ; properties . add ( property ) ; setProperties ( properties ) ; }

Set the given property on this resource.

@param property the property to set
@exception DAVException if there was a problem setting the property
@see #setProperties(Collection)

Set the given property on this resource .


public void unlock(LockToken token) throws DAVException {
        // Send the lock token in the header of the request.
        IContext context = newContext();
        context.setLockToken("<" + token.getToken() + ">"); //$NON-NLS-1$ //$NON-NLS-2$

        IResponse response = null;
        try {
            response = davClient.unlock(locator, context);
            examineResponse(response);
        } catch (IOException e) {
            throw new SystemException(e);
        } finally {
            closeResponse(response);
        }
    }

Unlock this resource with the given lock token.

@param token the lock token to remove from this resource
@exception DAVException if there was a problem unlocking this resource
@see IServer#unlock(Locator, Context)

Unlock this resource with the given lock token .


public void update(ILocator version) throws DAVException {
        Document document = newDocument();
        Update.createVersion(document, version.getResourceURL());

        IResponse response = null;
        try {
            response = davClient.update(locator, newContext(), document);
            examineResponse(response);
        } catch (IOException e) {
            throw new SystemException(e);
        } finally {
            closeResponse(response);
        }
    }

public void update ( ILocator version ) throws DAVException { Document document = newDocument ( ) ; Update . createVersion ( document , version . getResourceURL ( ) ) ; IResponse response = null ; try { response = davClient . update ( locator , newContext ( ) , document ) ; examineResponse ( response ) ; } catch ( IOException e ) { throw new SystemException ( e ) ; } finally { closeResponse ( response ) ; } }

Perform an UPDATE on the receiver to set the version it
is based upon.

@param version the Locator of the version that
is the target of the update request.
@throws DAVException if a problem occurs executing the update
on the WebDAV server.

Perform an UPDATE on the receiver to set the version it is based upon .


public void versionControl() throws DAVException {
        IResponse response = null;
        try {
            response = davClient.versionControl(locator, newContext(), null);
            examineResponse(response);
        } catch (IOException e) {
            throw new SystemException(e);
        } finally {
            closeResponse(response);
        }
    }

public void versionControl ( ) throws DAVException { IResponse response = null ; try { response = davClient . versionControl ( locator , newContext ( ) , null ) ; examineResponse ( response ) ; } catch ( IOException e ) { throw new SystemException ( e ) ; } finally { closeResponse ( response ) ; } }

Bring the receiver under version control.  This means that
the receiver is replaced by a version-controlled resource.
Note that the client may send version control to a resource
that is already under version control with no adverse effects.

@throws DAVException if a problem occurs bringing the
resource under version control.

Bring the receiver under version control . This means that the receiver is replaced by a version - controlled resource . Note that the client may send version control to a resource that is already under version control with no adverse effects .


public void delete(boolean mustExist) throws DAVException {
        IResponse response = null;
        try {
            response = davClient.delete(locator, newContext());
            if (!mustExist && (response.getStatusCode() == IResponse.SC_NOT_FOUND))
                return;
            examineResponse(response);
            examineMultiStatusResponse(response);
        } catch (IOException exception) {
            throw new SystemException(exception);
        } finally {
            closeResponse(response);
        }
    }

public void delete ( boolean mustExist ) throws DAVException { IResponse response = null ; try { response = davClient . delete ( locator , newContext ( ) ) ; if ( ! mustExist && ( response . getStatusCode ( ) == IResponse . SC_NOT_FOUND ) ) return ; examineResponse ( response ) ; examineMultiStatusResponse ( response ) ; } catch ( IOException exception ) { throw new SystemException ( exception ) ; } finally { closeResponse ( response ) ; } }

Delete this resource from the repository, optionally succeeding
in the delete if the resource was not found on the server.

@param mustExist if true then the delete will
fail if the resource was not on the server at the time of the
delete request.  If false the delete will succeed if
there was no such resource to delete.
@exception DAVException if there was a problem deleting
this resource.
@see IServer#delete(Locator, Context)

Delete this resource from the repository optionally succeeding in the delete if the resource was not found on the server .


protected void examineStatusCode(int code, String message) throws WebDAVException {
        if (code >= 300 && code <= 399)
            throw new RedirectionException(code, message);
        if (code >= 400 && code <= 499)
            throw new ClientException(code, message);
        if (code >= 500 && code <= 599)
            throw new ServerException(code, message);
    }

protected void examineStatusCode ( int code , String message ) throws WebDAVException { if ( code >= 300 && code <= 399 ) throw new RedirectionException ( code , message ) ; if ( code >= 400 && code <= 499 ) throw new ClientException ( code , message ) ; if ( code >= 500 && code <= 599 ) throw new ServerException ( code , message ) ; }

Check the given status code and throw a WebDAV
exception if the code indicates failure.  If the code
is success, this method does nothing.

@param code the status code to check.
@param message the status message accompanying the code.
@exception WebDAVException if the server returned an HTTP/WebDAV
error code (i.e., anything outside the 200-series codes).

Check the given status code and throw a WebDAV exception if the code indicates failure . If the code is success this method does nothing .


protected boolean propertyHasChild(QualifiedName propertyName, QualifiedName childName) throws DAVException {
        // If the property is not found, then the answer is 'no'.
        PropertyStatus propertyStat = getProperty(propertyName);
        if (propertyStat.getStatusCode() == IResponse.SC_NOT_FOUND)
            return false;
        // If there was a problem getting the property, throw an exception.
        examineStatusCode(propertyStat.getStatusCode(), propertyStat.getStatusMessage());
        // Check to see if the named child is in the retrieved property.
        try {
            return ElementEditor.hasChild(propertyStat.getProperty(), childName);
        } catch (MalformedElementException exception) {
            throw new SystemException(exception);
        }
    }

This is a helper method to check to see if the resource has a
property with the given name that in turn has a child with a
given name.

@return true if the resource does have such a
property with a named child and false if it does
not have such a property or does not have such a child of the
property.
@throws DAVException if a problem occurs determining result
from the server.

This is a helper method to check to see if the resource has a property with the given name that in turn has a child with a given name .


public void write(OutputStream os) throws IOException {
        if (requestBodyWriter == null) {
            if (inputRead) {
                is.reset();
                inputRead = false;
            }
            super.write(os);
        } else {
            requestBodyWriter.writeRequestBody(os);
        }
    }

public void write ( OutputStream os ) throws IOException { if ( requestBodyWriter == null ) { if ( inputRead ) { is . reset ( ) ; inputRead = false ; } super . write ( os ) ; } else { requestBodyWriter . writeRequestBody ( os ) ; } }

Writes this request's body to the given output stream. This method may
be called more than once during the lifetime of this request.

@param os an output stream
@exception IOException if there is an I/O error

Writes this request s body to the given output stream . This method may be called more than once during the lifetime of this request .


public static String toHex(byte[] arr) {
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < arr.length; ++i) {
            buf.append(Integer.toHexString((arr[i] >> 4) & 0x0f));
            buf.append(Integer.toHexString(arr[i] & 0x0f));
        }
        return buf.toString();
    }

public static String toHex ( byte [ ] arr ) { StringBuffer buf = new StringBuffer ( ) ; for ( int i = 0 ; i < arr . length ; ++ i ) { buf . append ( Integer . toHexString ( ( arr [ i ] >> 4 ) & 0x0f ) ) ; buf . append ( Integer . toHexString ( arr [ i ] & 0x0f ) ) ; } return buf . toString ( ) ; }

Converts the given byte array to its equivalent hexadecimal string
and returns the result.

Converts the given byte array to its equivalent hexadecimal string and returns the result .


public static String toHex(int[] arr) {
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < arr.length; ++i) {
            buf.append(Integer.toHexString((arr[i] >> 28) & 0x0000000f));
            buf.append(Integer.toHexString((arr[i] >> 24) & 0x0000000f));
            buf.append(Integer.toHexString((arr[i] >> 20) & 0x0000000f));
            buf.append(Integer.toHexString((arr[i] >> 16) & 0x0000000f));
            buf.append(Integer.toHexString((arr[i] >> 12) & 0x0000000f));
            buf.append(Integer.toHexString((arr[i] >> 8) & 0x0000000f));
            buf.append(Integer.toHexString((arr[i] >> 4) & 0x0000000f));
            buf.append(Integer.toHexString((arr[i]) & 0x0000000f));
        }
        return buf.toString();
    }

public static String toHex ( int [ ] arr ) { StringBuffer buf = new StringBuffer ( ) ; for ( int i = 0 ; i < arr . length ; ++ i ) { buf . append ( Integer . toHexString ( ( arr [ i ] >> 28 ) & 0x0000000f ) ) ; buf . append ( Integer . toHexString ( ( arr [ i ] >> 24 ) & 0x0000000f ) ) ; buf . append ( Integer . toHexString ( ( arr [ i ] >> 20 ) & 0x0000000f ) ) ; buf . append ( Integer . toHexString ( ( arr [ i ] >> 16 ) & 0x0000000f ) ) ; buf . append ( Integer . toHexString ( ( arr [ i ] >> 12 ) & 0x0000000f ) ) ; buf . append ( Integer . toHexString ( ( arr [ i ] >> 8 ) & 0x0000000f ) ) ; buf . append ( Integer . toHexString ( ( arr [ i ] >> 4 ) & 0x0000000f ) ) ; buf . append ( Integer . toHexString ( ( arr [ i ] ) & 0x0000000f ) ) ; } return buf . toString ( ) ; }

Converts the given int array to its equivalent hexadecimal string
and returns the result.

Converts the given int array to its equivalent hexadecimal string and returns the result .


public void setIsAllProp(boolean isAllProp) {
        Element child = getFirstChild(root, childNames);
        boolean isAlreadyAllProp = isDAVElement(child, "allprop"); //$NON-NLS-1$
        if (isAllProp) {
            if (!isAlreadyAllProp) {
                if (child != null)
                    root.removeChild(child);
                appendChild(root, "allprop"); //$NON-NLS-1$
            }
        } else if (isAlreadyAllProp)
            root.removeChild(child);
    }

public void setIsAllProp ( boolean isAllProp ) { Element child = getFirstChild ( root , childNames ) ; boolean isAlreadyAllProp = isDAVElement ( child , "allprop" ) ; //$NON-NLS-1$ if ( isAllProp ) { if ( ! isAlreadyAllProp ) { if ( child != null ) root . removeChild ( child ) ; appendChild ( root , "allprop" ) ; //$NON-NLS-1$ } } else if ( isAlreadyAllProp ) root . removeChild ( child ) ; }

Sets whether this propfind is in the "all prop" form.

@param isAllProp boolean indicating whether this propfind will be in the
"all prop" form

Sets whether this propfind is in the all prop form .


public void setIsPropName(boolean isPropName) {
        Element child = getFirstChild(root, childNames);
        boolean isAlreadyPropName = isDAVElement(child, "propname"); //$NON-NLS-1$
        if (isPropName) {
            if (!isAlreadyPropName) {
                if (child != null)
                    root.removeChild(child);
                appendChild(root, "propname"); //$NON-NLS-1$
            }
        } else if (isAlreadyPropName)
            root.removeChild(child);
    }

public void setIsPropName ( boolean isPropName ) { Element child = getFirstChild ( root , childNames ) ; boolean isAlreadyPropName = isDAVElement ( child , "propname" ) ; //$NON-NLS-1$ if ( isPropName ) { if ( ! isAlreadyPropName ) { if ( child != null ) root . removeChild ( child ) ; appendChild ( root , "propname" ) ; //$NON-NLS-1$ } } else if ( isAlreadyPropName ) root . removeChild ( child ) ; }

Sets whether this propfind is in the "prop name" form.

@param isPropName boolean indicating whether this propfind will be in the
"prop name" form

Sets whether this propfind is in the prop name form .


public Prop setProp() {
        Assert.isTrue(getFirstChild(root, new String[] {"allprop", "propname"}) == null); //$NON-NLS-1$ //$NON-NLS-2$
        Element prop = setChild(root, "prop", new String[] {"prop"}, true); //$NON-NLS-1$ //$NON-NLS-2$
        try {
            return new Prop(prop);
        } catch (MalformedElementException e) {
            Assert.isTrue(false, Policy.bind("assert.internalError")); //$NON-NLS-1$
            return null; // Never reached.
        }
    }

public
Prop
setProp
(
)
{
Assert
.
isTrue
(
getFirstChild
(
root
,
new
String
[
]
{
"allprop"
,
"propname"
}
)
==
)
;
//$NON-NLS-1$ //$NON-NLS-2$
Element
prop
=
setChild
(
root
,
"prop"
,
new
String
[
]
{
"prop"
}
,
true
)
;
//$NON-NLS-1$ //$NON-NLS-2$
try
{
return
new
Prop
(
prop
)
;
}
catch
(
MalformedElementException
e
)
{
Assert
.
isTrue
(
false
,
Policy
.
bind
(
"assert.internalError"
)
)
;
//$NON-NLS-1$
return
;
// Never reached.
}
}

Creates and sets a new prop on this propfind and returns an editor on
it. This propfind must not already be in the "all prop" or "prop
name" form.

@return an editor on a new prop element

Creates and sets a new prop on this propfind and returns an editor on it . This propfind must not already be in the all prop or prop name form .


public static String stripLastWord(String prefix) {
        if ( "".equals( prefix ) ) {
            return prefix;
        }
        if ( prefix.charAt( prefix.length() - 1 ) == ' ' ) {
            return "";
        } else {
            char[] c = prefix.toCharArray();
            int start = 0;
            for ( int i = c.length - 1; i >= 0; i-- ) {
                if ( Character.isWhitespace( c[i] ) || c[i] == '(' || c[i] == ':' || c[i] == ';' || c[i] == '=' || c[i] == '<' || c[i] == '>' || c[i] == '.' || c[i] == '{' || c[i] == '}' ) {
                    start = i + 1;
                    break;
                }
            }
            prefix = prefix.substring( start,
                                       prefix.length() );
            return prefix;
        }
    }

public static String stripLastWord ( String prefix ) { if ( "" . equals ( prefix ) ) { return prefix ; } if ( prefix . charAt ( prefix . length ( ) - 1 ) == ' ' ) { return "" ; } else { char [ ] c = prefix . toCharArray ( ) ; int start = 0 ; for ( int i = c . length - 1 ; i >= 0 ; i -- ) { if ( Character . isWhitespace ( c [ i ] ) || c [ i ] == ' ' || c [ i ] == ' ' || c [ i ] == ' ' || c [ i ] == ' ' || c [ i ] == ' ' || c [ i ] == ' ' || c [ i ] == ' ' || c [ i ] == ' ' || c [ i ] == ' ' ) { start = i + 1 ; break ; } } prefix = prefix . substring ( start , prefix . length ( ) ) ; return prefix ; } }

Looks behind, gets stuff after the white space. Basically ripping out the
last word.

Looks behind gets stuff after the white space . Basically ripping out the last word .


public void update() {
        TreeViewer viewer = getTreeViewer();
        if (viewer != null) {
            Control control = viewer.getControl();
            if (control != null && !control.isDisposed()) {
                initRules();
                populatePackageTreeNode();
                viewer.refresh();
                control.setRedraw(false);
                viewer.expandToLevel(2);
                control.setRedraw(true);
            }
        }
    }

public void update ( ) { TreeViewer viewer = getTreeViewer ( ) ; if ( viewer != null ) { Control control = viewer . getControl ( ) ; if ( control != null && ! control . isDisposed ( ) ) { initRules ( ) ; populatePackageTreeNode ( ) ; viewer . refresh ( ) ; control . setRedraw ( false ) ; viewer . expandToLevel ( 2 ) ; control . setRedraw ( true ) ; } } }


public void write(OutputStream os) throws IOException {
        Assert.isTrue(!inputRead);
        Assert.isTrue(!hasInputStream);

        int bytesRead = 0;
        int totalBytesRead = 0;
        byte[] buffer = bufferPool.getBuffer();
        long contentLength = getContentLength();

        try {
            while (bytesRead != -1 && (contentLength == -1 || contentLength > totalBytesRead)) {
                if (contentLength == -1) {
                    bytesRead = is.read(buffer);
                } else {
                    bytesRead = is.read(buffer, 0, (int) Math.min(buffer.length, contentLength - totalBytesRead));
                }
                if (bytesRead == -1) {
                    if (contentLength >= 0) {
                        throw new IOException(Policy.bind("exception.unexpectedEndStream")); //$NON-NLS-1$
                    }
                } else {
                    totalBytesRead += bytesRead;
                    os.write(buffer, 0, bytesRead);
                }
            }
        } finally {
            bufferPool.putBuffer(buffer);
            inputRead = true;
        }
    }

public void write ( OutputStream os ) throws IOException { Assert . isTrue ( ! inputRead ) ; Assert . isTrue ( ! hasInputStream ) ; int bytesRead = 0 ; int totalBytesRead = 0 ; byte [ ] buffer = bufferPool . getBuffer ( ) ; long contentLength = getContentLength ( ) ; try { while ( bytesRead != - 1 && ( contentLength == - 1 || contentLength > totalBytesRead ) ) { if ( contentLength == - 1 ) { bytesRead = is . read ( buffer ) ; } else { bytesRead = is . read ( buffer , 0 , ( int ) Math . min ( buffer . length , contentLength - totalBytesRead ) ) ; } if ( bytesRead == - 1 ) { if ( contentLength >= 0 ) { throw new IOException ( Policy . bind ( "exception.unexpectedEndStream" ) ) ; //$NON-NLS-1$ } } else { totalBytesRead += bytesRead ; os . write ( buffer , 0 , bytesRead ) ; } } } finally { bufferPool . putBuffer ( buffer ) ; inputRead = true ; } }

Writes this messages body to the given output stream. This method may
only be called once during the lifetime of this message.

@param os an output stream
@exception IOException if there is an I/O error

Writes this messages body to the given output stream . This method may only be called once during the lifetime of this message .


public synchronized void stepOver() throws DebugException {

        // Detection for active stackframe
        if ( !(getTopStackFrame() instanceof MVELStackFrame) ) {
            super.stepOver();
            return;
        }

        //MVEL step over
        MVELStackFrame mvelStack = (MVELStackFrame) getTopStackFrame();

        if ( !canStepOver() || !mvelStack.canStepOver() ) {
            return;
        }

        if ( !setRemoteOnBreakReturn( Debugger.STEP ) ) {
            return;
        }

        setRunning( true );

        preserveStackFrames();

        fireEvent( new DebugEvent( this,
                                   DebugEvent.RESUME,
                                   DebugEvent.STEP_OVER ) );

        try {
            getUnderlyingThread().resume();
        } catch ( RuntimeException e ) {
            //stepEnd();
            targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.JDIThread_exception_stepping, e.toString()), e);
        }

    }

public
synchronized
void
stepOver
(
)
throws
DebugException
{
// Detection for active stackframe
if
(
!
(
getTopStackFrame
(
)
instanceof
MVELStackFrame
)
)
{
super
.
stepOver
(
)
;
return
;
}
//MVEL step over
MVELStackFrame
mvelStack
=
(
MVELStackFrame
)
getTopStackFrame
(
)
;
if
(
!
canStepOver
(
)
||
!
mvelStack
.
canStepOver
(
)
)
{
return
;
}
if
(
!
setRemoteOnBreakReturn
(
Debugger
.
STEP
)
)
{
return
;
}
setRunning
(
true
)
;
preserveStackFrames
(
)
;
fireEvent
(
new
DebugEvent
(
this
,
DebugEvent
.
RESUME
,
DebugEvent
.
STEP_OVER
)
)
;
try
{
getUnderlyingThread
(
)
.
resume
(
)
;
}
catch
(
RuntimeException
e
)
{
//stepEnd();
targetRequestFailed
(
MessageFormat
.
format
(
JDIDebugModelMessages
.
JDIThread_exception_stepping
,
e
.
toString
(
)
)
,
e
)
;
}
}

I don't see the need for any of this custom stepOver stuff, why is it here?

I don t see the need for any of this custom stepOver stuff why is it here?


protected void markParseErrors(List<DroolsBuildMarker> markers,
                                   List<BaseKnowledgeBuilderResultImpl> parserErrors) {
        for ( Iterator<BaseKnowledgeBuilderResultImpl> iter = parserErrors.iterator(); iter.hasNext(); ) {
            Object error = iter.next();
            if ( error instanceof ParserError ) {
                ParserError err = (ParserError) error;
                markers.add( new DroolsBuildMarker( err.getMessage(),
                                                    err.getRow() ) );
            } else if ( error instanceof KnowledgeBuilderResult) {
                KnowledgeBuilderResult res = (KnowledgeBuilderResult) error;
                int[] errorLines = res.getLines();
                markers.add( new DroolsBuildMarker( res.getMessage(),
                                                    errorLines != null && errorLines.length > 0 ? errorLines[0] : -1 ) );
            } else if ( error instanceof ExpanderException ) {
                ExpanderException exc = (ExpanderException) error;
                // TODO line mapping is incorrect
                markers.add( new DroolsBuildMarker( exc.getMessage(),
                                                    -1 ) );
            } else {
                markers.add( new DroolsBuildMarker( error.toString() ) );
            }
        }
    }

protected
void
markParseErrors
(
List
<
DroolsBuildMarker
>
markers
,
List
<
BaseKnowledgeBuilderResultImpl
>
parserErrors
)
{
for
(
Iterator
<
BaseKnowledgeBuilderResultImpl
>
iter
=
parserErrors
.
iterator
(
)
;
iter
.
hasNext
(
)
;
)
{
Object
error
=
iter
.
next
(
)
;
if
(
error
instanceof
ParserError
)
{
ParserError
err
=
(
ParserError
)
error
;
markers
.
add
(
new
DroolsBuildMarker
(
err
.
getMessage
(
)
,
err
.
getRow
(
)
)
)
;
}
else
if
(
error
instanceof
KnowledgeBuilderResult
)
{
KnowledgeBuilderResult
res
=
(
KnowledgeBuilderResult
)
error
;
int
[
]
errorLines
=
res
.
getLines
(
)
;
markers
.
add
(
new
DroolsBuildMarker
(
res
.
getMessage
(
)
,
errorLines
!=
&&
errorLines
.
length
>
0
errorLines
[
0
]
:
1
)
)
;
}
else
if
(
error
instanceof
ExpanderException
)
{
ExpanderException
exc
=
(
ExpanderException
)
error
;
// TODO line mapping is incorrect
markers
.
add
(
new
DroolsBuildMarker
(
exc
.
getMessage
(
)
,
1
)
)
;
}
else
{
markers
.
add
(
new
DroolsBuildMarker
(
error
.
toString
(
)
)
)
;
}
}
}

This will create markers for parse errors. Parse errors mean that antlr
has picked up some major typos in the input source.

This will create markers for parse errors . Parse errors mean that antlr has picked up some major typos in the input source .


public void skipWhiteSpace() {
        while (pos < s.length() && Character.isWhitespace(s.charAt(pos)))
            ++pos;
    }

public void skipWhiteSpace ( ) { while ( pos < s . length ( ) && Character . isWhitespace ( s . charAt ( pos ) ) ) ++ pos ; }

Skips the next sequence of white space in s. An exception is not
thrown if there is no matching white space.

Skips the next sequence of white space in s . An exception is not thrown if there is no matching white space .


public static boolean addResourceToGuvnor(String repLoc,
                                             String targetLoc,
                                             IFile selectedFile) {
        boolean res = false;
        try {
            String fullPath = targetLoc + selectedFile.getName();
            IWebDavClient client = WebDavServerCache.getWebDavClient(repLoc);
            if (client == null) {
                client = WebDavClientFactory.createClient(new URL(repLoc));
                WebDavServerCache.cacheWebDavClient(repLoc, client);
            }
            try {
//                res = client.createResource(fullPath, selectedFile.getContents(), false);
                // Hack: When creating a file, if the actual contents are passed first,
                // the client hangs for about 20 seconds when closing the InputStream.
                // Don't know why...
                // But, if the file is created with empty contents, and then the contents
                // set, the operation is fast (less than a couple of seconds)
                res = client.createResource(fullPath, new ByteArrayInputStream(new byte[0]), false);
                if (res) {
                    client.putResource(fullPath, selectedFile.getContents());
                }
            } catch (WebDavException wde) {
                if (wde.getErrorCode() != IResponse.SC_UNAUTHORIZED) {
                    // If not an authentication failure, we don't know what to do with it
                    throw wde;
                }
                boolean retry = PlatformUtils.getInstance().
                                    authenticateForServer(repLoc, client);
                if (retry) {
//                    res = client.createResource(fullPath, selectedFile.getContents(), false);
                    // See Hack note immediately above...
                    res = client.createResource(fullPath, new ByteArrayInputStream(new byte[0]), false);
                    if (res) {
                        client.putResource(fullPath, selectedFile.getContents());
                    }
                }
            }
            if (res) {
                GuvnorMetadataUtils.markCurrentGuvnorResource(selectedFile);
                ResourceProperties resProps = client.queryProperties(fullPath);
                GuvnorMetadataProps mdProps =
                        new GuvnorMetadataProps(selectedFile.getName(),
                                               repLoc,
                                               fullPath, resProps.getLastModifiedDate(),
                                               resProps.getRevision());
                GuvnorMetadataUtils.setGuvnorMetadataProps(selectedFile.getFullPath(), mdProps);
            }
        } catch (Exception e) {
            Activator.getDefault().displayError(IStatus.ERROR, e.getMessage(), e, true);
        }
        return res;
    }

Adds a resource to Guvnor.
@param repLoc The location of the Guvnor repository
@param targetLoc The location in Guvnor to add the resource
@param selectedFile The resource to add
@return true if the resource is added, false if there is already a resource
with the same name in the given location.


public static void commitFileChanges(IFile selectedFile) {
        try {
            GuvnorMetadataProps props = GuvnorMetadataUtils.getGuvnorMetadata(selectedFile);
            IWebDavClient client = WebDavServerCache.getWebDavClient(props.getRepository());
            if (client == null) {
                client = WebDavClientFactory.createClient(new URL(props.getRepository()));
                WebDavServerCache.cacheWebDavClient(props.getRepository(), client);
            }
            ResourceProperties remoteProps = null;
            try {
                remoteProps = client.queryProperties(props.getFullpath());
            } catch (WebDavException wde) {
                if (wde.getErrorCode() != IResponse.SC_UNAUTHORIZED) {
                    // If not an authentication failure, we don't know what to do with it
                    throw wde;
                }
                boolean retry = PlatformUtils.getInstance().
                                    authenticateForServer(props.getRepository(), client);
                if (retry) {
                    remoteProps = client.queryProperties(props.getFullpath());
                }
            }
            if (remoteProps == null) {
                throw new Exception("Could not retrieve server version of " + props.getFullpath()); //$NON-NLS-1$
            }
            // Check to make sure that the version in the repository is the same as the base
            // version for the local copy
            boolean proceed = true;
            if (!props.getRevision().equals(remoteProps.getRevision())) {
                String msg = MessageFormat.format(Messages.getString("overwrite.confirmation"), //$NON-NLS-1$
                                                 new Object[] { selectedFile.getName(),
                                                                remoteProps.getRevision(),
                                                                props.getRevision() });
                Display display = PlatformUI.getWorkbench().getDisplay();
                proceed = MessageDialog.openQuestion(display.getActiveShell(),
                                                    Messages.getString("overwrite.confirmation.caption"), msg); //$NON-NLS-1$

            }
            if (proceed) {
                client.putResource(props.getFullpath(), selectedFile.getContents());
                GuvnorMetadataUtils.markCurrentGuvnorResource(selectedFile);
                ResourceProperties resProps = client.queryProperties(props.getFullpath());
                GuvnorMetadataProps mdProps = GuvnorMetadataUtils.getGuvnorMetadata(selectedFile);
                mdProps.setVersion(resProps.getLastModifiedDate());
                mdProps.setRevision(resProps.getRevision());
                GuvnorMetadataUtils.setGuvnorMetadataProps(selectedFile.getFullPath(), mdProps);
            }
        } catch (Exception e) {
            Activator.getDefault().displayError(IStatus.ERROR, e.getMessage(), e, true);
        }
    }

Commits changes to Guvnor.
@param selectedFile The Guvnor controlled file with pending changes


public int getAge() {
        String ageString = get(AGE);
        return (ageString == null) ? -1 : Integer.parseInt(ageString);
    }

public int getAge ( ) { String ageString = get ( AGE ) ; return ( ageString == null ) ? - 1 : Integer . parseInt ( ageString ) ; }

Get the sender's estimate of the time since the response was generated.
Return the int value for the AGE key. Return -1 if the value is not set.

Implements the corresponding API in the interface
Context.

@return the value for AGE
@see Context#getAge()

Get the sender s estimate of the time since the response was generated . Return the int value for the AGE key . Return - 1 if the value is not set .


public long getContentLength() {
        String lengthString = get(CONTENT_LENGTH);
        return (lengthString == null) ? -1 : Long.parseLong(lengthString);
    }

public long getContentLength ( ) { String lengthString = get ( CONTENT_LENGTH ) ; return ( lengthString == null ) ? - 1 : Long . parseLong ( lengthString ) ; }

Get the content length in bytes of the entity body.
Return the value for the CONTENT_LENGTH key.
Returns -1 if the Content-Length has not been set.

Implements the corresponding API in the interface
Context.

@return the value for CONTENT_LENGTH
@see Context#getContentLength()

Get the content length in bytes of the entity body . Return the value for the CONTENT_LENGTH key . Returns - 1 if the Content - Length has not been set .


public int getMaxForwards() {
        String s = get(MAX_FORWARDS);
        return s == null ? -1 : Integer.parseInt(s);
    }

public int getMaxForwards ( ) { String s = get ( MAX_FORWARDS ) ; return s == null ? - 1 : Integer . parseInt ( s ) ; }

Return the integer value for the MAX_FORWARDS key.

Implements the corresponding API in the interface
Context.

@return the value for MAX_FORWARDS
@see Context#getMaxForwards()

Return the integer value for the MAX_FORWARDS key .


public boolean getOverwrite() {
        String overwriteString = get(OVERWRITE);
        return overwriteString == null ? false : overwriteString.equalsIgnoreCase("T"); //$NON-NLS-1$
    }

public boolean getOverwrite ( ) { String overwriteString = get ( OVERWRITE ) ; return overwriteString == null ? false : overwriteString . equalsIgnoreCase ( "T" ) ; //$NON-NLS-1$ }

Get the flag that indicates if copy or move should overwrite
an existing destination. Return the boolean value for the
OVERWRITE key.

Implements the corresponding API in the interface
Context.

@return the value for OVERWRITE
@see Context#OVERWRITE

Get the flag that indicates if copy or move should overwrite an existing destination . Return the boolean value for the OVERWRITE key .


public boolean getPassthrough() {
        String s = get(PASSTHROUGH);
        return s == null ? false : s.equalsIgnoreCase("T"); //$NON-NLS-1$
    }

public boolean getPassthrough ( ) { String s = get ( PASSTHROUGH ) ; return s == null ? false : s . equalsIgnoreCase ( "T" ) ; //$NON-NLS-1$ }

Return the boolean value for the PASSTHROUGH key.

Implements the corresponding API in the interface
Context.

@return the value for PASSTHROUGH
@see Context#getPassthrough()

Return the boolean value for the PASSTHROUGH key .


public int getTimeout() {
        String timeoutString = get(TIMEOUT);
        if (timeoutString == null)
            return -1;
        if (timeoutString.equalsIgnoreCase(DEPTH_INFINITY))
            return -2;
        if (timeoutString.regionMatches(true, 1, "Second-", 1, 7)) //$NON-NLS-1$
            return Integer.parseInt(timeoutString.substring(7));
        // ignore all other cases, and use infinite timeout
        return -2;
    }

Get the lock timeout value. The value -1 means that the
value was not set, the value -2 means that the value was "Infinity".
Return the integer value for the TIMEOUT key.

Implements the corresponding API in the interface
Context.

@return the value for TIMEOUT
@see Context#getTimeout()

Get the lock timeout value . The value - 1 means that the value was not set the value - 2 means that the value was Infinity . Return the integer value for the TIMEOUT key .


public void put(String key, String value) {
        ContextKey ckey = new ContextKey(key);
        if ((value == null) || (value.length() == 0))
            properties.remove(ckey);
        else
            properties.put(ckey, value);
    }

public void put ( String key , String value ) { ContextKey ckey = new ContextKey ( key ) ; if ( ( value == null ) || ( value . length ( ) == 0 ) ) properties . remove ( ckey ) ; else properties . put ( ckey , value ) ; }

Put the given key-value pair into the context.

@param key the key
@param value its associated value

Put the given key - value pair into the context .


public void setTimeout(int value) {
        if (value == -1)
            put(TIMEOUT, ""); //$NON-NLS-1$
        else
            put(TIMEOUT, (value == -2) ? DEPTH_INFINITY : "Second-" + Integer.toString(value)); //$NON-NLS-1$
    }

public void setTimeout ( int value ) { if ( value == - 1 ) put ( TIMEOUT , "" ) ; //$NON-NLS-1$ else put ( TIMEOUT , ( value == - 2 ) ? DEPTH_INFINITY : "Second-" + Integer . toString ( value ) ) ; //$NON-NLS-1$ }

Set the lock timeout value in seconds. Pass -1 to clear the
value, pass -2 to set "Infinity". Set the integer value for the
TIMEOUT key.

Implements the corresponding API in the interface
Context.

@param value the value for TIMEOUT
@see Context#setTimeout(int)

Set the lock timeout value in seconds . Pass - 1 to clear the value pass - 2 to set Infinity . Set the integer value for the TIMEOUT key .


protected BufferedReader openDSLFile(String filename) {
        try {
            FileReader reader = new FileReader(filename);
            BufferedReader breader = new BufferedReader(reader);
            return breader;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

protected BufferedReader openDSLFile ( String filename ) { try { FileReader reader = new FileReader ( filename ) ; BufferedReader breader = new BufferedReader ( reader ) ; return breader ; } catch ( IOException e ) { e . printStackTrace ( ) ; return null ; } }

method will create a BufferedReader to read the file.
@param filename
@return

method will create a BufferedReader to read the file .


protected void parseFile(BufferedReader reader) {
        String line = null;
        try {
            while ( (line = reader.readLine()) != null) {
                Section section = getSection(line);
                String nl = stripHeadingAndCode(line);
                String objname = this.getObjMetadata(nl);
                nl = this.stripObjMetadata(nl);
                addEntry(section, nl, objname);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

protected void parseFile ( BufferedReader reader ) { String line = null ; try { while ( ( line = reader . readLine ( ) ) != null ) { Section section = getSection ( line ) ; String nl = stripHeadingAndCode ( line ) ; String objname = this . getObjMetadata ( nl ) ; nl = this . stripObjMetadata ( nl ) ; addEntry ( section , nl , objname ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } }

method will use the BufferedReader to read the contents of the file.
It calls other methods to parse the line and build the tree.
@param reader

method will use the BufferedReader to read the contents of the file . It calls other methods to parse the line and build the tree .


protected String getObjMetadata(String text) {
        if (text.startsWith("[")) {
            return text.substring(1,text.lastIndexOf("]"));
        } else {
            return "";
        }
    }

protected String getObjMetadata ( String text ) { if ( text . startsWith ( "[" ) ) { return text . substring ( 1 , text . lastIndexOf ( "]" ) ) ; } else { return "" ; } }

Method will return just the object metadata
@param text
@return


protected String stripObjMetadata(String text) {
        if (text.startsWith("[")) {
            return text.substring(text.lastIndexOf("]") + 1);
        } else {
            return text;
        }
    }

protected String stripObjMetadata ( String text ) { if ( text . startsWith ( "[" ) ) { return text . substring ( text . lastIndexOf ( "]" ) + 1 ) ; } else { return text ; } }

method will strip the metadata from the text string
@param text
@return


public void addTokens(String[] tokens, Node rootNode) {
        Node thenode = rootNode;
        for (int i = 0; i < tokens.length; i++) {
            Node newnode = thenode.addToken(tokens[i]);
            thenode = newnode;
        }
    }

public void addTokens ( String [ ] tokens , Node rootNode ) { Node thenode = rootNode ; for ( int i = 0 ; i < tokens . length ; i ++ ) { Node newnode = thenode . addToken ( tokens [ i ] ) ; thenode = newnode ; } }

method adds the token to root
@param tokens


public Node[] getConditionChildren(String text) {
        Node thenode = this.rootCond;
        if (text.length() > 0) {
            StringTokenizer tokenz = new StringTokenizer(text);
            this.last = this.current;
            while (tokenz.hasMoreTokens()) {
                String strtk = tokenz.nextToken();
                Node ch = thenode.getChild(strtk);
                // if a child is found, we set thenode to the child Node
                if (ch != null) {
                    thenode = ch;
                } else {
                    break;
                }
            }
            if (thenode != this.rootCond) {
                this.current = thenode;
            }
        }
        Collection<Node> children = thenode.getChildren();
        Node[] nchild = new Node[children.size()];
        return children.toArray(nchild);
    }

the method will tokenize the text and try to find
the node that matches and return the children. the method
will traverse down the network as far as it can and return
the children at that level.
@param text
@return

the method will tokenize the text and try to find the node that matches and return the children . the method will traverse down the network as far as it can and return the children at that level .


public Node[] getChildren(String obj, String text) {
        Node thenode = this.rootCond.getChild(obj);
        if (thenode == null) {
            for (Node child: this.rootCond.getChildren()) {
                String tokenText = child.getToken();
                if (tokenText != null) {
                    int index = tokenText.indexOf("{");
                    if (index != -1) {
                        String substring = tokenText.substring(0, index);
                        if (obj != null && obj.startsWith(substring)) {
                            thenode = child;
                        }
                    }
                }
            }
        }
        if (thenode != null && text.length() > 0) {
            StringTokenizer tokenz = new StringTokenizer(text);
            this.last = this.current;
            while (tokenz.hasMoreTokens()) {
                String strtk = tokenz.nextToken();
                Node ch = thenode.getChild(strtk);
                // if a child is found, we set thenode to the child Node
                if (ch != null) {
                    thenode = ch;
                } else {
                    break;
                }
            }
            if (thenode != this.rootCond) {
                this.current = thenode;
            }
        }
        if (thenode == null) {
            return null;
            // thenode = this.rootCond;
        }
        Collection<Node> children = thenode.getChildren();
        Node[] nchild = new Node[children.size()];
        return children.toArray(nchild);
    }

the method expects the caller to pass the object
@param obj
@param text
@return


public void addChildToList(Node n, String prefix, ArrayList<String> list) {
        if (n.getChildren().size() > 0) {
            for (Node child : n.getChildren()) {
                if (prefix != null && "-".equals(child.getToken())) {
                    if (!list.contains(prefix)) {
                        list.add(prefix);
                    }
                    return;
                }
                String text = (prefix == null ? "" : prefix + " ") + child.getToken();
                // list.add(text);
                addChildToList(child,text,list);
            }
        } else {
            if (!list.contains(prefix)) {
                list.add(prefix);
            }
        }
    }

public
void
addChildToList
(
Node
n
,
String
prefix
,
ArrayList
<
String
>
list
)
{
if
(
n
.
getChildren
(
)
.
size
(
)
>
0
)
{
for
(
Node
child
:
n
.
getChildren
(
)
)
{
if
(
prefix
!=
&&
"-"
.
equals
(
child
.
getToken
(
)
)
)
{
if
(
!
list
.
contains
(
prefix
)
)
{
list
.
add
(
prefix
)
;
}
return
;
}
String
text
=
(
prefix
==
""
:
prefix
+
" "
)
+
child
.
getToken
(
)
;
// list.add(text);
addChildToList
(
child
,
text
,
list
)
;
}
}
else
{
if
(
!
list
.
contains
(
prefix
)
)
{
list
.
add
(
prefix
)
;
}
}
}

method will prepend the parent text to the child and generate
the possible combinations in text format.
@param n
@param prefix
@param list

method will prepend the parent text to the child and generate the possible combinations in text format .


public void printTree() {
        System.out.println("ROOT");
        for (Node n : rootCond.getChildren()) {
            printNode(n);
        }
    }

public void printTree ( ) { System . out . println ( "ROOT" ) ; for ( Node n : rootCond . getChildren ( ) ) { printNode ( n ) ; } }

The method will print the DSLTree to System.out in text format.

The method will print the DSLTree to System . out in text format .


protected void printNode(Node n) {
        printTabs(n.getDepth());
        System.out.println("- \"" + n.getToken() + "\"");
        for (Node c : n.getChildren()) {
            printNode(c);
        }
    }

protected
void
printNode
(
Node
n
)
{
printTabs
(
n
.
getDepth
(
)
)
;
System
.
out
.
println
(
"- \""
+
n
.
getToken
(
)
+
"\""
)
;
for
(
Node
c
:
n
.
getChildren
(
)
)
{
printNode
(
c
)
;
}
}

method will print the node and then iterate over the children
@param n


protected void printTabs(int count) {
        for (int idx=0; idx < count; idx++) {
            System.out.print(tab);
        }
    }

protected void printTabs ( int count ) { for ( int idx = 0 ; idx < count ; idx ++ ) { System . out . print ( tab ) ; } }

Method will print n number of tabs
@param count


public static JsonValue readFrom( String text ) {
    try {
      return new JsonParser( text ).parse();
    } catch( IOException exception ) {
      // JsonParser does not throw IOException for String
      throw new RuntimeException( exception );
    }
  }

Reads a JSON value from the given string.

@param text
the string that contains the JSON value
@return the JSON value that has been read
@throws ParseException
if the input is not valid JSON

Reads a JSON value from the given string .


public static ImageDescriptor getImageDescriptor(String id) {
        ImageDescriptor retVal = getDefault().getImageRegistry().getDescriptor(id);
        if (retVal == null) {
            retVal = loadImageDescriptor(id);
            getDefault().getImageRegistry().put(id, retVal);
        }
        return retVal;
    }

public static ImageDescriptor getImageDescriptor ( String id ) { ImageDescriptor retVal = getDefault ( ) . getImageRegistry ( ) . getDescriptor ( id ) ; if ( retVal == null ) { retVal = loadImageDescriptor ( id ) ; getDefault ( ) . getImageRegistry ( ) . put ( id , retVal ) ; } return retVal ; }

Returns an image descriptor for the image file at the given
plug-in relative path

@param path the path
@return the image descriptor

Returns an image descriptor for the image file at the given plug - in relative path


public Response invoke(Request request) throws IOException {
        Assert.isNotNull(request);

        try {
            open();

            URL resourceUrl = request.getResourceUrl();
            URL originServerUrl = new URL(resourceUrl.getProtocol(), resourceUrl.getHost(), resourceUrl.getPort(), "/"); //$NON-NLS-1$

            URL proxyServerUrl = getProxyServerUrl(originServerUrl);
            if (proxyServerUrl == null && !matchesProxyServerException(originServerUrl)) {
                proxyServerUrl = getDefaultProxyServerUrl();
            }

            IContext context = webDAVFactory.newContext(request.getContext());

            IContext defaultContext = getContext(originServerUrl);
            if (defaultContext == null) {
                defaultContext = getDefaultContext();
            }

            if (defaultContext != null) {
                Enumeration e = defaultContext.keys();
                while (e.hasMoreElements()) {
                    String key = (String) e.nextElement();
                    context.put(key, defaultContext.get(key));
                }
            }

            if (authority != null) {
                authority.authorize(request, null, context, proxyServerUrl, true);
                authority.authorize(request, null, context, proxyServerUrl, false);
            }

            return invoke1(request, context, proxyServerUrl, originServerUrl, 0, 0);
        } finally {
            request.close();
        }
    }

public Response invoke ( Request request ) throws IOException { Assert . isNotNull ( request ) ; try { open ( ) ; URL resourceUrl = request . getResourceUrl ( ) ; URL originServerUrl = new URL ( resourceUrl . getProtocol ( ) , resourceUrl . getHost ( ) , resourceUrl . getPort ( ) , "/" ) ; //$NON-NLS-1$ URL proxyServerUrl = getProxyServerUrl ( originServerUrl ) ; if ( proxyServerUrl == null && ! matchesProxyServerException ( originServerUrl ) ) { proxyServerUrl = getDefaultProxyServerUrl ( ) ; } IContext context = webDAVFactory . newContext ( request . getContext ( ) ) ; IContext defaultContext = getContext ( originServerUrl ) ; if ( defaultContext == null ) { defaultContext = getDefaultContext ( ) ; } if ( defaultContext != null ) { Enumeration e = defaultContext . keys ( ) ; while ( e . hasMoreElements ( ) ) { String key = ( String ) e . nextElement ( ) ; context . put ( key , defaultContext . get ( key ) ) ; } } if ( authority != null ) { authority . authorize ( request , null , context , proxyServerUrl , true ) ; authority . authorize ( request , null , context , proxyServerUrl , false ) ; } return invoke1 ( request , context , proxyServerUrl , originServerUrl , 0 , 0 ) ; } finally { request . close ( ) ; } }

Sends the given request to the server and returns the server's
response.

@param request the request to send to the server
@return the server's response
@throws IOException if an I/O error occurs. Reasons include:

The client is closed.

The client could not connect to the server

An I/O error occurs while communicating with the server

Sends the given request to the server and returns the server s response .


public void setRequestHeaderField(String fieldName, String fieldValue) {
        Assert.isNotNull(fieldName);
        Assert.isNotNull(fieldValue);
        endRequest();
        requestHeader.addField(fieldName, fieldValue);
    }

public void setRequestHeaderField ( String fieldName , String fieldValue ) { Assert . isNotNull ( fieldName ) ; Assert . isNotNull ( fieldValue ) ; endRequest ( ) ; requestHeader . addField ( fieldName , fieldValue ) ; }

Sets the request header value associated with the given field.

@param fieldName the request header field
@param fieldValue the request header value
@see #getRequestHeaderFieldValue(String)

Sets the request header value associated with the given field .


private void createRuleSampleLauncher(IJavaProject project)
            throws JavaModelException, IOException {

        Version version = startPage.getRuntime().getVersion();
        if (version.getMajor()==4) {
            createProjectJavaFile(project, "org/drools/eclipse/wizard/project/RuleLauncherSample_4.java.template", "DroolsTest.java");
        } else if (version.getMajor()==5) {
            createProjectJavaFile(project, "org/drools/eclipse/wizard/project/RuleLauncherSample_5.java.template", "DroolsTest.java");
        } else if (version.getMajor()>=6) {
            createProjectJavaFile(project, "org/drools/eclipse/wizard/project/RuleLauncherSample_6.java.template", "DroolsTest.java");
        }
    }


private void createRule(IJavaProject project, IProgressMonitor monitor) throws CoreException {
        if (startPage.getRuntime().getVersion().getMajor()>=6) {
        	FileUtils.createFolder(project, "src/main/resources/com/sample/rules", monitor);
            createProjectFile(project, monitor, "org/drools/eclipse/wizard/project/Sample.drl.template", "src/main/resources/com/sample/rules", "Sample.drl");
        } else {
            createProjectFile(project, monitor, "org/drools/eclipse/wizard/project/Sample.drl.template", "src/main/rules", "Sample.drl");
        }
    }


private void createRuleFlow(IJavaProject project, IProgressMonitor monitor) throws CoreException {

        Version version = startPage.getRuntime().getVersion();
        if (version.getMajor()==4) {
        	createProjectFile(project, monitor, "org/drools/eclipse/wizard/project/ruleflow_4.rf.template", "src/main/rules", "ruleflow.rf");
        	createProjectFile(project, monitor, "org/drools/eclipse/wizard/project/ruleflow_4.rfm.template", "src/main/rules", "ruleflow.rfm");
        	createProjectFile(project, monitor, "org/drools/eclipse/wizard/project/ruleflow_4.drl.template", "src/main/rules", "ruleflow.drl");
        } else if (version.getMajor()==5 && version.getMinor()==0) {
        	createProjectFile(project, monitor, "org/drools/eclipse/wizard/project/ruleflow.rf.template", "src/main/rules", "ruleflow.rf");
        } else if (version.getMajor()==5) {
        	createProjectFile(project, monitor, "org/drools/eclipse/wizard/project/sample.bpmn.template", "src/main/rules", "sample.bpmn");
        } else {
        	FileUtils.createFolder(project, "src/main/resources/com/sample/process", monitor);
        	createProjectFile(project, monitor, "org/drools/eclipse/wizard/project/sample.bpmn.template", "src/main/resources/com/sample/process", "sample.bpmn");
        }
    }


private void createRuleFlowSampleLauncher(IJavaProject project)
            throws JavaModelException, IOException {

        String s;
        Version version = startPage.getRuntime().getVersion();
        if (version.getMajor()==4) {
            s = "org/drools/eclipse/wizard/project/RuleFlowLauncherSample_4.java.template";
        } else if (version.getMajor()==5 && version.getMinor()==0) {
            s = "org/drools/eclipse/wizard/project/RuleFlowLauncherSample.java.template";
        } else if (version.getMajor()==5) {
            s = "org/drools/eclipse/wizard/project/ProcessLauncherSample_bpmn_5.java.template";
        } else {
            s = "org/drools/eclipse/wizard/project/ProcessLauncherSample_bpmn_6.java.template";
        }
        createProjectJavaFile(project, s, "ProcessTest.java");
    }

Create the sample RuleFlow launcher file.

Create the sample RuleFlow launcher file .


public List<IInstallableUnit> getSelectedIUs(){
    	List<IInstallableUnit> result = new ArrayList<IInstallableUnit>();
    	for (Object o : getCheckedElements()) {
    		if (o instanceof IUTreeItem) {
    			IUTreeItem item = (IUTreeItem) o;
	    		if (item.parent!=null)
	    			result.add(item.iu);
    		}
    	}
    	return result;
    }

public List < IInstallableUnit > getSelectedIUs ( ) { List < IInstallableUnit > result = new ArrayList < IInstallableUnit > ( ) ; for ( Object o : getCheckedElements ( ) ) { if ( o instanceof IUTreeItem ) { IUTreeItem item = ( IUTreeItem ) o ; if ( item . parent != null ) result . add ( item . iu ) ; } } return result ; }

Returns only the installable units that are features, ignoring feature groups.

@return

Returns only the installable units that are features ignoring feature groups .


public void createImage(OutputStream stream, int format) {
        SWTGraphics g = null;
        GC gc = null;
        Image image = null;
        LayerManager layerManager = (LayerManager)
            getGraphicalViewer().getEditPartRegistry().get(LayerManager.ID);
        IFigure figure = layerManager.getLayer(LayerConstants.PRINTABLE_LAYERS);
        Rectangle r = figure.getBounds();
        try {
            image = new Image(Display.getDefault(), r.width, r.height);
            gc = new GC(image);
            g = new SWTGraphics(gc);
            g.translate(r.x * -1, r.y * -1);
            figure.paint(g);
            ImageLoader imageLoader = new ImageLoader();
            imageLoader.data = new ImageData[] { image.getImageData() };
            imageLoader.save(stream, format);
        } catch (Throwable t) {
            DroolsEclipsePlugin.log(t);
        } finally {
            if (g != null) {
                g.dispose();
            }
            if (gc != null) {
                gc.dispose();
            }
            if (image != null) {
                image.dispose();
            }
        }
    }

public void createImage ( OutputStream stream , int format ) { SWTGraphics g = null ; GC gc = null ; Image image = null ; LayerManager layerManager = ( LayerManager ) getGraphicalViewer ( ) . getEditPartRegistry ( ) . get ( LayerManager . ID ) ; IFigure figure = layerManager . getLayer ( LayerConstants . PRINTABLE_LAYERS ) ; Rectangle r = figure . getBounds ( ) ; try { image = new Image ( Display . getDefault ( ) , r . width , r . height ) ; gc = new GC ( image ) ; g = new SWTGraphics ( gc ) ; g . translate ( r . x * - 1 , r . y * - 1 ) ; figure . paint ( g ) ; ImageLoader imageLoader = new ImageLoader ( ) ; imageLoader . data = new ImageData [ ] { image . getImageData ( ) } ; imageLoader . save ( stream , format ) ; } catch ( Throwable t ) { DroolsEclipsePlugin . log ( t ) ; } finally { if ( g != null ) { g . dispose ( ) ; } if ( gc != null ) { gc . dispose ( ) ; } if ( image != null ) { image . dispose ( ) ; } } }

Writes the content of this editor to the given stream.
Possible formats are for example SWT.IMAGE_BMP, IMAGE_GIF,
IMAGE_JPEG, IMAGE_PNG.
@param stream
@param format

Writes the content of this editor to the given stream . Possible formats are for example SWT . IMAGE_BMP IMAGE_GIF IMAGE_JPEG IMAGE_PNG .


public String getFieldName() {
        AlphaNodeFieldConstraint constraint = this.node.getConstraint();
        if (constraint instanceof MvelConstraint) {
        	MvelConstraint mvelConstraint = (MvelConstraint) constraint;
            InternalReadAccessor accessor = mvelConstraint.getFieldExtractor();
            if (accessor instanceof ClassFieldReader) {
                return ((ClassFieldReader) accessor).getFieldName();
            }
        }
        return null;
    }

public String getFieldName ( ) { AlphaNodeFieldConstraint constraint = this . node . getConstraint ( ) ; if ( constraint instanceof MvelConstraint ) { MvelConstraint mvelConstraint = ( MvelConstraint ) constraint ; InternalReadAccessor accessor = mvelConstraint . getFieldExtractor ( ) ; if ( accessor instanceof ClassFieldReader ) { return ( ( ClassFieldReader ) accessor ) . getFieldName ( ) ; } } return null ; }

Constraint has field extractor and this method is returning fieldName
it.

@return field name

Constraint has field extractor and this method is returning fieldName it .


public String getEvaluator() {
        AlphaNodeFieldConstraint constraint = this.node.getConstraint();
        if (constraint instanceof MvelConstraint) {
        	MvelConstraint mvelConstraint = (MvelConstraint) constraint;
            return mvelConstraint.toString();
        }
        return null;
    }

public String getEvaluator ( ) { AlphaNodeFieldConstraint constraint = this . node . getConstraint ( ) ; if ( constraint instanceof MvelConstraint ) { MvelConstraint mvelConstraint = ( MvelConstraint ) constraint ; return mvelConstraint . toString ( ) ; } return null ; }

Constraint's evaluator string

@return evaluator string


public String getValue() {
        AlphaNodeFieldConstraint constraint = this.node.getConstraint();
        if (constraint instanceof MvelConstraint) {
        	MvelConstraint mvelConstraint = (MvelConstraint) constraint;
        	FieldValue field = mvelConstraint.getField();
            return field != null ? field.toString() : null;
        }
        return null;
    }

public String getValue ( ) { AlphaNodeFieldConstraint constraint = this . node . getConstraint ( ) ; if ( constraint instanceof MvelConstraint ) { MvelConstraint mvelConstraint = ( MvelConstraint ) constraint ; FieldValue field = mvelConstraint . getField ( ) ; return field != null ? field . toString ( ) : null ; } return null ; }

Constraint field string

@return field string


private void addGuvnorResourceProperties(ResourceProperties props,
                                            String filename, String resource) throws Exception {
        if (props == null) {
            return;
        }
        IResponse response = null;
        try {
            String path = resource.substring(0, resource.lastIndexOf('/'));
            String apiVer = changeToAPICall(path);
            Properties guvProps = new Properties();
            response = getResourceInputStream(apiVer);
            guvProps.load(response.getInputStream());
            String val = guvProps.getProperty(filename);
            if (val != null) {
                StringTokenizer tokens = new StringTokenizer(val, ","); //$NON-NLS-1$
//                String dateStamp = tokens.nextToken();
//                String revision = tokens.nextToken();
                if(tokens.hasMoreElements()){
                    props.setLastModifiedDate(tokens.nextToken());
                }
                if(tokens.hasMoreElements()){
                    props.setRevision(tokens.nextToken());
                }
            } else {
                Exception nfe = new Exception("Failed to get Guvnor properties for " + filename); //$NON-NLS-1$
                Activator.getDefault().writeLog(IStatus.WARNING, nfe.getMessage(), nfe);
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }

Adds Guvnor-specific resource properties to the collection.
@param props The resource properties colleciton
@param filename The name of the resource
@param resource The full path to the resource in Guvnor
@throws Exception

Adds Guvnor - specific resource properties to the collection .