private void loadConfig(IFile input) {
        IResource res = findDSLResource( input, dslConfigName );
        if (res instanceof IFile) {
            IFile dslConf = (IFile) res;
            if (dslConf.exists()) {
                InputStream stream = null;
                try {
                    stream = dslConf.getContents();
                    readConfig( stream );
                    valid = true;
                } catch ( Exception e ) {
                    throw new IllegalStateException("Unable to open DSL config file. (Exception: " + e.getMessage() + ")");
                } finally {
                    closeStream( stream );
                }

            }
        }
    }

This does the hunting around the projec to find the .dsl file.

This does the hunting around the projec to find the . dsl file .


void readConfig(InputStream stream) throws IOException, CoreException {
        DSLTokenizedMappingFile file = new DSLTokenizedMappingFile();
        file.parseAndLoad(new InputStreamReader(stream));

        DSLMapping grammar = file.getMapping();
        List<DSLMappingEntry> conditions = grammar.getEntries( DSLMappingEntry.CONDITION );
        List<DSLMappingEntry> consequences = grammar.getEntries( DSLMappingEntry.CONSEQUENCE );

        conditionProposals = buildProposals(conditions);
        consequenceProposals = buildProposals(consequences);

        dslTree.buildTree(grammar);
    }

void readConfig ( InputStream stream ) throws IOException , CoreException { DSLTokenizedMappingFile file = new DSLTokenizedMappingFile ( ) ; file . parseAndLoad ( new InputStreamReader ( stream ) ) ; DSLMapping grammar = file . getMapping ( ) ; List < DSLMappingEntry > conditions = grammar . getEntries ( DSLMappingEntry . CONDITION ) ; List < DSLMappingEntry > consequences = grammar . getEntries ( DSLMappingEntry . CONSEQUENCE ) ; conditionProposals = buildProposals ( conditions ) ; consequenceProposals = buildProposals ( consequences ) ; dslTree . buildTree ( grammar ) ; }

This will load in the DSL config file, using the DSLMapping from drools-compiler

This will load in the DSL config file using the DSLMapping from drools - compiler


public Menu getMenu(Control parent) {

        setMenu( new Menu( parent ) );

        final Shell shell = parent.getShell();
        addProjectWizard( menu,
                shell );

        addRuleWizard( menu,
                       shell );

        addDSLWizard( menu,
                      shell );

        addDTWizard( menu,
                      shell );

        return menu;
    }

public Menu getMenu ( Control parent ) { setMenu ( new Menu ( parent ) ) ; final Shell shell = parent . getShell ( ) ; addProjectWizard ( menu , shell ) ; addRuleWizard ( menu , shell ) ; addDSLWizard ( menu , shell ) ; addDTWizard ( menu , shell ) ; return menu ; }

Return a menu which launches the various wizards


public ResponseBody addResponse() {
        Element response = addChild(root, "response", childNames, true); //$NON-NLS-1$
        try {
            return new ResponseBody(response);
        } catch (MalformedElementException e) {
            Assert.isTrue(false, Policy.bind("assert.internalError")); //$NON-NLS-1$
            return null; // Never reached.
        }
    }

public
ResponseBody
addResponse
(
)
{
Element
response
=
addChild
(
root
,
"response"
,
childNames
,
true
)
;
//$NON-NLS-1$
try
{
return
new
ResponseBody
(
response
)
;
}
catch
(
MalformedElementException
e
)
{
Assert
.
isTrue
(
false
,
Policy
.
bind
(
"assert.internalError"
)
)
;
//$NON-NLS-1$
return
;
// Never reached.
}
}

Creates and adds a response element to this multistatus and returns
an editor on it.

@return an editor on a response element

Creates and adds a response element to this multistatus and returns an editor on it .


public void addHref(String href) {
        String encodedHref = encodeHref(href);
        if (isDuplicate(encodedHref))
            return;
        appendChild(root, "href", encodedHref); //$NON-NLS-1$
    }

