package nesstar.example; import java.io.*; import java.net.*; import java.util.*; import java.util.logging.*; import nesstar.util.*; import nesstar.rdf.*; import nesstar.api.*; import nesstar.api.cosmos.*; import nesstar.client.Init; /* * CosmosClient.java * Cosmos Common API Examples for the Cosmos Use Cases * @author Pasqualino 'Titto' Assini */ public class CosmosClient { /** * Printout a message * @param msg the message */ public static void dbg(String msg) { System.out.println(msg); } /** * @param root the root of the classification * @return the RDF serialization of the classification */ public static String getClassificationRDF(CodeList root) throws Exception { String rdf = getRDF(root); // Set URL of root object to . rdf = StringUtils.replace(rdf,root.getID().toString(), "."); // Make URLs of other objects relative rdf = StringUtils.replace(rdf, RDFDB.getLocalObjURL(), "#"); return rdf; } /** * @param root the root of the object graph * @return the RDF serialization of the object graph */ public static String getRDF(RDFObject root) throws Exception { HashSet objsToSave = new HashSet(); addToObjsToSave(root,objsToSave); return root.getDB().nToRDF(objsToSave.iterator()); } /** * Add an object and its parts to the set of object to save */ static void addToObjsToSave(Object obj, Set objsToSave) throws Exception { if (obj==null) return; // Traverse object graph // For each type of Cosmos object: // - add the object to the list of objects to save in the RDF file // - plus all the objects that are parts of the object if (obj instanceof CodeList) { objsToSave.add(obj); addToSave(((CodeList)obj).getDomains(),objsToSave); } else if (obj instanceof ValueDomain) { objsToSave.add(obj); addToSave(((ValueDomain)obj).getValues(),objsToSave); } else if (obj instanceof Value) { objsToSave.add(obj); addToSave(((Value)obj).getChildren(),objsToSave); } else if (obj instanceof IPISDataset) { objsToSave.add(obj); addToSave(((IPISDataset)obj).getVariables(),objsToSave); addToSave(((IPISDataset)obj).getRows(),objsToSave); } else if (obj instanceof Variable) { objsToSave.add(obj); addToObjsToSave(((Variable)obj).getValueDomain(),objsToSave); } } /** * Add a list of objects to the list of objects to be saved in the RDF file * @param parts the list of objects to save * @param objsToSave the total set of objects to save */ static void addToSave(List parts,Set objsToSave) throws Exception { if (parts==null) return; objsToSave.add(((RDFList)parts).getBag()); Iterator p = parts.iterator(); while (p.hasNext()) addToObjsToSave(p.next(),objsToSave); } /* Example of encoding the classification (for simplicity only CodeList and ValueDomains are created): CodeList: Name: CLACARS 2002 Title: Classification of cars and other light vehicles 2002 Value Domain: Name: Car main type LevelNumber: 1 Value Domain: Name: Car sub type LevelNumber: 2 (Value of Value Domain with level number 1) Code: 010 Name: Sport cars (Value of Value Domain with level number 2) Code: 0101 Name: Road racer Relation: Sports cars is parent of Road racer */ static void metawarePublishingExample() throws Exception { dbg("Metaware Classification Publishing Example"); // Initialise RDF Protocol Init.testInit(); // Get the default DB NetDB db = Protocol.getDB(); // Create objects CodeList cl = CodeList.newInstance(db); cl.setLabel("CLACARS 2002"); cl.setComment("Classification of cars and other light vehicles 2002"); cl.setCodingType("A fake classification"); ValueDomain domain1 = ValueDomain.newInstance(db); domain1.setLabel("Car main type"); domain1.setLevelNumber(new Integer(1)); ValueDomain domain2 = ValueDomain.newInstance(db); domain2.setLabel("Car sub type"); domain2.setLevelNumber(new Integer(2)); // Set the relationship between the code list and its value domains Vector domains = new Vector(); domains.add(domain1); domains.add(domain2); cl.setDomains(domains); // Convert the object graph to RDF String rdf = getClassificationRDF(cl); // Store the objects coded in RDF/XML as a file on some web server // (in this example we use a web directory on a Nesstar server) String webServerDir = "y:/sdk"; FileUtils.writeAll(new File(webServerDir+"/classification.xml"),rdf); } static void classificationBrowsingExample() throws Exception { dbg("Classification Browsing Example"); // We can now use the API to access the objects published by metaware: // at the URL (substitute your Web directory URL): String webServerURL = "http://www.nesstar.org/sdk"; String codeListURL = webServerURL + "/classification.xml"; // The same information can also be accessed using : // - any Web Browser // - the Java API // - the Nesstar Object Browser with a call such as: // http://..webServerURL../browser?FRAMES=false&action=LIST&url=http://nesport4.essex.ac.uk:8080/classification.xml // Initialise the protocol Init.testInit(); NetDB db = Protocol.getDB(); // Retrieve the root CodeList object from the Net CodeList cl = (CodeList)db.retrieve(codeListURL); dbg("cl.ID="+cl.getID()); dbg("cl.label="+cl.getLabel()); dbg("cl.comment="+cl.getComment()); // Traverse the object graph to retrieve the other objects // Get the value domains Iterator domains = cl.getDomains().iterator(); while (domains.hasNext()) { ValueDomain domain = (ValueDomain)domains.next(); dbg("domain.ID="+domain.getID()); dbg("domain.label="+domain.getLabel()); dbg("domains.levelNumber="+domain.getLevelNumber()); } } /** * @param serverURL the server URL, e.g. "http://nesport4.essex.ac.uk:8080" * @param classID the id/name of the cosmos class, e.g. "IPISDataset" * @param objID the ID of the object, e.g. "v1" * @return the URL of the server object */ static URL getObjURL(String serverURL,String classID,String objID) throws MalformedURLException { return new URL(serverURL+"/obj/"+classID+"/"+objID); } /** The URL of the Cosmos Server */ static String SERVER_URL = "http://nesport4.essex.ac.uk:8080"; /** The name of the Cosmos Server */ static String SERVER_NAME = "COSMOS"; /** The password of the server administrator of the Cosmos Server */ static String ADMIN_PWD = "cosmospwd"; /** * @param datasetID the ID of the dataset, e.g. "dataset1" * @return the URL of a Dataset published in the Cosmos server */ static URL getDatasetURL(String datasetID) throws MalformedURLException { return getObjURL(SERVER_URL,"xIPISDataset",datasetID); } /** * @param variableID the ID of the variable, e.g. "v1" * @return the URL of a variable published in the Cosmos server */ static URL getVariableURL(String variableID) throws MalformedURLException { return getObjURL(SERVER_URL,"xVariable",variableID); } /** * @param domainID the ID of the domain, e.g. "domain1" * @return the URL of a value domain published in the Cosmos server */ static URL getValueDomainURL(String domainID) throws MalformedURLException { return getObjURL(SERVER_URL,"xValueDomain",domainID); } /** * @param serverID the name of the server, e.g. "Cosmos" * @return the URL of the root server object */ static URL getServerURL(String serverID) throws MalformedURLException { return getObjURL(SERVER_URL,"cServer",serverID); } static void ipisPublishingExample() throws Exception { dbg("IPIS Publishing Example"); // Initialise RDF Protocol Init.testInit(); // Get the default DB NetDB db = Protocol.getDB(); // Create the IPIS objects: a dataset with 2 variables IPISDataset dataset1 = IPISDataset.getInstance(db,getDatasetURL("dataset1")); dataset1.setLabel("IPISDataset 1"); dataset1.setComment("The first IPIS Dataset"); Variable v1 = Variable.getInstance(db,getVariableURL("V1")); v1.setLabel("V1"); ValueDomain domain1 = ValueDomain.getInstance(db,getValueDomainURL("Domain1")); domain1.setLabel("Domain1"); domain1.setComment("An Interesting Type"); domain1.setLevelNumber(new Integer(1)); v1.setValueDomain(domain1); Variable v2 = Variable.getInstance(db,getVariableURL("V2")); v2.setLabel("V2"); List variables = new Vector(); variables.add(v1); variables.add(v2); dataset1.setVariables(variables); // Store the objects in an RDF-coded file String rdf = getRDF(dataset1); File ipisObjects = new File("c:/temp/ipis.xml"); FileUtils.writeAll(ipisObjects,rdf); // Get the Server object nesstar.api.common.Server server = (nesstar.api.common.Server)db.retrieve(getServerURL(SERVER_NAME)); // Login with the server as admin server.Login("admin",ADMIN_PWD,null); // Upload the objects (dataset, variables, etc.) into the server server.Import(ipisObjects,null); } static void ipisProcessingExample() throws Exception { dbg("IPIS Processing Example"); // Initialise the API Init.testInit(); NetDB db = Protocol.getDB(); // Find the URL of the IPISDataset (using the registry or by other means) URL datasetURL = getDatasetURL("dataset1"); // Retrieve the IPISDataset object IPISDataset dataset = (IPISDataset)db.retrieve(datasetURL); // Display the variables to the user // and allow the user to select the statistical operation to apply // and the operation parameters List variables = dataset.getVariables(); dbg("variables:"+variables); // Let's check that we got back what we published Iterator v = variables.iterator(); Variable v1 = (Variable)v.next(); dbg("v1="+v1); Variable v2 = (Variable)v.next(); dbg("v2="+v2); ValueDomain domain1 = v1.getValueDomain(); dbg("domain1="+domain1); dbg("domain1.label="+domain1.getLabel()); dbg("domain1.comment="+domain1.getComment()); dbg("domain1.level="+domain1.getLevelNumber()); // Apply a project operation // The result is a new dataset List selectedVariables = new Vector(); selectedVariables.add(variables.get(0)); IPISDataset projectResult = dataset.Project(selectedVariables,null); dbg("project() returned dataset="+projectResult); dbg("result.label="+projectResult.getLabel()); dbg("result.comment="+projectResult.getComment()); // Apply a select operation // The result is a new dataset String query = "Gender='male'"; IPISDataset selectResult = dataset.Select(query,null); dbg("select("+query+") returned dataset="+selectResult); dbg("result.label="+selectResult.getLabel()); dbg("result.comment="+selectResult.getComment()); } static void logSet(String prop,String value) { System.setProperty("org.apache.commons.logging."+prop,"org.apache.commons.logging."+value); } private static Logger logger = Logger.getLogger("com.wombat.nose"); private static FileHandler fh; static void setupLogging() throws IOException { //String logCls="Jdk14Logger"; String logCls="SimpleLog"; logSet("Log","impl."+logCls); logSet(logCls+".defaultlog", "debug"); //System.setProperty("org.apache.commons.logging.Log","org.apache.commons.logging.impl.SimpleLog"); System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "debug"); System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true"); System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "debug"); System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug"); //fh = new FileHandler("%t/CosmosClientLog.txt"); fh = new FileHandler("c:/temp/CosmosClientLog.txt"); fh.setFormatter(new SimpleFormatter()); // Send logger output to our FileHandler. logger.addHandler(fh); // Request that every detail gets logged. logger.setLevel(Level.ALL); // Log a simple INFO message. logger.info("doing stuff"); } static void simpleCheck() throws Exception { dbg("Simple check of protocol funtionality"); // Initialise the API Init.testInit(); //Protocol.setProxies("",0,"",0); Protocol.setProxies(null,0,null,0); NetDB db = Protocol.getDB(); //String serverURL = "http://nesstar2.essex.ac.uk/obj/cServer/Automatic" //String serverURL = "http://nesstar.nsd.uib.no:8080/obj/cServer/NSDDEV"; //String serverURL = "http://xytyytyutu.org/obj/cServer/NSDDEV"; String serverURL = "http://nesstar.nsd.uib.no:7000/obj/cServer/NSDDEV"; nesstar.api.Server server = nesstar.api.common.Server.retrieve(new URL(serverURL)); //nesstar.api.common.Server server = (nesstar.api.common.Server)db.reload("http://nesstar2.essex.ac.uk/obj/cServer/Automatic"); } /** * @param args the command line arguments */ public static void main(String[] args) throws Exception { simpleCheck(); //metawarePublishingExample(); //classificationBrowsingExample(); //ipisPublishingExample(); //ipisProcessingExample(); } }