From 6a7c174fc585721a349f8f236bf0f2892c718c95 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Thu, 6 Mar 2014 16:22:17 +0100 Subject: CompositeActivityDef.instanciate wasn't calling configureInstance, which copies over the properties from the def to the instance. ActivitySlotDef does it again, because it copies the slot props over, but instantiated CompositeActivities ended up with no props from the original Def. Fixes #169 --- .../com/c2kernel/lifecycle/CompositeActivityDef.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/lifecycle/CompositeActivityDef.java b/src/main/java/com/c2kernel/lifecycle/CompositeActivityDef.java index c430f20..ef5e148 100644 --- a/src/main/java/com/c2kernel/lifecycle/CompositeActivityDef.java +++ b/src/main/java/com/c2kernel/lifecycle/CompositeActivityDef.java @@ -158,6 +158,7 @@ public class CompositeActivityDef extends ActivityDef public WfVertex instantiate(String name) throws ObjectNotFoundException, InvalidDataException { CompositeActivity cAct = new CompositeActivity(); + configureInstance(cAct); cAct.setType(getName()); cAct.setName(name); GraphableVertex[] vertexDefs = getLayoutableChildren(); @@ -225,4 +226,20 @@ public class CompositeActivityDef extends ActivityDef } public void setCastorNonLayoutableChildren(String[] dummy) { } + + @Override + public boolean verify() { + boolean err = super.verify(); + GraphableVertex[] vChildren = getChildren(); + for (int i = 0; i < vChildren.length; i++) + { + WfVertexDef wfvChild = (WfVertexDef)vChildren[i]; + if (!(wfvChild.verify())) + { + mErrors.add(wfvChild.getName()+": "+wfvChild.getErrors()); + err = false; + } + } + return err; + } } -- cgit v1.2.3 From bad46b9c4ac8226de56da5367bc7c1bd9797218c Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Thu, 6 Mar 2014 16:24:43 +0100 Subject: AddStepsFromDescription was never used, and probably shouldn't be. It messes with the link between WfDef and Item, and is now removed. --- .../predefined/AddStepsFromDescription.java | 50 ---------------------- .../predefined/PredefinedStepContainer.java | 1 - 2 files changed, 51 deletions(-) delete mode 100644 src/main/java/com/c2kernel/lifecycle/instance/predefined/AddStepsFromDescription.java (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/AddStepsFromDescription.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/AddStepsFromDescription.java deleted file mode 100644 index 30d014c..0000000 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/AddStepsFromDescription.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.c2kernel.lifecycle.instance.predefined; - -//Java -import com.c2kernel.common.InvalidDataException; -import com.c2kernel.graph.model.GraphPoint; -import com.c2kernel.lifecycle.CompositeActivityDef; -import com.c2kernel.lifecycle.instance.CompositeActivity; -import com.c2kernel.lifecycle.instance.Workflow; -import com.c2kernel.lookup.AgentPath; -import com.c2kernel.process.Gateway; -import com.c2kernel.utils.Logger; - -public class AddStepsFromDescription extends PredefinedStep -{ - public AddStepsFromDescription() - { - super(); - } - - @Override - protected String runActivityLogic(AgentPath agent, int itemSysKey, - int transitionID, String requestData) throws InvalidDataException { - - - Logger.msg(1, "AddStepsFromDescription::request() - Starting "); - - Workflow lifeCycle = getWf(); - - try - { - Logger.msg(8, "AddStepsFromDescription::request() - data:" + getDataList(requestData)[0]); - lifeCycle.getChildGraphModel().removeVertex(lifeCycle.search("workflow/domain")); - CompositeActivityDef actDef = (CompositeActivityDef) Gateway.getMarshaller().unmarshall(getDataList(requestData)[0]); - CompositeActivity domain = (CompositeActivity)actDef.instantiate(); - lifeCycle.initChild(domain, true, new GraphPoint(150, 100)); - domain.setName("domain"); - domain.setType(actDef.getName()); - lifeCycle.run(agent, itemSysKey); - Gateway.getStorage().put(itemSysKey, lifeCycle, null); - Logger.msg(1, "AddStepsFromDescription::request() - DONE."); - return requestData; - } - catch (Exception ex) - { - Logger.error("AddStepsFromDescription::request() - during unmarshall."); - Logger.error(ex); - throw new InvalidDataException("AddStepsFromDescription::request() - during unmarshall.", ""); - } - } -} diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/PredefinedStepContainer.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/PredefinedStepContainer.java index 8127113..bfab876 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/PredefinedStepContainer.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/PredefinedStepContainer.java @@ -17,7 +17,6 @@ public class PredefinedStepContainer extends CompositeActivity predInit("CreateItemFromDescription", "Create a new item using this item as its description", new CreateItemFromDescription()); predInit("AddDomainPath", "Adds a new path to this entity in the LDAP domain tree", new AddDomainPath()); predInit("RemoveDomainPath", "Removes an existing path to this Entity from the LDAP domain tree", new RemoveDomainPath()); - predInit("AddStepsFromDescription", "Creates the domain-specific LifeCycle from a description", new AddStepsFromDescription()); predInit("ReplaceDomainWorkflow", "Replaces the domain CA with the supplied one. Used by the GUI to save new Wf layout", new ReplaceDomainWorkflow()); predInit("AddC2KObject", "Adds or overwrites a C2Kernel object for this Item", new AddC2KObject()); predInit("RemoveC2KObject", "Removes the named C2Kernel object from this Item.", new RemoveC2KObject()); -- cgit v1.2.3 From 4fb2c8d2a573b2078a3ced1c6142de3a20cfa660 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Thu, 6 Mar 2014 16:27:08 +0100 Subject: Fixes #166 Also allows multiple errors in each node, and composites collect the errors of their children. --- .../com/c2kernel/lifecycle/ActivitySlotDef.java | 47 ++++++++++++++-------- .../java/com/c2kernel/lifecycle/WfVertexDef.java | 12 +++++- 2 files changed, 40 insertions(+), 19 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/lifecycle/ActivitySlotDef.java b/src/main/java/com/c2kernel/lifecycle/ActivitySlotDef.java index 514dc72..85c942f 100644 --- a/src/main/java/com/c2kernel/lifecycle/ActivitySlotDef.java +++ b/src/main/java/com/c2kernel/lifecycle/ActivitySlotDef.java @@ -65,17 +65,17 @@ public class ActivitySlotDef extends WfVertexDef mErrors.add("Unreachable"); err = false; } - else if (nbInEdgres > 1) + if (nbInEdgres > 1) { mErrors.add("Bad nb of previous"); err = false; } - else if (nbOutEdges > 1) + if (nbOutEdges > 1) { mErrors.add("too many next"); err = false; } - else if (nbOutEdges == 0) + if (nbOutEdges == 0) { if (!((CompositeActivityDef) getParent()).hasGoodNumberOfActivity()) { @@ -83,22 +83,35 @@ public class ActivitySlotDef extends WfVertexDef err = false; } } - else - { - Vertex[] outV = getOutGraphables(); - Vertex[] anteVertices = GraphTraversal.getTraversal(getParent().getChildrenGraphModel(), this, GraphTraversal.kUp, false); - boolean errInLoop = false; - for (Vertex element : outV) { - for (Vertex anteVertice : anteVertices) - if (!loop() && element.getID() == anteVertice.getID()) - errInLoop = true; - } - if (errInLoop) - { - mErrors.add("Problem in Loop"); - err = false; + + Vertex[] allSiblings = getParent().getChildGraphModel().getVertices(); + String thisName = (String)getProperties().get("Name"); + if (thisName == null || thisName.length()==0) mErrors.add("Slot name is empty"); + else for (Vertex v : allSiblings) { + if (v instanceof ActivitySlotDef && v.getID()!=getID()) { + ActivitySlotDef otherSlot = (ActivitySlotDef)v; + String otherName = (String)otherSlot.getProperties().get("Name"); + if (otherName != null && otherName.equals(thisName)) { + mErrors.add("Duplicate slot name"); + err = false; + } } } + + // Loop check + Vertex[] outV = getOutGraphables(); + Vertex[] anteVertices = GraphTraversal.getTraversal(getParent().getChildrenGraphModel(), this, GraphTraversal.kUp, false); + boolean errInLoop = false; + for (Vertex element : outV) { + for (Vertex anteVertice : anteVertices) + if (!loop() && element.getID() == anteVertice.getID()) + errInLoop = true; + } + if (errInLoop) + { + mErrors.add("Problem in Loop"); + err = false; + } return err; } /** diff --git a/src/main/java/com/c2kernel/lifecycle/WfVertexDef.java b/src/main/java/com/c2kernel/lifecycle/WfVertexDef.java index 6a46bee..b2bd306 100644 --- a/src/main/java/com/c2kernel/lifecycle/WfVertexDef.java +++ b/src/main/java/com/c2kernel/lifecycle/WfVertexDef.java @@ -59,8 +59,16 @@ public abstract class WfVertexDef extends GraphableVertex { if (mErrors.size() == 0) return "No error"; - else - return mErrors.elementAt(0); + else if (mErrors.size() == 1) + return mErrors.elementAt(0); + else { + StringBuffer errorBuffer = new StringBuffer(); + for (String error : mErrors) { + if (errorBuffer.length() > 0) errorBuffer.append("\n"); + errorBuffer.append(error); + } + return errorBuffer.toString(); + } } /** -- cgit v1.2.3 From 7e98470f8acd69fa885286ccd6efd5769bad1754 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Thu, 6 Mar 2014 16:28:03 +0100 Subject: Type was being overridden with 'domain' if the CompositeActivity name was 'domain'. Stop this to let the type name be the CompositeActivityDef name. --- src/main/java/com/c2kernel/lifecycle/instance/CompositeActivity.java | 2 -- 1 file changed, 2 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/lifecycle/instance/CompositeActivity.java b/src/main/java/com/c2kernel/lifecycle/instance/CompositeActivity.java index f9ab0fe..016298f 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/CompositeActivity.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/CompositeActivity.java @@ -397,8 +397,6 @@ public class CompositeActivity extends Activity @Override public String getType() { - if (getName().equals("domain")) - return "domain"; return super.getType(); } -- cgit v1.2.3 From 696ec0bc6f005ea75db10cff9eded999456e47f2 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Thu, 6 Mar 2014 16:28:55 +0100 Subject: New methods in Outcome to support XPath queries to make extraction of XML data in scripts easier. Fixes #167 --- .../com/c2kernel/persistency/outcome/Outcome.java | 24 +++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/persistency/outcome/Outcome.java b/src/main/java/com/c2kernel/persistency/outcome/Outcome.java index b2f706b..f25922c 100644 --- a/src/main/java/com/c2kernel/persistency/outcome/Outcome.java +++ b/src/main/java/com/c2kernel/persistency/outcome/Outcome.java @@ -5,6 +5,11 @@ import java.util.StringTokenizer; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpression; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; @@ -29,6 +34,7 @@ public class Outcome implements C2KLocalObject { Document dom; static DocumentBuilder parser; static DOMImplementationLS impl; + static XPath xpath; static { // Set up parser @@ -50,7 +56,9 @@ public class Outcome implements C2KLocalObject { Logger.error(e); Logger.die("Cannot function without XML serialiser"); } - + + XPathFactory xPathFactory = XPathFactory.newInstance(); + xpath = xPathFactory.newXPath(); } //id is the eventID @@ -169,6 +177,20 @@ public class Outcome implements C2KLocalObject { else return null; } + + public String getFieldByXPath(String xpathExpr) throws XPathExpressionException { + + XPathExpression expr = xpath.compile(xpathExpr); + return (String)expr.evaluate(getDOM(), XPathConstants.STRING); + + } + + public NodeList getNodesByXPath(String xpathExpr) throws XPathExpressionException { + + XPathExpression expr = xpath.compile(xpathExpr); + return (NodeList)expr.evaluate(getDOM(), XPathConstants.NODESET); + + } static public String serialize(Document doc, boolean prettyPrint) { -- cgit v1.2.3 From 53040641471c131f759c932167bed79040c806c5 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Thu, 6 Mar 2014 16:30:41 +0100 Subject: ActivityDefs loaded from ActDefCache get a 'Version' property set with their Viewpoint name so the resulting Activity's version will be set correctly. Refs #168 --- src/main/java/com/c2kernel/utils/ActDefCache.java | 1 + 1 file changed, 1 insertion(+) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/utils/ActDefCache.java b/src/main/java/com/c2kernel/utils/ActDefCache.java index ab2bd90..66695f5 100644 --- a/src/main/java/com/c2kernel/utils/ActDefCache.java +++ b/src/main/java/com/c2kernel/utils/ActDefCache.java @@ -34,6 +34,7 @@ public class ActDefCache extends DescriptionObjectCache { } try { thisActDef = (ActivityDef)Gateway.getMarshaller().unmarshall(marshalledAct); + thisActDef.getProperties().put("Version", version); } catch (Exception ex) { Logger.error(ex); throw new InvalidDataException("Could not unmarshall '"+name+"' v"+version+": "+ex.getMessage(), ""); -- cgit v1.2.3 From 7c341c90d5d45ddf4b868f7ccec91d9cdd23792f Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Thu, 6 Mar 2014 16:32:29 +0100 Subject: Module resources get a 'Module' property set when they belong to a particular module. If they belong to a particular module, they are moved into the correct sub-context for that module. If the resource is already set to a different module, and error occurs. --- src/main/java/com/c2kernel/process/Bootstrap.java | 36 +++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/process/Bootstrap.java b/src/main/java/com/c2kernel/process/Bootstrap.java index 4f64adf..d472978 100644 --- a/src/main/java/com/c2kernel/process/Bootstrap.java +++ b/src/main/java/com/c2kernel/process/Bootstrap.java @@ -125,6 +125,33 @@ public class Bootstrap else { DomainPath path = (DomainPath)en.nextElement(); thisProxy = (ItemProxy)Gateway.getProxyManager().getProxy(path); + + DomainPath modDomPath = getResourceDomPath(itemType, ns, itemName); + String moduleName = (ns==null?"kernel":ns); + String itemModule; + try{ + itemModule = thisProxy.getProperty("Module"); + if (!itemModule.equals("") && !itemModule.equals("null") && !moduleName.equals(itemModule)) { + Logger.error("Bootstrap.verifyResource() - Resource '"+itemName+"' included in module "+moduleName+" but is assigned to '"+itemModule+"'. Not overwriting."); + return; + } + } catch (ObjectNotFoundException ex) { + itemModule = ""; + } + + if (!moduleName.equals(itemModule)) { // write module property + Gateway.getStorage().put(thisProxy.getSystemKey(), new Property("Module", moduleName, false), null); + } + + if (!modDomPath.equals(path)) { // move item to module subtree + Logger.msg("Module item "+itemName+" found with path "+path.toString()+". Moving to "+modDomPath.toString()); + modDomPath.setEntity(new EntityPath(thisProxy.getSystemKey())); + if (!modDomPath.exists()) + Gateway.getLDAPLookup().add(modDomPath); + Gateway.getLDAPLookup().delete(path); + } + + try { Viewpoint currentData = (Viewpoint)thisProxy.getObject(ClusterStorage.VIEWPOINT+"/"+getDataType(itemType)+"/"+version); Outcome oldData = currentData.getOutcome(); @@ -161,7 +188,12 @@ public class Bootstrap Gateway.getStorage().commit(thisProxy); } - /** + private static DomainPath getResourceDomPath(String itemType, String ns, + String itemName) throws Exception { + return new DomainPath(getTypeRoot(itemType).toString()+"/system/"+(ns==null?"kernel":ns)+"/"+itemName); + } + + /** * @param itemType * @param itemName * @param data @@ -195,7 +227,7 @@ public class Bootstrap 1, Gateway.getMarshaller().marshall(props), Gateway.getMarshaller().marshall(ca)); - DomainPath newDomPath = new DomainPath(getTypeRoot(itemType).toString()+"/system/"+(ns==null?"kernel":ns)+"/"+itemName); + DomainPath newDomPath = getResourceDomPath(itemType, ns, itemName); newDomPath.setEntity(entityPath); Gateway.getLDAPLookup().add(newDomPath); return (ItemProxy)Gateway.getProxyManager().getProxy(entityPath); -- cgit v1.2.3 From 59000bddf2cd1551d0ddfd423d835a20c4feab18 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Mon, 10 Mar 2014 10:12:09 +0100 Subject: More alignment with Agilium version. Fixes an advancement problem on Join --- .../lifecycle/instance/AdvancementCalculator.java | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/lifecycle/instance/AdvancementCalculator.java b/src/main/java/com/c2kernel/lifecycle/instance/AdvancementCalculator.java index 6302dc7..e688a47 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/AdvancementCalculator.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/AdvancementCalculator.java @@ -10,7 +10,7 @@ import com.c2kernel.graph.model.Vertex; public class AdvancementCalculator implements Serializable { private CompositeActivity activity; - private Hashtable isMarked; + private Hashtable isMarked; private Hashtable HasNextMarked; public Hashtable hasprevActive; private long mCurrentNbActExp = 0; @@ -24,7 +24,7 @@ public class AdvancementCalculator implements Serializable private boolean mHasPrevActive = false; public AdvancementCalculator() { - isMarked = new Hashtable(); + isMarked = new Hashtable(); HasNextMarked = new Hashtable(); hasprevActive = new Hashtable(); } @@ -39,7 +39,7 @@ public class AdvancementCalculator implements Serializable activity = act; Vertex v = activity.getChildGraphModel().getStartVertex(); check(v, this); - isMarked = new Hashtable(); + isMarked = new Hashtable(); calc(v, this); // Logger.debug(0, act.getName()+" <<<<<<<<<"); } @@ -77,11 +77,10 @@ public class AdvancementCalculator implements Serializable current.mMaximuNbActexp += adv.mMaximuNbActexp; current.mNbActpassed += adv.mNbActpassed; current.mNbActpassedWithCurrent += adv.mNbActpassedWithCurrent; - current.mIsbranchActive = current.mIsbranchActive || adv.mIsbranchActive||act.getActive(); + current.mIsbranchActive = current.mIsbranchActive || adv.mIsbranchActive || act.getActive(); current.mNbActLeftWithCurrent += adv.mNbActLeftWithCurrent; current.mNbActLeftWithoutCurrent += adv.mNbActLeftWithoutCurrent; - current.mHasPrevActive |= adv.mHasPrevActive||act.getActive(); - if (adv.hasprevActive.size()!=0) current.mHasPrevActive=true; + current.mHasPrevActive |= adv.mHasPrevActive || act.getActive() || adv.hasprevActive.size()!=0; } else { @@ -92,6 +91,14 @@ public class AdvancementCalculator implements Serializable current.mNbActpassed += 1; current.mNbActpassedWithCurrent += 1; } + else if (act.getActive()) + { + current.mIsbranchActive = true; + current.mIsbranchFinished = false; + current.mHasPrevActive = true; + current.mNbActpassedWithCurrent += 1; + current.mNbActLeftWithCurrent += 1; + } else { current.mIsbranchFinished = false; -- cgit v1.2.3 From ddd7a9c7c9d3fc79f105d68a32905a087b05f07a Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Tue, 18 Mar 2014 11:53:35 +0100 Subject: getActPropString should return null when the property is null. --- src/main/java/com/c2kernel/entity/agent/Job.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/entity/agent/Job.java b/src/main/java/com/c2kernel/entity/agent/Job.java index 02dd541..ea28e38 100644 --- a/src/main/java/com/c2kernel/entity/agent/Job.java +++ b/src/main/java/com/c2kernel/entity/agent/Job.java @@ -335,6 +335,7 @@ public class Job implements C2KLocalObject public String getActPropString(String name) { - return String.valueOf(actProps.get(name)); + Object obj = getActProp(name); + return obj==null?null:String.valueOf(obj); } } \ No newline at end of file -- cgit v1.2.3 From 9a6f9da9438308d80cda9df3d53aaa9f1b14683a Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Wed, 19 Mar 2014 16:17:15 +0100 Subject: Set the class loader of the ScriptingEngine to the same as the Script class, instead of the thread context one. Should solve problems with Jetty etc. --- src/main/java/com/c2kernel/scripting/Script.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/scripting/Script.java b/src/main/java/com/c2kernel/scripting/Script.java index e3b4478..92a49cf 100644 --- a/src/main/java/com/c2kernel/scripting/Script.java +++ b/src/main/java/com/c2kernel/scripting/Script.java @@ -173,7 +173,7 @@ public class Script } public void setScriptEngine(String lang) throws ScriptingEngineException { - engine = new ScriptEngineManager().getEngineByName(lang); + engine = new ScriptEngineManager(getClass().getClassLoader()).getEngineByName(lang); if (engine==null) throw new ScriptingEngineException("No script engine for '"+lang+"' found."); Bindings beans = engine.createBindings(); -- cgit v1.2.3 From 1d54a4abc26bf03e1c759d47282e79d6485a988a Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Thu, 27 Mar 2014 10:59:24 +0100 Subject: RemoveDomainPath now checks if the DomainPath exists, is not a context, and is an alias of the current Item. Fixes #176 --- .../instance/predefined/RemoveDomainPath.java | 32 ++++++++++++++-------- 1 file changed, 20 insertions(+), 12 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/RemoveDomainPath.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/RemoveDomainPath.java index 642cf64..e33f722 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/RemoveDomainPath.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/RemoveDomainPath.java @@ -11,6 +11,8 @@ package com.c2kernel.lifecycle.instance.predefined; import com.c2kernel.common.InvalidDataException; +import com.c2kernel.common.ObjectCannotBeUpdated; +import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.lookup.AgentPath; import com.c2kernel.lookup.DomainPath; import com.c2kernel.lookup.LDAPLookup; @@ -34,19 +36,25 @@ public class RemoveDomainPath extends PredefinedStep Logger.msg(1,"RemoveDomainPath::request() - Starting."); - try - { - DomainPath domainPath = new DomainPath(getDataList(requestData)[0]); - lookupManager.delete(domainPath); - Logger.msg(8,"AddAlias::request() - context:" + domainPath.toString() + " DONE."); - return requestData; + DomainPath domainPath = new DomainPath(getDataList(requestData)[0]); + if (!domainPath.exists()) + throw new InvalidDataException("Domain path "+domainPath.toString()+" does not exist.", ""); + + if (domainPath.getType()!=DomainPath.ENTITY) + + try { + if (domainPath.getEntity().getSysKey() != itemSysKey) + throw new InvalidDataException("Domain path "+domainPath.toString()+" is not an alias of the current Item "+itemSysKey, ""); + } catch (ObjectNotFoundException ex) { + throw new InvalidDataException("Domain path "+domainPath.toString()+" is a context.", ""); } - catch( Exception ex ) - { - Logger.error("AddAlias::request() - during anyHelper.extract."); - Logger.error(ex); - throw new InvalidDataException(ex.toString(), ""); + try { + lookupManager.delete(domainPath); + Logger.msg(8,"AddAlias::request() - context:" + domainPath.toString() + " DONE."); + return requestData; + } catch (ObjectCannotBeUpdated ex) { + Logger.error(ex); + throw new InvalidDataException("Problem updating directory", ""); } - } } -- cgit v1.2.3 From 391c7935ae40f60672b88312b02151c3f941796e Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Mon, 31 Mar 2014 16:18:42 +0200 Subject: Outcome.setFieldByXPath (refs #167) --- .../com/c2kernel/persistency/outcome/Outcome.java | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/persistency/outcome/Outcome.java b/src/main/java/com/c2kernel/persistency/outcome/Outcome.java index f25922c..5604332 100644 --- a/src/main/java/com/c2kernel/persistency/outcome/Outcome.java +++ b/src/main/java/com/c2kernel/persistency/outcome/Outcome.java @@ -12,6 +12,7 @@ import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; +import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.w3c.dom.bootstrap.DOMImplementationRegistry; @@ -118,11 +119,20 @@ public class Outcome implements C2KLocalObject { } public void setData(Document data) { - mData = serialize(data, false); dom = data; + mData = null; } + + public void setFieldByXPath(String xpath, String data) throws XPathExpressionException { + Node field = getNodeByXPath(xpath); + field.setNodeValue(data); + } + public String getData() { + if (mData == null && dom != null) { + mData = serialize(dom, false); + } return mData; } @@ -158,7 +168,7 @@ public class Outcome implements C2KLocalObject { * @return a DOM Document */ public Document getDOM() { - if (dom == null) + if (dom == null && mData != null) try { synchronized (parser) { dom = parser.parse(new InputSource(new StringReader(mData))); @@ -191,6 +201,13 @@ public class Outcome implements C2KLocalObject { return (NodeList)expr.evaluate(getDOM(), XPathConstants.NODESET); } + + public Node getNodeByXPath(String xpathExpr) throws XPathExpressionException { + + XPathExpression expr = xpath.compile(xpathExpr); + return (Node)expr.evaluate(getDOM(), XPathConstants.NODE); + + } static public String serialize(Document doc, boolean prettyPrint) { -- cgit v1.2.3 From 105351949f127a4f936391f5ac8ae93bea707a35 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Wed, 2 Apr 2014 15:22:51 +0200 Subject: Remove stray transitionId parameter from previous State Machine API --- src/main/java/com/c2kernel/events/History.java | 1 - 1 file changed, 1 deletion(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/events/History.java b/src/main/java/com/c2kernel/events/History.java index 8ccd97a..bf77f40 100644 --- a/src/main/java/com/c2kernel/events/History.java +++ b/src/main/java/com/c2kernel/events/History.java @@ -65,7 +65,6 @@ public class History extends RemoteMap { } public Event addEvent(String agentName, String agentRole, - int stepTransitionId, String stepName, String stepPath, String stepType, -- cgit v1.2.3 From aaa9509c6f4e5ac0edb308041d1ffa361b468a5f Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Wed, 2 Apr 2014 15:30:06 +0200 Subject: ResourceImportHandler interface to allow custom types or override the structure of standard ones. Specify with ResourceImportHandler. c2kprop. DefaultResourceImportHandler is used if not defined, which handled the 5 standard types (CA,EA,OD,SC,SM). Fixes #178 --- .../predefined/entitycreation/NewAgent.java | 5 - .../predefined/entitycreation/NewItem.java | 6 - .../predefined/entitycreation/NewRole.java | 5 - src/main/java/com/c2kernel/process/Bootstrap.java | 197 ++++++++++----------- .../java/com/c2kernel/process/module/Module.java | 9 +- .../com/c2kernel/process/module/ModuleImport.java | 5 +- .../c2kernel/process/module/ModuleResource.java | 13 -- .../resource/DefaultResourceImportHandler.java | 87 +++++++++ .../process/resource/ResourceImportHandler.java | 47 +++++ 9 files changed, 239 insertions(+), 135 deletions(-) create mode 100644 src/main/java/com/c2kernel/process/resource/DefaultResourceImportHandler.java create mode 100644 src/main/java/com/c2kernel/process/resource/ResourceImportHandler.java (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewAgent.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewAgent.java index 12bbb56..2c025d2 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewAgent.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewAgent.java @@ -57,9 +57,4 @@ public class NewAgent extends ModuleImport implements java.io.Serializable { } } - - @Override - public String getPath(String ns) { - return null; - } } diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java index d5da008..5f8cf12 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java @@ -188,10 +188,4 @@ public class NewItem extends ModuleImport { } } } - - @Override - public String getPath(String ns) { - setNamespace(ns); - return initialPath; - } } diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewRole.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewRole.java index 1800b0e..003b7f7 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewRole.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewRole.java @@ -11,11 +11,6 @@ public class NewRole extends ModuleImport { public NewRole() { } - - @Override - public String getPath(String ns) { - return null; // roles don't have user-specified domain paths - } public void create(int agentId) throws ObjectAlreadyExistsException, ObjectCannotBeUpdated { Gateway.getLDAPLookup().getRoleManager().createRole(name, jobList); diff --git a/src/main/java/com/c2kernel/process/Bootstrap.java b/src/main/java/com/c2kernel/process/Bootstrap.java index d472978..df8ced7 100644 --- a/src/main/java/com/c2kernel/process/Bootstrap.java +++ b/src/main/java/com/c2kernel/process/Bootstrap.java @@ -2,6 +2,8 @@ package com.c2kernel.process; import java.net.InetAddress; import java.util.Enumeration; +import java.util.HashMap; +import java.util.Set; import java.util.StringTokenizer; import org.custommonkey.xmlunit.Diff; @@ -27,6 +29,8 @@ import com.c2kernel.lookup.RolePath; import com.c2kernel.persistency.ClusterStorage; import com.c2kernel.persistency.outcome.Outcome; import com.c2kernel.persistency.outcome.Viewpoint; +import com.c2kernel.process.resource.DefaultResourceImportHandler; +import com.c2kernel.process.resource.ResourceImportHandler; import com.c2kernel.property.Property; import com.c2kernel.property.PropertyArrayList; import com.c2kernel.property.PropertyDescription; @@ -43,6 +47,7 @@ import com.c2kernel.utils.Logger; public class Bootstrap { static DomainPath thisServerPath; + static HashMap resHandlerCache = new HashMap(); /** * Run everything without timing-out the service wrapper @@ -98,10 +103,8 @@ public class Bootstrap String itemType = thisItem.substring(0,delim); String itemName = thisItem.substring(delim+1); try { - String data = Gateway.getResource().getTextResource(ns, "boot/"+thisItem+(itemType.equals("OD")?".xsd":".xml")); - if (data == null) - Logger.die("No data found for "+getDataType(itemType)+" "+itemName); - verifyResource(ns, itemName, 0, itemType, data, reset); + String location = "boot/"+thisItem+(itemType.equals("OD")?".xsd":".xml"); + verifyResource(ns, itemName, 0, itemType, location, reset); } catch (Exception e) { Logger.error(e); Logger.die("Error importing bootstrap items. Unsafe to continue."); @@ -110,97 +113,123 @@ public class Bootstrap } - public static void verifyResource(String ns, String itemName, Integer version, String itemType, String data, boolean reset) throws Exception { + public static DomainPath verifyResource(String ns, String itemName, Integer version, String itemType, String dataLocation, boolean reset) throws Exception { if (version == null) version = 0; - Logger.msg(1, "Bootstrap.verifyResource() - Verifying version "+version+" of "+getDataType(itemType)+" "+itemName); + ResourceImportHandler typeImpHandler = getHandler(itemType); + Logger.msg(1, "Bootstrap.verifyResource() - Verifying version "+version+" of "+typeImpHandler.getName()+" "+itemName); - Enumeration en = Gateway.getLDAPLookup().search(getTypeRoot(itemType), itemName); + // Find or create Item for Resource + DomainPath modDomPath = typeImpHandler.getPath(itemName, ns); ItemProxy thisProxy; - Outcome newOutcome = new Outcome(0, data, getDataType(itemType), 0); - + Enumeration en = Gateway.getLDAPLookup().search(typeImpHandler.getTypeRoot(), itemName); if (!en.hasMoreElements()) { - Logger.msg("Bootstrap.verifyResource() - "+getDataType(itemType)+" "+itemName+" not found. Creating new."); - thisProxy = createResourceItem(itemType, itemName, ns); + Logger.msg("Bootstrap.verifyResource() - "+typeImpHandler.getName()+" "+itemName+" not found. Creating new."); + thisProxy = createResourceItem(typeImpHandler, itemName, ns); } else { DomainPath path = (DomainPath)en.nextElement(); thisProxy = (ItemProxy)Gateway.getProxyManager().getProxy(path); - - DomainPath modDomPath = getResourceDomPath(itemType, ns, itemName); - String moduleName = (ns==null?"kernel":ns); - String itemModule; - try{ - itemModule = thisProxy.getProperty("Module"); - if (!itemModule.equals("") && !itemModule.equals("null") && !moduleName.equals(itemModule)) { - Logger.error("Bootstrap.verifyResource() - Resource '"+itemName+"' included in module "+moduleName+" but is assigned to '"+itemModule+"'. Not overwriting."); - return; - } - } catch (ObjectNotFoundException ex) { - itemModule = ""; - } - - if (!moduleName.equals(itemModule)) { // write module property - Gateway.getStorage().put(thisProxy.getSystemKey(), new Property("Module", moduleName, false), null); - } - - if (!modDomPath.equals(path)) { // move item to module subtree - Logger.msg("Module item "+itemName+" found with path "+path.toString()+". Moving to "+modDomPath.toString()); - modDomPath.setEntity(new EntityPath(thisProxy.getSystemKey())); - if (!modDomPath.exists()) - Gateway.getLDAPLookup().add(modDomPath); - Gateway.getLDAPLookup().delete(path); - } - - - try { - Viewpoint currentData = (Viewpoint)thisProxy.getObject(ClusterStorage.VIEWPOINT+"/"+getDataType(itemType)+"/"+version); + + // Verify module property and location + + String moduleName = (ns==null?"kernel":ns); + String itemModule; + try{ + itemModule = thisProxy.getProperty("Module"); + if (!itemModule.equals("") && !itemModule.equals("null") && !moduleName.equals(itemModule)) { + Logger.error("Bootstrap.verifyResource() - Module clash! Resource '"+itemName+"' included in module "+moduleName+" but is assigned to '"+itemModule+"'. Not overwriting."); + return path; + } + } catch (ObjectNotFoundException ex) { + itemModule = ""; + } + + if (!moduleName.equals(itemModule)) { // write module property + Gateway.getStorage().put(thisProxy.getSystemKey(), new Property("Module", moduleName, false), thisProxy); + } + + if (!modDomPath.equals(path)) { // move item to module subtree + Logger.msg("Module item "+itemName+" found with path "+path.toString()+". Moving to "+modDomPath.toString()); + modDomPath.setEntity(new EntityPath(thisProxy.getSystemKey())); + if (!modDomPath.exists()) + Gateway.getLDAPLookup().add(modDomPath); + Gateway.getLDAPLookup().delete(path); + } + } + + // Verify/Import Outcomes, creating events and views as necessary + Set impList = typeImpHandler.getResourceOutcomes(itemName, ns, dataLocation, version); + for (Outcome newOutcome : impList) { + try { + Viewpoint currentData = (Viewpoint)thisProxy.getObject(ClusterStorage.VIEWPOINT+"/"+newOutcome.getSchemaType()+"/"+version); Outcome oldData = currentData.getOutcome(); XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreComments(true); Diff xmlDiff = new Diff(newOutcome.getDOM(), oldData.getDOM()); if (xmlDiff.identical()) { Logger.msg(5, "Bootstrap.verifyResource() - Data identical, no update required"); - return; + continue; } else { Logger.msg("Difference found in "+itemName+": "+xmlDiff.toString()); if (!reset && !currentData.getEvent().getStepPath().equals("Bootstrap")) { Logger.msg("Version "+version+" was not set by Bootstrap, and reset not requested. Not overwriting."); - return; + continue; } } } catch (ObjectNotFoundException ex) { - Logger.error("Bootstrap.verifyResource() - Item "+itemName+" exists but version "+version+" not found! Attempting to insert new."); + Logger.msg("Bootstrap.verifyResource() - Item "+itemName+" exists but version "+version+" not found! Attempting to insert new."); } + + // data was missing or doesn't match + Logger.msg("Bootstrap.verifyResource() - Writing new "+newOutcome.getSchemaType()+"version "+version+" to "+typeImpHandler.getName()+" "+itemName); + History hist = new History(thisProxy.getSystemKey(), thisProxy); + Transition predefDone = new Transition(0, "Done", 0, 0); + Event newEvent = hist.addEvent("system", "Admin", "Bootstrap", "Bootstrap", "Bootstrap", newOutcome.getSchemaType(), 0, "PredefinedStep", 0, predefDone, String.valueOf(version)); + newOutcome.setID(newEvent.getID()); + Viewpoint newLastView = new Viewpoint(thisProxy.getSystemKey(), newOutcome.getSchemaType(), "last", 0, newEvent.getID()); + Viewpoint newNumberView = new Viewpoint(thisProxy.getSystemKey(), newOutcome.getSchemaType(), String.valueOf(version), 0, newEvent.getID()); + Gateway.getStorage().put(thisProxy.getSystemKey(), newOutcome, thisProxy); + Gateway.getStorage().put(thisProxy.getSystemKey(), newLastView, thisProxy); + Gateway.getStorage().put(thisProxy.getSystemKey(), newNumberView, thisProxy); } - // data was missing or doesn't match - Logger.msg("Bootstrap.verifyResource() - Writing new version "+version+" to "+getDataType(itemType)+" "+itemName); - History hist = new History(thisProxy.getSystemKey(), thisProxy); - Transition predefDone = new Transition(0, "Done", 0, 0); - Event newEvent = hist.addEvent("system", "Admin", "Bootstrap", "Bootstrap", "Bootstrap", getDataType(itemType), 0, "PredefinedStep", 0, predefDone, String.valueOf(version)); - newOutcome.setID(newEvent.getID()); - Viewpoint newLastView = new Viewpoint(thisProxy.getSystemKey(), getDataType(itemType), "last", 0, newEvent.getID()); - Viewpoint newZeroView = new Viewpoint(thisProxy.getSystemKey(), getDataType(itemType), String.valueOf(version), 0, newEvent.getID()); - Gateway.getStorage().put(thisProxy.getSystemKey(), newOutcome, thisProxy); - Gateway.getStorage().put(thisProxy.getSystemKey(), newLastView, thisProxy); - Gateway.getStorage().put(thisProxy.getSystemKey(), newZeroView, thisProxy); - Gateway.getStorage().commit(thisProxy); + Gateway.getStorage().commit(thisProxy); + return modDomPath; + } + + private static ResourceImportHandler getHandler(String resType) throws Exception { + if (resHandlerCache.containsKey(resType)) + return resHandlerCache.get(resType); + ResourceImportHandler handler; + Object handlerProp = Gateway.getProperties().get("ResourceImportHandler."+resType); + if (handlerProp instanceof ResourceImportHandler) + handler = (ResourceImportHandler)handlerProp; + else if (handlerProp instanceof String) { //class name + try { + Class handlerClass = Class.forName((String)handlerProp); + handler = (ResourceImportHandler) handlerClass.newInstance(); + } catch (ClassNotFoundException e) { + throw new Exception("Handler class "+handlerProp+" for importing "+resType+" resources not found"); + } catch (ClassCastException e) { + throw new Exception(handlerProp+" for importing "+resType+" was not a ResourceImportHandler"); + } + } + else + handler = new DefaultResourceImportHandler(resType); + + resHandlerCache.put(resType, handler); + return handler; } - - private static DomainPath getResourceDomPath(String itemType, String ns, - String itemName) throws Exception { - return new DomainPath(getTypeRoot(itemType).toString()+"/system/"+(ns==null?"kernel":ns)+"/"+itemName); - } /** * @param itemType * @param itemName * @param data */ - private static ItemProxy createResourceItem(String itemType, String itemName, String ns) throws Exception { + private static ItemProxy createResourceItem(ResourceImportHandler impHandler, String itemName, String ns) throws Exception { // create props - PropertyDescriptionList pdList = (PropertyDescriptionList)Gateway.getMarshaller().unmarshall(Gateway.getResource().getTextResource(null, "boot/property/"+itemType+"Prop.xml")); + PropertyDescriptionList pdList = impHandler.getPropDesc(); PropertyArrayList props = new PropertyArrayList(); for (int i = 0; i < pdList.list.size(); i++) { PropertyDescription pd = pdList.list.get(i); @@ -209,16 +238,11 @@ public class Bootstrap props.list.add(new Property(propName, propVal, pd.getIsMutable())); } - CompositeActivity ca = new CompositeActivity(); - if (ns!=null && Gateway.getProperties().getBoolean("Module.debug", false)) { - String wf; - if (itemType.equals("CA")) wf = "ManageCompositeActDef"; - else if (itemType.equals("EA")) wf = "ManageElementaryActDef"; - else if (itemType.equals("OD")) wf = "ManageSchema"; - else if (itemType.equals("SC")) wf = "ManageScript"; - else throw new Exception("Unknown bootstrap item type: "+itemType); - ca = (CompositeActivity) ((CompositeActivityDef)LocalObjectLoader.getActDef(wf, 0)).instantiate(); - } + CompositeActivity ca; + if (ns!=null && Gateway.getProperties().getBoolean("Module.debug", false)) + ca = (CompositeActivity) ((CompositeActivityDef)LocalObjectLoader.getActDef(impHandler.getWorkflowName(), 0)).instantiate(); + else + ca = new CompositeActivity(); EntityPath entityPath = Gateway.getLDAPLookup().getNextKeyManager().generateNextEntityKey(); TraceableEntity newItem = (TraceableEntity)Gateway.getCorbaServer().createEntity(entityPath); @@ -227,39 +251,12 @@ public class Bootstrap 1, Gateway.getMarshaller().marshall(props), Gateway.getMarshaller().marshall(ca)); - DomainPath newDomPath = getResourceDomPath(itemType, ns, itemName); + DomainPath newDomPath = impHandler.getPath(itemName, ns); newDomPath.setEntity(entityPath); Gateway.getLDAPLookup().add(newDomPath); return (ItemProxy)Gateway.getProxyManager().getProxy(entityPath); } - public static DomainPath getTypeRoot(String type) throws Exception { - if (type.equals("CA") || type.equals("EA")) - return new DomainPath("/desc/ActivityDesc/"); - if (type.equals("SC")) - return new DomainPath("/desc/Script/"); - if (type.equals("OD")) - return new DomainPath("/desc/OutcomeDesc/"); - if (type.equals("SM")) - return new DomainPath("/desc/StateMachine"); - throw new Exception("Unknown bootstrap item type: "+type); - } - - private static String getDataType(String type) throws Exception { - if (type.equals("CA")) - return "CompositeActivityDef"; - if (type.equals("EA")) - return "ElementaryActivityDef"; - if (type.equals("OD")) - return "Schema"; - if (type.equals("SC")) - return "Script"; - if (type.equals("SM")) - return "StateMachine"; - throw new Exception("Unknown bootstrap item type: "+type); - - } - /************************************************************************** * Checks for the existence of the admin users so you can use Cristal **************************************************************************/ diff --git a/src/main/java/com/c2kernel/process/module/Module.java b/src/main/java/com/c2kernel/process/module/Module.java index fda4b1b..a7c707e 100644 --- a/src/main/java/com/c2kernel/process/module/Module.java +++ b/src/main/java/com/c2kernel/process/module/Module.java @@ -11,6 +11,7 @@ import com.c2kernel.lifecycle.instance.predefined.entitycreation.NewAgent; import com.c2kernel.lifecycle.instance.predefined.entitycreation.NewItem; import com.c2kernel.lifecycle.instance.predefined.entitycreation.NewRole; import com.c2kernel.lifecycle.instance.predefined.entitycreation.Outcome; +import com.c2kernel.lookup.DomainPath; import com.c2kernel.lookup.RolePath; import com.c2kernel.process.Bootstrap; import com.c2kernel.process.Gateway; @@ -59,10 +60,9 @@ public class Module { // Add dependency for all children Dependency children = new Dependency("Contents"); for (ModuleImport thisImport : imports.list) { - String path = thisImport.getPath(ns); + DomainPath path = thisImport.path; if (path != null) - children.dependencyMemberList.add( - new DependencyMember(path+"/"+thisImport.name)); + children.dependencyMemberList.add(new DependencyMember(path.toString())); } moduleItem.dependencyList.add(children); // Add moduleXML @@ -78,7 +78,8 @@ public class Module { for (ModuleResource thisRes : imports.getResources()) { try { - Bootstrap.verifyResource(ns, thisRes.name, thisRes.version, thisRes.resourceType, Gateway.getResource().getTextResource(ns, thisRes.resourceLocation), reset); + thisRes.path = Bootstrap.verifyResource(ns, thisRes.name, thisRes.version, + thisRes.resourceType, thisRes.resourceLocation, reset); } catch (Exception ex) { Logger.error(ex); } diff --git a/src/main/java/com/c2kernel/process/module/ModuleImport.java b/src/main/java/com/c2kernel/process/module/ModuleImport.java index 77bf3f6..1f5b16d 100644 --- a/src/main/java/com/c2kernel/process/module/ModuleImport.java +++ b/src/main/java/com/c2kernel/process/module/ModuleImport.java @@ -1,9 +1,10 @@ package com.c2kernel.process.module; +import com.c2kernel.lookup.DomainPath; + public abstract class ModuleImport { public String name; + public DomainPath path; - public abstract String getPath(String ns); - } \ No newline at end of file diff --git a/src/main/java/com/c2kernel/process/module/ModuleResource.java b/src/main/java/com/c2kernel/process/module/ModuleResource.java index 2f7b638..b36623f 100644 --- a/src/main/java/com/c2kernel/process/module/ModuleResource.java +++ b/src/main/java/com/c2kernel/process/module/ModuleResource.java @@ -8,17 +8,4 @@ public class ModuleResource extends ModuleImport { public ModuleResource() { } - - @Override - public String getPath(String ns) { - StringBuffer path = new StringBuffer(); - if (resourceType.equals("CA") || resourceType.equals("EA")) - path.append("/desc/ActivityDesc/"); - if (resourceType.equals("SC")) - path.append("/desc/Script/"); - if (resourceType.equals("OD")) - path.append("/desc/OutcomeDesc/"); - path.append("system/").append(ns==null?"kernel":ns); - return path.toString(); - } } \ No newline at end of file diff --git a/src/main/java/com/c2kernel/process/resource/DefaultResourceImportHandler.java b/src/main/java/com/c2kernel/process/resource/DefaultResourceImportHandler.java new file mode 100644 index 0000000..afcf021 --- /dev/null +++ b/src/main/java/com/c2kernel/process/resource/DefaultResourceImportHandler.java @@ -0,0 +1,87 @@ +package com.c2kernel.process.resource; + +import java.util.HashSet; +import java.util.Set; + +import com.c2kernel.lookup.DomainPath; +import com.c2kernel.persistency.outcome.Outcome; +import com.c2kernel.process.Gateway; +import com.c2kernel.property.PropertyDescriptionList; + +public class DefaultResourceImportHandler implements ResourceImportHandler { + + String resType; + String schemaName; + String typeRoot; + DomainPath typeRootPath; + String wfDef; + PropertyDescriptionList props; + + public DefaultResourceImportHandler(String resType) throws Exception { + this.resType = resType; + if (resType.equals("CA")) { + wfDef = "ManageCompositeActDef"; + schemaName = "CompositeActivityDef"; + typeRoot = "/desc/ActivityDesc"; + } + else if (resType.equals("EA")) { + wfDef = "ManageElementaryActDef"; + schemaName = "ElementaryActivityDef"; + typeRoot = "/desc/ActivityDesc"; + } + else if (resType.equals("OD")) { + wfDef = "ManageSchema"; + schemaName = "Schema"; + typeRoot = "/desc/OutcomeDesc"; + } + else if (resType.equals("SC")) { + wfDef = "ManageScript"; + schemaName = "Script"; + typeRoot = "/desc/Script"; + } + else if (resType.equals("SM")) { + wfDef = "ManageStateMachine"; + schemaName = "StateMachine"; + typeRoot = "/desc/StateMachine"; + } + else throw new Exception("Unknown bootstrap item type: "+resType); + typeRootPath = new DomainPath(typeRoot); + props = (PropertyDescriptionList)Gateway.getMarshaller().unmarshall(Gateway.getResource().getTextResource(null, "boot/property/"+resType+"Prop.xml")); + } + + @Override + public DomainPath getTypeRoot() { + return typeRootPath; + } + + @Override + public String getName() { + return schemaName; + } + + @Override + public DomainPath getPath(String name, String ns) throws Exception { + return new DomainPath(typeRoot+"/system/"+(ns==null?"kernel":ns)+'/'+name); + } + + @Override + public Set getResourceOutcomes(String name, String ns, String location, int version) throws Exception { + HashSet retArr = new HashSet(); + String data = Gateway.getResource().getTextResource(ns, location); + if (data == null) + throw new Exception("No data found for "+schemaName+" "+name); + Outcome resOutcome = new Outcome(0, data, schemaName, 0); + retArr.add(resOutcome); + return retArr; + } + + @Override + public PropertyDescriptionList getPropDesc() throws Exception { + return props; + } + + @Override + public String getWorkflowName() throws Exception { + return wfDef; + } +} diff --git a/src/main/java/com/c2kernel/process/resource/ResourceImportHandler.java b/src/main/java/com/c2kernel/process/resource/ResourceImportHandler.java new file mode 100644 index 0000000..8f825b5 --- /dev/null +++ b/src/main/java/com/c2kernel/process/resource/ResourceImportHandler.java @@ -0,0 +1,47 @@ +package com.c2kernel.process.resource; + +import java.util.Set; + +import com.c2kernel.lookup.DomainPath; +import com.c2kernel.persistency.outcome.Outcome; +import com.c2kernel.property.PropertyDescriptionList; + +public interface ResourceImportHandler { + + + /** Returns the DomainPath for a specific resource + * @param ns - module namespace + * @param name - resource name + * @return + */ + public DomainPath getPath(String name, String ns) throws Exception; + + /** Generates the outcomes that the resource should contain. + * @param res - the module resource definition + * @return a set of outcomes to be synced with the resource item. + * @throws Exception - if the supplied resources are not valid + */ + public Set getResourceOutcomes(String name, String ns, String location, int version) throws Exception; + + /** Gives the CompActDef name to instantiate to provide the workflow for this type of resource. + * Should be found in the CA typeroot (/desc/ActivityDesc/) + * @return String workflow name + * @throws Exception + */ + public String getWorkflowName() throws Exception; + + /** Should return all of the Properties the resource Item + * will have on creation. The Property 'Name' will be created and populated automatically, even if not declared. + * @return a PropertyDescriptionList - an arraylist of PropertyDescriptions + * @throws Exception + */ + public PropertyDescriptionList getPropDesc() throws Exception; + + /** The directory context to search for existing resources. The name of the resource must be unique below this point. + * @return Root path + */ + public DomainPath getTypeRoot(); + + public String getName(); + +} -- cgit v1.2.3 From b870cda6389d3efcdb8018eb13aaa77186e9fdfe Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Fri, 4 Apr 2014 12:53:34 +0200 Subject: AbstractMain with config file checking got lost from previous commit. Refs #177 --- .../java/com/c2kernel/process/AbstractMain.java | 70 +++++++++------------- 1 file changed, 27 insertions(+), 43 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/process/AbstractMain.java b/src/main/java/com/c2kernel/process/AbstractMain.java index 03807f0..b594c1a 100644 --- a/src/main/java/com/c2kernel/process/AbstractMain.java +++ b/src/main/java/com/c2kernel/process/AbstractMain.java @@ -29,54 +29,31 @@ abstract public class AbstractMain { public static boolean runningAsWrapper = false; - /************************************************************************** - * - **************************************************************************/ - static protected void usage() - { - System.out.println(); - System.out.println("USAGE: com.c2kernel.process.AbstractMain \n" + - " -config \n" + - " [-connect ] (or LocalCentre in conf)\n" + - " [-h] [-help] \n" + - " [-logLevel 0-19] \n" + - " [-logFile ]"); - Logger.die("Initialisation error"); - } /************************************************************************** * reading and setting input paramaters **************************************************************************/ - public static Properties readC2KArgs( String[] args ) { + public static Properties readC2KArgs( String[] args ) throws Exception { Properties c2kProps; Properties argProps = new Properties(); int logLevel = 0; PrintStream logStream = System.out; - if (args == null) return argProps; - int i = 0; while( i < args.length ) { if (args[i].startsWith("-") && args[i].length()>1) { String key = args[i].substring(1); - if (argProps.containsKey(key)) { - System.err.println("Argument "+args[i]+" given twice"); - usage(); - } + if (argProps.containsKey(key)) + throw new Exception("Argument "+args[i]+" given twice"); String value = ""; if (!args[i+1].startsWith("-")) value = args[++i]; argProps.put(key, value); i++; } - else { - System.err.println("Bad argument: "+args[i]); - usage(); - } - } - - if( argProps.containsKey("h") || argProps.containsKey("help")) { - usage(); + else + throw new Exception("Bad argument: "+args[i]); + } if (argProps.containsKey("logFile")) @@ -84,7 +61,7 @@ abstract public class AbstractMain logStream = new PrintStream(new FileOutputStream(argProps.getProperty("logFile"), true)); } catch (FileNotFoundException e) { e.printStackTrace(); - System.err.println("Logfile "+argProps.getProperty("logFile")+" cannot be created"); + throw new Exception("Logfile "+argProps.getProperty("logFile")+" cannot be created"); } // Set up log stream @@ -100,9 +77,11 @@ abstract public class AbstractMain } String configPath = argProps.getProperty("config"); - if (configPath == null || !new File(configPath).exists()) { - System.err.println("Config file "+configPath+" not found"); - } + if (configPath == null) + throw new Exception("Config file not specified"); + + if (!new File(configPath).exists()) + throw new Exception("Config file "+configPath+" not found"); else Logger.msg(0, "Config file: "+configPath); @@ -110,17 +89,22 @@ abstract public class AbstractMain c2kProps = FileStringUtility.loadConfigFile(argProps.getProperty("config") ); c2kProps.putAll(argProps); // args overlap config - if (c2kProps.containsKey("connect")) { - String connectFile = c2kProps.getProperty("connect"); + String connectFile = c2kProps.getProperty("connect"); + if (connectFile == null) + throw new Exception("Connect file not specified"); + + if (!new File(connectFile).exists()) + throw new Exception("Connect file "+connectFile+" not found"); + else Logger.msg(0, "Connect file: "+connectFile); - FileStringUtility.appendConfigFile( c2kProps, connectFile); - - if (!c2kProps.containsKey("LocalCentre")) { - String connectFileName = new File(connectFile).getName(); - String centreId = connectFileName.substring(0, connectFileName.lastIndexOf(".clc")); - c2kProps.setProperty("LocalCentre", centreId); - } - } + + FileStringUtility.appendConfigFile( c2kProps, connectFile); + + if (!c2kProps.containsKey("LocalCentre")) { + String connectFileName = new File(connectFile).getName(); + String centreId = connectFileName.substring(0, connectFileName.lastIndexOf(".clc")); + c2kProps.setProperty("LocalCentre", centreId); + } c2kProps.putAll(argProps); // args override connect file too Logger.msg(7, "AbstractMain::standardSetUp() - readC2KArgs() DONE."); -- cgit v1.2.3 From c672fa9d426beb92d9149ebc32c9cdf9bece7845 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Fri, 4 Apr 2014 13:34:58 +0200 Subject: When generating the next SystemKey in NextKeyManager, make sure that there is nothing already in the storage for that key. This prevents data loss when the LDAP is out-of-sync with the storages. Fixes #179 --- src/main/java/com/c2kernel/lookup/NextKeyManager.java | 13 +++++++++++++ .../com/c2kernel/persistency/ClusterStorageManager.java | 2 +- 2 files changed, 14 insertions(+), 1 deletion(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/lookup/NextKeyManager.java b/src/main/java/com/c2kernel/lookup/NextKeyManager.java index fd873fd..a4ead4b 100644 --- a/src/main/java/com/c2kernel/lookup/NextKeyManager.java +++ b/src/main/java/com/c2kernel/lookup/NextKeyManager.java @@ -2,6 +2,9 @@ package com.c2kernel.lookup; import com.c2kernel.common.ObjectCannotBeUpdated; import com.c2kernel.common.ObjectNotFoundException; +import com.c2kernel.persistency.ClusterStorageException; +import com.c2kernel.process.Gateway; +import com.c2kernel.utils.Logger; import com.novell.ldap.LDAPEntry; /************************************************************************** @@ -35,6 +38,16 @@ public class NextKeyManager { } catch (InvalidEntityPathException ex) { throw new ObjectCannotBeUpdated("Invalid syskey "+(lastKey.getSysKey()+1)+". Maybe centre is full."); } + //test that storage is empty for that key + try { + if (Gateway.getStorage().getClusterContents(lastKey.getSysKey(), "").length > 0) + throw new ObjectCannotBeUpdated("NextKeyManager: Storage already contains data for syskey "+lastKey.getSysKey()+ + ". Storage is out of sync with nextkey. Please contact an administrator", ""); + } catch (ClusterStorageException e) { + Logger.error(e); + throw new ObjectCannotBeUpdated("Could not check storage for prior data for the next generated systemKey: "+e.getMessage()); + } + //set the last key writeLastEntityKey(lastKey.getSysKey()); diff --git a/src/main/java/com/c2kernel/persistency/ClusterStorageManager.java b/src/main/java/com/c2kernel/persistency/ClusterStorageManager.java index 402c466..0546bab 100644 --- a/src/main/java/com/c2kernel/persistency/ClusterStorageManager.java +++ b/src/main/java/com/c2kernel/persistency/ClusterStorageManager.java @@ -173,7 +173,7 @@ public class ClusterStorageManager { } } } catch (ClusterStorageException e) { - Logger.error("ClusterStorageManager.getClusterContents() - reader " + thisReader.getName() + + Logger.msg(5, "ClusterStorageManager.getClusterContents() - reader " + thisReader.getName() + " could not retrieve contents of " + sysKey + "/" + path + ": " + e.getMessage()); } } -- cgit v1.2.3 From 11e7a9aaed7c22ec93a791ea752e159b4b120e4e Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Fri, 4 Apr 2014 17:26:10 +0200 Subject: Module XML now supports a workflowVer attribute for the Item element. If not given, it assumed version 0, as per the previous behaviour. Fixes #180 --- .../predefined/entitycreation/NewItem.java | 23 +++++++++++++++++----- src/main/java/com/c2kernel/process/Bootstrap.java | 2 +- .../java/com/c2kernel/process/module/Module.java | 2 +- src/main/resources/boot/OD/Module.xsd | 4 +++- src/main/resources/mapFiles/NewEntityMap.xml | 3 +++ 5 files changed, 26 insertions(+), 8 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java index 5f8cf12..07b8462 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java @@ -39,6 +39,7 @@ public class NewItem extends ModuleImport { public String initialPath; public String workflow; + public Integer workflowVer; public ArrayList properties = new ArrayList(); public ArrayList aggregationList = new ArrayList(); public ArrayList dependencyList = new ArrayList(); @@ -48,11 +49,12 @@ public class NewItem extends ModuleImport { public NewItem() { } - public NewItem(String name, String initialPath, String wf) { + public NewItem(String name, String initialPath, String wf, int wfVer) { this(); this.name = name; this.initialPath = initialPath; this.workflow = wf; + this.workflowVer = wfVer; } public void setNamespace(String ns) { @@ -82,11 +84,22 @@ public class NewItem extends ModuleImport { // set the name property properties.add(new Property("Name", name, true)); - // init the new item + // find workflow def + CompositeActivityDef compact; + // default workflow version is 0 if not given + int usedWfVer; + if (workflowVer == null) usedWfVer = 0; + else usedWfVer = workflowVer.intValue(); try { - - // find workflow def - CompositeActivityDef compact = (CompositeActivityDef)LocalObjectLoader.getActDef(workflow, 0); + compact = (CompositeActivityDef)LocalObjectLoader.getActDef(workflow, usedWfVer); + } catch (ObjectNotFoundException ex) { + throw new CannotManageException("Could not find workflow "+workflow+"v"+usedWfVer+" for item "+domPath, ""); + } catch (InvalidDataException e) { + throw new CannotManageException("Workflow def "+workflow+" v"+usedWfVer+" for item "+domPath+" was not valid", ""); + } + + try { + // initialise the new item with workflow and properties newItem.initialise( agentId, Gateway.getMarshaller().marshall(new PropertyArrayList(properties)), diff --git a/src/main/java/com/c2kernel/process/Bootstrap.java b/src/main/java/com/c2kernel/process/Bootstrap.java index df8ced7..a750b3f 100644 --- a/src/main/java/com/c2kernel/process/Bootstrap.java +++ b/src/main/java/com/c2kernel/process/Bootstrap.java @@ -183,7 +183,7 @@ public class Bootstrap } // data was missing or doesn't match - Logger.msg("Bootstrap.verifyResource() - Writing new "+newOutcome.getSchemaType()+"version "+version+" to "+typeImpHandler.getName()+" "+itemName); + Logger.msg("Bootstrap.verifyResource() - Writing new "+newOutcome.getSchemaType()+" v"+version+" to "+typeImpHandler.getName()+" "+itemName); History hist = new History(thisProxy.getSystemKey(), thisProxy); Transition predefDone = new Transition(0, "Done", 0, 0); Event newEvent = hist.addEvent("system", "Admin", "Bootstrap", "Bootstrap", "Bootstrap", newOutcome.getSchemaType(), 0, "PredefinedStep", 0, predefDone, String.valueOf(version)); diff --git a/src/main/java/com/c2kernel/process/module/Module.java b/src/main/java/com/c2kernel/process/module/Module.java index a7c707e..3e8ab2a 100644 --- a/src/main/java/com/c2kernel/process/module/Module.java +++ b/src/main/java/com/c2kernel/process/module/Module.java @@ -51,7 +51,7 @@ public class Module { } public void addModuleItem(String moduleXML) { - NewItem moduleItem = new NewItem(name, "/desc/modules/", "ModuleWorkflow"); + NewItem moduleItem = new NewItem(name, "/desc/modules/", "ModuleWorkflow", 0); // Module properties moduleItem.properties.add(new com.c2kernel.property.Property("Namespace", ns, false)); moduleItem.properties.add(new com.c2kernel.property.Property("Name", name, false)); diff --git a/src/main/resources/boot/OD/Module.xsd b/src/main/resources/boot/OD/Module.xsd index 882b374..d25352e 100644 --- a/src/main/resources/boot/OD/Module.xsd +++ b/src/main/resources/boot/OD/Module.xsd @@ -150,7 +150,9 @@ + use="required" /> + diff --git a/src/main/resources/mapFiles/NewEntityMap.xml b/src/main/resources/mapFiles/NewEntityMap.xml index 239fa21..84c4ce7 100644 --- a/src/main/resources/mapFiles/NewEntityMap.xml +++ b/src/main/resources/mapFiles/NewEntityMap.xml @@ -11,6 +11,9 @@ + + + -- cgit v1.2.3 From a399f7cb69c94f02a7942147a9c4766a0d5152e3 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Wed, 9 Apr 2014 11:48:45 +0200 Subject: BadArgumentsException - more specific exception thrown by readC2KArgs when the arguments are wrong. --- src/main/java/com/c2kernel/process/AbstractMain.java | 17 +++++++++-------- .../process/resource/BadArgumentsException.java | 17 +++++++++++++++++ src/test/java/LauncherTest.java | 9 +++++---- 3 files changed, 31 insertions(+), 12 deletions(-) create mode 100644 src/main/java/com/c2kernel/process/resource/BadArgumentsException.java (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/process/AbstractMain.java b/src/main/java/com/c2kernel/process/AbstractMain.java index b594c1a..e241ee2 100644 --- a/src/main/java/com/c2kernel/process/AbstractMain.java +++ b/src/main/java/com/c2kernel/process/AbstractMain.java @@ -17,6 +17,7 @@ import java.io.PrintStream; import java.util.Enumeration; import java.util.Properties; +import com.c2kernel.process.resource.BadArgumentsException; import com.c2kernel.utils.FileStringUtility; import com.c2kernel.utils.Logger; @@ -33,7 +34,7 @@ abstract public class AbstractMain /************************************************************************** * reading and setting input paramaters **************************************************************************/ - public static Properties readC2KArgs( String[] args ) throws Exception { + public static Properties readC2KArgs( String[] args ) throws BadArgumentsException { Properties c2kProps; Properties argProps = new Properties(); int logLevel = 0; @@ -44,7 +45,7 @@ abstract public class AbstractMain if (args[i].startsWith("-") && args[i].length()>1) { String key = args[i].substring(1); if (argProps.containsKey(key)) - throw new Exception("Argument "+args[i]+" given twice"); + throw new BadArgumentsException("Argument "+args[i]+" given twice"); String value = ""; if (!args[i+1].startsWith("-")) value = args[++i]; @@ -52,7 +53,7 @@ abstract public class AbstractMain i++; } else - throw new Exception("Bad argument: "+args[i]); + throw new BadArgumentsException("Bad argument: "+args[i]); } @@ -61,7 +62,7 @@ abstract public class AbstractMain logStream = new PrintStream(new FileOutputStream(argProps.getProperty("logFile"), true)); } catch (FileNotFoundException e) { e.printStackTrace(); - throw new Exception("Logfile "+argProps.getProperty("logFile")+" cannot be created"); + throw new BadArgumentsException("Logfile "+argProps.getProperty("logFile")+" cannot be created"); } // Set up log stream @@ -78,10 +79,10 @@ abstract public class AbstractMain String configPath = argProps.getProperty("config"); if (configPath == null) - throw new Exception("Config file not specified"); + throw new BadArgumentsException("Config file not specified"); if (!new File(configPath).exists()) - throw new Exception("Config file "+configPath+" not found"); + throw new BadArgumentsException("Config file "+configPath+" not found"); else Logger.msg(0, "Config file: "+configPath); @@ -91,10 +92,10 @@ abstract public class AbstractMain String connectFile = c2kProps.getProperty("connect"); if (connectFile == null) - throw new Exception("Connect file not specified"); + throw new BadArgumentsException("Connect file not specified"); if (!new File(connectFile).exists()) - throw new Exception("Connect file "+connectFile+" not found"); + throw new BadArgumentsException("Connect file "+connectFile+" not found"); else Logger.msg(0, "Connect file: "+connectFile); diff --git a/src/main/java/com/c2kernel/process/resource/BadArgumentsException.java b/src/main/java/com/c2kernel/process/resource/BadArgumentsException.java new file mode 100644 index 0000000..c7fe7cf --- /dev/null +++ b/src/main/java/com/c2kernel/process/resource/BadArgumentsException.java @@ -0,0 +1,17 @@ +package com.c2kernel.process.resource; + +public class BadArgumentsException extends Exception { + + public BadArgumentsException() { + super(); + } + + public BadArgumentsException(String message) { + super(message); + } + + public BadArgumentsException(Throwable cause) { + super(cause); + } + +} diff --git a/src/test/java/LauncherTest.java b/src/test/java/LauncherTest.java index 39c2b6e..8abba93 100644 --- a/src/test/java/LauncherTest.java +++ b/src/test/java/LauncherTest.java @@ -1,6 +1,7 @@ import java.util.Properties; import com.c2kernel.process.AbstractMain; +import com.c2kernel.process.resource.BadArgumentsException; import com.c2kernel.utils.Logger; @@ -40,7 +41,7 @@ public class LauncherTest { try { props = AbstractMain.readC2KArgs(args); throw new Exception("Invalid connect file not detected"); - } catch (Exception ex) { } + } catch (BadArgumentsException ex) { } } public void testWrongConnectFileName() throws Exception { @@ -49,7 +50,7 @@ public class LauncherTest { try { props = AbstractMain.readC2KArgs(args); throw new Exception("Invalid connect file not detected"); - } catch (Exception ex) { } + } catch (BadArgumentsException ex) { } } public void testMissingConnectArg() throws Exception { @@ -59,7 +60,7 @@ public class LauncherTest { try { props = AbstractMain.readC2KArgs(args); throw new Exception("Missing connect file not detected"); - } catch (Exception ex) { } + } catch (BadArgumentsException ex) { } } public void testMissingConfigArg() throws Exception { @@ -69,6 +70,6 @@ public class LauncherTest { try { props = AbstractMain.readC2KArgs(args); throw new Exception("Missing config file not detected"); - } catch (Exception ex) { } + } catch (BadArgumentsException ex) { } } } -- cgit v1.2.3 From c7f54d570ab6a8a3c3ba1db6045d003f988f191d Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Wed, 9 Apr 2014 11:50:42 +0200 Subject: ResourceLoader.getModuleDefURLs interface method to allow the ResourceLoader to specify exactly where the module.xml files come from. Dumpc2kProps cleanup --- src/main/java/com/c2kernel/process/Gateway.java | 8 ++------ src/main/java/com/c2kernel/process/resource/Resource.java | 6 ++++++ src/main/java/com/c2kernel/process/resource/ResourceLoader.java | 3 +++ 3 files changed, 11 insertions(+), 6 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/process/Gateway.java b/src/main/java/com/c2kernel/process/Gateway.java index 0d9dbe6..ea49ded 100644 --- a/src/main/java/com/c2kernel/process/Gateway.java +++ b/src/main/java/com/c2kernel/process/Gateway.java @@ -108,7 +108,7 @@ public class Gateway // init module manager try { - mModules = new ModuleManager(ClassLoader.getSystemResources("META-INF/cristal/module.xml"), AbstractMain.runningAsWrapper); + mModules = new ModuleManager(mResource.getModuleDefURLs(), AbstractMain.runningAsWrapper); } catch (Exception e) { Logger.error(e); throw new InvalidDataException("Could not load module definitions.", ""); @@ -437,11 +437,7 @@ public class Gateway static public void dumpC2KProps(int logLevel) { if (!Logger.doLog(logLevel)) return; - Logger.msg(logLevel, "C2K Properties:"); - for (Enumeration e = propertyNames(); e.hasMoreElements();) { - String name = (String) e.nextElement(); - Logger.msg(" "+name+": "+getProperty(name)); - } + mC2KProps.dumpProps(logLevel); } static public ObjectProperties getProperties() { diff --git a/src/main/java/com/c2kernel/process/resource/Resource.java b/src/main/java/com/c2kernel/process/resource/Resource.java index 4d07f35..2ee95c5 100644 --- a/src/main/java/com/c2kernel/process/resource/Resource.java +++ b/src/main/java/com/c2kernel/process/resource/Resource.java @@ -3,6 +3,7 @@ package com.c2kernel.process.resource; //Java import java.net.MalformedURLException; import java.net.URL; +import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; @@ -160,4 +161,9 @@ public class Resource implements ResourceLoader { throw new ObjectNotFoundException(e.getMessage(),null); } } + + @Override + public Enumeration getModuleDefURLs() throws Exception { + return ClassLoader.getSystemResources("META-INF/cristal/module.xml"); + } } diff --git a/src/main/java/com/c2kernel/process/resource/ResourceLoader.java b/src/main/java/com/c2kernel/process/resource/ResourceLoader.java index fdf2508..2bbc4d1 100644 --- a/src/main/java/com/c2kernel/process/resource/ResourceLoader.java +++ b/src/main/java/com/c2kernel/process/resource/ResourceLoader.java @@ -2,6 +2,7 @@ package com.c2kernel.process.resource; import java.net.MalformedURLException; import java.net.URL; +import java.util.Enumeration; import java.util.HashMap; import com.c2kernel.common.InvalidDataException; @@ -38,4 +39,6 @@ public interface ResourceLoader { public Class getClassForName(String name) throws ClassNotFoundException; + public Enumeration getModuleDefURLs() throws Exception; + } \ No newline at end of file -- cgit v1.2.3 From 2da70c5647f883994d58f7be0d68b0b5e334c72c Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Wed, 9 Apr 2014 11:51:20 +0200 Subject: Merge module properties as the loading order is established, so that they override each other in the correct order. --- .../java/com/c2kernel/process/module/ModuleManager.java | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/process/module/ModuleManager.java b/src/main/java/com/c2kernel/process/module/ModuleManager.java index 3cb4904..9ff42e5 100644 --- a/src/main/java/com/c2kernel/process/module/ModuleManager.java +++ b/src/main/java/com/c2kernel/process/module/ModuleManager.java @@ -54,11 +54,6 @@ public class ModuleManager { if (moduleNs.contains(newModule.getNs())) throw new ModuleException("Module namespace clash: "+newModule.getNs()); Logger.debug(4, "Module found: "+newModule.getNs()+" - "+newModule.getName()); loadedModules.add(newModule.getName()); moduleNs.add(newModule.getNs()); - Properties modProp = newModule.getProperties(isServer); - for (Enumeration e = modProp.propertyNames(); e.hasMoreElements();) { - String propName = (String)e.nextElement(); - props.put(propName, modProp.get(propName)); - } } catch (ModuleException e) { Logger.error("Could not load module description from "+newModuleURL); throw e; @@ -69,7 +64,7 @@ public class ModuleManager { } Logger.debug(5, "Checking dependencies"); - boolean allDepsPresent = false; + boolean allDepsPresent = true; ArrayList prevModules = new ArrayList(); for (int i=0; i e = modProp.propertyNames(); e.hasMoreElements();) { + String propName = (String)e.nextElement(); + props.put(propName, modProp.get(propName)); + } prevModules.add(thisMod.getName()); } - if (allDepsPresent) Logger.die("Unmet module dependencies. Cannot continue"); + if (!allDepsPresent) Logger.die("Unmet module dependencies. Cannot continue"); } public String getModuleVersions() { -- cgit v1.2.3 From 6f1332fb24e04b6970fc636788d219ac0d133e9a Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Wed, 9 Apr 2014 11:51:51 +0200 Subject: Improve property dumping, using Object.toString and giving the property class. --- src/main/java/com/c2kernel/utils/ObjectProperties.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/utils/ObjectProperties.java b/src/main/java/com/c2kernel/utils/ObjectProperties.java index 79aee78..dd4a59d 100644 --- a/src/main/java/com/c2kernel/utils/ObjectProperties.java +++ b/src/main/java/com/c2kernel/utils/ObjectProperties.java @@ -144,11 +144,10 @@ public class ObjectProperties extends Properties { } public void dumpProps(int logLevel) { - if (!Logger.doLog(logLevel)) return; Logger.msg(logLevel, "Properties:"); for (Enumeration e = propertyNames(); e.hasMoreElements();) { String name = (String) e.nextElement(); - Logger.msg(" "+name+": "+getProperty(name)); + Logger.msg(" "+name+" ("+getObject(name).getClass().getSimpleName()+"): "+getObject(name).toString()); } } -- cgit v1.2.3 From c85dc62591ab2ce9eec3fd93004ba474f7b1fb19 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Wed, 9 Apr 2014 23:17:03 +0200 Subject: Expanded server predefined steps to include server and agent maintenance steps. Fixes #174 --- .../lifecycle/instance/predefined/Erase.java | 8 +-- .../instance/predefined/PredefinedStep.java | 13 +++- .../predefined/PredefinedStepContainer.java | 2 - .../predefined/ServerPredefinedStepContainer.java | 21 ++++-- .../predefined/entitycreation/CreateNewAgent.java | 1 + .../predefined/entitycreation/CreateNewItem.java | 1 + .../predefined/server/AddDomainContext.java | 48 ++++++++++++++ .../instance/predefined/server/RemoveAgent.java | 61 ++++++++++++++++++ .../predefined/server/RemoveDomainContext.java | 41 ++++++++++++ .../predefined/server/SetAgentPassword.java | 52 +++++++++++++++ .../instance/predefined/server/SetAgentRoles.java | 74 ++++++++++++++++++++++ src/main/java/com/c2kernel/lookup/LDAPLookup.java | 12 ++-- .../java/com/c2kernel/lookup/LDAPRoleManager.java | 13 ++++ src/test/resources/NewServerPredefStepTest.js | 12 ++++ 14 files changed, 338 insertions(+), 21 deletions(-) create mode 100644 src/main/java/com/c2kernel/lifecycle/instance/predefined/server/AddDomainContext.java create mode 100644 src/main/java/com/c2kernel/lifecycle/instance/predefined/server/RemoveAgent.java create mode 100644 src/main/java/com/c2kernel/lifecycle/instance/predefined/server/RemoveDomainContext.java create mode 100644 src/main/java/com/c2kernel/lifecycle/instance/predefined/server/SetAgentPassword.java create mode 100644 src/main/java/com/c2kernel/lifecycle/instance/predefined/server/SetAgentRoles.java create mode 100644 src/test/resources/NewServerPredefStepTest.js (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/Erase.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/Erase.java index 305128b..0f3a246 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/Erase.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/Erase.java @@ -20,9 +20,7 @@ import com.c2kernel.lookup.AgentPath; import com.c2kernel.lookup.DomainPath; import com.c2kernel.lookup.EntityPath; import com.c2kernel.lookup.Path; -import com.c2kernel.persistency.ClusterStorage; import com.c2kernel.process.Gateway; -import com.c2kernel.property.Property; import com.c2kernel.utils.Logger; @@ -48,12 +46,8 @@ public class Erase extends PredefinedStep try { - // FIXME: This should search for the entity key. Name shouldn't be unique. - // find entity name - Property name = (Property)Gateway.getStorage().get(itemSysKey, ClusterStorage.PROPERTY+"/Name", null); - // get all domain paths - Enumeration domPaths = Gateway.getLDAPLookup().search(new DomainPath(), name.getValue()); + Enumeration domPaths = Gateway.getLDAPLookup().searchAliases(new EntityPath(itemSysKey)); while (domPaths.hasMoreElements()) { DomainPath path = (DomainPath)domPaths.nextElement(); // delete them diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/PredefinedStep.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/PredefinedStep.java index 3cf73ba..d0fde2a 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/PredefinedStep.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/PredefinedStep.java @@ -26,6 +26,15 @@ public abstract class PredefinedStep extends Activity ******************************************************************************************************************************************************************************************************************************************************************************************************/ private boolean isPredefined = false; + public static final int DONE = 0; + public static final int AVAILABLE = 0; + + public PredefinedStep() { + super(); + getProperties().put("SchemaType", "PredefinedStepOutcome"); + getProperties().put("SchemaVersion", "0"); + } + @Override public boolean getActive() { @@ -35,8 +44,8 @@ public abstract class PredefinedStep extends Activity return super.getActive(); } - public static final int DONE = 0; - public static final int AVAILABLE = 0; + + @Override protected String getDefaultSMName() { return "PredefinedStep"; diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/PredefinedStepContainer.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/PredefinedStepContainer.java index bfab876..43cc8ca 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/PredefinedStepContainer.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/PredefinedStepContainer.java @@ -37,8 +37,6 @@ public class PredefinedStepContainer extends CompositeActivity act.setName(alias); act.setType(alias); act.getProperties().put("Description", Description); - act.getProperties().put("SchemaType", "PredefinedStepOutcome"); - act.getProperties().put("SchemaVersion", "0"); act.setCentrePoint(new GraphPoint()); act.setIsPredefined(true); addChild(act, new GraphPoint(100, 75 * ++num)); diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/ServerPredefinedStepContainer.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/ServerPredefinedStepContainer.java index d11c05b..667ae5d 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/ServerPredefinedStepContainer.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/ServerPredefinedStepContainer.java @@ -3,6 +3,11 @@ package com.c2kernel.lifecycle.instance.predefined; import com.c2kernel.graph.model.GraphPoint; import com.c2kernel.lifecycle.instance.predefined.entitycreation.CreateNewAgent; import com.c2kernel.lifecycle.instance.predefined.entitycreation.CreateNewItem; +import com.c2kernel.lifecycle.instance.predefined.server.AddDomainContext; +import com.c2kernel.lifecycle.instance.predefined.server.RemoveAgent; +import com.c2kernel.lifecycle.instance.predefined.server.RemoveDomainContext; +import com.c2kernel.lifecycle.instance.predefined.server.SetAgentPassword; +import com.c2kernel.lifecycle.instance.predefined.server.SetAgentRoles; /************************************************************************** * @@ -21,18 +26,22 @@ public class ServerPredefinedStepContainer extends PredefinedStepContainer { public void createChildren() { super.createChildren(); - serverPredInit("CreateNewItem", "Creates a new Item in this Server without description.", new CreateNewItem(), "NewItem"); - serverPredInit("CreateNewAgent", "Creates a new Agent in this Server without description.", new CreateNewAgent(), "NewAgent"); + serverPredInit("CreateNewItem", "Creates a new Item in this Server without description.", new CreateNewItem()); + serverPredInit("CreateNewAgent", "Creates a new Agent in this Server without description.", new CreateNewAgent()); + serverPredInit("RemoveDomainContext", "Deletes an existing context in the domain tree, but only if empty", new RemoveDomainContext()); + serverPredInit("AddDomainContext", "Creates an empty domain context in the tree", new AddDomainContext()); + //TODO: remove the following when agents have workflows + serverPredInit("RemoveAgent", "Deletes the named Agent in this Server.", new RemoveAgent()); + serverPredInit("SetAgentPassword", "Changes the named Agent's password in this Server.", new SetAgentPassword()); + serverPredInit("SetAgentRoles", "Sets the roles of the named Agent.", new SetAgentRoles()); } - public void serverPredInit(String alias, String Description, PredefinedStep act, String schema) + public void serverPredInit(String alias, String Description, PredefinedStep act) { act.setName(alias); act.setType(alias); act.getProperties().put("Description", Description); - act.getProperties().put("SchemaType", schema); - act.getProperties().put("SchemaVersion", "0"); - act.getProperties().put("AgentRole", "Admin"); + act.getProperties().put("Agent Role", "Admin"); act.setCentrePoint(new GraphPoint()); act.setIsPredefined(true); addChild(act, new GraphPoint(100, 75 * ++num)); diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewAgent.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewAgent.java index b85cbc3..7715e2a 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewAgent.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewAgent.java @@ -18,6 +18,7 @@ public class CreateNewAgent extends PredefinedStep public CreateNewAgent() { super(); + getProperties().put("SchemaType", "Agent"); } //requestdata is xmlstring diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewItem.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewItem.java index 2db4fe6..bddb39f 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewItem.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewItem.java @@ -21,6 +21,7 @@ public class CreateNewItem extends PredefinedStep public CreateNewItem() { super(); + getProperties().put("SchemaType", "Item"); } //requestdata is xmlstring diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/AddDomainContext.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/AddDomainContext.java new file mode 100644 index 0000000..7595711 --- /dev/null +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/AddDomainContext.java @@ -0,0 +1,48 @@ +package com.c2kernel.lifecycle.instance.predefined.server; + +import java.util.Stack; + +import com.c2kernel.common.InvalidDataException; +import com.c2kernel.common.ObjectAlreadyExistsException; +import com.c2kernel.common.ObjectCannotBeUpdated; +import com.c2kernel.lifecycle.instance.predefined.PredefinedStep; +import com.c2kernel.lookup.AgentPath; +import com.c2kernel.lookup.DomainPath; +import com.c2kernel.process.Gateway; +import com.c2kernel.utils.Logger; + +public class AddDomainContext extends PredefinedStep { + + public AddDomainContext() { + super(); + } + + @Override + protected String runActivityLogic(AgentPath agent, int itemSysKey, + int transitionID, String requestData) throws InvalidDataException { + + Logger.msg(1, "AddDomainContext::request() - Starting."); + + DomainPath pathToAdd = new DomainPath(getDataList(requestData)[0]); + if (pathToAdd.exists()) + throw new InvalidDataException("Context "+pathToAdd+" already exists", ""); + // collect parent paths if they don't exist + Stack pathsToAdd = new Stack(); + while(pathToAdd!= null && !pathToAdd.exists()) { + pathsToAdd.push(pathToAdd); + pathToAdd = pathToAdd.getParent(); + } + while(!pathsToAdd.empty()) { + pathToAdd = pathsToAdd.pop(); + try { + Gateway.getLDAPLookup().add(pathToAdd); + } catch (ObjectAlreadyExistsException e) { + Logger.error("Context "+pathToAdd+" inconsistently exists."); + } catch (ObjectCannotBeUpdated e) { + Logger.error(e); + throw new InvalidDataException("Exception adding path "+pathToAdd+": "+e.getMessage(), ""); + } + } + return requestData; + } +} diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/RemoveAgent.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/RemoveAgent.java new file mode 100644 index 0000000..75fe80b --- /dev/null +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/RemoveAgent.java @@ -0,0 +1,61 @@ +package com.c2kernel.lifecycle.instance.predefined.server; + +import com.c2kernel.common.InvalidDataException; +import com.c2kernel.common.ObjectCannotBeUpdated; +import com.c2kernel.common.ObjectNotFoundException; +import com.c2kernel.lifecycle.instance.predefined.PredefinedStep; +import com.c2kernel.lookup.AgentPath; +import com.c2kernel.lookup.RolePath; +import com.c2kernel.persistency.ClusterStorageException; +import com.c2kernel.process.Gateway; +import com.c2kernel.utils.Logger; + +public class RemoveAgent extends PredefinedStep { + + public RemoveAgent() { + super(); + } + + @Override + protected String runActivityLogic(AgentPath agent, int itemSysKey, + int transitionID, String requestData) throws InvalidDataException { + + Logger.msg(1, "RemoveAgent::request() - Starting."); + + String[] params = getDataList(requestData); + AgentPath targetAgent; + try { + targetAgent = Gateway.getLDAPLookup().getRoleManager().getAgentPath(params[0]); + } catch (ObjectNotFoundException e) { + throw new InvalidDataException("Agent "+params[0]+" not found", ""); + } + //remove from roles + for (RolePath role: targetAgent.getRoles()) { + try { + role.removeAgent(targetAgent); + } catch (ObjectCannotBeUpdated e) { + Logger.error(e); + throw new InvalidDataException("Error removing "+params[0]+" from Role "+role.getName(), ""); + } catch (ObjectNotFoundException e) { + Logger.error(e); + throw new InvalidDataException("Tried to remove "+params[0]+" from Role "+role.getName()+" that doesn't exist.", ""); + } + } + //clear out all storages + try { + Gateway.getStorage().removeCluster(targetAgent.getSysKey(), "", null); + } catch (ClusterStorageException e) { + Logger.error(e); + throw new InvalidDataException("Error deleting storage for "+params[0], ""); + } + //remove entity path + try { + Gateway.getLDAPLookup().delete(targetAgent); + } catch (ObjectCannotBeUpdated e) { + throw new InvalidDataException("Error deleting AgentPath for "+params[0], ""); + } + return requestData; + + } + +} diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/RemoveDomainContext.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/RemoveDomainContext.java new file mode 100644 index 0000000..77a7545 --- /dev/null +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/RemoveDomainContext.java @@ -0,0 +1,41 @@ +package com.c2kernel.lifecycle.instance.predefined.server; + +import com.c2kernel.common.InvalidDataException; +import com.c2kernel.common.ObjectCannotBeUpdated; +import com.c2kernel.common.ObjectNotFoundException; +import com.c2kernel.lifecycle.instance.predefined.PredefinedStep; +import com.c2kernel.lookup.AgentPath; +import com.c2kernel.lookup.DomainPath; +import com.c2kernel.process.Gateway; +import com.c2kernel.utils.Logger; + +public class RemoveDomainContext extends PredefinedStep { + public RemoveDomainContext() { + super(); + } + + @Override + protected String runActivityLogic(AgentPath agent, int itemSysKey, + int transitionID, String requestData) throws InvalidDataException { + + Logger.msg(1, "RemoveDomainContext::request() - Starting."); + + DomainPath pathToDelete = new DomainPath(getDataList(requestData)[0]); + if (!pathToDelete.exists()) + throw new InvalidDataException("Context "+pathToDelete+" does not exist", ""); + try { + pathToDelete.getEntity(); + throw new InvalidDataException("Path "+pathToDelete+" is an Entity. Use its own Erase step instead, or RemoveAgent.", ""); + } catch (ObjectNotFoundException ex) { } + if (pathToDelete.getChildren().hasMoreElements()) + throw new InvalidDataException("Context "+pathToDelete+" is not empty. Cannot delete.", ""); + + try { + Gateway.getLDAPLookup().delete(pathToDelete); + } catch (ObjectCannotBeUpdated e) { + Logger.error(e); + throw new InvalidDataException("Exception deleting path"+pathToDelete+": "+e.getMessage(), ""); + } + return requestData; + } +} diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/SetAgentPassword.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/SetAgentPassword.java new file mode 100644 index 0000000..bb19030 --- /dev/null +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/SetAgentPassword.java @@ -0,0 +1,52 @@ +package com.c2kernel.lifecycle.instance.predefined.server; + +import java.security.NoSuchAlgorithmException; + +import com.c2kernel.common.InvalidDataException; +import com.c2kernel.common.ObjectCannotBeUpdated; +import com.c2kernel.common.ObjectNotFoundException; +import com.c2kernel.lifecycle.instance.predefined.PredefinedStep; +import com.c2kernel.lookup.AgentPath; +import com.c2kernel.process.Gateway; +import com.c2kernel.utils.Logger; + +public class SetAgentPassword extends PredefinedStep { + + public SetAgentPassword() { + super(); + } + + @Override + protected String runActivityLogic(AgentPath agent, int itemSysKey, + int transitionID, String requestData) throws InvalidDataException { + + Logger.msg(1, "SetAgentPassword::request() - Starting."); + + String[] params = getDataList(requestData); + if (params.length!=2) + throw new InvalidDataException("Requires 2 params: agent name and new password", ""); + AgentPath targetAgent; + try { + targetAgent = Gateway.getLDAPLookup().getRoleManager().getAgentPath(params[0]); + } catch (ObjectNotFoundException e) { + throw new InvalidDataException("Agent "+params[0]+" not found", ""); + } + + try { + Gateway.getLDAPLookup().getRoleManager().setAgentPassword(targetAgent, params[1]); + } catch (ObjectNotFoundException e) { + Logger.error(e); + throw new InvalidDataException("Agent "+params[0]+" not found.", ""); + } catch (ObjectCannotBeUpdated e) { + Logger.error(e); + throw new InvalidDataException("Error updating LDAP entry.", ""); + } catch (NoSuchAlgorithmException e) { + Logger.error(e); + throw new InvalidDataException("Cryptographic libraries for password hashing not found.", ""); + } + + params[1] = "REDACTED"; // censor user's password from outcome + return bundleData(params); + } + +} diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/SetAgentRoles.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/SetAgentRoles.java new file mode 100644 index 0000000..51be40a --- /dev/null +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/SetAgentRoles.java @@ -0,0 +1,74 @@ +package com.c2kernel.lifecycle.instance.predefined.server; + +import java.util.ArrayList; + +import com.c2kernel.common.InvalidDataException; +import com.c2kernel.common.ObjectNotFoundException; +import com.c2kernel.lifecycle.instance.predefined.PredefinedStep; +import com.c2kernel.lookup.AgentPath; +import com.c2kernel.lookup.LDAPRoleManager; +import com.c2kernel.lookup.RolePath; +import com.c2kernel.process.Gateway; +import com.c2kernel.utils.Logger; + +public class SetAgentRoles extends PredefinedStep { + + public SetAgentRoles() { + super(); + } + + @Override + protected String runActivityLogic(AgentPath agent, int itemSysKey, + int transitionID, String requestData) throws InvalidDataException { + + Logger.msg(1, "SetAgentRoles::request() - Starting."); + + String[] params = getDataList(requestData); + AgentPath targetAgent; + try { + targetAgent = Gateway.getLDAPLookup().getRoleManager().getAgentPath(params[0]); + } catch (ObjectNotFoundException e) { + throw new InvalidDataException("Agent "+params[0]+" not found", ""); + } + + LDAPRoleManager roleMan = Gateway.getLDAPLookup().getRoleManager(); + RolePath[] currentRoles = targetAgent.getRoles(); + ArrayList requestedRoles = new ArrayList(); + if (params.length>1) + for (int i=1; i rolesToRemove = new ArrayList(); + for (RolePath existingRole : currentRoles) { // + if (requestedRoles.contains(existingRole)) // if we have it, and it's requested, then it will be kept + requestedRoles.remove(existingRole); // so remove it from request - this will be left with roles to be added + else + rolesToRemove.add(existingRole); // else this role will be removed + } + + // remove roles not in new list + for (RolePath roleToRemove : rolesToRemove) + try { + roleToRemove.removeAgent(targetAgent); + } catch (Exception e) { + Logger.error(e); + throw new InvalidDataException("Error removing role "+roleToRemove.getName(), ""); + } + + // add requested roles we don't already have + for (RolePath roleToAdd : requestedRoles) + try { + roleToAdd.addAgent(targetAgent); + } catch (Exception e) { + Logger.error(e); + throw new InvalidDataException("Error adding role "+roleToAdd.getName(), ""); + } + + return requestData; + } + +} diff --git a/src/main/java/com/c2kernel/lookup/LDAPLookup.java b/src/main/java/com/c2kernel/lookup/LDAPLookup.java index 08a80b6..4ea6e68 100644 --- a/src/main/java/com/c2kernel/lookup/LDAPLookup.java +++ b/src/main/java/com/c2kernel/lookup/LDAPLookup.java @@ -352,10 +352,6 @@ public class LDAPLookup else return search(start.getFullDN(),LDAPConnection.SCOPE_SUB,"(&"+query.toString()+")",searchCons); } - - public LDAPPathSet searchType(Path start, Path type) { - return null; - } protected LDAPPathSet search(String startDN, int scope, String filter, LDAPSearchConstraints searchCons) { @@ -396,6 +392,14 @@ public class LDAPLookup searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER); return search(start.getFullDN(), LDAPConnection.SCOPE_SUB, "objectClass=aliasObject", searchCons); } + + public LDAPPathSet searchAliases(EntityPath entity) { + LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); + searchCons.setBatchSize(0); + searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER); + return search(new DomainPath().getFullDN(), LDAPConnection.SCOPE_SUB, "(&(objectClass=aliasObject)(aliasedObjectName="+ + LDAPLookupUtils.escapeDN(entity.getFullDN())+"))", searchCons); + } public boolean exists(Path path) { return LDAPLookupUtils.exists(getConnection(), path.getFullDN()); diff --git a/src/main/java/com/c2kernel/lookup/LDAPRoleManager.java b/src/main/java/com/c2kernel/lookup/LDAPRoleManager.java index b2cffc6..f40cd53 100644 --- a/src/main/java/com/c2kernel/lookup/LDAPRoleManager.java +++ b/src/main/java/com/c2kernel/lookup/LDAPRoleManager.java @@ -1,5 +1,6 @@ package com.c2kernel.lookup; +import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Enumeration; @@ -207,5 +208,17 @@ public class LDAPRoleManager { // set attribute LDAPLookupUtils.setAttributeValue(mLdap.getConnection(), roleEntry, "jobList", hasJobList?"TRUE":"FALSE"); } + + public void setAgentPassword(AgentPath agent, String newPassword) throws ObjectNotFoundException, ObjectCannotBeUpdated, NoSuchAlgorithmException { + String encPasswd = AgentPath.generateUserPassword(newPassword, "SHA"); + LDAPEntry agentEntry; + try { + agentEntry = LDAPLookupUtils.getEntry(mLdap.getConnection(), agent.getFullDN()); + } catch (ObjectNotFoundException e) { + throw new ObjectNotFoundException("Agent "+agent.getAgentName()+" does not exist", ""); + } + LDAPLookupUtils.setAttributeValue(mLdap.getConnection(), agentEntry, "userPassword", encPasswd); + + } } diff --git a/src/test/resources/NewServerPredefStepTest.js b/src/test/resources/NewServerPredefStepTest.js new file mode 100644 index 0000000..64d3d29 --- /dev/null +++ b/src/test/resources/NewServerPredefStepTest.js @@ -0,0 +1,12 @@ +var serverPath=new com.c2kernel.lookup.DomainPath("/servers/pcuwe04.cern.ch"); +var serverItem=proxy.getProxy(serverPath); + +var predef = "AddDomainContext"; var params = new Array(1); params[0] = "/test/context"; agent.execute(serverItem, predef, params); +var predef = "RemoveDomainContext"; agent.execute(serverItem, predef, params); +params[0] = "/test"; agent.execute(serverItem, predef, params); +var predef = "SetAgentPassword"; params = Array(2); params[0] = "dev"; params[1] = "hunter2"; agent.execute(serverItem, predef, params); +com.c2kernel.process.Gateway.login("dev", "hunter2"); +var predef = "SetAgentRoles"; agent.execute(serverItem, predef, params); //Role shouldn't exist +params = Array(3); params[0] = "dev"; params[1] = "Admin"; params[2] = "UserCode"; agent.execute(serverItem, predef, params); +params = Array(2); params[0] = "dev"; params[1] = "Admin"; agent.execute(serverItem, predef, params); +var predef = "RemoveAgent"; var params = new Array(1); params[0] = "dev"; agent.execute(serverItem, predef, params); -- cgit v1.2.3 From c42a902b973b1d24f2ef38cc9ed22ed0a059d13f Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Fri, 11 Apr 2014 16:57:30 +0200 Subject: OutcomeInitiator interface to create initial states of outcomes if empty in the Job. Called when job.getOutcome() is called when none exists. Viewpoint last still overrides. Fixes #47 --- src/main/java/com/c2kernel/entity/agent/Job.java | 90 +++++++++++++++++----- .../com/c2kernel/lifecycle/WfCastorHashMap.java | 1 + .../persistency/outcome/OutcomeInitiator.java | 10 +++ .../java/com/c2kernel/utils/DescriptionObject.java | 3 + 4 files changed, 86 insertions(+), 18 deletions(-) create mode 100644 src/main/java/com/c2kernel/persistency/outcome/OutcomeInitiator.java (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/entity/agent/Job.java b/src/main/java/com/c2kernel/entity/agent/Job.java index ea28e38..e3f58e5 100644 --- a/src/main/java/com/c2kernel/entity/agent/Job.java +++ b/src/main/java/com/c2kernel/entity/agent/Job.java @@ -1,5 +1,7 @@ package com.c2kernel.entity.agent; +import java.util.HashMap; + import com.c2kernel.common.InvalidDataException; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.entity.C2KLocalObject; @@ -10,7 +12,9 @@ import com.c2kernel.lookup.AgentPath; import com.c2kernel.lookup.EntityPath; import com.c2kernel.lookup.InvalidEntityPathException; import com.c2kernel.persistency.ClusterStorage; +import com.c2kernel.persistency.ClusterStorageException; import com.c2kernel.persistency.outcome.Outcome; +import com.c2kernel.persistency.outcome.OutcomeInitiator; import com.c2kernel.persistency.outcome.Schema; import com.c2kernel.persistency.outcome.Viewpoint; import com.c2kernel.process.Gateway; @@ -63,6 +67,10 @@ public class Job implements C2KLocalObject private ItemProxy item = null; private boolean outcomeSet; + + // outcome initiator cache + + static private HashMap ocInitCache = new HashMap(); /*************************************************************************** * Empty constructor for Castor @@ -273,26 +281,72 @@ public class Job implements C2KLocalObject Logger.error(e); } } + + public String getLastView() throws InvalidDataException { + String viewName = (String) getActProp("Viewpoint"); + if (viewName.length() > 0) { + // find schema + String schemaName; + try { + schemaName = getSchemaName(); + } catch (ObjectNotFoundException e1) { + throw new InvalidDataException("Schema "+getActProp("SchemaType")+" v"+getActProp("SchemaVersion")+" not found"); + } + + try { + Viewpoint view = (Viewpoint) Gateway.getStorage().get(getItemSysKey(), + ClusterStorage.VIEWPOINT + "/" + schemaName + "/" + viewName, null); + return view.getOutcome().getData(); + } catch (ObjectNotFoundException ex) { // viewpoint doesn't exist yet + return null; + } catch (ClusterStorageException e) { + Logger.error(e); + throw new InvalidDataException("ViewpointOutcomeInitiator: ClusterStorageException loading viewpoint " + + ClusterStorage.VIEWPOINT + "/" + schemaName + "/" + viewName+" in syskey "+getItemSysKey()); + } + } + else + return null; + } + + public OutcomeInitiator getOutcomeInitiator() throws InvalidDataException { + String ocInitName = (String) getActProp("OutcomeInit"); + OutcomeInitiator ocInit; + if (ocInitName.length() > 0) { + String ocPropName = "OutcomeInit."+ocInitName; + synchronized (ocInitCache) { + ocInit = ocInitCache.get(ocPropName); + if (ocInit == null) { + Object ocInitObj = Gateway.getProperties().get(ocPropName); + if (ocInitObj instanceof String) { + try { + ocInitObj = Class.forName((String)ocInitObj).newInstance(); + } catch (Exception e) { + Logger.error(e); + throw new InvalidDataException("Could not instantiate OutcomeInstantiator "+ocInitObj+" for "+ocPropName); + } + } + ocInit = (OutcomeInitiator)ocInitObj; // throw runtime class cast if it isn't one + ocInitCache.put(ocPropName, ocInit); + } + } + return ocInit; + } + else + return null; + } - public String getOutcomeString() + public String getOutcomeString() throws InvalidDataException { - if (outcomeData == null && isOutcomeRequired()) - { - String viewName = (String) getActProp("Viewpoint"); - outcomeData = null; - if (viewName.length() > 0) - try - { - Viewpoint view = (Viewpoint) Gateway.getStorage().get(getItemSysKey(), ClusterStorage.VIEWPOINT + "/" + getSchemaName() + "/" + viewName, null); - outcomeData = view.getOutcome().getData(); - outcomeSet = true; - } catch (Exception ex) - { - outcomeData = null; - outcomeSet = false; - } - - } + if (outcomeData == null && transition.hasOutcome(actProps)) { + outcomeData = getLastView(); + if (outcomeData == null) { + OutcomeInitiator ocInit = getOutcomeInitiator(); + if (ocInit != null) + outcomeData = ocInit.initOutcome(this); + } + if (outcomeData != null) outcomeSet = true; + } return outcomeData; } diff --git a/src/main/java/com/c2kernel/lifecycle/WfCastorHashMap.java b/src/main/java/com/c2kernel/lifecycle/WfCastorHashMap.java index 5a9d472..be2f043 100644 --- a/src/main/java/com/c2kernel/lifecycle/WfCastorHashMap.java +++ b/src/main/java/com/c2kernel/lifecycle/WfCastorHashMap.java @@ -23,5 +23,6 @@ public class WfCastorHashMap extends CastorHashMap put("StateMachineName", "Default"); put("StateMachineVersion", 0); put("Viewpoint", ""); + put("OutcomeInit", ""); } } diff --git a/src/main/java/com/c2kernel/persistency/outcome/OutcomeInitiator.java b/src/main/java/com/c2kernel/persistency/outcome/OutcomeInitiator.java new file mode 100644 index 0000000..82068bb --- /dev/null +++ b/src/main/java/com/c2kernel/persistency/outcome/OutcomeInitiator.java @@ -0,0 +1,10 @@ +package com.c2kernel.persistency.outcome; + +import com.c2kernel.common.InvalidDataException; +import com.c2kernel.entity.agent.Job; + +public interface OutcomeInitiator { + + public String initOutcome(Job job) throws InvalidDataException; + +} diff --git a/src/main/java/com/c2kernel/utils/DescriptionObject.java b/src/main/java/com/c2kernel/utils/DescriptionObject.java index 4d7d108..f8ba72d 100644 --- a/src/main/java/com/c2kernel/utils/DescriptionObject.java +++ b/src/main/java/com/c2kernel/utils/DescriptionObject.java @@ -4,5 +4,8 @@ public interface DescriptionObject { public String getName(); public int getVersion(); + + public void setName(String name); + public void setVersion(int version); } -- cgit v1.2.3 From 434fbb2deee42b3222aeb7a97ed24141e374e104 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Fri, 11 Apr 2014 16:57:58 +0200 Subject: Give Item name when NewItem import fails --- .../c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java index 07b8462..588b2fc 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java @@ -105,7 +105,7 @@ public class NewItem extends ModuleImport { Gateway.getMarshaller().marshall(new PropertyArrayList(properties)), Gateway.getMarshaller().marshall(compact.instantiate())); } catch (Exception ex) { - Logger.error("Error initialising new item"); + Logger.error("Error initialising new item "+name ); Logger.error(ex); throw new CannotManageException("Problem initialising new item. See server log.", ""); } -- cgit v1.2.3 From 3ee9c263ca512068d2669cdf9a10679424eb6ce2 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Fri, 11 Apr 2014 16:58:25 +0200 Subject: ProxyLoader should return null when the object is not found on the server, not propagate the exception. --- src/main/java/com/c2kernel/persistency/ProxyLoader.java | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/persistency/ProxyLoader.java b/src/main/java/com/c2kernel/persistency/ProxyLoader.java index a2f7141..4324e94 100644 --- a/src/main/java/com/c2kernel/persistency/ProxyLoader.java +++ b/src/main/java/com/c2kernel/persistency/ProxyLoader.java @@ -2,6 +2,7 @@ package com.c2kernel.persistency; import java.util.HashMap; import java.util.StringTokenizer; +import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.entity.AgentHelper; import com.c2kernel.entity.C2KLocalObject; import com.c2kernel.entity.ItemHelper; @@ -61,6 +62,8 @@ public class ProxyLoader extends ClusterStorage { else return (C2KLocalObject)Gateway.getMarshaller().unmarshall(queryData); } + } catch (ObjectNotFoundException e) { + return null; } catch (Exception e) { Logger.error(e); throw new ClusterStorageException(e.getMessage()); -- cgit v1.2.3 From 410dc5af0fec0e29635cc049351076712f2d4727 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Fri, 11 Apr 2014 17:00:47 +0200 Subject: Remove description editing workflows from the kernel - they have been moved to cristal-dev. Requires future post-processing for previous Module.debug functionality --- src/main/java/com/c2kernel/process/Bootstrap.java | 11 +- .../java/com/c2kernel/process/module/Module.java | 2 +- .../resources/boot/CA/ManageCompositeActDef.xml | 208 -------------------- .../resources/boot/CA/ManageElementaryActDef.xml | 212 -------------------- src/main/resources/boot/CA/ManageSchema.xml | 216 -------------------- src/main/resources/boot/CA/ManageScript.xml | 217 --------------------- src/main/resources/boot/CA/ManageStateMachine.xml | 214 -------------------- src/main/resources/boot/CA/ModuleWorkflow.xml | 100 ---------- .../resources/boot/EA/AssignNewVersionFromLast.xml | 20 -- src/main/resources/boot/EA/EditActivityDef.xml | 19 -- .../resources/boot/EA/EditModuleDefinition.xml | 1 - src/main/resources/boot/EA/EditSchema.xml | 19 -- .../resources/boot/EA/EditScriptDefinition.xml | 19 -- src/main/resources/boot/EA/EditStateMachine.xml | 19 -- .../boot/SC/CreateNewNumberedVersionFromLast.xml | 31 --- src/main/resources/boot/allbootitems.txt | 13 -- 16 files changed, 8 insertions(+), 1313 deletions(-) delete mode 100644 src/main/resources/boot/CA/ManageCompositeActDef.xml delete mode 100644 src/main/resources/boot/CA/ManageElementaryActDef.xml delete mode 100644 src/main/resources/boot/CA/ManageSchema.xml delete mode 100644 src/main/resources/boot/CA/ManageScript.xml delete mode 100644 src/main/resources/boot/CA/ManageStateMachine.xml delete mode 100644 src/main/resources/boot/CA/ModuleWorkflow.xml delete mode 100644 src/main/resources/boot/EA/AssignNewVersionFromLast.xml delete mode 100644 src/main/resources/boot/EA/EditActivityDef.xml delete mode 100644 src/main/resources/boot/EA/EditModuleDefinition.xml delete mode 100644 src/main/resources/boot/EA/EditSchema.xml delete mode 100644 src/main/resources/boot/EA/EditScriptDefinition.xml delete mode 100644 src/main/resources/boot/EA/EditStateMachine.xml delete mode 100644 src/main/resources/boot/SC/CreateNewNumberedVersionFromLast.xml (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/process/Bootstrap.java b/src/main/java/com/c2kernel/process/Bootstrap.java index a750b3f..601db31 100644 --- a/src/main/java/com/c2kernel/process/Bootstrap.java +++ b/src/main/java/com/c2kernel/process/Bootstrap.java @@ -238,11 +238,14 @@ public class Bootstrap props.list.add(new Property(propName, propVal, pd.getIsMutable())); } - CompositeActivity ca; + CompositeActivity ca = new CompositeActivity(); if (ns!=null && Gateway.getProperties().getBoolean("Module.debug", false)) - ca = (CompositeActivity) ((CompositeActivityDef)LocalObjectLoader.getActDef(impHandler.getWorkflowName(), 0)).instantiate(); - else - ca = new CompositeActivity(); + try { + ca = (CompositeActivity) ((CompositeActivityDef)LocalObjectLoader.getActDef(impHandler.getWorkflowName(), 0)).instantiate(); + } catch (ObjectNotFoundException ex) { + Logger.error("Module resource workflow "+impHandler.getWorkflowName()+" not found. Using empty."); + } + EntityPath entityPath = Gateway.getLDAPLookup().getNextKeyManager().generateNextEntityKey(); TraceableEntity newItem = (TraceableEntity)Gateway.getCorbaServer().createEntity(entityPath); diff --git a/src/main/java/com/c2kernel/process/module/Module.java b/src/main/java/com/c2kernel/process/module/Module.java index 3e8ab2a..32a5997 100644 --- a/src/main/java/com/c2kernel/process/module/Module.java +++ b/src/main/java/com/c2kernel/process/module/Module.java @@ -51,7 +51,7 @@ public class Module { } public void addModuleItem(String moduleXML) { - NewItem moduleItem = new NewItem(name, "/desc/modules/", "ModuleWorkflow", 0); + NewItem moduleItem = new NewItem(name, "/desc/modules/", "NoWorkflow", 0); // Module properties moduleItem.properties.add(new com.c2kernel.property.Property("Namespace", ns, false)); moduleItem.properties.add(new com.c2kernel.property.Property("Name", name, false)); diff --git a/src/main/resources/boot/CA/ManageCompositeActDef.xml b/src/main/resources/boot/CA/ManageCompositeActDef.xml deleted file mode 100644 index f1def44..0000000 --- a/src/main/resources/boot/CA/ManageCompositeActDef.xml +++ /dev/null @@ -1,208 +0,0 @@ - - - - - - - - - - 19 - 20 - 21 - - - - - - - - - - - - 17 - 20 - 18 - - - - - - - - - - - 16 - 17 - - - - - - - - - 8 - 21 - - - - - - - - - - - 25 - 7 - 8 - - - - - - - - - - - - 18 - 19 - - - - - AssignNewVersionFromLast - - - - - - - - 7 - 16 - 24 - - - - - - - - - - - 24 - 25 - - - - - EditActivityDef - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/main/resources/boot/CA/ManageElementaryActDef.xml b/src/main/resources/boot/CA/ManageElementaryActDef.xml deleted file mode 100644 index 756fb8a..0000000 --- a/src/main/resources/boot/CA/ManageElementaryActDef.xml +++ /dev/null @@ -1,212 +0,0 @@ - - - - - - - - - - 19 - 20 - 21 - - - - - - - - - - - - 17 - 20 - 18 - - - - - - - - - - - 8 - 21 - - - - - - - - - - - 16 - 17 - - - - - - - - - 25 - 7 - 8 - - - - - - - - - - - - 7 - 16 - 24 - - - - - - - - - - - 18 - 19 - - - - - - - AssignNewVersionFromLast - - - - - - - - 24 - 25 - - - - - - - EditActivityDef - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/main/resources/boot/CA/ManageSchema.xml b/src/main/resources/boot/CA/ManageSchema.xml deleted file mode 100644 index 69580fe..0000000 --- a/src/main/resources/boot/CA/ManageSchema.xml +++ /dev/null @@ -1,216 +0,0 @@ - - - - - - - - - - 19 - 20 - 21 - - - - - - - - - - - - - 17 - 20 - 18 - - - - - - - - - - - 16 - 17 - - - - - - - - - - - - 8 - 21 - - - - - - - - - - - 6 - 7 - 8 - - - - - - - - - - - - - 18 - 19 - - - - - - - AssignNewVersionFromLast - - - - - - - - 7 - 16 - 5 - - - - - - - - - - - 5 - 6 - - - - - - EditSchema - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/main/resources/boot/CA/ManageScript.xml b/src/main/resources/boot/CA/ManageScript.xml deleted file mode 100644 index 9dff06f..0000000 --- a/src/main/resources/boot/CA/ManageScript.xml +++ /dev/null @@ -1,217 +0,0 @@ - - - - - - - - - - 24 - 25 - 26 - - - - - - - - - - - - - 21 - 22 - 23 - - - - - - - - - - - - - 18 - 25 - 20 - - - - - - - - - - - 17 - 23 - 19 - - - - - - - - - - - 17 - 18 - - - - - - - - - - - - 19 - 21 - - - - - - EditScriptDefinition - - - - - - - - 20 - 24 - - - - - - - AssignNewVersionFromLast - - - - - - - - 22 - 26 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/main/resources/boot/CA/ManageStateMachine.xml b/src/main/resources/boot/CA/ManageStateMachine.xml deleted file mode 100644 index 47d769b..0000000 --- a/src/main/resources/boot/CA/ManageStateMachine.xml +++ /dev/null @@ -1,214 +0,0 @@ - - - - - - - - - - 19 - 20 - 21 - - - - - - - - - - - - - 17 - 20 - 18 - - - - - - - - - - - 16 - 17 - - - - - - - - - - - - 8 - 21 - - - - - - - - - - - 6 - 7 - 8 - - - - - - - - - - - - - 18 - 19 - - - - - AssignNewVersionFromLast - - - - - - - - 7 - 16 - 5 - - - - - - - - - - - 5 - 6 - - - - - - EditStateMachine - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/main/resources/boot/CA/ModuleWorkflow.xml b/src/main/resources/boot/CA/ModuleWorkflow.xml deleted file mode 100644 index 1eb3ee4..0000000 --- a/src/main/resources/boot/CA/ModuleWorkflow.xml +++ /dev/null @@ -1,100 +0,0 @@ - - - - - - - - - - 7 - - - - - - - - - - - 4 - 5 - 7 - - - - - - - - - - - - - 5 - 3 - - - - - - - - - - - 3 - 4 - - - - - EditModuleDefinition - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/main/resources/boot/EA/AssignNewVersionFromLast.xml b/src/main/resources/boot/EA/AssignNewVersionFromLast.xml deleted file mode 100644 index 248dfee..0000000 --- a/src/main/resources/boot/EA/AssignNewVersionFromLast.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/src/main/resources/boot/EA/EditActivityDef.xml b/src/main/resources/boot/EA/EditActivityDef.xml deleted file mode 100644 index e90c225..0000000 --- a/src/main/resources/boot/EA/EditActivityDef.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/src/main/resources/boot/EA/EditModuleDefinition.xml b/src/main/resources/boot/EA/EditModuleDefinition.xml deleted file mode 100644 index 04afe4d..0000000 --- a/src/main/resources/boot/EA/EditModuleDefinition.xml +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/src/main/resources/boot/EA/EditSchema.xml b/src/main/resources/boot/EA/EditSchema.xml deleted file mode 100644 index 3b01fdc..0000000 --- a/src/main/resources/boot/EA/EditSchema.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/src/main/resources/boot/EA/EditScriptDefinition.xml b/src/main/resources/boot/EA/EditScriptDefinition.xml deleted file mode 100644 index 11c14ec..0000000 --- a/src/main/resources/boot/EA/EditScriptDefinition.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/src/main/resources/boot/EA/EditStateMachine.xml b/src/main/resources/boot/EA/EditStateMachine.xml deleted file mode 100644 index a1060b7..0000000 --- a/src/main/resources/boot/EA/EditStateMachine.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/src/main/resources/boot/SC/CreateNewNumberedVersionFromLast.xml b/src/main/resources/boot/SC/CreateNewNumberedVersionFromLast.xml deleted file mode 100644 index 7a63b76..0000000 --- a/src/main/resources/boot/SC/CreateNewNumberedVersionFromLast.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - diff --git a/src/main/resources/boot/allbootitems.txt b/src/main/resources/boot/allbootitems.txt index 9bbea75..7a3cd03 100644 --- a/src/main/resources/boot/allbootitems.txt +++ b/src/main/resources/boot/allbootitems.txt @@ -12,21 +12,8 @@ OD/Schema OD/Script OD/Errors OD/StateMachine -EA/AssignNewVersionFromLast -EA/EditActivityDef -EA/EditSchema -EA/EditScriptDefinition -EA/EditStateMachine EA/CreateNewItem EA/CreateNewAgent -EA/EditModuleDefinition CA/NoWorkflow CA/ServerItemWorkflow -CA/ModuleWorkflow -CA/ManageCompositeActDef -CA/ManageElementaryActDef -CA/ManageSchema -CA/ManageScript -CA/ManageStateMachine -SC/CreateNewNumberedVersionFromLast SC/ServerNewEntity -- cgit v1.2.3 From 45e0e3988f5efd6463727d3510022f3cbaa8170a Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Mon, 14 Apr 2014 14:54:57 +0200 Subject: getClusterContents fixed for subtrees. Still has problems. --- .../persistency/MemoryOnlyClusterStorage.java | 36 +++++++++++++++++++--- 1 file changed, 32 insertions(+), 4 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/persistency/MemoryOnlyClusterStorage.java b/src/main/java/com/c2kernel/persistency/MemoryOnlyClusterStorage.java index a895c32..4766d82 100644 --- a/src/main/java/com/c2kernel/persistency/MemoryOnlyClusterStorage.java +++ b/src/main/java/com/c2kernel/persistency/MemoryOnlyClusterStorage.java @@ -1,10 +1,12 @@ package com.c2kernel.persistency; import java.util.ArrayList; +import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.Map; import com.c2kernel.entity.C2KLocalObject; +import com.c2kernel.utils.Logger; public class MemoryOnlyClusterStorage extends ClusterStorage { @@ -96,18 +98,44 @@ public class MemoryOnlyClusterStorage extends ClusterStorage { Map sysKeyMemCache = memoryCache.get(sysKey); ArrayList result = new ArrayList(); if (sysKeyMemCache != null) { - if (path.endsWith("/")) + while (path.endsWith("/")) path = path.substring(0,path.length()-1); path = path+"/"; for (String thisPath : sysKeyMemCache.keySet()) { if (thisPath.startsWith(path)) { - int slash = path.indexOf('/'); - String suffix = slash>-1?path.substring(slash+1):path; + String end = thisPath.substring(path.length()); + int slash = end.indexOf('/'); + String suffix = slash>-1?end.substring(0, slash):end; if (!result.contains(suffix)) result.add(suffix); } } } return result.toArray(new String[result.size()]); } - + + public void dumpContents(int sysKey) { + synchronized(memoryCache) { + Logger.msg(0, "Cached Objects of Entity "+sysKey); + Map sysKeyMemCache = memoryCache.get(sysKey); + if (sysKeyMemCache == null) { + Logger.msg(0, "No cache found"); + return; + } + try { + synchronized(sysKeyMemCache) { + for (Object name : sysKeyMemCache.keySet()) { + String path = (String) name; + try { + Logger.msg(0, " Path "+path+": "+sysKeyMemCache.get(path).getClass().getName()); + } catch (NullPointerException e) { + Logger.msg(0, " Path "+path+": reaped"); + } + } + } + } catch (ConcurrentModificationException ex) { + Logger.msg(0, "Cache modified - aborting"); + } + } + Logger.msg(0, "Total number of cached entities: "+memoryCache.size()); + } } -- cgit v1.2.3 From e8645422ab8c50d952f1651f2f0acdf0edc95e51 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Wed, 16 Apr 2014 17:46:13 +0200 Subject: XPath fixes, tests, and cleverer get and set FieldByXPath --- .../com/c2kernel/persistency/outcome/Outcome.java | 68 ++++++++++++++++++---- src/test/java/OutcomeTest.java | 37 ++++++++++++ src/test/resources/outcomeTest.xml | 6 ++ 3 files changed, 101 insertions(+), 10 deletions(-) create mode 100644 src/test/java/OutcomeTest.java create mode 100644 src/test/resources/outcomeTest.xml (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/persistency/outcome/Outcome.java b/src/main/java/com/c2kernel/persistency/outcome/Outcome.java index 5604332..9ad84b2 100644 --- a/src/main/java/com/c2kernel/persistency/outcome/Outcome.java +++ b/src/main/java/com/c2kernel/persistency/outcome/Outcome.java @@ -20,6 +20,7 @@ import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSSerializer; import org.xml.sax.InputSource; +import com.c2kernel.common.InvalidDataException; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.common.PersistencyException; import com.c2kernel.entity.C2KLocalObject; @@ -73,7 +74,7 @@ public class Outcome implements C2KLocalObject { public Outcome(String path, String data) throws PersistencyException { // derive all the meta data from the path StringTokenizer tok = new StringTokenizer(path,"/"); - if (tok.countTokens() != 3 && !(tok.nextToken().equals("Outcome"))) + if (tok.countTokens() != 3 && !(tok.nextToken().equals(ClusterStorage.OUTCOME))) throw new PersistencyException("Outcome() - Outcome path must have three components: "+path, null); mSchemaType = tok.nextToken(); String verstring = tok.nextToken(); @@ -123,9 +124,63 @@ public class Outcome implements C2KLocalObject { mData = null; } - public void setFieldByXPath(String xpath, String data) throws XPathExpressionException { + public String getFieldByXPath(String xpath) throws XPathExpressionException, InvalidDataException { Node field = getNodeByXPath(xpath); - field.setNodeValue(data); + if (field == null) + throw new InvalidDataException(xpath, ""); + + else if (field.getNodeType()==Node.TEXT_NODE || field.getNodeType()==Node.CDATA_SECTION_NODE) + return field.getNodeValue(); + + else if (field.getNodeType()==Node.ELEMENT_NODE) { + NodeList fieldChildren = field.getChildNodes(); + if (fieldChildren.getLength() == 0) + throw new InvalidDataException("No child node for element", ""); + + else if (fieldChildren.getLength() == 1) { + Node child = fieldChildren.item(0); + if (child.getNodeType()==Node.TEXT_NODE || child.getNodeType()==Node.CDATA_SECTION_NODE) + return child.getNodeValue(); + else + throw new InvalidDataException("Can't get data from child node of type "+child.getNodeName(), ""); + } + else + throw new InvalidDataException("Element "+xpath+" has too many children", ""); + } + else if (field.getNodeType()==Node.ATTRIBUTE_NODE) + return field.getNodeValue(); + else + throw new InvalidDataException("Don't know what to do with node "+field.getNodeName(), ""); + } + + public void setFieldByXPath(String xpath, String data) throws XPathExpressionException, InvalidDataException { + Node field = getNodeByXPath(xpath); + if (field == null) + throw new InvalidDataException(xpath, ""); + + else if (field.getNodeType()==Node.ELEMENT_NODE) { + NodeList fieldChildren = field.getChildNodes(); + if (fieldChildren.getLength() == 0) { + field.appendChild(dom.createTextNode(data)); + } + else if (fieldChildren.getLength() == 1) { + Node child = fieldChildren.item(0); + switch (child.getNodeType()) { + case Node.TEXT_NODE: + case Node.CDATA_SECTION_NODE: + child.setNodeValue(data); + break; + default: + throw new InvalidDataException("Can't set child node of type "+child.getNodeName(), ""); + } + } + else + throw new InvalidDataException("Element "+xpath+" has too many children", ""); + } + else if (field.getNodeType()==Node.ATTRIBUTE_NODE) + field.setNodeValue(data); + else + throw new InvalidDataException("Don't know what to do with node "+field.getNodeName(), ""); } @@ -188,13 +243,6 @@ public class Outcome implements C2KLocalObject { return null; } - public String getFieldByXPath(String xpathExpr) throws XPathExpressionException { - - XPathExpression expr = xpath.compile(xpathExpr); - return (String)expr.evaluate(getDOM(), XPathConstants.STRING); - - } - public NodeList getNodesByXPath(String xpathExpr) throws XPathExpressionException { XPathExpression expr = xpath.compile(xpathExpr); diff --git a/src/test/java/OutcomeTest.java b/src/test/java/OutcomeTest.java new file mode 100644 index 0000000..d90f2ea --- /dev/null +++ b/src/test/java/OutcomeTest.java @@ -0,0 +1,37 @@ +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import com.c2kernel.persistency.outcome.Outcome; +import com.c2kernel.utils.FileStringUtility; + + +public class OutcomeTest { + + Outcome testOc; + + public OutcomeTest() throws Exception { + String ocData = FileStringUtility.url2String(OutcomeTest.class.getResource("outcomeTest.xml")); + testOc = new Outcome("/Outcome/Test/0/0", ocData); + } + + public void testDOMAccess() throws Exception { + assert "Field1contents".equals(testOc.getField("Field1")) : "getField() failed"; + } + + public void testXPath() throws Exception { + Node field1Node = testOc.getNodeByXPath("//Field1/text()"); + assert field1Node!=null : "XPath for Element query failed"; + assert field1Node.getNodeValue() != null : "Field1 node was null"; + assert field1Node.getNodeValue().equals("Field1contents") : "Incorrect value for element node through XPath"; + assert "Field1contents".equals(testOc.getFieldByXPath("//Field1")): "getFieldByXPath failed"; + testOc.setFieldByXPath("//Field2", "NewField2"); + assert "NewField2".equals(testOc.getFieldByXPath("//Field2")): "getFieldByXPath failed to retrieve updated value"; + assert testOc.getNodeByXPath("//Field2/text()").getNodeValue() != null : "Field2 text node is null"; + assert testOc.getNodeByXPath("//Field2/text()").getNodeValue().equals("NewField2") : "Failed to setFieldByXPath for element"; + Node field2attr = testOc.getNodeByXPath("//Field2/@attr"); + assert field2attr.getNodeValue().equals("attribute"): "Failed to retrieve attribute value via XPath"; + NodeList field3nodes = testOc.getNodesByXPath("//Field3"); + assert field3nodes.getLength()==2 : "getNodesByXPath returned wrong number of nodes"; + + } +} diff --git a/src/test/resources/outcomeTest.xml b/src/test/resources/outcomeTest.xml new file mode 100644 index 0000000..563c72c --- /dev/null +++ b/src/test/resources/outcomeTest.xml @@ -0,0 +1,6 @@ + + Field1contents + + repeating + element + \ No newline at end of file -- cgit v1.2.3 From 6dfa1bbe05a712174e937af89d5223e98d9d7d06 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Wed, 16 Apr 2014 17:47:19 +0200 Subject: Don't use logger to report exceptions, in case the Logger didn't get initialized. --- src/main/java/com/c2kernel/process/StandardServer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/process/StandardServer.java b/src/main/java/com/c2kernel/process/StandardServer.java index 546aaa5..e283cb6 100644 --- a/src/main/java/com/c2kernel/process/StandardServer.java +++ b/src/main/java/com/c2kernel/process/StandardServer.java @@ -72,7 +72,7 @@ public class StandardServer extends AbstractMain implements WrapperListener } catch( Exception ex ) { - Logger.error(ex); + ex.printStackTrace(); Logger.die("Startup failed"); } return null; -- cgit v1.2.3 From a1f0ecbb6a2bea6aa214322c412af2f3c5ce124b Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Wed, 7 May 2014 17:33:13 +0200 Subject: Agent now extends Item, so they can have workflows. All traces of the old 'Entity' superclasses should be removed, including proxies and paths. Very large change, breaks API compatibility with CRISTAL 2.x. Fixes #135 --- src/main/idl/Entity.idl | 132 ++++---- .../java/com/c2kernel/collection/Aggregation.java | 24 +- .../collection/AggregationDescription.java | 4 +- .../com/c2kernel/collection/AggregationMember.java | 76 ++--- .../c2kernel/collection/CollectionArrayList.java | 10 +- .../com/c2kernel/collection/CollectionMember.java | 12 +- .../java/com/c2kernel/collection/Dependency.java | 12 +- .../c2kernel/collection/DependencyDescription.java | 2 +- .../com/c2kernel/collection/DependencyMember.java | 58 ++-- .../collection/Parent2ChildCollection.java | 6 +- .../com/c2kernel/entity/AgentImplementation.java | 78 +++++ src/main/java/com/c2kernel/entity/CorbaServer.java | 14 +- .../com/c2kernel/entity/ItemImplementation.java | 281 +++++++++++++++++ .../java/com/c2kernel/entity/TraceableEntity.java | 207 +------------ .../com/c2kernel/entity/agent/ActiveEntity.java | 263 ++++------------ src/main/java/com/c2kernel/entity/agent/Job.java | 8 +- .../java/com/c2kernel/entity/proxy/AgentProxy.java | 63 ++-- .../com/c2kernel/entity/proxy/EntityProxy.java | 247 --------------- .../c2kernel/entity/proxy/EntityProxyManager.java | 339 --------------------- .../c2kernel/entity/proxy/EntityProxyObserver.java | 27 -- .../java/com/c2kernel/entity/proxy/ItemProxy.java | 285 +++++++++++++---- .../c2kernel/entity/proxy/MemberSubscription.java | 18 +- .../entity/proxy/ProxyClientConnection.java | 2 +- .../com/c2kernel/entity/proxy/ProxyManager.java | 337 ++++++++++++++++++++ .../com/c2kernel/entity/proxy/ProxyObserver.java | 27 ++ .../entity/proxy/ProxyServerConnection.java | 4 +- .../com/c2kernel/entity/transfer/TransferItem.java | 9 +- .../com/c2kernel/entity/transfer/TransferSet.java | 4 +- .../com/c2kernel/lifecycle/instance/WfVertex.java | 4 +- .../instance/predefined/AddDomainPath.java | 8 +- .../instance/predefined/AssignItemToSlot.java | 10 +- .../lifecycle/instance/predefined/ClearSlot.java | 4 +- .../predefined/CreateItemFromDescription.java | 32 +- .../lifecycle/instance/predefined/Erase.java | 6 +- .../predefined/RemoveSlotFromCollection.java | 8 +- .../predefined/entitycreation/NewAgent.java | 2 +- .../predefined/entitycreation/NewItem.java | 73 ++--- .../routingHelpers/ViewpointDataHelper.java | 8 +- src/main/java/com/c2kernel/lookup/AgentPath.java | 10 +- src/main/java/com/c2kernel/lookup/DomainPath.java | 10 +- src/main/java/com/c2kernel/lookup/EntityPath.java | 175 ----------- .../c2kernel/lookup/InvalidAgentPathException.java | 2 +- .../lookup/InvalidEntityPathException.java | 13 - .../c2kernel/lookup/InvalidItemPathException.java | 13 + src/main/java/com/c2kernel/lookup/ItemPath.java | 175 +++++++++++ src/main/java/com/c2kernel/lookup/LDAPLookup.java | 36 +-- .../com/c2kernel/lookup/LDAPPropertyManager.java | 10 +- .../java/com/c2kernel/lookup/LDAPRoleManager.java | 2 +- .../java/com/c2kernel/lookup/NextKeyManager.java | 14 +- src/main/java/com/c2kernel/lookup/Path.java | 2 +- .../persistency/ClusterStorageManager.java | 6 +- .../c2kernel/persistency/LDAPClusterStorage.java | 26 +- .../java/com/c2kernel/persistency/ProxyLoader.java | 24 +- .../java/com/c2kernel/persistency/RemoteMap.java | 14 +- .../c2kernel/persistency/XMLClusterStorage.java | 8 +- src/main/java/com/c2kernel/process/Bootstrap.java | 23 +- src/main/java/com/c2kernel/process/Gateway.java | 12 +- .../java/com/c2kernel/process/UserCodeProcess.java | 4 +- .../com/c2kernel/utils/DescriptionObjectCache.java | 4 +- src/main/resources/mapFiles/CollectionMap.xml | 16 +- src/test/java/LauncherTest.java | 2 +- 61 files changed, 1598 insertions(+), 1707 deletions(-) create mode 100644 src/main/java/com/c2kernel/entity/AgentImplementation.java create mode 100644 src/main/java/com/c2kernel/entity/ItemImplementation.java delete mode 100644 src/main/java/com/c2kernel/entity/proxy/EntityProxy.java delete mode 100644 src/main/java/com/c2kernel/entity/proxy/EntityProxyManager.java delete mode 100644 src/main/java/com/c2kernel/entity/proxy/EntityProxyObserver.java create mode 100644 src/main/java/com/c2kernel/entity/proxy/ProxyManager.java create mode 100644 src/main/java/com/c2kernel/entity/proxy/ProxyObserver.java delete mode 100644 src/main/java/com/c2kernel/lookup/EntityPath.java delete mode 100644 src/main/java/com/c2kernel/lookup/InvalidEntityPathException.java create mode 100644 src/main/java/com/c2kernel/lookup/InvalidItemPathException.java create mode 100644 src/main/java/com/c2kernel/lookup/ItemPath.java (limited to 'src/main/java') diff --git a/src/main/idl/Entity.idl b/src/main/idl/Entity.idl index f94bdf4..2aa9188 100644 --- a/src/main/idl/Entity.idl +++ b/src/main/idl/Entity.idl @@ -21,7 +21,7 @@ module entity * in a tree structure. **/ - abstract interface ManageableEntity + interface Item { /** @@ -29,7 +29,24 @@ module entity **/ unsigned long getSystemKey(); - + /** Initialises a new Item. Initial properties and the lifecycle are supplied. They should come from the Item's description. + * + * @param agentId the Agent doing the initialisation + * @param itemProps The XML marshalled {@link com.c2kernel.Property.PropertyArrayList PropertyArrayList} containing the initial + * Property objects of the Item + * @param workflow The XML marshalled new lifecycle of the Item + * @param collection The XML marshalled CollectionArrayList of the initial state of the Item's collections + * @exception ObjectNotFoundException + **/ + void initialise( in unsigned long agentId, + in string itemProps, + in string workflow, + in string collections ) + raises( common::AccessRightsException, + common::InvalidDataException, + common::PersistencyException, + common::ObjectNotFoundException ); + /** * Returns a chunk of XML which may be a serialized C2KLocalObject, or in the case of Outcomes is merely a fragment of XML. * @@ -54,77 +71,6 @@ module entity raises( common::AccessRightsException, common::ObjectNotFoundException, common::PersistencyException ); - }; - - - /************************************************************************** - * Agent is a ManageableEntity that represents an Activity executor in the - * system. It holds a job list, which are persistent requests for execution - * from waiting activities assigned to a role that has such Job pushing enabled. - **************************************************************************/ - interface Agent : ManageableEntity - { - /** Initialises a new Agent. Should not be done by client processes - they - * should use an Agent factory such as a Server item. - * @param agentProps - XML marshalled {@link com.c2kernel.Property.PropertyArrayList PropertyArrayList} containing the initial - * Property objects of the Agent - * @throws AccessRightsException not yet implemented, reserved for future access control - * @throws InvalidDataException when the data supplied couldn't be unmarshalled - * @throws PersistencyException when there was a problem communicating with storage - **/ - void initialise( in string agentProps ) - raises( common::AccessRightsException, - common::InvalidDataException, - common::PersistencyException ); - - /** Supplies the new set of jobs for the given item and activity. The Agent should replace all existing jobs for that activity - * with the given set. This method should generally only be called by a workflow while performing an execution. - * - * @param sysKey the item which generated the jobs - * @param stepPath the activity within the lifecycle of the item which the jobs relate to - * @param newJobs an XML marshalled {@link com.c2kernel.entity.agent.JobArrayList JobArrayList} containing the new Jobs - **/ - void refreshJobList( in unsigned long sysKey, in string stepPath, in string newJobs ); - - /** Add this Agent to the given role - * @param roleName the new role to add - * @throws ObjectNotFoundException when the role doesn't exist - * @throws CannotManageException when an error occurs writing the data to LDAP - **/ - void addRole( in string roleName ) - raises( common::ObjectNotFoundException, - common::CannotManageException ); - - /** Remove this Agent from the given role - * @param the role name to remove - * @throws CannotManageException when an error occurs writing the data to LDAP - **/ - void removeRole( in string roleName ) - raises( common::ObjectNotFoundException, - common::CannotManageException ); - }; - - - /************************************************************************** - * Item is an ManageableEntity which has a lifecycle, and as a consequence - * generates Events, Outcomes and Viewpoints. - **************************************************************************/ - interface Item : ManageableEntity - { - /** Initialises a new Item. Initial properties and the lifecycle are supplied. They should come from the Item's description. - * - * @param agentId the Agent doing the initialisation - * @param itemProps The XML marshalled {@link com.c2kernel.Property.PropertyArrayList PropertyArrayList} containing the initial - * Property objects of the Agent - * @param workflow The XML marshalled new lifecycle of the Item - * @exception ObjectNotFoundException - **/ - void initialise( in unsigned long agentId, - in string itemProps, - in string workflow ) - raises( common::AccessRightsException, - common::InvalidDataException, - common::PersistencyException ); /** * Requests a transition of an Activity in this Item's workflow. If possible and permitted, an Event is @@ -158,7 +104,7 @@ module entity void requestAction( in unsigned long agentID, in string stepPath, in unsigned long transitionID, - in string requestData + in string requestData ) raises( common::AccessRightsException, common::InvalidTransitionException, @@ -184,10 +130,44 @@ module entity in boolean filter ) raises( common::AccessRightsException, common::ObjectNotFoundException, - common::PersistencyException ); + common::PersistencyException ); + }; + + /************************************************************************** + * Agent is a ManageableEntity that represents an Activity executor in the + * system. It holds a job list, which are persistent requests for execution + * from waiting activities assigned to a role that has such Job pushing enabled. + **************************************************************************/ + interface Agent : Item + { + + /** Supplies the new set of jobs for the given item and activity. The Agent should replace all existing jobs for that activity + * with the given set. This method should generally only be called by a workflow while performing an execution. + * + * @param sysKey the item which generated the jobs + * @param stepPath the activity within the lifecycle of the item which the jobs relate to + * @param newJobs an XML marshalled {@link com.c2kernel.entity.agent.JobArrayList JobArrayList} containing the new Jobs + **/ + void refreshJobList( in unsigned long sysKey, in string stepPath, in string newJobs ); + + /** Add this Agent to the given role + * @param roleName the new role to add + * @throws ObjectNotFoundException when the role doesn't exist + * @throws CannotManageException when an error occurs writing the data to LDAP + **/ + void addRole( in string roleName ) + raises( common::ObjectNotFoundException, + common::CannotManageException ); - }; //end of Item + /** Remove this Agent from the given role + * @param the role name to remove + * @throws CannotManageException when an error occurs writing the data to LDAP + **/ + void removeRole( in string roleName ) + raises( common::ObjectNotFoundException, + common::CannotManageException ); + }; }; //end of module entity diff --git a/src/main/java/com/c2kernel/collection/Aggregation.java b/src/main/java/com/c2kernel/collection/Aggregation.java index 063eb77..f2ef710 100644 --- a/src/main/java/com/c2kernel/collection/Aggregation.java +++ b/src/main/java/com/c2kernel/collection/Aggregation.java @@ -6,8 +6,8 @@ import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.graph.model.GraphModel; import com.c2kernel.graph.model.GraphPoint; import com.c2kernel.graph.model.TypeNameAndConstructionInfo; -import com.c2kernel.lookup.EntityPath; -import com.c2kernel.lookup.InvalidEntityPathException; +import com.c2kernel.lookup.ItemPath; +import com.c2kernel.lookup.InvalidItemPathException; import com.c2kernel.persistency.ClusterStorage; import com.c2kernel.process.Gateway; import com.c2kernel.utils.CastorHashMap; @@ -50,12 +50,12 @@ abstract public class Aggregation extends Parent2ChildCollection -1) { // some clients use this method when not setting a member - aggMem.assignEntity(entityKey); - aggMem.setIsComposite( getIsComposite(entityKey, getName()) ); + if (sysKey > -1) { // some clients use this method when not setting a member + aggMem.assignItem(sysKey); + aggMem.setIsComposite( getIsComposite(sysKey, getName()) ); } - Logger.msg(8, "AggregationDescription::addMember(" + entityKey + ") assigned to new slot " + aggMem.getID()); + Logger.msg(8, "AggregationDescription::addMember(" + sysKey + ") assigned to new slot " + aggMem.getID()); return aggMem; } @@ -130,7 +130,7 @@ abstract public class Aggregation extends Parent2ChildCollection -1) { + if (sysKey > -1) { if (mClassProps == null || getProperties() == null) throw new MembershipException("ClassProps not yet set. Cannot check membership validity."); @@ -89,11 +89,11 @@ public class AggregationMember extends GraphableVertex implements CollectionMemb String aClassProp = sub.nextToken(); try { String memberValue = (String)getProperties().get(aClassProp); - Property entityProperty = (Property)Gateway.getStorage().get(entityKey, ClusterStorage.PROPERTY+"/"+aClassProp, null); - if (entityProperty == null) - throw new MembershipException("Property "+aClassProp+ " does not exist for entityKey=" + entityKey ); - if (entityProperty.getValue() == null || !entityProperty.getValue().equalsIgnoreCase(memberValue)) - throw new MembershipException("Value of mandatory prop "+aClassProp+" does not match: " + entityProperty.getValue()+"!="+memberValue); + Property ItemProperty = (Property)Gateway.getStorage().get(sysKey, ClusterStorage.PROPERTY+"/"+aClassProp, null); + if (ItemProperty == null) + throw new MembershipException("Property "+aClassProp+ " does not exist for sysKey=" + sysKey ); + if (ItemProperty.getValue() == null || !ItemProperty.getValue().equalsIgnoreCase(memberValue)) + throw new MembershipException("Value of mandatory prop "+aClassProp+" does not match: " + ItemProperty.getValue()+"!="+memberValue); } catch (MembershipException ex) { throw ex; @@ -106,46 +106,46 @@ public class AggregationMember extends GraphableVertex implements CollectionMemb } } - mEntityKey = entityKey; - mEntity = null; - entityName = null; + mSystemKey = sysKey; + mItem = null; + ItemName = null; } @Override - public void clearEntity() { - mEntityKey = -1; - mEntity = null; + public void clearItem() { + mSystemKey = -1; + mItem = null; } @Override - public EntityProxy resolveEntity() throws ObjectNotFoundException { - if (mEntity == null) { + public ItemProxy resolveItem() throws ObjectNotFoundException { + if (mItem == null) { try { - EntityPath path = new EntityPath(mEntityKey); - mEntity = Gateway.getProxyManager().getProxy(path); - } catch (InvalidEntityPathException ex) { + ItemPath path = new ItemPath(mSystemKey); + mItem = Gateway.getProxyManager().getProxy(path); + } catch (InvalidItemPathException ex) { throw new ObjectNotFoundException("No member defined", ""); } } - return mEntity; + return mItem; } - public String getEntityName() { - if (entityName == null) { - if (mEntityKey > -1) { + public String getItemName() { + if (ItemName == null) { + if (mSystemKey > -1) { try { - entityName = resolveEntity().getName(); + ItemName = resolveItem().getName(); } catch (ObjectNotFoundException ex) { Logger.error(ex); - entityName = "Error ("+mEntityKey+")"; + ItemName = "Error ("+mSystemKey+")"; } } else - entityName = "Empty"; + ItemName = "Empty"; } - return entityName; + return ItemName; } } diff --git a/src/main/java/com/c2kernel/collection/CollectionArrayList.java b/src/main/java/com/c2kernel/collection/CollectionArrayList.java index 586f99f..d91ec20 100644 --- a/src/main/java/com/c2kernel/collection/CollectionArrayList.java +++ b/src/main/java/com/c2kernel/collection/CollectionArrayList.java @@ -4,23 +4,23 @@ import java.util.ArrayList; import com.c2kernel.utils.CastorArrayList; -public class CollectionArrayList extends CastorArrayList> { +public class CollectionArrayList extends CastorArrayList> { public CollectionArrayList() { super(); } - public CollectionArrayList(ArrayList> aList) + public CollectionArrayList(ArrayList> aList) { super(); - for (Collection coll : aList) { + for (Collection coll : aList) { put(coll); } } /** Overwrite */ - public void put(Collection c) { - for (Collection thisColl : list) { + public void put(Collection c) { + for (Collection thisColl : list) { if (thisColl.getName().equals(c.getName())) { list.remove(thisColl); break; diff --git a/src/main/java/com/c2kernel/collection/CollectionMember.java b/src/main/java/com/c2kernel/collection/CollectionMember.java index 0b21e30..ff5d1cd 100644 --- a/src/main/java/com/c2kernel/collection/CollectionMember.java +++ b/src/main/java/com/c2kernel/collection/CollectionMember.java @@ -3,7 +3,7 @@ package com.c2kernel.collection; import java.io.Serializable; import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.entity.proxy.EntityProxy; +import com.c2kernel.entity.proxy.ItemProxy; import com.c2kernel.utils.CastorHashMap; /************************************************************************** @@ -20,12 +20,12 @@ import com.c2kernel.utils.CastorHashMap; public interface CollectionMember extends Serializable { - public void setEntityKey(int entityKey) throws MembershipException; - public int getEntityKey(); + public void setSystemKey(int sysKey) throws MembershipException; + public int getSystemKey(); - public void assignEntity(int entityKey) throws MembershipException; - public void clearEntity(); - public EntityProxy resolveEntity() throws ObjectNotFoundException; + public void assignItem(int ItemKey) throws MembershipException; + public void clearItem(); + public ItemProxy resolveItem() throws ObjectNotFoundException; public void setID(int Id); public int getID(); diff --git a/src/main/java/com/c2kernel/collection/Dependency.java b/src/main/java/com/c2kernel/collection/Dependency.java index cbbf28c..c90fa9d 100644 --- a/src/main/java/com/c2kernel/collection/Dependency.java +++ b/src/main/java/com/c2kernel/collection/Dependency.java @@ -57,7 +57,7 @@ public class Dependency extends Parent2ChildCollection } @Override - public DependencyMember addMember(int entityKey) throws MembershipException { + public DependencyMember addMember(int sysKey) throws MembershipException { // create member object DependencyMember depMember = new DependencyMember(); depMember.setID(getCounter()); @@ -65,14 +65,14 @@ public class Dependency extends Parent2ChildCollection depMember.setClassProps(mClassProps); // assign entity - depMember.assignEntity(entityKey); + depMember.assignItem(sysKey); mMembers.list.add(depMember); - Logger.msg(8, "Dependency::addMember(" + entityKey + ") added to children."); + Logger.msg(8, "Dependency::addMember(" + sysKey + ") added to children."); return depMember; } @Override - public DependencyMember addMember(int entityKey, CastorHashMap props, String classProps) + public DependencyMember addMember(int sysKey, CastorHashMap props, String classProps) throws MembershipException { if (classProps != null && !classProps.equals(mClassProps)) @@ -97,9 +97,9 @@ public class Dependency extends Parent2ChildCollection depMember.setClassProps(mClassProps); // assign entity - depMember.assignEntity(entityKey); + depMember.assignItem(sysKey); mMembers.list.add(depMember); - Logger.msg(8, "Dependency::addMember(" + entityKey + ") added to children."); + Logger.msg(8, "Dependency::addMember(" + sysKey + ") added to children."); return depMember; } diff --git a/src/main/java/com/c2kernel/collection/DependencyDescription.java b/src/main/java/com/c2kernel/collection/DependencyDescription.java index 681e98b..79b4880 100644 --- a/src/main/java/com/c2kernel/collection/DependencyDescription.java +++ b/src/main/java/com/c2kernel/collection/DependencyDescription.java @@ -23,7 +23,7 @@ public class DependencyDescription extends Dependency implements CollectionDescr Dependency newDep = new Dependency(depName); if (mMembers.list.size() == 1) { // constrain the members based on the property description DependencyMember mem = mMembers.list.get(0); - PropertyDescriptionList pdList = PropertyUtility.getPropertyDescriptionOutcome(mem.getEntityKey()); + PropertyDescriptionList pdList = PropertyUtility.getPropertyDescriptionOutcome(mem.getSystemKey()); if (pdList!=null) { newDep.setProperties(PropertyUtility.createProperty(pdList)); newDep.setClassProps(pdList.getClassProps()); diff --git a/src/main/java/com/c2kernel/collection/DependencyMember.java b/src/main/java/com/c2kernel/collection/DependencyMember.java index 4ca2090..169f9ea 100644 --- a/src/main/java/com/c2kernel/collection/DependencyMember.java +++ b/src/main/java/com/c2kernel/collection/DependencyMember.java @@ -3,9 +3,9 @@ package com.c2kernel.collection; import java.util.StringTokenizer; import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.entity.proxy.EntityProxy; -import com.c2kernel.lookup.EntityPath; -import com.c2kernel.lookup.InvalidEntityPathException; +import com.c2kernel.entity.proxy.ItemProxy; +import com.c2kernel.lookup.ItemPath; +import com.c2kernel.lookup.InvalidItemPathException; import com.c2kernel.persistency.ClusterStorage; import com.c2kernel.process.Gateway; import com.c2kernel.property.Property; @@ -23,8 +23,8 @@ import com.c2kernel.utils.Logger; public class DependencyMember implements CollectionMember { - private int mEntityKey = -1; - private EntityProxy mEntity = null; + private int mSystemKey = -1; + private ItemProxy mItem = null; private int mId = -1; private CastorHashMap mProperties = null; private String mClassProps; @@ -35,22 +35,22 @@ public class DependencyMember implements CollectionMember **************************************************************************/ public DependencyMember() { - mEntityKey = -1; + mSystemKey = -1; mProperties = new CastorHashMap(); } @Override - public void setEntityKey(int entityKey) + public void setSystemKey(int sysKey) { - mEntityKey = entityKey; - mEntity = null; + mSystemKey = sysKey; + mItem = null; } @Override - public int getEntityKey() + public int getSystemKey() { - return mEntityKey; + return mSystemKey; } @Override @@ -97,9 +97,9 @@ public class DependencyMember implements CollectionMember } @Override - public void assignEntity(int entityKey) throws MembershipException + public void assignItem(int ItemKey) throws MembershipException { - if (entityKey > -1) { + if (ItemKey > -1) { if (mClassProps == null || getProperties() == null) throw new MembershipException("ClassProps not yet set. Cannot check membership validity."); @@ -110,11 +110,11 @@ public class DependencyMember implements CollectionMember String aClassProp = sub.nextToken(); try { String memberValue = (String)getProperties().get(aClassProp); - Property entityProperty = (Property)Gateway.getStorage().get(entityKey, ClusterStorage.PROPERTY+"/"+aClassProp, null); - if (entityProperty == null) - throw new MembershipException("Property "+aClassProp+ " does not exist for entityKey=" + entityKey ); - if (!entityProperty.getValue().equalsIgnoreCase(memberValue)) - throw new MembershipException("DependencyMember::checkProperty() Values of mandatory prop "+aClassProp+" do not match " + entityProperty.getValue()+"!="+memberValue); + Property ItemProperty = (Property)Gateway.getStorage().get(ItemKey, ClusterStorage.PROPERTY+"/"+aClassProp, null); + if (ItemProperty == null) + throw new MembershipException("Property "+aClassProp+ " does not exist for ItemKey=" + ItemKey ); + if (!ItemProperty.getValue().equalsIgnoreCase(memberValue)) + throw new MembershipException("DependencyMember::checkProperty() Values of mandatory prop "+aClassProp+" do not match " + ItemProperty.getValue()+"!="+memberValue); } catch (Exception ex) { @@ -124,27 +124,27 @@ public class DependencyMember implements CollectionMember } } - mEntityKey = entityKey; - mEntity = null; + mSystemKey = ItemKey; + mItem = null; } @Override - public void clearEntity() { - mEntityKey = -1; - mEntity = null; + public void clearItem() { + mSystemKey = -1; + mItem = null; } @Override - public EntityProxy resolveEntity() throws ObjectNotFoundException { - if (mEntity == null) { + public ItemProxy resolveItem() throws ObjectNotFoundException { + if (mItem == null) { try { - EntityPath path = new EntityPath(mEntityKey); - mEntity = Gateway.getProxyManager().getProxy(path); - } catch (InvalidEntityPathException ex) { + ItemPath path = new ItemPath(mSystemKey); + mItem = Gateway.getProxyManager().getProxy(path); + } catch (InvalidItemPathException ex) { throw new ObjectNotFoundException("No member defined", ""); } } - return mEntity; + return mItem; } diff --git a/src/main/java/com/c2kernel/collection/Parent2ChildCollection.java b/src/main/java/com/c2kernel/collection/Parent2ChildCollection.java index d59b613..814cca8 100644 --- a/src/main/java/com/c2kernel/collection/Parent2ChildCollection.java +++ b/src/main/java/com/c2kernel/collection/Parent2ChildCollection.java @@ -88,10 +88,10 @@ abstract public class Parent2ChildCollection impleme mMembers = newMembers; } - public boolean contains(int entityKey) { + public boolean contains(int sysKey) { for (Object name : mMembers.list) { CollectionMember element = (CollectionMember)name; - if (element.getEntityKey() == entityKey) + if (element.getSystemKey() == sysKey) return true; } return false; @@ -102,7 +102,7 @@ abstract public class Parent2ChildCollection impleme for (int i=0; i mEntityCache; + private final Map mEntityCache; private POA mRootPOA; private POA mItemPOA; private POA mAgentPOA; private POAManager mPOAManager; public CorbaServer() throws InvalidDataException { - mEntityCache = new SoftCache(50); + mEntityCache = new SoftCache(50); // init POA try { @@ -119,7 +119,7 @@ public class CorbaServer { **************************************************************************/ private Servant getEntity(int sysKey, org.omg.PortableServer.POA poa) throws ObjectNotFoundException { try { - EntityPath entityPath = new EntityPath(sysKey); + ItemPath entityPath = new ItemPath(sysKey); Servant entity = null; synchronized (mEntityCache) { entity = mEntityCache.get(entityPath); @@ -141,7 +141,7 @@ public class CorbaServer { } return entity; - } catch (InvalidEntityPathException ex) { + } catch (InvalidItemPathException ex) { throw new ObjectNotFoundException("Invalid Entity Key", ""); } } @@ -164,7 +164,7 @@ public class CorbaServer { * @param entityPath * @return */ - public Servant createEntity(EntityPath entityPath) throws CannotManageException, ObjectAlreadyExistsException { + public Servant createEntity(ItemPath entityPath) throws CannotManageException, ObjectAlreadyExistsException { try { if (entityPath == null) entityPath = Gateway.getLDAPLookup().getNextKeyManager().generateNextEntityKey(); diff --git a/src/main/java/com/c2kernel/entity/ItemImplementation.java b/src/main/java/com/c2kernel/entity/ItemImplementation.java new file mode 100644 index 0000000..e0d107a --- /dev/null +++ b/src/main/java/com/c2kernel/entity/ItemImplementation.java @@ -0,0 +1,281 @@ +package com.c2kernel.entity; + +import com.c2kernel.collection.Collection; +import com.c2kernel.collection.CollectionArrayList; +import com.c2kernel.common.AccessRightsException; +import com.c2kernel.common.InvalidDataException; +import com.c2kernel.common.InvalidTransitionException; +import com.c2kernel.common.ObjectAlreadyExistsException; +import com.c2kernel.common.ObjectNotFoundException; +import com.c2kernel.common.PersistencyException; +import com.c2kernel.entity.agent.JobArrayList; +import com.c2kernel.lifecycle.instance.CompositeActivity; +import com.c2kernel.lifecycle.instance.Workflow; +import com.c2kernel.lookup.AgentPath; +import com.c2kernel.lookup.InvalidItemPathException; +import com.c2kernel.persistency.ClusterStorage; +import com.c2kernel.persistency.ClusterStorageException; +import com.c2kernel.persistency.TransactionManager; +import com.c2kernel.process.Gateway; +import com.c2kernel.property.Property; +import com.c2kernel.property.PropertyArrayList; +import com.c2kernel.utils.Logger; + +public class ItemImplementation implements ItemOperations { + + protected final TransactionManager mStorage; + protected final int mSystemKey; + + protected ItemImplementation(int systemKey) { + this.mStorage = Gateway.getStorage(); + this.mSystemKey = systemKey; + } + + @Override + public int getSystemKey() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public void initialise(int agentId, String propString, String initWfString, + String initCollsString) throws AccessRightsException, + InvalidDataException, PersistencyException + { + Logger.msg(5, "Item::initialise("+mSystemKey+") - agent:"+agentId); + Object locker = new Object(); + + AgentPath agentPath; + try { + agentPath = new AgentPath(agentId); + } catch (InvalidItemPathException e) { + throw new AccessRightsException("Invalid Agent Id:" + agentId); + } + + // must supply properties + if (propString == null || propString.length() == 0) { + throw new InvalidDataException("No properties supplied", ""); + } + + // store properties + try { + PropertyArrayList props = (PropertyArrayList) Gateway + .getMarshaller().unmarshall(propString); + for (Property thisProp : props.list) + mStorage.put(mSystemKey, thisProp, locker); + } catch (Throwable ex) { + Logger.msg(8, "TraceableEntity::initialise(" + mSystemKey + + ") - Properties were invalid: " + propString); + Logger.error(ex); + mStorage.abort(locker); + throw new InvalidDataException("Properties were invalid", ""); + } + + // create wf + try { + Workflow lc = null; + if (initWfString == null || initWfString.length() == 0) + lc = new Workflow(new CompositeActivity()); + else + lc = new Workflow((CompositeActivity) Gateway + .getMarshaller().unmarshall(initWfString)); + lc.initialise(mSystemKey, agentPath); + mStorage.put(mSystemKey, lc, locker); + } catch (Throwable ex) { + Logger.msg(8, "TraceableEntity::initialise(" + mSystemKey + + ") - Workflow was invalid: " + initWfString); + Logger.error(ex); + mStorage.abort(locker); + throw new InvalidDataException("Workflow was invalid", ""); + } + + // init collections + if (initCollsString != null && initCollsString.length() > 0) { + try { + CollectionArrayList colls = (CollectionArrayList) Gateway + .getMarshaller().unmarshall(initCollsString); + for (Collection thisColl : colls.list) { + mStorage.put(mSystemKey, thisColl, locker); + } + } catch (Throwable ex) { + Logger.msg(8, "TraceableEntity::initialise(" + mSystemKey + + ") - Collections were invalid: " + + initCollsString); + Logger.error(ex); + mStorage.abort(locker); + throw new InvalidDataException("Collections were invalid"); + } + } + mStorage.commit(locker); + Logger.msg(3, "Initialisation of item " + mSystemKey + + " was successful"); + } + + + @Override + public void requestAction(int agentId, String stepPath, int transitionID, + String requestData) throws AccessRightsException, + InvalidTransitionException, ObjectNotFoundException, + InvalidDataException, PersistencyException, + ObjectAlreadyExistsException { + + try { + + Logger.msg(1, "TraceableEntity::request(" + mSystemKey + ") - " + + transitionID + " " + stepPath + " by " + agentId); + + AgentPath agent = new AgentPath(agentId); + Workflow lifeCycle = (Workflow) mStorage.get(mSystemKey, + ClusterStorage.LIFECYCLE + "/workflow", null); + + lifeCycle.requestAction(agent, stepPath, mSystemKey, + transitionID, requestData); + + // store the workflow if we've changed the state of the domain + // wf + if (!(stepPath.startsWith("workflow/predefined"))) + mStorage.put(mSystemKey, lifeCycle, null); + + // Normal operation exceptions + } catch (AccessRightsException ex) { + Logger.msg("Propagating AccessRightsException back to the calling agent"); + throw ex; + } catch (InvalidTransitionException ex) { + Logger.msg("Propagating InvalidTransitionException back to the calling agent"); + throw ex; + } catch (ObjectNotFoundException ex) { + Logger.msg("Propagating ObjectNotFoundException back to the calling agent"); + throw ex; + // errors + } catch (ClusterStorageException ex) { + Logger.error(ex); + throw new PersistencyException("Error on storage: " + + ex.getMessage(), ""); + } catch (InvalidItemPathException ex) { + Logger.error(ex); + throw new AccessRightsException("Invalid Agent Id: " + agentId, + ""); + } catch (InvalidDataException ex) { + Logger.error(ex); + Logger.msg("Propagating InvalidDataException back to the calling agent"); + throw ex; + } catch (ObjectAlreadyExistsException ex) { + Logger.error(ex); + Logger.msg("Propagating ObjectAlreadyExistsException back to the calling agent"); + throw ex; + // non-CORBA exception hasn't been caught! + } catch (Throwable ex) { + Logger.error("Unknown Error: requestAction on " + mSystemKey + + " by " + agentId + " executing " + stepPath); + Logger.error(ex); + throw new InvalidDataException( + "Extraordinary Exception during execution:" + + ex.getClass().getName() + " - " + + ex.getMessage(), ""); + } + } + + @Override + public String queryLifeCycle(int agentId, boolean filter) + throws AccessRightsException, ObjectNotFoundException, + PersistencyException { + Logger.msg(1, "TraceableEntity::queryLifeCycle(" + mSystemKey + + ") - agent: " + agentId); + try { + AgentPath agent; + try { + agent = new AgentPath(agentId); + } catch (InvalidItemPathException e) { + throw new AccessRightsException("Agent " + agentId + + " doesn't exist"); + } + Workflow wf; + try { + wf = (Workflow) mStorage.get(mSystemKey, + ClusterStorage.LIFECYCLE + "/workflow", null); + } catch (ClusterStorageException e) { + Logger.error("TraceableEntity::queryLifeCycle(" + + mSystemKey + ") - Error loading workflow"); + Logger.error(e); + throw new PersistencyException("Error loading workflow"); + } + JobArrayList jobBag = new JobArrayList(); + CompositeActivity domainWf = (CompositeActivity) wf + .search("workflow/domain"); + jobBag.list = filter ? domainWf.calculateJobs(agent, + mSystemKey, true) : domainWf.calculateAllJobs(agent, + mSystemKey, true); + Logger.msg(1, "TraceableEntity::queryLifeCycle(" + mSystemKey + + ") - Returning " + jobBag.list.size() + " jobs."); + try { + return Gateway.getMarshaller().marshall(jobBag); + } catch (Exception e) { + Logger.error(e); + throw new PersistencyException("Error marshalling job bag"); + } + } catch (Throwable ex) { + Logger.error("TraceableEntity::queryLifeCycle(" + mSystemKey + + ") - Unknown error"); + Logger.error(ex); + throw new PersistencyException( + "Unknown error querying jobs. Please see server log."); + } + } + + @Override + public String queryData(String path) throws AccessRightsException, + ObjectNotFoundException, PersistencyException { + + String result = ""; + + Logger.msg(1, "TraceableEntity::queryData(" + mSystemKey + ") - " + + path); + + try { // check for cluster contents query + + if (path.endsWith("/all")) { + int allPos = path.lastIndexOf("all"); + String query = path.substring(0, allPos); + String[] ids = mStorage.getClusterContents(mSystemKey, + query); + + for (int i = 0; i < ids.length; i++) { + result += ids[i]; + + if (i != ids.length - 1) + result += ","; + } + } + // **************************************************************** + else { // retrieve the object instead + C2KLocalObject obj = mStorage.get(mSystemKey, path, null); + + // marshall it, or in the case of an outcome get the data. + result = Gateway.getMarshaller().marshall(obj); + } + } catch (ObjectNotFoundException ex) { + throw ex; + } catch (Throwable ex) { + Logger.warning("TraceableEntity::queryData(" + mSystemKey + + ") - " + path + " Failed: " + ex.getClass().getName()); + throw new PersistencyException("Server exception: " + + ex.getClass().getName(), ""); + } + + if (Logger.doLog(9)) + Logger.msg(9, "TraceableEntity::queryData(" + mSystemKey + + ") - result:" + result); + + return result; + } + + /** + * + */ + @Override + protected void finalize() throws Throwable { + Logger.msg(7, "Item "+mSystemKey+" reaped"); + Gateway.getStorage().clearCache(mSystemKey, null); + super.finalize(); + } +} diff --git a/src/main/java/com/c2kernel/entity/TraceableEntity.java b/src/main/java/com/c2kernel/entity/TraceableEntity.java index b6ccd8c..ffd5859 100644 --- a/src/main/java/com/c2kernel/entity/TraceableEntity.java +++ b/src/main/java/com/c2kernel/entity/TraceableEntity.java @@ -18,17 +18,6 @@ import com.c2kernel.common.InvalidTransitionException; import com.c2kernel.common.ObjectAlreadyExistsException; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.common.PersistencyException; -import com.c2kernel.entity.agent.JobArrayList; -import com.c2kernel.lifecycle.instance.CompositeActivity; -import com.c2kernel.lifecycle.instance.Workflow; -import com.c2kernel.lookup.AgentPath; -import com.c2kernel.lookup.InvalidEntityPathException; -import com.c2kernel.persistency.ClusterStorage; -import com.c2kernel.persistency.ClusterStorageException; -import com.c2kernel.persistency.TransactionManager; -import com.c2kernel.process.Gateway; -import com.c2kernel.property.Property; -import com.c2kernel.property.PropertyArrayList; import com.c2kernel.utils.Logger; /************************************************************************** @@ -62,10 +51,8 @@ import com.c2kernel.utils.Logger; public class TraceableEntity extends ItemPOA { - private final int mSystemKey; private final org.omg.PortableServer.POA mPoa; - private final TransactionManager mStorage; - + private final ItemImplementation mItemImpl; /************************************************************************** * Constructor used by the Locator only @@ -74,10 +61,8 @@ public class TraceableEntity extends ItemPOA org.omg.PortableServer.POA poa ) { Logger.msg(5,"TraceableEntity::constructor() - SystemKey:" + key ); - - mSystemKey = key; - mPoa = poa; - mStorage = Gateway.getStorage(); + mPoa = poa; + mItemImpl = new ItemImplementation(key); } @@ -100,8 +85,7 @@ public class TraceableEntity extends ItemPOA @Override public int getSystemKey() { - Logger.msg(8, "TraceableEntity::getSystemKey() - " + mSystemKey); - return mSystemKey; + return mItemImpl.getSystemKey(); } /************************************************************************** @@ -110,54 +94,15 @@ public class TraceableEntity extends ItemPOA @Override public void initialise( int agentId, String propString, - String initWfString + String initWfString, + String initCollsString ) throws AccessRightsException, InvalidDataException, PersistencyException { - Logger.msg(5, "TraceableEntity::initialise("+mSystemKey+") - agent:"+agentId); synchronized (this) { - Workflow lc = null; - PropertyArrayList props = null; - - AgentPath agentPath; - try { - agentPath = new AgentPath(agentId); - } catch (InvalidEntityPathException e) { - throw new AccessRightsException("Invalid Agent Id:" + agentId); - } - - //unmarshalling checks the validity of the received strings - - // create properties - if (!propString.equals("")) { - try { - props = (PropertyArrayList)Gateway.getMarshaller().unmarshall(propString); - for (Object name : props.list) { - Property thisProp = (Property)name; - mStorage.put(mSystemKey, thisProp, props); - } - } catch (Throwable ex) { - Logger.msg(8, "TraceableEntity::initialise("+mSystemKey+ ") - Properties were invalid: "+propString); - Logger.error(ex); - mStorage.abort(props); - } - mStorage.commit(props); - } - - // create wf - try { - if (initWfString == null || initWfString.equals("")) - lc = new Workflow(new CompositeActivity()); - else - lc = new Workflow((CompositeActivity)Gateway.getMarshaller().unmarshall(initWfString)); - lc.initialise(mSystemKey, agentPath); - mStorage.put(mSystemKey, lc, null); - } catch (Throwable ex) { - Logger.msg(8, "TraceableEntity::initialise("+mSystemKey+") - Workflow was invalid: "+initWfString); - Logger.error(ex); - } + mItemImpl.initialise(agentId, propString, initWfString, initCollsString); } } @@ -179,55 +124,7 @@ public class TraceableEntity extends ItemPOA ObjectAlreadyExistsException { synchronized (this) { - try { - - Logger.msg(1, "TraceableEntity::request("+mSystemKey+") - " + - transitionID + " "+stepPath + " by " +agentId ); - - AgentPath agent = new AgentPath(agentId); - Workflow lifeCycle = (Workflow)mStorage.get(mSystemKey, ClusterStorage.LIFECYCLE+"/workflow", null); - - lifeCycle.requestAction( agent, - stepPath, - mSystemKey, - transitionID, - requestData ); - - // store the workflow if we've changed the state of the domain wf - if (!(stepPath.startsWith("workflow/predefined"))) - mStorage.put(mSystemKey, lifeCycle, null); - - // Normal operation exceptions - } catch (AccessRightsException ex) { - Logger.msg("Propagating AccessRightsException back to the calling agent"); - throw ex; - } catch (InvalidTransitionException ex) { - Logger.msg("Propagating InvalidTransitionException back to the calling agent"); - throw ex; - } catch (ObjectNotFoundException ex) { - Logger.msg("Propagating ObjectNotFoundException back to the calling agent"); - throw ex; - // errors - } catch (ClusterStorageException ex) { - Logger.error(ex); - throw new PersistencyException("Error on storage: "+ex.getMessage(), ""); - } catch (InvalidEntityPathException ex) { - Logger.error(ex); - throw new AccessRightsException("Invalid Agent Id: "+agentId, ""); - } catch (InvalidDataException ex) { - Logger.error(ex); - Logger.msg("Propagating InvalidDataException back to the calling agent"); - throw ex; - } catch (ObjectAlreadyExistsException ex) { - Logger.error(ex); - Logger.msg("Propagating ObjectAlreadyExistsException back to the calling agent"); - throw ex; - // non-CORBA exception hasn't been caught! - } catch (Throwable ex) { - Logger.error("Unknown Error: requestAction on "+mSystemKey+" by "+agentId+" executing "+stepPath); - Logger.error(ex); - throw new InvalidDataException("Extraordinary Exception during execution:"+ex.getClass().getName()+" - "+ex.getMessage(), ""); - } + mItemImpl.requestAction(agentId, stepPath, transitionID, requestData); } } @@ -243,38 +140,7 @@ public class TraceableEntity extends ItemPOA PersistencyException { synchronized (this) { - Logger.msg(1, "TraceableEntity::queryLifeCycle("+mSystemKey+") - agent: " + agentId); - try { - AgentPath agent; - try { - agent = new AgentPath(agentId); - } catch (InvalidEntityPathException e) { - throw new AccessRightsException("Agent "+agentId+" doesn't exist"); - } - Workflow wf; - try { - wf = (Workflow)mStorage.get(mSystemKey, ClusterStorage.LIFECYCLE+"/workflow", null); - } catch (ClusterStorageException e) { - Logger.error("TraceableEntity::queryLifeCycle("+mSystemKey+") - Error loading workflow"); - Logger.error(e); - throw new PersistencyException("Error loading workflow"); - } - JobArrayList jobBag = new JobArrayList(); - CompositeActivity domainWf = (CompositeActivity)wf.search("workflow/domain"); - jobBag.list = filter?domainWf.calculateJobs(agent, mSystemKey, true):domainWf.calculateAllJobs(agent, mSystemKey, true); - Logger.msg(1, "TraceableEntity::queryLifeCycle("+mSystemKey+") - Returning "+jobBag.list.size()+" jobs."); - try { - return Gateway.getMarshaller().marshall( jobBag ); - } catch (Exception e) { - Logger.error(e); - throw new PersistencyException("Error marshalling job bag"); - } - } - catch ( Throwable ex ) { - Logger.error("TraceableEntity::queryLifeCycle("+mSystemKey+") - Unknown error"); - Logger.error(ex); - throw new PersistencyException("Unknown error querying jobs. Please see server log."); - } + return mItemImpl.queryLifeCycle(agentId, filter); } } @@ -296,60 +162,7 @@ public class TraceableEntity extends ItemPOA PersistencyException { synchronized (this) { - String result = ""; - - Logger.msg(1, "TraceableEntity::queryData("+mSystemKey+") - " + path ); - - try - { // check for cluster contents query - - if (path.endsWith("/all")) - { - int allPos = path.lastIndexOf("all"); - String query = path.substring(0,allPos); - String[] ids = mStorage.getClusterContents( mSystemKey, query ); - - for( int i=0; i transaction aborted!"); - } - - Logger.msg(5, "ActiveEntity::init() - completed."); - } - - /** - * - * @param propsString - * @return Properties - * @throws InvalidDataException Properties cannot be unmarshalled - * @throws ClusterStorageException - */ - private PropertyArrayList initProps( String propsString ) - throws InvalidDataException, - ClusterStorageException - { - PropertyArrayList props = null; - - // create properties - if( propsString != null && !propsString.equals("") ) - { - try - { - props = (PropertyArrayList)Gateway.getMarshaller().unmarshall(propsString); - } - catch( Exception ex ) - { - //any exception during unmarshall indicates that data was - //incorrect or the castor mapping was not set up - Logger.error(ex); - throw new InvalidDataException(ex.toString(), null); - } - - Iterator iter = props.list.iterator(); - - while( iter.hasNext() ) - mDatabase.put( mSystemKey, iter.next(), props ); - } - else - { - Logger.warning("ActiveEntity::initProps() - NO Properties!"); - } - - return props; - } /************************************************************************** * @@ -152,8 +49,8 @@ public class ActiveEntity extends AgentPOA @Override public org.omg.PortableServer.POA _default_POA() { - if(mPOA != null) - return mPOA; + if(mPoa != null) + return mPoa; else return super._default_POA(); } @@ -166,7 +63,7 @@ public class ActiveEntity extends AgentPOA @Override public int getSystemKey() { - return mSystemKey; + return mAgentImpl.getSystemKey(); } @@ -175,55 +72,14 @@ public class ActiveEntity extends AgentPOA * **************************************************************************/ @Override - public String queryData(String xpath) + public String queryData(String path) throws AccessRightsException, ObjectNotFoundException, PersistencyException { - String result = ""; - int allPos = -1; - - Logger.msg(1, "ActiveEntity::queryData("+mSystemKey+") - " + xpath ); - - try - { - if( (allPos=xpath.indexOf("all")) != -1 ) - { - String query = xpath.substring(0,allPos); - String[] ids = mDatabase.getClusterContents( mSystemKey, query ); - - for( int i=0; i, EntityProxyObserver> mSubscriptions; - - /************************************************************************** - * - **************************************************************************/ - protected EntityProxy( org.omg.CORBA.Object ior, - int systemKey) - throws ObjectNotFoundException - { - Logger.msg(8,"EntityProxy::EntityProxy() - Initialising '" +systemKey+ "' entity"); - - initialise( ior, systemKey); - } - - /************************************************************************** - * - **************************************************************************/ - private void initialise( org.omg.CORBA.Object ior, - int systemKey) - throws ObjectNotFoundException - { - Logger.msg(8, "EntityProxy::initialise() - Initialising '" +systemKey+ "' entity"); - - mIOR = ior; - mSystemKey = systemKey; - mSubscriptions = new HashMap, EntityProxyObserver>(); - } - - - /************************************************************************** - * - **************************************************************************/ - public ManageableEntity getEntity() throws ObjectNotFoundException - { - if (mEntity == null) { - mEntity = narrow(); - } - return mEntity; - } - - abstract public ManageableEntity narrow() throws ObjectNotFoundException; - - /************************************************************************** - * - **************************************************************************/ - //check who is using.. and if toString() is sufficient - @Override - public int getSystemKey() - { - return mSystemKey; - } - - - /************************************************************************** - * - **************************************************************************/ - @Override - public String queryData( String path ) - throws ObjectNotFoundException - { - - try { - Logger.msg(7, "EntityProxy.queryData() - "+mSystemKey+"/"+path); - if (path.endsWith("all")) { - Logger.msg(7, "EntityProxy.queryData() - listing contents"); - String[] result = Gateway.getStorage().getClusterContents(mSystemKey, path.substring(0, path.length()-3)); - StringBuffer retString = new StringBuffer(); - for (int i = 0; i < result.length; i++) { - retString.append(result[i]); - if (i"+e.getMessage()+""; - } - } - - public String[] getContents( String path ) throws ObjectNotFoundException { - try { - return Gateway.getStorage().getClusterContents(mSystemKey, path.substring(0, path.length())); - } catch (ClusterStorageException e) { - throw new ObjectNotFoundException(e.toString()); - } - } - - - /************************************************************************** - * - **************************************************************************/ - public C2KLocalObject getObject( String xpath ) - throws ObjectNotFoundException - { - // load from storage, falling back to proxy loader if not found in others - try - { - return Gateway.getStorage().get( mSystemKey, xpath , null); - } - catch( ClusterStorageException ex ) - { - Logger.msg(4, "Exception loading object :"+mSystemKey+"/"+xpath); - throw new ObjectNotFoundException( ex.toString() ); - } - } - - - - public String getProperty( String name ) - throws ObjectNotFoundException - { - Logger.msg(5, "Get property "+name+" from syskey/"+mSystemKey); - Property prop = (Property)getObject("Property/"+name); - try - { - return prop.getValue(); - } - catch (NullPointerException ex) - { - throw new ObjectNotFoundException(); - } - } - - public String getName() - { - try { - return getProperty("Name"); - } catch (ObjectNotFoundException ex) { - return null; - } - } - - - /************************************************************************** - * Subscription methods - **************************************************************************/ - - public void subscribe (MemberSubscription newSub) { - - newSub.setSubject(this); - synchronized (this){ - mSubscriptions.put( newSub, newSub.getObserver() ); - } - new Thread(newSub).start(); - Logger.msg(7, "Subscribed "+newSub.getObserver().getClass().getName()+" for "+newSub.interest); - } - - public void unsubscribe(EntityProxyObserver observer) - { - synchronized (this){ - for (Iterator> e = mSubscriptions.keySet().iterator(); e.hasNext();) { - MemberSubscription thisSub = e.next(); - if (mSubscriptions.get( thisSub ) == observer) { - e.remove(); - Logger.msg(7, "Unsubscribed "+observer.getClass().getName()); - } - } - } - } - - public void dumpSubscriptions(int logLevel) { - if (mSubscriptions.size() == 0) return; - Logger.msg(logLevel, "Subscriptions to proxy "+mSystemKey+":"); - synchronized(this) { - for (MemberSubscription element : mSubscriptions.keySet()) { - EntityProxyObserver obs = element.getObserver(); - if (obs != null) - Logger.msg(logLevel, " "+element.getObserver().getClass().getName()+" subscribed to "+element.interest); - else - Logger.msg(logLevel, " Phantom subscription to "+element.interest); - } - } - } - - public void notify(ProxyMessage message) { - Logger.msg(4, "EntityProxy.notify() - Received change notification for "+message.getPath()+" on "+mSystemKey); - synchronized (this){ - if (!message.getServer().equals(EntityProxyManager.serverName)) - Gateway.getStorage().clearCache(mSystemKey, message.getPath()); - for (Iterator> e = mSubscriptions.keySet().iterator(); e.hasNext();) { - MemberSubscription newSub = e.next(); - if (newSub.getObserver() == null) { // phantom - Logger.msg(4, "Removing phantom subscription to "+newSub.interest); - e.remove(); - } - else - newSub.update(message.getPath(), message.getState()); - } - } - } - - /** - * If this is reaped, clear out the cache for it too. - */ - @Override - protected void finalize() throws Throwable { - Logger.msg(7, "Proxy "+mSystemKey+" reaped"); - Gateway.getStorage().clearCache(mSystemKey, null); - Gateway.getProxyManager().removeProxy(mSystemKey); - super.finalize(); - } - -} diff --git a/src/main/java/com/c2kernel/entity/proxy/EntityProxyManager.java b/src/main/java/com/c2kernel/entity/proxy/EntityProxyManager.java deleted file mode 100644 index c49e7f5..0000000 --- a/src/main/java/com/c2kernel/entity/proxy/EntityProxyManager.java +++ /dev/null @@ -1,339 +0,0 @@ -/************************************************************************** - * EntityProxyFactory.java - * - * $Revision: 1.45 $ - * $Date: 2005/05/10 11:40:09 $ - * - * Copyright (C) 2001 CERN - European Organization for Nuclear Research - * All rights reserved. - **************************************************************************/ - -package com.c2kernel.entity.proxy; - -import java.util.ArrayList; -import java.util.ConcurrentModificationException; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; - -import com.c2kernel.common.InvalidDataException; -import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.lookup.AgentPath; -import com.c2kernel.lookup.DomainPath; -import com.c2kernel.lookup.Path; -import com.c2kernel.persistency.ClusterStorage; -import com.c2kernel.process.Gateway; -import com.c2kernel.property.Property; -import com.c2kernel.utils.Logger; -import com.c2kernel.utils.SoftCache; -import com.c2kernel.utils.server.SimpleTCPIPServer; - - -public class EntityProxyManager -{ - SoftCache proxyPool = new SoftCache(50); - HashMap treeSubscribers = new HashMap(); - HashMap connections = new HashMap(); - - // server objects - static ArrayList proxyClients = new ArrayList(); - static SimpleTCPIPServer proxyServer = null; - static String serverName = null; - - /** - * Create an entity proxy manager to listen for proxy events and reap unused proxies - */ - public EntityProxyManager() - { - Logger.msg(5, "EntityProxyManager - Starting....."); - - Enumeration servers = Gateway.getLDAPLookup().searchEntities(new DomainPath("/servers")); - while(servers.hasMoreElements()) { - Path thisServerPath = servers.nextElement(); - try { - int syskey = thisServerPath.getSysKey(); - String remoteServer = ((Property)Gateway.getStorage().get(syskey, ClusterStorage.PROPERTY+"/Name", null)).getValue(); - String portStr = ((Property)Gateway.getStorage().get(syskey, ClusterStorage.PROPERTY+"/ProxyPort", null)).getValue(); - int remotePort = Integer.parseInt(portStr); - connectToProxyServer(remoteServer, remotePort); - - } catch (Exception ex) { - Logger.error("Exception retrieving proxy server connection data for "+thisServerPath); - Logger.error(ex); - } - } - } - - public void connectToProxyServer(String name, int port) { - ProxyServerConnection oldConn = connections.get(name); - if (oldConn != null) - oldConn.shutdown(); - connections.put(name, new ProxyServerConnection(name, port, this)); - } - - - protected void resubscribe(ProxyServerConnection conn) { - synchronized (proxyPool) { - for (Integer key : proxyPool.keySet()) { - ProxyMessage sub = new ProxyMessage(key.intValue(), ProxyMessage.ADDPATH, false); - Logger.msg(5, "Subscribing to entity "+key); - conn.sendMessage(sub); - } - } - } - - /** - * @param sub - */ - private void sendMessage(ProxyMessage sub) { - for (ProxyServerConnection element : connections.values()) { - element.sendMessage(sub); - } - - } - - public void shutdown() { - Logger.msg("EntityProxyManager.shutdown() - flagging shutdown of server connections"); - for (ProxyServerConnection element : connections.values()) { - element.shutdown(); - } - } - - protected void processMessage(ProxyMessage thisMessage) throws InvalidDataException { - if (Logger.doLog(9)) Logger.msg(9, thisMessage.toString()); - - if (thisMessage.getPath().equals(ProxyMessage.PINGPATH)) // ping response - return; - - if (thisMessage.getSysKey() == ProxyMessage.NA) // must be domain path info - informTreeSubscribers(thisMessage.getState(), thisMessage.getPath()); - else { - // proper proxy message - Logger.msg(5, "Received proxy message: "+thisMessage.toString()); - Integer key = new Integer(thisMessage.getSysKey()); - EntityProxy relevant = proxyPool.get(key); - if (relevant == null) - Logger.warning("Received proxy message for sysKey "+thisMessage.getSysKey()+" which we don't have a proxy for."); - else - try { - relevant.notify(thisMessage); - } catch (Throwable ex) { - Logger.error("Error caught notifying proxy listener "+relevant.toString()+" of "+thisMessage.toString()); - Logger.error(ex); - } - } - } - - private void informTreeSubscribers(boolean state, String path) { - DomainPath last = new DomainPath(path); - DomainPath parent; boolean first = true; - synchronized(treeSubscribers) { - while((parent = last.getParent()) != null) { - ArrayList currentKeys = new ArrayList(); - currentKeys.addAll(treeSubscribers.keySet()); - for (DomainPathSubscriber sub : currentKeys) { - DomainPath interest = treeSubscribers.get(sub); - if (interest!= null && interest.equals(parent)) { - if (state == ProxyMessage.ADDED) - sub.pathAdded(last); - else if (first) - sub.pathRemoved(last); - } - } - last = parent; - first = false; - } - } - } - - public void subscribeTree(DomainPathSubscriber sub, DomainPath interest) { - synchronized(treeSubscribers) { - treeSubscribers.put(sub, interest); - } - } - - public void unsubscribeTree(DomainPathSubscriber sub) { - synchronized(treeSubscribers) { - treeSubscribers.remove(sub); - } - } - - /************************************************************************** - * - **************************************************************************/ - private EntityProxy createProxy( org.omg.CORBA.Object ior, - int systemKey, - boolean isItem ) - throws ObjectNotFoundException - { - - EntityProxy newProxy = null; - - Logger.msg(5, "EntityProxyFactory::creating proxy on entity " + systemKey); - - if( isItem ) - { - newProxy = new ItemProxy(ior, systemKey); - } - else - { - newProxy = new AgentProxy(ior, systemKey); - } - - // subscribe to changes from server - ProxyMessage sub = new ProxyMessage(systemKey, ProxyMessage.ADDPATH, false); - sendMessage(sub); - reportCurrentProxies(9); - return ( newProxy ); - } - - protected void removeProxy( int systemKey ) - { - ProxyMessage sub = new ProxyMessage(systemKey, ProxyMessage.DELPATH, true); - Logger.msg(5,"EntityProxyManager.removeProxy() - Unsubscribing to proxy informer for "+systemKey); - sendMessage(sub); - } - - - /************************************************************************** - * EntityProxy getProxy( ManageableEntity, SystemKey) - * - * Called by the other GetProxy methods. Fills in either the ior or the - * SystemKey - **************************************************************************/ - private EntityProxy getProxy( org.omg.CORBA.Object ior, - int systemKey, - boolean isItem ) - throws ObjectNotFoundException - { - Integer key = new Integer(systemKey); - - synchronized(proxyPool) { - EntityProxy newProxy; - // return it if it exists - newProxy = proxyPool.get(key); - if (newProxy == null) { - // create a new one - newProxy = createProxy(ior, systemKey, isItem ); - proxyPool.put(key, newProxy); - } - return newProxy; - - } - } - - /************************************************************************** - * EntityProxy getProxy( String ) - * - * Proxy from Alias - **************************************************************************/ - public EntityProxy getProxy( Path path ) - throws ObjectNotFoundException - { - - //convert namePath to dn format - Logger.msg(8,"EntityProxyFactory::getProxy(" + path.toString() + ")"); - boolean isItem = !(path.getEntity() instanceof AgentPath); - return getProxy( Gateway.getLDAPLookup().getIOR(path), - path.getSysKey(), - isItem ); - - } - - /************************************************************************** - * void reportCurrentProxies() - * - * A utility to Dump the current proxies loaded - **************************************************************************/ - public void reportCurrentProxies(int logLevel) - { - if (!Logger.doLog(logLevel)) return; - Logger.msg(logLevel, "Current proxies: "); - try { - synchronized(proxyPool) { - Iterator i = proxyPool.keySet().iterator(); - - for( int count=0; i.hasNext(); count++ ) - { - Integer nextProxy = i.next(); - EntityProxy thisProxy = proxyPool.get(nextProxy); - if (thisProxy != null) - Logger.msg(logLevel, - "" + count + ": " - + proxyPool.get(nextProxy).getClass().getName() - + ": " + nextProxy); - } - } - } catch (ConcurrentModificationException ex) { - Logger.msg(logLevel, "Proxy cache modified. Aborting."); - } - } - - - /************************************************************************** - * Static Proxy Server methods - **************************************************************************/ - - /** - * Initialises the Proxy event UDP server listening on 'Host.Proxy.port' from c2kprops - * @param c2kProps - */ - public static void initServer() - { - Logger.msg(5, "EntityProxyFactory::initServer - Starting....."); - int port = Gateway.getProperties().getInt("ItemServer.Proxy.port", 0); - serverName = Gateway.getProperties().getProperty("ItemServer.name"); - if (port == 0) { - Logger.error("ItemServer.Proxy.port not defined in connect file. Remote proxies will not be informed of entity changes."); - return; - } - - // set up the proxy server - try { - Logger.msg(5, "EntityProxyFactory::initServer - Initialising proxy informer on port "+port); - proxyServer = new SimpleTCPIPServer(port, ProxyClientConnection.class, 200); - proxyServer.startListening(); - } catch (Exception ex) { - Logger.error("Error setting up Proxy Server. Remote proxies will not be informed of entity changes."); - Logger.error(ex); - } - } - - public static void sendProxyEvent(ProxyMessage message) { - if (proxyServer != null && message.getPath() != null) - synchronized(proxyClients) { - for (ProxyClientConnection client : proxyClients) { - client.sendMessage(message); - } - } - } - - public static void reportConnections(int logLevel) { - synchronized(proxyClients) { - Logger.msg(logLevel, "Currently connected proxy clients:"); - for (ProxyClientConnection client : proxyClients) { - Logger.msg(logLevel, " "+client); - } - } - } - - public static void shutdownServer() { - if (proxyServer != null) { - Logger.msg(1, "EntityProxyManager: Closing Server."); - proxyServer.stopListening(); - } - } - - public static void registerProxyClient(ProxyClientConnection client) { - synchronized(proxyClients) { - proxyClients.add(client); - } - } - - public static void unRegisterProxyClient(ProxyClientConnection client) { - synchronized(proxyClients) { - proxyClients.remove(client); - } - } -} - diff --git a/src/main/java/com/c2kernel/entity/proxy/EntityProxyObserver.java b/src/main/java/com/c2kernel/entity/proxy/EntityProxyObserver.java deleted file mode 100644 index 3ddb99c..0000000 --- a/src/main/java/com/c2kernel/entity/proxy/EntityProxyObserver.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.c2kernel.entity.proxy; - -import com.c2kernel.entity.C2KLocalObject; - - - -public interface EntityProxyObserver -{ - /************************************************************************** - * Subscribed items are broken apart and fed one by one to these methods. - * Replacement after an event is done by feeding the new memberbase with the same id. - * ID could be an XPath? - **************************************************************************/ - public void add(V contents); - - /************************************************************************** - * the 'type' parameter should be an indication of the type of object - * supplied so that the subscriber can associate the call back with - * one of its subscriptions. If we go with an Xpath subscription form, - * then the id will probably be sufficient. - * Should be comparable (substring whatever) with the parameter given to - * the subscribe method of ItemProxy. - **************************************************************************/ - public void remove(String id); - - public void control(String control, String msg); -} diff --git a/src/main/java/com/c2kernel/entity/proxy/ItemProxy.java b/src/main/java/com/c2kernel/entity/proxy/ItemProxy.java index 0e6859d..355acd8 100644 --- a/src/main/java/com/c2kernel/entity/proxy/ItemProxy.java +++ b/src/main/java/com/c2kernel/entity/proxy/ItemProxy.java @@ -10,25 +10,40 @@ package com.c2kernel.entity.proxy; +import java.io.IOException; import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; + +import org.exolab.castor.mapping.MappingException; +import org.exolab.castor.xml.MarshalException; +import org.exolab.castor.xml.ValidationException; import com.c2kernel.collection.Collection; -import com.c2kernel.collection.CollectionMember; +import com.c2kernel.collection.CollectionArrayList; import com.c2kernel.common.AccessRightsException; import com.c2kernel.common.InvalidDataException; import com.c2kernel.common.InvalidTransitionException; import com.c2kernel.common.ObjectAlreadyExistsException; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.common.PersistencyException; +import com.c2kernel.entity.C2KLocalObject; import com.c2kernel.entity.Item; import com.c2kernel.entity.ItemHelper; -import com.c2kernel.entity.ManageableEntity; import com.c2kernel.entity.agent.Job; import com.c2kernel.entity.agent.JobArrayList; +import com.c2kernel.lifecycle.instance.CompositeActivity; import com.c2kernel.lifecycle.instance.Workflow; +import com.c2kernel.lookup.InvalidItemPathException; +import com.c2kernel.lookup.ItemPath; +import com.c2kernel.lookup.Path; import com.c2kernel.persistency.ClusterStorage; +import com.c2kernel.persistency.ClusterStorageException; import com.c2kernel.persistency.outcome.Viewpoint; import com.c2kernel.process.Gateway; +import com.c2kernel.property.Property; +import com.c2kernel.property.PropertyArrayList; +import com.c2kernel.utils.CastorXMLUtility; import com.c2kernel.utils.Logger; /****************************************************************************** @@ -38,43 +53,86 @@ import com.c2kernel.utils.Logger; * @version $Revision: 1.25 $ $Date: 2005/05/10 11:40:09 $ * @author $Author: abranson $ ******************************************************************************/ -public class ItemProxy extends EntityProxy +public class ItemProxy { + protected Item mItem = null; + protected org.omg.CORBA.Object mIOR; + protected int mSystemKey; + protected Path mPath; + private final HashMap, ProxyObserver> + mSubscriptions; + /************************************************************************** - * + * **************************************************************************/ protected ItemProxy( org.omg.CORBA.Object ior, int systemKey) throws ObjectNotFoundException { - super(ior, systemKey); + Logger.msg(8, "ItemProxy::initialise() - Initialising entity " +systemKey); + + mIOR = ior; + mSystemKey = systemKey; + mSubscriptions = new HashMap, ProxyObserver>(); + try { + mPath = new ItemPath(systemKey); + } catch (InvalidItemPathException e) { + throw new ObjectNotFoundException(); + } } + + public int getSystemKey() + { + return mSystemKey; + } + + public Path getPath() { + return mPath; + } + + protected Item getItem() throws ObjectNotFoundException { + if (mItem == null) + mItem = narrow(); + return mItem; + } - @Override - public ManageableEntity narrow() throws ObjectNotFoundException + public Item narrow() throws ObjectNotFoundException { try { return ItemHelper.narrow(mIOR); } catch (org.omg.CORBA.BAD_PARAM ex) { } throw new ObjectNotFoundException("CORBA Object was not an Item, or the server is down."); } - /************************************************************************** + /** + * @throws MappingException + * @throws IOException + * @throws ValidationException + * @throws MarshalException ************************************************************************ * * **************************************************************************/ - public void initialise( int agentId, - String itemProps, - String workflow ) + public void initialise( int agentId, + PropertyArrayList itemProps, + CompositeActivity workflow, + CollectionArrayList colls + ) throws AccessRightsException, InvalidDataException, PersistencyException, - ObjectNotFoundException + ObjectNotFoundException, MarshalException, ValidationException, IOException, MappingException { Logger.msg(7, "ItemProxy::initialise - started"); - - ((Item)getEntity()).initialise( agentId, itemProps, workflow ); + CastorXMLUtility xml = Gateway.getMarshaller(); + if (itemProps == null) throw new InvalidDataException("No initial properties supplied"); + String propString = xml.marshall(itemProps); + String wfString = ""; + if (workflow != null) wfString = xml.marshall(workflow); + String collString = ""; + if (colls != null) collString = xml.marshall(colls); + + getItem().initialise( agentId, propString, wfString, collString); } public void setProperty(AgentProxy agent, String name, String value) @@ -100,7 +158,7 @@ public class ItemProxy extends EntityProxy /************************************************************************** * **************************************************************************/ - protected void requestAction( Job thisJob ) + public void requestAction( Job thisJob ) throws AccessRightsException, InvalidTransitionException, ObjectNotFoundException, @@ -120,44 +178,10 @@ public class ItemProxy extends EntityProxy throw new InvalidDataException("No Agent specified.", ""); Logger.msg(7, "ItemProxy - executing "+thisJob.getStepPath()+" for "+thisJob.getAgentName()); - requestAction (thisJob.getAgentId(), thisJob.getStepPath(), + getItem().requestAction (thisJob.getAgentId(), thisJob.getStepPath(), thisJob.getTransition().getId(), outcome); } - //requestData is xmlString - public void requestAction( int agentId, - String stepPath, - int transitionID, - String requestData - ) - throws AccessRightsException, - InvalidTransitionException, - ObjectNotFoundException, - InvalidDataException, - PersistencyException, - ObjectAlreadyExistsException - { - ((Item)getEntity()).requestAction( agentId, - stepPath, - transitionID, - requestData ); - } - - /************************************************************************** - * - **************************************************************************/ - public String queryLifeCycle( int agentId, - boolean filter - ) - throws AccessRightsException, - ObjectNotFoundException, - PersistencyException - { - return ((Item)getEntity()).queryLifeCycle( agentId, - filter ); - } - - /************************************************************************** * **************************************************************************/ @@ -168,7 +192,7 @@ public class ItemProxy extends EntityProxy { JobArrayList thisJobList; try { - String jobs = queryLifeCycle(agentId, filter); + String jobs = getItem().queryLifeCycle(agentId, filter); thisJobList = (JobArrayList)Gateway.getMarshaller().unmarshall(jobs); } catch (Exception e) { @@ -208,8 +232,8 @@ public class ItemProxy extends EntityProxy } - public Collection getCollection(String collName) throws ObjectNotFoundException { - return (Collection)getObject(ClusterStorage.COLLECTION+"/"+collName); + public Collection getCollection(String collName) throws ObjectNotFoundException { + return (Collection)getObject(ClusterStorage.COLLECTION+"/"+collName); } public Workflow getWorkflow() throws ObjectNotFoundException { @@ -226,4 +250,159 @@ public class ItemProxy extends EntityProxy PersistencyException { return getJobByName(actName, agent.getSystemKey()); } + + /** + * If this is reaped, clear out the cache for it too. + */ + @Override + protected void finalize() throws Throwable { + Logger.msg(7, "Proxy "+mSystemKey+" reaped"); + Gateway.getStorage().clearCache(mSystemKey, null); + Gateway.getProxyManager().removeProxy(mSystemKey); + super.finalize(); + } + + /************************************************************************** + * + **************************************************************************/ + public String queryData( String path ) + throws ObjectNotFoundException + { + + try { + Logger.msg(7, "EntityProxy.queryData() - "+mSystemKey+"/"+path); + if (path.endsWith("all")) { + Logger.msg(7, "EntityProxy.queryData() - listing contents"); + String[] result = Gateway.getStorage().getClusterContents(mSystemKey, path.substring(0, path.length()-3)); + StringBuffer retString = new StringBuffer(); + for (int i = 0; i < result.length; i++) { + retString.append(result[i]); + if (i"+e.getMessage()+""; + } + } + + public String[] getContents( String path ) throws ObjectNotFoundException { + try { + return Gateway.getStorage().getClusterContents(mSystemKey, path.substring(0, path.length())); + } catch (ClusterStorageException e) { + throw new ObjectNotFoundException(e.toString()); + } + } + + + /************************************************************************** + * + **************************************************************************/ + public C2KLocalObject getObject( String xpath ) + throws ObjectNotFoundException + { + // load from storage, falling back to proxy loader if not found in others + try + { + return Gateway.getStorage().get( mSystemKey, xpath , null); + } + catch( ClusterStorageException ex ) + { + Logger.msg(4, "Exception loading object :"+mSystemKey+"/"+xpath); + throw new ObjectNotFoundException( ex.toString() ); + } + } + + + + public String getProperty( String name ) + throws ObjectNotFoundException + { + Logger.msg(5, "Get property "+name+" from syskey/"+mSystemKey); + Property prop = (Property)getObject("Property/"+name); + try + { + return prop.getValue(); + } + catch (NullPointerException ex) + { + throw new ObjectNotFoundException(); + } + } + + public String getName() + { + try { + return getProperty("Name"); + } catch (ObjectNotFoundException ex) { + return null; + } + } + + + + + /************************************************************************** + * Subscription methods + **************************************************************************/ + + public void subscribe(MemberSubscription newSub) { + + newSub.setSubject(this); + synchronized (this){ + mSubscriptions.put( newSub, newSub.getObserver() ); + } + new Thread(newSub).start(); + Logger.msg(7, "Subscribed "+newSub.getObserver().getClass().getName()+" for "+newSub.interest); + } + + public void unsubscribe(ProxyObserver observer) + { + synchronized (this){ + for (Iterator> e = mSubscriptions.keySet().iterator(); e.hasNext();) { + MemberSubscription thisSub = e.next(); + if (mSubscriptions.get( thisSub ) == observer) { + e.remove(); + Logger.msg(7, "Unsubscribed "+observer.getClass().getName()); + } + } + } + } + + public void dumpSubscriptions(int logLevel) { + if (mSubscriptions.size() == 0) return; + Logger.msg(logLevel, "Subscriptions to proxy "+mSystemKey+":"); + synchronized(this) { + for (MemberSubscription element : mSubscriptions.keySet()) { + ProxyObserver obs = element.getObserver(); + if (obs != null) + Logger.msg(logLevel, " "+element.getObserver().getClass().getName()+" subscribed to "+element.interest); + else + Logger.msg(logLevel, " Phantom subscription to "+element.interest); + } + } + } + + public void notify(ProxyMessage message) { + Logger.msg(4, "EntityProxy.notify() - Received change notification for "+message.getPath()+" on "+mSystemKey); + synchronized (this){ + if (!message.getServer().equals(ProxyManager.serverName)) + Gateway.getStorage().clearCache(mSystemKey, message.getPath()); + for (Iterator> e = mSubscriptions.keySet().iterator(); e.hasNext();) { + MemberSubscription newSub = e.next(); + if (newSub.getObserver() == null) { // phantom + Logger.msg(4, "Removing phantom subscription to "+newSub.interest); + e.remove(); + } + else + newSub.update(message.getPath(), message.getState()); + } + } + } } diff --git a/src/main/java/com/c2kernel/entity/proxy/MemberSubscription.java b/src/main/java/com/c2kernel/entity/proxy/MemberSubscription.java index 1de18f8..01994e4 100644 --- a/src/main/java/com/c2kernel/entity/proxy/MemberSubscription.java +++ b/src/main/java/com/c2kernel/entity/proxy/MemberSubscription.java @@ -12,14 +12,14 @@ public class MemberSubscription implements Runnable { public static final String ERROR = "Error"; public static final String END = "theEND"; - EntityProxy subject; + ItemProxy subject; String interest; // keep the subscriber by weak reference, so it is not kept from the garbage collector if no longer used - WeakReference> observerReference; + WeakReference> observerReference; ArrayList contents = new ArrayList(); boolean preLoad; - public MemberSubscription(EntityProxyObserver observer, String interest, boolean preLoad) { + public MemberSubscription(ProxyObserver observer, String interest, boolean preLoad) { setObserver(observer); this.interest = interest; this.preLoad = preLoad; @@ -33,7 +33,7 @@ public class MemberSubscription implements Runnable { private void loadChildren() { C newMember; - EntityProxyObserver observer = getObserver(); + ProxyObserver observer = getObserver(); if (observer == null) return; //reaped try { // fetch contents of path @@ -77,7 +77,7 @@ public class MemberSubscription implements Runnable { } public void update(String path, boolean deleted) { - EntityProxyObserver observer = getObserver(); + ProxyObserver observer = getObserver(); if (observer == null) return; //reaped Logger.msg(7, "Processing proxy message path "+path +" for "+observer+". Interest: "+interest+" Was Deleted:"+deleted); if (!path.startsWith(interest)) // doesn't concern us @@ -106,15 +106,15 @@ public class MemberSubscription implements Runnable { } } - public void setObserver(EntityProxyObserver observer) { - observerReference = new WeakReference>(observer); + public void setObserver(ProxyObserver observer) { + observerReference = new WeakReference>(observer); } - public void setSubject(EntityProxy subject) { + public void setSubject(ItemProxy subject) { this.subject = subject; } - public EntityProxyObserver getObserver() { + public ProxyObserver getObserver() { return observerReference.get(); } } diff --git a/src/main/java/com/c2kernel/entity/proxy/ProxyClientConnection.java b/src/main/java/com/c2kernel/entity/proxy/ProxyClientConnection.java index 9687f22..5abdb16 100644 --- a/src/main/java/com/c2kernel/entity/proxy/ProxyClientConnection.java +++ b/src/main/java/com/c2kernel/entity/proxy/ProxyClientConnection.java @@ -36,7 +36,7 @@ public class ProxyClientConnection implements SocketHandler { public ProxyClientConnection() { super(); thisClientId = ++clientId; - EntityProxyManager.registerProxyClient(this); + ProxyManager.registerProxyClient(this); Logger.msg(1, "Proxy Client Connection Handler "+thisClientId+" ready."); } diff --git a/src/main/java/com/c2kernel/entity/proxy/ProxyManager.java b/src/main/java/com/c2kernel/entity/proxy/ProxyManager.java new file mode 100644 index 0000000..d19e38f --- /dev/null +++ b/src/main/java/com/c2kernel/entity/proxy/ProxyManager.java @@ -0,0 +1,337 @@ +/************************************************************************** + * ProxyManager.java + * + * $Revision: 1.45 $ + * $Date: 2005/05/10 11:40:09 $ + * + * Copyright (C) 2001 CERN - European Organization for Nuclear Research + * All rights reserved. + **************************************************************************/ + +package com.c2kernel.entity.proxy; + +import java.util.ArrayList; +import java.util.ConcurrentModificationException; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; + +import com.c2kernel.common.InvalidDataException; +import com.c2kernel.common.ObjectNotFoundException; +import com.c2kernel.lookup.AgentPath; +import com.c2kernel.lookup.DomainPath; +import com.c2kernel.lookup.Path; +import com.c2kernel.persistency.ClusterStorage; +import com.c2kernel.process.Gateway; +import com.c2kernel.property.Property; +import com.c2kernel.utils.Logger; +import com.c2kernel.utils.SoftCache; +import com.c2kernel.utils.server.SimpleTCPIPServer; + + +public class ProxyManager +{ + SoftCache proxyPool = new SoftCache(50); + HashMap treeSubscribers = new HashMap(); + HashMap connections = new HashMap(); + + // server objects + static ArrayList proxyClients = new ArrayList(); + static SimpleTCPIPServer proxyServer = null; + static String serverName = null; + + /** + * Create a proxy manager to listen for proxy events and reap unused proxies + */ + public ProxyManager() + { + Logger.msg(5, "ProxyManager - Starting....."); + + Enumeration servers = Gateway.getLDAPLookup().searchEntities(new DomainPath("/servers")); + while(servers.hasMoreElements()) { + Path thisServerPath = servers.nextElement(); + try { + int syskey = thisServerPath.getSysKey(); + String remoteServer = ((Property)Gateway.getStorage().get(syskey, ClusterStorage.PROPERTY+"/Name", null)).getValue(); + String portStr = ((Property)Gateway.getStorage().get(syskey, ClusterStorage.PROPERTY+"/ProxyPort", null)).getValue(); + int remotePort = Integer.parseInt(portStr); + connectToProxyServer(remoteServer, remotePort); + + } catch (Exception ex) { + Logger.error("Exception retrieving proxy server connection data for "+thisServerPath); + Logger.error(ex); + } + } + } + + public void connectToProxyServer(String name, int port) { + ProxyServerConnection oldConn = connections.get(name); + if (oldConn != null) + oldConn.shutdown(); + connections.put(name, new ProxyServerConnection(name, port, this)); + } + + + protected void resubscribe(ProxyServerConnection conn) { + synchronized (proxyPool) { + for (Integer key : proxyPool.keySet()) { + ProxyMessage sub = new ProxyMessage(key.intValue(), ProxyMessage.ADDPATH, false); + Logger.msg(5, "Subscribing to item "+key); + conn.sendMessage(sub); + } + } + } + + /** + * @param sub + */ + private void sendMessage(ProxyMessage sub) { + for (ProxyServerConnection element : connections.values()) { + element.sendMessage(sub); + } + + } + + public void shutdown() { + Logger.msg("ProxyManager.shutdown() - flagging shutdown of server connections"); + for (ProxyServerConnection element : connections.values()) { + element.shutdown(); + } + } + + protected void processMessage(ProxyMessage thisMessage) throws InvalidDataException { + if (Logger.doLog(9)) Logger.msg(9, thisMessage.toString()); + + if (thisMessage.getPath().equals(ProxyMessage.PINGPATH)) // ping response + return; + + if (thisMessage.getSysKey() == ProxyMessage.NA) // must be domain path info + informTreeSubscribers(thisMessage.getState(), thisMessage.getPath()); + else { + // proper proxy message + Logger.msg(5, "Received proxy message: "+thisMessage.toString()); + Integer key = new Integer(thisMessage.getSysKey()); + ItemProxy relevant = proxyPool.get(key); + if (relevant == null) + Logger.warning("Received proxy message for sysKey "+thisMessage.getSysKey()+" which we don't have a proxy for."); + else + try { + relevant.notify(thisMessage); + } catch (Throwable ex) { + Logger.error("Error caught notifying proxy listener "+relevant.toString()+" of "+thisMessage.toString()); + Logger.error(ex); + } + } + } + + private void informTreeSubscribers(boolean state, String path) { + DomainPath last = new DomainPath(path); + DomainPath parent; boolean first = true; + synchronized(treeSubscribers) { + while((parent = last.getParent()) != null) { + ArrayList currentKeys = new ArrayList(); + currentKeys.addAll(treeSubscribers.keySet()); + for (DomainPathSubscriber sub : currentKeys) { + DomainPath interest = treeSubscribers.get(sub); + if (interest!= null && interest.equals(parent)) { + if (state == ProxyMessage.ADDED) + sub.pathAdded(last); + else if (first) + sub.pathRemoved(last); + } + } + last = parent; + first = false; + } + } + } + + public void subscribeTree(DomainPathSubscriber sub, DomainPath interest) { + synchronized(treeSubscribers) { + treeSubscribers.put(sub, interest); + } + } + + public void unsubscribeTree(DomainPathSubscriber sub) { + synchronized(treeSubscribers) { + treeSubscribers.remove(sub); + } + } + + /************************************************************************** + * + **************************************************************************/ + private ItemProxy createProxy( org.omg.CORBA.Object ior, + int systemKey, + boolean isItem ) + throws ObjectNotFoundException + { + + ItemProxy newProxy = null; + + Logger.msg(5, "ProxyManager::creating proxy on Item " + systemKey); + + if( isItem ) + { + newProxy = new ItemProxy(ior, systemKey); + } + else + { + newProxy = new AgentProxy(ior, systemKey); + } + + // subscribe to changes from server + ProxyMessage sub = new ProxyMessage(systemKey, ProxyMessage.ADDPATH, false); + sendMessage(sub); + reportCurrentProxies(9); + return ( newProxy ); + } + + protected void removeProxy( int systemKey ) + { + ProxyMessage sub = new ProxyMessage(systemKey, ProxyMessage.DELPATH, true); + Logger.msg(5,"ProxyManager.removeProxy() - Unsubscribing to proxy informer for "+systemKey); + sendMessage(sub); + } + + + /************************************************************************** + * Called by the other GetProxy methods. Fills in either the ior or the + * SystemKey + **************************************************************************/ + private ItemProxy getProxy( org.omg.CORBA.Object ior, + int systemKey, + boolean isItem ) + throws ObjectNotFoundException + { + Integer key = new Integer(systemKey); + + synchronized(proxyPool) { + ItemProxy newProxy; + // return it if it exists + newProxy = proxyPool.get(key); + if (newProxy == null) { + // create a new one + newProxy = createProxy(ior, systemKey, isItem ); + proxyPool.put(key, newProxy); + } + return newProxy; + + } + } + + /************************************************************************** + * ItemProxy getProxy( String ) + * + * Proxy from Alias + **************************************************************************/ + public ItemProxy getProxy( Path path ) + throws ObjectNotFoundException + { + + //convert namePath to dn format + Logger.msg(8,"ProxyManager::getProxy(" + path.toString() + ")"); + boolean isItem = !(path.getEntity() instanceof AgentPath); + return getProxy( Gateway.getLDAPLookup().getIOR(path), + path.getSysKey(), + isItem ); + + } + + /************************************************************************** + * void reportCurrentProxies() + * + * A utility to Dump the current proxies loaded + **************************************************************************/ + public void reportCurrentProxies(int logLevel) + { + if (!Logger.doLog(logLevel)) return; + Logger.msg(logLevel, "Current proxies: "); + try { + synchronized(proxyPool) { + Iterator i = proxyPool.keySet().iterator(); + + for( int count=0; i.hasNext(); count++ ) + { + Integer nextProxy = i.next(); + ItemProxy thisProxy = proxyPool.get(nextProxy); + if (thisProxy != null) + Logger.msg(logLevel, + "" + count + ": " + + proxyPool.get(nextProxy).getClass().getName() + + ": " + nextProxy); + } + } + } catch (ConcurrentModificationException ex) { + Logger.msg(logLevel, "Proxy cache modified. Aborting."); + } + } + + + /************************************************************************** + * Static Proxy Server methods + **************************************************************************/ + + /** + * Initialises the Proxy event UDP server listening on 'Host.Proxy.port' from c2kprops + * @param c2kProps + */ + public static void initServer() + { + Logger.msg(5, "ProxyManager::initServer - Starting....."); + int port = Gateway.getProperties().getInt("ItemServer.Proxy.port", 0); + serverName = Gateway.getProperties().getProperty("ItemServer.name"); + if (port == 0) { + Logger.error("ItemServer.Proxy.port not defined in connect file. Remote proxies will not be informed of changes."); + return; + } + + // set up the proxy server + try { + Logger.msg(5, "ProxyManager::initServer - Initialising proxy informer on port "+port); + proxyServer = new SimpleTCPIPServer(port, ProxyClientConnection.class, 200); + proxyServer.startListening(); + } catch (Exception ex) { + Logger.error("Error setting up Proxy Server. Remote proxies will not be informed of changes."); + Logger.error(ex); + } + } + + public static void sendProxyEvent(ProxyMessage message) { + if (proxyServer != null && message.getPath() != null) + synchronized(proxyClients) { + for (ProxyClientConnection client : proxyClients) { + client.sendMessage(message); + } + } + } + + public static void reportConnections(int logLevel) { + synchronized(proxyClients) { + Logger.msg(logLevel, "Currently connected proxy clients:"); + for (ProxyClientConnection client : proxyClients) { + Logger.msg(logLevel, " "+client); + } + } + } + + public static void shutdownServer() { + if (proxyServer != null) { + Logger.msg(1, "ProxyManager: Closing Server."); + proxyServer.stopListening(); + } + } + + public static void registerProxyClient(ProxyClientConnection client) { + synchronized(proxyClients) { + proxyClients.add(client); + } + } + + public static void unRegisterProxyClient(ProxyClientConnection client) { + synchronized(proxyClients) { + proxyClients.remove(client); + } + } +} + diff --git a/src/main/java/com/c2kernel/entity/proxy/ProxyObserver.java b/src/main/java/com/c2kernel/entity/proxy/ProxyObserver.java new file mode 100644 index 0000000..b15a972 --- /dev/null +++ b/src/main/java/com/c2kernel/entity/proxy/ProxyObserver.java @@ -0,0 +1,27 @@ +package com.c2kernel.entity.proxy; + +import com.c2kernel.entity.C2KLocalObject; + + + +public interface ProxyObserver +{ + /************************************************************************** + * Subscribed items are broken apart and fed one by one to these methods. + * Replacement after an event is done by feeding the new memberbase with the same id. + * ID could be an XPath? + **************************************************************************/ + public void add(V contents); + + /************************************************************************** + * the 'type' parameter should be an indication of the type of object + * supplied so that the subscriber can associate the call back with + * one of its subscriptions. If we go with an Xpath subscription form, + * then the id will probably be sufficient. + * Should be comparable (substring whatever) with the parameter given to + * the subscribe method of ItemProxy. + **************************************************************************/ + public void remove(String id); + + public void control(String control, String msg); +} diff --git a/src/main/java/com/c2kernel/entity/proxy/ProxyServerConnection.java b/src/main/java/com/c2kernel/entity/proxy/ProxyServerConnection.java index 6807953..54ca787 100644 --- a/src/main/java/com/c2kernel/entity/proxy/ProxyServerConnection.java +++ b/src/main/java/com/c2kernel/entity/proxy/ProxyServerConnection.java @@ -29,7 +29,7 @@ public class ProxyServerConnection extends Thread String serverName; int serverPort; Socket serverConnection; - EntityProxyManager manager; + ProxyManager manager; // for talking to the proxy server PrintWriter serverStream; boolean listening = false; @@ -38,7 +38,7 @@ public class ProxyServerConnection extends Thread /** * Create an entity proxy manager to listen for proxy events and reap unused proxies */ - public ProxyServerConnection(String host, int port, EntityProxyManager manager) + public ProxyServerConnection(String host, int port, ProxyManager manager) { Logger.msg(5, "ProxyServerConnection - Initialising connection to "+host+":"+port); serverName = host; diff --git a/src/main/java/com/c2kernel/entity/transfer/TransferItem.java b/src/main/java/com/c2kernel/entity/transfer/TransferItem.java index 520063a..df81721 100644 --- a/src/main/java/com/c2kernel/entity/transfer/TransferItem.java +++ b/src/main/java/com/c2kernel/entity/transfer/TransferItem.java @@ -9,7 +9,7 @@ import com.c2kernel.entity.C2KLocalObject; import com.c2kernel.entity.TraceableEntity; import com.c2kernel.lifecycle.instance.Workflow; import com.c2kernel.lookup.DomainPath; -import com.c2kernel.lookup.EntityPath; +import com.c2kernel.lookup.ItemPath; import com.c2kernel.lookup.Path; import com.c2kernel.persistency.ClusterStorage; import com.c2kernel.persistency.outcome.Outcome; @@ -89,7 +89,7 @@ public class TransferItem { } // create item - EntityPath entityPath = new EntityPath(sysKey); + ItemPath entityPath = new ItemPath(sysKey); TraceableEntity newItem = (TraceableEntity)Gateway.getCorbaServer().createEntity(entityPath); Gateway.getLDAPLookup().add(entityPath); @@ -107,7 +107,10 @@ public class TransferItem { throw new Exception("No workflow found in import for "+sysKey); // init item - newItem.initialise(importAgentId, Gateway.getMarshaller().marshall(props), Gateway.getMarshaller().marshall(wf.search("workflow/domain"))); + newItem.initialise(importAgentId, + Gateway.getMarshaller().marshall(props), + Gateway.getMarshaller().marshall(wf.search("workflow/domain")), + null); // store objects importByType(ClusterStorage.COLLECTION, objects); diff --git a/src/main/java/com/c2kernel/entity/transfer/TransferSet.java b/src/main/java/com/c2kernel/entity/transfer/TransferSet.java index 7a3ba2e..a7d81b6 100644 --- a/src/main/java/com/c2kernel/entity/transfer/TransferSet.java +++ b/src/main/java/com/c2kernel/entity/transfer/TransferSet.java @@ -3,7 +3,7 @@ package com.c2kernel.entity.transfer; import java.io.File; import java.util.ArrayList; -import com.c2kernel.lookup.EntityPath; +import com.c2kernel.lookup.ItemPath; import com.c2kernel.lookup.NextKeyManager; import com.c2kernel.process.Gateway; import com.c2kernel.utils.FileStringUtility; @@ -85,7 +85,7 @@ public class TransferSet { try { // find the current last key NextKeyManager nextKeyMan = Gateway.getLDAPLookup().getNextKeyManager(); - EntityPath lastKey = nextKeyMan.getLastEntityPath(); + ItemPath lastKey = nextKeyMan.getLastEntityPath(); Logger.msg(1, "Last key imported was "+packageLastKey+". LDAP lastkey was "+lastKey.getSysKey()); diff --git a/src/main/java/com/c2kernel/lifecycle/instance/WfVertex.java b/src/main/java/com/c2kernel/lifecycle/instance/WfVertex.java index a6e39ae..0fc9bf9 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/WfVertex.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/WfVertex.java @@ -13,7 +13,7 @@ import com.c2kernel.common.PersistencyException; import com.c2kernel.graph.model.GraphableVertex; import com.c2kernel.lifecycle.routingHelpers.ViewpointDataHelper; import com.c2kernel.lookup.AgentPath; -import com.c2kernel.lookup.EntityPath; +import com.c2kernel.lookup.ItemPath; import com.c2kernel.persistency.ClusterStorage; import com.c2kernel.process.Gateway; import com.c2kernel.scripting.Script; @@ -154,7 +154,7 @@ public abstract class WfVertex extends GraphableVertex //TODO: is this right? if (requiredInput.containsKey("item")) { - script.setInputParamValue("item", Gateway.getProxyManager().getProxy(new EntityPath(itemSysKey))); + script.setInputParamValue("item", Gateway.getProxyManager().getProxy(new ItemPath(itemSysKey))); } if (requiredInput.containsKey("agent")) { AgentPath systemAgent = Gateway.getLDAPLookup().getRoleManager().getAgentPath("system"); diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/AddDomainPath.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/AddDomainPath.java index d28fe3c..9eb15f2 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/AddDomainPath.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/AddDomainPath.java @@ -13,8 +13,8 @@ package com.c2kernel.lifecycle.instance.predefined; import com.c2kernel.common.InvalidDataException; import com.c2kernel.lookup.AgentPath; import com.c2kernel.lookup.DomainPath; -import com.c2kernel.lookup.EntityPath; -import com.c2kernel.lookup.InvalidEntityPathException; +import com.c2kernel.lookup.ItemPath; +import com.c2kernel.lookup.InvalidItemPathException; import com.c2kernel.lookup.LDAPLookup; import com.c2kernel.process.Gateway; import com.c2kernel.utils.Logger; @@ -39,13 +39,13 @@ public class AddDomainPath extends PredefinedStep try { - DomainPath domainPath = new DomainPath(getDataList(requestData)[0], new EntityPath(itemSysKey)); + DomainPath domainPath = new DomainPath(getDataList(requestData)[0], new ItemPath(itemSysKey)); lookupManager.add(domainPath); Logger.msg(8,"AddDomainPath::request() - systemKey:" + itemSysKey + ". Adding dompath. DONE."); return requestData; } - catch (InvalidEntityPathException ex) + catch (InvalidItemPathException ex) { Logger.error(ex); throw new InvalidDataException(ex.toString(), ""); diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/AssignItemToSlot.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/AssignItemToSlot.java index 7d36f35..78d4087 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/AssignItemToSlot.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/AssignItemToSlot.java @@ -52,7 +52,7 @@ public class AssignItemToSlot extends PredefinedStep String collName; int slotNo; - int entityKey; + int sysKey; Aggregation agg; Logger.msg(1, "AssignItemToSlot::request() - Starting."); @@ -63,7 +63,7 @@ public class AssignItemToSlot extends PredefinedStep String[] params = getDataList(requestData); collName = params[0]; slotNo = Integer.parseInt(params[1]); - entityKey = Integer.parseInt(params[2]); + sysKey = Integer.parseInt(params[2]); } catch (Exception e) { throw new InvalidDataException("Invalid parameters", ""); } @@ -85,12 +85,12 @@ public class AssignItemToSlot extends PredefinedStep boolean stored = false; for (AggregationMember member : agg.getMembers().list) { if (member.getID() == slotNo) { - if (member.getEntityKey() > -1) + if (member.getSystemKey() > -1) throw new InvalidDataException("Member slot not empty", ""); try { - member.assignEntity(entityKey); + member.assignItem(sysKey); } catch (MembershipException e) { - throw new InvalidDataException("Entity "+entityKey+" does not fit in this slot", ""); + throw new InvalidDataException("Entity "+sysKey+" does not fit in this slot", ""); } stored = true; break; diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/ClearSlot.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/ClearSlot.java index 60e63f1..772f62e 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/ClearSlot.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/ClearSlot.java @@ -76,9 +76,9 @@ public class ClearSlot extends PredefinedStep boolean stored = false; for (AggregationMember member : agg.getMembers().list) { if (member.getID() == slotNo) { - if (member.getEntityKey() > -1) + if (member.getSystemKey() > -1) throw new InvalidDataException("Member slot already empty", ""); - member.clearEntity(); + member.clearItem(); stored = true; break; } diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/CreateItemFromDescription.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/CreateItemFromDescription.java index 3197ce5..e6da64a 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/CreateItemFromDescription.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/CreateItemFromDescription.java @@ -12,9 +12,9 @@ package com.c2kernel.lifecycle.instance.predefined; import java.util.ArrayList; -import java.util.Iterator; import com.c2kernel.collection.Collection; +import com.c2kernel.collection.CollectionArrayList; import com.c2kernel.collection.CollectionDescription; import com.c2kernel.collection.CollectionMember; import com.c2kernel.common.AccessRightsException; @@ -26,7 +26,7 @@ import com.c2kernel.entity.TraceableEntity; import com.c2kernel.lifecycle.CompositeActivityDef; import com.c2kernel.lookup.AgentPath; import com.c2kernel.lookup.DomainPath; -import com.c2kernel.lookup.EntityPath; +import com.c2kernel.lookup.ItemPath; import com.c2kernel.lookup.LDAPLookup; import com.c2kernel.persistency.ClusterStorage; import com.c2kernel.persistency.TransactionManager; @@ -77,22 +77,21 @@ public class CreateItemFromDescription extends PredefinedStep throw new ObjectAlreadyExistsException("The item name " +newName+ " exists already.", ""); // get init objects - String[] collNames = storage.getClusterContents(itemSysKey, ClusterStorage.COLLECTION); - ArrayList collections = new ArrayList(); - - // loop through collections to instantiate + // loop through collections, collecting instantiated descriptions and finding the default workflow def + CollectionArrayList colls = new CollectionArrayList(); + String[] collNames = storage.getClusterContents(itemSysKey, ClusterStorage.COLLECTION); for (String collName : collNames) { Collection thisCol = (Collection)storage.get(itemSysKey, ClusterStorage.COLLECTION+"/"+collName, null); if (thisCol instanceof CollectionDescription) { CollectionDescription thisDesc = (CollectionDescription)thisCol; - collections.add(Gateway.getMarshaller().marshall(thisDesc.newInstance())); + colls.put(thisDesc.newInstance()); } else if (thisCol.getName().equalsIgnoreCase("workflow") && wfDefName == null) { ArrayList members = thisCol.getMembers().list; // get the first member from the wf collection CollectionMember wfMember = members.get(0); - wfDefName = wfMember.resolveEntity().getName(); + wfDefName = wfMember.resolveItem().getName(); Object wfVerObj = wfMember.getProperties().get("Version"); try { wfDefVer = Integer.parseInt(wfVerObj.toString()); @@ -135,7 +134,7 @@ public class CreateItemFromDescription extends PredefinedStep // generate new entity key Logger.msg(6, "CreateItemFromDescription - Requesting new sysKey"); - EntityPath entityPath = lookup.getNextKeyManager().generateNextEntityKey(); + ItemPath entityPath = lookup.getNextKeyManager().generateNextEntityKey(); // resolve the item factory Logger.msg(6, "CreateItemFromDescription - Resolving item factory"); @@ -155,18 +154,9 @@ public class CreateItemFromDescription extends PredefinedStep newItem.initialise( agent.getSysKey(), Gateway.getMarshaller().marshall(props), - Gateway.getMarshaller().marshall(wfDef.instantiate())); - - // add collections - if (collections.size() > 0) { - Logger.msg(6, "CreateItemFromDescription - Adding Collections"); - String[] colls = new String[1]; - for (Iterator iter = collections.iterator(); iter.hasNext();) { - colls[0] = iter.next(); - // TODO: initialize - newItem.requestAction(agent.getSysKey(), "workflow/predefined/AddC2KObject", PredefinedStep.DONE, PredefinedStep.bundleData(colls)); - } - } + Gateway.getMarshaller().marshall(wfDef.instantiate()), + Gateway.getMarshaller().marshall(colls) + ); // add its domain path Logger.msg(3, "CreateItemFromDescription - Creating "+context); diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/Erase.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/Erase.java index 0f3a246..412fe52 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/Erase.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/Erase.java @@ -18,7 +18,7 @@ import java.util.Enumeration; import com.c2kernel.common.InvalidDataException; import com.c2kernel.lookup.AgentPath; import com.c2kernel.lookup.DomainPath; -import com.c2kernel.lookup.EntityPath; +import com.c2kernel.lookup.ItemPath; import com.c2kernel.lookup.Path; import com.c2kernel.process.Gateway; import com.c2kernel.utils.Logger; @@ -47,7 +47,7 @@ public class Erase extends PredefinedStep try { // get all domain paths - Enumeration domPaths = Gateway.getLDAPLookup().searchAliases(new EntityPath(itemSysKey)); + Enumeration domPaths = Gateway.getLDAPLookup().searchAliases(new ItemPath(itemSysKey)); while (domPaths.hasMoreElements()) { DomainPath path = (DomainPath)domPaths.nextElement(); // delete them @@ -59,7 +59,7 @@ public class Erase extends PredefinedStep Gateway.getStorage().removeCluster(itemSysKey, "", null); //remove entity path - Gateway.getLDAPLookup().delete(new EntityPath(itemSysKey)); + Gateway.getLDAPLookup().delete(new ItemPath(itemSysKey)); } catch( Exception ex ) { diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/RemoveSlotFromCollection.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/RemoveSlotFromCollection.java index 3cc9f7c..38638cd 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/RemoveSlotFromCollection.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/RemoveSlotFromCollection.java @@ -51,7 +51,7 @@ public class RemoveSlotFromCollection extends PredefinedStep String collName; int slotNo; - int entityKey = -1; + int sysKey = -1; Collection coll; Logger.msg(1, "RemoveSlotFromCollection::request() - Starting."); @@ -61,12 +61,12 @@ public class RemoveSlotFromCollection extends PredefinedStep String[] params = getDataList(requestData); collName = params[0]; slotNo = params[1].length()>0?Integer.parseInt(params[1]):-1; - if (params.length>2) entityKey = params[2].length()>0?Integer.parseInt(params[2]):-1; + if (params.length>2) sysKey = params[2].length()>0?Integer.parseInt(params[2]):-1; } catch (Exception e) { throw new InvalidDataException("Invalid parameters", ""); } - if (slotNo == -1 && entityKey == -1) + if (slotNo == -1 && sysKey == -1) throw new InvalidDataException("Must give either slot number or entity key", ""); // load collection @@ -81,7 +81,7 @@ public class RemoveSlotFromCollection extends PredefinedStep if (slotNo == -1) { // find slot from entity key for (CollectionMember member : coll.getMembers().list) { - if (member.getEntityKey() == entityKey) { + if (member.getSystemKey() == sysKey) { slotNo = member.getID(); break; } diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewAgent.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewAgent.java index 2c025d2..baea8dd 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewAgent.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewAgent.java @@ -41,7 +41,7 @@ public class NewAgent extends ModuleImport implements java.io.Serializable { properties.add(new com.c2kernel.property.Property("Name", name, true)); properties.add(new com.c2kernel.property.Property("Type", "Agent", false)); try { - newAgentEnt.initialise(Gateway.getMarshaller().marshall(new PropertyArrayList(properties))); + newAgentEnt.initialise(agentId, Gateway.getMarshaller().marshall(new PropertyArrayList(properties)), null, null); } catch (Exception ex) { Logger.error(ex); throw new CannotManageException("Error initialising new agent"); diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java index 588b2fc..52a214e 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java @@ -6,6 +6,7 @@ import java.util.ArrayList; import org.custommonkey.xmlunit.Diff; import org.custommonkey.xmlunit.XMLUnit; +import com.c2kernel.collection.CollectionArrayList; import com.c2kernel.collection.MembershipException; import com.c2kernel.common.CannotManageException; import com.c2kernel.common.InvalidDataException; @@ -18,7 +19,7 @@ import com.c2kernel.events.History; import com.c2kernel.lifecycle.CompositeActivityDef; import com.c2kernel.lifecycle.instance.stateMachine.Transition; import com.c2kernel.lookup.DomainPath; -import com.c2kernel.lookup.EntityPath; +import com.c2kernel.lookup.ItemPath; import com.c2kernel.persistency.ClusterStorage; import com.c2kernel.persistency.ClusterStorageException; import com.c2kernel.persistency.outcome.Viewpoint; @@ -69,7 +70,7 @@ public class NewItem extends ModuleImport { public void create(int agentId, boolean reset) throws ObjectCannotBeUpdated, ObjectNotFoundException, CannotManageException, ObjectAlreadyExistsException { DomainPath domPath = new DomainPath(new DomainPath(initialPath), name); - EntityPath entPath; TraceableEntity newItem; + ItemPath entPath; TraceableEntity newItem; if (domPath.exists()) { entPath = domPath.getEntity(); newItem = Gateway.getCorbaServer().getItem(entPath.getSysKey()); @@ -98,12 +99,35 @@ public class NewItem extends ModuleImport { throw new CannotManageException("Workflow def "+workflow+" v"+usedWfVer+" for item "+domPath+" was not valid", ""); } + // create collections + CollectionArrayList colls = new CollectionArrayList(); + for (Dependency element: dependencyList) { + try { + com.c2kernel.collection.Dependency newDep = element.create(); + colls.put(newDep); + } catch (MembershipException ex) { + Logger.error(ex); + throw new CannotManageException("A specified member is not of the correct type in "+element.name, ""); + } + } + + for (Aggregation element : aggregationList) { + try { + com.c2kernel.collection.Aggregation newAgg = element.create(); + colls.put(newAgg); + } catch (MembershipException ex) { + Logger.error(ex); + throw new CannotManageException("A specified member is not of the correct type in "+element.name, ""); + } + } + + // (re)initialise the new item with properties, workflow and collections try { - // initialise the new item with workflow and properties newItem.initialise( agentId, Gateway.getMarshaller().marshall(new PropertyArrayList(properties)), - Gateway.getMarshaller().marshall(compact.instantiate())); + Gateway.getMarshaller().marshall(compact.instantiate()), + Gateway.getMarshaller().marshall(colls)); } catch (Exception ex) { Logger.error("Error initialising new item "+name ); Logger.error(ex); @@ -159,46 +183,5 @@ public class NewItem extends ModuleImport { domPath.setEntity(entPath); Gateway.getLDAPLookup().add(domPath); } - - // create collections - for (Dependency element: dependencyList) { - try { - com.c2kernel.collection.Dependency newDep = element.create(); - if (!reset) { - try { - Gateway.getStorage().get(entPath.getSysKey(), ClusterStorage.COLLECTION+"/"+newDep.getName(), null); - Logger.msg("Not overwriting dependency "+newDep.getName()); - continue; // TODO: a proper compare here - } catch (ObjectNotFoundException ex) { } // doesn't exist, ok to create - } - Gateway.getStorage().put(entPath.getSysKey(), element.create(), null); - } catch (ClusterStorageException ex) { - Logger.error(ex); - throw new CannotManageException("Could not create Dependency "+element.name, ""); - } catch (MembershipException ex) { - Logger.error(ex); - throw new CannotManageException("A specified member is not of the correct type in "+element.name, ""); - } - } - - for (Aggregation element : aggregationList) { - try { - com.c2kernel.collection.Aggregation newAgg = element.create(); - if (!reset) { - try { - Gateway.getStorage().get(entPath.getSysKey(), ClusterStorage.COLLECTION+"/"+newAgg.getName(), null); - Logger.msg("Not overwriting aggregation "+newAgg.getName()); - continue; // TODO: a proper compare here - } catch (ObjectNotFoundException ex) { } // doesn't exist, ok to create - } - Gateway.getStorage().put(entPath.getSysKey(), newAgg, null); - } catch (ClusterStorageException ex) { - Logger.error(ex); - throw new CannotManageException("Could not create Aggregation "+element.name, ""); - } catch (MembershipException ex) { - Logger.error(ex); - throw new CannotManageException("A specified member is not of the correct type in "+element.name, ""); - } - } } } diff --git a/src/main/java/com/c2kernel/lifecycle/routingHelpers/ViewpointDataHelper.java b/src/main/java/com/c2kernel/lifecycle/routingHelpers/ViewpointDataHelper.java index 0258347..5b70dd0 100644 --- a/src/main/java/com/c2kernel/lifecycle/routingHelpers/ViewpointDataHelper.java +++ b/src/main/java/com/c2kernel/lifecycle/routingHelpers/ViewpointDataHelper.java @@ -2,7 +2,7 @@ package com.c2kernel.lifecycle.routingHelpers; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.entity.proxy.ItemProxy; -import com.c2kernel.lookup.EntityPath; +import com.c2kernel.lookup.ItemPath; import com.c2kernel.persistency.ClusterStorage; import com.c2kernel.persistency.outcome.Outcome; import com.c2kernel.persistency.outcome.Viewpoint; @@ -51,12 +51,12 @@ public class ViewpointDataHelper else return errArr; // find entity - EntityPath sourcePath; + ItemPath sourcePath; try { - sourcePath = new EntityPath(Integer.parseInt(entityPath)); + sourcePath = new ItemPath(Integer.parseInt(entityPath)); } catch (Exception e) { - sourcePath = new EntityPath(entityPath); + sourcePath = new ItemPath(entityPath); } try { diff --git a/src/main/java/com/c2kernel/lookup/AgentPath.java b/src/main/java/com/c2kernel/lookup/AgentPath.java index 5ff6988..a560795 100644 --- a/src/main/java/com/c2kernel/lookup/AgentPath.java +++ b/src/main/java/com/c2kernel/lookup/AgentPath.java @@ -29,14 +29,14 @@ import com.novell.ldap.LDAPEntry; * @version $Revision: 1.12 $ $Date: 2005/10/13 08:15:00 $ * @author $Author: abranson $ **/ -public class AgentPath extends EntityPath +public class AgentPath extends ItemPath { private String mAgentName=null; private String mPassword=null; public AgentPath(int syskey, String agentName) - throws InvalidAgentPathException,InvalidEntityPathException + throws InvalidAgentPathException,InvalidItemPathException { super(syskey); if (agentName!=null && agentName.length()>0) @@ -46,16 +46,16 @@ public class AgentPath extends EntityPath } public AgentPath(int syskey) - throws InvalidEntityPathException + throws InvalidItemPathException { super(syskey); } - public AgentPath(EntityPath entity) { + public AgentPath(ItemPath entity) { super(); try { setSysKey(entity.getSysKey()); - } catch (InvalidEntityPathException ex) { + } catch (InvalidItemPathException ex) { //won't happen as the entity path was valid } } diff --git a/src/main/java/com/c2kernel/lookup/DomainPath.java b/src/main/java/com/c2kernel/lookup/DomainPath.java index ce849ce..b0784f9 100644 --- a/src/main/java/com/c2kernel/lookup/DomainPath.java +++ b/src/main/java/com/c2kernel/lookup/DomainPath.java @@ -23,7 +23,7 @@ import com.novell.ldap.LDAPAttributeSet; **/ public class DomainPath extends Path { - private EntityPath target = null; + private ItemPath target = null; protected static String mTypeRoot; /* Very simple extension to Path. Only copies constructors and defines root */ @@ -49,7 +49,7 @@ public class DomainPath extends Path super(path, Path.UNKNOWN); } - public DomainPath(String path, EntityPath entity) throws InvalidEntityPathException + public DomainPath(String path, ItemPath entity) throws InvalidItemPathException { super(path, Path.UNKNOWN); setEntity(entity); @@ -76,7 +76,7 @@ public class DomainPath extends Path return new DomainPath(parentPath); } - public void setEntity(EntityPath newTarget) { + public void setEntity(ItemPath newTarget) { if (newTarget == null) { // clear target = null; mType = Path.CONTEXT; @@ -88,7 +88,7 @@ public class DomainPath extends Path } @Override - public EntityPath getEntity() throws ObjectNotFoundException { + public ItemPath getEntity() throws ObjectNotFoundException { if (mType == UNKNOWN) { // must decide checkType(); } @@ -109,7 +109,7 @@ public class DomainPath extends Path public void checkType() { try { setEntity(Gateway.getLDAPLookup().resolvePath(this)); - } catch (InvalidEntityPathException ex) { + } catch (InvalidItemPathException ex) { Logger.error(ex); mType = CONTEXT; } catch (ObjectNotFoundException ex) { diff --git a/src/main/java/com/c2kernel/lookup/EntityPath.java b/src/main/java/com/c2kernel/lookup/EntityPath.java deleted file mode 100644 index 4f9b771..0000000 --- a/src/main/java/com/c2kernel/lookup/EntityPath.java +++ /dev/null @@ -1,175 +0,0 @@ -/************************************************************************** - * EntityPath.java - * - * $Revision: 1.14 $ - * $Date: 2006/03/03 13:52:21 $ - * - * Copyright (C) 2001 CERN - European Organization for Nuclear Research - * All rights reserved. - **************************************************************************/ - -package com.c2kernel.lookup; - -import java.util.ArrayList; - -import com.c2kernel.common.ObjectCannotBeUpdated; -import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.process.Gateway; -import com.novell.ldap.LDAPAttribute; -import com.novell.ldap.LDAPAttributeSet; - - -/** -* Extends Path to enforce SystemKey structure and support int form -* -* @version $Revision: 1.14 $ $Date: 2006/03/03 13:52:21 $ -* @author $Author: abranson $ -**/ -public class EntityPath extends Path -{ - // no of components in a syskey - public static final int elementNo = 3; - // no of digits in a syskey component - public static final int elementLen = 3; - // maximum possible int syskey - public static final int maxSysKey = (int)Math.pow(10, elementNo*elementLen)-1; - protected static String mTypeRoot; - /* - * From syskey int - * Note no EntityPath constructors allow setting of CONTEXT or ENTITY: - * The object decides that for itself from the number of components - */ - - public EntityPath(int syskey) throws InvalidEntityPathException { - super(); - setSysKey(syskey); - } - - /* - */ - public EntityPath() - { - super(); - } - - - /* - */ - public EntityPath(String[] path) throws InvalidEntityPathException - { - super(path, Path.CONTEXT); // dummy - it will get replaced in checkSysPath() - checkSysPath(); - } - - /* - */ - public EntityPath(String path) throws InvalidEntityPathException - { - super(path, Path.CONTEXT); - checkSysPath(); - } - - /* - */ - public EntityPath(EntityPath parent, String child) throws InvalidEntityPathException { - super(parent, child); - checkSysPath(); - } - - // EntityPaths root in /entity - @Override - public String getRoot() { - return "entity"; - } - - @Override - public EntityPath getEntity() throws ObjectNotFoundException { - return this; - } - - public byte[] getOID() { - if (mSysKey == Path.INVALID) return null; - return String.valueOf(mSysKey).getBytes(); - } - - /*************************************************************************/ - - /** Returns int form of syskey (if possible) - */ - @Override - public int getSysKey() { - if (mSysKey == Path.INVALID && mType == Path.ENTITY) - try { - if (mPath.length != elementNo) - throw new InvalidEntityPathException("Incorrect number of components for a system key"); - mSysKey = 0; - for (String keypart : mPath) { - if (keypart.length()!=elementLen+1) - throw new InvalidEntityPathException("Component '"+keypart+"' is not the correct size for a system key"); - for(int j=1; j= '0') && (c <='9')) - mSysKey = mSysKey*10 + c - '0'; - else - throw new InvalidEntityPathException("Component '"+keypart+"' contained a non-numeric char (excluding first char 'd')."); - - } - } - } catch (InvalidEntityPathException ex) { - mSysKey = Path.INVALID; - } - return mSysKey; - } - - /** Sets path from int syskey - */ - public void setSysKey(int sysKey) throws InvalidEntityPathException - { - if (sysKey < 0 || sysKey > maxSysKey) - throw new InvalidEntityPathException("System key "+sysKey+" out of range"); - String stringPath = Integer.toString(sysKey); - ArrayList newKey = new ArrayList(); - for (int i=0; i elementNo) - throw new InvalidEntityPathException("EntityPath cannot have more than "+elementNo+" components: "+toString()); - if (mPath.length == elementNo) - mType = Path.ENTITY; - else - mType = Path.CONTEXT; - } - - @Override - public LDAPAttributeSet createAttributeSet() throws ObjectCannotBeUpdated { - LDAPAttributeSet attrs = new LDAPAttributeSet(); - attrs.add(new LDAPAttribute("objectclass","cristalentity")); - attrs.add(new LDAPAttribute("intsyskey",Integer.toString(mSysKey))); - attrs.add(new LDAPAttribute("cn", getPath()[getPath().length-1])); - if (mIOR != null) - attrs.add(new LDAPAttribute("ior", Gateway.getORB().object_to_string(mIOR))); - return attrs; - } -} - diff --git a/src/main/java/com/c2kernel/lookup/InvalidAgentPathException.java b/src/main/java/com/c2kernel/lookup/InvalidAgentPathException.java index be4d952..a74e1ee 100644 --- a/src/main/java/com/c2kernel/lookup/InvalidAgentPathException.java +++ b/src/main/java/com/c2kernel/lookup/InvalidAgentPathException.java @@ -1,6 +1,6 @@ package com.c2kernel.lookup; -public class InvalidAgentPathException extends InvalidEntityPathException { +public class InvalidAgentPathException extends InvalidItemPathException { public InvalidAgentPathException() { super(); diff --git a/src/main/java/com/c2kernel/lookup/InvalidEntityPathException.java b/src/main/java/com/c2kernel/lookup/InvalidEntityPathException.java deleted file mode 100644 index 27c754d..0000000 --- a/src/main/java/com/c2kernel/lookup/InvalidEntityPathException.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.c2kernel.lookup; - -public class InvalidEntityPathException extends Exception { - - public InvalidEntityPathException() { - super(); - } - - public InvalidEntityPathException(String msg) { - super(msg); - } - -} diff --git a/src/main/java/com/c2kernel/lookup/InvalidItemPathException.java b/src/main/java/com/c2kernel/lookup/InvalidItemPathException.java new file mode 100644 index 0000000..5b37cd7 --- /dev/null +++ b/src/main/java/com/c2kernel/lookup/InvalidItemPathException.java @@ -0,0 +1,13 @@ +package com.c2kernel.lookup; + +public class InvalidItemPathException extends Exception { + + public InvalidItemPathException() { + super(); + } + + public InvalidItemPathException(String msg) { + super(msg); + } + +} diff --git a/src/main/java/com/c2kernel/lookup/ItemPath.java b/src/main/java/com/c2kernel/lookup/ItemPath.java new file mode 100644 index 0000000..89fe5ee --- /dev/null +++ b/src/main/java/com/c2kernel/lookup/ItemPath.java @@ -0,0 +1,175 @@ +/************************************************************************** + * EntityPath.java + * + * $Revision: 1.14 $ + * $Date: 2006/03/03 13:52:21 $ + * + * Copyright (C) 2001 CERN - European Organization for Nuclear Research + * All rights reserved. + **************************************************************************/ + +package com.c2kernel.lookup; + +import java.util.ArrayList; + +import com.c2kernel.common.ObjectCannotBeUpdated; +import com.c2kernel.common.ObjectNotFoundException; +import com.c2kernel.process.Gateway; +import com.novell.ldap.LDAPAttribute; +import com.novell.ldap.LDAPAttributeSet; + + +/** +* Extends Path to enforce SystemKey structure and support int form +* +* @version $Revision: 1.14 $ $Date: 2006/03/03 13:52:21 $ +* @author $Author: abranson $ +**/ +public class ItemPath extends Path +{ + // no of components in a syskey + public static final int elementNo = 3; + // no of digits in a syskey component + public static final int elementLen = 3; + // maximum possible int syskey + public static final int maxSysKey = (int)Math.pow(10, elementNo*elementLen)-1; + protected static String mTypeRoot; + /* + * From syskey int + * Note no EntityPath constructors allow setting of CONTEXT or ENTITY: + * The object decides that for itself from the number of components + */ + + public ItemPath(int syskey) throws InvalidItemPathException { + super(); + setSysKey(syskey); + } + + /* + */ + public ItemPath() + { + super(); + } + + + /* + */ + public ItemPath(String[] path) throws InvalidItemPathException + { + super(path, Path.CONTEXT); // dummy - it will get replaced in checkSysPath() + checkSysPath(); + } + + /* + */ + public ItemPath(String path) throws InvalidItemPathException + { + super(path, Path.CONTEXT); + checkSysPath(); + } + + /* + */ + public ItemPath(ItemPath parent, String child) throws InvalidItemPathException { + super(parent, child); + checkSysPath(); + } + + // EntityPaths root in /entity + @Override + public String getRoot() { + return "entity"; + } + + @Override + public ItemPath getEntity() throws ObjectNotFoundException { + return this; + } + + public byte[] getOID() { + if (mSysKey == Path.INVALID) return null; + return String.valueOf(mSysKey).getBytes(); + } + + /*************************************************************************/ + + /** Returns int form of syskey (if possible) + */ + @Override + public int getSysKey() { + if (mSysKey == Path.INVALID && mType == Path.ENTITY) + try { + if (mPath.length != elementNo) + throw new InvalidItemPathException("Incorrect number of components for a system key"); + mSysKey = 0; + for (String keypart : mPath) { + if (keypart.length()!=elementLen+1) + throw new InvalidItemPathException("Component '"+keypart+"' is not the correct size for a system key"); + for(int j=1; j= '0') && (c <='9')) + mSysKey = mSysKey*10 + c - '0'; + else + throw new InvalidItemPathException("Component '"+keypart+"' contained a non-numeric char (excluding first char 'd')."); + + } + } + } catch (InvalidItemPathException ex) { + mSysKey = Path.INVALID; + } + return mSysKey; + } + + /** Sets path from int syskey + */ + public void setSysKey(int sysKey) throws InvalidItemPathException + { + if (sysKey < 0 || sysKey > maxSysKey) + throw new InvalidItemPathException("System key "+sysKey+" out of range"); + String stringPath = Integer.toString(sysKey); + ArrayList newKey = new ArrayList(); + for (int i=0; i elementNo) + throw new InvalidItemPathException("EntityPath cannot have more than "+elementNo+" components: "+toString()); + if (mPath.length == elementNo) + mType = Path.ENTITY; + else + mType = Path.CONTEXT; + } + + @Override + public LDAPAttributeSet createAttributeSet() throws ObjectCannotBeUpdated { + LDAPAttributeSet attrs = new LDAPAttributeSet(); + attrs.add(new LDAPAttribute("objectclass","cristalentity")); + attrs.add(new LDAPAttribute("intsyskey",Integer.toString(mSysKey))); + attrs.add(new LDAPAttribute("cn", getPath()[getPath().length-1])); + if (mIOR != null) + attrs.add(new LDAPAttribute("ior", Gateway.getORB().object_to_string(mIOR))); + return attrs; + } +} + diff --git a/src/main/java/com/c2kernel/lookup/LDAPLookup.java b/src/main/java/com/c2kernel/lookup/LDAPLookup.java index 4ea6e68..116362e 100644 --- a/src/main/java/com/c2kernel/lookup/LDAPLookup.java +++ b/src/main/java/com/c2kernel/lookup/LDAPLookup.java @@ -12,7 +12,7 @@ import com.c2kernel.common.ObjectCannotBeUpdated; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.entity.TraceableEntity; import com.c2kernel.entity.agent.ActiveEntity; -import com.c2kernel.entity.proxy.EntityProxyManager; +import com.c2kernel.entity.proxy.ProxyManager; import com.c2kernel.entity.proxy.ProxyMessage; import com.c2kernel.process.Gateway; import com.c2kernel.property.PropertyDescription; @@ -67,13 +67,13 @@ public class LDAPLookup Path.mRootPath=props.mRootPath; Path.mLocalPath=props.mLocalPath; - EntityPath.mTypeRoot = "cn=entity,"+props.mLocalPath; + ItemPath.mTypeRoot = "cn=entity,"+props.mLocalPath; DomainPath.mTypeRoot = "cn=domain,"+props.mLocalPath; - mNextKeyManager = new NextKeyManager(this, "cn=last,"+EntityPath.mTypeRoot); + mNextKeyManager = new NextKeyManager(this, "cn=last,"+ItemPath.mTypeRoot); Logger.msg(7, "LDAP.useOldProps="+Gateway.getProperties().getBoolean("LDAP.useOldProps", false)); mPropManager = new LDAPPropertyManager(this); - mRoleManager = new LDAPRoleManager(this, "cn=agent,"+DomainPath.mTypeRoot, EntityPath.mTypeRoot); + mRoleManager = new LDAPRoleManager(this, "cn=agent,"+DomainPath.mTypeRoot, ItemPath.mTypeRoot); } @@ -199,12 +199,12 @@ public class LDAPLookup * * @param domPath * @return - * @throws InvalidEntityPathException + * @throws InvalidItemPathException * @throws ObjectNotFoundException */ - protected EntityPath resolvePath(DomainPath domPath) - throws InvalidEntityPathException, ObjectNotFoundException { - EntityPath referencedPath = null; + protected ItemPath resolvePath(DomainPath domPath) + throws InvalidItemPathException, ObjectNotFoundException { + ItemPath referencedPath = null; LDAPEntry domEntry = LDAPLookupUtils.getEntry(getConnection(), domPath .getFullDN(), LDAPSearchConstraints.DEREF_ALWAYS); String entityKey = LDAPLookupUtils.getFirstAttributeValue(domEntry, @@ -216,7 +216,7 @@ public class LDAPLookup if (objClass.equals("cristalagent")) referencedPath = new AgentPath(Integer.parseInt(entityKey)); else - referencedPath = new EntityPath(Integer.parseInt(entityKey)); + referencedPath = new ItemPath(Integer.parseInt(entityKey)); return referencedPath; } @@ -231,7 +231,7 @@ public class LDAPLookup LDAPEntry newEntry = new LDAPEntry(path.getFullDN(),attrSet); LDAPLookupUtils.addEntry(getConnection(),newEntry); if (path instanceof DomainPath) - EntityProxyManager.sendProxyEvent(new ProxyMessage(ProxyMessage.NA, path.toString(), ProxyMessage.ADDED)); + ProxyManager.sendProxyEvent(new ProxyMessage(ProxyMessage.NA, path.toString(), ProxyMessage.ADDED)); return newEntry; } catch (LDAPException ex) { if (ex.getResultCode() == LDAPException.ENTRY_ALREADY_EXISTS) @@ -251,7 +251,7 @@ public class LDAPLookup throw new ObjectCannotBeUpdated(ex.getLDAPErrorMessage(), ""); } if (path instanceof DomainPath) { - EntityProxyManager.sendProxyEvent(new ProxyMessage(ProxyMessage.NA, path.toString(), ProxyMessage.DELETED)); + ProxyManager.sendProxyEvent(new ProxyMessage(ProxyMessage.NA, path.toString(), ProxyMessage.DELETED)); } } @@ -393,7 +393,7 @@ public class LDAPLookup return search(start.getFullDN(), LDAPConnection.SCOPE_SUB, "objectClass=aliasObject", searchCons); } - public LDAPPathSet searchAliases(EntityPath entity) { + public LDAPPathSet searchAliases(ItemPath entity) { LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); searchCons.setBatchSize(0); searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER); @@ -431,7 +431,7 @@ public class LDAPLookup * @throws ObjectNotFoundException * @throws ObjectNotFoundException */ - protected Path nodeToPath(LDAPEntry entry) throws InvalidEntityPathException, ObjectNotFoundException + protected Path nodeToPath(LDAPEntry entry) throws InvalidItemPathException, ObjectNotFoundException { String dn = entry.getDN(); @@ -470,14 +470,14 @@ public class LDAPLookup thisPath = domainPath; } else if (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","cristalentity") || - (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","cristalcontext") && dn.endsWith(EntityPath.mTypeRoot))) + (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","cristalcontext") && dn.endsWith(ItemPath.mTypeRoot))) { - if(dn.endsWith(EntityPath.mTypeRoot)) { - EntityPath entityPath; + if(dn.endsWith(ItemPath.mTypeRoot)) { + ItemPath entityPath; if (entityKey != -1) - entityPath = new EntityPath(entityKey); + entityPath = new ItemPath(entityKey); else { - entityPath = new EntityPath(); + entityPath = new ItemPath(); entityPath.setDN(dn); } thisPath = entityPath; diff --git a/src/main/java/com/c2kernel/lookup/LDAPPropertyManager.java b/src/main/java/com/c2kernel/lookup/LDAPPropertyManager.java index fcf1ef8..51b9ded 100644 --- a/src/main/java/com/c2kernel/lookup/LDAPPropertyManager.java +++ b/src/main/java/com/c2kernel/lookup/LDAPPropertyManager.java @@ -35,7 +35,7 @@ public class LDAPPropertyManager { * @return * @throws ObjectNotFoundException */ - public boolean hasProperties(EntityPath thisEntity) throws ObjectNotFoundException { + public boolean hasProperties(ItemPath thisEntity) throws ObjectNotFoundException { LDAPEntry entityEntry = LDAPLookupUtils.getEntry(ldap.getConnection(), thisEntity.getFullDN()); return entityEntry.getAttribute("cristalprop") != null; } @@ -45,7 +45,7 @@ public class LDAPPropertyManager { * @return array of Property * @throws ObjectNotFoundException */ - public String[] getPropertyNames(EntityPath thisEntity) throws ObjectNotFoundException { + public String[] getPropertyNames(ItemPath thisEntity) throws ObjectNotFoundException { LDAPEntry entityEntry = LDAPLookupUtils.getEntry(ldap.getConnection(), thisEntity.getFullDN()); ArrayList propbag = new ArrayList(); LDAPAttribute props = entityEntry.getAttribute("cristalprop"); @@ -66,7 +66,7 @@ public class LDAPPropertyManager { * @return The Property object * @throws ObjectNotFoundException */ - public Property getProperty(EntityPath thisEntity, String name) throws ObjectNotFoundException { + public Property getProperty(ItemPath thisEntity, String name) throws ObjectNotFoundException { LDAPEntry entityEntry = LDAPLookupUtils.getEntry(ldap.getConnection(), thisEntity.getFullDN()); return getProperty(entityEntry, name); } @@ -77,7 +77,7 @@ public class LDAPPropertyManager { * @throws ObjectNotFoundException * @throws ObjectCannotBeUpdated */ - public void deleteProperty(EntityPath thisEntity, String name) throws ObjectNotFoundException, ObjectCannotBeUpdated { + public void deleteProperty(ItemPath thisEntity, String name) throws ObjectNotFoundException, ObjectCannotBeUpdated { LDAPEntry entityEntry = LDAPLookupUtils.getEntry(ldap.getConnection(), thisEntity.getFullDN()); Property prop = getProperty(entityEntry, name); Logger.msg(6, "LDAPLookupUtils.deleteProperty("+name+") - Deleting property"); @@ -94,7 +94,7 @@ public class LDAPPropertyManager { * @throws ObjectNotFoundException * @throws ObjectCannotBeUpdated */ - public void setProperty(EntityPath thisEntity, Property prop) throws ObjectNotFoundException, ObjectCannotBeUpdated { + public void setProperty(ItemPath thisEntity, Property prop) throws ObjectNotFoundException, ObjectCannotBeUpdated { LDAPEntry entityEntry = LDAPLookupUtils.getEntry(ldap.getConnection(), thisEntity.getFullDN()); try { Property oldProp = getProperty(entityEntry, prop.getName()); diff --git a/src/main/java/com/c2kernel/lookup/LDAPRoleManager.java b/src/main/java/com/c2kernel/lookup/LDAPRoleManager.java index f40cd53..091f6d7 100644 --- a/src/main/java/com/c2kernel/lookup/LDAPRoleManager.java +++ b/src/main/java/com/c2kernel/lookup/LDAPRoleManager.java @@ -124,7 +124,7 @@ public class LDAPRoleManager { agents.add(path); } catch (ObjectNotFoundException ex) { Logger.error("Agent "+userDN+" does not exist"); - } catch (InvalidEntityPathException ex) { + } catch (InvalidItemPathException ex) { Logger.error("Agent "+userDN+" is not a valid entity"); } } diff --git a/src/main/java/com/c2kernel/lookup/NextKeyManager.java b/src/main/java/com/c2kernel/lookup/NextKeyManager.java index a4ead4b..9aea50d 100644 --- a/src/main/java/com/c2kernel/lookup/NextKeyManager.java +++ b/src/main/java/com/c2kernel/lookup/NextKeyManager.java @@ -28,14 +28,14 @@ public class NextKeyManager { this.lastKeyPath = lastKeyPath; } - public synchronized EntityPath generateNextEntityKey() + public synchronized ItemPath generateNextEntityKey() throws ObjectCannotBeUpdated, ObjectNotFoundException { - EntityPath lastKey = getLastEntityPath(); + ItemPath lastKey = getLastEntityPath(); try { lastKey.setSysKey(lastKey.getSysKey()+1); - } catch (InvalidEntityPathException ex) { + } catch (InvalidItemPathException ex) { throw new ObjectCannotBeUpdated("Invalid syskey "+(lastKey.getSysKey()+1)+". Maybe centre is full."); } //test that storage is empty for that key @@ -56,7 +56,7 @@ public class NextKeyManager { public synchronized AgentPath generateNextAgentKey() throws ObjectCannotBeUpdated, ObjectNotFoundException { - EntityPath newEntity = generateNextEntityKey(); + ItemPath newEntity = generateNextEntityKey(); return new AgentPath(newEntity); } @@ -65,15 +65,15 @@ public class NextKeyManager { LDAPLookupUtils.setAttributeValue(ldap.getConnection(), lastKeyEntry,"intsyskey",Integer.toString(sysKey)); } - public EntityPath getLastEntityPath() throws ObjectNotFoundException + public ItemPath getLastEntityPath() throws ObjectNotFoundException { LDAPEntry lastKeyEntry = LDAPLookupUtils.getEntry(ldap.getConnection(),lastKeyPath); String lastKey = LDAPLookupUtils.getFirstAttributeValue(lastKeyEntry,"intsyskey"); try { int sysKey = Integer.parseInt(lastKey); - EntityPath sysPath = new EntityPath(sysKey); + ItemPath sysPath = new ItemPath(sysKey); return sysPath; - } catch (InvalidEntityPathException ex) { + } catch (InvalidItemPathException ex) { throw new ObjectNotFoundException("Invalid syskey. Maybe centre is full."); } catch (NumberFormatException ex) { throw new ObjectNotFoundException("Invalid syskey in lastkey."); diff --git a/src/main/java/com/c2kernel/lookup/Path.java b/src/main/java/com/c2kernel/lookup/Path.java index 4bec43a..16f3e5d 100644 --- a/src/main/java/com/c2kernel/lookup/Path.java +++ b/src/main/java/com/c2kernel/lookup/Path.java @@ -279,7 +279,7 @@ public abstract class Path implements Serializable throw new ObjectNotFoundException("No match for "+name, ""); } - public abstract EntityPath getEntity() throws ObjectNotFoundException; + public abstract ItemPath getEntity() throws ObjectNotFoundException; public abstract LDAPAttributeSet createAttributeSet() throws ObjectCannotBeUpdated; diff --git a/src/main/java/com/c2kernel/persistency/ClusterStorageManager.java b/src/main/java/com/c2kernel/persistency/ClusterStorageManager.java index 0546bab..d0c3f77 100644 --- a/src/main/java/com/c2kernel/persistency/ClusterStorageManager.java +++ b/src/main/java/com/c2kernel/persistency/ClusterStorageManager.java @@ -10,7 +10,7 @@ import java.util.StringTokenizer; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.entity.C2KLocalObject; import com.c2kernel.entity.agent.JobList; -import com.c2kernel.entity.proxy.EntityProxyManager; +import com.c2kernel.entity.proxy.ProxyManager; import com.c2kernel.entity.proxy.ProxyMessage; import com.c2kernel.events.History; import com.c2kernel.persistency.outcome.Outcome; @@ -291,7 +291,7 @@ public class ClusterStorageManager { if (Logger.doLog(9)) dumpCacheContents(9); // transmit proxy event - EntityProxyManager.sendProxyEvent( new ProxyMessage(sysKeyIntObj.intValue(), path, ProxyMessage.ADDED)); + ProxyManager.sendProxyEvent( new ProxyMessage(sysKeyIntObj.intValue(), path, ProxyMessage.ADDED)); } /** Deletes a cluster from all writers */ @@ -317,7 +317,7 @@ public class ClusterStorageManager { // transmit proxy event - EntityProxyManager.sendProxyEvent( new ProxyMessage(sysKeyIntObj.intValue(), path, ProxyMessage.DELETED)); + ProxyManager.sendProxyEvent( new ProxyMessage(sysKeyIntObj.intValue(), path, ProxyMessage.DELETED)); } public void clearCache(Integer sysKeyIntObj, String path) { diff --git a/src/main/java/com/c2kernel/persistency/LDAPClusterStorage.java b/src/main/java/com/c2kernel/persistency/LDAPClusterStorage.java index 5a305f9..2c10bbf 100644 --- a/src/main/java/com/c2kernel/persistency/LDAPClusterStorage.java +++ b/src/main/java/com/c2kernel/persistency/LDAPClusterStorage.java @@ -4,8 +4,8 @@ import java.util.StringTokenizer; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.entity.C2KLocalObject; -import com.c2kernel.lookup.EntityPath; -import com.c2kernel.lookup.InvalidEntityPathException; +import com.c2kernel.lookup.ItemPath; +import com.c2kernel.lookup.InvalidItemPathException; import com.c2kernel.lookup.LDAPPropertyManager; import com.c2kernel.process.Gateway; import com.c2kernel.property.Property; @@ -53,10 +53,10 @@ public class LDAPClusterStorage extends ClusterStorage { throw new ClusterStorageException("Path length was invalid: "+path); String type = tok.nextToken(); - EntityPath thisEntity; + ItemPath thisEntity; try { - thisEntity = new EntityPath(sysKey.intValue()); - } catch (InvalidEntityPathException e) { + thisEntity = new ItemPath(sysKey.intValue()); + } catch (InvalidItemPathException e) { throw new ClusterStorageException("Invalid Syskey:"+sysKey); } @@ -84,10 +84,10 @@ public class LDAPClusterStorage extends ClusterStorage { String type = obj.getClusterType(); - EntityPath thisEntity; + ItemPath thisEntity; try { - thisEntity = new EntityPath(sysKey.intValue()); - } catch (InvalidEntityPathException e) { + thisEntity = new ItemPath(sysKey.intValue()); + } catch (InvalidItemPathException e) { throw new ClusterStorageException("Invalid Syskey:"+sysKey); } @@ -112,10 +112,10 @@ public class LDAPClusterStorage extends ClusterStorage { throw new ClusterStorageException("Path length was invalid: "+path); String type = tok.nextToken(); - EntityPath thisEntity; + ItemPath thisEntity; try { - thisEntity = new EntityPath(sysKey.intValue()); - } catch (InvalidEntityPathException e) { + thisEntity = new ItemPath(sysKey.intValue()); + } catch (InvalidItemPathException e) { throw new ClusterStorageException("Invalid Syskey:"+sysKey); } @@ -146,7 +146,7 @@ public class LDAPClusterStorage extends ClusterStorage { String type = getClusterType(path); try { - EntityPath thisEntity = new EntityPath(sysKey.intValue()); + ItemPath thisEntity = new ItemPath(sysKey.intValue()); if (type.equals(PROPERTY)) return ldapStore.getPropertyNames(thisEntity); else @@ -160,7 +160,7 @@ public class LDAPClusterStorage extends ClusterStorage { } else throw new ClusterStorageException("Cluster type "+type+" not supported."); - } catch (InvalidEntityPathException e) { + } catch (InvalidItemPathException e) { throw new ClusterStorageException("Invalid Syskey:"+sysKey); } catch (ObjectNotFoundException e) { throw new ClusterStorageException("Entity "+sysKey+" does not exist"); diff --git a/src/main/java/com/c2kernel/persistency/ProxyLoader.java b/src/main/java/com/c2kernel/persistency/ProxyLoader.java index 4324e94..9c14df5 100644 --- a/src/main/java/com/c2kernel/persistency/ProxyLoader.java +++ b/src/main/java/com/c2kernel/persistency/ProxyLoader.java @@ -5,9 +5,9 @@ import java.util.StringTokenizer; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.entity.AgentHelper; import com.c2kernel.entity.C2KLocalObject; +import com.c2kernel.entity.Item; import com.c2kernel.entity.ItemHelper; -import com.c2kernel.entity.ManageableEntity; -import com.c2kernel.lookup.EntityPath; +import com.c2kernel.lookup.ItemPath; import com.c2kernel.lookup.LDAPLookup; import com.c2kernel.persistency.outcome.Outcome; import com.c2kernel.process.Gateway; @@ -18,7 +18,7 @@ import com.c2kernel.utils.Logger; */ public class ProxyLoader extends ClusterStorage { - HashMap entities = new HashMap(); + HashMap entities = new HashMap(); LDAPLookup lookup; @Override @@ -49,7 +49,7 @@ public class ProxyLoader extends ClusterStorage { @Override public C2KLocalObject get(Integer sysKey, String path) throws ClusterStorageException { try { - ManageableEntity thisEntity = getIOR(sysKey); + Item thisEntity = getIOR(sysKey); String type = getClusterType(path); // fetch the xml from the item @@ -90,7 +90,7 @@ public class ProxyLoader extends ClusterStorage { @Override public String[] getClusterContents(Integer sysKey, String path) throws ClusterStorageException { try { - ManageableEntity thisEntity = getIOR(sysKey); + Item thisEntity = getIOR(sysKey); String contents = thisEntity.queryData(path+"/all"); StringTokenizer tok = new StringTokenizer(contents, ","); String[] result = new String[tok.countTokens()]; @@ -104,7 +104,7 @@ public class ProxyLoader extends ClusterStorage { } } - private ManageableEntity getIOR(Integer sysKey) throws ClusterStorageException { + private Item getIOR(Integer sysKey) throws ClusterStorageException { if (entities.containsKey(sysKey)) { // check the cache Logger.msg(7, "ProxyLoader.getIOR() - "+sysKey+" cached."); @@ -113,22 +113,22 @@ public class ProxyLoader extends ClusterStorage { try { Logger.msg(7, "ProxyLoader.getIOR() - Resolving "+sysKey+"."); - org.omg.CORBA.Object ior = lookup.getIOR(new EntityPath(sysKey.intValue())); + org.omg.CORBA.Object ior = lookup.getIOR(new ItemPath(sysKey.intValue())); - ManageableEntity thisEntity = null; + Item thisItem = null; try { - thisEntity = ItemHelper.narrow(ior); + thisItem = ItemHelper.narrow(ior); } catch (org.omg.CORBA.BAD_PARAM ex) { try { - thisEntity = AgentHelper.narrow(ior); + thisItem = AgentHelper.narrow(ior); } catch (org.omg.CORBA.BAD_PARAM ex2) { throw new ClusterStorageException ("Could not narrow "+sysKey+" as a known Entity type"); } } Logger.msg(7, "ProxyLoader.getIOR() - Found "+sysKey+"."); - entities.put(sysKey, thisEntity); - return thisEntity; + entities.put(sysKey, thisItem); + return thisItem; } catch (Exception e) { throw new ClusterStorageException("Error narrowing "+sysKey+": "+e.getMessage()); } diff --git a/src/main/java/com/c2kernel/persistency/RemoteMap.java b/src/main/java/com/c2kernel/persistency/RemoteMap.java index b36648f..9f1d8a3 100644 --- a/src/main/java/com/c2kernel/persistency/RemoteMap.java +++ b/src/main/java/com/c2kernel/persistency/RemoteMap.java @@ -9,10 +9,10 @@ import java.util.TreeMap; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.entity.C2KLocalObject; -import com.c2kernel.entity.proxy.EntityProxy; -import com.c2kernel.entity.proxy.EntityProxyObserver; +import com.c2kernel.entity.proxy.ItemProxy; import com.c2kernel.entity.proxy.MemberSubscription; -import com.c2kernel.lookup.EntityPath; +import com.c2kernel.entity.proxy.ProxyObserver; +import com.c2kernel.lookup.ItemPath; import com.c2kernel.process.Gateway; import com.c2kernel.utils.Logger; @@ -34,9 +34,9 @@ public class RemoteMap extends TreeMap impl private String mPath = ""; Object keyLock = null; TransactionManager storage; - EntityProxyObserver listener; + ProxyObserver listener; Comparator comp; - EntityProxy source; + ItemProxy source; Object mLocker; // if this remote map will participate in a transaction public RemoteMap(int sysKey, String path, Object locker) { @@ -68,7 +68,7 @@ public class RemoteMap extends TreeMap impl } catch (NumberFormatException e) {} storage = Gateway.getStorage(); - listener = new EntityProxyObserver() { + listener = new ProxyObserver() { @Override public void add(V obj) { synchronized (this) { @@ -88,7 +88,7 @@ public class RemoteMap extends TreeMap impl }; try { - source = Gateway.getProxyManager().getProxy(new EntityPath(sysKey)); + source = Gateway.getProxyManager().getProxy(new ItemPath(sysKey)); source.subscribe(new MemberSubscription(listener, path, false)); } catch (Exception ex) { Logger.error("Error subscribing to remote map. Changes will not be received"); diff --git a/src/main/java/com/c2kernel/persistency/XMLClusterStorage.java b/src/main/java/com/c2kernel/persistency/XMLClusterStorage.java index f63dac6..50c76f0 100644 --- a/src/main/java/com/c2kernel/persistency/XMLClusterStorage.java +++ b/src/main/java/com/c2kernel/persistency/XMLClusterStorage.java @@ -3,8 +3,8 @@ import java.io.File; import java.util.ArrayList; import com.c2kernel.entity.C2KLocalObject; -import com.c2kernel.lookup.EntityPath; -import com.c2kernel.lookup.InvalidEntityPathException; +import com.c2kernel.lookup.ItemPath; +import com.c2kernel.lookup.InvalidItemPathException; import com.c2kernel.persistency.outcome.Outcome; import com.c2kernel.process.Gateway; import com.c2kernel.utils.FileStringUtility; @@ -145,8 +145,8 @@ public class XMLClusterStorage extends ClusterStorage { } } - protected String getFilePath(Integer sysKey, String path) throws InvalidEntityPathException { - EntityPath thisEntity = new EntityPath(sysKey.intValue()); + protected String getFilePath(Integer sysKey, String path) throws InvalidItemPathException { + ItemPath thisEntity = new ItemPath(sysKey.intValue()); if (path.length() == 0 || path.charAt(0) != '/') path = "/"+path; String filePath = rootDir+thisEntity.toString()+path; Logger.msg(8, "XMLClusterStorage.getFilePath() - "+filePath); diff --git a/src/main/java/com/c2kernel/process/Bootstrap.java b/src/main/java/com/c2kernel/process/Bootstrap.java index 601db31..e2ad24e 100644 --- a/src/main/java/com/c2kernel/process/Bootstrap.java +++ b/src/main/java/com/c2kernel/process/Bootstrap.java @@ -10,7 +10,6 @@ import org.custommonkey.xmlunit.Diff; import org.custommonkey.xmlunit.XMLUnit; import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.entity.TraceableEntity; import com.c2kernel.entity.proxy.ItemProxy; import com.c2kernel.events.Event; import com.c2kernel.events.History; @@ -22,7 +21,7 @@ import com.c2kernel.lifecycle.instance.predefined.ServerPredefinedStepContainer; import com.c2kernel.lifecycle.instance.stateMachine.Transition; import com.c2kernel.lookup.AgentPath; import com.c2kernel.lookup.DomainPath; -import com.c2kernel.lookup.EntityPath; +import com.c2kernel.lookup.ItemPath; import com.c2kernel.lookup.LDAPLookup; import com.c2kernel.lookup.Path; import com.c2kernel.lookup.RolePath; @@ -128,7 +127,7 @@ public class Bootstrap } else { DomainPath path = (DomainPath)en.nextElement(); - thisProxy = (ItemProxy)Gateway.getProxyManager().getProxy(path); + thisProxy = Gateway.getProxyManager().getProxy(path); // Verify module property and location @@ -150,7 +149,7 @@ public class Bootstrap if (!modDomPath.equals(path)) { // move item to module subtree Logger.msg("Module item "+itemName+" found with path "+path.toString()+". Moving to "+modDomPath.toString()); - modDomPath.setEntity(new EntityPath(thisProxy.getSystemKey())); + modDomPath.setEntity(new ItemPath(thisProxy.getSystemKey())); if (!modDomPath.exists()) Gateway.getLDAPLookup().add(modDomPath); Gateway.getLDAPLookup().delete(path); @@ -247,17 +246,15 @@ public class Bootstrap } - EntityPath entityPath = Gateway.getLDAPLookup().getNextKeyManager().generateNextEntityKey(); - TraceableEntity newItem = (TraceableEntity)Gateway.getCorbaServer().createEntity(entityPath); + ItemPath entityPath = Gateway.getLDAPLookup().getNextKeyManager().generateNextEntityKey(); + Gateway.getCorbaServer().createEntity(entityPath); Gateway.getLDAPLookup().add(entityPath); - newItem.initialise( - 1, - Gateway.getMarshaller().marshall(props), - Gateway.getMarshaller().marshall(ca)); DomainPath newDomPath = impHandler.getPath(itemName, ns); newDomPath.setEntity(entityPath); Gateway.getLDAPLookup().add(newDomPath); - return (ItemProxy)Gateway.getProxyManager().getProxy(entityPath); + ItemProxy newItemProxy = Gateway.getProxyManager().getProxy(entityPath); + newItemProxy.initialise( 1, props, ca, null); + return newItemProxy; } /************************************************************************** @@ -281,7 +278,7 @@ public class Bootstrap } try { - EntityPath entityPath = lookup.getNextKeyManager().generateNextEntityKey(); + ItemPath entityPath = lookup.getNextKeyManager().generateNextEntityKey(); AgentPath agentPath = new AgentPath(entityPath.getSysKey(), name); agentPath.setPassword(pass); Gateway.getCorbaServer().createEntity(agentPath); @@ -318,7 +315,7 @@ public class Bootstrap public static void createServerItem() throws Exception { String serverName = Gateway.getProperties().getProperty("ItemServer.name"); thisServerPath = new DomainPath("/servers/"+serverName); - EntityPath serverEntity; + ItemPath serverEntity; try { serverEntity = thisServerPath.getEntity(); } catch (ObjectNotFoundException ex) { diff --git a/src/main/java/com/c2kernel/process/Gateway.java b/src/main/java/com/c2kernel/process/Gateway.java index ea49ded..6c7b68d 100644 --- a/src/main/java/com/c2kernel/process/Gateway.java +++ b/src/main/java/com/c2kernel/process/Gateway.java @@ -13,7 +13,7 @@ import com.c2kernel.common.InvalidDataException; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.entity.CorbaServer; import com.c2kernel.entity.proxy.AgentProxy; -import com.c2kernel.entity.proxy.EntityProxyManager; +import com.c2kernel.entity.proxy.ProxyManager; import com.c2kernel.lookup.AgentPath; import com.c2kernel.lookup.LDAPLookup; import com.c2kernel.lookup.LDAPProperties; @@ -57,7 +57,7 @@ public class Gateway static private boolean orbDestroyed = false; static private LDAPLookup mLDAPLookup; static private TransactionManager mStorage; - static private EntityProxyManager mProxyManager; + static private ProxyManager mProxyManager; static private CorbaServer mCorbaServer; static private CastorXMLUtility mMarshaller; static private AgentProxy mCurrentUser = null; @@ -151,7 +151,7 @@ public class Gateway mLDAPLookup.install(); // start entity proxy server - EntityProxyManager.initServer(); + ProxyManager.initServer(); // Init ORB - set various config String serverName = getProperty("ItemServer.name"); @@ -329,7 +329,7 @@ public class Gateway // Init storages mStorage = new TransactionManager(); - mProxyManager = new EntityProxyManager(); + mProxyManager = new ProxyManager(); } @@ -360,7 +360,7 @@ public class Gateway if (mProxyManager != null) mProxyManager.shutdown(); mProxyManager = null; - EntityProxyManager.shutdownServer(); + ProxyManager.shutdownServer(); // close log consoles Logger.closeConsole(); @@ -405,7 +405,7 @@ public class Gateway return mResource; } - static public EntityProxyManager getProxyManager() + static public ProxyManager getProxyManager() { return mProxyManager; } diff --git a/src/main/java/com/c2kernel/process/UserCodeProcess.java b/src/main/java/com/c2kernel/process/UserCodeProcess.java index f7bbe74..47742aa 100644 --- a/src/main/java/com/c2kernel/process/UserCodeProcess.java +++ b/src/main/java/com/c2kernel/process/UserCodeProcess.java @@ -9,7 +9,7 @@ import com.c2kernel.common.InvalidTransitionException; import com.c2kernel.entity.C2KLocalObject; import com.c2kernel.entity.agent.Job; import com.c2kernel.entity.proxy.AgentProxy; -import com.c2kernel.entity.proxy.EntityProxyObserver; +import com.c2kernel.entity.proxy.ProxyObserver; import com.c2kernel.entity.proxy.MemberSubscription; import com.c2kernel.persistency.ClusterStorage; import com.c2kernel.scripting.ErrorInfo; @@ -24,7 +24,7 @@ import com.c2kernel.utils.Logger; * Copyright (C) 2003 CERN - European Organization for Nuclear Research * All rights reserved. **************************************************************************/ -public class UserCodeProcess extends StandardClient implements EntityProxyObserver, Runnable { +public class UserCodeProcess extends StandardClient implements ProxyObserver, Runnable { // Default state machine transitions private static final int START = 1; diff --git a/src/main/java/com/c2kernel/utils/DescriptionObjectCache.java b/src/main/java/com/c2kernel/utils/DescriptionObjectCache.java index d5382da..4322ef4 100644 --- a/src/main/java/com/c2kernel/utils/DescriptionObjectCache.java +++ b/src/main/java/com/c2kernel/utils/DescriptionObjectCache.java @@ -5,7 +5,7 @@ package com.c2kernel.utils; import com.c2kernel.common.InvalidDataException; import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.entity.proxy.EntityProxyObserver; +import com.c2kernel.entity.proxy.ProxyObserver; import com.c2kernel.entity.proxy.ItemProxy; import com.c2kernel.entity.proxy.MemberSubscription; import com.c2kernel.persistency.ClusterStorage; @@ -46,7 +46,7 @@ public abstract class DescriptionObjectCache { } } - public class CacheEntry implements EntityProxyObserver { + public class CacheEntry implements ProxyObserver { public String id; public ItemProxy proxy; public E def; diff --git a/src/main/resources/mapFiles/CollectionMap.xml b/src/main/resources/mapFiles/CollectionMap.xml index 804022b..ff6a61b 100644 --- a/src/main/resources/mapFiles/CollectionMap.xml +++ b/src/main/resources/mapFiles/CollectionMap.xml @@ -15,12 +15,12 @@ - - + get-method="getSystemKey" + set-method="setSystemKey"> + - - + get-method="getSystemKey" + set-method="setSystemKey"> + Date: Thu, 8 May 2014 16:29:54 +0200 Subject: Allow getDOM to return an empty Document if the outcome isn't set. Then applications can build Outcomes themselves without having to create their own DOMImplementations. Fixes #184 --- src/main/java/com/c2kernel/persistency/outcome/Outcome.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/persistency/outcome/Outcome.java b/src/main/java/com/c2kernel/persistency/outcome/Outcome.java index 9ad84b2..08fd75b 100644 --- a/src/main/java/com/c2kernel/persistency/outcome/Outcome.java +++ b/src/main/java/com/c2kernel/persistency/outcome/Outcome.java @@ -226,7 +226,10 @@ public class Outcome implements C2KLocalObject { if (dom == null && mData != null) try { synchronized (parser) { - dom = parser.parse(new InputSource(new StringReader(mData))); + if (mData!=null) + dom = parser.parse(new InputSource(new StringReader(mData))); + else + dom = parser.newDocument(); } } catch (Exception e) { Logger.error(e); -- cgit v1.2.3 From 8fc06d9c794c704eed2ab8707768fc72cc677ded Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Mon, 12 May 2014 16:55:54 +0200 Subject: Tweak locks to hopefully avoid deadlocks a bit --- .../c2kernel/persistency/TransactionManager.java | 89 +++++++++++++--------- 1 file changed, 52 insertions(+), 37 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/persistency/TransactionManager.java b/src/main/java/com/c2kernel/persistency/TransactionManager.java index 86e8199..d966eec 100644 --- a/src/main/java/com/c2kernel/persistency/TransactionManager.java +++ b/src/main/java/com/c2kernel/persistency/TransactionManager.java @@ -63,16 +63,14 @@ public class TransactionManager { Integer sysKeyIntObj = new Integer(sysKey); // check to see if the locker has been modifying this cluster - synchronized(locks) { - if (locks.containsKey(sysKeyIntObj) && locks.get(sysKeyIntObj).equals(locker)) { - ArrayList lockerTransaction = pendingTransactions.get(locker); - for (TransactionEntry thisEntry : lockerTransaction) { - if (sysKey == thisEntry.sysKey.intValue() && path.equals(thisEntry.getPath())) { - if (thisEntry.obj == null) - throw new ClusterStorageException("ClusterStorageManager.get() - Cluster " + path + " has been deleted in " + sysKey + - " but not yet committed"); - return thisEntry.obj; - } + if (locks.containsKey(sysKeyIntObj) && locks.get(sysKeyIntObj).equals(locker)) { + ArrayList lockerTransaction = pendingTransactions.get(locker); + for (TransactionEntry thisEntry : lockerTransaction) { + if (sysKey == thisEntry.sysKey.intValue() && path.equals(thisEntry.getPath())) { + if (thisEntry.obj == null) + throw new ClusterStorageException("ClusterStorageManager.get() - Cluster " + path + " has been deleted in " + sysKey + + " but not yet committed"); + return thisEntry.obj; } } } @@ -85,6 +83,7 @@ public class TransactionManager { */ public void put(int sysKey, C2KLocalObject obj, Object locker) throws ClusterStorageException { Integer sysKeyIntObj = new Integer(sysKey); + Object tempLocker = null; ArrayList lockerTransaction; String path = ClusterStorage.getPath(obj); @@ -99,28 +98,35 @@ public class TransactionManager { throw new ClusterStorageException("ClusterStorageManager.get() - Access denied: Object " + sysKeyIntObj + " has been locked for writing by " + thisLocker); } - else { // either we are the locker, or there is no locker - if (locker == null) { // non-locking put/delete - storage.put(sysKeyIntObj, obj); - return; + else { // no locks for this item + if (locker == null) { // lock the item until the non-transactional put is complete :/ + tempLocker = new Object(); + locks.put(sysKeyIntObj, tempLocker); + lockerTransaction = null; } - else {// initialise the transaction + else { // initialise the transaction locks.put(sysKeyIntObj, locker); lockerTransaction = new ArrayList(); pendingTransactions.put(locker, lockerTransaction); } } - - // create the new entry in the transaction table - TransactionEntry newEntry = new TransactionEntry(sysKeyIntObj, path, obj); - /* equals() in TransactionEntry only compares sysKey and path, so we can use - * contains() in ArrayList to looks for preexisting entries for this cluster - * and overwrite them. - */ - if (lockerTransaction.contains(newEntry)) - lockerTransaction.remove(newEntry); - lockerTransaction.add(newEntry); } + + if (tempLocker != null) { // non-locking put/delete + storage.put(sysKeyIntObj, obj); + locks.remove(sysKeyIntObj); + return; + } + + // create the new entry in the transaction table + TransactionEntry newEntry = new TransactionEntry(sysKeyIntObj, path, obj); + /* equals() in TransactionEntry only compares sysKey and path, so we can use + * contains() in ArrayList to looks for preexisting entries for this cluster + * and overwrite them. + */ + if (lockerTransaction.contains(newEntry)) + lockerTransaction.remove(newEntry); + lockerTransaction.add(newEntry); } /** Public delete method. Uses the put method, with null as the object value. @@ -128,6 +134,7 @@ public class TransactionManager { public void remove(int sysKey, String path, Object locker) throws ClusterStorageException { Integer sysKeyIntObj = new Integer(sysKey); ArrayList lockerTransaction; + Object tempLocker = null; synchronized(locks) { // look to see if this object is already locked if (locks.containsKey(sysKeyIntObj)) { @@ -141,8 +148,9 @@ public class TransactionManager { } else { // either we are the locker, or there is no locker if (locker == null) { // non-locking put/delete - storage.remove(sysKeyIntObj, path); - return; + tempLocker = new Object(); + locks.put(sysKeyIntObj, tempLocker); + lockerTransaction = null; } else {// initialise the transaction locks.put(sysKeyIntObj, locker); @@ -150,17 +158,24 @@ public class TransactionManager { pendingTransactions.put(locker, lockerTransaction); } } - - // create the new entry in the transaction table - TransactionEntry newEntry = new TransactionEntry(sysKeyIntObj, path, null); - /* equals() in TransactionEntry only compares sysKey and path, so we can use - * contains() in ArrayList to looks for preexisting entries for this cluster - * and overwrite them. - */ - if (lockerTransaction.contains(newEntry)) - lockerTransaction.remove(newEntry); - lockerTransaction.add(newEntry); } + + if (tempLocker != null) { + storage.remove(sysKeyIntObj, path); + locks.remove(sysKeyIntObj); + return; + } + + // create the new entry in the transaction table + TransactionEntry newEntry = new TransactionEntry(sysKeyIntObj, path, null); + /* equals() in TransactionEntry only compares sysKey and path, so we can use + * contains() in ArrayList to looks for preexisting entries for this cluster + * and overwrite them. + */ + if (lockerTransaction.contains(newEntry)) + lockerTransaction.remove(newEntry); + lockerTransaction.add(newEntry); + } /** -- cgit v1.2.3 From b8f1b6c330ba5117a608ae8113bad6a07d471881 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Fri, 9 May 2014 16:50:26 +0200 Subject: Return that should have been a continue. NewItem imports were bailing out if an Outcome was unchanged, skipping collection imports. --- .../c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java index 52a214e..c0197db 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java @@ -147,7 +147,7 @@ public class NewItem extends ModuleImport { Diff xmlDiff = new Diff(newOutcome.getDOM(), impView.getOutcome().getDOM()); if (xmlDiff.identical()) { Logger.msg(5, "NewItem.create() - View "+thisOutcome.schema+"/"+thisOutcome.viewname+" in "+name+" identical, no update required"); - return; + continue; } else { Logger.msg("NewItem.create() - Difference found in view "+thisOutcome.schema+"/"+thisOutcome.viewname+" in "+name+": "+xmlDiff.toString()); -- cgit v1.2.3 From 40ef76037aeac4ee2b9d857a092e5ea026c0bb5c Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Wed, 14 May 2014 13:23:26 +0200 Subject: Refactored Proxy update notification server into its own class and thread, so executions return before proxy messages are sent. Another deadlock suspect. --- .../java/com/c2kernel/entity/proxy/ItemProxy.java | 2 +- .../entity/proxy/ProxyClientConnection.java | 3 +- .../com/c2kernel/entity/proxy/ProxyManager.java | 72 +------------- .../com/c2kernel/entity/proxy/ProxyServer.java | 106 +++++++++++++++++++++ src/main/java/com/c2kernel/lookup/LDAPLookup.java | 5 +- .../persistency/ClusterStorageManager.java | 5 +- src/main/java/com/c2kernel/process/Gateway.java | 21 ++-- 7 files changed, 129 insertions(+), 85 deletions(-) create mode 100644 src/main/java/com/c2kernel/entity/proxy/ProxyServer.java (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/entity/proxy/ItemProxy.java b/src/main/java/com/c2kernel/entity/proxy/ItemProxy.java index 355acd8..f3a2f44 100644 --- a/src/main/java/com/c2kernel/entity/proxy/ItemProxy.java +++ b/src/main/java/com/c2kernel/entity/proxy/ItemProxy.java @@ -392,7 +392,7 @@ public class ItemProxy public void notify(ProxyMessage message) { Logger.msg(4, "EntityProxy.notify() - Received change notification for "+message.getPath()+" on "+mSystemKey); synchronized (this){ - if (!message.getServer().equals(ProxyManager.serverName)) + if (Gateway.getProxyServer()== null || !message.getServer().equals(Gateway.getProxyServer().getServerName())) Gateway.getStorage().clearCache(mSystemKey, message.getPath()); for (Iterator> e = mSubscriptions.keySet().iterator(); e.hasNext();) { MemberSubscription newSub = e.next(); diff --git a/src/main/java/com/c2kernel/entity/proxy/ProxyClientConnection.java b/src/main/java/com/c2kernel/entity/proxy/ProxyClientConnection.java index 5abdb16..3a7e129 100644 --- a/src/main/java/com/c2kernel/entity/proxy/ProxyClientConnection.java +++ b/src/main/java/com/c2kernel/entity/proxy/ProxyClientConnection.java @@ -11,6 +11,7 @@ import java.util.ArrayList; import java.util.Iterator; import com.c2kernel.common.InvalidDataException; +import com.c2kernel.process.Gateway; import com.c2kernel.utils.Logger; import com.c2kernel.utils.server.SocketHandler; @@ -36,7 +37,7 @@ public class ProxyClientConnection implements SocketHandler { public ProxyClientConnection() { super(); thisClientId = ++clientId; - ProxyManager.registerProxyClient(this); + Gateway.getProxyServer().registerProxyClient(this); Logger.msg(1, "Proxy Client Connection Handler "+thisClientId+" ready."); } diff --git a/src/main/java/com/c2kernel/entity/proxy/ProxyManager.java b/src/main/java/com/c2kernel/entity/proxy/ProxyManager.java index d19e38f..b217f3e 100644 --- a/src/main/java/com/c2kernel/entity/proxy/ProxyManager.java +++ b/src/main/java/com/c2kernel/entity/proxy/ProxyManager.java @@ -26,7 +26,6 @@ import com.c2kernel.process.Gateway; import com.c2kernel.property.Property; import com.c2kernel.utils.Logger; import com.c2kernel.utils.SoftCache; -import com.c2kernel.utils.server.SimpleTCPIPServer; public class ProxyManager @@ -35,11 +34,6 @@ public class ProxyManager HashMap treeSubscribers = new HashMap(); HashMap connections = new HashMap(); - // server objects - static ArrayList proxyClients = new ArrayList(); - static SimpleTCPIPServer proxyServer = null; - static String serverName = null; - /** * Create a proxy manager to listen for proxy events and reap unused proxies */ @@ -268,70 +262,6 @@ public class ProxyManager } - /************************************************************************** - * Static Proxy Server methods - **************************************************************************/ - - /** - * Initialises the Proxy event UDP server listening on 'Host.Proxy.port' from c2kprops - * @param c2kProps - */ - public static void initServer() - { - Logger.msg(5, "ProxyManager::initServer - Starting....."); - int port = Gateway.getProperties().getInt("ItemServer.Proxy.port", 0); - serverName = Gateway.getProperties().getProperty("ItemServer.name"); - if (port == 0) { - Logger.error("ItemServer.Proxy.port not defined in connect file. Remote proxies will not be informed of changes."); - return; - } - - // set up the proxy server - try { - Logger.msg(5, "ProxyManager::initServer - Initialising proxy informer on port "+port); - proxyServer = new SimpleTCPIPServer(port, ProxyClientConnection.class, 200); - proxyServer.startListening(); - } catch (Exception ex) { - Logger.error("Error setting up Proxy Server. Remote proxies will not be informed of changes."); - Logger.error(ex); - } - } - - public static void sendProxyEvent(ProxyMessage message) { - if (proxyServer != null && message.getPath() != null) - synchronized(proxyClients) { - for (ProxyClientConnection client : proxyClients) { - client.sendMessage(message); - } - } - } - - public static void reportConnections(int logLevel) { - synchronized(proxyClients) { - Logger.msg(logLevel, "Currently connected proxy clients:"); - for (ProxyClientConnection client : proxyClients) { - Logger.msg(logLevel, " "+client); - } - } - } - - public static void shutdownServer() { - if (proxyServer != null) { - Logger.msg(1, "ProxyManager: Closing Server."); - proxyServer.stopListening(); - } - } - - public static void registerProxyClient(ProxyClientConnection client) { - synchronized(proxyClients) { - proxyClients.add(client); - } - } - - public static void unRegisterProxyClient(ProxyClientConnection client) { - synchronized(proxyClients) { - proxyClients.remove(client); - } - } + } diff --git a/src/main/java/com/c2kernel/entity/proxy/ProxyServer.java b/src/main/java/com/c2kernel/entity/proxy/ProxyServer.java new file mode 100644 index 0000000..c576cda --- /dev/null +++ b/src/main/java/com/c2kernel/entity/proxy/ProxyServer.java @@ -0,0 +1,106 @@ +package com.c2kernel.entity.proxy; + +import java.util.ArrayList; +import java.util.concurrent.LinkedBlockingQueue; + +import com.c2kernel.process.Gateway; +import com.c2kernel.utils.Logger; +import com.c2kernel.utils.server.SimpleTCPIPServer; + +public class ProxyServer implements Runnable { + + // server objects + ArrayList proxyClients; + SimpleTCPIPServer proxyListener = null; + String serverName = null; + boolean keepRunning = true; + LinkedBlockingQueue messageQueue; + + public ProxyServer(String serverName) { + Logger.msg(5, "ProxyManager::initServer - Starting....."); + int port = Gateway.getProperties().getInt("ItemServer.Proxy.port", 0); + this.serverName = serverName; + this.proxyClients = new ArrayList(); + this.messageQueue = new LinkedBlockingQueue(); + + if (port == 0) { + Logger.error("ItemServer.Proxy.port not defined in connect file. Remote proxies will not be informed of changes."); + return; + } + + // set up the proxy server + try { + Logger.msg(5, "ProxyManager::initServer - Initialising proxy informer on port "+port); + proxyListener = new SimpleTCPIPServer(port, ProxyClientConnection.class, 200); + proxyListener.startListening(); + } catch (Exception ex) { + Logger.error("Error setting up Proxy Server. Remote proxies will not be informed of changes."); + Logger.error(ex); + } + // start the message queue delivery thread + new Thread(this).start(); + } + + @Override + public void run() { + + while(keepRunning) { + ProxyMessage message = messageQueue.poll(); + if (message != null) { + synchronized(proxyClients) { + for (ProxyClientConnection client : proxyClients) { + client.sendMessage(message); + } + } + } else + try { + synchronized(this) { wait(); } + } catch (InterruptedException e) { } + } + + } + + public String getServerName() { + return serverName; + } + + public void sendProxyEvent(ProxyMessage message) { + try { + synchronized(this) { + messageQueue.put(message); + notify(); + } + } catch (InterruptedException e) { } + } + + public void reportConnections(int logLevel) { + synchronized(proxyClients) { + Logger.msg(logLevel, "Currently connected proxy clients:"); + for (ProxyClientConnection client : proxyClients) { + Logger.msg(logLevel, " "+client); + } + } + } + + public void shutdownServer() { + Logger.msg(1, "ProxyManager: Closing Server."); + proxyListener.stopListening(); + synchronized(this) { + keepRunning = false; + notify(); + } + } + + public void registerProxyClient(ProxyClientConnection client) { + synchronized(proxyClients) { + proxyClients.add(client); + } + } + + public void unRegisterProxyClient(ProxyClientConnection client) { + synchronized(proxyClients) { + proxyClients.remove(client); + } + } + +} diff --git a/src/main/java/com/c2kernel/lookup/LDAPLookup.java b/src/main/java/com/c2kernel/lookup/LDAPLookup.java index 116362e..eae803b 100644 --- a/src/main/java/com/c2kernel/lookup/LDAPLookup.java +++ b/src/main/java/com/c2kernel/lookup/LDAPLookup.java @@ -12,7 +12,6 @@ import com.c2kernel.common.ObjectCannotBeUpdated; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.entity.TraceableEntity; import com.c2kernel.entity.agent.ActiveEntity; -import com.c2kernel.entity.proxy.ProxyManager; import com.c2kernel.entity.proxy.ProxyMessage; import com.c2kernel.process.Gateway; import com.c2kernel.property.PropertyDescription; @@ -231,7 +230,7 @@ public class LDAPLookup LDAPEntry newEntry = new LDAPEntry(path.getFullDN(),attrSet); LDAPLookupUtils.addEntry(getConnection(),newEntry); if (path instanceof DomainPath) - ProxyManager.sendProxyEvent(new ProxyMessage(ProxyMessage.NA, path.toString(), ProxyMessage.ADDED)); + Gateway.getProxyServer().sendProxyEvent(new ProxyMessage(ProxyMessage.NA, path.toString(), ProxyMessage.ADDED)); return newEntry; } catch (LDAPException ex) { if (ex.getResultCode() == LDAPException.ENTRY_ALREADY_EXISTS) @@ -251,7 +250,7 @@ public class LDAPLookup throw new ObjectCannotBeUpdated(ex.getLDAPErrorMessage(), ""); } if (path instanceof DomainPath) { - ProxyManager.sendProxyEvent(new ProxyMessage(ProxyMessage.NA, path.toString(), ProxyMessage.DELETED)); + Gateway.getProxyServer().sendProxyEvent(new ProxyMessage(ProxyMessage.NA, path.toString(), ProxyMessage.DELETED)); } } diff --git a/src/main/java/com/c2kernel/persistency/ClusterStorageManager.java b/src/main/java/com/c2kernel/persistency/ClusterStorageManager.java index d0c3f77..20857c6 100644 --- a/src/main/java/com/c2kernel/persistency/ClusterStorageManager.java +++ b/src/main/java/com/c2kernel/persistency/ClusterStorageManager.java @@ -10,7 +10,6 @@ import java.util.StringTokenizer; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.entity.C2KLocalObject; import com.c2kernel.entity.agent.JobList; -import com.c2kernel.entity.proxy.ProxyManager; import com.c2kernel.entity.proxy.ProxyMessage; import com.c2kernel.events.History; import com.c2kernel.persistency.outcome.Outcome; @@ -291,7 +290,7 @@ public class ClusterStorageManager { if (Logger.doLog(9)) dumpCacheContents(9); // transmit proxy event - ProxyManager.sendProxyEvent( new ProxyMessage(sysKeyIntObj.intValue(), path, ProxyMessage.ADDED)); + Gateway.getProxyServer().sendProxyEvent( new ProxyMessage(sysKeyIntObj.intValue(), path, ProxyMessage.ADDED)); } /** Deletes a cluster from all writers */ @@ -317,7 +316,7 @@ public class ClusterStorageManager { // transmit proxy event - ProxyManager.sendProxyEvent( new ProxyMessage(sysKeyIntObj.intValue(), path, ProxyMessage.DELETED)); + Gateway.getProxyServer().sendProxyEvent( new ProxyMessage(sysKeyIntObj.intValue(), path, ProxyMessage.DELETED)); } public void clearCache(Integer sysKeyIntObj, String path) { diff --git a/src/main/java/com/c2kernel/process/Gateway.java b/src/main/java/com/c2kernel/process/Gateway.java index 6c7b68d..01cc202 100644 --- a/src/main/java/com/c2kernel/process/Gateway.java +++ b/src/main/java/com/c2kernel/process/Gateway.java @@ -14,6 +14,7 @@ import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.entity.CorbaServer; import com.c2kernel.entity.proxy.AgentProxy; import com.c2kernel.entity.proxy.ProxyManager; +import com.c2kernel.entity.proxy.ProxyServer; import com.c2kernel.lookup.AgentPath; import com.c2kernel.lookup.LDAPLookup; import com.c2kernel.lookup.LDAPProperties; @@ -57,7 +58,8 @@ public class Gateway static private boolean orbDestroyed = false; static private LDAPLookup mLDAPLookup; static private TransactionManager mStorage; - static private ProxyManager mProxyManager; + static private ProxyManager mProxyManager; + static private ProxyServer mProxyServer; static private CorbaServer mCorbaServer; static private CastorXMLUtility mMarshaller; static private AgentProxy mCurrentUser = null; @@ -151,13 +153,13 @@ public class Gateway mLDAPLookup.install(); // start entity proxy server - ProxyManager.initServer(); + mProxyServer = new ProxyServer(mC2KProps.getProperty("ItemServer.name")); // Init ORB - set various config - String serverName = getProperty("ItemServer.name"); + String serverName = mC2KProps.getProperty("ItemServer.name"); if (serverName != null) mC2KProps.put("com.sun.CORBA.ORBServerHost", serverName); - String serverPort = getProperty("ItemServer.iiop", "1500"); + String serverPort = mC2KProps.getProperty("ItemServer.iiop", "1500"); mC2KProps.put("com.sun.CORBA.ORBServerPort", serverPort); //TODO: externalize this (or replace corba completely) mC2KProps.put("com.sun.CORBA.POA.ORBServerId", "1"); @@ -356,11 +358,13 @@ public class Gateway mLDAPLookup.disconnect(); mLDAPLookup = null; - // shut down proxy manager + // shut down proxy manager & server + if (mProxyServer != null) + mProxyServer.shutdownServer(); if (mProxyManager != null) mProxyManager.shutdown(); mProxyManager = null; - ProxyManager.shutdownServer(); + // close log consoles Logger.closeConsole(); @@ -410,6 +414,11 @@ public class Gateway return mProxyManager; } + + public static ProxyServer getProxyServer() { + return mProxyServer; + } + static public String getCentreId() { return getProperty("LocalCentre"); } -- cgit v1.2.3 From 989655901ebfc4952e48efef682b1fab9f0f7b1c Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Wed, 14 May 2014 13:24:09 +0200 Subject: Bug in cherry pick - create new DOM when there is no String outcome data. --- src/main/java/com/c2kernel/persistency/outcome/Outcome.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/persistency/outcome/Outcome.java b/src/main/java/com/c2kernel/persistency/outcome/Outcome.java index 08fd75b..70a2a24 100644 --- a/src/main/java/com/c2kernel/persistency/outcome/Outcome.java +++ b/src/main/java/com/c2kernel/persistency/outcome/Outcome.java @@ -223,7 +223,7 @@ public class Outcome implements C2KLocalObject { * @return a DOM Document */ public Document getDOM() { - if (dom == null && mData != null) + if (dom == null) try { synchronized (parser) { if (mData!=null) -- cgit v1.2.3 From bff4c943158c18cd70bc270bbb208ead63d020fd Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Wed, 14 May 2014 13:30:21 +0200 Subject: Removed unnecessary ItemProxy casts after removal of EntityProxy --- src/main/java/com/c2kernel/entity/agent/Job.java | 4 ++-- .../com/c2kernel/lifecycle/routingHelpers/ViewpointDataHelper.java | 2 +- src/main/java/com/c2kernel/process/module/ModuleManager.java | 2 +- src/main/java/com/c2kernel/utils/LocalObjectLoader.java | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/entity/agent/Job.java b/src/main/java/com/c2kernel/entity/agent/Job.java index fa2bcd6..efbd5fb 100644 --- a/src/main/java/com/c2kernel/entity/agent/Job.java +++ b/src/main/java/com/c2kernel/entity/agent/Job.java @@ -9,8 +9,8 @@ import com.c2kernel.entity.proxy.ItemProxy; import com.c2kernel.lifecycle.instance.Activity; import com.c2kernel.lifecycle.instance.stateMachine.Transition; import com.c2kernel.lookup.AgentPath; -import com.c2kernel.lookup.ItemPath; import com.c2kernel.lookup.InvalidItemPathException; +import com.c2kernel.lookup.ItemPath; import com.c2kernel.persistency.ClusterStorage; import com.c2kernel.persistency.ClusterStorageException; import com.c2kernel.persistency.outcome.Outcome; @@ -254,7 +254,7 @@ public class Job implements C2KLocalObject public ItemProxy getItemProxy() throws ObjectNotFoundException, InvalidItemPathException { if (item == null) - item = (ItemProxy) Gateway.getProxyManager().getProxy(new ItemPath(itemSysKey)); + item = Gateway.getProxyManager().getProxy(new ItemPath(itemSysKey)); return item; } diff --git a/src/main/java/com/c2kernel/lifecycle/routingHelpers/ViewpointDataHelper.java b/src/main/java/com/c2kernel/lifecycle/routingHelpers/ViewpointDataHelper.java index 5b70dd0..61e3423 100644 --- a/src/main/java/com/c2kernel/lifecycle/routingHelpers/ViewpointDataHelper.java +++ b/src/main/java/com/c2kernel/lifecycle/routingHelpers/ViewpointDataHelper.java @@ -61,7 +61,7 @@ public class ViewpointDataHelper try { // load viewpoint - ItemProxy dataSource = (ItemProxy)Gateway.getProxyManager().getProxy(sourcePath); + ItemProxy dataSource = Gateway.getProxyManager().getProxy(sourcePath); Viewpoint view = (Viewpoint)dataSource.getObject(ClusterStorage.VIEWPOINT + "/" + viewpoint); Outcome outcome = view.getOutcome(); if (xpath == null) { diff --git a/src/main/java/com/c2kernel/process/module/ModuleManager.java b/src/main/java/com/c2kernel/process/module/ModuleManager.java index 9ff42e5..0afe3af 100644 --- a/src/main/java/com/c2kernel/process/module/ModuleManager.java +++ b/src/main/java/com/c2kernel/process/module/ModuleManager.java @@ -138,7 +138,7 @@ public class ModuleManager { public void registerModules() throws ModuleException { ItemProxy serverEntity; try { - serverEntity = (ItemProxy)Gateway.getProxyManager().getProxy(new DomainPath("/servers/"+Gateway.getProperties().getProperty("ItemServer.name"))); + serverEntity = Gateway.getProxyManager().getProxy(new DomainPath("/servers/"+Gateway.getProperties().getProperty("ItemServer.name"))); } catch (ObjectNotFoundException e) { throw new ModuleException("Cannot find local server name."); } diff --git a/src/main/java/com/c2kernel/utils/LocalObjectLoader.java b/src/main/java/com/c2kernel/utils/LocalObjectLoader.java index aef7b96..05f8aba 100644 --- a/src/main/java/com/c2kernel/utils/LocalObjectLoader.java +++ b/src/main/java/com/c2kernel/utils/LocalObjectLoader.java @@ -21,7 +21,7 @@ public class LocalObjectLoader { { DomainPath defRoot = new DomainPath(root); DomainPath defPath = (DomainPath)defRoot.find(name); - return (ItemProxy)Gateway.getProxyManager().getProxy(defPath); + return Gateway.getProxyManager().getProxy(defPath); } static public String getScript(String scriptName, int scriptVersion) throws ObjectNotFoundException { -- cgit v1.2.3 From 2ee6d3c6e816214892fdd541a9aae535686be788 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Wed, 14 May 2014 13:30:34 +0200 Subject: Resolved missing @Override warnings --- src/main/java/com/c2kernel/lifecycle/ActivityDef.java | 1 + .../java/com/c2kernel/lifecycle/instance/stateMachine/StateMachine.java | 2 ++ 2 files changed, 3 insertions(+) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/lifecycle/ActivityDef.java b/src/main/java/com/c2kernel/lifecycle/ActivityDef.java index f39badb..5f123d9 100644 --- a/src/main/java/com/c2kernel/lifecycle/ActivityDef.java +++ b/src/main/java/com/c2kernel/lifecycle/ActivityDef.java @@ -62,6 +62,7 @@ public class ActivityDef extends WfVertexDef implements C2KLocalObject, Descript return mName; } + @Override public void setVersion(int v) { mVersion = v; diff --git a/src/main/java/com/c2kernel/lifecycle/instance/stateMachine/StateMachine.java b/src/main/java/com/c2kernel/lifecycle/instance/stateMachine/StateMachine.java index c165e6f..ff9d5a8 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/stateMachine/StateMachine.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/stateMachine/StateMachine.java @@ -105,10 +105,12 @@ public class StateMachine implements DescriptionObject return version; } + @Override public void setName(String name) { this.name = name; } + @Override public void setVersion(int version) { this.version = version; } -- cgit v1.2.3 From 8e8185210f5bd87cb5dcda3a458fe059f811aafc Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Thu, 15 May 2014 15:10:13 +0200 Subject: Introduced 'Layer' attribute to allow overriding of descriptions. Desc with the same name in the same description tree will be ranked by LocalObjectLoader according to this number, and the highest one chosen for instantiation. Fixes #188 --- src/main/java/com/c2kernel/process/Bootstrap.java | 25 +++++++++++++++---- .../java/com/c2kernel/process/module/Module.java | 3 ++- .../com/c2kernel/process/module/ModuleInfo.java | 1 + .../java/com/c2kernel/utils/LocalObjectLoader.java | 28 ++++++++++++++++++++-- src/main/resources/boot/OD/Module.xsd | 1 + src/main/resources/boot/property/CAProp.xml | 1 + src/main/resources/boot/property/EAProp.xml | 1 + src/main/resources/boot/property/ODProp.xml | 1 + src/main/resources/boot/property/SCProp.xml | 1 + src/main/resources/boot/property/SMProp.xml | 1 + src/main/resources/mapFiles/ModuleMap.xml | 3 +++ 11 files changed, 58 insertions(+), 8 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/process/Bootstrap.java b/src/main/java/com/c2kernel/process/Bootstrap.java index e2ad24e..f273c5d 100644 --- a/src/main/java/com/c2kernel/process/Bootstrap.java +++ b/src/main/java/com/c2kernel/process/Bootstrap.java @@ -103,7 +103,7 @@ public class Bootstrap String itemName = thisItem.substring(delim+1); try { String location = "boot/"+thisItem+(itemType.equals("OD")?".xsd":".xml"); - verifyResource(ns, itemName, 0, itemType, location, reset); + verifyResource(ns, itemName, 0, itemType, location, 0, reset); } catch (Exception e) { Logger.error(e); Logger.die("Error importing bootstrap items. Unsafe to continue."); @@ -112,7 +112,7 @@ public class Bootstrap } - public static DomainPath verifyResource(String ns, String itemName, Integer version, String itemType, String dataLocation, boolean reset) throws Exception { + public static DomainPath verifyResource(String ns, String itemName, Integer version, String itemType, String dataLocation, int layer, boolean reset) throws Exception { if (version == null) version = 0; ResourceImportHandler typeImpHandler = getHandler(itemType); Logger.msg(1, "Bootstrap.verifyResource() - Verifying version "+version+" of "+typeImpHandler.getName()+" "+itemName); @@ -123,7 +123,7 @@ public class Bootstrap Enumeration en = Gateway.getLDAPLookup().search(typeImpHandler.getTypeRoot(), itemName); if (!en.hasMoreElements()) { Logger.msg("Bootstrap.verifyResource() - "+typeImpHandler.getName()+" "+itemName+" not found. Creating new."); - thisProxy = createResourceItem(typeImpHandler, itemName, ns); + thisProxy = createResourceItem(typeImpHandler, itemName, layer, ns); } else { DomainPath path = (DomainPath)en.nextElement(); @@ -147,6 +147,15 @@ public class Bootstrap Gateway.getStorage().put(thisProxy.getSystemKey(), new Property("Module", moduleName, false), thisProxy); } + // overwrite layer if different + int currentLayer = -1; + try { + String layerProp = thisProxy.getProperty("Layer"); + currentLayer = Integer.parseInt(layerProp); + } catch (Exception e) { } + if (currentLayer != layer) + Gateway.getStorage().put(thisProxy.getSystemKey(), new Property("Layer", String.valueOf(layer), false), thisProxy); + if (!modDomPath.equals(path)) { // move item to module subtree Logger.msg("Module item "+itemName+" found with path "+path.toString()+". Moving to "+modDomPath.toString()); modDomPath.setEntity(new ItemPath(thisProxy.getSystemKey())); @@ -224,16 +233,22 @@ public class Bootstrap /** * @param itemType * @param itemName + * @param layer * @param data */ - private static ItemProxy createResourceItem(ResourceImportHandler impHandler, String itemName, String ns) throws Exception { + private static ItemProxy createResourceItem(ResourceImportHandler impHandler, String itemName, int layer, String ns) throws Exception { // create props PropertyDescriptionList pdList = impHandler.getPropDesc(); PropertyArrayList props = new PropertyArrayList(); for (int i = 0; i < pdList.list.size(); i++) { PropertyDescription pd = pdList.list.get(i); String propName = pd.getName(); - String propVal = propName.equals("Name")?itemName:pd.getDefaultValue(); + String propVal; + if (propName.equals("Name")) + propVal = itemName; + else if (propName.equals("Layer")) + propVal = String.valueOf(layer); + else propVal = pd.getDefaultValue(); props.list.add(new Property(propName, propVal, pd.getIsMutable())); } diff --git a/src/main/java/com/c2kernel/process/module/Module.java b/src/main/java/com/c2kernel/process/module/Module.java index 32a5997..2c182ea 100644 --- a/src/main/java/com/c2kernel/process/module/Module.java +++ b/src/main/java/com/c2kernel/process/module/Module.java @@ -56,6 +56,7 @@ public class Module { moduleItem.properties.add(new com.c2kernel.property.Property("Namespace", ns, false)); moduleItem.properties.add(new com.c2kernel.property.Property("Name", name, false)); moduleItem.properties.add(new com.c2kernel.property.Property("Type", "Module", false)); + moduleItem.properties.add(new com.c2kernel.property.Property("Layer", String.valueOf(info.layer), true)); moduleItem.properties.add(new com.c2kernel.property.Property("Version", info.version, true)); // Add dependency for all children Dependency children = new Dependency("Contents"); @@ -79,7 +80,7 @@ public class Module { for (ModuleResource thisRes : imports.getResources()) { try { thisRes.path = Bootstrap.verifyResource(ns, thisRes.name, thisRes.version, - thisRes.resourceType, thisRes.resourceLocation, reset); + thisRes.resourceType, thisRes.resourceLocation, info.layer, reset); } catch (Exception ex) { Logger.error(ex); } diff --git a/src/main/java/com/c2kernel/process/module/ModuleInfo.java b/src/main/java/com/c2kernel/process/module/ModuleInfo.java index 55e02c9..646a915 100644 --- a/src/main/java/com/c2kernel/process/module/ModuleInfo.java +++ b/src/main/java/com/c2kernel/process/module/ModuleInfo.java @@ -6,6 +6,7 @@ public class ModuleInfo { public String desc; public String version; + public int layer = 0; public ArrayList dependency = new ArrayList(); public ModuleInfo() { diff --git a/src/main/java/com/c2kernel/utils/LocalObjectLoader.java b/src/main/java/com/c2kernel/utils/LocalObjectLoader.java index 05f8aba..307cd97 100644 --- a/src/main/java/com/c2kernel/utils/LocalObjectLoader.java +++ b/src/main/java/com/c2kernel/utils/LocalObjectLoader.java @@ -1,11 +1,14 @@ package com.c2kernel.utils; +import java.util.Enumeration; + import com.c2kernel.common.InvalidDataException; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.entity.proxy.ItemProxy; import com.c2kernel.lifecycle.ActivityDef; import com.c2kernel.lifecycle.instance.stateMachine.StateMachine; import com.c2kernel.lookup.DomainPath; +import com.c2kernel.lookup.Path; import com.c2kernel.persistency.ClusterStorage; import com.c2kernel.persistency.ClusterStorageException; import com.c2kernel.persistency.outcome.Schema; @@ -20,8 +23,29 @@ public class LocalObjectLoader { throws ObjectNotFoundException { DomainPath defRoot = new DomainPath(root); - DomainPath defPath = (DomainPath)defRoot.find(name); - return Gateway.getProxyManager().getProxy(defPath); + Enumeration e = Gateway.getLDAPLookup().search(defRoot, name); + ItemProxy defProxy = null; int currentLayer = -1; + while (e.hasMoreElements()) { + DomainPath defPath = (DomainPath)e.nextElement(); + ItemProxy thisProxy = Gateway.getProxyManager().getProxy(defPath); + int thisLayer; + try { + String thisLayerProp = thisProxy.getProperty("Layer"); + thisLayer = Integer.parseInt(thisLayerProp); + } catch (Exception ex) { + thisLayer = 0; + } + if (thisLayer > currentLayer) { + currentLayer = thisLayer; + defProxy = thisProxy; + } + else if (thisLayer == currentLayer) { + throw new ObjectNotFoundException("Duplicate definition for "+name+" in "+root+" found in Layer "+thisLayer, ""); + } + } + if (defProxy == null) + throw new ObjectNotFoundException("No match for "+name+" in "+root, ""); + return defProxy; } static public String getScript(String scriptName, int scriptVersion) throws ObjectNotFoundException { diff --git a/src/main/resources/boot/OD/Module.xsd b/src/main/resources/boot/OD/Module.xsd index d25352e..c768e3f 100644 --- a/src/main/resources/boot/OD/Module.xsd +++ b/src/main/resources/boot/OD/Module.xsd @@ -9,6 +9,7 @@ + diff --git a/src/main/resources/boot/property/CAProp.xml b/src/main/resources/boot/property/CAProp.xml index ac37ae7..b29884a 100644 --- a/src/main/resources/boot/property/CAProp.xml +++ b/src/main/resources/boot/property/CAProp.xml @@ -2,5 +2,6 @@ + diff --git a/src/main/resources/boot/property/EAProp.xml b/src/main/resources/boot/property/EAProp.xml index a345695..2477c93 100644 --- a/src/main/resources/boot/property/EAProp.xml +++ b/src/main/resources/boot/property/EAProp.xml @@ -2,5 +2,6 @@ + diff --git a/src/main/resources/boot/property/ODProp.xml b/src/main/resources/boot/property/ODProp.xml index 894a6ee..f4d7b15 100644 --- a/src/main/resources/boot/property/ODProp.xml +++ b/src/main/resources/boot/property/ODProp.xml @@ -1,5 +1,6 @@ + diff --git a/src/main/resources/boot/property/SCProp.xml b/src/main/resources/boot/property/SCProp.xml index f5de23c..9ff0366 100644 --- a/src/main/resources/boot/property/SCProp.xml +++ b/src/main/resources/boot/property/SCProp.xml @@ -1,5 +1,6 @@ + diff --git a/src/main/resources/boot/property/SMProp.xml b/src/main/resources/boot/property/SMProp.xml index 8581e74..f43d0b5 100644 --- a/src/main/resources/boot/property/SMProp.xml +++ b/src/main/resources/boot/property/SMProp.xml @@ -1,5 +1,6 @@ + diff --git a/src/main/resources/mapFiles/ModuleMap.xml b/src/main/resources/mapFiles/ModuleMap.xml index 45f6cbe..440b852 100644 --- a/src/main/resources/mapFiles/ModuleMap.xml +++ b/src/main/resources/mapFiles/ModuleMap.xml @@ -38,6 +38,9 @@ + + + -- cgit v1.2.3 From 62c7a46967e949304e6b242854526463aae7ee17 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Fri, 16 May 2014 10:38:32 +0200 Subject: item.request returns the final outcome, which may be modified during the execution (e.g. in the case of Predefined Steps). Fixes #136 --- src/main/idl/Entity.idl | 2 +- .../java/com/c2kernel/entity/ItemImplementation.java | 5 +++-- src/main/java/com/c2kernel/entity/TraceableEntity.java | 4 ++-- .../java/com/c2kernel/entity/agent/ActiveEntity.java | 4 ++-- .../java/com/c2kernel/entity/proxy/AgentProxy.java | 18 ++++++++++-------- src/main/java/com/c2kernel/entity/proxy/ItemProxy.java | 4 ++-- .../java/com/c2kernel/lifecycle/instance/Activity.java | 4 +++- .../c2kernel/lifecycle/instance/CompositeActivity.java | 4 ++-- .../java/com/c2kernel/lifecycle/instance/Workflow.java | 4 ++-- 9 files changed, 27 insertions(+), 22 deletions(-) (limited to 'src/main/java') diff --git a/src/main/idl/Entity.idl b/src/main/idl/Entity.idl index 2aa9188..51884a3 100644 --- a/src/main/idl/Entity.idl +++ b/src/main/idl/Entity.idl @@ -101,7 +101,7 @@ module entity * @throws PersistencyException There was a problem committing the changes to storage. * @throws ObjectAlreadyExistsException Not normally thrown, but reserved for PredefinedSteps to throw if they need to. **/ - void requestAction( in unsigned long agentID, + string requestAction( in unsigned long agentID, in string stepPath, in unsigned long transitionID, in string requestData diff --git a/src/main/java/com/c2kernel/entity/ItemImplementation.java b/src/main/java/com/c2kernel/entity/ItemImplementation.java index e0d107a..b12e105 100644 --- a/src/main/java/com/c2kernel/entity/ItemImplementation.java +++ b/src/main/java/com/c2kernel/entity/ItemImplementation.java @@ -113,7 +113,7 @@ public class ItemImplementation implements ItemOperations { @Override - public void requestAction(int agentId, String stepPath, int transitionID, + public String requestAction(int agentId, String stepPath, int transitionID, String requestData) throws AccessRightsException, InvalidTransitionException, ObjectNotFoundException, InvalidDataException, PersistencyException, @@ -128,7 +128,7 @@ public class ItemImplementation implements ItemOperations { Workflow lifeCycle = (Workflow) mStorage.get(mSystemKey, ClusterStorage.LIFECYCLE + "/workflow", null); - lifeCycle.requestAction(agent, stepPath, mSystemKey, + String finalOutcome = lifeCycle.requestAction(agent, stepPath, mSystemKey, transitionID, requestData); // store the workflow if we've changed the state of the domain @@ -136,6 +136,7 @@ public class ItemImplementation implements ItemOperations { if (!(stepPath.startsWith("workflow/predefined"))) mStorage.put(mSystemKey, lifeCycle, null); + return finalOutcome; // Normal operation exceptions } catch (AccessRightsException ex) { Logger.msg("Propagating AccessRightsException back to the calling agent"); diff --git a/src/main/java/com/c2kernel/entity/TraceableEntity.java b/src/main/java/com/c2kernel/entity/TraceableEntity.java index ffd5859..a0980ee 100644 --- a/src/main/java/com/c2kernel/entity/TraceableEntity.java +++ b/src/main/java/com/c2kernel/entity/TraceableEntity.java @@ -111,7 +111,7 @@ public class TraceableEntity extends ItemPOA **************************************************************************/ //requestdata is xmlstring @Override - public void requestAction( int agentId, + public String requestAction( int agentId, String stepPath, int transitionID, String requestData @@ -124,7 +124,7 @@ public class TraceableEntity extends ItemPOA ObjectAlreadyExistsException { synchronized (this) { - mItemImpl.requestAction(agentId, stepPath, transitionID, requestData); + return mItemImpl.requestAction(agentId, stepPath, transitionID, requestData); } } diff --git a/src/main/java/com/c2kernel/entity/agent/ActiveEntity.java b/src/main/java/com/c2kernel/entity/agent/ActiveEntity.java index c59b0fe..a799b62 100644 --- a/src/main/java/com/c2kernel/entity/agent/ActiveEntity.java +++ b/src/main/java/com/c2kernel/entity/agent/ActiveEntity.java @@ -120,14 +120,14 @@ public class ActiveEntity extends AgentPOA } @Override - public void requestAction(int agentID, String stepPath, int transitionID, + public String requestAction(int agentID, String stepPath, int transitionID, String requestData) throws AccessRightsException, InvalidTransitionException, ObjectNotFoundException, InvalidDataException, PersistencyException, ObjectAlreadyExistsException { synchronized (this) { - mAgentImpl.requestAction(agentID, stepPath, transitionID, requestData); + return mAgentImpl.requestAction(agentID, stepPath, transitionID, requestData); } } diff --git a/src/main/java/com/c2kernel/entity/proxy/AgentProxy.java b/src/main/java/com/c2kernel/entity/proxy/AgentProxy.java index 29550d4..b6566a8 100644 --- a/src/main/java/com/c2kernel/entity/proxy/AgentProxy.java +++ b/src/main/java/com/c2kernel/entity/proxy/AgentProxy.java @@ -82,7 +82,7 @@ public class AgentProxy extends ItemProxy * @param job - the job to execute * @throws ScriptErrorException */ - public void execute(ItemProxy item, Job job) + public String execute(ItemProxy item, Job job) throws AccessRightsException, InvalidTransitionException, ObjectNotFoundException, @@ -152,12 +152,14 @@ public class AgentProxy extends ItemProxy job.setAgentId(getSystemKey()); Logger.msg(3, "AgentProxy - submitting job to item proxy"); - item.requestAction(job); + String result = item.requestAction(job); if (Logger.doLog(3)) { Date timeNow = new Date(); long secsNow = (timeNow.getTime()-startTime.getTime())/1000; Logger.msg(3, "Execution took "+secsNow+" seconds"); } + + return result; } private Object callScript(ItemProxy item, Job job) throws ScriptingEngineException { @@ -178,7 +180,7 @@ public class AgentProxy extends ItemProxy * @throws ObjectAlreadyExistsException * @throws ScriptErrorException */ - public void execute(Job job) + public String execute(Job job) throws AccessRightsException, InvalidDataException, InvalidTransitionException, @@ -189,13 +191,13 @@ public class AgentProxy extends ItemProxy { try { ItemProxy targetItem = Gateway.getProxyManager().getProxy(new ItemPath(job.getItemSysKey())); - execute(targetItem, job); + return execute(targetItem, job); } catch (InvalidItemPathException e) { throw new ObjectNotFoundException("Job contained invalid item sysKey: "+job.getItemSysKey(), ""); } } - public void execute(ItemProxy item, String predefStep, C2KLocalObject obj) + public String execute(ItemProxy item, String predefStep, C2KLocalObject obj) throws AccessRightsException, InvalidDataException, InvalidTransitionException, @@ -210,10 +212,10 @@ public class AgentProxy extends ItemProxy Logger.error(ex); throw new InvalidDataException("Error on marshall", ""); } - execute(item, predefStep, param); + return execute(item, predefStep, param); } - public void execute(ItemProxy item, String predefStep, String... params) + public String execute(ItemProxy item, String predefStep, String... params) throws AccessRightsException, InvalidDataException, InvalidTransitionException, @@ -221,7 +223,7 @@ public class AgentProxy extends ItemProxy PersistencyException, ObjectAlreadyExistsException { - item.getItem().requestAction(getSystemKey(), "workflow/predefined/"+predefStep, PredefinedStep.DONE, PredefinedStep.bundleData(params)); + return item.getItem().requestAction(getSystemKey(), "workflow/predefined/"+predefStep, PredefinedStep.DONE, PredefinedStep.bundleData(params)); } /** Wrappers for scripts */ diff --git a/src/main/java/com/c2kernel/entity/proxy/ItemProxy.java b/src/main/java/com/c2kernel/entity/proxy/ItemProxy.java index f3a2f44..454da6d 100644 --- a/src/main/java/com/c2kernel/entity/proxy/ItemProxy.java +++ b/src/main/java/com/c2kernel/entity/proxy/ItemProxy.java @@ -158,7 +158,7 @@ public class ItemProxy /************************************************************************** * **************************************************************************/ - public void requestAction( Job thisJob ) + public String requestAction( Job thisJob ) throws AccessRightsException, InvalidTransitionException, ObjectNotFoundException, @@ -178,7 +178,7 @@ public class ItemProxy throw new InvalidDataException("No Agent specified.", ""); Logger.msg(7, "ItemProxy - executing "+thisJob.getStepPath()+" for "+thisJob.getAgentName()); - getItem().requestAction (thisJob.getAgentId(), thisJob.getStepPath(), + return getItem().requestAction (thisJob.getAgentId(), thisJob.getStepPath(), thisJob.getTransition().getId(), outcome); } diff --git a/src/main/java/com/c2kernel/lifecycle/instance/Activity.java b/src/main/java/com/c2kernel/lifecycle/instance/Activity.java index 8e578c2..b86e200 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/Activity.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/Activity.java @@ -129,7 +129,7 @@ public class Activity extends WfVertex /** cf Item request * @throws ObjectNotFoundException * @throws PersistencyException */ - public void request(AgentPath agent, int itemSysKey, int transitionID, String requestData) throws AccessRightsException, InvalidTransitionException, InvalidDataException, ObjectNotFoundException, PersistencyException + public String request(AgentPath agent, int itemSysKey, int transitionID, String requestData) throws AccessRightsException, InvalidTransitionException, InvalidDataException, ObjectNotFoundException, PersistencyException { // Find requested transition @@ -203,6 +203,8 @@ public class Activity extends WfVertex //refresh all the job lists pushJobsToAgents(itemSysKey); + + return outcome; } protected String runActivityLogic(AgentPath agent, int itemSysKey, diff --git a/src/main/java/com/c2kernel/lifecycle/instance/CompositeActivity.java b/src/main/java/com/c2kernel/lifecycle/instance/CompositeActivity.java index 016298f..e6d1bf9 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/CompositeActivity.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/CompositeActivity.java @@ -413,12 +413,12 @@ public class CompositeActivity extends Activity } @Override - public void request(AgentPath agent, int itemSysKey, int transitionID, String requestData) throws AccessRightsException, InvalidTransitionException, InvalidDataException, ObjectNotFoundException, PersistencyException + public String request(AgentPath agent, int itemSysKey, int transitionID, String requestData) throws AccessRightsException, InvalidTransitionException, InvalidDataException, ObjectNotFoundException, PersistencyException { if (getChildrenGraphModel().getStartVertex() != null && !getStateMachine().getState(state).isFinished() && transitionID == CompositeActivity.START) ((WfVertex) getChildrenGraphModel().getStartVertex()).run(agent, itemSysKey); - super.request(agent, itemSysKey, transitionID, requestData); + return super.request(agent, itemSysKey, transitionID, requestData); } public void refreshJobs(int itemSysKey) diff --git a/src/main/java/com/c2kernel/lifecycle/instance/Workflow.java b/src/main/java/com/c2kernel/lifecycle/instance/Workflow.java index fa5e66b..8ff2fe2 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/Workflow.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/Workflow.java @@ -99,12 +99,12 @@ public class Workflow extends CompositeActivity implements C2KLocalObject * @throws PersistencyException */ //requestData is xmlstring - public void requestAction(AgentPath agent, String stepPath, int itemSysKey, int transitionID, String requestData) + public String requestAction(AgentPath agent, String stepPath, int itemSysKey, int transitionID, String requestData) throws ObjectNotFoundException, AccessRightsException, InvalidTransitionException, InvalidDataException, ObjectAlreadyExistsException, PersistencyException { Logger.msg(3, "Action: " + transitionID + " " + stepPath + " by " + agent.getAgentName()); if (search(stepPath) != null) - ((Activity) search(stepPath)).request(agent, itemSysKey, transitionID, requestData); + return ((Activity) search(stepPath)).request(agent, itemSysKey, transitionID, requestData); else throw new ObjectNotFoundException(stepPath + " not found", ""); } -- cgit v1.2.3 From 42adf60503b73c5106b30ba57fdeba13b3091169 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Thu, 22 May 2014 10:14:42 +0200 Subject: Renamed method in DescriptionObjectCache which still refered to activities. --- src/main/java/com/c2kernel/utils/DescriptionObjectCache.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/utils/DescriptionObjectCache.java b/src/main/java/com/c2kernel/utils/DescriptionObjectCache.java index 4322ef4..d7c5ec1 100644 --- a/src/main/java/com/c2kernel/utils/DescriptionObjectCache.java +++ b/src/main/java/com/c2kernel/utils/DescriptionObjectCache.java @@ -37,7 +37,7 @@ public abstract class DescriptionObjectCache { public abstract D loadObject(String name, int version, ItemProxy proxy) throws ObjectNotFoundException, InvalidDataException; - public void removeAct(String id) { + public void removeObject(String id) { synchronized(cache) { if (cache.keySet().contains(id)) { Logger.msg(7, "ActDefCache: Removing activity def "+id+" from cache"); @@ -60,17 +60,17 @@ public abstract class DescriptionObjectCache { } @Override public void finalize() { - parent.removeAct(id); + parent.removeObject(id); proxy.unsubscribe(this); } @Override public void add(Viewpoint contents) { - parent.removeAct(id); + parent.removeObject(id); } @Override public void remove(String oldId) { - parent.removeAct(oldId); + parent.removeObject(oldId); } @Override -- cgit v1.2.3 From 8bb86312d4f07dcb343ca2d212f4020906dbdb52 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Thu, 5 Jun 2014 15:00:02 +0200 Subject: ObjectProperties.getInstance() - if the property contains a String then attempt to instantiate an object from that classname, otherwise return the object. --- src/main/java/com/c2kernel/utils/ObjectProperties.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/utils/ObjectProperties.java b/src/main/java/com/c2kernel/utils/ObjectProperties.java index dd4a59d..731b009 100644 --- a/src/main/java/com/c2kernel/utils/ObjectProperties.java +++ b/src/main/java/com/c2kernel/utils/ObjectProperties.java @@ -150,6 +150,18 @@ public class ObjectProperties extends Properties { Logger.msg(" "+name+" ("+getObject(name).getClass().getSimpleName()+"): "+getObject(name).toString()); } } - + + public Object getInstance(String propName, Object defaultVal) throws InstantiationException, IllegalAccessException, ClassNotFoundException { + Object prop = getObject(propName, defaultVal); + if (prop == null || prop.equals("")) + throw new InstantiationException("Property '"+propName+"' was not defined. Cannot instantiate."); + if (prop instanceof String) + return Class.forName((String)prop).newInstance(); + return prop; + } + + public Object getInstance(String propName) throws InstantiationException, IllegalAccessException, ClassNotFoundException { + return getInstance(propName, null); + } } -- cgit v1.2.3 From d4fa3bd9dd48f4d5e26850a23f5ba48a9c10ad64 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Thu, 5 Jun 2014 15:02:07 +0200 Subject: LDAP refactored behind interfaces. All functions of LDAP now hidden behind interfaces: Authenticator, Lookup and NextKeyManager (LDAP property storage was already a ClusterStorage). Gateway holds additional objects, and Fixes #26 #191. Refs #27 (needs additional work for read perms and auth tokens) --- .../com/c2kernel/entity/AgentImplementation.java | 4 +- src/main/java/com/c2kernel/entity/CorbaServer.java | 6 +- src/main/java/com/c2kernel/entity/agent/Job.java | 2 +- .../java/com/c2kernel/entity/proxy/AgentProxy.java | 22 +- .../com/c2kernel/entity/proxy/ProxyManager.java | 31 +- .../com/c2kernel/entity/transfer/TransferItem.java | 14 +- .../com/c2kernel/entity/transfer/TransferSet.java | 4 +- .../com/c2kernel/lifecycle/instance/Activity.java | 4 +- .../com/c2kernel/lifecycle/instance/JobPusher.java | 7 +- .../com/c2kernel/lifecycle/instance/WfVertex.java | 2 +- .../instance/predefined/AddDomainPath.java | 6 +- .../predefined/CreateItemFromDescription.java | 8 +- .../lifecycle/instance/predefined/Erase.java | 12 +- .../instance/predefined/RemoveDomainPath.java | 4 +- .../predefined/entitycreation/NewAgent.java | 6 +- .../predefined/entitycreation/NewItem.java | 6 +- .../predefined/entitycreation/NewRole.java | 2 +- .../predefined/server/AddDomainContext.java | 2 +- .../instance/predefined/server/RemoveAgent.java | 4 +- .../predefined/server/RemoveDomainContext.java | 4 +- .../predefined/server/SetAgentPassword.java | 4 +- .../instance/predefined/server/SetAgentRoles.java | 6 +- .../instance/stateMachine/Transition.java | 4 +- src/main/java/com/c2kernel/lookup/AgentPath.java | 42 +- src/main/java/com/c2kernel/lookup/DomainPath.java | 21 +- .../c2kernel/lookup/InvalidItemPathException.java | 2 +- .../com/c2kernel/lookup/InvalidPathException.java | 13 + src/main/java/com/c2kernel/lookup/ItemPath.java | 16 - src/main/java/com/c2kernel/lookup/LDAPLookup.java | 496 ------------- .../java/com/c2kernel/lookup/LDAPLookupUtils.java | 340 --------- src/main/java/com/c2kernel/lookup/LDAPPathSet.java | 72 -- .../java/com/c2kernel/lookup/LDAPProperties.java | 54 -- .../com/c2kernel/lookup/LDAPPropertyManager.java | 138 ---- .../java/com/c2kernel/lookup/LDAPRoleManager.java | 224 ------ src/main/java/com/c2kernel/lookup/Lookup.java | 77 ++ .../java/com/c2kernel/lookup/NextKeyManager.java | 84 --- src/main/java/com/c2kernel/lookup/Path.java | 87 +-- src/main/java/com/c2kernel/lookup/RolePath.java | 35 +- .../com/c2kernel/lookup/ldap/LDAPAuthManager.java | 95 +++ .../java/com/c2kernel/lookup/ldap/LDAPLookup.java | 775 +++++++++++++++++++++ .../com/c2kernel/lookup/ldap/LDAPLookupUtils.java | 365 ++++++++++ .../c2kernel/lookup/ldap/LDAPNextKeyManager.java | 92 +++ .../java/com/c2kernel/lookup/ldap/LDAPPathSet.java | 81 +++ .../com/c2kernel/lookup/ldap/LDAPProperties.java | 38 + .../c2kernel/lookup/ldap/LDAPPropertyManager.java | 141 ++++ .../c2kernel/persistency/LDAPClusterStorage.java | 12 +- .../com/c2kernel/persistency/NextKeyManager.java | 19 + .../java/com/c2kernel/persistency/ProxyLoader.java | 8 +- src/main/java/com/c2kernel/process/Bootstrap.java | 45 +- .../java/com/c2kernel/process/ClientShell.java | 4 +- src/main/java/com/c2kernel/process/Gateway.java | 192 ++--- .../java/com/c2kernel/process/UserCodeProcess.java | 8 +- .../com/c2kernel/process/auth/Authenticator.java | 14 +- .../com/c2kernel/process/auth/ConsoleAuth.java | 4 +- .../java/com/c2kernel/process/auth/ProxyLogin.java | 12 + .../java/com/c2kernel/process/module/Module.java | 13 +- .../com/c2kernel/process/module/ModuleManager.java | 12 +- .../com/c2kernel/process/module/ModuleScript.java | 11 +- src/main/java/com/c2kernel/scripting/Script.java | 2 +- .../java/com/c2kernel/scripting/ScriptConsole.java | 10 +- .../java/com/c2kernel/utils/LocalObjectLoader.java | 8 +- 61 files changed, 1956 insertions(+), 1870 deletions(-) create mode 100644 src/main/java/com/c2kernel/lookup/InvalidPathException.java delete mode 100644 src/main/java/com/c2kernel/lookup/LDAPLookup.java delete mode 100644 src/main/java/com/c2kernel/lookup/LDAPLookupUtils.java delete mode 100644 src/main/java/com/c2kernel/lookup/LDAPPathSet.java delete mode 100644 src/main/java/com/c2kernel/lookup/LDAPProperties.java delete mode 100644 src/main/java/com/c2kernel/lookup/LDAPPropertyManager.java delete mode 100644 src/main/java/com/c2kernel/lookup/LDAPRoleManager.java create mode 100644 src/main/java/com/c2kernel/lookup/Lookup.java delete mode 100644 src/main/java/com/c2kernel/lookup/NextKeyManager.java create mode 100644 src/main/java/com/c2kernel/lookup/ldap/LDAPAuthManager.java create mode 100644 src/main/java/com/c2kernel/lookup/ldap/LDAPLookup.java create mode 100644 src/main/java/com/c2kernel/lookup/ldap/LDAPLookupUtils.java create mode 100644 src/main/java/com/c2kernel/lookup/ldap/LDAPNextKeyManager.java create mode 100644 src/main/java/com/c2kernel/lookup/ldap/LDAPPathSet.java create mode 100644 src/main/java/com/c2kernel/lookup/ldap/LDAPProperties.java create mode 100644 src/main/java/com/c2kernel/lookup/ldap/LDAPPropertyManager.java create mode 100644 src/main/java/com/c2kernel/persistency/NextKeyManager.java create mode 100644 src/main/java/com/c2kernel/process/auth/ProxyLogin.java (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/entity/AgentImplementation.java b/src/main/java/com/c2kernel/entity/AgentImplementation.java index d31b94a..8010114 100644 --- a/src/main/java/com/c2kernel/entity/AgentImplementation.java +++ b/src/main/java/com/c2kernel/entity/AgentImplementation.java @@ -53,7 +53,7 @@ public class AgentImplementation extends ItemImplementation implements @Override public void addRole(String roleName) throws CannotManageException, ObjectNotFoundException { - RolePath newRole = Gateway.getLDAPLookup().getRoleManager().getRolePath(roleName); + RolePath newRole = Gateway.getLookup().getRolePath(roleName); try { newRole.addAgent(new AgentPath(mSystemKey)); } catch (InvalidItemPathException ex) { @@ -65,7 +65,7 @@ public class AgentImplementation extends ItemImplementation implements @Override public void removeRole(String roleName) throws CannotManageException, ObjectNotFoundException { - RolePath rolePath = Gateway.getLDAPLookup().getRoleManager().getRolePath(roleName); + RolePath rolePath = Gateway.getLookup().getRolePath(roleName); try { rolePath.removeAgent(new AgentPath(mSystemKey)); } catch (InvalidItemPathException e) { diff --git a/src/main/java/com/c2kernel/entity/CorbaServer.java b/src/main/java/com/c2kernel/entity/CorbaServer.java index 4a129ae..3a01ed7 100644 --- a/src/main/java/com/c2kernel/entity/CorbaServer.java +++ b/src/main/java/com/c2kernel/entity/CorbaServer.java @@ -14,8 +14,8 @@ import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.entity.agent.ActiveEntity; import com.c2kernel.entity.agent.ActiveLocator; import com.c2kernel.lookup.AgentPath; -import com.c2kernel.lookup.ItemPath; import com.c2kernel.lookup.InvalidItemPathException; +import com.c2kernel.lookup.ItemPath; import com.c2kernel.process.Gateway; import com.c2kernel.utils.Logger; import com.c2kernel.utils.SoftCache; @@ -126,7 +126,7 @@ public class CorbaServer { if (entity == null) { Logger.msg(7, "Creating new servant for "+sysKey); - Class entityClass = Gateway.getLDAPLookup().getEntityClass(entityPath); + Class entityClass = Gateway.getLookup().getItemClass(entityPath); if (entityClass == TraceableEntity.class) { if (poa == null) poa = mItemPOA; @@ -167,7 +167,7 @@ public class CorbaServer { public Servant createEntity(ItemPath entityPath) throws CannotManageException, ObjectAlreadyExistsException { try { if (entityPath == null) - entityPath = Gateway.getLDAPLookup().getNextKeyManager().generateNextEntityKey(); + entityPath = Gateway.getNextKeyManager().generateNextEntityKey(); } catch (Exception ex) { Logger.error(ex); throw new CannotManageException("Cannot generate next entity key"); diff --git a/src/main/java/com/c2kernel/entity/agent/Job.java b/src/main/java/com/c2kernel/entity/agent/Job.java index efbd5fb..cef35ef 100644 --- a/src/main/java/com/c2kernel/entity/agent/Job.java +++ b/src/main/java/com/c2kernel/entity/agent/Job.java @@ -164,7 +164,7 @@ public class Job implements C2KLocalObject public int getAgentId() throws ObjectNotFoundException { if (agentId == -1) - agentId = Gateway.getLDAPLookup().getRoleManager().getAgentPath(getAgentName()).getSysKey(); + agentId = Gateway.getLookup().getAgentPath(getAgentName()).getSysKey(); return agentId; } diff --git a/src/main/java/com/c2kernel/entity/proxy/AgentProxy.java b/src/main/java/com/c2kernel/entity/proxy/AgentProxy.java index b6566a8..e5a52f0 100644 --- a/src/main/java/com/c2kernel/entity/proxy/AgentProxy.java +++ b/src/main/java/com/c2kernel/entity/proxy/AgentProxy.java @@ -11,7 +11,7 @@ package com.c2kernel.entity.proxy; import java.util.Date; -import java.util.Enumeration; +import java.util.Iterator; import com.c2kernel.common.AccessRightsException; import com.c2kernel.common.InvalidDataException; @@ -32,6 +32,7 @@ import com.c2kernel.lookup.Path; import com.c2kernel.persistency.outcome.OutcomeValidator; import com.c2kernel.persistency.outcome.Schema; import com.c2kernel.process.Gateway; +import com.c2kernel.process.auth.Authenticator; import com.c2kernel.scripting.ErrorInfo; import com.c2kernel.scripting.Script; import com.c2kernel.scripting.ScriptErrorException; @@ -50,6 +51,7 @@ public class AgentProxy extends ItemProxy { AgentPath agentPath; + Authenticator auth; /************************************************************************** * Creates an AgentProxy without cache and change notification **************************************************************************/ @@ -66,7 +68,15 @@ public class AgentProxy extends ItemProxy } } - @Override + public Authenticator getAuthObj() { + return auth; + } + + public void setAuthObj(Authenticator auth) { + this.auth = auth; + } + + @Override public Agent narrow() throws ObjectNotFoundException { try { @@ -237,14 +247,14 @@ public class AgentProxy extends ItemProxy /** Let scripts resolve items */ public ItemProxy searchItem(String name) throws ObjectNotFoundException { - Enumeration results = Gateway.getLDAPLookup().search(new DomainPath(""),name); + Iterator results = Gateway.getLookup().search(new DomainPath(""),name); Path returnPath = null; - if (!results.hasMoreElements()) + if (!results.hasNext()) throw new ObjectNotFoundException(name, ""); - while(results.hasMoreElements()) { - Path nextMatch = results.nextElement(); + while(results.hasNext()) { + Path nextMatch = results.next(); if (returnPath != null && nextMatch.getSysKey() != -1 && returnPath.getSysKey() != nextMatch.getSysKey()) throw new ObjectNotFoundException("Too many items with that name"); returnPath = nextMatch; diff --git a/src/main/java/com/c2kernel/entity/proxy/ProxyManager.java b/src/main/java/com/c2kernel/entity/proxy/ProxyManager.java index b217f3e..2b2e0e9 100644 --- a/src/main/java/com/c2kernel/entity/proxy/ProxyManager.java +++ b/src/main/java/com/c2kernel/entity/proxy/ProxyManager.java @@ -12,7 +12,6 @@ package com.c2kernel.entity.proxy; import java.util.ArrayList; import java.util.ConcurrentModificationException; -import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; @@ -41,9 +40,9 @@ public class ProxyManager { Logger.msg(5, "ProxyManager - Starting....."); - Enumeration servers = Gateway.getLDAPLookup().searchEntities(new DomainPath("/servers")); - while(servers.hasMoreElements()) { - Path thisServerPath = servers.nextElement(); + Iterator servers = Gateway.getLookup().searchEntities(new DomainPath("/servers")); + while(servers.hasNext()) { + Path thisServerPath = servers.next(); try { int syskey = thisServerPath.getSysKey(); String remoteServer = ((Property)Gateway.getStorage().get(syskey, ClusterStorage.PROPERTY+"/Name", null)).getValue(); @@ -157,7 +156,7 @@ public class ProxyManager **************************************************************************/ private ItemProxy createProxy( org.omg.CORBA.Object ior, int systemKey, - boolean isItem ) + boolean isAgent ) throws ObjectNotFoundException { @@ -165,13 +164,13 @@ public class ProxyManager Logger.msg(5, "ProxyManager::creating proxy on Item " + systemKey); - if( isItem ) + if( isAgent ) { - newProxy = new ItemProxy(ior, systemKey); + newProxy = new AgentProxy(ior, systemKey); } else { - newProxy = new AgentProxy(ior, systemKey); + newProxy = new ItemProxy(ior, systemKey); } // subscribe to changes from server @@ -195,7 +194,7 @@ public class ProxyManager **************************************************************************/ private ItemProxy getProxy( org.omg.CORBA.Object ior, int systemKey, - boolean isItem ) + boolean isAgent ) throws ObjectNotFoundException { Integer key = new Integer(systemKey); @@ -206,7 +205,7 @@ public class ProxyManager newProxy = proxyPool.get(key); if (newProxy == null) { // create a new one - newProxy = createProxy(ior, systemKey, isItem ); + newProxy = createProxy(ior, systemKey, isAgent ); proxyPool.put(key, newProxy); } return newProxy; @@ -225,12 +224,18 @@ public class ProxyManager //convert namePath to dn format Logger.msg(8,"ProxyManager::getProxy(" + path.toString() + ")"); - boolean isItem = !(path.getEntity() instanceof AgentPath); - return getProxy( Gateway.getLDAPLookup().getIOR(path), + boolean isAgent = (path.getEntity() instanceof AgentPath); + return getProxy( Gateway.getLookup().resolve(path), path.getSysKey(), - isItem ); + isAgent ); } + + public AgentProxy getAgentProxy( AgentPath path ) + throws ObjectNotFoundException + { + return (AgentProxy) getProxy(path); + } /************************************************************************** * void reportCurrentProxies() diff --git a/src/main/java/com/c2kernel/entity/transfer/TransferItem.java b/src/main/java/com/c2kernel/entity/transfer/TransferItem.java index df81721..9a4cfc5 100644 --- a/src/main/java/com/c2kernel/entity/transfer/TransferItem.java +++ b/src/main/java/com/c2kernel/entity/transfer/TransferItem.java @@ -2,7 +2,7 @@ package com.c2kernel.entity.transfer; import java.io.File; import java.util.ArrayList; -import java.util.Enumeration; +import java.util.Iterator; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.entity.C2KLocalObject; @@ -26,7 +26,7 @@ public class TransferItem { public TransferItem() throws Exception { try { - importAgentId = Gateway.getLDAPLookup().getRoleManager().getAgentPath("system").getSysKey(); + importAgentId = Gateway.getLookup().getAgentPath("system").getSysKey(); } catch (ObjectNotFoundException e) { Logger.error("TransferItem - System user not found!"); throw e; @@ -37,9 +37,9 @@ public class TransferItem { this.sysKey = sysKey; domainPaths = new ArrayList(); Property name = (Property)Gateway.getStorage().get(sysKey, ClusterStorage.PROPERTY + "/Name", null); - Enumeration paths = Gateway.getLDAPLookup().search(new DomainPath(), name.getValue()); - while (paths.hasMoreElements()) { - DomainPath thisPath = (DomainPath)paths.nextElement(); + Iterator paths = Gateway.getLookup().search(new DomainPath(), name.getValue()); + while (paths.hasNext()) { + DomainPath thisPath = (DomainPath)paths.next(); domainPaths.add(thisPath.toString()); } } @@ -91,7 +91,7 @@ public class TransferItem { // create item ItemPath entityPath = new ItemPath(sysKey); TraceableEntity newItem = (TraceableEntity)Gateway.getCorbaServer().createEntity(entityPath); - Gateway.getLDAPLookup().add(entityPath); + Gateway.getLookup().add(entityPath); PropertyArrayList props = new PropertyArrayList(); Workflow wf = null; @@ -121,7 +121,7 @@ public class TransferItem { // add domPaths for (String element : domainPaths) { DomainPath newPath = new DomainPath(element, entityPath); - Gateway.getLDAPLookup().add(newPath); + Gateway.getLookup().add(newPath); } } diff --git a/src/main/java/com/c2kernel/entity/transfer/TransferSet.java b/src/main/java/com/c2kernel/entity/transfer/TransferSet.java index a7d81b6..7a5833f 100644 --- a/src/main/java/com/c2kernel/entity/transfer/TransferSet.java +++ b/src/main/java/com/c2kernel/entity/transfer/TransferSet.java @@ -4,7 +4,7 @@ import java.io.File; import java.util.ArrayList; import com.c2kernel.lookup.ItemPath; -import com.c2kernel.lookup.NextKeyManager; +import com.c2kernel.persistency.NextKeyManager; import com.c2kernel.process.Gateway; import com.c2kernel.utils.FileStringUtility; import com.c2kernel.utils.Logger; @@ -84,7 +84,7 @@ public class TransferSet { try { // find the current last key - NextKeyManager nextKeyMan = Gateway.getLDAPLookup().getNextKeyManager(); + NextKeyManager nextKeyMan = Gateway.getNextKeyManager(); ItemPath lastKey = nextKeyMan.getLastEntityPath(); Logger.msg(1, "Last key imported was "+packageLastKey+". LDAP lastkey was "+lastKey.getSysKey()); diff --git a/src/main/java/com/c2kernel/lifecycle/instance/Activity.java b/src/main/java/com/c2kernel/lifecycle/instance/Activity.java index b86e200..88cbeb6 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/Activity.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/Activity.java @@ -19,7 +19,6 @@ import com.c2kernel.lifecycle.instance.stateMachine.State; import com.c2kernel.lifecycle.instance.stateMachine.StateMachine; import com.c2kernel.lifecycle.instance.stateMachine.Transition; import com.c2kernel.lookup.AgentPath; -import com.c2kernel.lookup.LDAPRoleManager; import com.c2kernel.lookup.RolePath; import com.c2kernel.persistency.ClusterStorageException; import com.c2kernel.persistency.outcome.Outcome; @@ -455,10 +454,9 @@ public class Activity extends WfVertex String agentRole = getCurrentAgentRole(); if (agentRole == null || agentRole.length()==0) return; - LDAPRoleManager roleMan = Gateway.getLDAPLookup().getRoleManager(); RolePath myRole; try { - myRole = roleMan.getRolePath(agentRole); + myRole = Gateway.getLookup().getRolePath(agentRole); } catch (ObjectNotFoundException ex) { // non-existent role Logger.msg(7, "Activity.pushJobsToAgents() - Activity role '"+agentRole+" not found."); return; diff --git a/src/main/java/com/c2kernel/lifecycle/instance/JobPusher.java b/src/main/java/com/c2kernel/lifecycle/instance/JobPusher.java index a0a51d0..89e7708 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/JobPusher.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/JobPusher.java @@ -1,11 +1,12 @@ package com.c2kernel.lifecycle.instance; -import java.util.Enumeration; +import java.util.Iterator; import com.c2kernel.entity.Agent; import com.c2kernel.entity.AgentHelper; import com.c2kernel.entity.agent.JobArrayList; import com.c2kernel.lookup.AgentPath; +import com.c2kernel.lookup.Path; import com.c2kernel.lookup.RolePath; import com.c2kernel.process.Gateway; import com.c2kernel.utils.Logger; @@ -25,9 +26,9 @@ final class JobPusher extends Thread { public void run() { Thread.currentThread().setName("Agent job pusher for "+itemSysKey+":"+activity.getName()+" to role "+myRole); - for (Enumeration e = myRole.getChildren(); e.hasMoreElements();) + for (Iterator e = myRole.getChildren(); e.hasNext();) { - AgentPath nextAgent = e.nextElement(); + AgentPath nextAgent = (AgentPath)e.next(); Logger.msg(7, "Activity.pushJobsToAgents() - Calculating jobs for " + nextAgent.getAgentName()); try { diff --git a/src/main/java/com/c2kernel/lifecycle/instance/WfVertex.java b/src/main/java/com/c2kernel/lifecycle/instance/WfVertex.java index 0fc9bf9..2f0ef0d 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/WfVertex.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/WfVertex.java @@ -157,7 +157,7 @@ public abstract class WfVertex extends GraphableVertex script.setInputParamValue("item", Gateway.getProxyManager().getProxy(new ItemPath(itemSysKey))); } if (requiredInput.containsKey("agent")) { - AgentPath systemAgent = Gateway.getLDAPLookup().getRoleManager().getAgentPath("system"); + AgentPath systemAgent = Gateway.getLookup().getAgentPath("system"); script.setInputParamValue("agent", Gateway.getProxyManager().getProxy(systemAgent)); } Object retVal = script.execute(); diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/AddDomainPath.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/AddDomainPath.java index 9eb15f2..3da17e9 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/AddDomainPath.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/AddDomainPath.java @@ -13,9 +13,9 @@ package com.c2kernel.lifecycle.instance.predefined; import com.c2kernel.common.InvalidDataException; import com.c2kernel.lookup.AgentPath; import com.c2kernel.lookup.DomainPath; -import com.c2kernel.lookup.ItemPath; import com.c2kernel.lookup.InvalidItemPathException; -import com.c2kernel.lookup.LDAPLookup; +import com.c2kernel.lookup.ItemPath; +import com.c2kernel.lookup.Lookup; import com.c2kernel.process.Gateway; import com.c2kernel.utils.Logger; @@ -32,7 +32,7 @@ public class AddDomainPath extends PredefinedStep int transitionID, String requestData) throws InvalidDataException { Logger.msg(8,"AddAlias::request()"); - LDAPLookup lookupManager = Gateway.getLDAPLookup(); + Lookup lookupManager = Gateway.getLookup(); Logger.msg(1,"AddAlias::request() - Starting."); diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/CreateItemFromDescription.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/CreateItemFromDescription.java index e6da64a..e16a92c 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/CreateItemFromDescription.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/CreateItemFromDescription.java @@ -27,7 +27,6 @@ import com.c2kernel.lifecycle.CompositeActivityDef; import com.c2kernel.lookup.AgentPath; import com.c2kernel.lookup.DomainPath; import com.c2kernel.lookup.ItemPath; -import com.c2kernel.lookup.LDAPLookup; import com.c2kernel.persistency.ClusterStorage; import com.c2kernel.persistency.TransactionManager; import com.c2kernel.process.Gateway; @@ -67,7 +66,6 @@ public class CreateItemFromDescription extends PredefinedStep PropertyArrayList props = new PropertyArrayList(); Logger.msg(1, "AddNewItem::request() - Starting."); TransactionManager storage = Gateway.getStorage(); - LDAPLookup lookup = Gateway.getLDAPLookup(); try { // check if the path is already taken @@ -134,7 +132,7 @@ public class CreateItemFromDescription extends PredefinedStep // generate new entity key Logger.msg(6, "CreateItemFromDescription - Requesting new sysKey"); - ItemPath entityPath = lookup.getNextKeyManager().generateNextEntityKey(); + ItemPath entityPath = Gateway.getNextKeyManager().generateNextEntityKey(); // resolve the item factory Logger.msg(6, "CreateItemFromDescription - Resolving item factory"); @@ -144,7 +142,7 @@ public class CreateItemFromDescription extends PredefinedStep CorbaServer factory = Gateway.getCorbaServer(); if (factory == null) throw new AccessRightsException("This process cannot create new Items", ""); TraceableEntity newItem = (TraceableEntity)factory.createEntity(entityPath); - Gateway.getLDAPLookup().add(entityPath); + Gateway.getLookup().add(entityPath); // initialise it with its properties and workflow @@ -161,7 +159,7 @@ public class CreateItemFromDescription extends PredefinedStep // add its domain path Logger.msg(3, "CreateItemFromDescription - Creating "+context); context.setEntity(entityPath); - Gateway.getLDAPLookup().add(context); + Gateway.getLookup().add(context); return requestData; } catch (Exception e) { Logger.error(e); diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/Erase.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/Erase.java index 412fe52..3c4a6a7 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/Erase.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/Erase.java @@ -13,7 +13,7 @@ package com.c2kernel.lifecycle.instance.predefined; -import java.util.Enumeration; +import java.util.Iterator; import com.c2kernel.common.InvalidDataException; import com.c2kernel.lookup.AgentPath; @@ -47,19 +47,19 @@ public class Erase extends PredefinedStep try { // get all domain paths - Enumeration domPaths = Gateway.getLDAPLookup().searchAliases(new ItemPath(itemSysKey)); - while (domPaths.hasMoreElements()) { - DomainPath path = (DomainPath)domPaths.nextElement(); + Iterator domPaths = Gateway.getLookup().searchAliases(new ItemPath(itemSysKey)); + while (domPaths.hasNext()) { + DomainPath path = (DomainPath)domPaths.next(); // delete them if (path.getSysKey() == itemSysKey) - Gateway.getLDAPLookup().delete(path); + Gateway.getLookup().delete(path); } //clear out all storages Gateway.getStorage().removeCluster(itemSysKey, "", null); //remove entity path - Gateway.getLDAPLookup().delete(new ItemPath(itemSysKey)); + Gateway.getLookup().delete(new ItemPath(itemSysKey)); } catch( Exception ex ) { diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/RemoveDomainPath.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/RemoveDomainPath.java index e33f722..1ee5e8c 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/RemoveDomainPath.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/RemoveDomainPath.java @@ -15,7 +15,7 @@ import com.c2kernel.common.ObjectCannotBeUpdated; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.lookup.AgentPath; import com.c2kernel.lookup.DomainPath; -import com.c2kernel.lookup.LDAPLookup; +import com.c2kernel.lookup.Lookup; import com.c2kernel.process.Gateway; import com.c2kernel.utils.Logger; @@ -32,7 +32,7 @@ public class RemoveDomainPath extends PredefinedStep int transitionID, String requestData) throws InvalidDataException { Logger.msg(8,"RemoveDomainPath::request()"); - LDAPLookup lookupManager = Gateway.getLDAPLookup(); + Lookup lookupManager = Gateway.getLookup(); Logger.msg(1,"RemoveDomainPath::request() - Starting."); diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewAgent.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewAgent.java index baea8dd..10e5e6f 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewAgent.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewAgent.java @@ -32,11 +32,11 @@ public class NewAgent extends ModuleImport implements java.io.Serializable { } public void create(int agentId) throws ObjectNotFoundException, ObjectCannotBeUpdated, NoSuchAlgorithmException, CannotManageException, ObjectAlreadyExistsException { - AgentPath newAgent = Gateway.getLDAPLookup().getNextKeyManager().generateNextAgentKey(); + AgentPath newAgent = Gateway.getNextKeyManager().generateNextAgentKey(); newAgent.setAgentName(name); newAgent.setPassword(password); ActiveEntity newAgentEnt = (ActiveEntity)Gateway.getCorbaServer().createEntity(newAgent); - Gateway.getLDAPLookup().add(newAgent); + Gateway.getLookup().add(newAgent); // assemble properties properties.add(new com.c2kernel.property.Property("Name", name, true)); properties.add(new com.c2kernel.property.Property("Type", "Agent", false)); @@ -49,7 +49,7 @@ public class NewAgent extends ModuleImport implements java.io.Serializable { for (String role : roles) { RolePath thisRole; try { - thisRole = Gateway.getLDAPLookup().getRoleManager().getRolePath(role); + thisRole = Gateway.getLookup().getRolePath(role); } catch (ObjectNotFoundException ex) { throw new ObjectNotFoundException("Role "+role+" does not exist."); } diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java index c0197db..b1ef0e4 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java @@ -77,9 +77,9 @@ public class NewItem extends ModuleImport { } else { // create item - entPath = Gateway.getLDAPLookup().getNextKeyManager().generateNextEntityKey(); + entPath = Gateway.getNextKeyManager().generateNextEntityKey(); newItem = (TraceableEntity)Gateway.getCorbaServer().createEntity(entPath); - Gateway.getLDAPLookup().add(entPath); + Gateway.getLookup().add(entPath); } // set the name property @@ -181,7 +181,7 @@ public class NewItem extends ModuleImport { // register domain path (before collections in case of recursive collections) if (!domPath.exists()) { domPath.setEntity(entPath); - Gateway.getLDAPLookup().add(domPath); + Gateway.getLookup().add(domPath); } } } diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewRole.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewRole.java index 003b7f7..74415a5 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewRole.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewRole.java @@ -13,7 +13,7 @@ public class NewRole extends ModuleImport { } public void create(int agentId) throws ObjectAlreadyExistsException, ObjectCannotBeUpdated { - Gateway.getLDAPLookup().getRoleManager().createRole(name, jobList); + Gateway.getLookup().createRole(name, jobList); } } diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/AddDomainContext.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/AddDomainContext.java index 7595711..a931143 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/AddDomainContext.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/AddDomainContext.java @@ -35,7 +35,7 @@ public class AddDomainContext extends PredefinedStep { while(!pathsToAdd.empty()) { pathToAdd = pathsToAdd.pop(); try { - Gateway.getLDAPLookup().add(pathToAdd); + Gateway.getLookup().add(pathToAdd); } catch (ObjectAlreadyExistsException e) { Logger.error("Context "+pathToAdd+" inconsistently exists."); } catch (ObjectCannotBeUpdated e) { diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/RemoveAgent.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/RemoveAgent.java index 75fe80b..19641fe 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/RemoveAgent.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/RemoveAgent.java @@ -25,7 +25,7 @@ public class RemoveAgent extends PredefinedStep { String[] params = getDataList(requestData); AgentPath targetAgent; try { - targetAgent = Gateway.getLDAPLookup().getRoleManager().getAgentPath(params[0]); + targetAgent = Gateway.getLookup().getAgentPath(params[0]); } catch (ObjectNotFoundException e) { throw new InvalidDataException("Agent "+params[0]+" not found", ""); } @@ -50,7 +50,7 @@ public class RemoveAgent extends PredefinedStep { } //remove entity path try { - Gateway.getLDAPLookup().delete(targetAgent); + Gateway.getLookup().delete(targetAgent); } catch (ObjectCannotBeUpdated e) { throw new InvalidDataException("Error deleting AgentPath for "+params[0], ""); } diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/RemoveDomainContext.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/RemoveDomainContext.java index 77a7545..a55f7dd 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/RemoveDomainContext.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/RemoveDomainContext.java @@ -27,11 +27,11 @@ public class RemoveDomainContext extends PredefinedStep { pathToDelete.getEntity(); throw new InvalidDataException("Path "+pathToDelete+" is an Entity. Use its own Erase step instead, or RemoveAgent.", ""); } catch (ObjectNotFoundException ex) { } - if (pathToDelete.getChildren().hasMoreElements()) + if (Gateway.getLookup().getChildren(pathToDelete).hasNext()) throw new InvalidDataException("Context "+pathToDelete+" is not empty. Cannot delete.", ""); try { - Gateway.getLDAPLookup().delete(pathToDelete); + Gateway.getLookup().delete(pathToDelete); } catch (ObjectCannotBeUpdated e) { Logger.error(e); throw new InvalidDataException("Exception deleting path"+pathToDelete+": "+e.getMessage(), ""); diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/SetAgentPassword.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/SetAgentPassword.java index bb19030..8a2863a 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/SetAgentPassword.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/SetAgentPassword.java @@ -27,13 +27,13 @@ public class SetAgentPassword extends PredefinedStep { throw new InvalidDataException("Requires 2 params: agent name and new password", ""); AgentPath targetAgent; try { - targetAgent = Gateway.getLDAPLookup().getRoleManager().getAgentPath(params[0]); + targetAgent = Gateway.getLookup().getAgentPath(params[0]); } catch (ObjectNotFoundException e) { throw new InvalidDataException("Agent "+params[0]+" not found", ""); } try { - Gateway.getLDAPLookup().getRoleManager().setAgentPassword(targetAgent, params[1]); + Gateway.getLookup().setAgentPassword(targetAgent, params[1]); } catch (ObjectNotFoundException e) { Logger.error(e); throw new InvalidDataException("Agent "+params[0]+" not found.", ""); diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/SetAgentRoles.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/SetAgentRoles.java index 51be40a..19c6bd8 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/SetAgentRoles.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/SetAgentRoles.java @@ -6,7 +6,6 @@ import com.c2kernel.common.InvalidDataException; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.lifecycle.instance.predefined.PredefinedStep; import com.c2kernel.lookup.AgentPath; -import com.c2kernel.lookup.LDAPRoleManager; import com.c2kernel.lookup.RolePath; import com.c2kernel.process.Gateway; import com.c2kernel.utils.Logger; @@ -26,18 +25,17 @@ public class SetAgentRoles extends PredefinedStep { String[] params = getDataList(requestData); AgentPath targetAgent; try { - targetAgent = Gateway.getLDAPLookup().getRoleManager().getAgentPath(params[0]); + targetAgent = Gateway.getLookup().getAgentPath(params[0]); } catch (ObjectNotFoundException e) { throw new InvalidDataException("Agent "+params[0]+" not found", ""); } - LDAPRoleManager roleMan = Gateway.getLDAPLookup().getRoleManager(); RolePath[] currentRoles = targetAgent.getRoles(); ArrayList requestedRoles = new ArrayList(); if (params.length>1) for (int i=1; i 0) - role = Gateway.getLDAPLookup().getRoleManager().getRolePath(actRole); + role = Gateway.getLookup().getRolePath(actRole); } // Decide the access diff --git a/src/main/java/com/c2kernel/lookup/AgentPath.java b/src/main/java/com/c2kernel/lookup/AgentPath.java index a560795..a0bb7fd 100644 --- a/src/main/java/com/c2kernel/lookup/AgentPath.java +++ b/src/main/java/com/c2kernel/lookup/AgentPath.java @@ -15,12 +15,8 @@ import java.security.NoSuchAlgorithmException; import org.apache.xerces.impl.dv.util.Base64; -import com.c2kernel.common.ObjectCannotBeUpdated; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.process.Gateway; -import com.novell.ldap.LDAPAttribute; -import com.novell.ldap.LDAPAttributeSet; -import com.novell.ldap.LDAPEntry; /** @@ -70,8 +66,7 @@ public class AgentPath extends ItemPath if (mAgentName==null) { try { - LDAPEntry agentEntry = LDAPLookupUtils.getEntry(Gateway.getLDAPLookup().getConnection(), this.getDN() + mLocalPath); - mAgentName = LDAPLookupUtils.getFirstAttributeValue(agentEntry,"uid"); + mAgentName = Gateway.getLookup().getAgentName(this); } catch (ObjectNotFoundException e) { mAgentName = ""; } @@ -81,16 +76,16 @@ public class AgentPath extends ItemPath public RolePath[] getRoles() { - return Gateway.getLDAPLookup().getRoleManager().getRoles(this); + return Gateway.getLookup().getRoles(this); } public boolean hasRole(RolePath role) { - return Gateway.getLDAPLookup().getRoleManager().hasRole(this, role); + return Gateway.getLookup().hasRole(this, role); } public boolean hasRole(String role) { try { - return hasRole(Gateway.getLDAPLookup().getRoleManager().getRolePath(role)); + return hasRole(Gateway.getLookup().getRolePath(role)); } catch (ObjectNotFoundException ex) { return false; } @@ -113,7 +108,7 @@ public class AgentPath extends ItemPath mAgentName; } - static String generateUserPassword(String pass, String algo) throws NoSuchAlgorithmException { + public static String generateUserPassword(String pass, String algo) throws NoSuchAlgorithmException { MessageDigest sha = MessageDigest.getInstance(algo); sha.reset(); sha.update(pass.getBytes()); @@ -123,32 +118,5 @@ public class AgentPath extends ItemPath return digest.toString(); } - @Override - public LDAPAttributeSet createAttributeSet() throws ObjectCannotBeUpdated - { - LDAPAttributeSet attrs = new LDAPAttributeSet(); - attrs.add(new LDAPAttribute("objectclass","cristalagent")); - attrs.add(new LDAPAttribute("intsyskey",Integer.toString(mSysKey))); - attrs.add(new LDAPAttribute("cn", getPath()[getPath().length-1])); - if (mIOR != null) - attrs.add(new LDAPAttribute("ior", Gateway.getORB().object_to_string(mIOR))); - - if (mAgentName!=null && mAgentName.length()>0) - attrs.add(new LDAPAttribute("uid",mAgentName)); - else - throw new ObjectCannotBeUpdated("Cannot create agent. No userId specified", ""); - - if (mPassword!=null && mPassword.length()>0) - try { - attrs.add(new LDAPAttribute("userPassword",generateUserPassword(mPassword, "SHA"))); - } catch (NoSuchAlgorithmException ex) { - throw new ObjectCannotBeUpdated("Cryptographic libraries for password hashing not found.", ""); - } - else - throw new ObjectCannotBeUpdated("Cannot create agent. No password given", ""); - - return attrs; - } - } diff --git a/src/main/java/com/c2kernel/lookup/DomainPath.java b/src/main/java/com/c2kernel/lookup/DomainPath.java index b0784f9..706719e 100644 --- a/src/main/java/com/c2kernel/lookup/DomainPath.java +++ b/src/main/java/com/c2kernel/lookup/DomainPath.java @@ -13,8 +13,6 @@ package com.c2kernel.lookup; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.process.Gateway; import com.c2kernel.utils.Logger; -import com.novell.ldap.LDAPAttribute; -import com.novell.ldap.LDAPAttributeSet; /** @@ -108,7 +106,7 @@ public class DomainPath extends Path public void checkType() { try { - setEntity(Gateway.getLDAPLookup().resolvePath(this)); + setEntity(Gateway.getLookup().resolvePath(this)); } catch (InvalidItemPathException ex) { Logger.error(ex); mType = CONTEXT; @@ -137,22 +135,5 @@ public class DomainPath extends Path } else return INVALID; } - - @Override - public LDAPAttributeSet createAttributeSet() { - LDAPAttributeSet attrs = new LDAPAttributeSet(); - attrs.add(new LDAPAttribute("cn",getName())); - if (getType() == ENTITY) { - String objectclass_values[] = { "alias", "aliasObject" }; - attrs.add(new LDAPAttribute("objectclass",objectclass_values)); - attrs.add(new LDAPAttribute("aliasedObjectName",target.getFullDN())); - } - - else - { - attrs.add(new LDAPAttribute("objectclass","cristalcontext")); - } - return attrs; - } } diff --git a/src/main/java/com/c2kernel/lookup/InvalidItemPathException.java b/src/main/java/com/c2kernel/lookup/InvalidItemPathException.java index 5b37cd7..58174a8 100644 --- a/src/main/java/com/c2kernel/lookup/InvalidItemPathException.java +++ b/src/main/java/com/c2kernel/lookup/InvalidItemPathException.java @@ -1,6 +1,6 @@ package com.c2kernel.lookup; -public class InvalidItemPathException extends Exception { +public class InvalidItemPathException extends InvalidPathException { public InvalidItemPathException() { super(); diff --git a/src/main/java/com/c2kernel/lookup/InvalidPathException.java b/src/main/java/com/c2kernel/lookup/InvalidPathException.java new file mode 100644 index 0000000..77887cf --- /dev/null +++ b/src/main/java/com/c2kernel/lookup/InvalidPathException.java @@ -0,0 +1,13 @@ +package com.c2kernel.lookup; + +public class InvalidPathException extends Exception { + + public InvalidPathException() { + super(); + } + + public InvalidPathException(String msg) { + super(msg); + } + +} diff --git a/src/main/java/com/c2kernel/lookup/ItemPath.java b/src/main/java/com/c2kernel/lookup/ItemPath.java index 89fe5ee..17e5659 100644 --- a/src/main/java/com/c2kernel/lookup/ItemPath.java +++ b/src/main/java/com/c2kernel/lookup/ItemPath.java @@ -12,11 +12,7 @@ package com.c2kernel.lookup; import java.util.ArrayList; -import com.c2kernel.common.ObjectCannotBeUpdated; import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.process.Gateway; -import com.novell.ldap.LDAPAttribute; -import com.novell.ldap.LDAPAttributeSet; /** @@ -147,7 +143,6 @@ public class ItemPath extends Path mPath = (newKey.toArray(mPath)); mSysKey = sysKey; mStringPath = null; - mDN = null; mType = Path.ENTITY; checkSysPath(); } @@ -160,16 +155,5 @@ public class ItemPath extends Path else mType = Path.CONTEXT; } - - @Override - public LDAPAttributeSet createAttributeSet() throws ObjectCannotBeUpdated { - LDAPAttributeSet attrs = new LDAPAttributeSet(); - attrs.add(new LDAPAttribute("objectclass","cristalentity")); - attrs.add(new LDAPAttribute("intsyskey",Integer.toString(mSysKey))); - attrs.add(new LDAPAttribute("cn", getPath()[getPath().length-1])); - if (mIOR != null) - attrs.add(new LDAPAttribute("ior", Gateway.getORB().object_to_string(mIOR))); - return attrs; - } } diff --git a/src/main/java/com/c2kernel/lookup/LDAPLookup.java b/src/main/java/com/c2kernel/lookup/LDAPLookup.java deleted file mode 100644 index eae803b..0000000 --- a/src/main/java/com/c2kernel/lookup/LDAPLookup.java +++ /dev/null @@ -1,496 +0,0 @@ -/* - * Directory Lookup Service * - * author: Florida Estrella -*/ - -package com.c2kernel.lookup; - -import java.util.StringTokenizer; - -import com.c2kernel.common.ObjectAlreadyExistsException; -import com.c2kernel.common.ObjectCannotBeUpdated; -import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.entity.TraceableEntity; -import com.c2kernel.entity.agent.ActiveEntity; -import com.c2kernel.entity.proxy.ProxyMessage; -import com.c2kernel.process.Gateway; -import com.c2kernel.property.PropertyDescription; -import com.c2kernel.property.PropertyDescriptionList; -import com.c2kernel.utils.Logger; -import com.novell.ldap.LDAPAttributeSet; -import com.novell.ldap.LDAPConnection; -import com.novell.ldap.LDAPDN; -import com.novell.ldap.LDAPEntry; -import com.novell.ldap.LDAPException; -import com.novell.ldap.LDAPSearchConstraints; -import com.novell.ldap.LDAPSearchResults; - -/** - * The LDAPLookup object, statically accessible through the Gateway, manages - * the LDAP connection for the cristal process. It provides: - *
    - *
  • Authentication - returning an AgentProxy object if a user has logged in - *
  • System key generation - through the NextKeyManager - *
  • Agent and Role lookup/modification - through the RoleManager - *
  • - * @version $Revision: 1.113 $ $Date: 2006/03/03 13:52:21 $ - * @author $Author: abranson $ - */ - -public class LDAPLookup - -{ - private LDAPConnection mLDAPConn; - private final LDAPProperties mLDAPProps; - private final NextKeyManager mNextKeyManager; - private final LDAPPropertyManager mPropManager; - private final LDAPRoleManager mRoleManager; - - - - /** - * Creates a new LDAPLookup manager with the properties supplied. - * This should be only done by the Gateway during initialisation. - * - * @param props The LDAP properties object that extracts LDAP connection properties from the global c2kprops - */ - public LDAPLookup(LDAPProperties props) throws LDAPException - { - Logger.msg(8,"LDAPLookup - initialising."); - - mLDAPProps = props; - - mLDAPConn = createConnection(mLDAPProps); - - Path.mGlobalPath=props.mGlobalPath; - Path.mRootPath=props.mRootPath; - Path.mLocalPath=props.mLocalPath; - - ItemPath.mTypeRoot = "cn=entity,"+props.mLocalPath; - DomainPath.mTypeRoot = "cn=domain,"+props.mLocalPath; - - mNextKeyManager = new NextKeyManager(this, "cn=last,"+ItemPath.mTypeRoot); - Logger.msg(7, "LDAP.useOldProps="+Gateway.getProperties().getBoolean("LDAP.useOldProps", false)); - mPropManager = new LDAPPropertyManager(this); - mRoleManager = new LDAPRoleManager(this, "cn=agent,"+DomainPath.mTypeRoot, ItemPath.mTypeRoot); - - } - - /** - * Utility method to connect to an LDAP server - * @param lp LDAP properties to connect with - * @return a novell LDAPConnection object - * @throws LDAPException when the connection was unsuccessful - */ - public static LDAPConnection createConnection(LDAPProperties lp) throws LDAPException { - LDAPConnection ld = new LDAPConnection(); - - Logger.msg(3, "LDAPLookup - connecting to " + lp.mHost); - ld.connect(lp.mHost, Integer.valueOf(lp.mPort).intValue()); - - Logger.msg(3, "LDAPLookup - authenticating user:" + lp.mUser); - ld.bind( LDAPConnection.LDAP_V3, lp.mUser, - String.valueOf(lp.mPassword).getBytes()); - - Logger.msg(3, "LDAPLookup - authentication successful"); - LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); - searchCons.setMaxResults(0); - ld.setConstraints(searchCons); - - return ld; - } - - /** - * Gets the entity key generator, used to get a unique system key for new entities. - * @return the global NextKeyManager - */ - public NextKeyManager getNextKeyManager() - { - return mNextKeyManager; - } - - /** - * Gets the property manager, that is used to read and write cristal properties to the LDAP store. - * @return Returns the global LDAPPropertyManager. - */ - public LDAPPropertyManager getPropManager() { - return mPropManager; - } - /** - * Gets the role manager, that is used to add and remove roles and agents. - * @return Returns the mRoleManager. - */ - public LDAPRoleManager getRoleManager() { - return mRoleManager; - } - - /** - * Returns the current LDAP connection, and attempts to reconnect if it has been closed. - * @return - */ - protected LDAPConnection getConnection() - { - if (!mLDAPConn.isConnected()) { - Logger.warning("LDAPLookup - lost connection to LDAP server. Attempting to reconnect."); - try { - mLDAPConn = createConnection(mLDAPProps); - } catch (LDAPException ex) { } - } - return mLDAPConn; - } - - /** - * Disconnects the connection with the LDAP server during shutdown - */ - public void disconnect() { - Logger.msg(1, "LDAP Lookup: Shutting down LDAP connection."); - if (mLDAPConn != null) { - try { - mLDAPConn.disconnect(); - } catch (LDAPException e) { - Logger.error(e); - } - mLDAPConn = null; - } - } - - /** - * Attempts to resolve the CORBA object for a Path, either directly or through an alias. - * @param path the path to resolve - * @return the CORBA object - * @throws ObjectNotFoundException When the path does not exist - */ - public org.omg.CORBA.Object getIOR(Path path) - throws ObjectNotFoundException - { - return resolveObject(path.getFullDN()); - } - - /** - * Attempts to resolve the CORBA object from the IOR attribute of a DN, either directly or through an alias - * @param dn The String dn - * @throws ObjectNotFoundException when the dn or aliased dn does not exist - */ - private org.omg.CORBA.Object resolveObject(String dn) - throws ObjectNotFoundException - { - Logger.msg(8,"LDAPLookup.resolveObject("+dn+")"); - LDAPEntry anEntry = LDAPLookupUtils.getEntry(getConnection(),dn,LDAPSearchConstraints.DEREF_NEVER); - if (anEntry != null) - { - String iorString; - try { - iorString = LDAPLookupUtils.getFirstAttributeValue(anEntry, "ior"); - org.omg.CORBA.Object ior=Gateway.getORB().string_to_object(iorString); - if (ior!=null) - return ior; - else - throw new ObjectNotFoundException("LDAPLookup.resolveObject() - " + dn + " has no IOR", ""); - } catch (ObjectNotFoundException ex) { - return resolveObject(LDAPLookupUtils.getFirstAttributeValue(anEntry,"aliasedObjectName")); - } - } - else - throw new ObjectNotFoundException("LDAPLookup.resolveObject() LDAP node " + dn + " is not in LDAP or has no IOR.", ""); - } - - /** - * - * @param domPath - * @return - * @throws InvalidItemPathException - * @throws ObjectNotFoundException - */ - protected ItemPath resolvePath(DomainPath domPath) - throws InvalidItemPathException, ObjectNotFoundException { - ItemPath referencedPath = null; - LDAPEntry domEntry = LDAPLookupUtils.getEntry(getConnection(), domPath - .getFullDN(), LDAPSearchConstraints.DEREF_ALWAYS); - String entityKey = LDAPLookupUtils.getFirstAttributeValue(domEntry, - "intsyskey"); - Logger.msg(7, "DomainPath " + domPath + " is a reference to " - + entityKey); - String objClass = LDAPLookupUtils.getFirstAttributeValue(domEntry, - "objectClass"); - if (objClass.equals("cristalagent")) - referencedPath = new AgentPath(Integer.parseInt(entityKey)); - else - referencedPath = new ItemPath(Integer.parseInt(entityKey)); - - return referencedPath; - } - - - public LDAPEntry add(Path path) - throws ObjectCannotBeUpdated, ObjectAlreadyExistsException - { - try { - checkLDAPContext(path); - LDAPAttributeSet attrSet = path.createAttributeSet(); - LDAPEntry newEntry = new LDAPEntry(path.getFullDN(),attrSet); - LDAPLookupUtils.addEntry(getConnection(),newEntry); - if (path instanceof DomainPath) - Gateway.getProxyServer().sendProxyEvent(new ProxyMessage(ProxyMessage.NA, path.toString(), ProxyMessage.ADDED)); - return newEntry; - } catch (LDAPException ex) { - if (ex.getResultCode() == LDAPException.ENTRY_ALREADY_EXISTS) - throw new ObjectAlreadyExistsException(ex.getLDAPErrorMessage(), ""); - else - throw new ObjectCannotBeUpdated(ex.getLDAPErrorMessage(), ""); - } - } - - //deletes a node - //throws LDAPexception if node cannot be deleted (eg node is not a leaf) - public void delete(Path path) throws ObjectCannotBeUpdated - { - try { - LDAPLookupUtils.delete(getConnection(),path.getDN()+Path.mLocalPath); - } catch (LDAPException ex) { - throw new ObjectCannotBeUpdated(ex.getLDAPErrorMessage(), ""); - } - if (path instanceof DomainPath) { - Gateway.getProxyServer().sendProxyEvent(new ProxyMessage(ProxyMessage.NA, path.toString(), ProxyMessage.DELETED)); - } - } - - //change specs, add boolean alias leaf context - protected void checkLDAPContext(Path path) - { - String dn = path.getFullDN(); - if (!LDAPLookupUtils.exists(getConnection(),dn)) - { - String listDN[] = path.getPath(); - String name = "cn="+ path.getRoot() + "," + Path.mLocalPath; - int i=0; - while (i getEntityClass(Path path) throws ObjectNotFoundException { - String[] attr = { LDAPConnection.ALL_USER_ATTRS }; - try { - LDAPEntry anEntry=getConnection().read(path.getDN()+Path.mLocalPath,attr); - String type = LDAPLookupUtils.getFirstAttributeValue(anEntry, "objectClass"); - if (type.equals("cristalentity")) - return TraceableEntity.class; - else if (type.equals("cristalagent")) - return ActiveEntity.class; - else - throw new ObjectNotFoundException("Not an entity", ""); - - } catch (LDAPException ex) { - if (ex.getResultCode() == LDAPException.NO_SUCH_OBJECT) - throw new ObjectNotFoundException("Entity does not exist", ""); - Logger.error(ex); - throw new ObjectNotFoundException("Error getting entity class", ""); - } - } - - /** converts an LDAPentry to a Path object - * Note that the search producing the entry should have retrieved the attrs - * 'ior' and 'uniquemember' - * @throws ObjectNotFoundException - * @throws ObjectNotFoundException - */ - protected Path nodeToPath(LDAPEntry entry) throws InvalidItemPathException, ObjectNotFoundException - { - String dn = entry.getDN(); - - // extract syskey - int entityKey = -1; - try { - String entityKeyStr = LDAPLookupUtils.getFirstAttributeValue(entry,"intsyskey"); - entityKey = Integer.parseInt(entityKeyStr); - } catch (Exception e) { } - - // extract IOR - org.omg.CORBA.Object ior = null; - try { - String stringIOR = LDAPLookupUtils.getFirstAttributeValue(entry,"ior"); - ior = Gateway.getORB().string_to_object(stringIOR); - } catch (ObjectNotFoundException e2) { } - - /* Find the right path class */ - Path thisPath; - if (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","cristalagent")) - { //cristalagent - String agentID = LDAPLookupUtils.getFirstAttributeValue(entry,"uid"); - thisPath = new AgentPath(entityKey, agentID); - } - - else if (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","cristalrole")) - { //cristalrole - thisPath = new RolePath(LDAPDN.explodeDN(dn,true)[0], - LDAPLookupUtils.getFirstAttributeValue(entry, "jobList").equals("TRUE")); - } - else if (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","aliasObject") || - (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","cristalcontext") && dn.endsWith(DomainPath.mTypeRoot))) - { - DomainPath domainPath = new DomainPath(); - domainPath.setDN(dn); - thisPath = domainPath; - } - else if (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","cristalentity") || - (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","cristalcontext") && dn.endsWith(ItemPath.mTypeRoot))) - { - if(dn.endsWith(ItemPath.mTypeRoot)) { - ItemPath entityPath; - if (entityKey != -1) - entityPath = new ItemPath(entityKey); - else { - entityPath = new ItemPath(); - entityPath.setDN(dn); - } - thisPath = entityPath; - } - else - throw new ObjectNotFoundException("Entity found outside entity tree"); - } - else - { - throw new ObjectNotFoundException("Unrecognised LDAP entry. Not a cristal entry"); - } - - //set IOR if we have one - if (ior!=null) thisPath.setIOR(ior); - return thisPath; - } -} diff --git a/src/main/java/com/c2kernel/lookup/LDAPLookupUtils.java b/src/main/java/com/c2kernel/lookup/LDAPLookupUtils.java deleted file mode 100644 index 0964565..0000000 --- a/src/main/java/com/c2kernel/lookup/LDAPLookupUtils.java +++ /dev/null @@ -1,340 +0,0 @@ -/* - * Lookup helper class. - */ - -package com.c2kernel.lookup; - -//import netscape.ldap.*; -//import netscape.ldap.util.*; -import com.c2kernel.common.ObjectAlreadyExistsException; -import com.c2kernel.common.ObjectCannotBeUpdated; -import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.utils.Logger; -import com.novell.ldap.LDAPAttribute; -import com.novell.ldap.LDAPAttributeSet; -import com.novell.ldap.LDAPConnection; -import com.novell.ldap.LDAPDN; -import com.novell.ldap.LDAPEntry; -import com.novell.ldap.LDAPException; -import com.novell.ldap.LDAPModification; -import com.novell.ldap.LDAPSearchConstraints; -import com.novell.ldap.LDAPSearchResults; - -/** - * @version $Revision: 1.74 $ $Date: 2006/03/03 13:52:21 $ - * @author $Author: abranson $ - */ - -final public class LDAPLookupUtils -{ - static final char[] META_CHARS = {'+', '=', '"', ',', '<', '>', ';', '/'}; - static final String[] META_ESCAPED = {"2B", "3D", "22", "2C", "3C", "3E", "3B", "2F"}; - static public LDAPEntry getEntry(LDAPConnection ld, String dn,int dereference) - throws ObjectNotFoundException - { - try { - LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); - searchCons.setBatchSize(0); - searchCons.setDereference(dereference); - LDAPEntry thisEntry = ld.read(dn,searchCons); - if (thisEntry != null) return thisEntry; - } catch (LDAPException ex) { - throw new ObjectNotFoundException("LDAP Exception: "+ex.getMessage(), ""); - } - throw new ObjectNotFoundException(dn+" does not exist", ""); - - } - - //Given a DN, return an LDAP Entry - static public LDAPEntry getEntry(LDAPConnection ld, String dn) - throws ObjectNotFoundException - { - return getEntry(ld, dn, LDAPSearchConstraints.DEREF_NEVER); - } - - static public String getFirstAttributeValue(LDAPEntry anEntry, String attribute) throws ObjectNotFoundException - { - LDAPAttribute attr = anEntry.getAttribute(attribute); - if (attr==null) - throw new ObjectNotFoundException("No attributes named '"+attribute+"'", ""); - return (String)attr.getStringValues().nextElement(); - } - - static public String[] getAllAttributeValues(LDAPEntry anEntry, String attribute) throws ObjectNotFoundException - { - LDAPAttribute attr = anEntry.getAttribute(attribute); - if (attr!=null) - return attr.getStringValueArray(); - - throw new ObjectNotFoundException("No attributes named '"+attribute+"'", ""); - - } - - static public boolean existsAttributeValue(LDAPEntry anEntry, String attribute, String value) - { - LDAPAttribute attr = anEntry.getAttribute(attribute); - if (attr!=null) - { - String[] attrValues = new String[attr.size()]; - attrValues = attr.getStringValueArray(); - for (int i=0;i { - LDAPSearchResults results; - LDAPEntry nextEntry; - - public LDAPPathSet() { // empty - results = null; - } - - public LDAPPathSet(LDAPSearchResults results) { - this.results = results; - } - - @Override - public boolean hasMoreElements() { - if (results == null) return false; - if (nextEntry != null) return true; - if (results.hasMore()) - try { - nextEntry = results.next(); - return true; - } catch (LDAPException ex) { - if (ex.getResultCode()!=32) {// no results - Logger.error(ex); - Logger.error("Error loading LDAP result set: "+ex.getMessage()); - } - } - return false; - } - - @Override - public Path nextElement() { - if (results == null) return null; - try { - if (nextEntry == null) - nextEntry = results.next(); - Path nextPath = Gateway.getLDAPLookup().nodeToPath(nextEntry); - nextEntry = null; - return nextPath; - } catch (Exception ex) { - Logger.error("Error loading next path"); - Logger.error(ex); - nextEntry = null; - if (hasMoreElements()) { - Logger.error("Skipping to next entry"); - return nextElement(); - } - else - return null; - } - } -} diff --git a/src/main/java/com/c2kernel/lookup/LDAPProperties.java b/src/main/java/com/c2kernel/lookup/LDAPProperties.java deleted file mode 100644 index df0b85d..0000000 --- a/src/main/java/com/c2kernel/lookup/LDAPProperties.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Directory Lookup Service -*/ - -package com.c2kernel.lookup; - -import java.math.BigInteger; -import java.security.SecureRandom; - -import com.c2kernel.process.Gateway; - -/** - * @version $Revision: 1.16 $ $Date: 2005/10/12 12:51:54 $ - * @author $Author: abranson $ - */ -public class LDAPProperties -{ - public String mGlobalPath = null; //o=cern.ch - public String mRootPath = null; //cn=cristal2 - public String mLocalPath = null; //cn=lab27 - public Integer mPort = null; - public String mHost = null; - public String mUser = null; - public String mPassword = null; - public static String mGeneratedPassword = null; - public String mDbPath = null; - - public LDAPProperties() - { - mGlobalPath = Gateway.getProperties().getProperty( "LDAP.GlobalPath" ); - mRootPath = Gateway.getProperties().getProperty( "LDAP.RootPath" ); - mLocalPath = Gateway.getProperties().getProperty( "LDAP.LocalPath" ); - mPort = Gateway.getProperties().getInt( "LDAP.port", 389 ); - mHost = Gateway.getProperties().getProperty( "LDAP.host" ); - mUser = Gateway.getProperties().getProperty( "LDAP.user" ); - mPassword = Gateway.getProperties().getProperty( "LDAP.password" ); - - mRootPath += "," + mGlobalPath; - mLocalPath += "," + mRootPath; - - } - - - public void generateRootPassword() { - if (mPassword == null) { - if (mGeneratedPassword == null) { - SecureRandom random = new SecureRandom(); - mGeneratedPassword = new BigInteger(130, random).toString(32); - } - mPassword = mGeneratedPassword; - } - } -} - diff --git a/src/main/java/com/c2kernel/lookup/LDAPPropertyManager.java b/src/main/java/com/c2kernel/lookup/LDAPPropertyManager.java deleted file mode 100644 index 51b9ded..0000000 --- a/src/main/java/com/c2kernel/lookup/LDAPPropertyManager.java +++ /dev/null @@ -1,138 +0,0 @@ -package com.c2kernel.lookup; - -import java.util.ArrayList; -import java.util.Enumeration; - -import com.c2kernel.common.ObjectCannotBeUpdated; -import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.property.Property; -import com.c2kernel.utils.Logger; -import com.novell.ldap.LDAPAttribute; -import com.novell.ldap.LDAPEntry; - -/************************************************************************** - * - * $Revision: 1.3 $ - * $Date: 2006/03/03 13:52:21 $ - * - * Copyright (C) 2003 CERN - European Organization for Nuclear Research - * All rights reserved. - **************************************************************************/ - -public class LDAPPropertyManager { - /** - * - */ - protected LDAPLookup ldap; - - public LDAPPropertyManager(LDAPLookup ldap) { - super(); - this.ldap = ldap; - } - - /** - * @param thisEntity - EntityPath of the subject entity - * @return - * @throws ObjectNotFoundException - */ - public boolean hasProperties(ItemPath thisEntity) throws ObjectNotFoundException { - LDAPEntry entityEntry = LDAPLookupUtils.getEntry(ldap.getConnection(), thisEntity.getFullDN()); - return entityEntry.getAttribute("cristalprop") != null; - } - - /** - * @param thisEntity - EntityPath of the subject entity - * @return array of Property - * @throws ObjectNotFoundException - */ - public String[] getPropertyNames(ItemPath thisEntity) throws ObjectNotFoundException { - LDAPEntry entityEntry = LDAPLookupUtils.getEntry(ldap.getConnection(), thisEntity.getFullDN()); - ArrayList propbag = new ArrayList(); - LDAPAttribute props = entityEntry.getAttribute("cristalprop"); - for (Enumeration e = props.getStringValues(); e.hasMoreElements();) { - String thisProp = (String)e.nextElement(); - String thisName = thisProp.substring(0, thisProp.indexOf(':')); - if (thisName.startsWith("!") && thisName.length()>1) thisName = thisName.substring(1); - propbag.add(thisName); - } - - String[] retArr = new String[props.size()]; - return propbag.toArray(retArr); - } - - /** - * @param thisEntity - EntityPath of the subject entity - * @param propName - the name of the property to retrieve - * @return The Property object - * @throws ObjectNotFoundException - */ - public Property getProperty(ItemPath thisEntity, String name) throws ObjectNotFoundException { - LDAPEntry entityEntry = LDAPLookupUtils.getEntry(ldap.getConnection(), thisEntity.getFullDN()); - return getProperty(entityEntry, name); - } - - /** - * @param thisEntity - EntityPath of the subject entity - * @param name - the property name to delete - * @throws ObjectNotFoundException - * @throws ObjectCannotBeUpdated - */ - public void deleteProperty(ItemPath thisEntity, String name) throws ObjectNotFoundException, ObjectCannotBeUpdated { - LDAPEntry entityEntry = LDAPLookupUtils.getEntry(ldap.getConnection(), thisEntity.getFullDN()); - Property prop = getProperty(entityEntry, name); - Logger.msg(6, "LDAPLookupUtils.deleteProperty("+name+") - Deleting property"); - LDAPLookupUtils.removeAttributeValue(ldap.getConnection(), entityEntry, "cristalprop", getPropertyAttrValue(prop)); - } - - private static String getPropertyAttrValue(Property prop) { - return (prop.isMutable()?"":"!")+prop.getName()+":"+prop.getValue(); - } - - /** - * @param thisEntity - EntityPath of the subject entity - * @param prop - the property to store - * @throws ObjectNotFoundException - * @throws ObjectCannotBeUpdated - */ - public void setProperty(ItemPath thisEntity, Property prop) throws ObjectNotFoundException, ObjectCannotBeUpdated { - LDAPEntry entityEntry = LDAPLookupUtils.getEntry(ldap.getConnection(), thisEntity.getFullDN()); - try { - Property oldProp = getProperty(entityEntry, prop.getName()); - Logger.msg(6, "LDAPLookupUtils.setProperty("+prop.getName()+") - Removing old value '"+oldProp.getValue()+"'"); - LDAPLookupUtils.removeAttributeValue(ldap.getConnection(), entityEntry, "cristalprop", getPropertyAttrValue(oldProp)); - } catch (ObjectNotFoundException ex) { - Logger.msg(6, "LDAPLookupUtils.setProperty("+prop.getName()+") - creating new property."); - } - Logger.msg(6, "LDAPLookupUtils.setProperty("+prop.getName()+") - setting to '"+prop.getValue()+"'"); - LDAPLookupUtils.addAttributeValue(ldap.getConnection(), entityEntry, "cristalprop", getPropertyAttrValue(prop)); - } - - public static Property getProperty(LDAPEntry myEntry, String propName) throws ObjectNotFoundException { - // delete existing props - LDAPAttribute props = myEntry.getAttribute("cristalprop"); - if (props == null) - throw new ObjectNotFoundException("Property "+propName+" does not exist", ""); - String propPrefix = propName+":"; - String roPropPrefix = "!"+propPrefix; - String val = null, name = null; boolean mutable = false; - for (Enumeration e = props.getStringValues(); name==null && e.hasMoreElements();) { - String attrVal = (String)e.nextElement(); - if (attrVal.toLowerCase().startsWith(propPrefix.toLowerCase())) { - name = attrVal.substring(0, propPrefix.length()-1); - val = attrVal.substring(propPrefix.length()); - mutable = true; break; - } - - if (attrVal.toLowerCase().startsWith(roPropPrefix.toLowerCase())) { - name = attrVal.substring(1, roPropPrefix.length()-1); - val = attrVal.substring(roPropPrefix.length()); - mutable = false; break; - } - } - if (name == null) - throw new ObjectNotFoundException("Property "+propName+" does not exist", ""); - Logger.msg(6, "Loaded "+(mutable?"":"Non-")+"Mutable Property: "+name+"="+val); - return new Property(name, val, mutable); - } - -} diff --git a/src/main/java/com/c2kernel/lookup/LDAPRoleManager.java b/src/main/java/com/c2kernel/lookup/LDAPRoleManager.java deleted file mode 100644 index 091f6d7..0000000 --- a/src/main/java/com/c2kernel/lookup/LDAPRoleManager.java +++ /dev/null @@ -1,224 +0,0 @@ -package com.c2kernel.lookup; - -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Enumeration; - -import com.c2kernel.common.ObjectAlreadyExistsException; -import com.c2kernel.common.ObjectCannotBeUpdated; -import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.utils.Logger; -import com.novell.ldap.LDAPConnection; -import com.novell.ldap.LDAPEntry; -import com.novell.ldap.LDAPException; -import com.novell.ldap.LDAPSearchConstraints; - -/************************************************************************** - * - * $Revision: 1.1 $ - * $Date: 2005/04/26 06:48:12 $ - * - * Copyright (C) 2003 CERN - European Organization for Nuclear Research - * All rights reserved. - **************************************************************************/ - -// public static final String codeRevision = "$Revision: 1.1 $ $Date: 2005/04/26 06:48:12 $ $Author: abranson $"; -public class LDAPRoleManager { - - /** - * - */ - LDAPLookup mLdap; - private final String mRolePath; - private final String mEntityPath; - - public LDAPRoleManager(LDAPLookup ldap, String rolePath, String entityPath) { - super(); - this.mLdap = ldap; - this.mRolePath = rolePath; - this.mEntityPath = entityPath; - } - - //NOTE: A role must have at LEAST 1 userDN, cannot be empty... - //Creates a cristalRole - //CristalRole is-a specialized CristalContext which contains multi-valued uniqueMember attribute pointing to cristalagents - public RolePath createRole(String roleName, boolean jobList) - throws ObjectAlreadyExistsException, ObjectCannotBeUpdated - { - - // create the role - RolePath rolePath = new RolePath(roleName, jobList); - String roleDN = rolePath.getFullDN(); - LDAPEntry roleNode; - try - { - roleNode = LDAPLookupUtils.getEntry(mLdap.getConnection(), rolePath.getFullDN()); - throw new ObjectAlreadyExistsException(); - } catch (ObjectNotFoundException ex) { } - - //create CristalRole if it does not exist - roleNode = new LDAPEntry(roleDN, rolePath.createAttributeSet()); - try { - LDAPLookupUtils.addEntry(mLdap.getConnection(),roleNode); - } catch (LDAPException e) { - throw new ObjectCannotBeUpdated(e.getLDAPErrorMessage(), ""); - } - return rolePath; - - - } - public void deleteRole(RolePath role) throws ObjectNotFoundException, ObjectCannotBeUpdated { - try { - LDAPLookupUtils.delete(mLdap.getConnection(), role.getFullDN()); - } catch (LDAPException ex) { - throw new ObjectCannotBeUpdated("Could not remove role"); - } - } - - protected void addRole(AgentPath agent, RolePath role) - throws ObjectCannotBeUpdated, ObjectNotFoundException - { - LDAPEntry roleEntry = LDAPLookupUtils.getEntry(mLdap.getConnection(), role.getFullDN()); - //add memberDN to uniqueMember if it is not yet a member - if (!LDAPLookupUtils.existsAttributeValue(roleEntry, "uniqueMember", agent.getFullDN())) - LDAPLookupUtils.addAttributeValue(mLdap.getConnection(), roleEntry, "uniqueMember", agent.getFullDN()); - else - throw new ObjectCannotBeUpdated("Agent " + agent.getAgentName() + " already has role " + role.getName()); - } - - protected void removeRole(AgentPath agent, RolePath role) - throws ObjectCannotBeUpdated, ObjectNotFoundException - { - LDAPEntry roleEntry = LDAPLookupUtils.getEntry(mLdap.getConnection(), role.getFullDN()); - if (LDAPLookupUtils.existsAttributeValue(roleEntry, "uniqueMember", agent.getFullDN())) - LDAPLookupUtils.removeAttributeValue(mLdap.getConnection(), roleEntry, "uniqueMember", agent.getFullDN()); - else - throw new ObjectCannotBeUpdated("Agent did not have that role"); - } - - protected boolean hasRole(AgentPath agent, RolePath role) { - String filter = "(&(objectclass=cristalrole)(uniqueMember="+agent.getFullDN()+")(cn="+role.getName()+"))"; - LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); - searchCons.setBatchSize(0); - searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER ); - return mLdap.search(mRolePath,LDAPConnection.SCOPE_SUB,filter,searchCons).hasMoreElements(); - } - - protected AgentPath[] getAgents(RolePath role) - throws ObjectNotFoundException - { - //get the roleDN entry, and its uniqueMember entry pointing to - LDAPEntry roleEntry; - try { - roleEntry = LDAPLookupUtils.getEntry(mLdap.getConnection(), role.getFullDN()); - } catch (ObjectNotFoundException e) { - throw new ObjectNotFoundException("Role does not exist", ""); - } - - String[] res = LDAPLookupUtils.getAllAttributeValues(roleEntry,"uniqueMember"); - ArrayList agents = new ArrayList(); - for (String userDN : res) { - try { - LDAPEntry userEntry = LDAPLookupUtils.getEntry(mLdap.getConnection(), userDN); - AgentPath path = (AgentPath)mLdap.nodeToPath(userEntry); - agents.add(path); - } catch (ObjectNotFoundException ex) { - Logger.error("Agent "+userDN+" does not exist"); - } catch (InvalidItemPathException ex) { - Logger.error("Agent "+userDN+" is not a valid entity"); - } - } - AgentPath[] usersList = new AgentPath[0]; - usersList = agents.toArray(usersList); - return usersList; - } - - //returns the role/s of a user - protected RolePath[] getRoles(AgentPath agentPath) - { - //search the mDomainPath tree uniqueMember=userDN - //filter = objectclass=cristalrole AND uniqueMember=userDN - String filter = "(&(objectclass=cristalrole)(uniqueMember="+agentPath.getFullDN()+"))"; - LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); - searchCons.setBatchSize(0); - searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER ); - Enumeration roles = mLdap.search(mRolePath,LDAPConnection.SCOPE_SUB,filter,searchCons); - ArrayList roleList = new ArrayList(); - - while(roles.hasMoreElements()) - { - RolePath path = (RolePath) roles.nextElement(); - roleList.add(path); - } - RolePath[] roleArr = new RolePath[roleList.size()]; - roleArr = roleList.toArray(roleArr); - return roleArr; - } - - /** - * Utility for looking up a login name - * - * @param ld - * @param agentName - * @param baseDN - * @return - * @throws ObjectNotFoundException - */ - public AgentPath getAgentPath(String agentName) throws ObjectNotFoundException - { - //search to get the userDN equivalent of the userID - LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); - searchCons.setBatchSize(0); - searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER ); - String filter = "(&(objectclass=cristalagent)(uid="+agentName+"))"; - Enumeration res = mLdap.search(mEntityPath,LDAPConnection.SCOPE_SUB,filter,searchCons); - if (!res.hasMoreElements()) - throw new ObjectNotFoundException("Agent not found"); - Path result = res.nextElement(); - if (result instanceof AgentPath) - return (AgentPath)result; - else - throw new ObjectNotFoundException("Entry was not an Agent"); - } - - public RolePath getRolePath(String roleName) throws ObjectNotFoundException - { - LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); - searchCons.setBatchSize(0); - searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER ); - String filter = "(&(objectclass=cristalrole)(cn="+roleName+"))"; - Enumeration res = mLdap.search(mRolePath,LDAPConnection.SCOPE_SUB,filter,searchCons); - if (!res.hasMoreElements()) - throw new ObjectNotFoundException("Role not found"); - Path result = res.nextElement(); - if (result instanceof RolePath) - return (RolePath)result; - else - throw new ObjectNotFoundException("Entry was not a Role"); - } - - public void setHasJobList(RolePath role, boolean hasJobList) throws ObjectNotFoundException, ObjectCannotBeUpdated { - // get entry - LDAPEntry roleEntry; - try { - roleEntry = LDAPLookupUtils.getEntry(mLdap.getConnection(), role.getFullDN()); - } catch (ObjectNotFoundException e) { - throw new ObjectNotFoundException("Role does not exist", ""); - } - // set attribute - LDAPLookupUtils.setAttributeValue(mLdap.getConnection(), roleEntry, "jobList", hasJobList?"TRUE":"FALSE"); - } - - public void setAgentPassword(AgentPath agent, String newPassword) throws ObjectNotFoundException, ObjectCannotBeUpdated, NoSuchAlgorithmException { - String encPasswd = AgentPath.generateUserPassword(newPassword, "SHA"); - LDAPEntry agentEntry; - try { - agentEntry = LDAPLookupUtils.getEntry(mLdap.getConnection(), agent.getFullDN()); - } catch (ObjectNotFoundException e) { - throw new ObjectNotFoundException("Agent "+agent.getAgentName()+" does not exist", ""); - } - LDAPLookupUtils.setAttributeValue(mLdap.getConnection(), agentEntry, "userPassword", encPasswd); - - } - -} diff --git a/src/main/java/com/c2kernel/lookup/Lookup.java b/src/main/java/com/c2kernel/lookup/Lookup.java new file mode 100644 index 0000000..026ad19 --- /dev/null +++ b/src/main/java/com/c2kernel/lookup/Lookup.java @@ -0,0 +1,77 @@ +package com.c2kernel.lookup; + +import java.security.NoSuchAlgorithmException; +import java.util.Iterator; + +import com.c2kernel.common.ObjectAlreadyExistsException; +import com.c2kernel.common.ObjectCannotBeUpdated; +import com.c2kernel.common.ObjectNotFoundException; +import com.c2kernel.process.auth.Authenticator; +import com.c2kernel.property.PropertyDescriptionList; + +public interface Lookup { + + public void initializeDirectory() throws ObjectNotFoundException; + + public void open(Authenticator user); + + public void close(); + + // Path resolution + + public Class getItemClass(Path path) throws ObjectNotFoundException; + + public ItemPath resolvePath(DomainPath domainPath) throws InvalidItemPathException, ObjectNotFoundException; + + public org.omg.CORBA.Object resolve(Path path) throws ObjectNotFoundException; + + // Path management + + public void add(Path newPath) throws ObjectCannotBeUpdated, ObjectAlreadyExistsException; + + public void delete(Path path) throws ObjectCannotBeUpdated; + + // Path finding and searching + + public boolean exists(Path path); + + public Iterator getChildren(Path path); + + public Iterator search(Path path, String name); + + public Iterator search(Path start, String propname, String propvalue); + + public Iterator search(Path start, PropertyDescriptionList props); + + public Iterator searchEntities(Path path); + + public Iterator searchAliases(DomainPath start); + + public Iterator searchAliases(ItemPath itemPath); + + // Role and agent management + + public AgentPath getAgentPath(String agentName) throws ObjectNotFoundException; + + public RolePath getRolePath(String roleName) throws ObjectNotFoundException; + + public RolePath createRole(String role, boolean b) throws ObjectAlreadyExistsException, ObjectCannotBeUpdated; + + public void addRole(AgentPath agent, RolePath rolePath) throws ObjectCannotBeUpdated, ObjectNotFoundException; + + public AgentPath[] getAgents(RolePath rolePath) throws ObjectNotFoundException; + + public RolePath[] getRoles(AgentPath agentPath); + + public boolean hasRole(AgentPath agentPath, RolePath role); + + public void removeRole(AgentPath agent, RolePath role) throws ObjectCannotBeUpdated, ObjectNotFoundException; + + public String getAgentName(AgentPath agentPath) throws ObjectNotFoundException; + + public void setAgentPassword(AgentPath agent, String newPassword) throws ObjectNotFoundException, ObjectCannotBeUpdated, NoSuchAlgorithmException; + + public void setHasJobList(RolePath role, boolean hasJobList) throws ObjectNotFoundException, ObjectCannotBeUpdated; + + +} diff --git a/src/main/java/com/c2kernel/lookup/NextKeyManager.java b/src/main/java/com/c2kernel/lookup/NextKeyManager.java deleted file mode 100644 index 9aea50d..0000000 --- a/src/main/java/com/c2kernel/lookup/NextKeyManager.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.c2kernel.lookup; - -import com.c2kernel.common.ObjectCannotBeUpdated; -import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.persistency.ClusterStorageException; -import com.c2kernel.process.Gateway; -import com.c2kernel.utils.Logger; -import com.novell.ldap.LDAPEntry; - -/************************************************************************** - * - * $Revision: 1.2 $ - * $Date: 2005/04/27 13:47:24 $ - * - * Copyright (C) 2003 CERN - European Organization for Nuclear Research - * All rights reserved. - **************************************************************************/ - -// public static final String codeRevision = "$Revision: 1.2 $ $Date: 2005/04/27 13:47:24 $ $Author: abranson $"; -public class NextKeyManager { - - LDAPLookup ldap; - String lastKeyPath; - - public NextKeyManager(LDAPLookup ldap, String lastKeyPath) { - super(); - this.ldap = ldap; - this.lastKeyPath = lastKeyPath; - } - - public synchronized ItemPath generateNextEntityKey() - throws ObjectCannotBeUpdated, ObjectNotFoundException - { - ItemPath lastKey = getLastEntityPath(); - - try { - lastKey.setSysKey(lastKey.getSysKey()+1); - } catch (InvalidItemPathException ex) { - throw new ObjectCannotBeUpdated("Invalid syskey "+(lastKey.getSysKey()+1)+". Maybe centre is full."); - } - //test that storage is empty for that key - try { - if (Gateway.getStorage().getClusterContents(lastKey.getSysKey(), "").length > 0) - throw new ObjectCannotBeUpdated("NextKeyManager: Storage already contains data for syskey "+lastKey.getSysKey()+ - ". Storage is out of sync with nextkey. Please contact an administrator", ""); - } catch (ClusterStorageException e) { - Logger.error(e); - throw new ObjectCannotBeUpdated("Could not check storage for prior data for the next generated systemKey: "+e.getMessage()); - } - - //set the last key - writeLastEntityKey(lastKey.getSysKey()); - - return lastKey; - } - - public synchronized AgentPath generateNextAgentKey() - throws ObjectCannotBeUpdated, ObjectNotFoundException { - ItemPath newEntity = generateNextEntityKey(); - return new AgentPath(newEntity); - } - - public void writeLastEntityKey(int sysKey) throws ObjectCannotBeUpdated, ObjectNotFoundException { - LDAPEntry lastKeyEntry = LDAPLookupUtils.getEntry(ldap.getConnection(),lastKeyPath); - LDAPLookupUtils.setAttributeValue(ldap.getConnection(), lastKeyEntry,"intsyskey",Integer.toString(sysKey)); - } - - public ItemPath getLastEntityPath() throws ObjectNotFoundException - { - LDAPEntry lastKeyEntry = LDAPLookupUtils.getEntry(ldap.getConnection(),lastKeyPath); - String lastKey = LDAPLookupUtils.getFirstAttributeValue(lastKeyEntry,"intsyskey"); - try { - int sysKey = Integer.parseInt(lastKey); - ItemPath sysPath = new ItemPath(sysKey); - return sysPath; - } catch (InvalidItemPathException ex) { - throw new ObjectNotFoundException("Invalid syskey. Maybe centre is full."); - } catch (NumberFormatException ex) { - throw new ObjectNotFoundException("Invalid syskey in lastkey."); - } - - } - -} diff --git a/src/main/java/com/c2kernel/lookup/Path.java b/src/main/java/com/c2kernel/lookup/Path.java index 16f3e5d..f9fd15d 100644 --- a/src/main/java/com/c2kernel/lookup/Path.java +++ b/src/main/java/com/c2kernel/lookup/Path.java @@ -12,15 +12,11 @@ package com.c2kernel.lookup; import java.io.Serializable; import java.util.ArrayList; -import java.util.Enumeration; +import java.util.Iterator; import java.util.StringTokenizer; -import com.c2kernel.common.ObjectCannotBeUpdated; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.process.Gateway; -import com.novell.ldap.LDAPAttributeSet; -import com.novell.ldap.LDAPConnection; -import com.novell.ldap.LDAPSearchConstraints; /** @@ -45,19 +41,11 @@ public abstract class Path implements Serializable protected String mStringPath = null; // entity or context protected short mType = CONTEXT; - // LDAP dn - protected String mDN = null; // int syskey (only valid for entity SystemPaths) protected int mSysKey = INVALID; // ior is stored in here when it is resolved protected org.omg.CORBA.Object mIOR = null; - // - // needed for unusual subclass constructors - - protected static String mGlobalPath; //cern.ch - protected static String mRootPath; //cristal2 - protected static String mLocalPath; //lab27 public Path() { } @@ -114,7 +102,6 @@ public abstract class Path implements Serializable public void setPath(String[] path) { mStringPath = null; - mDN = null; mPath = path.clone(); mSysKey = INVALID; } @@ -136,7 +123,6 @@ public abstract class Path implements Serializable mPath = (newPath.toArray(mPath)); mStringPath = null; - mDN = null; mSysKey = INVALID; } @@ -152,40 +138,10 @@ public abstract class Path implements Serializable public void setPath(Path path) { mStringPath = null; - mDN = null; mPath = (path.getPath().clone()); mSysKey = INVALID; } - /* LDAP dn e.g. cn=6L,cn=Barrel,cn=Crystal,cn=Product,cn=domain, - * system/domain node PRESENT - * trailing comma - */ - public void setDN(String dn) - { - // strip off root path components - String root = "cn="+getRoot()+","; - if (dn.endsWith(mLocalPath)) - dn = dn.substring(0, dn.lastIndexOf(mLocalPath)); - - if (dn.endsWith(root)) - dn = dn.substring(0, dn.lastIndexOf(root)); - - ArrayList newPath = new ArrayList(); - StringTokenizer tok = new StringTokenizer(dn, ","); - while (tok.hasMoreTokens()) { - String nextPath = tok.nextToken(); - if (nextPath.indexOf("cn=") == 0) - newPath.add(0, LDAPLookupUtils.unescapeDN(nextPath.substring(3))); - else - break; - } - mPath = (newPath.toArray(mPath)); - mSysKey = INVALID; - mStringPath = null; - mDN = dn+root; - } - /*************************************************************************/ @@ -212,23 +168,8 @@ public abstract class Path implements Serializable return mStringPath; } - public String getDN() { - if (mDN == null) { - StringBuffer dnBuffer = new StringBuffer(); - for (int i=mPath.length-1; i>=0; i--) - dnBuffer.append("cn=").append(LDAPLookupUtils.escapeDN(mPath[i])).append(","); - dnBuffer.append("cn="+getRoot()+","); - mDN = dnBuffer.toString(); - } - return mDN; - } - - public String getFullDN() { - return getDN()+mLocalPath; - } - public boolean exists() { - return Gateway.getLDAPLookup().exists(this); + return Gateway.getLookup().exists(this); } /** Queries the lookup for the IOR @@ -237,9 +178,9 @@ public abstract class Path implements Serializable public org.omg.CORBA.Object getIOR() { org.omg.CORBA.Object newIOR = null; if (mIOR==null) { // if not cached try to resolve - LDAPLookup myLookup = Gateway.getLDAPLookup(); + Lookup myLookup = Gateway.getLookup(); try { - newIOR = myLookup.getIOR(this); + newIOR = myLookup.resolve(this); } catch (ObjectNotFoundException ex) { } setIOR(newIOR); @@ -260,19 +201,11 @@ public abstract class Path implements Serializable return mSysKey; } - public Enumeration getChildren() { - String filter = "objectclass=*"; - LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); - searchCons.setBatchSize(10); - searchCons.setDereference(LDAPSearchConstraints.DEREF_FINDING ); - return Gateway.getLDAPLookup().search(getFullDN(), LDAPConnection.SCOPE_ONE,filter,searchCons); - } - public Path find(String name) throws ObjectNotFoundException { - Enumeration e = Gateway.getLDAPLookup().search(this, name); - if (e.hasMoreElements()) { - Path thisPath = e.nextElement(); - if (e.hasMoreElements()) + Iterator e = Gateway.getLookup().search(this, name); + if (e.hasNext()) { + Path thisPath = e.next(); + if (e.hasNext()) throw new ObjectNotFoundException("More than one match for "+name, ""); return thisPath; } @@ -281,8 +214,6 @@ public abstract class Path implements Serializable public abstract ItemPath getEntity() throws ObjectNotFoundException; - public abstract LDAPAttributeSet createAttributeSet() throws ObjectCannotBeUpdated; - @Override public boolean equals( Object path ) { @@ -298,7 +229,7 @@ public abstract class Path implements Serializable StringBuffer comp = new StringBuffer("Components: { "); for (String element : mPath) comp.append("'").append(element).append("' "); - return "Path - dump(): "+comp.toString()+"}\n dn="+getDN()+"\n string="+toString()+"\n int="+getSysKey()+"\n type="+mType; + return "Path - dump(): "+comp.toString()+"}\n string="+toString()+"\n int="+getSysKey()+"\n type="+mType; } } diff --git a/src/main/java/com/c2kernel/lookup/RolePath.java b/src/main/java/com/c2kernel/lookup/RolePath.java index 0e07012..bd23991 100644 --- a/src/main/java/com/c2kernel/lookup/RolePath.java +++ b/src/main/java/com/c2kernel/lookup/RolePath.java @@ -10,15 +10,13 @@ package com.c2kernel.lookup; -import java.util.Enumeration; -import java.util.Vector; +import java.util.ArrayList; +import java.util.Iterator; import com.c2kernel.common.ObjectCannotBeUpdated; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.process.Gateway; import com.c2kernel.utils.Logger; -import com.novell.ldap.LDAPAttribute; -import com.novell.ldap.LDAPAttributeSet; @@ -56,7 +54,7 @@ public class RolePath extends DomainPath */ public void setHasJobList(boolean hasJobList) throws ObjectNotFoundException, ObjectCannotBeUpdated { this.hasJobList = hasJobList; - Gateway.getLDAPLookup().getRoleManager().setHasJobList(this, hasJobList); + Gateway.getLookup().setHasJobList(this, hasJobList); } @@ -65,18 +63,17 @@ public class RolePath extends DomainPath mType = CONTEXT; } - @Override - public Enumeration getChildren() { + public Iterator getChildren() { AgentPath[] agents = getAgentsWithRole(); - Vector children = new Vector(agents.length); + ArrayList children = new ArrayList(agents.length); for (int i = 0; i < agents.length; i++) children.add(i, agents[i]); - return children.elements(); + return children.iterator(); } public AgentPath[] getAgentsWithRole() { try { - return Gateway.getLDAPLookup().getRoleManager().getAgents(this); + return Gateway.getLookup().getAgents(this); } catch (ObjectNotFoundException ex) { Logger.error("Cannot retrieve agent list. Role "+getName()+" does not exist in LDAP"); return new AgentPath[0]; @@ -84,11 +81,11 @@ public class RolePath extends DomainPath } public void addAgent(AgentPath agent) throws ObjectCannotBeUpdated, ObjectNotFoundException { - Gateway.getLDAPLookup().getRoleManager().addRole(agent, this); + Gateway.getLookup().addRole(agent, this); } public void removeAgent(AgentPath agent) throws ObjectCannotBeUpdated, ObjectNotFoundException { - Gateway.getLDAPLookup().getRoleManager().removeRole(agent, this); + Gateway.getLookup().removeRole(agent, this); } @Override @@ -99,9 +96,7 @@ public class RolePath extends DomainPath return "Path - dump(): "+ comp.toString()+ - "}\n dn="+ - getDN()+ - "\n string="+ + "}\n string="+ toString()+ "\n type="+ mType+ @@ -110,15 +105,5 @@ public class RolePath extends DomainPath "\n "; } - @Override - public LDAPAttributeSet createAttributeSet() - { - LDAPAttributeSet attrs = new LDAPAttributeSet(); - attrs.add(new LDAPAttribute("objectclass","cristalrole")); - String jobListString = hasJobList?"TRUE":"FALSE"; - attrs.add(new LDAPAttribute("jobList",jobListString)); - attrs.add(new LDAPAttribute("cn", getName())); - return attrs; - } } diff --git a/src/main/java/com/c2kernel/lookup/ldap/LDAPAuthManager.java b/src/main/java/com/c2kernel/lookup/ldap/LDAPAuthManager.java new file mode 100644 index 0000000..4c26de6 --- /dev/null +++ b/src/main/java/com/c2kernel/lookup/ldap/LDAPAuthManager.java @@ -0,0 +1,95 @@ +package com.c2kernel.lookup.ldap; + +import com.c2kernel.common.InvalidDataException; +import com.c2kernel.common.ObjectNotFoundException; +import com.c2kernel.process.Gateway; +import com.c2kernel.process.auth.Authenticator; +import com.c2kernel.utils.Logger; +import com.novell.ldap.LDAPConnection; +import com.novell.ldap.LDAPException; + +public class LDAPAuthManager implements Authenticator { + + private LDAPConnection mLDAPConn; + private LDAPProperties ldapProps; + + + @Override + public boolean authenticate(String agentName, + String password, String resource) throws InvalidDataException, ObjectNotFoundException { + + ldapProps = new LDAPProperties(Gateway.getProperties()); + + if (ldapProps.mHost!=null && ldapProps.mPort!= null && ldapProps.mLocalPath!=null ) + { + try { // anonymously bind to LDAP and find the agent entry for the username + ldapProps.mUser = ""; + ldapProps.mPassword = ""; + mLDAPConn = LDAPLookupUtils.createConnection(ldapProps); + LDAPLookup anonLookup = new LDAPLookup(ldapProps); + anonLookup.open(this); + String agentDN = anonLookup.getFullDN(anonLookup.getAgentPath(agentName)); + + //found agentDN, try to log in with it + ldapProps.mUser = agentDN; + ldapProps.mPassword = password; + mLDAPConn = LDAPLookupUtils.createConnection(ldapProps); + return true; + } catch (LDAPException e) { + return false; + } + } + else + { + throw new InvalidDataException("Cannot log in. Some connection properties are not set.", ""); + } + + } + + @Override + public boolean authenticate(String resource) throws InvalidDataException, ObjectNotFoundException { + ldapProps = new LDAPProperties(Gateway.getProperties()); + + if (ldapProps.mUser == null || ldapProps.mUser.length()==0 || + ldapProps.mPassword == null || ldapProps.mPassword.length()==0) + throw new InvalidDataException("LDAP root user properties not found in config."); + try { + mLDAPConn = LDAPLookupUtils.createConnection(ldapProps); + return true; + } catch (LDAPException e) { + return false; + } + } + + @Override + public LDAPConnection getAuthObject() { + + if (!mLDAPConn.isConnected()) { + Logger.warning("LDAPAuthManager - lost connection to LDAP server. Attempting to reconnect."); + try { + mLDAPConn = LDAPLookupUtils.createConnection(ldapProps); + } catch (LDAPException ex) { } + } + return mLDAPConn; + } + + @Override + public void disconnect() { + Logger.msg(1, "LDAP Lookup: Shutting down LDAP connection."); + if (mLDAPConn != null) { + try { + mLDAPConn.disconnect(); + } catch (LDAPException e) { + Logger.error(e); + } + mLDAPConn = null; + } + + } + + public LDAPAuthManager() { + // TODO Auto-generated constructor stub + } + + +} diff --git a/src/main/java/com/c2kernel/lookup/ldap/LDAPLookup.java b/src/main/java/com/c2kernel/lookup/ldap/LDAPLookup.java new file mode 100644 index 0000000..a96a46b --- /dev/null +++ b/src/main/java/com/c2kernel/lookup/ldap/LDAPLookup.java @@ -0,0 +1,775 @@ +/* + * Directory Lookup Service * + * author: Florida Estrella +*/ + +package com.c2kernel.lookup.ldap; + +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.StringTokenizer; + +import org.omg.CORBA.Object; + +import com.c2kernel.common.ObjectAlreadyExistsException; +import com.c2kernel.common.ObjectCannotBeUpdated; +import com.c2kernel.common.ObjectNotFoundException; +import com.c2kernel.entity.TraceableEntity; +import com.c2kernel.entity.agent.ActiveEntity; +import com.c2kernel.entity.proxy.ProxyMessage; +import com.c2kernel.lookup.AgentPath; +import com.c2kernel.lookup.DomainPath; +import com.c2kernel.lookup.InvalidItemPathException; +import com.c2kernel.lookup.ItemPath; +import com.c2kernel.lookup.Lookup; +import com.c2kernel.lookup.Path; +import com.c2kernel.lookup.RolePath; +import com.c2kernel.process.Gateway; +import com.c2kernel.process.auth.Authenticator; +import com.c2kernel.property.PropertyDescription; +import com.c2kernel.property.PropertyDescriptionList; +import com.c2kernel.utils.Logger; +import com.novell.ldap.LDAPAttribute; +import com.novell.ldap.LDAPAttributeSet; +import com.novell.ldap.LDAPConnection; +import com.novell.ldap.LDAPDN; +import com.novell.ldap.LDAPEntry; +import com.novell.ldap.LDAPException; +import com.novell.ldap.LDAPSearchConstraints; +import com.novell.ldap.LDAPSearchResults; + +/** + * The LDAPLookup object, statically accessible through the Gateway, manages + * the LDAP connection for the cristal process. It provides: + *
      + *
    • Authentication - returning an AgentProxy object if a user has logged in + *
    • System key generation - through the NextKeyManager + *
    • Agent and Role lookup/modification - through the RoleManager + *
    • + * @version $Revision: 1.113 $ $Date: 2006/03/03 13:52:21 $ + * @author $Author: abranson $ + */ + +public class LDAPLookup implements Lookup + +{ + private LDAPAuthManager mLDAPAuth; + private LDAPNextKeyManager mNextKeyManager; + private LDAPPropertyManager mPropManager; + + final String mItemTypeRoot, mDomainTypeRoot, mGlobalPath, mRootPath, mLocalPath, mRolePath; + + /** + * Creates a new LDAPLookup manager with the properties supplied. + * This should be only done by the Gateway during initialisation. + * + * @param props The LDAP properties object that extracts LDAP connection properties from the global c2kprops + */ + public LDAPLookup(LDAPProperties props) + { + Logger.msg(8,"LDAPLookup - initialising."); + + mGlobalPath=props.mGlobalPath; + mRootPath=props.mRootPath; + mLocalPath=props.mLocalPath; + + mItemTypeRoot = "cn=entity,"+props.mLocalPath; + mDomainTypeRoot = "cn=domain,"+props.mLocalPath; + mRolePath = "cn=agent,"+mDomainTypeRoot; + + } + + public LDAPLookup() { + this(new LDAPProperties(Gateway.getProperties())); + } + + @Override + public void open(Authenticator auth) { + mLDAPAuth = (LDAPAuthManager)auth; + mNextKeyManager = new LDAPNextKeyManager(mLDAPAuth, "cn=last,"+mItemTypeRoot); + Gateway.getProperties().setProperty("NextKeyManager", mNextKeyManager); + Logger.msg(7, "LDAP.useOldProps="+Gateway.getProperties().getBoolean("LDAP.useOldProps", false)); + mPropManager = new LDAPPropertyManager(this, mLDAPAuth); + } + + /** + * Gets the entity key generator, used to get a unique system key for new entities. + * @return the global NextKeyManager + */ + public LDAPNextKeyManager getNextKeyManager() + { + return mNextKeyManager; + } + + /** + * Gets the property manager, that is used to read and write cristal properties to the LDAP store. + * @return Returns the global LDAPPropertyManager. + */ + public LDAPPropertyManager getPropManager() { + return mPropManager; + } + + /** + * Disconnects the connection with the LDAP server during shutdown + */ + @Override + public void close() { + Logger.msg(1, "LDAP Lookup: Shutting down LDAP connection."); + if (mLDAPAuth != null) { + mLDAPAuth.disconnect(); + mLDAPAuth = null; + } + } + + /** + * Attempts to resolve the CORBA object for a Path, either directly or through an alias. + * @param path the path to resolve + * @return the CORBA object + * @throws ObjectNotFoundException When the path does not exist + */ + public org.omg.CORBA.Object getIOR(Path path) + throws ObjectNotFoundException + { + return resolveObject(getFullDN(path)); + } + + /** + * Attempts to resolve the CORBA object from the IOR attribute of a DN, either directly or through an alias + * @param dn The String dn + * @throws ObjectNotFoundException when the dn or aliased dn does not exist + */ + private org.omg.CORBA.Object resolveObject(String dn) + throws ObjectNotFoundException + { + Logger.msg(8,"LDAPLookup.resolveObject("+dn+")"); + LDAPEntry anEntry = LDAPLookupUtils.getEntry(mLDAPAuth.getAuthObject(),dn,LDAPSearchConstraints.DEREF_NEVER); + if (anEntry != null) + { + String iorString; + try { + iorString = LDAPLookupUtils.getFirstAttributeValue(anEntry, "ior"); + org.omg.CORBA.Object ior=Gateway.getORB().string_to_object(iorString); + if (ior!=null) + return ior; + else + throw new ObjectNotFoundException("LDAPLookup.resolveObject() - " + dn + " has no IOR", ""); + } catch (ObjectNotFoundException ex) { + return resolveObject(LDAPLookupUtils.getFirstAttributeValue(anEntry,"aliasedObjectName")); + } + } + else + throw new ObjectNotFoundException("LDAPLookup.resolveObject() LDAP node " + dn + " is not in LDAP or has no IOR.", ""); + } + + /** + * + * @param domPath + * @return + * @throws InvalidItemPathException + * @throws ObjectNotFoundException + */ + @Override + public ItemPath resolvePath(DomainPath domPath) + throws InvalidItemPathException, ObjectNotFoundException { + ItemPath referencedPath = null; + LDAPEntry domEntry = LDAPLookupUtils.getEntry(mLDAPAuth.getAuthObject(), + getFullDN(domPath), LDAPSearchConstraints.DEREF_ALWAYS); + String entityKey = LDAPLookupUtils.getFirstAttributeValue(domEntry, + "intsyskey"); + Logger.msg(7, "DomainPath " + domPath + " is a reference to " + + entityKey); + String objClass = LDAPLookupUtils.getFirstAttributeValue(domEntry, + "objectClass"); + if (objClass.equals("cristalagent")) + referencedPath = new AgentPath(Integer.parseInt(entityKey)); + else + referencedPath = new ItemPath(Integer.parseInt(entityKey)); + + return referencedPath; + } + + + @Override + public void add(Path path) + throws ObjectCannotBeUpdated, ObjectAlreadyExistsException + { + try { + checkLDAPContext(path); + LDAPAttributeSet attrSet = createAttributeSet(path); + LDAPEntry newEntry = new LDAPEntry(getFullDN(path),attrSet); + LDAPLookupUtils.addEntry(mLDAPAuth.getAuthObject(),newEntry); + if (path instanceof DomainPath) + Gateway.getProxyServer().sendProxyEvent(new ProxyMessage(ProxyMessage.NA, path.toString(), ProxyMessage.ADDED)); + } catch (LDAPException ex) { + if (ex.getResultCode() == LDAPException.ENTRY_ALREADY_EXISTS) + throw new ObjectAlreadyExistsException(ex.getLDAPErrorMessage(), ""); + else + throw new ObjectCannotBeUpdated(ex.getLDAPErrorMessage(), ""); + } + } + + //deletes a node + //throws LDAPexception if node cannot be deleted (eg node is not a leaf) + @Override + public void delete(Path path) throws ObjectCannotBeUpdated + { + try { + LDAPLookupUtils.delete(mLDAPAuth.getAuthObject(),getDN(path)+mLocalPath); + } catch (LDAPException ex) { + throw new ObjectCannotBeUpdated(ex.getLDAPErrorMessage(), ""); + } + if (path instanceof DomainPath) { + Gateway.getProxyServer().sendProxyEvent(new ProxyMessage(ProxyMessage.NA, path.toString(), ProxyMessage.DELETED)); + } + } + + //change specs, add boolean alias leaf context + protected void checkLDAPContext(Path path) + { + String dn = getFullDN(path); + if (!LDAPLookupUtils.exists(mLDAPAuth.getAuthObject(),dn)) + { + String listDN[] = path.getPath(); + String name = "cn="+ path.getRoot() + "," + mLocalPath; + int i=0; + while (i getItemClass(Path path) throws ObjectNotFoundException { + String[] attr = { LDAPConnection.ALL_USER_ATTRS }; + try { + LDAPEntry anEntry=mLDAPAuth.getAuthObject().read(getDN(path)+mLocalPath,attr); + String type = LDAPLookupUtils.getFirstAttributeValue(anEntry, "objectClass"); + if (type.equals("cristalentity")) + return TraceableEntity.class; + else if (type.equals("cristalagent")) + return ActiveEntity.class; + else + throw new ObjectNotFoundException("Not an entity", ""); + + } catch (LDAPException ex) { + if (ex.getResultCode() == LDAPException.NO_SUCH_OBJECT) + throw new ObjectNotFoundException("Entity does not exist", ""); + Logger.error(ex); + throw new ObjectNotFoundException("Error getting entity class", ""); + } + } + + /** converts an LDAPentry to a Path object + * Note that the search producing the entry should have retrieved the attrs + * 'ior' and 'uniquemember' + * @throws ObjectNotFoundException + * @throws ObjectNotFoundException + */ + protected Path nodeToPath(LDAPEntry entry) throws InvalidItemPathException, ObjectNotFoundException + { + String dn = entry.getDN(); + + // extract syskey + int entityKey = -1; + try { + String entityKeyStr = LDAPLookupUtils.getFirstAttributeValue(entry,"intsyskey"); + entityKey = Integer.parseInt(entityKeyStr); + } catch (Exception e) { } + + // extract IOR + org.omg.CORBA.Object ior = null; + try { + String stringIOR = LDAPLookupUtils.getFirstAttributeValue(entry,"ior"); + ior = Gateway.getORB().string_to_object(stringIOR); + } catch (ObjectNotFoundException e2) { } + + /* Find the right path class */ + Path thisPath; + if (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","cristalagent")) + { //cristalagent + String agentID = LDAPLookupUtils.getFirstAttributeValue(entry,"uid"); + thisPath = new AgentPath(entityKey, agentID); + } + + else if (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","cristalrole")) + { //cristalrole + thisPath = new RolePath(LDAPDN.explodeDN(dn,true)[0], + LDAPLookupUtils.getFirstAttributeValue(entry, "jobList").equals("TRUE")); + } + else if (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","aliasObject") || + (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","cristalcontext") && dn.endsWith(mDomainTypeRoot))) + { + DomainPath domainPath = new DomainPath(); + domainPath.setPath(getPathComponents(dn.substring(0, dn.lastIndexOf(mDomainTypeRoot)))); + thisPath = domainPath; + } + else if (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","cristalentity") || + (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","cristalcontext") && dn.endsWith(mItemTypeRoot))) + { + if(dn.endsWith(mItemTypeRoot)) { + ItemPath entityPath; + if (entityKey != -1) + entityPath = new ItemPath(entityKey); + else { + entityPath = new ItemPath(); + entityPath.setPath(getPathComponents(dn.substring(0, dn.lastIndexOf(mItemTypeRoot)))); + } + thisPath = entityPath; + } + else + throw new ObjectNotFoundException("Entity found outside entity tree"); + } + else + { + throw new ObjectNotFoundException("Unrecognised LDAP entry. Not a cristal entry"); + } + + //set IOR if we have one + if (ior!=null) thisPath.setIOR(ior); + return thisPath; + } + + public String getDN(Path path) { + StringBuffer dnBuffer = new StringBuffer(); + String[] pathComp = path.getPath(); + for (int i=pathComp.length-1; i>=0; i--) + dnBuffer.append("cn=").append(LDAPLookupUtils.escapeDN(pathComp[i])).append(","); + dnBuffer.append("cn="+path.getRoot()+","); + return dnBuffer.toString(); + } + + public String getFullDN(Path path) { + return getDN(path)+mLocalPath; + } + + public String[] getPathComponents(String dnFragment) { + ArrayList newPath = new ArrayList(); + StringTokenizer tok = new StringTokenizer(dnFragment, ","); + String[] path = new String[tok.countTokens()]; + while (tok.hasMoreTokens()) { + String nextPath = tok.nextToken(); + if (nextPath.indexOf("cn=") == 0) + newPath.add(0, LDAPLookupUtils.unescapeDN(nextPath.substring(3))); + else + break; + } + return newPath.toArray(path); + } + + @Override + public Object resolve(Path path) throws ObjectNotFoundException { + return resolveObject(getFullDN(path)); + } + + @Override + public Iterator getChildren(Path path) { + if (path instanceof RolePath) return ((RolePath)path).getChildren(); + String filter = "objectclass=*"; + LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); + searchCons.setBatchSize(10); + searchCons.setDereference(LDAPSearchConstraints.DEREF_FINDING ); + return search(getFullDN(path), LDAPConnection.SCOPE_ONE,filter,searchCons); + } + + public LDAPAttributeSet createAttributeSet(Path path) throws ObjectCannotBeUpdated { + LDAPAttributeSet attrs = new LDAPAttributeSet(); + + if (path instanceof RolePath) { + RolePath rolePath = (RolePath)path; + attrs.add(new LDAPAttribute("objectclass","cristalrole")); + String jobListString = rolePath.hasJobList()?"TRUE":"FALSE"; + attrs.add(new LDAPAttribute("jobList",jobListString)); + attrs.add(new LDAPAttribute("cn", rolePath.getName())); + } + else if (path instanceof DomainPath) { + DomainPath domPath = (DomainPath)path; + attrs.add(new LDAPAttribute("cn",domPath.getName())); + try { + attrs.add(new LDAPAttribute("aliasedObjectName",getFullDN(domPath.getEntity()))); + String objectclass_values[] = { "alias", "aliasObject" }; + attrs.add(new LDAPAttribute("objectclass",objectclass_values)); + } catch (ObjectNotFoundException e) { // no entity - is a context + attrs.add(new LDAPAttribute("objectclass","cristalcontext")); + } + } + + else if (path instanceof ItemPath) { + ItemPath itemPath = (ItemPath)path; + attrs.add(new LDAPAttribute("intsyskey",Integer.toString(itemPath.getSysKey()))); + attrs.add(new LDAPAttribute("cn", itemPath.getPath()[itemPath.getPath().length-1])); + if (itemPath.getIOR() != null) + attrs.add(new LDAPAttribute("ior", Gateway.getORB().object_to_string(itemPath.getIOR()))); + + if (path instanceof AgentPath) { + AgentPath agentPath = (AgentPath)path; + attrs.add(new LDAPAttribute("objectclass","cristalagent")); + + String agentName = agentPath.getAgentName(); + if (agentName != null && agentName.length() > 0) + attrs.add(new LDAPAttribute("uid", agentName)); + else + throw new ObjectCannotBeUpdated("Cannot create agent. No userId specified", ""); + + String agentPass = agentPath.getPassword(); + if (agentPass != null && agentPass.length() > 0) + try { + attrs.add(new LDAPAttribute("userPassword", AgentPath.generateUserPassword(agentPass, "SHA"))); + } catch (NoSuchAlgorithmException ex) { + throw new ObjectCannotBeUpdated("Cryptographic libraries for password hashing not found.", ""); + } + else + throw new ObjectCannotBeUpdated("Cannot create agent. No password given", ""); + } + else { + attrs.add(new LDAPAttribute("objectclass","cristalentity")); + } + } + + return attrs; + + } + + //NOTE: A role must have at LEAST 1 userDN, cannot be empty... + //Creates a cristalRole + //CristalRole is-a specialized CristalContext which contains multi-valued uniqueMember attribute pointing to cristalagents + @Override + public RolePath createRole(String roleName, boolean jobList) + throws ObjectAlreadyExistsException, ObjectCannotBeUpdated + { + + // create the role + RolePath rolePath = new RolePath(roleName, jobList); + String roleDN = getFullDN(rolePath); + LDAPEntry roleNode; + try + { + roleNode = LDAPLookupUtils.getEntry(mLDAPAuth.getAuthObject(), getFullDN(rolePath)); + throw new ObjectAlreadyExistsException(); + } catch (ObjectNotFoundException ex) { } + + //create CristalRole if it does not exist + roleNode = new LDAPEntry(roleDN, createAttributeSet(rolePath)); + try { + LDAPLookupUtils.addEntry(mLDAPAuth.getAuthObject(),roleNode); + } catch (LDAPException e) { + throw new ObjectCannotBeUpdated(e.getLDAPErrorMessage(), ""); + } + return rolePath; + + + } + public void deleteRole(RolePath role) throws ObjectNotFoundException, ObjectCannotBeUpdated { + try { + LDAPLookupUtils.delete(mLDAPAuth.getAuthObject(), getFullDN(role)); + } catch (LDAPException ex) { + throw new ObjectCannotBeUpdated("Could not remove role"); + } + } + + @Override + public void addRole(AgentPath agent, RolePath role) + throws ObjectCannotBeUpdated, ObjectNotFoundException + { + LDAPEntry roleEntry = LDAPLookupUtils.getEntry(mLDAPAuth.getAuthObject(), getFullDN(role)); + //add memberDN to uniqueMember if it is not yet a member + if (!LDAPLookupUtils.existsAttributeValue(roleEntry, "uniqueMember", getFullDN(agent))) + LDAPLookupUtils.addAttributeValue(mLDAPAuth.getAuthObject(), roleEntry, "uniqueMember", getFullDN(agent)); + else + throw new ObjectCannotBeUpdated("Agent " + agent.getAgentName() + " already has role " + role.getName()); + } + + @Override + public void removeRole(AgentPath agent, RolePath role) + throws ObjectCannotBeUpdated, ObjectNotFoundException + { + LDAPEntry roleEntry = LDAPLookupUtils.getEntry(mLDAPAuth.getAuthObject(), getFullDN(role)); + if (LDAPLookupUtils.existsAttributeValue(roleEntry, "uniqueMember", getFullDN(agent))) + LDAPLookupUtils.removeAttributeValue(mLDAPAuth.getAuthObject(), roleEntry, "uniqueMember", getFullDN(agent)); + else + throw new ObjectCannotBeUpdated("Agent did not have that role"); + } + + @Override + public boolean hasRole(AgentPath agent, RolePath role) { + String filter = "(&(objectclass=cristalrole)(uniqueMember="+getFullDN(agent)+")(cn="+role.getName()+"))"; + LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); + searchCons.setBatchSize(0); + searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER ); + return search(mRolePath,LDAPConnection.SCOPE_SUB,filter,searchCons).hasNext(); + } + + @Override + public AgentPath[] getAgents(RolePath role) + throws ObjectNotFoundException + { + //get the roleDN entry, and its uniqueMember entry pointing to + LDAPEntry roleEntry; + try { + roleEntry = LDAPLookupUtils.getEntry(mLDAPAuth.getAuthObject(), getFullDN(role)); + } catch (ObjectNotFoundException e) { + throw new ObjectNotFoundException("Role does not exist", ""); + } + + String[] res = LDAPLookupUtils.getAllAttributeValues(roleEntry,"uniqueMember"); + ArrayList agents = new ArrayList(); + for (String userDN : res) { + try { + LDAPEntry userEntry = LDAPLookupUtils.getEntry(mLDAPAuth.getAuthObject(), userDN); + AgentPath path = (AgentPath)nodeToPath(userEntry); + agents.add(path); + } catch (ObjectNotFoundException ex) { + Logger.error("Agent "+userDN+" does not exist"); + } catch (InvalidItemPathException ex) { + Logger.error("Agent "+userDN+" is not a valid entity"); + } + } + AgentPath[] usersList = new AgentPath[0]; + usersList = agents.toArray(usersList); + return usersList; + } + + //returns the role/s of a user + @Override + public RolePath[] getRoles(AgentPath agentPath) + { + //search the mDomainPath tree uniqueMember=userDN + //filter = objectclass=cristalrole AND uniqueMember=userDN + String filter = "(&(objectclass=cristalrole)(uniqueMember="+getFullDN(agentPath)+"))"; + LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); + searchCons.setBatchSize(0); + searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER ); + Iterator roles = search(mRolePath,LDAPConnection.SCOPE_SUB,filter,searchCons); + ArrayList roleList = new ArrayList(); + + while(roles.hasNext()) + { + RolePath path = (RolePath) roles.next(); + roleList.add(path); + } + RolePath[] roleArr = new RolePath[roleList.size()]; + roleArr = roleList.toArray(roleArr); + return roleArr; + } + + /** + * Utility for looking up a login name + * + * @param ld + * @param agentName + * @param baseDN + * @return + * @throws ObjectNotFoundException + */ + @Override + public AgentPath getAgentPath(String agentName) throws ObjectNotFoundException + { + //search to get the userDN equivalent of the userID + LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); + searchCons.setBatchSize(0); + searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER ); + String filter = "(&(objectclass=cristalagent)(uid="+agentName+"))"; + Iterator res = search(mItemTypeRoot,LDAPConnection.SCOPE_SUB,filter,searchCons); + if (!res.hasNext()) + throw new ObjectNotFoundException("Agent not found: "+agentName, ""); + Path result = res.next(); + if (result instanceof AgentPath) + return (AgentPath)result; + else + throw new ObjectNotFoundException("Entry was not an Agent"); + } + + @Override + public RolePath getRolePath(String roleName) throws ObjectNotFoundException + { + LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); + searchCons.setBatchSize(0); + searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER ); + String filter = "(&(objectclass=cristalrole)(cn="+roleName+"))"; + Iterator res = search(mRolePath,LDAPConnection.SCOPE_SUB,filter,searchCons); + if (!res.hasNext()) + throw new ObjectNotFoundException("Role not found"); + Path result = res.next(); + if (result instanceof RolePath) + return (RolePath)result; + else + throw new ObjectNotFoundException("Entry was not a Role"); + } + + @Override + public void setHasJobList(RolePath role, boolean hasJobList) throws ObjectNotFoundException, ObjectCannotBeUpdated { + // get entry + LDAPEntry roleEntry; + try { + roleEntry = LDAPLookupUtils.getEntry(mLDAPAuth.getAuthObject(), getFullDN(role)); + } catch (ObjectNotFoundException e) { + throw new ObjectNotFoundException("Role does not exist", ""); + } + // set attribute + LDAPLookupUtils.setAttributeValue(mLDAPAuth.getAuthObject(), roleEntry, "jobList", hasJobList?"TRUE":"FALSE"); + } + + @Override + public void setAgentPassword(AgentPath agent, String newPassword) throws ObjectNotFoundException, ObjectCannotBeUpdated, NoSuchAlgorithmException { + String encPasswd = AgentPath.generateUserPassword(newPassword, "SHA"); + LDAPEntry agentEntry; + try { + agentEntry = LDAPLookupUtils.getEntry(mLDAPAuth.getAuthObject(), getFullDN(agent)); + } catch (ObjectNotFoundException e) { + throw new ObjectNotFoundException("Agent "+agent.getAgentName()+" does not exist", ""); + } + LDAPLookupUtils.setAttributeValue(mLDAPAuth.getAuthObject(), agentEntry, "userPassword", encPasswd); + + } + + @Override + public String getAgentName(AgentPath agentPath) + throws ObjectNotFoundException { + LDAPEntry agentEntry = LDAPLookupUtils.getEntry(mLDAPAuth.getAuthObject(), getFullDN(agentPath)); + return LDAPLookupUtils.getFirstAttributeValue(agentEntry,"uid"); + } + +} diff --git a/src/main/java/com/c2kernel/lookup/ldap/LDAPLookupUtils.java b/src/main/java/com/c2kernel/lookup/ldap/LDAPLookupUtils.java new file mode 100644 index 0000000..e1c8ac4 --- /dev/null +++ b/src/main/java/com/c2kernel/lookup/ldap/LDAPLookupUtils.java @@ -0,0 +1,365 @@ +/* + * Lookup helper class. + */ + +package com.c2kernel.lookup.ldap; + +//import netscape.ldap.*; +//import netscape.ldap.util.*; +import com.c2kernel.common.ObjectAlreadyExistsException; +import com.c2kernel.common.ObjectCannotBeUpdated; +import com.c2kernel.common.ObjectNotFoundException; +import com.c2kernel.utils.Logger; +import com.novell.ldap.LDAPAttribute; +import com.novell.ldap.LDAPAttributeSet; +import com.novell.ldap.LDAPConnection; +import com.novell.ldap.LDAPDN; +import com.novell.ldap.LDAPEntry; +import com.novell.ldap.LDAPException; +import com.novell.ldap.LDAPModification; +import com.novell.ldap.LDAPSearchConstraints; +import com.novell.ldap.LDAPSearchResults; + +/** + * @version $Revision: 1.74 $ $Date: 2006/03/03 13:52:21 $ + * @author $Author: abranson $ + */ + +final public class LDAPLookupUtils +{ + static final char[] META_CHARS = {'+', '=', '"', ',', '<', '>', ';', '/'}; + static final String[] META_ESCAPED = {"2B", "3D", "22", "2C", "3C", "3E", "3B", "2F"}; + static public LDAPEntry getEntry(LDAPConnection ld, String dn,int dereference) + throws ObjectNotFoundException + { + try { + LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); + searchCons.setBatchSize(0); + searchCons.setDereference(dereference); + LDAPEntry thisEntry = ld.read(dn,searchCons); + if (thisEntry != null) return thisEntry; + } catch (LDAPException ex) { + throw new ObjectNotFoundException("LDAP Exception for dn:"+dn+": \n"+ex.getMessage(), ""); + } + throw new ObjectNotFoundException(dn+" does not exist", ""); + + } + + + /** + * Utility method to connect to an LDAP server + * @param lp LDAP properties to connect with + * @return a novell LDAPConnection object + * @throws LDAPException when the connection was unsuccessful + */ + public static LDAPConnection createConnection(LDAPProperties lp) throws LDAPException { + LDAPConnection ld = new LDAPConnection(); + + Logger.msg(3, "LDAPLookup - connecting to " + lp.mHost); + ld.connect(lp.mHost, Integer.valueOf(lp.mPort).intValue()); + + Logger.msg(3, "LDAPLookup - authenticating user:" + lp.mUser); + ld.bind( LDAPConnection.LDAP_V3, lp.mUser, + String.valueOf(lp.mPassword).getBytes()); + + Logger.msg(3, "LDAPLookup - authentication successful"); + LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); + searchCons.setMaxResults(0); + ld.setConstraints(searchCons); + + return ld; + } + + //Given a DN, return an LDAP Entry + static public LDAPEntry getEntry(LDAPConnection ld, String dn) + throws ObjectNotFoundException + { + return getEntry(ld, dn, LDAPSearchConstraints.DEREF_NEVER); + } + + static public String getFirstAttributeValue(LDAPEntry anEntry, String attribute) throws ObjectNotFoundException + { + LDAPAttribute attr = anEntry.getAttribute(attribute); + if (attr==null) + throw new ObjectNotFoundException("No attributes named '"+attribute+"'", ""); + return (String)attr.getStringValues().nextElement(); + } + + static public String[] getAllAttributeValues(LDAPEntry anEntry, String attribute) throws ObjectNotFoundException + { + LDAPAttribute attr = anEntry.getAttribute(attribute); + if (attr!=null) + return attr.getStringValueArray(); + + throw new ObjectNotFoundException("No attributes named '"+attribute+"'", ""); + + } + + static public boolean existsAttributeValue(LDAPEntry anEntry, String attribute, String value) + { + LDAPAttribute attr = anEntry.getAttribute(attribute); + if (attr!=null) + { + String[] attrValues = new String[attr.size()]; + attrValues = attr.getStringValueArray(); + for (int i=0;i 0) + throw new ObjectCannotBeUpdated("NextKeyManager: Storage already contains data for syskey "+lastKey.getSysKey()+ + ". Storage is out of sync with nextkey. Please contact an administrator", ""); + } catch (ClusterStorageException e) { + Logger.error(e); + throw new ObjectCannotBeUpdated("Could not check storage for prior data for the next generated systemKey: "+e.getMessage()); + } + + //set the last key + writeLastEntityKey(lastKey.getSysKey()); + + return lastKey; + } + + @Override + public synchronized AgentPath generateNextAgentKey() + throws ObjectCannotBeUpdated, ObjectNotFoundException { + ItemPath newEntity = generateNextEntityKey(); + return new AgentPath(newEntity); + } + + @Override + public void writeLastEntityKey(int sysKey) throws ObjectCannotBeUpdated, ObjectNotFoundException { + LDAPEntry lastKeyEntry = LDAPLookupUtils.getEntry(ldap.getAuthObject(),lastKeyPath); + LDAPLookupUtils.setAttributeValue(ldap.getAuthObject(), lastKeyEntry,"intsyskey",Integer.toString(sysKey)); + } + + @Override + public ItemPath getLastEntityPath() throws ObjectNotFoundException + { + LDAPEntry lastKeyEntry = LDAPLookupUtils.getEntry(ldap.getAuthObject(),lastKeyPath); + String lastKey = LDAPLookupUtils.getFirstAttributeValue(lastKeyEntry,"intsyskey"); + try { + int sysKey = Integer.parseInt(lastKey); + ItemPath sysPath = new ItemPath(sysKey); + return sysPath; + } catch (InvalidItemPathException ex) { + throw new ObjectNotFoundException("Invalid syskey. Maybe centre is full."); + } catch (NumberFormatException ex) { + throw new ObjectNotFoundException("Invalid syskey in lastkey."); + } + + } + +} diff --git a/src/main/java/com/c2kernel/lookup/ldap/LDAPPathSet.java b/src/main/java/com/c2kernel/lookup/ldap/LDAPPathSet.java new file mode 100644 index 0000000..806976d --- /dev/null +++ b/src/main/java/com/c2kernel/lookup/ldap/LDAPPathSet.java @@ -0,0 +1,81 @@ +package com.c2kernel.lookup.ldap; + +import java.util.Iterator; + +import com.c2kernel.lookup.Path; +import com.c2kernel.utils.Logger; +import com.novell.ldap.LDAPEntry; +import com.novell.ldap.LDAPException; +import com.novell.ldap.LDAPSearchResults; + +/************************************************************************** + * + * $Revision: 1.6 $ + * $Date: 2005/12/01 14:23:14 $ + * + * Copyright (C) 2003 CERN - European Organization for Nuclear Research + * All rights reserved. + **************************************************************************/ + + + +public class LDAPPathSet implements Iterator { + LDAPSearchResults results; + LDAPEntry nextEntry; + LDAPLookup ldap; + + public LDAPPathSet(LDAPLookup ldap) { // empty + this.ldap = ldap; + results = null; + } + + public LDAPPathSet(LDAPSearchResults results, LDAPLookup ldap) { + this.ldap = ldap; + this.results = results; + } + + @Override + public boolean hasNext() { + if (results == null) return false; + if (nextEntry != null) return true; + if (results.hasMore()) + try { + nextEntry = results.next(); + return true; + } catch (LDAPException ex) { + if (ex.getResultCode()!=32) {// no results + Logger.error(ex); + Logger.error("Error loading LDAP result set: "+ex.getMessage()); + } + } + return false; + } + + @Override + public Path next() { + if (results == null) return null; + try { + if (nextEntry == null) + nextEntry = results.next(); + Path nextPath = ldap.nodeToPath(nextEntry); + nextEntry = null; + return nextPath; + } catch (Exception ex) { + Logger.error("Error loading next path"); + Logger.error(ex); + nextEntry = null; + if (hasNext()) { + Logger.error("Skipping to next entry"); + return next(); + } + else + return null; + } + } + + @Override + public void remove() { + // do nothing + + } +} diff --git a/src/main/java/com/c2kernel/lookup/ldap/LDAPProperties.java b/src/main/java/com/c2kernel/lookup/ldap/LDAPProperties.java new file mode 100644 index 0000000..1e9f971 --- /dev/null +++ b/src/main/java/com/c2kernel/lookup/ldap/LDAPProperties.java @@ -0,0 +1,38 @@ +/* + * Directory Lookup Service +*/ + +package com.c2kernel.lookup.ldap; + +import com.c2kernel.utils.ObjectProperties; + +/** + * @version $Revision: 1.16 $ $Date: 2005/10/12 12:51:54 $ + * @author $Author: abranson $ + */ +public class LDAPProperties +{ + public String mGlobalPath = null; //o=cern.ch + public String mRootPath = null; //cn=cristal2 + public String mLocalPath = null; //cn=lab27 + public Integer mPort = null; + public String mHost = null; + public String mUser = null; + public String mPassword = null; + + public LDAPProperties(ObjectProperties obj) + { + mGlobalPath = obj.getProperty( "LDAP.GlobalPath" ); + mRootPath = obj.getProperty( "LDAP.RootPath" ); + mLocalPath = obj.getProperty( "LDAP.LocalPath" ); + mPort = obj.getInt( "LDAP.port", 389 ); + mHost = obj.getProperty( "LDAP.host" ); + mUser = obj.getProperty( "LDAP.user" ); + mPassword = obj.getProperty( "LDAP.password" ); + + mRootPath += "," + mGlobalPath; + mLocalPath += "," + mRootPath; + + } +} + diff --git a/src/main/java/com/c2kernel/lookup/ldap/LDAPPropertyManager.java b/src/main/java/com/c2kernel/lookup/ldap/LDAPPropertyManager.java new file mode 100644 index 0000000..1b6e906 --- /dev/null +++ b/src/main/java/com/c2kernel/lookup/ldap/LDAPPropertyManager.java @@ -0,0 +1,141 @@ +package com.c2kernel.lookup.ldap; + +import java.util.ArrayList; +import java.util.Enumeration; + +import com.c2kernel.common.ObjectCannotBeUpdated; +import com.c2kernel.common.ObjectNotFoundException; +import com.c2kernel.lookup.ItemPath; +import com.c2kernel.property.Property; +import com.c2kernel.utils.Logger; +import com.novell.ldap.LDAPAttribute; +import com.novell.ldap.LDAPEntry; + +/************************************************************************** + * + * $Revision: 1.3 $ + * $Date: 2006/03/03 13:52:21 $ + * + * Copyright (C) 2003 CERN - European Organization for Nuclear Research + * All rights reserved. + **************************************************************************/ + +public class LDAPPropertyManager { + /** + * + */ + protected LDAPLookup ldap; + private final LDAPAuthManager auth; + + public LDAPPropertyManager(LDAPLookup ldap, LDAPAuthManager auth) { + super(); + this.ldap = ldap; + this.auth = auth; + } + + /** + * @param thisItem - EntityPath of the subject entity + * @return + * @throws ObjectNotFoundException + */ + public boolean hasProperties(ItemPath thisItem) throws ObjectNotFoundException { + LDAPEntry entityEntry = LDAPLookupUtils.getEntry(auth.getAuthObject(), ldap.getFullDN(thisItem)); + return entityEntry.getAttribute("cristalprop") != null; + } + + /** + * @param thisItem - EntityPath of the subject entity + * @return array of Property + * @throws ObjectNotFoundException + */ + public String[] getPropertyNames(ItemPath thisItem) throws ObjectNotFoundException { + LDAPEntry entityEntry = LDAPLookupUtils.getEntry(auth.getAuthObject(), ldap.getFullDN(thisItem)); + ArrayList propbag = new ArrayList(); + LDAPAttribute props = entityEntry.getAttribute("cristalprop"); + for (Enumeration e = props.getStringValues(); e.hasMoreElements();) { + String thisProp = (String)e.nextElement(); + String thisName = thisProp.substring(0, thisProp.indexOf(':')); + if (thisName.startsWith("!") && thisName.length()>1) thisName = thisName.substring(1); + propbag.add(thisName); + } + + String[] retArr = new String[props.size()]; + return propbag.toArray(retArr); + } + + /** + * @param thisItem - EntityPath of the subject entity + * @param propName - the name of the property to retrieve + * @return The Property object + * @throws ObjectNotFoundException + */ + public Property getProperty(ItemPath thisItem, String name) throws ObjectNotFoundException { + LDAPEntry entityEntry = LDAPLookupUtils.getEntry(auth.getAuthObject(), ldap.getFullDN(thisItem)); + return getProperty(entityEntry, name); + } + + /** + * @param thisItem - EntityPath of the subject entity + * @param name - the property name to delete + * @throws ObjectNotFoundException + * @throws ObjectCannotBeUpdated + */ + public void deleteProperty(ItemPath thisItem, String name) throws ObjectNotFoundException, ObjectCannotBeUpdated { + LDAPEntry entityEntry = LDAPLookupUtils.getEntry(auth.getAuthObject(), ldap.getFullDN(thisItem)); + Property prop = getProperty(entityEntry, name); + Logger.msg(6, "LDAPLookupUtils.deleteProperty("+name+") - Deleting property"); + LDAPLookupUtils.removeAttributeValue(auth.getAuthObject(), entityEntry, "cristalprop", getPropertyAttrValue(prop)); + } + + private static String getPropertyAttrValue(Property prop) { + return (prop.isMutable()?"":"!")+prop.getName()+":"+prop.getValue(); + } + + /** + * @param thisItem - EntityPath of the subject entity + * @param prop - the property to store + * @throws ObjectNotFoundException + * @throws ObjectCannotBeUpdated + */ + public void setProperty(ItemPath thisItem, Property prop) throws ObjectNotFoundException, ObjectCannotBeUpdated { + LDAPEntry entityEntry = LDAPLookupUtils.getEntry(auth.getAuthObject(), ldap.getFullDN(thisItem)); + try { + Property oldProp = getProperty(entityEntry, prop.getName()); + Logger.msg(6, "LDAPLookupUtils.setProperty("+prop.getName()+") - Removing old value '"+oldProp.getValue()+"'"); + LDAPLookupUtils.removeAttributeValue(auth.getAuthObject(), entityEntry, "cristalprop", getPropertyAttrValue(oldProp)); + } catch (ObjectNotFoundException ex) { + Logger.msg(6, "LDAPLookupUtils.setProperty("+prop.getName()+") - creating new property."); + } + Logger.msg(6, "LDAPLookupUtils.setProperty("+prop.getName()+") - setting to '"+prop.getValue()+"'"); + LDAPLookupUtils.addAttributeValue(auth.getAuthObject(), entityEntry, "cristalprop", getPropertyAttrValue(prop)); + } + + public static Property getProperty(LDAPEntry myEntry, String propName) throws ObjectNotFoundException { + // delete existing props + LDAPAttribute props = myEntry.getAttribute("cristalprop"); + if (props == null) + throw new ObjectNotFoundException("Property "+propName+" does not exist", ""); + String propPrefix = propName+":"; + String roPropPrefix = "!"+propPrefix; + String val = null, name = null; boolean mutable = false; + for (Enumeration e = props.getStringValues(); name==null && e.hasMoreElements();) { + String attrVal = (String)e.nextElement(); + if (attrVal.toLowerCase().startsWith(propPrefix.toLowerCase())) { + name = attrVal.substring(0, propPrefix.length()-1); + val = attrVal.substring(propPrefix.length()); + mutable = true; break; + } + + if (attrVal.toLowerCase().startsWith(roPropPrefix.toLowerCase())) { + name = attrVal.substring(1, roPropPrefix.length()-1); + val = attrVal.substring(roPropPrefix.length()); + mutable = false; break; + } + } + if (name == null) + throw new ObjectNotFoundException("Property "+propName+" does not exist", ""); + Logger.msg(6, "Loaded "+(mutable?"":"Non-")+"Mutable Property: "+name+"="+val); + return new Property(name, val, mutable); + } + +} diff --git a/src/main/java/com/c2kernel/persistency/LDAPClusterStorage.java b/src/main/java/com/c2kernel/persistency/LDAPClusterStorage.java index 2c10bbf..cc65805 100644 --- a/src/main/java/com/c2kernel/persistency/LDAPClusterStorage.java +++ b/src/main/java/com/c2kernel/persistency/LDAPClusterStorage.java @@ -4,9 +4,11 @@ import java.util.StringTokenizer; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.entity.C2KLocalObject; -import com.c2kernel.lookup.ItemPath; import com.c2kernel.lookup.InvalidItemPathException; -import com.c2kernel.lookup.LDAPPropertyManager; +import com.c2kernel.lookup.ItemPath; +import com.c2kernel.lookup.Lookup; +import com.c2kernel.lookup.ldap.LDAPLookup; +import com.c2kernel.lookup.ldap.LDAPPropertyManager; import com.c2kernel.process.Gateway; import com.c2kernel.property.Property; import com.c2kernel.utils.Logger; @@ -16,7 +18,11 @@ public class LDAPClusterStorage extends ClusterStorage { @Override public void open() throws ClusterStorageException { - ldapStore = Gateway.getLDAPLookup().getPropManager(); + Lookup lookup = Gateway.getLookup(); + if (lookup instanceof LDAPLookup) + ldapStore = ((LDAPLookup)lookup).getPropManager(); + else + throw new ClusterStorageException("Cannot use LDAP cluster storage without LDAP Lookup"); } diff --git a/src/main/java/com/c2kernel/persistency/NextKeyManager.java b/src/main/java/com/c2kernel/persistency/NextKeyManager.java new file mode 100644 index 0000000..e0d0013 --- /dev/null +++ b/src/main/java/com/c2kernel/persistency/NextKeyManager.java @@ -0,0 +1,19 @@ +package com.c2kernel.persistency; + +import com.c2kernel.common.ObjectCannotBeUpdated; +import com.c2kernel.common.ObjectNotFoundException; +import com.c2kernel.lookup.AgentPath; +import com.c2kernel.lookup.ItemPath; + +public interface NextKeyManager { + + public ItemPath generateNextEntityKey() + throws ObjectCannotBeUpdated, ObjectNotFoundException; + + public AgentPath generateNextAgentKey() + throws ObjectCannotBeUpdated, ObjectNotFoundException; + + public void writeLastEntityKey(int sysKey) throws ObjectCannotBeUpdated, ObjectNotFoundException; + + public ItemPath getLastEntityPath() throws ObjectNotFoundException; +} diff --git a/src/main/java/com/c2kernel/persistency/ProxyLoader.java b/src/main/java/com/c2kernel/persistency/ProxyLoader.java index 9c14df5..fe48966 100644 --- a/src/main/java/com/c2kernel/persistency/ProxyLoader.java +++ b/src/main/java/com/c2kernel/persistency/ProxyLoader.java @@ -8,7 +8,7 @@ import com.c2kernel.entity.C2KLocalObject; import com.c2kernel.entity.Item; import com.c2kernel.entity.ItemHelper; import com.c2kernel.lookup.ItemPath; -import com.c2kernel.lookup.LDAPLookup; +import com.c2kernel.lookup.Lookup; import com.c2kernel.persistency.outcome.Outcome; import com.c2kernel.process.Gateway; import com.c2kernel.utils.Logger; @@ -19,11 +19,11 @@ import com.c2kernel.utils.Logger; public class ProxyLoader extends ClusterStorage { HashMap entities = new HashMap(); - LDAPLookup lookup; + Lookup lookup; @Override public void open() throws ClusterStorageException { - lookup = Gateway.getLDAPLookup(); + lookup = Gateway.getLookup(); } @Override @@ -113,7 +113,7 @@ public class ProxyLoader extends ClusterStorage { try { Logger.msg(7, "ProxyLoader.getIOR() - Resolving "+sysKey+"."); - org.omg.CORBA.Object ior = lookup.getIOR(new ItemPath(sysKey.intValue())); + org.omg.CORBA.Object ior = lookup.resolve(new ItemPath(sysKey.intValue())); Item thisItem = null; try { diff --git a/src/main/java/com/c2kernel/process/Bootstrap.java b/src/main/java/com/c2kernel/process/Bootstrap.java index f273c5d..bcc5e68 100644 --- a/src/main/java/com/c2kernel/process/Bootstrap.java +++ b/src/main/java/com/c2kernel/process/Bootstrap.java @@ -1,8 +1,8 @@ package com.c2kernel.process; import java.net.InetAddress; -import java.util.Enumeration; import java.util.HashMap; +import java.util.Iterator; import java.util.Set; import java.util.StringTokenizer; @@ -10,6 +10,7 @@ import org.custommonkey.xmlunit.Diff; import org.custommonkey.xmlunit.XMLUnit; import com.c2kernel.common.ObjectNotFoundException; +import com.c2kernel.entity.proxy.AgentProxy; import com.c2kernel.entity.proxy.ItemProxy; import com.c2kernel.events.Event; import com.c2kernel.events.History; @@ -22,7 +23,7 @@ import com.c2kernel.lifecycle.instance.stateMachine.Transition; import com.c2kernel.lookup.AgentPath; import com.c2kernel.lookup.DomainPath; import com.c2kernel.lookup.ItemPath; -import com.c2kernel.lookup.LDAPLookup; +import com.c2kernel.lookup.Lookup; import com.c2kernel.lookup.Path; import com.c2kernel.lookup.RolePath; import com.c2kernel.persistency.ClusterStorage; @@ -47,6 +48,7 @@ public class Bootstrap { static DomainPath thisServerPath; static HashMap resHandlerCache = new HashMap(); + static HashMap systemAgents = new HashMap(); /** * Run everything without timing-out the service wrapper @@ -71,7 +73,7 @@ public class Bootstrap Logger.msg("Bootstrap.run() - Initialising Server Item Workflow"); initServerItemWf(); - // register modules + Gateway.getModuleManager().setUser(systemAgents.get("system")); Gateway.getModuleManager().registerModules(); Logger.msg("Bootstrap.run() - Bootstrapping complete"); @@ -120,13 +122,13 @@ public class Bootstrap // Find or create Item for Resource DomainPath modDomPath = typeImpHandler.getPath(itemName, ns); ItemProxy thisProxy; - Enumeration en = Gateway.getLDAPLookup().search(typeImpHandler.getTypeRoot(), itemName); - if (!en.hasMoreElements()) { + Iterator en = Gateway.getLookup().search(typeImpHandler.getTypeRoot(), itemName); + if (!en.hasNext()) { Logger.msg("Bootstrap.verifyResource() - "+typeImpHandler.getName()+" "+itemName+" not found. Creating new."); thisProxy = createResourceItem(typeImpHandler, itemName, layer, ns); } else { - DomainPath path = (DomainPath)en.nextElement(); + DomainPath path = (DomainPath)en.next(); thisProxy = Gateway.getProxyManager().getProxy(path); // Verify module property and location @@ -160,8 +162,8 @@ public class Bootstrap Logger.msg("Module item "+itemName+" found with path "+path.toString()+". Moving to "+modDomPath.toString()); modDomPath.setEntity(new ItemPath(thisProxy.getSystemKey())); if (!modDomPath.exists()) - Gateway.getLDAPLookup().add(modDomPath); - Gateway.getLDAPLookup().delete(path); + Gateway.getLookup().add(modDomPath); + Gateway.getLookup().delete(path); } } @@ -261,12 +263,12 @@ public class Bootstrap } - ItemPath entityPath = Gateway.getLDAPLookup().getNextKeyManager().generateNextEntityKey(); + ItemPath entityPath = Gateway.getNextKeyManager().generateNextEntityKey(); Gateway.getCorbaServer().createEntity(entityPath); - Gateway.getLDAPLookup().add(entityPath); + Gateway.getLookup().add(entityPath); DomainPath newDomPath = impHandler.getPath(itemName, ns); newDomPath.setEntity(entityPath); - Gateway.getLDAPLookup().add(newDomPath); + Gateway.getLookup().add(newDomPath); ItemProxy newItemProxy = Gateway.getProxyManager().getProxy(entityPath); newItemProxy.initialise( 1, props, ca, null); return newItemProxy; @@ -277,9 +279,9 @@ public class Bootstrap **************************************************************************/ private static void checkAgent(String name, String pass, String role, boolean joblist) throws Exception { Logger.msg(1, "Bootstrap.checkAgent() - Checking for existence of '"+name+"' user."); - LDAPLookup lookup = Gateway.getLDAPLookup(); + Lookup lookup = Gateway.getLookup(); try { - lookup.getRoleManager().getAgentPath(name); + systemAgents.put(name, Gateway.getProxyManager().getAgentProxy(lookup.getAgentPath(name))); Logger.msg(3, "Bootstrap.checkAgent() - User '"+name+"' found."); return; } catch (ObjectNotFoundException ex) { } @@ -287,23 +289,24 @@ public class Bootstrap RolePath rolePath; try { - rolePath = lookup.getRoleManager().getRolePath(role); + rolePath = lookup.getRolePath(role); } catch (ObjectNotFoundException ex) { - rolePath = lookup.getRoleManager().createRole(role, joblist); + rolePath = lookup.createRole(role, joblist); } try { - ItemPath entityPath = lookup.getNextKeyManager().generateNextEntityKey(); + ItemPath entityPath = Gateway.getNextKeyManager().generateNextEntityKey(); AgentPath agentPath = new AgentPath(entityPath.getSysKey(), name); agentPath.setPassword(pass); Gateway.getCorbaServer().createEntity(agentPath); - Gateway.getLDAPLookup().add(agentPath); + Gateway.getLookup().add(agentPath); // assign admin role Logger.msg("Bootstrap.checkAgent() - Assigning role '"+role+"'"); rolePath.addAgent(agentPath); Gateway.getStorage().put(agentPath.getSysKey(), new Property("Name", name, true), null); Gateway.getStorage().put(agentPath.getSysKey(), new Property("Type", "Agent", false), null); + systemAgents.put(name, Gateway.getProxyManager().getAgentProxy(agentPath)); Logger.msg("Bootstrap.checkAgent() - Done"); } catch (Exception ex) { Logger.error("Unable to create "+name+" user."); @@ -335,11 +338,11 @@ public class Bootstrap serverEntity = thisServerPath.getEntity(); } catch (ObjectNotFoundException ex) { Logger.msg("Creating server item "+thisServerPath); - serverEntity = Gateway.getLDAPLookup().getNextKeyManager().generateNextEntityKey(); + serverEntity = Gateway.getNextKeyManager().generateNextEntityKey(); Gateway.getCorbaServer().createEntity(serverEntity); - Gateway.getLDAPLookup().add(serverEntity); + Gateway.getLookup().add(serverEntity); thisServerPath.setEntity(serverEntity); - Gateway.getLDAPLookup().add(thisServerPath); + Gateway.getLookup().add(thisServerPath); } Gateway.getStorage().put(serverEntity.getSysKey(), new Property("Name", serverName, false), null); Gateway.getStorage().put(serverEntity.getSysKey(), new Property("Type", "Server", false), null); @@ -359,7 +362,7 @@ public class Bootstrap PredefinedStepContainer predef = (PredefinedStepContainer)wf.search("workflow/predefined"); wf.getChildGraphModel().removeVertex(predef); wf.addChild(new ServerPredefinedStepContainer(), predef.getCentrePoint()); - wf.initialise(thisServerPath.getSysKey(), Gateway.getLDAPLookup().getRoleManager().getAgentPath("system")); + wf.initialise(thisServerPath.getSysKey(), systemAgents.get("system").getPath()); Gateway.getStorage().put(thisServerPath.getSysKey(), wf, null); } } diff --git a/src/main/java/com/c2kernel/process/ClientShell.java b/src/main/java/com/c2kernel/process/ClientShell.java index 6a620d8..b6afb2c 100644 --- a/src/main/java/com/c2kernel/process/ClientShell.java +++ b/src/main/java/com/c2kernel/process/ClientShell.java @@ -3,7 +3,7 @@ package com.c2kernel.process; import java.util.Scanner; import com.c2kernel.entity.proxy.AgentProxy; -import com.c2kernel.process.auth.Authenticator; +import com.c2kernel.process.auth.ProxyLogin; import com.c2kernel.scripting.Script; public class ClientShell extends StandardClient { @@ -40,7 +40,7 @@ public class ClientShell extends StandardClient { Gateway.init(readC2KArgs(args)); String authClassName = Gateway.getProperties().getProperty("cli.auth"); Class authClass = Gateway.getResource().getClassForName(authClassName); - Authenticator auth = (Authenticator)authClass.newInstance(); + ProxyLogin auth = (ProxyLogin)authClass.newInstance(); AgentProxy user = auth.authenticate(Gateway.getProperties().getProperty("Name")); ClientShell shell = new ClientShell(user); shell.run(); diff --git a/src/main/java/com/c2kernel/process/Gateway.java b/src/main/java/com/c2kernel/process/Gateway.java index 01cc202..836b34b 100644 --- a/src/main/java/com/c2kernel/process/Gateway.java +++ b/src/main/java/com/c2kernel/process/Gateway.java @@ -16,10 +16,11 @@ import com.c2kernel.entity.proxy.AgentProxy; import com.c2kernel.entity.proxy.ProxyManager; import com.c2kernel.entity.proxy.ProxyServer; import com.c2kernel.lookup.AgentPath; -import com.c2kernel.lookup.LDAPLookup; -import com.c2kernel.lookup.LDAPProperties; +import com.c2kernel.lookup.Lookup; import com.c2kernel.persistency.ClusterStorageException; +import com.c2kernel.persistency.NextKeyManager; import com.c2kernel.persistency.TransactionManager; +import com.c2kernel.process.auth.Authenticator; import com.c2kernel.process.module.ModuleManager; import com.c2kernel.process.resource.Resource; import com.c2kernel.process.resource.ResourceLoader; @@ -37,7 +38,7 @@ import com.c2kernel.utils.ObjectProperties; * * Child objects: *
        - *
      • LDAPLookup - Provides access to the CRISTAL directory. Find or + *
      • Lookup - Provides access to the CRISTAL directory. Find or * search for Items or Agents. *
      • EntityProxyManager - Gives a local proxy object for Entities found * in LDAP. Execute activities in Items, query or subscribe to Entity data. @@ -56,13 +57,13 @@ public class Gateway static private ModuleManager mModules; static private org.omg.CORBA.ORB mORB; static private boolean orbDestroyed = false; - static private LDAPLookup mLDAPLookup; + static private Lookup mLookup; + static private NextKeyManager mNextKeyManager; static private TransactionManager mStorage; static private ProxyManager mProxyManager; static private ProxyServer mProxyServer; static private CorbaServer mCorbaServer; static private CastorXMLUtility mMarshaller; - static private AgentProxy mCurrentUser = null; static private ResourceLoader mResource; @@ -71,7 +72,7 @@ public class Gateway /** * Initialises the Gateway and all of the client objects it holds, with - * the exception of the LDAPLookup, which is initialised during connect() + * the exception of the Lookup, which is initialised during connect() * * @param props - java.util.Properties containing all application properties. * If null, the java system properties are used @@ -83,7 +84,7 @@ public class Gateway /** * Initialises the Gateway and all of the client objects it holds, with - * the exception of the LDAPLookup, which is initialised during connect() + * the exception of the Lookup, which is initialised during connect() * * @param props - java.util.Properties containing all application properties. * If null, the java system properties are used @@ -135,9 +136,6 @@ public class Gateway Language.isTranlated=true; Language.mTableOfTranslation = FileStringUtility.loadLanguageFile(languageFile); } - - // if client, run module startup scripts. Otherwise bootstrap will do it after all imports - if (!AbstractMain.runningAsWrapper) mModules.runScripts("startup"); } /** @@ -149,9 +147,12 @@ public class Gateway */ static public void startServer() throws InvalidDataException { try { - // check top level LDAP contexts - mLDAPLookup.install(); + // check top level directory contexts + mLookup.initializeDirectory(); + // init next key manager + mNextKeyManager = (NextKeyManager)mC2KProps.getInstance("NextKeyManager"); + // start entity proxy server mProxyServer = new ProxyServer(mC2KProps.getProperty("ItemServer.name")); @@ -199,140 +200,59 @@ public class Gateway throws InvalidDataException, ClusterStorageException { - LDAPProperties ldapProps = new LDAPProperties(); - - if( ldapProps.mHost != null && ldapProps.mPort != null && - ldapProps.mUser != null && ldapProps.mPassword != null ) - { - try - { - mLDAPLookup = new LDAPLookup(ldapProps); - } - catch (Exception ex) - { - Logger.error(ex); - throw new InvalidDataException("Cannot authenticate. Name and/or password invalid.", ""); - } - } - else - { - Logger.error("LDAP properties not set for server login."); - throw new InvalidDataException("Cannot authenticate with LDAP.", ""); - } - - setup(); - } - - /** - * Authenticates a user and returns and AgentProxy on them without overriding the system LDAP context. - * Useful for handling multiple users in one context e.g. on a web server - * - * @param agentName - username - * @param agentPassword - password - * @return AgentProxy on that user - * @throws InvalidDataException - * @throws ObjectNotFoundException - */ - static public AgentProxy login(String agentName, String agentPassword) throws InvalidDataException, ObjectNotFoundException { - LDAPProperties ldapProps = new LDAPProperties(); - AgentPath agentPath; - try { - agentPath = mLDAPLookup.getRoleManager().getAgentPath(agentName); - } catch (Exception ex) { + try { + Authenticator auth = (Authenticator)mC2KProps.getInstance("Authenticator"); + auth.authenticate("System"); + + mLookup = (Lookup)mC2KProps.getInstance("Lookup"); + mLookup.open(auth); + + mStorage = new TransactionManager(); + mProxyManager = new ProxyManager(); + + } catch (Exception ex) { Logger.error(ex); - throw new ObjectNotFoundException("Could not resolve agent", ""); + throw new InvalidDataException("Cannot connect server process. Please check config.", ""); } - String agentDN = agentPath.getFullDN(); - ldapProps.mUser = agentDN; - ldapProps.mPassword = agentPassword; - try { - LDAPLookup.createConnection(ldapProps); - return (AgentProxy)getProxyManager().getProxy(mLDAPLookup.getRoleManager().getAgentPath(agentName)); - } catch (Exception ex) { - Logger.error(ex); - throw new InvalidDataException("Could not log in", ""); - } - } + } /** - * Logs into the LDAP server with the given username and password, and initialises the lookup. + * Logs in with the given username and password, and initialises the lookup, storage and proxy manager. * * @param agentName - username * @param agentPassword - password * @return an AgentProxy on the requested user * @throws InvalidDataException + * @throws ClusterStorageException + * @throws ClassNotFoundException + * @throws IllegalAccessException + * @throws InstantiationException */ - static public AgentProxy connect(String agentName, String agentPassword) - throws InvalidDataException, ObjectNotFoundException - { - - LDAPProperties ldapProps = new LDAPProperties(); - if (ldapProps.mHost!=null && ldapProps.mPort!= null && ldapProps.mLocalPath!=null ) - { - try { - ldapProps.mUser = ""; - ldapProps.mPassword = ""; - mLDAPLookup = new LDAPLookup(ldapProps); - String agentDN = mLDAPLookup.getRoleManager().getAgentPath(agentName).getFullDN(); - - //found agentDN, try to log in with it - ldapProps.mUser = agentDN; - ldapProps.mPassword = agentPassword; - mLDAPLookup = new LDAPLookup(ldapProps); - - // find agent proxy - AgentPath agentPath = mLDAPLookup.getRoleManager().getAgentPath(agentName); - - if (agentPath!=null) - { - setup(); - mCurrentUser = (AgentProxy) mProxyManager.getProxy(agentPath); - return mCurrentUser; - } - else - { - throw new InvalidDataException("The agentDN " +agentDN+ " is invalid.", ""); - } - } catch (ClusterStorageException e) { - throw new InvalidDataException(Language.translate("Error initialising storage")+Language.translate(". See log."), ""); - } catch (ObjectNotFoundException e) { - throw new ObjectNotFoundException(Language.translate("Invalid username/password"), ""); - } catch (Exception e) { - throw new InvalidDataException(Language.translate("Could not log in")+": "+Language.translate(e.getMessage()), ""); - } - - } - else - { - throw new InvalidDataException("Cannot log in. Some connection properties are not set.", ""); - } - - } - - /** - * @return the mCurrentUser - */ - public static AgentProxy getCurrentUser() { - return mCurrentUser; - } - - /** - * Initializes the storage and proxy manager, called during connect. - * - * @throws InvalidDataException - * @throws ClusterStorageException - */ - static private void setup() - throws InvalidDataException, - ClusterStorageException + static public AgentProxy connect(String agentName, String agentPassword, String resource) + throws InvalidDataException, ObjectNotFoundException, ClusterStorageException, InstantiationException, IllegalAccessException, ClassNotFoundException { + Authenticator auth = (Authenticator)mC2KProps.getInstance("Authenticator"); + if (!auth.authenticate(agentName, agentPassword, resource)) + throw new InvalidDataException("Login failed", ""); + + mLookup = (Lookup)mC2KProps.getInstance("Lookup"); + mLookup.open(auth); - // Init storages mStorage = new TransactionManager(); mProxyManager = new ProxyManager(); + // find agent proxy + AgentPath agentPath = mLookup.getAgentPath(agentName); + AgentProxy userProxy = (AgentProxy) mProxyManager.getProxy(agentPath); + userProxy.setAuthObj(auth); + + // Run module startup scripts. Server does this during bootstrap + mModules.setUser(userProxy); + mModules.runScripts("startup"); + + return userProxy; } /** @@ -354,9 +274,9 @@ public class Gateway mStorage = null; // disconnect from ldap - if (mLDAPLookup != null) - mLDAPLookup.disconnect(); - mLDAPLookup = null; + if (mLookup != null) + mLookup.close(); + mLookup = null; // shut down proxy manager & server if (mProxyServer != null) @@ -384,9 +304,9 @@ public class Gateway return mORB; } - static public LDAPLookup getLDAPLookup() + static public Lookup getLookup() { - return mLDAPLookup; + return mLookup; } static public CorbaServer getCorbaServer() @@ -461,5 +381,9 @@ public class Gateway } } + + public static NextKeyManager getNextKeyManager() { + return mNextKeyManager; + } } diff --git a/src/main/java/com/c2kernel/process/UserCodeProcess.java b/src/main/java/com/c2kernel/process/UserCodeProcess.java index 47742aa..0d35025 100644 --- a/src/main/java/com/c2kernel/process/UserCodeProcess.java +++ b/src/main/java/com/c2kernel/process/UserCodeProcess.java @@ -9,8 +9,8 @@ import com.c2kernel.common.InvalidTransitionException; import com.c2kernel.entity.C2KLocalObject; import com.c2kernel.entity.agent.Job; import com.c2kernel.entity.proxy.AgentProxy; -import com.c2kernel.entity.proxy.ProxyObserver; import com.c2kernel.entity.proxy.MemberSubscription; +import com.c2kernel.entity.proxy.ProxyObserver; import com.c2kernel.persistency.ClusterStorage; import com.c2kernel.scripting.ErrorInfo; import com.c2kernel.scripting.ScriptErrorException; @@ -38,12 +38,12 @@ public class UserCodeProcess extends StandardClient implements ProxyObserver errors = new HashMap(); HashMap jobs; - public UserCodeProcess(String agentName, String agentPass) { + public UserCodeProcess(String agentName, String agentPass, String resource) { // login - try for a while in case server hasn't imported our user yet for (int i=1;i<6;i++) { try { Logger.msg("Login attempt "+i+" of 5"); - agent = Gateway.connect(agentName, agentPass); + agent = Gateway.connect(agentName, agentPass, resource); break; } catch (Exception ex) { Logger.error("Could not log in."); @@ -209,7 +209,7 @@ public class UserCodeProcess extends StandardClient implements ProxyObserver modules = new ArrayList(); HashMap modulesXML = new HashMap(); Properties props = new Properties(); + AgentProxy user; boolean isServer; OutcomeValidator moduleValidator; @@ -110,6 +112,10 @@ public class ModuleManager { if (!allDepsPresent) Logger.die("Unmet module dependencies. Cannot continue"); } + public void setUser(AgentProxy user) { + this.user = user; + } + public String getModuleVersions() { StringBuffer ver = new StringBuffer(); for (Module thisMod : modules) { @@ -127,7 +133,7 @@ public class ModuleManager { public void runScripts(String event) { for (Module thisMod : modules) { try { - thisMod.runScript(event, isServer); + thisMod.runScript(event, user, isServer); } catch (ScriptingEngineException e) { Logger.error(e); Logger.die(e.getMessage()); @@ -152,7 +158,7 @@ public class ModuleManager { try { String nsReset = Gateway.getProperties().getProperty("Module."+thisMod.ns+".reset"); boolean thisReset = nsReset == null?reset:nsReset.equals("true"); - thisMod.importAll(serverEntity, modulesXML.get(thisMod.ns), thisReset); + thisMod.importAll(serverEntity, user, modulesXML.get(thisMod.ns), thisReset); } catch (Exception e) { Logger.error(e); throw new ModuleException("Error importing items for module "+thisMod.getName()); @@ -160,7 +166,7 @@ public class ModuleManager { Logger.msg("Module "+thisMod.getName()+" registered"); try { - thisMod.runScript("startup", true); + thisMod.runScript("startup", user, true); } catch (ScriptingEngineException e) { Logger.error(e); throw new ModuleException("Error in startup script for module "+thisMod.getName()); diff --git a/src/main/java/com/c2kernel/process/module/ModuleScript.java b/src/main/java/com/c2kernel/process/module/ModuleScript.java index beed6f9..f16f390 100644 --- a/src/main/java/com/c2kernel/process/module/ModuleScript.java +++ b/src/main/java/com/c2kernel/process/module/ModuleScript.java @@ -1,7 +1,6 @@ package com.c2kernel.process.module; import com.c2kernel.entity.proxy.AgentProxy; -import com.c2kernel.process.Gateway; import com.c2kernel.scripting.Script; import com.c2kernel.scripting.ScriptingEngineException; @@ -23,16 +22,8 @@ public class ModuleScript { this.script = script; } - public Script getScript(String ns) throws ScriptingEngineException { - AgentProxy user = Gateway.getCurrentUser(); - try { - if (user == null) user = (AgentProxy)Gateway.getProxyManager().getProxy( - Gateway.getLDAPLookup().getRoleManager().getAgentPath("system")); - } catch (Exception ex) { - throw new ScriptingEngineException("System agent unavailable"); - } + public Script getScript(String ns, AgentProxy user) throws ScriptingEngineException { return new Script(lang, ns+" "+target+" "+event, script, user); - } public boolean shouldRun(String event, boolean isServer) { diff --git a/src/main/java/com/c2kernel/scripting/Script.java b/src/main/java/com/c2kernel/scripting/Script.java index 92a49cf..83849d9 100644 --- a/src/main/java/com/c2kernel/scripting/Script.java +++ b/src/main/java/com/c2kernel/scripting/Script.java @@ -151,7 +151,7 @@ public class Script beans.put("storage", Gateway.getStorage()); beans.put("db", Gateway.getStorage().getDb()); beans.put("proxy", Gateway.getProxyManager()); - beans.put("lookup", Gateway.getLDAPLookup()); + beans.put("lookup", Gateway.getLookup()); beans.put("orb", Gateway.getORB()); beans.put("agent", agent); beans.put("output", out); diff --git a/src/main/java/com/c2kernel/scripting/ScriptConsole.java b/src/main/java/com/c2kernel/scripting/ScriptConsole.java index 83e210b..a01e25f 100644 --- a/src/main/java/com/c2kernel/scripting/ScriptConsole.java +++ b/src/main/java/com/c2kernel/scripting/ScriptConsole.java @@ -16,7 +16,6 @@ import javax.script.ScriptEngine; import org.tanukisoftware.wrapper.WrapperManager; -import com.c2kernel.entity.proxy.AgentProxy; import com.c2kernel.process.Gateway; import com.c2kernel.utils.Logger; import com.c2kernel.utils.server.SocketHandler; @@ -138,16 +137,9 @@ public class ScriptConsole implements SocketHandler { // get system objects try { Logger.addLogStream(output, 0); - AgentProxy user = Gateway.getCurrentUser(); - try { - if (user == null) user = (AgentProxy)Gateway.getProxyManager().getProxy( - Gateway.getLDAPLookup().getRoleManager().getAgentPath("system")); - } catch (Exception ex) { - output.println("System agent unavailable"); - } Script context; try { - context = new Script("javascript", user, output); + context = new Script("javascript", null, output); } catch (Exception ex) { output.println("Error initializing console script context"); ex.printStackTrace(output); diff --git a/src/main/java/com/c2kernel/utils/LocalObjectLoader.java b/src/main/java/com/c2kernel/utils/LocalObjectLoader.java index 307cd97..f0d8928 100644 --- a/src/main/java/com/c2kernel/utils/LocalObjectLoader.java +++ b/src/main/java/com/c2kernel/utils/LocalObjectLoader.java @@ -1,6 +1,6 @@ package com.c2kernel.utils; -import java.util.Enumeration; +import java.util.Iterator; import com.c2kernel.common.InvalidDataException; import com.c2kernel.common.ObjectNotFoundException; @@ -23,10 +23,10 @@ public class LocalObjectLoader { throws ObjectNotFoundException { DomainPath defRoot = new DomainPath(root); - Enumeration e = Gateway.getLDAPLookup().search(defRoot, name); + Iterator e = Gateway.getLookup().search(defRoot, name); ItemProxy defProxy = null; int currentLayer = -1; - while (e.hasMoreElements()) { - DomainPath defPath = (DomainPath)e.nextElement(); + while (e.hasNext()) { + DomainPath defPath = (DomainPath)e.next(); ItemProxy thisProxy = Gateway.getProxyManager().getProxy(defPath); int thisLayer; try { -- cgit v1.2.3 From 49fe139f52afcb444478400d10db41263ef1162d Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Thu, 5 Jun 2014 15:28:46 +0200 Subject: Add Authenticator to the open() method params of ClusterStorage. Passed in through the TransactionManager. This allows user-login to storages. Fixes #192 --- src/main/java/com/c2kernel/persistency/ClusterStorage.java | 3 ++- src/main/java/com/c2kernel/persistency/ClusterStorageManager.java | 5 +++-- src/main/java/com/c2kernel/persistency/LDAPClusterStorage.java | 3 ++- src/main/java/com/c2kernel/persistency/MemoryOnlyClusterStorage.java | 3 ++- src/main/java/com/c2kernel/persistency/ProxyLoader.java | 3 ++- src/main/java/com/c2kernel/persistency/TransactionManager.java | 5 +++-- src/main/java/com/c2kernel/persistency/XMLClusterStorage.java | 5 +++-- src/main/java/com/c2kernel/process/Gateway.java | 4 ++-- 8 files changed, 19 insertions(+), 12 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/persistency/ClusterStorage.java b/src/main/java/com/c2kernel/persistency/ClusterStorage.java index 9c18bb4..76aaf1e 100644 --- a/src/main/java/com/c2kernel/persistency/ClusterStorage.java +++ b/src/main/java/com/c2kernel/persistency/ClusterStorage.java @@ -3,6 +3,7 @@ package com.c2kernel.persistency; import com.c2kernel.entity.C2KLocalObject; import com.c2kernel.persistency.outcome.Outcome; import com.c2kernel.persistency.outcome.Viewpoint; +import com.c2kernel.process.auth.Authenticator; import com.c2kernel.utils.Logger; /** Interface for persistency managers of entities. It allows different kernel objects to be stored in different backend. For instance, @@ -85,7 +86,7 @@ public abstract class ClusterStorage { public static final String[] allClusterTypes = { PROPERTY, COLLECTION, LIFECYCLE, OUTCOME, HISTORY, VIEWPOINT, JOB }; // connection maintenance - public abstract void open() + public abstract void open(Authenticator auth) throws ClusterStorageException; public abstract void close() throws ClusterStorageException; diff --git a/src/main/java/com/c2kernel/persistency/ClusterStorageManager.java b/src/main/java/com/c2kernel/persistency/ClusterStorageManager.java index 20857c6..c9ede04 100644 --- a/src/main/java/com/c2kernel/persistency/ClusterStorageManager.java +++ b/src/main/java/com/c2kernel/persistency/ClusterStorageManager.java @@ -15,6 +15,7 @@ import com.c2kernel.events.History; import com.c2kernel.persistency.outcome.Outcome; import com.c2kernel.persistency.outcome.Viewpoint; import com.c2kernel.process.Gateway; +import com.c2kernel.process.auth.Authenticator; import com.c2kernel.utils.Logger; import com.c2kernel.utils.SoftCache; import com.c2kernel.utils.WeakCache; @@ -38,7 +39,7 @@ public class ClusterStorageManager { * Initialises all ClusterStorage handlers listed by class name in the property "ClusterStorages" * This property is usually process specific, and so should be in the server/client.conf and not the connect file. */ - public ClusterStorageManager() throws ClusterStorageException { + public ClusterStorageManager(Authenticator auth) throws ClusterStorageException { Object clusterStorageProp = Gateway.getProperties().getObject("ClusterStorage"); if (clusterStorageProp == null || clusterStorageProp.equals("")) { throw new ClusterStorageException("ClusterStorageManager.init() - no ClusterStorages defined. No persistency!"); @@ -64,7 +65,7 @@ public class ClusterStorageManager { int clusterNo = 0; for (ClusterStorage newStorage : rootStores) { try { - newStorage.open(); + newStorage.open(auth); } catch (ClusterStorageException ex) { Logger.error(ex); throw new ClusterStorageException("ClusterStorageManager.init() - Error initialising storage handler " + newStorage.getClass().getName() + diff --git a/src/main/java/com/c2kernel/persistency/LDAPClusterStorage.java b/src/main/java/com/c2kernel/persistency/LDAPClusterStorage.java index cc65805..4762a33 100644 --- a/src/main/java/com/c2kernel/persistency/LDAPClusterStorage.java +++ b/src/main/java/com/c2kernel/persistency/LDAPClusterStorage.java @@ -10,6 +10,7 @@ import com.c2kernel.lookup.Lookup; import com.c2kernel.lookup.ldap.LDAPLookup; import com.c2kernel.lookup.ldap.LDAPPropertyManager; import com.c2kernel.process.Gateway; +import com.c2kernel.process.auth.Authenticator; import com.c2kernel.property.Property; import com.c2kernel.utils.Logger; @@ -17,7 +18,7 @@ public class LDAPClusterStorage extends ClusterStorage { LDAPPropertyManager ldapStore; @Override - public void open() throws ClusterStorageException { + public void open(Authenticator auth) throws ClusterStorageException { Lookup lookup = Gateway.getLookup(); if (lookup instanceof LDAPLookup) ldapStore = ((LDAPLookup)lookup).getPropManager(); diff --git a/src/main/java/com/c2kernel/persistency/MemoryOnlyClusterStorage.java b/src/main/java/com/c2kernel/persistency/MemoryOnlyClusterStorage.java index 4766d82..cd5d122 100644 --- a/src/main/java/com/c2kernel/persistency/MemoryOnlyClusterStorage.java +++ b/src/main/java/com/c2kernel/persistency/MemoryOnlyClusterStorage.java @@ -6,6 +6,7 @@ import java.util.HashMap; import java.util.Map; import com.c2kernel.entity.C2KLocalObject; +import com.c2kernel.process.auth.Authenticator; import com.c2kernel.utils.Logger; public class MemoryOnlyClusterStorage extends ClusterStorage { @@ -19,7 +20,7 @@ public class MemoryOnlyClusterStorage extends ClusterStorage { } @Override - public void open() throws ClusterStorageException { + public void open(Authenticator auth) throws ClusterStorageException { } diff --git a/src/main/java/com/c2kernel/persistency/ProxyLoader.java b/src/main/java/com/c2kernel/persistency/ProxyLoader.java index fe48966..57b91af 100644 --- a/src/main/java/com/c2kernel/persistency/ProxyLoader.java +++ b/src/main/java/com/c2kernel/persistency/ProxyLoader.java @@ -11,6 +11,7 @@ import com.c2kernel.lookup.ItemPath; import com.c2kernel.lookup.Lookup; import com.c2kernel.persistency.outcome.Outcome; import com.c2kernel.process.Gateway; +import com.c2kernel.process.auth.Authenticator; import com.c2kernel.utils.Logger; /** Used by proxies to load clusters by queryData from the Entity. @@ -22,7 +23,7 @@ public class ProxyLoader extends ClusterStorage { Lookup lookup; @Override - public void open() throws ClusterStorageException { + public void open(Authenticator auth) throws ClusterStorageException { lookup = Gateway.getLookup(); } diff --git a/src/main/java/com/c2kernel/persistency/TransactionManager.java b/src/main/java/com/c2kernel/persistency/TransactionManager.java index d966eec..94b8123 100644 --- a/src/main/java/com/c2kernel/persistency/TransactionManager.java +++ b/src/main/java/com/c2kernel/persistency/TransactionManager.java @@ -7,6 +7,7 @@ import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.entity.C2KLocalObject; import com.c2kernel.entity.agent.JobList; import com.c2kernel.events.History; +import com.c2kernel.process.auth.Authenticator; import com.c2kernel.utils.Logger; public class TransactionManager { @@ -15,8 +16,8 @@ public class TransactionManager { HashMap> pendingTransactions; ClusterStorageManager storage; - public TransactionManager() throws ClusterStorageException { - storage = new ClusterStorageManager(); + public TransactionManager(Authenticator auth) throws ClusterStorageException { + storage = new ClusterStorageManager(auth); locks = new HashMap(); pendingTransactions = new HashMap>(); } diff --git a/src/main/java/com/c2kernel/persistency/XMLClusterStorage.java b/src/main/java/com/c2kernel/persistency/XMLClusterStorage.java index 50c76f0..e6c6e9f 100644 --- a/src/main/java/com/c2kernel/persistency/XMLClusterStorage.java +++ b/src/main/java/com/c2kernel/persistency/XMLClusterStorage.java @@ -3,10 +3,11 @@ import java.io.File; import java.util.ArrayList; import com.c2kernel.entity.C2KLocalObject; -import com.c2kernel.lookup.ItemPath; import com.c2kernel.lookup.InvalidItemPathException; +import com.c2kernel.lookup.ItemPath; import com.c2kernel.persistency.outcome.Outcome; import com.c2kernel.process.Gateway; +import com.c2kernel.process.auth.Authenticator; import com.c2kernel.utils.FileStringUtility; import com.c2kernel.utils.Logger; @@ -17,7 +18,7 @@ public class XMLClusterStorage extends ClusterStorage { } @Override - public void open() throws ClusterStorageException { + public void open(Authenticator auth) throws ClusterStorageException { String rootProp = Gateway.getProperties().getProperty("XMLStorage.root"); if (rootProp == null) throw new ClusterStorageException("XMLClusterStorage.open() - Root path not given in config file."); diff --git a/src/main/java/com/c2kernel/process/Gateway.java b/src/main/java/com/c2kernel/process/Gateway.java index 836b34b..2db7aa1 100644 --- a/src/main/java/com/c2kernel/process/Gateway.java +++ b/src/main/java/com/c2kernel/process/Gateway.java @@ -207,7 +207,7 @@ public class Gateway mLookup = (Lookup)mC2KProps.getInstance("Lookup"); mLookup.open(auth); - mStorage = new TransactionManager(); + mStorage = new TransactionManager(auth); mProxyManager = new ProxyManager(); } catch (Exception ex) { @@ -240,7 +240,7 @@ public class Gateway mLookup = (Lookup)mC2KProps.getInstance("Lookup"); mLookup.open(auth); - mStorage = new TransactionManager(); + mStorage = new TransactionManager(auth); mProxyManager = new ProxyManager(); // find agent proxy -- cgit v1.2.3 From 8dbf947eb6e84ec6a3c6e9ba421c682d847a8b00 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Thu, 5 Jun 2014 16:13:23 +0200 Subject: Make LDAPNextKeyManager independent of the LDAPLookup. The authenticator is the only required common component. --- src/main/java/com/c2kernel/lookup/ldap/LDAPLookup.java | 12 ------------ .../java/com/c2kernel/lookup/ldap/LDAPNextKeyManager.java | 11 ++++++++--- 2 files changed, 8 insertions(+), 15 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/lookup/ldap/LDAPLookup.java b/src/main/java/com/c2kernel/lookup/ldap/LDAPLookup.java index a96a46b..10c1830 100644 --- a/src/main/java/com/c2kernel/lookup/ldap/LDAPLookup.java +++ b/src/main/java/com/c2kernel/lookup/ldap/LDAPLookup.java @@ -55,7 +55,6 @@ public class LDAPLookup implements Lookup { private LDAPAuthManager mLDAPAuth; - private LDAPNextKeyManager mNextKeyManager; private LDAPPropertyManager mPropManager; final String mItemTypeRoot, mDomainTypeRoot, mGlobalPath, mRootPath, mLocalPath, mRolePath; @@ -87,21 +86,10 @@ public class LDAPLookup implements Lookup @Override public void open(Authenticator auth) { mLDAPAuth = (LDAPAuthManager)auth; - mNextKeyManager = new LDAPNextKeyManager(mLDAPAuth, "cn=last,"+mItemTypeRoot); - Gateway.getProperties().setProperty("NextKeyManager", mNextKeyManager); Logger.msg(7, "LDAP.useOldProps="+Gateway.getProperties().getBoolean("LDAP.useOldProps", false)); mPropManager = new LDAPPropertyManager(this, mLDAPAuth); } - /** - * Gets the entity key generator, used to get a unique system key for new entities. - * @return the global NextKeyManager - */ - public LDAPNextKeyManager getNextKeyManager() - { - return mNextKeyManager; - } - /** * Gets the property manager, that is used to read and write cristal properties to the LDAP store. * @return Returns the global LDAPPropertyManager. diff --git a/src/main/java/com/c2kernel/lookup/ldap/LDAPNextKeyManager.java b/src/main/java/com/c2kernel/lookup/ldap/LDAPNextKeyManager.java index 4db8a49..48f938e 100644 --- a/src/main/java/com/c2kernel/lookup/ldap/LDAPNextKeyManager.java +++ b/src/main/java/com/c2kernel/lookup/ldap/LDAPNextKeyManager.java @@ -8,6 +8,7 @@ import com.c2kernel.lookup.ItemPath; import com.c2kernel.persistency.ClusterStorageException; import com.c2kernel.persistency.NextKeyManager; import com.c2kernel.process.Gateway; +import com.c2kernel.process.auth.Authenticator; import com.c2kernel.utils.Logger; import com.novell.ldap.LDAPEntry; @@ -26,10 +27,14 @@ public class LDAPNextKeyManager implements NextKeyManager { LDAPAuthManager ldap; String lastKeyPath; - public LDAPNextKeyManager(LDAPAuthManager ldap, String lastKeyPath) { + public LDAPNextKeyManager() { super(); - this.ldap = ldap; - this.lastKeyPath = lastKeyPath; + LDAPProperties props = new LDAPProperties(Gateway.getProperties()); + this.lastKeyPath = "cn=last,cn=entity,"+props.mLocalPath; + } + + public void open(Authenticator auth) { + this.ldap = (LDAPAuthManager)auth; } @Override -- cgit v1.2.3 From e73468fd08cc27aa31f76a27c916e45d5987c628 Mon Sep 17 00:00:00 2001 From: Andrew Branson Date: Thu, 5 Jun 2014 16:47:41 +0200 Subject: Moved old entitycreation package from the predefined step package to a new 'imports' package under entity. Renamed most classed with an 'Import' prefix to avoid clashes with other API classes. Fixes #194 --- .../java/com/c2kernel/entity/imports/Geometry.java | 29 ++++ .../com/c2kernel/entity/imports/ImportAgent.java | 60 +++++++ .../c2kernel/entity/imports/ImportAggregation.java | 51 ++++++ .../entity/imports/ImportAggregationMember.java | 33 ++++ .../c2kernel/entity/imports/ImportDependency.java | 66 ++++++++ .../entity/imports/ImportDependencyMember.java | 29 ++++ .../com/c2kernel/entity/imports/ImportItem.java | 187 +++++++++++++++++++++ .../com/c2kernel/entity/imports/ImportOutcome.java | 27 +++ .../com/c2kernel/entity/imports/ImportRole.java | 19 +++ .../predefined/ServerPredefinedStepContainer.java | 4 +- .../predefined/entitycreation/Aggregation.java | 51 ------ .../entitycreation/AggregationMember.java | 33 ---- .../predefined/entitycreation/CreateNewAgent.java | 42 ----- .../predefined/entitycreation/CreateNewItem.java | 41 ----- .../predefined/entitycreation/Dependency.java | 66 -------- .../entitycreation/DependencyMember.java | 29 ---- .../predefined/entitycreation/Geometry.java | 29 ---- .../predefined/entitycreation/NewAgent.java | 60 ------- .../predefined/entitycreation/NewItem.java | 187 --------------------- .../predefined/entitycreation/NewRole.java | 19 --- .../predefined/entitycreation/Outcome.java | 27 --- .../instance/predefined/server/CreateNewAgent.java | 43 +++++ .../instance/predefined/server/CreateNewItem.java | 42 +++++ .../java/com/c2kernel/process/module/Module.java | 28 +-- .../com/c2kernel/process/module/ModuleImports.java | 30 ++-- src/main/resources/mapFiles/NewEntityMap.xml | 30 ++-- 26 files changed, 632 insertions(+), 630 deletions(-) create mode 100644 src/main/java/com/c2kernel/entity/imports/Geometry.java create mode 100644 src/main/java/com/c2kernel/entity/imports/ImportAgent.java create mode 100644 src/main/java/com/c2kernel/entity/imports/ImportAggregation.java create mode 100644 src/main/java/com/c2kernel/entity/imports/ImportAggregationMember.java create mode 100644 src/main/java/com/c2kernel/entity/imports/ImportDependency.java create mode 100644 src/main/java/com/c2kernel/entity/imports/ImportDependencyMember.java create mode 100644 src/main/java/com/c2kernel/entity/imports/ImportItem.java create mode 100644 src/main/java/com/c2kernel/entity/imports/ImportOutcome.java create mode 100644 src/main/java/com/c2kernel/entity/imports/ImportRole.java delete mode 100644 src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/Aggregation.java delete mode 100644 src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/AggregationMember.java delete mode 100644 src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewAgent.java delete mode 100644 src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewItem.java delete mode 100644 src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/Dependency.java delete mode 100644 src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/DependencyMember.java delete mode 100644 src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/Geometry.java delete mode 100644 src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewAgent.java delete mode 100644 src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java delete mode 100644 src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewRole.java delete mode 100644 src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/Outcome.java create mode 100644 src/main/java/com/c2kernel/lifecycle/instance/predefined/server/CreateNewAgent.java create mode 100644 src/main/java/com/c2kernel/lifecycle/instance/predefined/server/CreateNewItem.java (limited to 'src/main/java') diff --git a/src/main/java/com/c2kernel/entity/imports/Geometry.java b/src/main/java/com/c2kernel/entity/imports/Geometry.java new file mode 100644 index 0000000..cb973d3 --- /dev/null +++ b/src/main/java/com/c2kernel/entity/imports/Geometry.java @@ -0,0 +1,29 @@ + + +package com.c2kernel.entity.imports; + + + +public class Geometry implements java.io.Serializable { + + + public int x; + + public int y; + + public int width; + + public int height; + + public Geometry() { + super(); + } + + public Geometry(int x, int y, int width, int height) { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + } + +} diff --git a/src/main/java/com/c2kernel/entity/imports/ImportAgent.java b/src/main/java/com/c2kernel/entity/imports/ImportAgent.java new file mode 100644 index 0000000..26e3325 --- /dev/null +++ b/src/main/java/com/c2kernel/entity/imports/ImportAgent.java @@ -0,0 +1,60 @@ +package com.c2kernel.entity.imports; + +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; + +import com.c2kernel.common.CannotManageException; +import com.c2kernel.common.ObjectAlreadyExistsException; +import com.c2kernel.common.ObjectCannotBeUpdated; +import com.c2kernel.common.ObjectNotFoundException; +import com.c2kernel.entity.agent.ActiveEntity; +import com.c2kernel.lookup.AgentPath; +import com.c2kernel.lookup.RolePath; +import com.c2kernel.process.Gateway; +import com.c2kernel.process.module.ModuleImport; +import com.c2kernel.property.Property; +import com.c2kernel.property.PropertyArrayList; +import com.c2kernel.utils.Logger; + +public class ImportAgent extends ModuleImport implements java.io.Serializable { + + public String password; + + public ArrayList roles = new ArrayList(); + public ArrayList properties = new ArrayList(); + + public ImportAgent() { + } + + public ImportAgent(String name, String password) { + this.name = name; + this.password = password; + } + + public void create(int agentId) throws ObjectNotFoundException, ObjectCannotBeUpdated, NoSuchAlgorithmException, CannotManageException, ObjectAlreadyExistsException { + AgentPath newAgent = Gateway.getNextKeyManager().generateNextAgentKey(); + newAgent.setAgentName(name); + newAgent.setPassword(password); + ActiveEntity newAgentEnt = (ActiveEntity)Gateway.getCorbaServer().createEntity(newAgent); + Gateway.getLookup().add(newAgent); + // assemble properties + properties.add(new com.c2kernel.property.Property("Name", name, true)); + properties.add(new com.c2kernel.property.Property("Type", "Agent", false)); + try { + newAgentEnt.initialise(agentId, Gateway.getMarshaller().marshall(new PropertyArrayList(properties)), null, null); + } catch (Exception ex) { + Logger.error(ex); + throw new CannotManageException("Error initialising new agent"); + } + for (String role : roles) { + RolePath thisRole; + try { + thisRole = Gateway.getLookup().getRolePath(role); + } catch (ObjectNotFoundException ex) { + throw new ObjectNotFoundException("Role "+role+" does not exist."); + } + thisRole.addAgent(newAgent); + } + + } +} diff --git a/src/main/java/com/c2kernel/entity/imports/ImportAggregation.java b/src/main/java/com/c2kernel/entity/imports/ImportAggregation.java new file mode 100644 index 0000000..1c75990 --- /dev/null +++ b/src/main/java/com/c2kernel/entity/imports/ImportAggregation.java @@ -0,0 +1,51 @@ +package com.c2kernel.entity.imports; + +import java.util.ArrayList; + +import com.c2kernel.collection.MembershipException; +import com.c2kernel.common.ObjectNotFoundException; +import com.c2kernel.graph.model.GraphPoint; +import com.c2kernel.lookup.DomainPath; +import com.c2kernel.property.PropertyDescription; +import com.c2kernel.property.PropertyDescriptionList; +import com.c2kernel.property.PropertyUtility; + +public class ImportAggregation implements java.io.Serializable { + + public boolean isDescription; + public ArrayList aggregationMemberList = new ArrayList(); + public String name; + + public ImportAggregation() { + super(); + } + + public ImportAggregation(String name, boolean isDescription) { + this(); + this.name = name; + this.isDescription = isDescription; + } + + public com.c2kernel.collection.Aggregation create() throws MembershipException, ObjectNotFoundException { + com.c2kernel.collection.Aggregation newAgg = isDescription?new com.c2kernel.collection.AggregationDescription(name):new com.c2kernel.collection.AggregationInstance(name); + newAgg.setName(name); + for (ImportAggregationMember thisMem : aggregationMemberList) { + StringBuffer classProps = new StringBuffer(); + if (thisMem.itemDescriptionPath != null && thisMem.itemDescriptionPath.length()>0) { + PropertyDescriptionList propList = PropertyUtility.getPropertyDescriptionOutcome(new DomainPath(thisMem.itemDescriptionPath).getSysKey()); + for (PropertyDescription pd : propList.list) { + thisMem.props.put(pd.getName(), pd.getDefaultValue()); + if (pd.getIsClassIdentifier()) + classProps.append((classProps.length()>0?",":"")).append(pd.getName()); + } + } + if (thisMem.itemPath != null && thisMem.itemPath.length()>0) { + int syskey = new DomainPath(thisMem.itemPath).getSysKey(); + if (syskey == -1) + throw new MembershipException("Cannot find "+thisMem.itemPath+" specified for collection."); + newAgg.addMember(syskey, thisMem.props, classProps.toString(), new GraphPoint(thisMem.geometry.x, thisMem.geometry.y), thisMem.geometry.width, thisMem.geometry.height); + } + } + return newAgg; + } +} diff --git a/src/main/java/com/c2kernel/entity/imports/ImportAggregationMember.java b/src/main/java/com/c2kernel/entity/imports/ImportAggregationMember.java new file mode 100644 index 0000000..7a1cf21 --- /dev/null +++ b/src/main/java/com/c2kernel/entity/imports/ImportAggregationMember.java @@ -0,0 +1,33 @@ +package com.c2kernel.entity.imports; + +import com.c2kernel.utils.CastorHashMap; +import com.c2kernel.utils.KeyValuePair; + +public class ImportAggregationMember implements java.io.Serializable { + + public int slotNo; + public String itemDescriptionPath; + public String itemPath; + public Geometry geometry; + public CastorHashMap props = new CastorHashMap(); + + + public ImportAggregationMember() { + super(); + } + + public ImportAggregationMember(int slotNo, String itemDescPath, String itemPath, Geometry geometry) { + this.slotNo = slotNo; + this.itemDescriptionPath = itemDescPath; + this.itemPath = itemPath; + this.geometry = geometry; + } + + public KeyValuePair[] getKeyValuePairs() { + return props.getKeyValuePairs(); + } + + public void setKeyValuePairs(KeyValuePair[] pairs) { + props.setKeyValuePairs(pairs); + } +} diff --git a/src/main/java/com/c2kernel/entity/imports/ImportDependency.java b/src/main/java/com/c2kernel/entity/imports/ImportDependency.java new file mode 100644 index 0000000..e6ce909 --- /dev/null +++ b/src/main/java/com/c2kernel/entity/imports/ImportDependency.java @@ -0,0 +1,66 @@ +package com.c2kernel.entity.imports; + +import java.util.ArrayList; + +import com.c2kernel.collection.MembershipException; +import com.c2kernel.common.ObjectNotFoundException; +import com.c2kernel.lookup.DomainPath; +import com.c2kernel.property.PropertyDescription; +import com.c2kernel.property.PropertyDescriptionList; +import com.c2kernel.property.PropertyUtility; +import com.c2kernel.utils.CastorHashMap; +import com.c2kernel.utils.KeyValuePair; + +public class ImportDependency implements java.io.Serializable { + + public String name; + public boolean isDescription; + public String itemDescriptionPath; + public ArrayList dependencyMemberList = new ArrayList(); + public CastorHashMap props = new CastorHashMap(); + + public ImportDependency() { + super(); + } + + public ImportDependency(String name) { + this(); + this.name = name; + } + + public KeyValuePair[] getKeyValuePairs() { + return props.getKeyValuePairs(); + } + + public void setKeyValuePairs(KeyValuePair[] pairs) { + props.setKeyValuePairs(pairs); + } + + /** + * @return + */ + public com.c2kernel.collection.Dependency create() throws MembershipException, ObjectNotFoundException { + com.c2kernel.collection.Dependency newDep = isDescription?new com.c2kernel.collection.DependencyDescription(name):new com.c2kernel.collection.Dependency(name); + if (itemDescriptionPath != null && itemDescriptionPath.length()>0) { + PropertyDescriptionList propList = PropertyUtility.getPropertyDescriptionOutcome(new DomainPath(itemDescriptionPath).getSysKey()); + StringBuffer classProps = new StringBuffer(); + for (PropertyDescription pd : propList.list) { + props.put(pd.getName(), pd.getDefaultValue()); + if (pd.getIsClassIdentifier()) + classProps.append((classProps.length()>0?",":"")).append(pd.getName()); + } + newDep.setProperties(props); + newDep.setClassProps(classProps.toString()); + } + + for (ImportDependencyMember thisMem : dependencyMemberList) { + int syskey = new DomainPath(thisMem.itemPath).getSysKey(); + if (syskey == -1) + throw new MembershipException("Cannot find "+thisMem.itemPath+" specified for collection."); + com.c2kernel.collection.DependencyMember newDepMem = newDep.addMember(syskey); + newDepMem.getProperties().putAll(thisMem.props); + } + return newDep; + } + +} diff --git a/src/main/java/com/c2kernel/entity/imports/ImportDependencyMember.java b/src/main/java/com/c2kernel/entity/imports/ImportDependencyMember.java new file mode 100644 index 0000000..6fc6b5a --- /dev/null +++ b/src/main/java/com/c2kernel/entity/imports/ImportDependencyMember.java @@ -0,0 +1,29 @@ + +package com.c2kernel.entity.imports; + +import com.c2kernel.utils.CastorHashMap; +import com.c2kernel.utils.KeyValuePair; + +public class ImportDependencyMember implements java.io.Serializable { + + + public String itemPath; + public CastorHashMap props = new CastorHashMap(); + + public ImportDependencyMember() { + super(); + } + + public ImportDependencyMember(String itemPath) { + this.itemPath = itemPath; + + } + + public KeyValuePair[] getKeyValuePairs() { + return props.getKeyValuePairs(); + } + + public void setKeyValuePairs(KeyValuePair[] pairs) { + props.setKeyValuePairs(pairs); + } +} diff --git a/src/main/java/com/c2kernel/entity/imports/ImportItem.java b/src/main/java/com/c2kernel/entity/imports/ImportItem.java new file mode 100644 index 0000000..a27d88d --- /dev/null +++ b/src/main/java/com/c2kernel/entity/imports/ImportItem.java @@ -0,0 +1,187 @@ +package com.c2kernel.entity.imports; + + +import java.util.ArrayList; + +import org.custommonkey.xmlunit.Diff; +import org.custommonkey.xmlunit.XMLUnit; + +import com.c2kernel.collection.CollectionArrayList; +import com.c2kernel.collection.MembershipException; +import com.c2kernel.common.CannotManageException; +import com.c2kernel.common.InvalidDataException; +import com.c2kernel.common.ObjectAlreadyExistsException; +import com.c2kernel.common.ObjectCannotBeUpdated; +import com.c2kernel.common.ObjectNotFoundException; +import com.c2kernel.entity.TraceableEntity; +import com.c2kernel.events.Event; +import com.c2kernel.events.History; +import com.c2kernel.lifecycle.CompositeActivityDef; +import com.c2kernel.lifecycle.instance.stateMachine.Transition; +import com.c2kernel.lookup.DomainPath; +import com.c2kernel.lookup.ItemPath; +import com.c2kernel.persistency.ClusterStorage; +import com.c2kernel.persistency.ClusterStorageException; +import com.c2kernel.persistency.outcome.Viewpoint; +import com.c2kernel.process.Gateway; +import com.c2kernel.process.module.ModuleImport; +import com.c2kernel.property.Property; +import com.c2kernel.property.PropertyArrayList; +import com.c2kernel.utils.LocalObjectLoader; +import com.c2kernel.utils.Logger; + +/** + * Complete Structure for new item + * + * @version $Revision: 1.8 $ $Date: 2006/03/03 13:52:21 $ + */ + +public class ImportItem extends ModuleImport { + + public String initialPath; + public String workflow; + public Integer workflowVer; + public ArrayList properties = new ArrayList(); + public ArrayList aggregationList = new ArrayList(); + public ArrayList dependencyList = new ArrayList(); + public ArrayList outcomes = new ArrayList(); + private String ns; + + public ImportItem() { + } + + public ImportItem(String name, String initialPath, String wf, int wfVer) { + this(); + this.name = name; + this.initialPath = initialPath; + this.workflow = wf; + this.workflowVer = wfVer; + } + + public void setNamespace(String ns) { + this.ns = ns; + if (initialPath == null) initialPath = "/desc/"+ns; + } + + public String getNamespace() { + return ns; + } + + public void create(int agentId, boolean reset) throws ObjectCannotBeUpdated, ObjectNotFoundException, CannotManageException, ObjectAlreadyExistsException { + DomainPath domPath = new DomainPath(new DomainPath(initialPath), name); + + ItemPath entPath; TraceableEntity newItem; + if (domPath.exists()) { + entPath = domPath.getEntity(); + newItem = Gateway.getCorbaServer().getItem(entPath.getSysKey()); + } + else { + // create item + entPath = Gateway.getNextKeyManager().generateNextEntityKey(); + newItem = (TraceableEntity)Gateway.getCorbaServer().createEntity(entPath); + Gateway.getLookup().add(entPath); + } + + // set the name property + properties.add(new Property("Name", name, true)); + + // find workflow def + CompositeActivityDef compact; + // default workflow version is 0 if not given + int usedWfVer; + if (workflowVer == null) usedWfVer = 0; + else usedWfVer = workflowVer.intValue(); + try { + compact = (CompositeActivityDef)LocalObjectLoader.getActDef(workflow, usedWfVer); + } catch (ObjectNotFoundException ex) { + throw new CannotManageException("Could not find workflow "+workflow+"v"+usedWfVer+" for item "+domPath, ""); + } catch (InvalidDataException e) { + throw new CannotManageException("Workflow def "+workflow+" v"+usedWfVer+" for item "+domPath+" was not valid", ""); + } + + // create collections + CollectionArrayList colls = new CollectionArrayList(); + for (ImportDependency element: dependencyList) { + try { + com.c2kernel.collection.Dependency newDep = element.create(); + colls.put(newDep); + } catch (MembershipException ex) { + Logger.error(ex); + throw new CannotManageException("A specified member is not of the correct type in "+element.name, ""); + } + } + + for (ImportAggregation element : aggregationList) { + try { + com.c2kernel.collection.Aggregation newAgg = element.create(); + colls.put(newAgg); + } catch (MembershipException ex) { + Logger.error(ex); + throw new CannotManageException("A specified member is not of the correct type in "+element.name, ""); + } + } + + // (re)initialise the new item with properties, workflow and collections + try { + newItem.initialise( + agentId, + Gateway.getMarshaller().marshall(new PropertyArrayList(properties)), + Gateway.getMarshaller().marshall(compact.instantiate()), + Gateway.getMarshaller().marshall(colls)); + } catch (Exception ex) { + Logger.error("Error initialising new item "+name ); + Logger.error(ex); + throw new CannotManageException("Problem initialising new item. See server log.", ""); + } + + // import outcomes + XMLUnit.setIgnoreWhitespace(true); + XMLUnit.setIgnoreComments(true); + History hist = new History(entPath.getSysKey(), null); + for (ImportOutcome thisOutcome : outcomes) { + com.c2kernel.persistency.outcome.Outcome newOutcome = new com.c2kernel.persistency.outcome.Outcome(-1, thisOutcome.getData(ns), thisOutcome.schema, thisOutcome.version); + Viewpoint impView; + try { + impView = (Viewpoint)Gateway.getStorage().get(entPath.getSysKey(), ClusterStorage.VIEWPOINT+"/"+thisOutcome.schema+"/"+thisOutcome.viewname, null); + + Diff xmlDiff = new Diff(newOutcome.getDOM(), impView.getOutcome().getDOM()); + if (xmlDiff.identical()) { + Logger.msg(5, "NewItem.create() - View "+thisOutcome.schema+"/"+thisOutcome.viewname+" in "+name+" identical, no update required"); + continue; + } + else { + Logger.msg("NewItem.create() - Difference found in view "+thisOutcome.schema+"/"+thisOutcome.viewname+" in "+name+": "+xmlDiff.toString()); + if (!reset && !impView.getEvent().getStepPath().equals("Import")) { + Logger.msg("Last edit was not done by import, and reset not requested. Not overwriting."); + continue; + } + } + } catch (ObjectNotFoundException ex) { + Logger.msg(3, "View "+thisOutcome.schema+"/"+thisOutcome.viewname+" not found in "+name+". Creating."); + impView = new Viewpoint(entPath.getSysKey(), thisOutcome.schema, thisOutcome.viewname, thisOutcome.version, -1); + } catch (ClusterStorageException e) { + throw new ObjectCannotBeUpdated("Could not check data for view "+thisOutcome.schema+"/"+thisOutcome.viewname+" in "+name); + } catch (InvalidDataException e) { + throw new ObjectCannotBeUpdated("Could not check previous event for view "+thisOutcome.schema+"/"+thisOutcome.viewname+" in "+name); + } + + // write new view/outcome/event + Transition predefDone = new Transition(0, "Done", 0, 0); + Event newEvent = hist.addEvent("system", "Admin", "Import", "Import", "Import", thisOutcome.schema, thisOutcome.version, "PredefinedStep", 0, predefDone, thisOutcome.viewname); + newOutcome.setID(newEvent.getID()); + impView.setEventId(newEvent.getID()); + try { + Gateway.getStorage().put(entPath.getSysKey(), newOutcome, null); + Gateway.getStorage().put(entPath.getSysKey(), impView, null); + } catch (ClusterStorageException e) { + throw new ObjectCannotBeUpdated("Could not store data for view "+thisOutcome.schema+"/"+thisOutcome.viewname+" in "+name); + } + } + + // register domain path (before collections in case of recursive collections) + if (!domPath.exists()) { + domPath.setEntity(entPath); + Gateway.getLookup().add(domPath); + } + } +} diff --git a/src/main/java/com/c2kernel/entity/imports/ImportOutcome.java b/src/main/java/com/c2kernel/entity/imports/ImportOutcome.java new file mode 100644 index 0000000..1428483 --- /dev/null +++ b/src/main/java/com/c2kernel/entity/imports/ImportOutcome.java @@ -0,0 +1,27 @@ +package com.c2kernel.entity.imports; + +import com.c2kernel.common.ObjectNotFoundException; +import com.c2kernel.process.Gateway; + +public class ImportOutcome { + public String schema, viewname, path, data; + public int version; + + public ImportOutcome() { + } + + public ImportOutcome(String schema, int version, String viewname, String path) { + super(); + this.schema = schema; + this.version = version; + this.viewname = viewname; + this.path = path; + } + + public String getData(String ns) throws ObjectNotFoundException { + if (data == null) + data = Gateway.getResource().getTextResource(ns, path); + return data; + } + +} diff --git a/src/main/java/com/c2kernel/entity/imports/ImportRole.java b/src/main/java/com/c2kernel/entity/imports/ImportRole.java new file mode 100644 index 0000000..8313c24 --- /dev/null +++ b/src/main/java/com/c2kernel/entity/imports/ImportRole.java @@ -0,0 +1,19 @@ +package com.c2kernel.entity.imports; + +import com.c2kernel.common.ObjectAlreadyExistsException; +import com.c2kernel.common.ObjectCannotBeUpdated; +import com.c2kernel.process.Gateway; +import com.c2kernel.process.module.ModuleImport; + +public class ImportRole extends ModuleImport { + + public boolean jobList; + + public ImportRole() { + } + + public void create(int agentId) throws ObjectAlreadyExistsException, ObjectCannotBeUpdated { + Gateway.getLookup().createRole(name, jobList); + } + +} diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/ServerPredefinedStepContainer.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/ServerPredefinedStepContainer.java index 667ae5d..32cf7b2 100644 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/ServerPredefinedStepContainer.java +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/ServerPredefinedStepContainer.java @@ -1,9 +1,9 @@ package com.c2kernel.lifecycle.instance.predefined; import com.c2kernel.graph.model.GraphPoint; -import com.c2kernel.lifecycle.instance.predefined.entitycreation.CreateNewAgent; -import com.c2kernel.lifecycle.instance.predefined.entitycreation.CreateNewItem; import com.c2kernel.lifecycle.instance.predefined.server.AddDomainContext; +import com.c2kernel.lifecycle.instance.predefined.server.CreateNewAgent; +import com.c2kernel.lifecycle.instance.predefined.server.CreateNewItem; import com.c2kernel.lifecycle.instance.predefined.server.RemoveAgent; import com.c2kernel.lifecycle.instance.predefined.server.RemoveDomainContext; import com.c2kernel.lifecycle.instance.predefined.server.SetAgentPassword; diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/Aggregation.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/Aggregation.java deleted file mode 100644 index 40e0604..0000000 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/Aggregation.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.c2kernel.lifecycle.instance.predefined.entitycreation; - -import java.util.ArrayList; - -import com.c2kernel.collection.MembershipException; -import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.graph.model.GraphPoint; -import com.c2kernel.lookup.DomainPath; -import com.c2kernel.property.PropertyDescription; -import com.c2kernel.property.PropertyDescriptionList; -import com.c2kernel.property.PropertyUtility; - -public class Aggregation implements java.io.Serializable { - - public boolean isDescription; - public ArrayList aggregationMemberList = new ArrayList(); - public String name; - - public Aggregation() { - super(); - } - - public Aggregation(String name, boolean isDescription) { - this(); - this.name = name; - this.isDescription = isDescription; - } - - public com.c2kernel.collection.Aggregation create() throws MembershipException, ObjectNotFoundException { - com.c2kernel.collection.Aggregation newAgg = isDescription?new com.c2kernel.collection.AggregationDescription(name):new com.c2kernel.collection.AggregationInstance(name); - newAgg.setName(name); - for (AggregationMember thisMem : aggregationMemberList) { - StringBuffer classProps = new StringBuffer(); - if (thisMem.itemDescriptionPath != null && thisMem.itemDescriptionPath.length()>0) { - PropertyDescriptionList propList = PropertyUtility.getPropertyDescriptionOutcome(new DomainPath(thisMem.itemDescriptionPath).getSysKey()); - for (PropertyDescription pd : propList.list) { - thisMem.props.put(pd.getName(), pd.getDefaultValue()); - if (pd.getIsClassIdentifier()) - classProps.append((classProps.length()>0?",":"")).append(pd.getName()); - } - } - if (thisMem.itemPath != null && thisMem.itemPath.length()>0) { - int syskey = new DomainPath(thisMem.itemPath).getSysKey(); - if (syskey == -1) - throw new MembershipException("Cannot find "+thisMem.itemPath+" specified for collection."); - newAgg.addMember(syskey, thisMem.props, classProps.toString(), new GraphPoint(thisMem.geometry.x, thisMem.geometry.y), thisMem.geometry.width, thisMem.geometry.height); - } - } - return newAgg; - } -} diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/AggregationMember.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/AggregationMember.java deleted file mode 100644 index 82c0437..0000000 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/AggregationMember.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.c2kernel.lifecycle.instance.predefined.entitycreation; - -import com.c2kernel.utils.CastorHashMap; -import com.c2kernel.utils.KeyValuePair; - -public class AggregationMember implements java.io.Serializable { - - public int slotNo; - public String itemDescriptionPath; - public String itemPath; - public Geometry geometry; - public CastorHashMap props = new CastorHashMap(); - - - public AggregationMember() { - super(); - } - - public AggregationMember(int slotNo, String itemDescPath, String itemPath, Geometry geometry) { - this.slotNo = slotNo; - this.itemDescriptionPath = itemDescPath; - this.itemPath = itemPath; - this.geometry = geometry; - } - - public KeyValuePair[] getKeyValuePairs() { - return props.getKeyValuePairs(); - } - - public void setKeyValuePairs(KeyValuePair[] pairs) { - props.setKeyValuePairs(pairs); - } -} diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewAgent.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewAgent.java deleted file mode 100644 index 7715e2a..0000000 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewAgent.java +++ /dev/null @@ -1,42 +0,0 @@ -/************************************************************************** - * CreateNewAgent.java - * - * Copyright (C) 2001 CERN - European Organization for Nuclear Research - * All rights reserved. - **************************************************************************/ - -package com.c2kernel.lifecycle.instance.predefined.entitycreation; - -import com.c2kernel.common.InvalidDataException; -import com.c2kernel.lifecycle.instance.predefined.PredefinedStep; -import com.c2kernel.lookup.AgentPath; -import com.c2kernel.process.Gateway; -import com.c2kernel.utils.Logger; - -public class CreateNewAgent extends PredefinedStep -{ - public CreateNewAgent() - { - super(); - getProperties().put("SchemaType", "Agent"); - } - - //requestdata is xmlstring - @Override - protected String runActivityLogic(AgentPath agent, int itemSysKey, - int transitionID, String requestData) throws InvalidDataException { - - String redactedRequestData; - try { - NewAgent newAgent = (NewAgent)Gateway.getMarshaller().unmarshall(requestData); - newAgent.create(agent.getSysKey()); - newAgent.password = "REDACTED"; - redactedRequestData = Gateway.getMarshaller().marshall(newAgent); - return redactedRequestData; - } catch (Exception ex) { - Logger.error(ex); - throw new InvalidDataException("Error creating agent", ""); - } - - } -} diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewItem.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewItem.java deleted file mode 100644 index bddb39f..0000000 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewItem.java +++ /dev/null @@ -1,41 +0,0 @@ -/************************************************************************** - * CreateNewItem - * - * Copyright (C) 2005 CERN - European Organization for Nuclear Research - * All rights reserved. - **************************************************************************/ - -package com.c2kernel.lifecycle.instance.predefined.entitycreation; - - - - -import com.c2kernel.common.InvalidDataException; -import com.c2kernel.lifecycle.instance.predefined.PredefinedStep; -import com.c2kernel.lookup.AgentPath; -import com.c2kernel.process.Gateway; -import com.c2kernel.utils.Logger; - -public class CreateNewItem extends PredefinedStep -{ - public CreateNewItem() - { - super(); - getProperties().put("SchemaType", "Item"); - } - - //requestdata is xmlstring - @Override - protected String runActivityLogic(AgentPath agent, int itemSysKey, - int transitionID, String requestData) throws InvalidDataException { - - try { - NewItem item = (NewItem)Gateway.getMarshaller().unmarshall(requestData); - item.create(agent.getSysKey(), false); - return requestData; - } catch (Exception ex) { - Logger.error(ex); - throw new InvalidDataException("Error creating item", ""); - } - } -} diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/Dependency.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/Dependency.java deleted file mode 100644 index b3be9d1..0000000 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/Dependency.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.c2kernel.lifecycle.instance.predefined.entitycreation; - -import java.util.ArrayList; - -import com.c2kernel.collection.MembershipException; -import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.lookup.DomainPath; -import com.c2kernel.property.PropertyDescription; -import com.c2kernel.property.PropertyDescriptionList; -import com.c2kernel.property.PropertyUtility; -import com.c2kernel.utils.CastorHashMap; -import com.c2kernel.utils.KeyValuePair; - -public class Dependency implements java.io.Serializable { - - public String name; - public boolean isDescription; - public String itemDescriptionPath; - public ArrayList dependencyMemberList = new ArrayList(); - public CastorHashMap props = new CastorHashMap(); - - public Dependency() { - super(); - } - - public Dependency(String name) { - this(); - this.name = name; - } - - public KeyValuePair[] getKeyValuePairs() { - return props.getKeyValuePairs(); - } - - public void setKeyValuePairs(KeyValuePair[] pairs) { - props.setKeyValuePairs(pairs); - } - - /** - * @return - */ - public com.c2kernel.collection.Dependency create() throws MembershipException, ObjectNotFoundException { - com.c2kernel.collection.Dependency newDep = isDescription?new com.c2kernel.collection.DependencyDescription(name):new com.c2kernel.collection.Dependency(name); - if (itemDescriptionPath != null && itemDescriptionPath.length()>0) { - PropertyDescriptionList propList = PropertyUtility.getPropertyDescriptionOutcome(new DomainPath(itemDescriptionPath).getSysKey()); - StringBuffer classProps = new StringBuffer(); - for (PropertyDescription pd : propList.list) { - props.put(pd.getName(), pd.getDefaultValue()); - if (pd.getIsClassIdentifier()) - classProps.append((classProps.length()>0?",":"")).append(pd.getName()); - } - newDep.setProperties(props); - newDep.setClassProps(classProps.toString()); - } - - for (DependencyMember thisMem : dependencyMemberList) { - int syskey = new DomainPath(thisMem.itemPath).getSysKey(); - if (syskey == -1) - throw new MembershipException("Cannot find "+thisMem.itemPath+" specified for collection."); - com.c2kernel.collection.DependencyMember newDepMem = newDep.addMember(syskey); - newDepMem.getProperties().putAll(thisMem.props); - } - return newDep; - } - -} diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/DependencyMember.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/DependencyMember.java deleted file mode 100644 index 573cdc8..0000000 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/DependencyMember.java +++ /dev/null @@ -1,29 +0,0 @@ - -package com.c2kernel.lifecycle.instance.predefined.entitycreation; - -import com.c2kernel.utils.CastorHashMap; -import com.c2kernel.utils.KeyValuePair; - -public class DependencyMember implements java.io.Serializable { - - - public String itemPath; - public CastorHashMap props = new CastorHashMap(); - - public DependencyMember() { - super(); - } - - public DependencyMember(String itemPath) { - this.itemPath = itemPath; - - } - - public KeyValuePair[] getKeyValuePairs() { - return props.getKeyValuePairs(); - } - - public void setKeyValuePairs(KeyValuePair[] pairs) { - props.setKeyValuePairs(pairs); - } -} diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/Geometry.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/Geometry.java deleted file mode 100644 index f18b6d4..0000000 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/Geometry.java +++ /dev/null @@ -1,29 +0,0 @@ - - -package com.c2kernel.lifecycle.instance.predefined.entitycreation; - - - -public class Geometry implements java.io.Serializable { - - - public int x; - - public int y; - - public int width; - - public int height; - - public Geometry() { - super(); - } - - public Geometry(int x, int y, int width, int height) { - this.x = x; - this.y = y; - this.width = width; - this.height = height; - } - -} diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewAgent.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewAgent.java deleted file mode 100644 index 10e5e6f..0000000 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewAgent.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.c2kernel.lifecycle.instance.predefined.entitycreation; - -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; - -import com.c2kernel.common.CannotManageException; -import com.c2kernel.common.ObjectAlreadyExistsException; -import com.c2kernel.common.ObjectCannotBeUpdated; -import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.entity.agent.ActiveEntity; -import com.c2kernel.lookup.AgentPath; -import com.c2kernel.lookup.RolePath; -import com.c2kernel.process.Gateway; -import com.c2kernel.process.module.ModuleImport; -import com.c2kernel.property.Property; -import com.c2kernel.property.PropertyArrayList; -import com.c2kernel.utils.Logger; - -public class NewAgent extends ModuleImport implements java.io.Serializable { - - public String password; - - public ArrayList roles = new ArrayList(); - public ArrayList properties = new ArrayList(); - - public NewAgent() { - } - - public NewAgent(String name, String password) { - this.name = name; - this.password = password; - } - - public void create(int agentId) throws ObjectNotFoundException, ObjectCannotBeUpdated, NoSuchAlgorithmException, CannotManageException, ObjectAlreadyExistsException { - AgentPath newAgent = Gateway.getNextKeyManager().generateNextAgentKey(); - newAgent.setAgentName(name); - newAgent.setPassword(password); - ActiveEntity newAgentEnt = (ActiveEntity)Gateway.getCorbaServer().createEntity(newAgent); - Gateway.getLookup().add(newAgent); - // assemble properties - properties.add(new com.c2kernel.property.Property("Name", name, true)); - properties.add(new com.c2kernel.property.Property("Type", "Agent", false)); - try { - newAgentEnt.initialise(agentId, Gateway.getMarshaller().marshall(new PropertyArrayList(properties)), null, null); - } catch (Exception ex) { - Logger.error(ex); - throw new CannotManageException("Error initialising new agent"); - } - for (String role : roles) { - RolePath thisRole; - try { - thisRole = Gateway.getLookup().getRolePath(role); - } catch (ObjectNotFoundException ex) { - throw new ObjectNotFoundException("Role "+role+" does not exist."); - } - thisRole.addAgent(newAgent); - } - - } -} diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java deleted file mode 100644 index b1ef0e4..0000000 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java +++ /dev/null @@ -1,187 +0,0 @@ -package com.c2kernel.lifecycle.instance.predefined.entitycreation; - - -import java.util.ArrayList; - -import org.custommonkey.xmlunit.Diff; -import org.custommonkey.xmlunit.XMLUnit; - -import com.c2kernel.collection.CollectionArrayList; -import com.c2kernel.collection.MembershipException; -import com.c2kernel.common.CannotManageException; -import com.c2kernel.common.InvalidDataException; -import com.c2kernel.common.ObjectAlreadyExistsException; -import com.c2kernel.common.ObjectCannotBeUpdated; -import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.entity.TraceableEntity; -import com.c2kernel.events.Event; -import com.c2kernel.events.History; -import com.c2kernel.lifecycle.CompositeActivityDef; -import com.c2kernel.lifecycle.instance.stateMachine.Transition; -import com.c2kernel.lookup.DomainPath; -import com.c2kernel.lookup.ItemPath; -import com.c2kernel.persistency.ClusterStorage; -import com.c2kernel.persistency.ClusterStorageException; -import com.c2kernel.persistency.outcome.Viewpoint; -import com.c2kernel.process.Gateway; -import com.c2kernel.process.module.ModuleImport; -import com.c2kernel.property.Property; -import com.c2kernel.property.PropertyArrayList; -import com.c2kernel.utils.LocalObjectLoader; -import com.c2kernel.utils.Logger; - -/** - * Complete Structure for new item - * - * @version $Revision: 1.8 $ $Date: 2006/03/03 13:52:21 $ - */ - -public class NewItem extends ModuleImport { - - public String initialPath; - public String workflow; - public Integer workflowVer; - public ArrayList properties = new ArrayList(); - public ArrayList aggregationList = new ArrayList(); - public ArrayList dependencyList = new ArrayList(); - public ArrayList outcomes = new ArrayList(); - private String ns; - - public NewItem() { - } - - public NewItem(String name, String initialPath, String wf, int wfVer) { - this(); - this.name = name; - this.initialPath = initialPath; - this.workflow = wf; - this.workflowVer = wfVer; - } - - public void setNamespace(String ns) { - this.ns = ns; - if (initialPath == null) initialPath = "/desc/"+ns; - } - - public String getNamespace() { - return ns; - } - - public void create(int agentId, boolean reset) throws ObjectCannotBeUpdated, ObjectNotFoundException, CannotManageException, ObjectAlreadyExistsException { - DomainPath domPath = new DomainPath(new DomainPath(initialPath), name); - - ItemPath entPath; TraceableEntity newItem; - if (domPath.exists()) { - entPath = domPath.getEntity(); - newItem = Gateway.getCorbaServer().getItem(entPath.getSysKey()); - } - else { - // create item - entPath = Gateway.getNextKeyManager().generateNextEntityKey(); - newItem = (TraceableEntity)Gateway.getCorbaServer().createEntity(entPath); - Gateway.getLookup().add(entPath); - } - - // set the name property - properties.add(new Property("Name", name, true)); - - // find workflow def - CompositeActivityDef compact; - // default workflow version is 0 if not given - int usedWfVer; - if (workflowVer == null) usedWfVer = 0; - else usedWfVer = workflowVer.intValue(); - try { - compact = (CompositeActivityDef)LocalObjectLoader.getActDef(workflow, usedWfVer); - } catch (ObjectNotFoundException ex) { - throw new CannotManageException("Could not find workflow "+workflow+"v"+usedWfVer+" for item "+domPath, ""); - } catch (InvalidDataException e) { - throw new CannotManageException("Workflow def "+workflow+" v"+usedWfVer+" for item "+domPath+" was not valid", ""); - } - - // create collections - CollectionArrayList colls = new CollectionArrayList(); - for (Dependency element: dependencyList) { - try { - com.c2kernel.collection.Dependency newDep = element.create(); - colls.put(newDep); - } catch (MembershipException ex) { - Logger.error(ex); - throw new CannotManageException("A specified member is not of the correct type in "+element.name, ""); - } - } - - for (Aggregation element : aggregationList) { - try { - com.c2kernel.collection.Aggregation newAgg = element.create(); - colls.put(newAgg); - } catch (MembershipException ex) { - Logger.error(ex); - throw new CannotManageException("A specified member is not of the correct type in "+element.name, ""); - } - } - - // (re)initialise the new item with properties, workflow and collections - try { - newItem.initialise( - agentId, - Gateway.getMarshaller().marshall(new PropertyArrayList(properties)), - Gateway.getMarshaller().marshall(compact.instantiate()), - Gateway.getMarshaller().marshall(colls)); - } catch (Exception ex) { - Logger.error("Error initialising new item "+name ); - Logger.error(ex); - throw new CannotManageException("Problem initialising new item. See server log.", ""); - } - - // import outcomes - XMLUnit.setIgnoreWhitespace(true); - XMLUnit.setIgnoreComments(true); - History hist = new History(entPath.getSysKey(), null); - for (Outcome thisOutcome : outcomes) { - com.c2kernel.persistency.outcome.Outcome newOutcome = new com.c2kernel.persistency.outcome.Outcome(-1, thisOutcome.getData(ns), thisOutcome.schema, thisOutcome.version); - Viewpoint impView; - try { - impView = (Viewpoint)Gateway.getStorage().get(entPath.getSysKey(), ClusterStorage.VIEWPOINT+"/"+thisOutcome.schema+"/"+thisOutcome.viewname, null); - - Diff xmlDiff = new Diff(newOutcome.getDOM(), impView.getOutcome().getDOM()); - if (xmlDiff.identical()) { - Logger.msg(5, "NewItem.create() - View "+thisOutcome.schema+"/"+thisOutcome.viewname+" in "+name+" identical, no update required"); - continue; - } - else { - Logger.msg("NewItem.create() - Difference found in view "+thisOutcome.schema+"/"+thisOutcome.viewname+" in "+name+": "+xmlDiff.toString()); - if (!reset && !impView.getEvent().getStepPath().equals("Import")) { - Logger.msg("Last edit was not done by import, and reset not requested. Not overwriting."); - continue; - } - } - } catch (ObjectNotFoundException ex) { - Logger.msg(3, "View "+thisOutcome.schema+"/"+thisOutcome.viewname+" not found in "+name+". Creating."); - impView = new Viewpoint(entPath.getSysKey(), thisOutcome.schema, thisOutcome.viewname, thisOutcome.version, -1); - } catch (ClusterStorageException e) { - throw new ObjectCannotBeUpdated("Could not check data for view "+thisOutcome.schema+"/"+thisOutcome.viewname+" in "+name); - } catch (InvalidDataException e) { - throw new ObjectCannotBeUpdated("Could not check previous event for view "+thisOutcome.schema+"/"+thisOutcome.viewname+" in "+name); - } - - // write new view/outcome/event - Transition predefDone = new Transition(0, "Done", 0, 0); - Event newEvent = hist.addEvent("system", "Admin", "Import", "Import", "Import", thisOutcome.schema, thisOutcome.version, "PredefinedStep", 0, predefDone, thisOutcome.viewname); - newOutcome.setID(newEvent.getID()); - impView.setEventId(newEvent.getID()); - try { - Gateway.getStorage().put(entPath.getSysKey(), newOutcome, null); - Gateway.getStorage().put(entPath.getSysKey(), impView, null); - } catch (ClusterStorageException e) { - throw new ObjectCannotBeUpdated("Could not store data for view "+thisOutcome.schema+"/"+thisOutcome.viewname+" in "+name); - } - } - - // register domain path (before collections in case of recursive collections) - if (!domPath.exists()) { - domPath.setEntity(entPath); - Gateway.getLookup().add(domPath); - } - } -} diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewRole.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewRole.java deleted file mode 100644 index 74415a5..0000000 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewRole.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.c2kernel.lifecycle.instance.predefined.entitycreation; - -import com.c2kernel.common.ObjectAlreadyExistsException; -import com.c2kernel.common.ObjectCannotBeUpdated; -import com.c2kernel.process.Gateway; -import com.c2kernel.process.module.ModuleImport; - -public class NewRole extends ModuleImport { - - public boolean jobList; - - public NewRole() { - } - - public void create(int agentId) throws ObjectAlreadyExistsException, ObjectCannotBeUpdated { - Gateway.getLookup().createRole(name, jobList); - } - -} diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/Outcome.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/Outcome.java deleted file mode 100644 index 1a966b5..0000000 --- a/src/main/java/com/c2kernel/lifecycle/instance/predefined/entitycreation/Outcome.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.c2kernel.lifecycle.instance.predefined.entitycreation; - -import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.process.Gateway; - -public class Outcome { - public String schema, viewname, path, data; - public int version; - - public Outcome() { - } - - public Outcome(String schema, int version, String viewname, String path) { - super(); - this.schema = schema; - this.version = version; - this.viewname = viewname; - this.path = path; - } - - public String getData(String ns) throws ObjectNotFoundException { - if (data == null) - data = Gateway.getResource().getTextResource(ns, path); - return data; - } - -} diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/CreateNewAgent.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/CreateNewAgent.java new file mode 100644 index 0000000..f2396da --- /dev/null +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/CreateNewAgent.java @@ -0,0 +1,43 @@ +/************************************************************************** + * CreateNewAgent.java + * + * Copyright (C) 2001 CERN - European Organization for Nuclear Research + * All rights reserved. + **************************************************************************/ + +package com.c2kernel.lifecycle.instance.predefined.server; + +import com.c2kernel.common.InvalidDataException; +import com.c2kernel.entity.imports.ImportAgent; +import com.c2kernel.lifecycle.instance.predefined.PredefinedStep; +import com.c2kernel.lookup.AgentPath; +import com.c2kernel.process.Gateway; +import com.c2kernel.utils.Logger; + +public class CreateNewAgent extends PredefinedStep +{ + public CreateNewAgent() + { + super(); + getProperties().put("SchemaType", "Agent"); + } + + //requestdata is xmlstring + @Override + protected String runActivityLogic(AgentPath agent, int itemSysKey, + int transitionID, String requestData) throws InvalidDataException { + + String redactedRequestData; + try { + ImportAgent newAgent = (ImportAgent)Gateway.getMarshaller().unmarshall(requestData); + newAgent.create(agent.getSysKey()); + newAgent.password = "REDACTED"; + redactedRequestData = Gateway.getMarshaller().marshall(newAgent); + return redactedRequestData; + } catch (Exception ex) { + Logger.error(ex); + throw new InvalidDataException("Error creating agent", ""); + } + + } +} diff --git a/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/CreateNewItem.java b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/CreateNewItem.java new file mode 100644 index 0000000..19fd80a --- /dev/null +++ b/src/main/java/com/c2kernel/lifecycle/instance/predefined/server/CreateNewItem.java @@ -0,0 +1,42 @@ +/************************************************************************** + * CreateNewItem + * + * Copyright (C) 2005 CERN - European Organization for Nuclear Research + * All rights reserved. + **************************************************************************/ + +package com.c2kernel.lifecycle.instance.predefined.server; + + + + +import com.c2kernel.common.InvalidDataException; +import com.c2kernel.entity.imports.ImportItem; +import com.c2kernel.lifecycle.instance.predefined.PredefinedStep; +import com.c2kernel.lookup.AgentPath; +import com.c2kernel.process.Gateway; +import com.c2kernel.utils.Logger; + +public class CreateNewItem extends PredefinedStep +{ + public CreateNewItem() + { + super(); + getProperties().put("SchemaType", "Item"); + } + + //requestdata is xmlstring + @Override + protected String runActivityLogic(AgentPath agent, int itemSysKey, + int transitionID, String requestData) throws InvalidDataException { + + try { + ImportItem item = (ImportItem)Gateway.getMarshaller().unmarshall(requestData); + item.create(agent.getSysKey(), false); + return requestData; + } catch (Exception ex) { + Logger.error(ex); + throw new InvalidDataException("Error creating item", ""); + } + } +} diff --git a/src/main/java/com/c2kernel/process/module/Module.java b/src/main/java/com/c2kernel/process/module/Module.java index dae5711..873754f 100644 --- a/src/main/java/com/c2kernel/process/module/Module.java +++ b/src/main/java/com/c2kernel/process/module/Module.java @@ -4,14 +4,14 @@ import java.util.ArrayList; import java.util.Properties; import com.c2kernel.common.ObjectNotFoundException; +import com.c2kernel.entity.imports.ImportDependency; +import com.c2kernel.entity.imports.ImportDependencyMember; +import com.c2kernel.entity.imports.ImportAgent; +import com.c2kernel.entity.imports.ImportItem; +import com.c2kernel.entity.imports.ImportRole; +import com.c2kernel.entity.imports.ImportOutcome; import com.c2kernel.entity.proxy.AgentProxy; import com.c2kernel.entity.proxy.ItemProxy; -import com.c2kernel.lifecycle.instance.predefined.entitycreation.Dependency; -import com.c2kernel.lifecycle.instance.predefined.entitycreation.DependencyMember; -import com.c2kernel.lifecycle.instance.predefined.entitycreation.NewAgent; -import com.c2kernel.lifecycle.instance.predefined.entitycreation.NewItem; -import com.c2kernel.lifecycle.instance.predefined.entitycreation.NewRole; -import com.c2kernel.lifecycle.instance.predefined.entitycreation.Outcome; import com.c2kernel.lookup.DomainPath; import com.c2kernel.lookup.RolePath; import com.c2kernel.process.Bootstrap; @@ -28,7 +28,7 @@ public class Module { public ModuleImports imports = new ModuleImports(); public ArrayList config = new ArrayList(); public ArrayList scripts = new ArrayList(); - public NewItem moduleItem; + public ImportItem moduleItem; public Module() { super(); @@ -52,7 +52,7 @@ public class Module { } public void addModuleItem(String moduleXML) { - NewItem moduleItem = new NewItem(name, "/desc/modules/", "NoWorkflow", 0); + ImportItem moduleItem = new ImportItem(name, "/desc/modules/", "NoWorkflow", 0); // Module properties moduleItem.properties.add(new com.c2kernel.property.Property("Namespace", ns, false)); moduleItem.properties.add(new com.c2kernel.property.Property("Name", name, false)); @@ -60,15 +60,15 @@ public class Module { moduleItem.properties.add(new com.c2kernel.property.Property("Layer", String.valueOf(info.layer), true)); moduleItem.properties.add(new com.c2kernel.property.Property("Version", info.version, true)); // Add dependency for all children - Dependency children = new Dependency("Contents"); + ImportDependency children = new ImportDependency("Contents"); for (ModuleImport thisImport : imports.list) { DomainPath path = thisImport.path; if (path != null) - children.dependencyMemberList.add(new DependencyMember(path.toString())); + children.dependencyMemberList.add(new ImportDependencyMember(path.toString())); } moduleItem.dependencyList.add(children); // Add moduleXML - Outcome moduleOutcome = new Outcome("Module", 0, "last", null); + ImportOutcome moduleOutcome = new ImportOutcome("Module", 0, "last", null); moduleOutcome.data = moduleXML; moduleItem.outcomes.add(moduleOutcome); imports.list.add(moduleItem); @@ -87,7 +87,7 @@ public class Module { } } - for (NewRole thisRole : imports.getRoles()) { + for (ImportRole thisRole : imports.getRoles()) { RolePath rolePath; try { rolePath = Gateway.getLookup().getRolePath(thisRole.name); @@ -101,7 +101,7 @@ public class Module { } } - for (NewAgent thisAgent : imports.getAgents()) { + for (ImportAgent thisAgent : imports.getAgents()) { try { Gateway.getLookup().getAgentPath(thisAgent.name); Logger.msg(3, "Module.importAll() - User '"+thisAgent.name+"' found."); @@ -111,7 +111,7 @@ public class Module { thisAgent.create(systemAgentId); } - for (NewItem thisItem : imports.getItems()) { + for (ImportItem thisItem : imports.getItems()) { thisItem.setNamespace(ns); thisItem.create(systemAgentId, reset); } diff --git a/src/main/java/com/c2kernel/process/module/ModuleImports.java b/src/main/java/com/c2kernel/process/module/ModuleImports.java index 5dfde42..e0ddd90 100644 --- a/src/main/java/com/c2kernel/process/module/ModuleImports.java +++ b/src/main/java/com/c2kernel/process/module/ModuleImports.java @@ -2,9 +2,9 @@ package com.c2kernel.process.module; import java.util.ArrayList; -import com.c2kernel.lifecycle.instance.predefined.entitycreation.NewAgent; -import com.c2kernel.lifecycle.instance.predefined.entitycreation.NewItem; -import com.c2kernel.lifecycle.instance.predefined.entitycreation.NewRole; +import com.c2kernel.entity.imports.ImportAgent; +import com.c2kernel.entity.imports.ImportItem; +import com.c2kernel.entity.imports.ImportRole; import com.c2kernel.utils.CastorArrayList; public class ModuleImports extends CastorArrayList { @@ -28,29 +28,29 @@ public class ModuleImports extends CastorArrayList { return subset; } - public ArrayList getItems() { - ArrayList subset = new ArrayList(); + public ArrayList getItems() { + ArrayList subset = new ArrayList(); for (ModuleImport imp : list) { - if (imp instanceof NewItem) - subset.add((NewItem)imp); + if (imp instanceof ImportItem) + subset.add((ImportItem)imp); } return subset; } - public ArrayList getAgents() { - ArrayList subset = new ArrayList(); + public ArrayList getAgents() { + ArrayList subset = new ArrayList(); for (ModuleImport imp : list) { - if (imp instanceof NewAgent) - subset.add((NewAgent)imp); + if (imp instanceof ImportAgent) + subset.add((ImportAgent)imp); } return subset; } - public ArrayList getRoles() { - ArrayList subset = new ArrayList(); + public ArrayList getRoles() { + ArrayList subset = new ArrayList(); for (ModuleImport imp : list) { - if (imp instanceof NewRole) - subset.add((NewRole)imp); + if (imp instanceof ImportRole) + subset.add((ImportRole)imp); } return subset; } diff --git a/src/main/resources/mapFiles/NewEntityMap.xml b/src/main/resources/mapFiles/NewEntityMap.xml index 84c4ce7..1e58a9e 100644 --- a/src/main/resources/mapFiles/NewEntityMap.xml +++ b/src/main/resources/mapFiles/NewEntityMap.xml @@ -1,6 +1,6 @@ - + @@ -17,28 +17,28 @@ - + - + - + - + - + - + @@ -48,7 +48,7 @@ - + - + @@ -70,7 +70,7 @@ - + @@ -80,7 +80,7 @@ - + - + @@ -97,7 +97,7 @@ - + @@ -111,7 +111,7 @@ - + @@ -126,7 +126,7 @@ - + -- cgit v1.2.3