public void addHref ( String href ) { String encodedHref = encodeHref ( href ) ; if ( isDuplicate ( encodedHref ) ) return ; appendChild ( root , "href" , encodedHref ) ; //$NON-NLS-1$ }

Adds the given href to the end of the set of hrefs. If the href
already exists it is not added.

@param href    the href to add to the end of the set of hrefs

Adds the given href to the end of the set of hrefs . If the href already exists it is not added .


public void insertHrefBefore(String newHref, String refHref) {
        String refHrefEncoded = encodeHref(refHref);
        String newHrefEncoded = encodeHref(newHref);
        if (isDuplicate(newHrefEncoded))
            return;
        Element child = getFirstChild(root, "href"); //$NON-NLS-1$
        while (child != null) {
            if (refHrefEncoded.equals(getFirstText(child))) {
                insertBefore(child, "href", newHrefEncoded); //$NON-NLS-1$
                return;
            }
            child = getNextSibling(child, "href"); //$NON-NLS-1$
        }
        Assert.isTrue(false, Policy.bind("assert.noHrefRef")); //$NON-NLS-1$
    }

public void insertHrefBefore ( String newHref , String refHref ) { String refHrefEncoded = encodeHref ( refHref ) ; String newHrefEncoded = encodeHref ( newHref ) ; if ( isDuplicate ( newHrefEncoded ) ) return ; Element child = getFirstChild ( root , "href" ) ; //$NON-NLS-1$ while ( child != null ) { if ( refHrefEncoded . equals ( getFirstText ( child ) ) ) { insertBefore ( child , "href" , newHrefEncoded ) ; //$NON-NLS-1$ return ; } child = getNextSibling ( child , "href" ) ; //$NON-NLS-1$ } Assert . isTrue ( false , Policy . bind ( "assert.noHrefRef" ) ) ; //$NON-NLS-1$ }

Inserts the given newHref before the given refHref in the set of
hrefs. If newHref already exists it is not inserted.

@param refHref the existing href
@param newHref the new href to be inserted before the existing href

Inserts the given newHref before the given refHref in the set of hrefs . If newHref already exists it is not inserted .


public void removeHref(String href) {
        String encodedHref = encodeHref(href);
        Element child = getFirstChild(root, "href"); //$NON-NLS-1$
        while (child != null) {
            if (encodedHref.equals(getFirstText(child))) {
                root.removeChild(child);
                return;
            }
            child = getNextSibling(child, "href"); //$NON-NLS-1$
        }
    }

public void removeHref ( String href ) { String encodedHref = encodeHref ( href ) ; Element child = getFirstChild ( root , "href" ) ; //$NON-NLS-1$ while ( child != null ) { if ( encodedHref . equals ( getFirstText ( child ) ) ) { root . removeChild ( child ) ; return ; } child = getNextSibling ( child , "href" ) ; //$NON-NLS-1$ } }

Remove the given href from the set of hrefs.

@param href    the href to remove from the set of hrefs

Remove the given href from the set of hrefs .


public PropStat addPropStat() {
        Element firstHref = getFirstChild(root, "href"); //$NON-NLS-1$
        Assert.isTrue(firstHref == null || getNextSibling(firstHref, new String[] {"href", "status"}) == null); //$NON-NLS-1$ //$NON-NLS-2$
        Element element = addChild(root, "propstat", fgNamesPropStat, false); //$NON-NLS-1$
        try {
            return new PropStat(element);
        } catch (MalformedElementException e) {
            Assert.isTrue(false, Policy.bind("assert.internalError")); //$NON-NLS-1$
            return null; // Never reached.
        }
    }

public
PropStat
addPropStat
(
)
{
Element
firstHref
=
getFirstChild
(
root
,
"href"
)
;
//$NON-NLS-1$
Assert
.
isTrue
(
firstHref
==
||
getNextSibling
(
firstHref
,
new
String
[
]
{
"href"
,
"status"
}
)
==
)
;
//$NON-NLS-1$ //$NON-NLS-2$
Element
element
=
addChild
(
root
,
"propstat"
,
fgNamesPropStat
,
false
)
;
//$NON-NLS-1$
try
{
return
new
PropStat
(
element
)
;
}
catch
(
MalformedElementException
e
)
{
Assert
.
isTrue
(
false
,
Policy
.
bind
(
"assert.internalError"
)
)
;
//$NON-NLS-1$
return
;
// Never reached.
}
}

Creates and adds a propstat element on this response and returns an
editor on it.

@return an editor on a propstat element

Creates and adds a propstat element on this response and returns an editor on it .


public String getHref() throws MalformedElementException {
        String href = getChildText(root, "href", true); //$NON-NLS-1$
        ensureNotNull(Policy.bind("ensure.missingHrefElmt"), href); //$NON-NLS-1$
        return decodeHref(href);
    }

public String getHref ( ) throws MalformedElementException { String href = getChildText ( root , "href" , true ) ; //$NON-NLS-1$ ensureNotNull ( Policy . bind ( "ensure.missingHrefElmt" ) , href ) ; //$NON-NLS-1$ return decodeHref ( href ) ; }

Returns this response's first href.

@return this response's first href.
@throws MalformedElementException if there is reason to believe that
this editor's underlying element is not well formed


public String getStatus() throws MalformedElementException {
        Element status = getFirstChild(root, "status"); //$NON-NLS-1$
        ensureNotNull(Policy.bind("ensure.missingStatusElmt"), status); //$NON-NLS-1$
        return getFirstText(status);
    }

public String getStatus ( ) throws MalformedElementException { Element status = getFirstChild ( root , "status" ) ; //$NON-NLS-1$ ensureNotNull ( Policy . bind ( "ensure.missingStatusElmt" ) , status ) ; //$NON-NLS-1$ return getFirstText ( status ) ; }

Returns this response's status.

@return this response's status
@throws MalformedElementException if there is reason to believe that
this editor's underlying element is not well formed, or if
this response is not in "status" form


public static IJavaStackFrame getStackFrame(IValue value)
            throws CoreException {
        IStatusHandler handler = getStackFrameProvider();
        if (handler != null) {
            IJavaStackFrame stackFrame = (IJavaStackFrame) handler
                    .handleStatus(fgNeedStackFrame, value);
            if (stackFrame != null) {
                return stackFrame;
            }
        }
        IDebugTarget target = value.getDebugTarget();
        IJavaDebugTarget javaTarget = (IJavaDebugTarget) target
                .getAdapter(IJavaDebugTarget.class);
        if (javaTarget != null) {
            IThread[] threads = javaTarget.getThreads();
            for (int i = 0; i < threads.length; i++) {
                IThread thread = threads[i];
                if (thread.isSuspended()) {
                    return (IJavaStackFrame) thread.getTopStackFrame();
                }
            }
        }
        return null;
    }

public static IJavaStackFrame getStackFrame ( IValue value ) throws CoreException { IStatusHandler handler = getStackFrameProvider ( ) ; if ( handler != null ) { IJavaStackFrame stackFrame = ( IJavaStackFrame ) handler . handleStatus ( fgNeedStackFrame , value ) ; if ( stackFrame != null ) { return stackFrame ; } } IDebugTarget target = value . getDebugTarget ( ) ; IJavaDebugTarget javaTarget = ( IJavaDebugTarget ) target . getAdapter ( IJavaDebugTarget . class ) ; if ( javaTarget != null ) { IThread [ ] threads = javaTarget . getThreads ( ) ; for ( int i = 0 ; i < threads . length ; i ++ ) { IThread thread = threads [ i ] ; if ( thread . isSuspended ( ) ) { return ( IJavaStackFrame ) thread . getTopStackFrame ( ) ; } } } return null ; }

Return the current stack frame context, or a valid stack frame for the
given value.

Return the current stack frame context or a valid stack frame for the given value .


private boolean isSubtypeOf(String class1,
                                String class2) {
        if (class1 == null || class2 == null) {
            return false;
        }
        class1 = convertToNonPrimitiveClass(class1);
        class2 = convertToNonPrimitiveClass(class2);
        // TODO add code to take primitive types into account
        ClassTypeResolver resolver = new ClassTypeResolver(getUniqueImports(),
                                                           ProjectClassLoader.getProjectClassLoader(getEditor()));
        try {
            Class<?> clazz1 = resolver.resolveType(class1);
            Class<?> clazz2 = resolver.resolveType(class2);
            if (clazz1 == null || clazz2 == null) {
                return false;
            }
            return clazz2.isAssignableFrom(clazz1);
        } catch (ClassNotFoundException exc) {
            return false;
        }
    }

Returns true if the first class is the same or a subtype of the second
class.

@param class1
@param class2
@return

Returns true if the first class is the same or a subtype of the second class .


public static boolean containsProposal(final Collection<ICompletionProposal> proposals, String newProposal) {
        for (ICompletionProposal prop : proposals) {
            String displayString = prop.getDisplayString();
            String[] existings = displayString.split(" ");
            if (existings.length == 0) {
                continue;
            }

            String[] newProposals = newProposal.split(" ");
            if (newProposals.length == 0) {
                continue;
            }

            if (existings[0].equals(newProposals[0])) {
                return true;
            }
        }
        return false;
    }

public
static
boolean
containsProposal
(
final
Collection
<
ICompletionProposal
>
proposals
,
String
newProposal
)
{
for
(
ICompletionProposal
prop
:
proposals
)
{
String
displayString
=
prop
.
getDisplayString
(
)
;
String
[
]
existings
=
displayString
.
split
(
" "
)
;
if
(
existings
.
length
==
0
)
{
continue
;
}
String
[
]
newProposals
=
newProposal
.
split
(
" "
)
;
if
(
newProposals
.
length
==
0
)
{
continue
;
}
if
(
existings
[
0
]
.
equals
(
newProposals
[
0
]
)
)
{
return
true
;
}
}
return
false
;
}

Attempt to compare proposals of different types based on the tokenized display string

@param proposals
@param newProposal
@return true if the collection contains a proposal which matches the new Proposal.
The match is based on the first token based on a space split


public static Node cloneNode(Document document, Node node) {

        Node nodeClone = null;

        switch (node.getNodeType()) {
            case Node.ELEMENT_NODE :
                {
                    nodeClone = document.createElement(((Element) node).getTagName());
                    NamedNodeMap namedNodeMap = node.getAttributes();
                    for (int i = 0; i < namedNodeMap.getLength(); ++i) {
                        Attr attr = (Attr) namedNodeMap.item(i);
                        Attr attrClone = document.createAttribute(attr.getName());
                        attrClone.setValue(attr.getValue());
                        ((Element) nodeClone).setAttributeNode(attrClone);
                    }
                }
                break;
            case Node.TEXT_NODE :
                nodeClone = document.createTextNode(((CharacterData) node).getData());
                break;
            case Node.CDATA_SECTION_NODE :
                nodeClone = document.createCDATASection(((CharacterData) node).getData());
                break;
            case Node.ENTITY_REFERENCE_NODE :
                nodeClone = document.createEntityReference(node.getNodeName());
                break;
            case Node.PROCESSING_INSTRUCTION_NODE :
                nodeClone = document.createProcessingInstruction(((ProcessingInstruction) node).getTarget(), ((ProcessingInstruction) node).getData());
                break;
            case Node.COMMENT_NODE :
                nodeClone = document.createComment(((CharacterData) node).getData());
                break;
            case Node.DOCUMENT_FRAGMENT_NODE :
                nodeClone = document.createDocumentFragment();
                break;
            case Node.DOCUMENT_NODE :
            case Node.DOCUMENT_TYPE_NODE :
            case Node.NOTATION_NODE :
            case Node.ATTRIBUTE_NODE :
            case Node.ENTITY_NODE :
                Assert.isTrue(false, Policy.bind("assert.notSupported")); //$NON-NLS-1$
                break;
            default :
                Assert.isTrue(false, Policy.bind("assert.unknownNodeType")); //$NON-NLS-1$
        }

        return nodeClone;
    }

public static Node cloneNode ( Document document , Node node ) { Node nodeClone = null ; switch ( node . getNodeType ( ) ) { case Node . ELEMENT_NODE : { nodeClone = document . createElement ( ( ( Element ) node ) . getTagName ( ) ) ; NamedNodeMap namedNodeMap = node . getAttributes ( ) ; for ( int i = 0 ; i < namedNodeMap . getLength ( ) ; ++ i ) { Attr attr = ( Attr ) namedNodeMap . item ( i ) ; Attr attrClone = document . createAttribute ( attr . getName ( ) ) ; attrClone . setValue ( attr . getValue ( ) ) ; ( ( Element ) nodeClone ) . setAttributeNode ( attrClone ) ; } } break ; case Node . TEXT_NODE : nodeClone = document . createTextNode ( ( ( CharacterData ) node ) . getData ( ) ) ; break ; case Node . CDATA_SECTION_NODE : nodeClone = document . createCDATASection ( ( ( CharacterData ) node ) . getData ( ) ) ; break ; case Node . ENTITY_REFERENCE_NODE : nodeClone = document . createEntityReference ( node . getNodeName ( ) ) ; break ; case Node . PROCESSING_INSTRUCTION_NODE : nodeClone = document . createProcessingInstruction ( ( ( ProcessingInstruction ) node ) . getTarget ( ) , ( ( ProcessingInstruction ) node ) . getData ( ) ) ; break ; case Node . COMMENT_NODE : nodeClone = document . createComment ( ( ( CharacterData ) node ) . getData ( ) ) ; break ; case Node . DOCUMENT_FRAGMENT_NODE : nodeClone = document . createDocumentFragment ( ) ; break ; case Node . DOCUMENT_NODE : case Node . DOCUMENT_TYPE_NODE : case Node . NOTATION_NODE : case Node . ATTRIBUTE_NODE : case Node . ENTITY_NODE : Assert . isTrue ( false , Policy . bind ( "assert.notSupported" ) ) ; //$NON-NLS-1$ break ; default : Assert . isTrue ( false , Policy . bind ( "assert.unknownNodeType" ) ) ; //$NON-NLS-1$ } return nodeClone ; }

Returns a clone of the given node.  The given document becomes the
owner document of the clone.

@param document the owner document of the clone
@param node     the node to clone
@return         a clone of the given node

Returns a clone of the given node . The given document becomes the owner document of the clone .


public void reset() throws IOException {
        if (file == null) {
            ((ByteArrayInputStream) is).reset();
        } else {
            if (fos != null) {
                while (skip(4096) > 0);
                fos.close();
                fos = null;
                if (length == -1) {
                    length = totalBytesRead;
                }
            }
            is.close();
            is = new FileInputStream(file);
        }

        totalBytesRead = 0;
    }

public void reset ( ) throws IOException { if ( file == null ) { ( ( ByteArrayInputStream ) is ) . reset ( ) ; } else { if ( fos != null ) { while ( skip ( 4096 ) > 0 ) ; fos . close ( ) ; fos = null ; if ( length == - 1 ) { length = totalBytesRead ; } } is . close ( ) ; is = new FileInputStream ( file ) ; } totalBytesRead = 0 ; }

Resets the stream to its beginning so it can be read again.

@exception IOException if there is an I/O error

Resets the stream to its beginning so it can be read again .


protected void createActions() {
        super.createActions();

        IAction a = new TextOperationAction(RuleEditorMessages
                .getResourceBundle(), "ContentAssistProposal.", this,
                ISourceViewer.CONTENTASSIST_PROPOSALS);
        a
                .setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
        setAction("ContentAssistProposal", a);

        a = new TextOperationAction(
                RuleEditorMessages.getResourceBundle(),
                "ContentAssistTip.", this, ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$
        a
                .setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION);
        setAction("ContentAssistTip", a);

        a = new ToggleBreakpointAction(getSite().getPart() , null, getVerticalRuler());
        setAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK, a);

    }

protected void createActions ( ) { super . createActions ( ) ; IAction a = new TextOperationAction ( RuleEditorMessages . getResourceBundle ( ) , "ContentAssistProposal." , this , ISourceViewer . CONTENTASSIST_PROPOSALS ) ; a . setActionDefinitionId ( ITextEditorActionDefinitionIds . CONTENT_ASSIST_PROPOSALS ) ; setAction ( "ContentAssistProposal" , a ) ; a = new TextOperationAction ( RuleEditorMessages . getResourceBundle ( ) , "ContentAssistTip." , this , ISourceViewer . CONTENTASSIST_CONTEXT_INFORMATION ) ; //$NON-NLS-1$ a . setActionDefinitionId ( ITextEditorActionDefinitionIds . CONTENT_ASSIST_CONTEXT_INFORMATION ) ; setAction ( "ContentAssistTip" , a ) ; a = new ToggleBreakpointAction ( getSite ( ) . getPart ( ) , null , getVerticalRuler ( ) ) ; setAction ( ITextEditorActionConstants . RULER_DOUBLE_CLICK , a ) ; }


public void addConnection(Connection conn) {
        if ( conn == null || conn.getSource() == conn.getTarget() ) {
            throw new IllegalArgumentException();
        }
        if ( conn.getSource() == this ) {
            sourceConnections.add( conn );
            firePropertyChange( SOURCE_CONNECTIONS_PROP,
                                null,
                                conn );
        } else if ( conn.getTarget() == this ) {
            targetConnections.add( conn );
            firePropertyChange( TARGET_CONNECTIONS_PROP,
                                null,
                                conn );
        }
    }

public void addConnection ( Connection conn ) { if ( conn == null || conn . getSource ( ) == conn . getTarget ( ) ) { throw new IllegalArgumentException ( ) ; } if ( conn . getSource ( ) == this ) { sourceConnections . add ( conn ) ; firePropertyChange ( SOURCE_CONNECTIONS_PROP , null , conn ) ; } else if ( conn . getTarget ( ) == this ) { targetConnections . add ( conn ) ; firePropertyChange ( TARGET_CONNECTIONS_PROP , null , conn ) ; } }

Add an incoming or outgoing connection to this vertex.
@param conn a non-null connection instance
@throws IllegalArgumentException if the connection is null or has not distinct endpoints

Add an incoming or outgoing connection to this vertex .


public Object getPropertyValue(Object propertyId) {
        if ( XPOS_PROP.equals( propertyId ) ) {
            return Integer.toString( location.x );
        }
        if ( YPOS_PROP.equals( propertyId ) ) {
            return Integer.toString( location.y );
        }
        if ( HEIGHT_PROP.equals( propertyId ) ) {
            return Integer.toString( size.height );
        }
        if ( WIDTH_PROP.equals( propertyId ) ) {
            return Integer.toString( size.width );
        }
        return null;
    }

public Object getPropertyValue ( Object propertyId ) { if ( XPOS_PROP . equals ( propertyId ) ) { return Integer . toString ( location . x ) ; } if ( YPOS_PROP . equals ( propertyId ) ) { return Integer . toString ( location . y ) ; } if ( HEIGHT_PROP . equals ( propertyId ) ) { return Integer . toString ( size . height ) ; } if ( WIDTH_PROP . equals ( propertyId ) ) { return Integer . toString ( size . width ) ; } return null ; }

Return the property value for the given propertyId, or null.

Return the property value for the given propertyId or null .


public void removeConnection(Connection conn) {
        if ( conn == null ) {
            throw new IllegalArgumentException();
        }
        if ( conn.getSource() == this ) {
            sourceConnections.remove( conn );
            firePropertyChange( SOURCE_CONNECTIONS_PROP,
                                null,
                                conn );
        } else if ( conn.getTarget() == this ) {
            targetConnections.remove( conn );
            firePropertyChange( TARGET_CONNECTIONS_PROP,
                                null,
                                conn );
        }
    }

public void removeConnection ( Connection conn ) { if ( conn == null ) { throw new IllegalArgumentException ( ) ; } if ( conn . getSource ( ) == this ) { sourceConnections . remove ( conn ) ; firePropertyChange ( SOURCE_CONNECTIONS_PROP , null , conn ) ; } else if ( conn . getTarget ( ) == this ) { targetConnections . remove ( conn ) ; firePropertyChange ( TARGET_CONNECTIONS_PROP , null , conn ) ; } }

Remove an incoming or outgoing connection from this vertex.

@param conn a non-null connection instance
@throws IllegalArgumentException if the parameter is null

Remove an incoming or outgoing connection from this vertex .


public void setLocation(Point newLocation) {
        if ( newLocation == null ) {
            throw new IllegalArgumentException();
        }
        location.setLocation( newLocation );
        firePropertyChange( LOCATION_PROP,
                            null,
                            location );
    }

public void setLocation ( Point newLocation ) { if ( newLocation == null ) { throw new IllegalArgumentException ( ) ; } location . setLocation ( newLocation ) ; firePropertyChange ( LOCATION_PROP , null , location ) ; }

Set the Location of this vertex.
@param newLocation a non-null Point instance
@throws IllegalArgumentException if the parameter is null


public void setPropertyValue(Object propertyId,
                                 Object value) {
        if ( XPOS_PROP.equals( propertyId ) ) {
            int x = Integer.parseInt( (String) value );
            setLocation( new Point( x,
                                    location.y ) );
        } else if ( YPOS_PROP.equals( propertyId ) ) {
            int y = Integer.parseInt( (String) value );
            setLocation( new Point( location.x,
                                    y ) );
        } else if ( HEIGHT_PROP.equals( propertyId ) ) {
            int height = Integer.parseInt( (String) value );
            setSize( new Dimension( size.width,
                                    height ) );
        } else if ( WIDTH_PROP.equals( propertyId ) ) {
            int width = Integer.parseInt( (String) value );
            setSize( new Dimension( width,
                                    size.height ) );
        }
    }

public void setPropertyValue ( Object propertyId , Object value ) { if ( XPOS_PROP . equals ( propertyId ) ) { int x = Integer . parseInt ( ( String ) value ) ; setLocation ( new Point ( x , location . y ) ) ; } else if ( YPOS_PROP . equals ( propertyId ) ) { int y = Integer . parseInt ( ( String ) value ) ; setLocation ( new Point ( location . x , y ) ) ; } else if ( HEIGHT_PROP . equals ( propertyId ) ) { int height = Integer . parseInt ( ( String ) value ) ; setSize ( new Dimension ( size . width , height ) ) ; } else if ( WIDTH_PROP . equals ( propertyId ) ) { int width = Integer . parseInt ( ( String ) value ) ; setSize ( new Dimension ( width , size . height ) ) ; } }

Set the property value for the given property id.

Set the property value for the given property id .


public void setSize(Dimension newSize) {
        if ( newSize != null ) {
            size.setSize( newSize );
            firePropertyChange( SIZE_PROP,
                                null,
                                size );
        }
    }

public void setSize ( Dimension newSize ) { if ( newSize != null ) { size . setSize ( newSize ) ; firePropertyChange ( SIZE_PROP , null , size ) ; } }

Set the Size of this vertex.
Will not update the size if newSize is null.
@param newSize a non-null Dimension instance or null

Set the Size of this vertex . Will not update the size if newSize is null .


public static String dumpConstraints(final Constraint[] constraints) {
        if ( constraints == null ) {
            return null;
        }
        final StringBuffer buffer = new StringBuffer();
        for ( int i = 0, length = constraints.length; i < length; i++ ) {
            buffer.append( constraints[i].toString() + "<br>" );
        }
        return buffer.toString();
    }

public static String dumpConstraints ( final Constraint [ ] constraints ) { if ( constraints == null ) { return null ; } final StringBuffer buffer = new StringBuffer ( ) ; for ( int i = 0 , length = constraints . length ; i < length ; i ++ ) { buffer . append ( constraints [ i ] . toString ( ) + "<br>" ) ; } return buffer . toString ( ) ; }

Constructs constraints string

@param constraints array of constraints
@return html-formatted constraints representation


public LockEntry addLockEntry() {

        Element lockentry = addChild(root, "lockentry", childNames, false); //$NON-NLS-1$
        Element locktype = appendChild(lockentry, "locktype"); //$NON-NLS-1$
        appendChild(locktype, "write"); //$NON-NLS-1$

        LockEntry result = null;
        try {
            result = new LockEntry(lockentry);
        } catch (MalformedElementException e) {
            Assert.isTrue(false, Policy.bind("assert.internalError")); //$NON-NLS-1$
        }

        return result;
    }

public LockEntry addLockEntry ( ) { Element lockentry = addChild ( root , "lockentry" , childNames , false ) ; //$NON-NLS-1$ Element locktype = appendChild ( lockentry , "locktype" ) ; //$NON-NLS-1$ appendChild ( locktype , "write" ) ; //$NON-NLS-1$ LockEntry result = null ; try { result = new LockEntry ( lockentry ) ; } catch ( MalformedElementException e ) { Assert . isTrue ( false , Policy . bind ( "assert.internalError" ) ) ; //$NON-NLS-1$ } return result ; }

Creates a new lockentry and adds it to this supported lock. Returns
an editor on the new lockentry.

@return an editor on a new lockentry for this supportedlock

Creates a new lockentry and adds it to this supported lock . Returns an editor on the new lockentry .


public boolean addChild(BaseVertex vertex) {
        if ( vertex != null && vertices.add( vertex ) ) {
            firePropertyChange( PROP_CHILD_ADDED,
                                null,
                                vertex );
            return true;
        }
        return false;
    }

public boolean addChild ( BaseVertex vertex ) { if ( vertex != null && vertices . add ( vertex ) ) { firePropertyChange ( PROP_CHILD_ADDED , null , vertex ) ; return true ; } return false ; }

Add new BaseVertex to the graph

@param vertex

@return true, if vertex was added, false otherwise


public boolean removeChild(BaseVertex vertex) {
        if ( vertex != null && vertices.remove( vertex ) ) {
            firePropertyChange( PROP_CHILD_REMOVED,
                                null,
                                vertex );
            return true;
        }
        return false;
    }

public boolean removeChild ( BaseVertex vertex ) { if ( vertex != null && vertices . remove ( vertex ) ) { firePropertyChange ( PROP_CHILD_REMOVED , null , vertex ) ; return true ; } return false ; }

Remove a vertex from this graph

@param vertex vertex to be removed
@return true, if the vertex removal succeeded, false otherwise


public void start(BundleContext context) throws Exception {
        super.start( context );
        IPreferenceStore preferenceStore = getPreferenceStore();
        useCachePreference = preferenceStore.getBoolean( IDroolsConstants.CACHE_PARSED_RULES );
        preferenceStore.addPropertyChangeListener( new IPropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent event) {
                if ( IDroolsConstants.CACHE_PARSED_RULES.equals( event.getProperty() ) ) {
                    useCachePreference = ((Boolean) event.getNewValue()).booleanValue();
                    if ( !useCachePreference ) {
                        clearCache();
                    }
                }
            }
        } );
    }

public void start ( BundleContext context ) throws Exception { super . start ( context ) ; IPreferenceStore preferenceStore = getPreferenceStore ( ) ; useCachePreference = preferenceStore . getBoolean ( IDroolsConstants . CACHE_PARSED_RULES ) ; preferenceStore . addPropertyChangeListener ( new IPropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent event ) { if ( IDroolsConstants . CACHE_PARSED_RULES . equals ( event . getProperty ( ) ) ) { useCachePreference = ( ( Boolean ) event . getNewValue ( ) ) . booleanValue ( ) ; if ( ! useCachePreference ) { clearCache ( ) ; } } } } ) ; }

This method is called upon plug-in activation

This method is called upon plug - in activation


public void stop(BundleContext context) throws Exception {
        super.stop( context );
        plugin = null;
        resourceBundle = null;
        parsedRules = null;
        compiledRules = null;
        processInfos = null;
        processInfosById = null;
        for (Color color: colors.values()) {
            color.dispose();
        }
    }

public void stop ( BundleContext context ) throws Exception { super . stop ( context ) ; plugin = null ; resourceBundle = null ; parsedRules = null ; compiledRules = null ; processInfos = null ; processInfosById = null ; for ( Color color : colors . values ( ) ) { color . dispose ( ) ; } }

This method is called when the plug-in is stopped

This method is called when the plug - in is stopped


public static String getResourceString(String key) {
        ResourceBundle bundle = DroolsEclipsePlugin.getDefault().getResourceBundle();
        try {
            return (bundle != null) ? bundle.getString( key ) : key;
        } catch ( MissingResourceException e ) {
            return key;
        }
    }

public static String getResourceString ( String key ) { ResourceBundle bundle = DroolsEclipsePlugin . getDefault ( ) . getResourceBundle ( ) ; try { return ( bundle != null ) ? bundle . getString ( key ) : key ; } catch ( MissingResourceException e ) { return key ; } }

Returns the string from the plugin's resource bundle,
or 'key' if not found.

Returns the string from the plugin s resource bundle or key if not found .


public ResourceBundle getResourceBundle() {
        try {
            if ( resourceBundle == null ) resourceBundle = ResourceBundle.getBundle( "droolsIDE.DroolsIDEPluginResources" );
        } catch ( MissingResourceException x ) {
            resourceBundle = null;
        }
        return resourceBundle;
    }

public ResourceBundle getResourceBundle ( ) { try { if ( resourceBundle == null ) resourceBundle = ResourceBundle . getBundle ( "droolsIDE.DroolsIDEPluginResources" ) ; } catch ( MissingResourceException x ) { resourceBundle = null ; } return resourceBundle ; }


public FormColors getRuleBuilderFormColors(Display display) {
        if ( ruleBuilderFormColors == null ) {
            ruleBuilderFormColors = new FormColors( display );
            ruleBuilderFormColors.markShared();
        }
        return ruleBuilderFormColors;
    }

public FormColors getRuleBuilderFormColors ( Display display ) { if ( ruleBuilderFormColors == null ) { ruleBuilderFormColors = new FormColors ( display ) ; ruleBuilderFormColors . markShared ( ) ; } return ruleBuilderFormColors ; }

Form Colors, default colors for now.

@param display
@return


public void setDateTime(String date) {
        String[] patterns = {RFC_1123_PATTERN, ISO_8601_UTC_PATTERN, ISO_8601_UTC_MILLIS_PATTERN, ISO_8601_PATTERN, ISO_8601_MILLIS_PATTERN, RFC_850_PATTERN, ASCTIME_PATTERN};
        for (int i = 0; i < patterns.length; i++) {
            if (setDateTime(date, patterns[i]))
                break;
        }
    }

public void setDateTime ( String date ) { String [ ] patterns = { RFC_1123_PATTERN , ISO_8601_UTC_PATTERN , ISO_8601_UTC_MILLIS_PATTERN , ISO_8601_PATTERN , ISO_8601_MILLIS_PATTERN , RFC_850_PATTERN , ASCTIME_PATTERN } ; for ( int i = 0 ; i < patterns . length ; i ++ ) { if ( setDateTime ( date , patterns [ i ] ) ) break ; } }

Do nothing if date format is not supported


protected boolean setDateTime(String date, String pattern) {
        boolean dateChanged = true;
        dateFormat.applyPattern(pattern);
        try {
            setDateTime(dateFormat.parse(date));
        } catch (ParseException e) {
            dateChanged = false;
        }
        return dateChanged;
    }

protected boolean setDateTime ( String date , String pattern ) { boolean dateChanged = true ; dateFormat . applyPattern ( pattern ) ; try { setDateTime ( dateFormat . parse ( date ) ) ; } catch ( ParseException e ) { dateChanged = false ; } return dateChanged ; }

Do nothing if date format is not supported.

Do nothing if date format is not supported .


public static IStatus error(final String message, final Throwable thr) {
		return new Status(IStatus.ERROR, PLUGIN_ID, 0,	message, thr);
	}

public static IStatus error ( final String message , final Throwable thr ) { return new Status ( IStatus . ERROR , PLUGIN_ID , 0 , message , thr ) ; }

Utility to create an error status for this plug-in.

@param message User comprehensible message
@param thr cause
@return an initialized error status

Utility to create an error status for this plug - in .


public static void logError(final String message, final Throwable thr) {
		getDefault().getLog().log(error(message, thr));
	}

public static void logError ( final String message , final Throwable thr ) { getDefault ( ) . getLog ( ) . log ( error ( message , thr ) ) ; }

Utility method to log errors in the Egit plugin.
@param message User comprehensible message
@param thr The exception through which we noticed the error

Utility method to log errors in the Egit plugin .


protected void addField(FieldEditor editor) {
		if (fields == null) {
			fields = new ArrayList<FieldEditor>();
		}
		// Set the actual preference name based on the current selection
		// in the Kie Navigator tree view. The preference name is constructed
		// from the path to the selected tree node by getPreferenceName().
		String name = editor.getPreferenceName();
		editor.setPreferenceName(getPreferenceName(name));
		fields.add(editor);
	}

Adds the given field editor to this page.

@param editor the field editor

Adds the given field editor to this page .


protected void adjustGridLayout() {
		int numColumns = calcNumberOfColumns();
		((GridLayout) fieldEditorParent.getLayout()).numColumns = numColumns;
		if (fields != null) {
			for (int i = 0; i < fields.size(); i++) {
				FieldEditor fieldEditor = fields.get(i);
				fieldEditor.fillIntoGrid(fieldEditorParent, numColumns);
			}
		}
	}

protected void adjustGridLayout ( ) { int numColumns = calcNumberOfColumns ( ) ; ( ( GridLayout ) fieldEditorParent . getLayout ( ) ) . numColumns = numColumns ; if ( fields != null ) { for ( int i = 0 ; i < fields . size ( ) ; i ++ ) { FieldEditor fieldEditor = fields . get ( i ) ; fieldEditor . fillIntoGrid ( fieldEditorParent , numColumns ) ; } } }

Adjust the layout of the field editors so that they are properly aligned.

Adjust the layout of the field editors so that they are properly aligned .


protected void applyFont() {
		if (fields != null) {
			Iterator<FieldEditor> e = fields.iterator();
			while (e.hasNext()) {
				FieldEditor pe = e.next();
				// pe.applyFont();
			}
		}
	}

protected
void
applyFont
(
)
{
if
(
fields
!=
)
{
Iterator
<
FieldEditor
>
e
=
fields
.
iterator
(
)
;
while
(
e
.
hasNext
(
)
)
{
FieldEditor
pe
=
e
.
next
(
)
;
// pe.applyFont();
}
}
}

Applys the font to the field editors managed by this page.

Applys the font to the field editors managed by this page .


private int calcNumberOfColumns() {
		int result = 0;
		if (fields != null) {
			Iterator<FieldEditor> e = fields.iterator();
			while (e.hasNext()) {
				FieldEditor pe = e.next();
				result = Math.max(result, pe.getNumberOfControls());
			}
		}
		return result;
	}

private int calcNumberOfColumns ( ) { int result = 0 ; if ( fields != null ) { Iterator < FieldEditor > e = fields . iterator ( ) ; while ( e . hasNext ( ) ) { FieldEditor pe = e . next ( ) ; result = Math . max ( result , pe . getNumberOfControls ( ) ) ; } } return result ; }

Calculates the number of columns needed to host all field editors.

@return the number of columns

Calculates the number of columns needed to host all field editors .


protected void initialize() {
		if (fields != null) {
			Iterator<FieldEditor> e = fields.iterator();
			while (e.hasNext()) {
				FieldEditor pe = e.next();
				pe.setPage(this);
				pe.setPropertyChangeListener(this);
				pe.setPreferenceStore(getPreferenceStore());
				pe.load();
			}
		}
	}

protected void initialize ( ) { if ( fields != null ) { Iterator < FieldEditor > e = fields . iterator ( ) ; while ( e . hasNext ( ) ) { FieldEditor pe = e . next ( ) ; pe . setPage ( this ) ; pe . setPropertyChangeListener ( this ) ; pe . setPreferenceStore ( getPreferenceStore ( ) ) ; pe . load ( ) ; } } }


public void firePropertyChangeEvent(Object source, String name, Object oldValue, Object newValue) {
		PropertyChangeEvent event= new PropertyChangeEvent(source, name, oldValue, newValue);
		Object[] listeners= fListeners.getListeners();
		for (int i= 0; i < listeners.length; i++)
			((IPropertyChangeListener) listeners[i]).propertyChange(event);
	}

public void firePropertyChangeEvent ( Object source , String name , Object oldValue , Object newValue ) { PropertyChangeEvent event = new PropertyChangeEvent ( source , name , oldValue , newValue ) ; Object [ ] listeners = fListeners . getListeners ( ) ; for ( int i = 0 ; i < listeners . length ; i ++ ) ( ( IPropertyChangeListener ) listeners [ i ] ) . propertyChange ( event ) ; }

Fires a property change event with the given source, property name, old and new value. Used
when the event source should be different from this mockup preference store.
@param source The event source
@param name The property name
@param oldValue The property's old value
@param newValue The property's new value

Fires a property change event with the given source property name old and new value . Used when the event source should be different from this mockup preference store .


public void setActiveEditor(IEditorPart part) {
        super.setActiveEditor( part );
        if ( part instanceof DRLRuleEditor2 ) {
            DRLRuleEditor2 p = (DRLRuleEditor2) part;
            p.setZoomComboContributionItem( zitem );
            p.setZoomInAction( zoomIn );
            p.setZoomOutAction( zoomOut );
        }
    }

public void setActiveEditor ( IEditorPart part ) { super . setActiveEditor ( part ) ; if ( part instanceof DRLRuleEditor2 ) { DRLRuleEditor2 p = ( DRLRuleEditor2 ) part ; p . setZoomComboContributionItem ( zitem ) ; p . setZoomInAction ( zoomIn ) ; p . setZoomOutAction ( zoomOut ) ; } }

In addition to @link org.eclipse.ui.part.MultiPageEditorActionBarContributor#setActiveEditor(org.eclipse.ui.IEditorPart)
it sets contribution items to DRLRuleEditor2 for later use when
multipageditor tabs are switched.


public void contributeToToolBar(IToolBarManager toolBarManager) {
        super.contributeToToolBar( toolBarManager );
        toolBarManager.add( new Separator() );
        String[] zoomStrings = new String[]{ZoomManager.FIT_ALL, ZoomManager.FIT_HEIGHT, ZoomManager.FIT_WIDTH};

        zitem = new ZoomComboContributionItem( getPage(),
                                               zoomStrings );
        zitem.setZoomManager( null );
        zitem.setVisible( false );

        zoomIn = new ZoomInAction2();
        zoomIn.setEnabled( false );

        zoomOut = new ZoomOutAction2();
        zoomOut.setEnabled( false );

        toolBarManager.add( zitem );
        toolBarManager.add( zoomIn );
        toolBarManager.add( zoomOut );

    }

public void contributeToToolBar ( IToolBarManager toolBarManager ) { super . contributeToToolBar ( toolBarManager ) ; toolBarManager . add ( new Separator ( ) ) ; String [ ] zoomStrings = new String [ ] { ZoomManager . FIT_ALL , ZoomManager . FIT_HEIGHT , ZoomManager . FIT_WIDTH } ; zitem = new ZoomComboContributionItem ( getPage ( ) , zoomStrings ) ; zitem . setZoomManager ( null ) ; zitem . setVisible ( false ) ; zoomIn = new ZoomInAction2 ( ) ; zoomIn . setEnabled ( false ) ; zoomOut = new ZoomOutAction2 ( ) ; zoomOut . setEnabled ( false ) ; toolBarManager . add ( zitem ) ; toolBarManager . add ( zoomIn ) ; toolBarManager . add ( zoomOut ) ; }

Adds Zoom-related contributions.

@see org.eclipse.ui.part.EditorActionBarContributor#contributeToToolBar(org.eclipse.jface.action.IToolBarManager)


private void determineDialect(String backText) {
        dialect = null;
        boolean mvel = MVEL_DIALECT_PATTERN.matcher(backText).matches();
        boolean java = JAVA_DIALECT_PATTERN.matcher(backText).matches();
        if (mvel) {
            dialect = MVEL_DIALECT;
        } else if (java) {
            dialect = JAVA_DIALECT;
        }
    }

private void determineDialect ( String backText ) { dialect = null ; boolean mvel = MVEL_DIALECT_PATTERN . matcher ( backText ) . matches ( ) ; boolean java = JAVA_DIALECT_PATTERN . matcher ( backText ) . matches ( ) ; if ( mvel ) { dialect = MVEL_DIALECT ; } else if ( java ) { dialect = JAVA_DIALECT ; } }

especially when parsing incomplete rules


protected IContext newContext(IContext userContext, ILocator locator) throws MalformedURLException {
        Assert.isNotNull(userContext);
        Assert.isNotNull(locator);
        IContext context = davFactory.newContext(userContext);
        if (locator.getLabel() != null)
            context.setLabel(locator.getLabel());
        return context;
    }

protected IContext newContext ( IContext userContext , ILocator locator ) throws MalformedURLException { Assert . isNotNull ( userContext ) ; Assert . isNotNull ( locator ) ; IContext context = davFactory . newContext ( userContext ) ; if ( locator . getLabel ( ) != null ) context . setLabel ( locator . getLabel ( ) ) ; return context ; }

Returns a new context that is based on the given context.

@param userContext
@param locator

@return a new context that is based on the given context

Returns a new context that is based on the given context .


public void doSave(IProgressMonitor monitor) {

        FileEditorInput input = (FileEditorInput) getEditorInput();
        File outputFile = input.getFile().getLocation().toFile();
        saveFile( monitor,
                  outputFile,
                  input );

    }

public void doSave ( IProgressMonitor monitor ) { FileEditorInput input = ( FileEditorInput ) getEditorInput ( ) ; File outputFile = input . getFile ( ) . getLocation ( ) . toFile ( ) ; saveFile ( monitor , outputFile , input ) ; }


private void createTableListeners() {

        //setup views into current selected
        table.addSelectionListener( new SelectionListener() {

            public void widgetSelected(SelectionEvent e) {
                populate();
            }

            public void widgetDefaultSelected(SelectionEvent e) {
                populate();
            }

            private void populate() {
                DSLMappingEntry selected = getCurrentSelected();
                exprText.setText( selected.getMappingKey() );
                mappingText.setText( selected.getMappingValue() );
                objText.setText( selected.getMetaData().getMetaData() == null ? "" : selected.getMetaData().getMetaData() );
            }

        } );

        //double click support
        table.addMouseListener( new MouseListener() {

            public void mouseDoubleClick(MouseEvent e) {
                showEditPopup();
            }

            public void mouseDown(MouseEvent e) {
            }

            public void mouseUp(MouseEvent e) {
            }

        } );

    }

private
void
createTableListeners
(
)
{
//setup views into current selected
table
.
addSelectionListener
(
new
SelectionListener
(
)
{
public
void
widgetSelected
(
SelectionEvent
e
)
{
populate
(
)
;
}
public
void
widgetDefaultSelected
(
SelectionEvent
e
)
{
populate
(
)
;
}
private
void
populate
(
)
{
DSLMappingEntry
selected
=
getCurrentSelected
(
)
;
exprText
.
setText
(
selected
.
getMappingKey
(
)
)
;
mappingText
.
setText
(
selected
.
getMappingValue
(
)
)
;
objText
.
setText
(
selected
.
getMetaData
(
)
.
getMetaData
(
)
==
""
:
selected
.
getMetaData
(
)
.
getMetaData
(
)
)
;
}
}
)
;
//double click support
table
.
addMouseListener
(
new
MouseListener
(
)
{
public
void
mouseDoubleClick
(
MouseEvent
e
)
{
showEditPopup
(
)
;
}
public
void
mouseDown
(
MouseEvent
e
)
{
}
public
void
mouseUp
(
MouseEvent
e
)
{
}
}
)
;
}


private void createTable(Composite parent) {
        int style = SWT.MULTI | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.HIDE_SELECTION;

        table = new Table( parent,
                           style );

        GridData gridData = new GridData( GridData.FILL_BOTH );
        gridData.grabExcessVerticalSpace = true;
        gridData.horizontalSpan = 3;
        table.setLayoutData( gridData );

        table.setLinesVisible( true );
        table.setHeaderVisible( true );

        TableColumn column;

        //Expression col
        column = new TableColumn( table,
                                  SWT.LEFT,
                                  0 );
        column.setText( "Language Expression" );
        column.setWidth( 350 );
        // Add listener to column so sorted when clicked
        column.addSelectionListener( new SelectionAdapter() {

            public void widgetSelected(SelectionEvent e) {
                tableViewer.setSorter( new DSLMappingSorter( DSLMappingSorter.EXPRESSION ) );
            }
        } );

        // 3rd column with task Owner
        column = new TableColumn( table,
                                  SWT.LEFT,
                                  1 );
        column.setText( "Rule Language Mapping" );
        column.setWidth( 200 );
        // Add listener to column so sorted when clicked
        column.addSelectionListener( new SelectionAdapter() {

            public void widgetSelected(SelectionEvent e) {
                tableViewer.setSorter( new DSLMappingSorter( DSLMappingSorter.MAPPING ) );
            }
        } );

        // 4th column with task PercentComplete
        column = new TableColumn( table,
                                  SWT.LEFT,
                                  2 );
        column.setText( "Object" );
        column.setWidth( 80 );

        // 5th column with task PercentComplete
        column = new TableColumn( table,
                                  SWT.LEFT,
                                  3 );
        column.setText( "Scope" );
        column.setWidth( 80 );

        //  Add listener to column so tasks are sorted when clicked
        column.addSelectionListener( new SelectionAdapter() {

            public void widgetSelected(SelectionEvent e) {
                tableViewer.setSorter( new DSLMappingSorter( DSLMappingSorter.SCOPE ) );
            }
        } );

    }


public void put(String url, Object value) throws MalformedURLException {
        Assert.isNotNull(url);
        Assert.isNotNull(value);
        put(new URL(url), value);
    }

public void put ( String url , Object value ) throws MalformedURLException { Assert . isNotNull ( url ) ; Assert . isNotNull ( value ) ; put ( new URL ( url ) , value ) ; }

Maps the given URL to the given value in this table.

@param url   a URL as a String
@param value an object
@throws      MalformedURLException if the given URL is malformed

Maps the given URL to the given value in this table .


private void put(URLKey url, Object value) {
        Assert.isNotNull(url);
        Assert.isNotNull(value);
        // Remove the old entry so the url key is replaced
        if (table.get(url) != null)
            table.remove(url);
        table.put(url, value);
    }

Maps the specified URL to the given value in this table.

@param url   a URLKey
@param value an object

Maps the specified URL to the given value in this table .


public Node addToken(String token) {
        Node newnode = new Node(token);
        // set the depth first
        newnode.setDepth(depth + 1);
        // add the node as a child
        newnode = addChild(newnode);
        return newnode;
    }

public
Node
addToken
(
String
token
)
{
Node
newnode
=
new
Node
(
token
)
;
// set the depth first
newnode
.
setDepth
(
depth
+
1
)
;
// add the node as a child
newnode
=
addChild
(
newnode
)
;
return
newnode
;
}

The method will create a new Node instance and try to add it as
a child node. If an Node with the same string token exists, the
method will return the existing node instead.
@param token
@return

The method will create a new Node instance and try to add it as a child node . If an Node with the same string token exists the method will return the existing node instead .


public Node addChild(Node n) {
        if (!this.children.containsKey(n.getToken())) {
            this.children.put(n.getToken(),n);
            n.setParent(this);
            return n;
        } else {
            return (Node)this.children.get(n.getToken());
        }
    }

public Node addChild ( Node n ) { if ( ! this . children . containsKey ( n . getToken ( ) ) ) { this . children . put ( n . getToken ( ) , n ) ; n . setParent ( this ) ; return n ; } else { return ( Node ) this . children . get ( n . getToken ( ) ) ; } }

The method will check to see if a Node with the same string token
already exists. If it doesn't, it will add the token as a child and
return the same node.

On the otherhand, if there is an existing Node for the same string
token, the method returns the existing Node instance.
@param n
@return

The method will check to see if a Node with the same string token already exists . If it doesn t it will add the token as a child and return the same node .


void setFile(IFile file, int offset, int length) {
        this.file = file;
        this.offset = offset;
        this.length = length;
    }

void setFile ( IFile file , int offset , int length ) { this . file = file ; this . offset = offset ; this . length = length ; }

be used directly.  Use DroolsModelBuilder instead.

be used directly . Use DroolsModelBuilder instead .


public void addCondition(Condition condition) throws WebDAVException {
        // a Resource URI can only be specified once in a Precondition
        Enumeration conditions = getConditions();
        if (condition.getResourceURI() != null) {
            while (conditions.hasMoreElements()) {
                Condition existingCondition = (Condition) conditions.nextElement();
                if (existingCondition.getResourceURI() != null && existingCondition.getResourceURI().equals(condition.getResourceURI()))
                    throw new WebDAVException(IResponse.SC_BAD_REQUEST, Policy.bind("error.parseMultipleSpecification", condition.getResourceURI())); //$NON-NLS-1$
            }
        }
        this.conditions.addElement(condition);
    }

Add a Condition to this Precondition. Conditions are OR'd together to
check for a matching resource.

@param condition the Condition to add
@exception WebDAVException thrown if the precondition already contains this condition

Add a Condition to this Precondition . Conditions are OR d together to check for a matching resource .


public void addStateTokenCondition(String resourceURI, String stateToken) throws WebDAVException {
        Condition condition = new Condition(resourceURI);
        ConditionTerm term = new ConditionTerm();
        term.addConditionFactor(new StateToken(stateToken));
        condition.addConditionTerm(term);
        addCondition(condition);
    }

public void addStateTokenCondition ( String resourceURI , String stateToken ) throws WebDAVException { Condition condition = new Condition ( resourceURI ) ; ConditionTerm term = new ConditionTerm ( ) ; term . addConditionFactor ( new StateToken ( stateToken ) ) ; condition . addConditionTerm ( term ) ; addCondition ( condition ) ; }

Add a condition created from the given URI and state token. This is a
convenience method used primarily to create preconditions for lock tokens
that must be provided in the resource context for methods that update
the resource.

@param resourceURI the URI of the resource the state token applies to. Null
implicitly specifies the resource processing the request
@param stateToken the state token to match

Add a condition created from the given URI and state token . This is a convenience method used primarily to create preconditions for lock tokens that must be provided in the resource context for methods that update the resource .


public boolean matches(Condition condition) {
        boolean match = false;
        Enumeration conditions = getConditions();
        while (!match && conditions.hasMoreElements()) {
            Condition existingCondition = (Condition) conditions.nextElement();
            match = existingCondition.matches(condition);
        }
        return match;
    }

public boolean matches ( Condition condition ) { boolean match = false ; Enumeration conditions = getConditions ( ) ; while ( ! match && conditions . hasMoreElements ( ) ) { Condition existingCondition = ( Condition ) conditions . nextElement ( ) ; match = existingCondition . matches ( condition ) ; } return match ; }

See if this Precondition contains a matching Condition.

@param condition the condition to match
@return true if this precondition contains atleast one condition matching the given condition

See if this Precondition contains a matching Condition .


public Prop getProp() throws MalformedElementException {
        Element prop = getFirstChild(root, "prop"); //$NON-NLS-1$
        ensureNotNull(Policy.bind("ensure.missingPropElmt"), prop); //$NON-NLS-1$
        return new Prop(prop);
    }

public Prop getProp ( ) throws MalformedElementException { Element prop = getFirstChild ( root , "prop" ) ; //$NON-NLS-1$ ensureNotNull ( Policy . bind ( "ensure.missingPropElmt" ) , prop ) ; //$NON-NLS-1$ return new Prop ( prop ) ; }

Returns this propstat's prop.

@return this propstat's prop
@throws MalformedElementException if there is reason to believe that
this editor's underlying element is not well formed


public String getStatus() throws MalformedElementException {
        String status = getChildText(root, "status", false); //$NON-NLS-1$
        ensureNotNull(Policy.bind("ensure.missingStatusElmt"), status); //$NON-NLS-1$
        return status;
    }

public String getStatus ( ) throws MalformedElementException { String status = getChildText ( root , "status" , false ) ; //$NON-NLS-1$ ensureNotNull ( Policy . bind ( "ensure.missingStatusElmt" ) , status ) ; //$NON-NLS-1$ return status ; }

Returns this propstat's status.

@return this propstat's status
@throws MalformedElementException if there is reason to believe that
this editor's underlying element is not well formed


public Prop setProp() {
        Element prop = setChild(root, "prop", childNames, true); //$NON-NLS-1$
        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
(
)
{
Element
prop
=
setChild
(
root
,
"prop"
,
childNames
,
true
)
;
//$NON-NLS-1$
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 propstat and returns an editor on
it.

@return an editor on a new prop element

Creates and sets a new prop on this propstat and returns an editor on it .


public String getLastLine(String backText) {
        BufferedReader breader = new BufferedReader(new StringReader(backText));
        String last = "";
        String line = null;
        try {
            while ((line = breader.readLine()) != null) {
                // only if the line has text do we set last to it
                if (line.length() > 0) {
                    last = line;
                }
            }
        } catch (IOException e) {
            DroolsEclipsePlugin.log(e);
        }
        // now that all the conditions for a single object are on the same line
        // we need to check for the left parenthesis
        if (last.indexOf("(") > -1) {
            last = last.substring(last.lastIndexOf("(") + 1);
        }
        // if the string has a comma "," we get the substring starting from
        // the index after the last comma
        if (last.indexOf(",") > -1) {
            last = last.substring(last.lastIndexOf(",") + 1);
        }
        // if the line ends with right parenthesis, we change it to zero length
        // string
        if (last.endsWith(")")) {
            last = "";
        }
        return last;
    }

because of how the backText works, we need to get the last line, so that
we can pass it to the DSLUtility

@param backText
@return

because of how the backText works we need to get the last line so that we can pass it to the DSLUtility


public String getLastNonDashLine(String backText) {
        BufferedReader breader = new BufferedReader(new StringReader(backText));
        String last = "";
        String line = null;
        try {
            while ((line = breader.readLine()) != null) {
                // there may be blank lines, so we trim first
                line = line.trim();
                // only if the line has text do we set last to it
                if (line.length() > 0 && !line.startsWith("-")) {
                    last = line;
                }
            }
        } catch (IOException e) {
            DroolsEclipsePlugin.log(e);
        }
        if (last.indexOf("(") > -1 && !last.endsWith(")")) {
            last = last.substring(0, last.indexOf("("));
        } else if (last.indexOf("(") > -1 && last.endsWith(")")) {
            last = "";
        }
        return last;
    }

Returns the last line that doesn't start with a dash

@param backText
@return

Returns the last line that doesn t start with a dash


public static String bind(String id, String binding) {
        return bind(id, new String[] {binding});
    }

public static String bind ( String id , String binding ) { return bind ( id , new String [ ] { binding } ) ; }

Lookup the message with the given ID in this catalog and bind its
substitution locations with the given string.

Lookup the message with the given ID in this catalog and bind its substitution locations with the given string .


public static String bind(String id, String binding1, String binding2) {
        return bind(id, new String[] {binding1, binding2});
    }

public static String bind ( String id , String binding1 , String binding2 ) { return bind ( id , new String [ ] { binding1 , binding2 } ) ; }

Lookup the message with the given ID in this catalog and bind its
substitution locations with the given strings.

Lookup the message with the given ID in this catalog and bind its substitution locations with the given strings .


public static String bind(String id, String[] bindings) {
        if (id == null)
            return "No message available";//$NON-NLS-1$
        String message = null;
        try {
            message = bundle.getString(id);
        } catch (MissingResourceException e) {
            // If we got an exception looking for the message, fail gracefully by just returning
            // the id we were looking for.  In most cases this is semi-informative so is not too bad.
            return "Missing message: " + id + "in: " + bundleName;//$NON-NLS-1$ //$NON-NLS-2$
        }
        if (bindings == null)
            return message;
        return MessageFormat.format(message, bindings);
    }

Lookup the message with the given ID in this catalog and bind its
substitution locations with the given string values.

Lookup the message with the given ID in this catalog and bind its substitution locations with the given string values .


private void createProcess(IJavaProject project, IProgressMonitor monitor, String exampleType)
			throws CoreException, IOException {
		// create the process (sample.bpmn) file
		String fileName = "org/jbpm/eclipse/wizard/project/" + exampleType + ".bpmn.template";
		IFolder folder = null;
		folder = project.getProject().getFolder("src/main/resources/com/sample");
		FileUtils.createFolder(folder, monitor);
		IFile file = folder.getFile("sample.bpmn");
		InputStream inputstream = getClass().getClassLoader().getResourceAsStream(fileName);
		if (!file.exists()) {
			file.create(inputstream, true, monitor);
		} else {
			file.setContents(inputstream, true, false, monitor);
		}

		// create a Java main class to invoke the process
		fileName = "org/jbpm/eclipse/wizard/project/ProcessMain-" + exampleType + ".java";
		IRuntime runtime = startPage.getRuntime();
		if (runtime.getVersion().getMajor() == 5) {
			fileName += ".v5.template";
		} else {
			fileName += ".template";
		}

		folder = project.getProject().getFolder("src/main/java");
		IPackageFragmentRoot packageFragmentRoot = project.getPackageFragmentRoot(folder);
		IPackageFragment packageFragment = packageFragmentRoot.createPackageFragment("com.sample", true, monitor);
		inputstream = getClass().getClassLoader().getResourceAsStream(fileName);
		packageFragment.createCompilationUnit("ProcessMain.java", new String(FileUtils.readStream(inputstream)), true,
				monitor);

		// create persistence.xml
		if (runtime.getVersion().getMajor() == 5) {
			if ("advanced".equals(exampleType)) {
	        	folder = project.getProject().getFolder("src/main/resources/META-INF");
	    		FileUtils.createFolder(folder, monitor);
	            inputstream = getClass().getClassLoader().getResourceAsStream(
	            	"org/jbpm/eclipse/wizard/project/ProcessLauncher-advanced-persistence.xml.template");
	            file = folder.getFile("persistence.xml");
	            if (!file.exists()) {
	                file.create(inputstream, true, monitor);
	            } else {
	                file.setContents(inputstream, true, false, monitor);
	            }
			}
		}
	}

Create the sample process file.
@throws IOException


private void createProcessSampleJUnit(IJavaProject project, String exampleType, IProgressMonitor monitor)
			throws JavaModelException, IOException {
		String s = "org/jbpm/eclipse/wizard/project/ProcessJUnit-" + exampleType + ".java";
		IRuntime runtime = startPage.getRuntime();
		if (runtime.getVersion().getMajor()==5) {
			s += ".v5.template";
		} else {
			s += ".template";
		}
		IFolder folder = project.getProject().getFolder("src/main/java");
        IPackageFragmentRoot packageFragmentRoot = project
                .getPackageFragmentRoot(folder);
        IPackageFragment packageFragment = packageFragmentRoot
                .createPackageFragment("com.sample", true, monitor);
        InputStream inputstream = getClass().getClassLoader()
                .getResourceAsStream(s);
        packageFragment.createCompilationUnit("ProcessTest.java", new String(
                FileUtils.readStream(inputstream)), true, monitor);
	}

Create the sample process junit test file.

Create the sample process junit test file .


@Override
	public String getRuntimeId() {
		IPreferenceStore store = org.kie.eclipse.Activator.getDefault().getPreferenceStore();
		String value = store.getString(getKieVersionPreferenceKey());
		return value;
	}

@ Override public String getRuntimeId ( ) { IPreferenceStore store = org . kie . eclipse . Activator . getDefault ( ) . getPreferenceStore ( ) ; String value = store . getString ( getKieVersionPreferenceKey ( ) ) ; return value ; }

Return the version number of the KIE Workbench that is installed on the
given server. If the server is not running or not responsive, use a value
from the Preference Store.

@param server
@return

Return the version number of the KIE Workbench that is installed on the given server . If the server is not running or not responsive use a value from the Preference Store .


public void visitRete(final Rete rete) {
        this.rootVertex = (ReteVertex) this.visitedNodes.get( dotId( rete ) );
        if ( this.rootVertex == null ) {
            this.rootVertex = new ReteVertex( rete );
            this.visitedNodes.put( dotId( rete ),
                                   this.rootVertex );
        }

        this.graph.addChild( this.rootVertex );
        this.parentVertex = this.rootVertex;

        for( EntryPointNode node : rete.getEntryPointNodes().values() ) {
            visit( node );
        }
    }

public void visitRete ( final Rete rete ) { this . rootVertex = ( ReteVertex ) this . visitedNodes . get ( dotId ( rete ) ) ; if ( this . rootVertex == null ) { this . rootVertex = new ReteVertex ( rete ) ; this . visitedNodes . put ( dotId ( rete ) , this . rootVertex ) ; } this . graph . addChild ( this . rootVertex ) ; this . parentVertex = this . rootVertex ; for ( EntryPointNode node : rete . getEntryPointNodes ( ) . values ( ) ) { visit ( node ) ; } }

Rete visits each of its ObjectTypeNodes.

Rete visits each of its ObjectTypeNodes .


private void visitNode(final Object node) {
        Object realNode = node;
        if ( node instanceof ObjectHashMap.ObjectEntry ) {
            ObjectHashMap.ObjectEntry entry = (ObjectHashMap.ObjectEntry) node;
            realNode = entry.getValue();
        }
        visit( realNode );
    }

private void visitNode ( final Object node ) { Object realNode = node ; if ( node instanceof ObjectHashMap . ObjectEntry ) { ObjectHashMap . ObjectEntry entry = ( ObjectHashMap . ObjectEntry ) node ; realNode = entry . getValue ( ) ; } visit ( realNode ) ; }

Helper method to ensure nodes are not visited more than once.

Helper method to ensure nodes are not visited more than once .


private static String dotId(final Object object) {
        return Integer.toHexString( System.identityHashCode( object ) ).toUpperCase();
    }

private static String dotId ( final Object object ) { return Integer . toHexString ( System . identityHashCode ( object ) ) . toUpperCase ( ) ; }

The identity hashCode for the given object is used as its unique DOT
identifier.

The identity hashCode for the given object is used as its unique DOT identifier .


public Prop addRemove() {
        Element remove = appendChild(root, "remove"); //$NON-NLS-1$
        Element prop = appendChild(remove, "prop"); //$NON-NLS-1$
        Prop result = null;
        try {
            result = new Prop(prop);
        } catch (MalformedElementException e) {
            Assert.isTrue(false, Policy.bind("assert.internalError")); //$NON-NLS-1$
        }
        return result;
    }

public Prop addRemove ( ) { Element remove = appendChild ( root , "remove" ) ; //$NON-NLS-1$ Element prop = appendChild ( remove , "prop" ) ; //$NON-NLS-1$ Prop result = null ; try { result = new Prop ( prop ) ; } catch ( MalformedElementException e ) { Assert . isTrue ( false , Policy . bind ( "assert.internalError" ) ) ; //$NON-NLS-1$ } return result ; }

Adds a remove to the given propertyupdate and returns an editor on
its prop.

@return an editor on a new prop

Adds a remove to the given propertyupdate and returns an editor on its prop .


public Prop addSet() {
        Element set = appendChild(root, "set"); //$NON-NLS-1$
        Element prop = appendChild(set, "prop"); //$NON-NLS-1$
        try {
            return new Prop(prop);
        } catch (MalformedElementException e) {
            Assert.isTrue(false, Policy.bind("assert.internalError")); //$NON-NLS-1$
            return null; // Never reached.
        }
    }

public
Prop
addSet
(
)
{
Element
set
=
appendChild
(
root
,
"set"
)
;
//$NON-NLS-1$
Element
prop
=
appendChild
(
set
,
"prop"
)
;
//$NON-NLS-1$
try
{
return
new
Prop
(
prop
)
;
}
catch
(
MalformedElementException
e
)
{
Assert
.
isTrue
(
false
,
Policy
.
bind
(
"assert.internalError"
)
)
;
//$NON-NLS-1$
return
;
// Never reached.
}
}

Adds a set to the given propertyupdate and returns an editor on its
prop.

@return an editor on a new prop

Adds a set to the given propertyupdate and returns an editor on its prop .


public ILocator newLocator(String resourceURL, String label) {
        return locatorFactory.newLocator(resourceURL, label);
    }

public ILocator newLocator ( String resourceURL , String label ) { return locatorFactory . newLocator ( resourceURL , label ) ; }

Answer a new resource locator that identifies a particular
server resource by it's URL and label.

@param resourceURL the URL of the resource.
@param label the version label of the resource.
@return the Locator to the resource.

Answer a new resource locator that identifies a particular server resource by it s URL and label .


public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) {
        PresentationReconciler reconciler = new PresentationReconciler();

        //bucket partition... (everything else outside a rule)
        DefaultDamagerRepairer dr = new DefaultDamagerRepairer(getScanner());
        reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
        reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);

        //inside a rule partition
        dr = new DefaultDamagerRepairer(getScanner());
        reconciler.setDamager(dr, DRLPartionScanner.RULE_PART_CONTENT);
        reconciler.setRepairer(dr, DRLPartionScanner.RULE_PART_CONTENT);

        //finally, inside a multi line comment.
        dr = new DefaultDamagerRepairer(new SingleTokenScanner(
                new TextAttribute(ColorManager.getInstance().getColor(
                        ColorManager.SINGLE_LINE_COMMENT))));
        reconciler.setDamager(dr, DRLPartionScanner.RULE_COMMENT);
        reconciler.setRepairer(dr, DRLPartionScanner.RULE_COMMENT);

        return reconciler;
    }

Define reconciler - this has to be done for each partition.
Currently there are 3 partitions, Inside rule, outside rule and inside comment.

Define reconciler - this has to be done for each partition . Currently there are 3 partitions Inside rule outside rule and inside comment .


public boolean sameAs(Object obj) {
        if (obj == null || !(obj instanceof Status))
            return false;
        Status other = (Status) obj;
        if (other.code != code || !other.message.equals(message))
            return false;
        return other.extendedStatus.equals(extendedStatus);
    }

public boolean sameAs ( Object obj ) { if ( obj == null || ! ( obj instanceof Status ) ) return false ; Status other = ( Status ) obj ; if ( other . code != code || ! other . message . equals ( message ) ) return false ; return other . extendedStatus . equals ( extendedStatus ) ; }

Answers whether the receiver and the argument are considered
identical.  To be identical, the receiver and the argument
must have the same status code, message, and extended status
information.

@param obj other object with which to test.
@return boolean indicating whether they are the same or not.
@see Status#equals(Object)

Answers whether the receiver and the argument are considered identical . To be identical the receiver and the argument must have the same status code message and extended status information .


public boolean contains(ConditionTerm term) {
        // iterate through the factors looking for a match
        boolean match = false;
        Enumeration terms = getConditionTerms();
        while (!match && terms.hasMoreElements()) {
            ConditionTerm t = (ConditionTerm) terms.nextElement();
            match = term.matches(t);
        }
        return match;
    }

Does this Condition contain the given ConditionTerm?

@param term the term to check for
@return true if the condition contains the given term, false otherwise


public static ConditionFactor create(StreamTokenizer tokenizer) throws WebDAVException {
        StateToken stateToken = new StateToken();
        try {
            int token = tokenizer.ttype;
            if (token == '<')
                token = tokenizer.nextToken();
            else
                throw new WebDAVException(IResponse.SC_BAD_REQUEST, Policy.bind("error.parseMissing", String.valueOf(token), "<")); //$NON-NLS-1$ //$NON-NLS-2$

            if (token == StreamTokenizer.TT_WORD) {
                stateToken.setURI(tokenizer.sval);
                token = tokenizer.nextToken();
            } else
                throw new WebDAVException(IResponse.SC_BAD_REQUEST, Policy.bind("error.parseMissingURI", String.valueOf(token))); //$NON-NLS-1$

            if (token == '>')
                token = tokenizer.nextToken();
            else
                throw new WebDAVException(IResponse.SC_BAD_REQUEST, Policy.bind("error.parseMissing", String.valueOf(token), ">")); //$NON-NLS-1$ //$NON-NLS-2$
        } catch (IOException exc) {
            // ignore or log?
        }
        return stateToken;
    }

public
static
ConditionFactor
create
(
StreamTokenizer
tokenizer
)
throws
WebDAVException
{
StateToken
stateToken
=
new
StateToken
(
)
;
try
{
int
token
=
tokenizer
.
ttype
;
if
(
token
==
'
'
)
token
=
tokenizer
.
nextToken
(
)
;
else
throw
new
WebDAVException
(
IResponse
.
SC_BAD_REQUEST
,
Policy
.
bind
(
"error.parseMissing"
,
String
.
valueOf
(
token
)
,
"<"
)
)
;
//$NON-NLS-1$ //$NON-NLS-2$
if
(
token
==
StreamTokenizer
.
TT_WORD
)
{
stateToken
.
setURI
(
tokenizer
.
sval
)
;
token
=
tokenizer
.
nextToken
(
)
;
}
else
throw
new
WebDAVException
(
IResponse
.
SC_BAD_REQUEST
,
Policy
.
bind
(
"error.parseMissingURI"
,
String
.
valueOf
(
token
)
)
)
;
//$NON-NLS-1$
if
(
token
==
'
'
)
token
=
tokenizer
.
nextToken
(
)
;
else
throw
new
WebDAVException
(
IResponse
.
SC_BAD_REQUEST
,
Policy
.
bind
(
"error.parseMissing"
,
String
.
valueOf
(
token
)
,
">"
)
)
;
//$NON-NLS-1$ //$NON-NLS-2$
}
catch
(
IOException
exc
)
{
// ignore or log?
}
return
stateToken
;
}

Create a StateToken by parsing the given If header as defined by
section 9.4 in the WebDAV spec.

@param tokenizer a StreamTokenizer on the contents of a WebDAV If header
@return the parsed ConditionFactor (StateToken)

Create a StateToken by parsing the given If header as defined by section 9 . 4 in the WebDAV spec .


protected void addPages() {
        try {
            textEditor = new DRLRuleEditor() {
                public void close(boolean save) {
                    super.close( save );
                    DRLRuleEditor2.this.close( save );
                }

                protected void setPartName(String partName) {
                    super.setPartName( partName );
                    DRLRuleEditor2.this.setPartName( partName );
                }
            };

            reteViewer = new ReteViewer(textEditor);

            int text = addPage( textEditor,
                                getEditorInput() );

            int rete = addPage( reteViewer,
                                getEditorInput() );

            setPageText( text,
                         "Text Editor" );
            setPageText( rete,
                         "Rete Tree" );

            textEditor.getDocumentProvider().getDocument( getEditorInput() ).addDocumentListener( new IDocumentListener() {

                public void documentAboutToBeChanged(DocumentEvent event) {
                }

                public void documentChanged(DocumentEvent event) {
                    reteViewer.fireDocumentChanged();
                }

            } );

        } catch ( PartInitException e ) {
            DroolsEclipsePlugin.log( e );
        }
    }

protected
void
addPages
(
)
{
try
{
textEditor
=
new
DRLRuleEditor
(
)
{
public
void
close
(
boolean
save
)
{
super
.
close
(
save
)
;
DRLRuleEditor2
.
this
.
close
(
save
)
;
}
protected
void
setPartName
(
String
partName
)
{
super
.
setPartName
(
partName
)
;
DRLRuleEditor2
.
this
.
setPartName
(
partName
)
;
}
}
;
reteViewer
=
new
ReteViewer
(
textEditor
)
;
int
text
=
addPage
(
textEditor
,
getEditorInput
(
)
)
;
int
rete
=
addPage
(
reteViewer
,
getEditorInput
(
)
)
;
setPageText
(
text
,
"Text Editor"
)
;
setPageText
(
rete
,
"Rete Tree"
)
;
textEditor
.
getDocumentProvider
(
)
.
getDocument
(
getEditorInput
(
)
)
.
addDocumentListener
(
new
IDocumentListener
(
)
{
public
void
documentAboutToBeChanged
(
DocumentEvent
event
)
{
}
public
void
documentChanged
(
DocumentEvent
event
)
{
reteViewer
.
fireDocumentChanged
(
)
;
}
}
)
;
}
catch
(
PartInitException
e
)
{
DroolsEclipsePlugin
.
log
(
e
)
;
}
}

Adds Text Editor for rules and Rete graph viewer

@see org.eclipse.ui.forms.editor.FormEditor#addPages()


protected String httpDelete(String request) throws IOException {
		String host = getKieRESTUrl();
		URL url = new URL(host + "/" + request);
		Activator.println("[DELETE] "+url.toString());
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("DELETE");
		conn.setRequestProperty("Content", "application/json");
		setHttpCredentials(conn);
		String response = new BufferedReader(new InputStreamReader((conn.getInputStream()))).readLine();
		Activator.println("[DELETE] response: "+response);

		if (conn.getResponseCode() != HttpURLConnection.HTTP_ACCEPTED) {
			throw new IOException("HTTP DELETE failed : HTTP error code : " + conn.getResponseCode());
		}

		JsonObject jo = JsonObject.readFrom(response);
		String status = jo.get("status").asString();
		if (status != null && !status.isEmpty()) {
			if (!"APPROVED".equals(status))
				throw new IOException("HTTP DELETE failed : Request status code : " + status);
		}
		String jobId = jo.get("jobId").asString();
		if (jobId != null && !jobId.isEmpty())
			return jobId;

		return response;
	}

Send an HTTP DELETE request to the KIE console.
@param request - the request URL fragment; see the Drools REST API
documentation for details
@return the Job ID. This can be used in calls to getJobStatus() to fetch
the completion status of the request.
@throws IOException

Send an HTTP DELETE request to the KIE console .


protected String httpPost(String request, JsonObject body) throws IOException, RuntimeException {
		String host = getKieRESTUrl();
		URL url = new URL(host + "/" + request);
		Activator.println("[POST] "+url.toString()+" body: "+body);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setDoOutput(body!=null);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", "application/json");
		setHttpCredentials(conn);

		if (body!=null) {
			java.io.OutputStream os = conn.getOutputStream();
			Writer writer = new OutputStreamWriter(os, "UTF-8");
			body.writeTo(writer);
			writer.close();
			os.flush();
		}

		String response = new BufferedReader(new InputStreamReader((conn.getInputStream()))).readLine();
		Activator.println("[POST] response: "+response);

		if (conn.getResponseCode() != HttpURLConnection.HTTP_ACCEPTED) {
			throw new IOException("HTTP POST failed : HTTP error code : " + conn.getResponseCode());
		}

		JsonObject jo = JsonObject.readFrom(response);
		String status = jo.get("status").asString();
		if (status != null && !status.isEmpty()) {
			if (!"APPROVED".equals(status))
				throw new IOException("HTTP POST failed : Request status code : " + status);
		}
		String jobId = jo.get("jobId").asString();
		if (jobId != null && !jobId.isEmpty())
			return jobId;

		return response;
	}

Send an HTTP POST request to the KIE console.

@param request - the request URL fragment; see the Drools REST API
documentation for details
@param body - the JSON object required by the request
@return the Job ID. This can be used in calls to getJobStatus() to fetch
the completion status of the request.
@throws IOException
@throws RuntimeException

Send an HTTP POST request to the KIE console .


public String getJobStatus(final String jobId, final String title) throws IOException, InterruptedException {
		final AtomicReference<String> ar = new AtomicReference<String>();

		IWorkbench wb = PlatformUI.getWorkbench();
		IProgressService ps = wb.getProgressService();
		try {
			ps.busyCursorWhile(new IRunnableWithProgress() {
				public void run(IProgressMonitor pm) throws InterruptedException {
					pm.beginTask("Waiting for Job "+jobId+":\n\n"+title, STATUS_REQUEST_TIMEOUT);
					pm.subTask(title);
					long startTime = System.currentTimeMillis();
					long stopTime = startTime;
					do {
						try {
							// send a Job Status request every STATUS_REQUEST_DELAY milliseconds
							Thread.sleep(STATUS_REQUEST_DELAY);
							String response = httpGet("jobs/" + jobId);
							JsonObject jo = JsonObject.readFrom(response);
							String status = jo.get("status").asString();
							String result = jo.get("result").asString();
							if ("null".equals(result)) {
								if (!"SUCCESS".equals(status))
									result = null;
							}
							if (status!=null && result!=null)
								ar.set(status + ":" + result);
							stopTime = System.currentTimeMillis();
							pm.worked(STATUS_REQUEST_DELAY);

							Activator.println("status="+status);
							Activator.println("result="+result);
						}
						catch (Exception e) {
							e.printStackTrace();
						}
						if (pm.isCanceled())
							throw new InterruptedException("Operation canceled");
					}
					while (ar.get()==null && stopTime - startTime < STATUS_REQUEST_TIMEOUT);
					pm.done();
					Activator.println(
							"\n----------------------------------\n"+
							"Job "+jobId+"\n"+title+"\ncompleted in "+(stopTime - startTime) / 1000.0+" sec\n"+
							"Status: " + ar.get()+
							"\n----------------------------------\n");
				}
			});
		}
		catch (InvocationTargetException e) {
			e.printStackTrace();
			return null;
		}

		return ar.get();
	}

Sends a job status request to the KIE Server.

@param jobId - the job ID from a previous HTTP POST or DELETE request
@return a string composed of a status word (e.g. "SUCCESS" or
"BAD_REQUEST") followed by a colon delimiter and a detailed
message.
@throws IOException

Sends a job status request to the KIE Server .


@SuppressWarnings("restriction")
	public void execute(IProgressMonitor monitor) {
		try {
			pullOperation.execute(monitor);
			results.putAll(pullOperation.getResults());
		}
		catch (CoreException e) {
			if (e.getStatus().getSeverity() == IStatus.CANCEL)
				results.putAll(pullOperation.getResults());
			else
				repoNode.handleException((Throwable) e);
		}
	}

@ SuppressWarnings ( "restriction" ) public void execute ( IProgressMonitor monitor ) { try { pullOperation . execute ( monitor ) ; results . putAll ( pullOperation . getResults ( ) ) ; } catch ( CoreException e ) { if ( e . getStatus ( ) . getSeverity ( ) == IStatus . CANCEL ) results . putAll ( pullOperation . getResults ( ) ) ; else repoNode . handleException ( ( Throwable ) e ) ; } }

Starts this operation synchronously.

@param monitor


private void handlePullResults(final Map<Repository, Object> resultsMap) {
		if (tasksToWaitFor.decrementAndGet() == 0 && !results.isEmpty())
			showResults();
	}

private void handlePullResults ( final Map < Repository , Object > resultsMap ) { if ( tasksToWaitFor . decrementAndGet ( ) == 0 && ! results . isEmpty ( ) ) showResults ( ) ; }

Post-process the pull results, allowing the user to deal with uncommitted
changes and re-pull if the initial pull failed because of these changes

@param resultsMap a copy of the initial pull results
@param shell

Post - process the pull results allowing the user to deal with uncommitted changes and re - pull if the initial pull failed because of these changes


public JsonArray set( int index, String value ) {
    values.set( index, valueOf( value ) );
    return this;
  }

public JsonArray set ( int index , String value ) { values . set ( index , valueOf ( value ) ) ; return this ; }

Replaces the element at the specified position in this array with the JSON representation of
the specified string.

@param index
the index of the array element to replace
@param value
the string to be stored at the specified array position
@return the array itself, to enable method chaining
@throws IndexOutOfBoundsException
if the index is out of range, i.e. index < 0 or
index >= size

Replaces the element at the specified position in this array with the JSON representation of the specified string .


public ActiveLock addActiveLock() {
        Element activelock = addChild(root, "activelock", childNames, false); //$NON-NLS-1$
        Element locktype = appendChild(activelock, "locktype"); //$NON-NLS-1$
        appendChild(locktype, "write"); //$NON-NLS-1$
        ActiveLock result = null;
        try {
            result = new ActiveLock(activelock);
        } catch (MalformedElementException e) {
            Assert.isTrue(false, Policy.bind("assert.internalError")); //$NON-NLS-1$
        }
        return result;
    }

public ActiveLock addActiveLock ( ) { Element activelock = addChild ( root , "activelock" , childNames , false ) ; //$NON-NLS-1$ Element locktype = appendChild ( activelock , "locktype" ) ; //$NON-NLS-1$ appendChild ( locktype , "write" ) ; //$NON-NLS-1$ ActiveLock result = null ; try { result = new ActiveLock ( activelock ) ; } catch ( MalformedElementException e ) { Assert . isTrue ( false , Policy . bind ( "assert.internalError" ) ) ; //$NON-NLS-1$ } return result ; }

Creates and adds a new activelock on this lockdiscovery and returns
an editor on it.

@return an editor on an activelock element

Creates and adds a new activelock on this lockdiscovery and returns an editor on it .


protected static void filterProposalsOnPrefix(String prefix, List<ICompletionProposal> props) {
        if ( prefix != null && prefix.trim().length() > 0 ) {
            Iterator<ICompletionProposal> iterator = props.iterator();
            String prefixLc = prefix.toLowerCase();
            while ( iterator.hasNext() ) {
                ICompletionProposal item = iterator.next();
                String content = item.getDisplayString().toLowerCase();
                if ( !content.toLowerCase().startsWith( prefixLc ) ) {
                    iterator.remove();
                }
            }
        }
    }

protected static void filterProposalsOnPrefix ( String prefix , List < ICompletionProposal > props ) { if ( prefix != null && prefix . trim ( ) . length ( ) > 0 ) { Iterator < ICompletionProposal > iterator = props . iterator ( ) ; String prefixLc = prefix . toLowerCase ( ) ; while ( iterator . hasNext ( ) ) { ICompletionProposal item = iterator . next ( ) ; String content = item . getDisplayString ( ) . toLowerCase ( ) ; if ( ! content . toLowerCase ( ) . startsWith ( prefixLc ) ) { iterator . remove ( ) ; } } } }

Filter out the proposals whose content does not start with the given prefix.

Filter out the proposals whose content does not start with the given prefix .


protected String readBackwards(int documentOffset, IDocument doc) throws BadLocationException {
        int startPart = doc.getPartition(documentOffset).getOffset();
        String prefix = doc.get(startPart, documentOffset - startPart);
        return prefix;
    }

protected String readBackwards ( int documentOffset , IDocument doc ) throws BadLocationException { int startPart = doc . getPartition ( documentOffset ) . getOffset ( ) ; String prefix = doc . get ( startPart , documentOffset - startPart ) ; return prefix ; }

Read some text from behind the cursor position.
This provides context to both filter what is shown based
on what the user has typed in, and also to provide more information for the
list of suggestions based on context.

Read some text from behind the cursor position . This provides context to both filter what is shown based on what the user has typed in and also to provide more information for the list of suggestions based on context .


public static RowList calculateReteRows(BaseVertex root) {
        RowList rowList = new RowList();

        rowList.add( 0,
                     root );

        int curRow = 0;

        final Set<BaseVertex> seenVertices = new HashSet<BaseVertex>();
        seenVertices.add( root );

        while ( curRow < rowList.getDepth() ) {
            final List<BaseVertex> rowVertices = rowList.get( curRow ).getVertices();

            for ( final Iterator<BaseVertex> rowNodeIter = rowVertices.iterator(); rowNodeIter.hasNext(); ) {
                final BaseVertex rowNode = rowNodeIter.next();

                final List<Connection> edges = rowNode.getSourceConnections();

                for ( final Iterator<Connection> edgeIter = edges.iterator(); edgeIter.hasNext(); ) {

                    final Connection edge = edgeIter.next();
                    final BaseVertex destNode = edge.getOpposite( rowNode );

                    if ( !seenVertices.contains( destNode ) ) {
                        rowList.add( curRow + 1,
                                     destNode );
                        seenVertices.add( destNode );
                    }
                }

                seenVertices.add( rowNode );
            }

            ++curRow;
        }

        rowList.optimize();

        return rowList;
    }

public static RowList calculateReteRows ( BaseVertex root ) { RowList rowList = new RowList ( ) ; rowList . add ( 0 , root ) ; int curRow = 0 ; final Set < BaseVertex > seenVertices = new HashSet < BaseVertex > ( ) ; seenVertices . add ( root ) ; while ( curRow < rowList . getDepth ( ) ) { final List < BaseVertex > rowVertices = rowList . get ( curRow ) . getVertices ( ) ; for ( final Iterator < BaseVertex > rowNodeIter = rowVertices . iterator ( ) ; rowNodeIter . hasNext ( ) ; ) { final BaseVertex rowNode = rowNodeIter . next ( ) ; final List < Connection > edges = rowNode . getSourceConnections ( ) ; for ( final Iterator < Connection > edgeIter = edges . iterator ( ) ; edgeIter . hasNext ( ) ; ) { final Connection edge = edgeIter . next ( ) ; final BaseVertex destNode = edge . getOpposite ( rowNode ) ; if ( ! seenVertices . contains ( destNode ) ) { rowList . add ( curRow + 1 , destNode ) ; seenVertices . add ( destNode ) ; } } seenVertices . add ( rowNode ) ; } ++ curRow ; } rowList . optimize ( ) ; return rowList ; }

Calculates layouting for provided graph.

@param root graph root vertex

@return Optimally layouted rows from provided graph

Calculates layouting for provided graph .


public void paint(Graphics g) {
        g.setAntialias( SWT.ON );
        Rectangle r = getBounds().getCopy();
        g.translate( r.getLocation() );
        g.setBackgroundColor( backgroundColor );
        g.setForegroundColor( borderColor );
        g.fillArc( 0,
                   0,
                   15,
                   15,
                   0,
                   360 );
        g.drawArc( 0,
                   0,
                   14,
                   14,
                   0,
                   360 );
        super.paint( g );
    }

public void paint ( Graphics g ) { g . setAntialias ( SWT . ON ) ; Rectangle r = getBounds ( ) . getCopy ( ) ; g . translate ( r . getLocation ( ) ) ; g . setBackgroundColor ( backgroundColor ) ; g . setForegroundColor ( borderColor ) ; g . fillArc ( 0 , 0 , 15 , 15 , 0 , 360 ) ; g . drawArc ( 0 , 0 , 14 , 14 , 0 , 360 ) ; super . paint ( g ) ; }


private EditPart getPartForElement(Object modelElement) {
        if ( modelElement instanceof ReteGraph ) {
            return new DiagramEditPart();
        }
        if ( modelElement instanceof BaseVertex ) {
            return new VertexEditPart();
        }
        if ( modelElement instanceof Connection ) {
            return new ConnectionEditPart();
        }
        DroolsEclipsePlugin.log( new Exception( "Can't create part for model element: " + ((modelElement != null) ? modelElement.getClass().getName() : "null") ) );
        return null;

    }

private
EditPart
getPartForElement
(
Object
modelElement
)
{
if
(
modelElement
instanceof
ReteGraph
)
{
return
new
DiagramEditPart
(
)
;
}
if
(
modelElement
instanceof
BaseVertex
)
{
return
new
VertexEditPart
(
)
;
}
if
(
modelElement
instanceof
Connection
)
{
return
new
ConnectionEditPart
(
)
;
}
DroolsEclipsePlugin
.
log
(
new
Exception
(
"Can't create part for model element: "
+
(
(
modelElement
!=
)
modelElement
.
getClass
(
)
.
getName
(
)
:
"null"
)
)
)
;
return
;
}

Maps object to EditPart.

@throws RuntimeException if no match was found


public static ImageDescriptor getImageDescriptor(String path) {
        JBPMEclipsePlugin plugin = getDefault();
        ImageRegistry reg = plugin.getImageRegistry();
        ImageDescriptor des = reg.getDescriptor(path);
        if (des == null) {
            des = AbstractUIPlugin.imageDescriptorFromPlugin("org.jbpm.eclipse", path);
            reg.put(path, des);
        }
        return des;
    }

public static ImageDescriptor getImageDescriptor ( String path ) { JBPMEclipsePlugin plugin = getDefault ( ) ; ImageRegistry reg = plugin . getImageRegistry ( ) ; ImageDescriptor des = reg . getDescriptor ( path ) ; if ( des == null ) { des = AbstractUIPlugin . imageDescriptorFromPlugin ( "org.jbpm.eclipse" , path ) ; reg . put ( path , des ) ; } return des ; }

Returns an image descriptor for the image file at the given
plug-in relative path.
Uses the plug ins image registry to "cache" it.

@param path the path
@return the image descriptor

Returns an image descriptor for the image file at the given plug - in relative path . Uses the plug ins image registry to cache it .


public final static void declareRegistryImage(String key, String path) {
        ImageDescriptor desc= ImageDescriptor.getMissingImageDescriptor();
        try {
            desc= ImageDescriptor.createFromURL(makeIconFileURL(path));
        } catch (MalformedURLException e) {
            DroolsEclipsePlugin.log(e);
        }
        imageRegistry.put(key, desc);
    }

public final static void declareRegistryImage ( String key , String path ) { ImageDescriptor desc = ImageDescriptor . getMissingImageDescriptor ( ) ; try { desc = ImageDescriptor . createFromURL ( makeIconFileURL ( path ) ) ; } catch ( MalformedURLException e ) { DroolsEclipsePlugin . log ( e ) ; } imageRegistry . put ( key , desc ) ; }

Declare an Image in the registry table.
@param key   The key to use when registering the image
@param path  The path where the image can be found. This path is relative to where
this plugin class is found (i.e. typically the packages directory)

Declare an Image in the registry table .


public void add(final int depth,
                    final BaseVertex vertex) {
        if ( this.rows.size() < (depth + 1) ) {
            final int addRows = depth - this.rows.size() + 1;

            for ( int i = 0; i < addRows; ++i ) {
                this.rows.add( new Row( (depth - addRows) + i ) );
            }
        }

        ((Row) this.rows.get( depth )).add( vertex );
    }

public void add ( final int depth , final BaseVertex vertex ) { if ( this . rows . size ( ) < ( depth + 1 ) ) { final int addRows = depth - this . rows . size ( ) + 1 ; for ( int i = 0 ; i < addRows ; ++ i ) { this . rows . add ( new Row ( ( depth - addRows ) + i ) ) ; } } ( ( Row ) this . rows . get ( depth ) ) . add ( vertex ) ; }

Adds new vertex to specified depth

@param depth depth for vertex
@param vertex vertex


public int getRow(final BaseVertex vertex) {
        final int numRows = this.rows.size();

        for ( int i = 0; i < numRows; ++i ) {
            if ( ((Row) this.rows.get( i )).contains( vertex ) ) {
                return i;
            }
        }

        return -1;
    }

public int getRow ( final BaseVertex vertex ) { final int numRows = this . rows . size ( ) ; for ( int i = 0 ; i < numRows ; ++ i ) { if ( ( ( Row ) this . rows . get ( i ) ) . contains ( vertex ) ) { return i ; } } return - 1 ; }

Finds specified vertex from the rows.

@param vertex vertex

@return row number where vertex was found (0..n-1). <code>-1</code> if not found.